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

#include <limits.h>

#ifndef GCC
#pragma hdrstop
#endif

#include "itempool.hxx"
#include "itemset.hxx"
#include "poolcach.hxx"

// STATIC DATA -----------------------------------------------------------

DBG_NAME(SfxItemPoolCache)

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

struct SfxItemModifyImpl
{
    const SfxSetItem  *pOrigItem;
    SfxSetItem        *pPoolItem;
};

SV_DECL_VARARR( SfxItemModifyArr_Impl, SfxItemModifyImpl, 8, 8 )
SV_IMPL_VARARR( SfxItemModifyArr_Impl, SfxItemModifyImpl);

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

SfxItemPoolCache::SfxItemPoolCache( SfxItemPool *pItemPool,
                                    const SfxPoolItem *pPutItem ):
    pPool(pItemPool),
    pCache(new SfxItemModifyArr_Impl),
    pSetToPut( 0 ),
    pItemToPut( &pItemPool->Put(*pPutItem) )
{
    DBG_CTOR(SfxItemPoolCache, 0);
    DBG_ASSERT(pItemPool, "kein Pool angegeben");
}

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

SfxItemPoolCache::SfxItemPoolCache( SfxItemPool *pItemPool,
                                    const SfxItemSet *pPutSet ):
    pPool(pItemPool),
    pCache(new SfxItemModifyArr_Impl),
    pSetToPut( pPutSet ),
    pItemToPut( 0 )
{
    DBG_CTOR(SfxItemPoolCache, 0);
    DBG_ASSERT(pItemPool, "kein Pool angegeben");
}

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

SfxItemPoolCache::~SfxItemPoolCache()
{
    DBG_DTOR(SfxItemPoolCache, 0);
    for ( USHORT nPos = 0; nPos < pCache->Count(); ++nPos ) {
        pPool->Remove( *(*pCache)[nPos].pPoolItem );
        pPool->Remove( *(*pCache)[nPos].pOrigItem );
    }
    delete pCache; pCache = 0;

    if ( pItemToPut )
        pPool->Remove( *pItemToPut );
}

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

const SfxSetItem& SfxItemPoolCache::ApplyTo( const SfxSetItem &rOrigItem, BOOL bNew )
{
    DBG_CHKTHIS(SfxItemPoolCache, 0);
    DBG_ASSERT( pPool == rOrigItem.GetItemSet().GetPool(), "invalid Pool" );
    DBG_ASSERT( IsDefaultItem( &rOrigItem ) || IsPooledItem( &rOrigItem ),
                "original not in pool" );

    // Suchen, ob diese Transformations schon einmal vorkam
    for ( USHORT nPos = 0; nPos < pCache->Count(); ++nPos )
    {
        SfxItemModifyImpl &rMapEntry = (*pCache)[nPos];
        if ( rMapEntry.pOrigItem == &rOrigItem )
        {
            // aendert sich ueberhaupt etwas?
            if ( rMapEntry.pPoolItem != &rOrigItem )
            {
                rMapEntry.pPoolItem->AddRef(2); // einen davon fuer den Cache
                if ( bNew )
                    pPool->Put( rOrigItem );    //! AddRef??
            }
            return *rMapEntry.pPoolItem;
        }
    }

    // die neue Attributierung in einem neuen Set eintragen
    SfxSetItem *pNewItem = (SfxSetItem *)rOrigItem.Clone();
    if ( pItemToPut )
    {
        pNewItem->GetItemSet().PutDirect( *pItemToPut );
        DBG_ASSERT( &pNewItem->GetItemSet().Get( pItemToPut->Which() ) == pItemToPut,
                    "wrong item in temporary set" );
    }
    else
        pNewItem->GetItemSet().Put( *pSetToPut );
    const SfxSetItem* pNewPoolItem = (const SfxSetItem*) &pPool->Put( *pNewItem );
    DBG_ASSERT( pNewPoolItem != pNewItem, "Pool: rein == raus?" );
    delete pNewItem;

    // Refernzzaehler anpassen, je einen davon fuer den Cache
    pNewPoolItem->AddRef( pNewPoolItem != &rOrigItem ? 2 : 1 );
    if ( bNew )
        pPool->Put( rOrigItem );    //! AddRef??

    // die Transformation im Cache eintragen
    SfxItemModifyImpl aModify;
    aModify.pOrigItem = &rOrigItem;
    aModify.pPoolItem = (SfxSetItem*) pNewPoolItem;
    pCache->Insert( aModify, pCache->Count() );

    DBG_ASSERT( !pItemToPut ||
                &pNewPoolItem->GetItemSet().Get( pItemToPut->Which() ) == pItemToPut,
                "wrong item in resulting set" );

    return *pNewPoolItem;
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.4.92); FILE MERGED 2006/09/01 17:43:13 kaib 1.4.92.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: poolcach.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 15:00:17 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#include <limits.h>

#ifndef GCC
#endif

#include "itempool.hxx"
#include "itemset.hxx"
#include "poolcach.hxx"

// STATIC DATA -----------------------------------------------------------

DBG_NAME(SfxItemPoolCache)

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

struct SfxItemModifyImpl
{
    const SfxSetItem  *pOrigItem;
    SfxSetItem        *pPoolItem;
};

SV_DECL_VARARR( SfxItemModifyArr_Impl, SfxItemModifyImpl, 8, 8 )
SV_IMPL_VARARR( SfxItemModifyArr_Impl, SfxItemModifyImpl);

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

SfxItemPoolCache::SfxItemPoolCache( SfxItemPool *pItemPool,
                                    const SfxPoolItem *pPutItem ):
    pPool(pItemPool),
    pCache(new SfxItemModifyArr_Impl),
    pSetToPut( 0 ),
    pItemToPut( &pItemPool->Put(*pPutItem) )
{
    DBG_CTOR(SfxItemPoolCache, 0);
    DBG_ASSERT(pItemPool, "kein Pool angegeben");
}

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

SfxItemPoolCache::SfxItemPoolCache( SfxItemPool *pItemPool,
                                    const SfxItemSet *pPutSet ):
    pPool(pItemPool),
    pCache(new SfxItemModifyArr_Impl),
    pSetToPut( pPutSet ),
    pItemToPut( 0 )
{
    DBG_CTOR(SfxItemPoolCache, 0);
    DBG_ASSERT(pItemPool, "kein Pool angegeben");
}

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

SfxItemPoolCache::~SfxItemPoolCache()
{
    DBG_DTOR(SfxItemPoolCache, 0);
    for ( USHORT nPos = 0; nPos < pCache->Count(); ++nPos ) {
        pPool->Remove( *(*pCache)[nPos].pPoolItem );
        pPool->Remove( *(*pCache)[nPos].pOrigItem );
    }
    delete pCache; pCache = 0;

    if ( pItemToPut )
        pPool->Remove( *pItemToPut );
}

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

const SfxSetItem& SfxItemPoolCache::ApplyTo( const SfxSetItem &rOrigItem, BOOL bNew )
{
    DBG_CHKTHIS(SfxItemPoolCache, 0);
    DBG_ASSERT( pPool == rOrigItem.GetItemSet().GetPool(), "invalid Pool" );
    DBG_ASSERT( IsDefaultItem( &rOrigItem ) || IsPooledItem( &rOrigItem ),
                "original not in pool" );

    // Suchen, ob diese Transformations schon einmal vorkam
    for ( USHORT nPos = 0; nPos < pCache->Count(); ++nPos )
    {
        SfxItemModifyImpl &rMapEntry = (*pCache)[nPos];
        if ( rMapEntry.pOrigItem == &rOrigItem )
        {
            // aendert sich ueberhaupt etwas?
            if ( rMapEntry.pPoolItem != &rOrigItem )
            {
                rMapEntry.pPoolItem->AddRef(2); // einen davon fuer den Cache
                if ( bNew )
                    pPool->Put( rOrigItem );    //! AddRef??
            }
            return *rMapEntry.pPoolItem;
        }
    }

    // die neue Attributierung in einem neuen Set eintragen
    SfxSetItem *pNewItem = (SfxSetItem *)rOrigItem.Clone();
    if ( pItemToPut )
    {
        pNewItem->GetItemSet().PutDirect( *pItemToPut );
        DBG_ASSERT( &pNewItem->GetItemSet().Get( pItemToPut->Which() ) == pItemToPut,
                    "wrong item in temporary set" );
    }
    else
        pNewItem->GetItemSet().Put( *pSetToPut );
    const SfxSetItem* pNewPoolItem = (const SfxSetItem*) &pPool->Put( *pNewItem );
    DBG_ASSERT( pNewPoolItem != pNewItem, "Pool: rein == raus?" );
    delete pNewItem;

    // Refernzzaehler anpassen, je einen davon fuer den Cache
    pNewPoolItem->AddRef( pNewPoolItem != &rOrigItem ? 2 : 1 );
    if ( bNew )
        pPool->Put( rOrigItem );    //! AddRef??

    // die Transformation im Cache eintragen
    SfxItemModifyImpl aModify;
    aModify.pOrigItem = &rOrigItem;
    aModify.pPoolItem = (SfxSetItem*) pNewPoolItem;
    pCache->Insert( aModify, pCache->Count() );

    DBG_ASSERT( !pItemToPut ||
                &pNewPoolItem->GetItemSet().Get( pItemToPut->Which() ) == pItemToPut,
                "wrong item in resulting set" );

    return *pNewPoolItem;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: IDocumentSettingAccess.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2006-08-14 15:13:28 $
 *
 *  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 IDOCUMENTSETTINGACCESS_HXX_INCLUDED
#define IDOCUMENTSETTINGACCESS_HXX_INCLUDED

#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef _VOS_REF_HXX
#include <vos/ref.hxx>
#endif
#ifndef _CHCMPRSE_HXX
#include <chcmprse.hxx>
#endif

class SvxForbiddenCharactersTable;
namespace com { namespace sun { namespace star { namespace i18n { struct ForbiddenCharacters; } } } }

 /** Provides access to settings of a document
 */
 class IDocumentSettingAccess
 {
 public:
     enum DocumentSettingId
     {
         // COMPATIBILITY FLAGS START
         PARA_SPACE_MAX,
         PARA_SPACE_MAX_AT_PAGES,

         TAB_COMPAT,

         ADD_FLY_OFFSETS,

         OLD_NUMBERING,

         ADD_EXT_LEADING,
         USE_VIRTUAL_DEVICE,
         USE_HIRES_VIRTUAL_DEVICE,
         OLD_LINE_SPACING,
         ADD_PARA_SPACING_TO_TABLE_CELLS,
         USE_FORMER_OBJECT_POS,
         USE_FORMER_TEXT_WRAPPING,
         CONSIDER_WRAP_ON_OBJECT_POSITION,

         IGNORE_FIRST_LINE_INDENT_IN_NUMBERING,
         DO_NOT_JUSTIFY_LINES_WITH_MANUAL_BREAK,
         DO_NOT_RESET_PARA_ATTRS_FOR_NUM_FONT,
         OUTLINE_LEVEL_YIELDS_OUTLINE_RULE,

         DO_NOT_CAPTURE_DRAW_OBJS_ON_PAGE,
         TABLE_ROW_KEEP,
         IGNORE_TABS_AND_BLANKS_FOR_LINE_CALCULATION,
         CLIP_AS_CHARACTER_ANCHORED_WRITER_FLY_FRAME,
         // COMPATIBILITY FLAGS END

         BROWSE_MODE,
         HTML_MODE,
         GLOBAL_DOCUMENT,
         GLOBAL_DOCUMENT_SAVE_LINKS,
         LABEL_DOCUMENT,
         PURGE_OLE,
         KERN_ASIAN_PUNCTUATION
     };

 public:
    /** Return the specified document setting.

       @param id
       [in] the identifier of the document setting to be returned.
       See above for a list of valid document setting identifiers.

       @returns
       the value of the requested document setting.
    */
    virtual bool get(/*[in]*/ DocumentSettingId id) const = 0;

    /** Set the specified document setting.

        @param id
        [in] the identifier of the document setting to be set.
        See above for a list of valid document setting identifiers.

        @param value
        [in] the new value of the specified document setting.
    */
    virtual void set(/*[in]*/ DocumentSettingId id, /*[in]*/ bool value) = 0;

    /** Return the forbidden characters.

       @param nLang
       [in] the language for which the forbidden character list is returned.

       @param bLocaleData
       [in] if set and there is no user defined forbidden character list for
            language lang, the default list for language lang will be returned.

       @returns
       a list of forbidden characters.
    */
    virtual const com::sun::star::i18n::ForbiddenCharacters*
        getForbiddenCharacters(/*[in]*/ USHORT nLang, /*[in]*/ bool bLocaleData ) const = 0;

    /** Set the forbidden characters.

       @param nLang
       [in] the language for which the forbidden character list should be set.

       @param rForbiddenCharacters
       [in] the new list of forbidden characters for language lang.
    */
    virtual void setForbiddenCharacters(/*[in]*/ USHORT nLang,
                                        /*[in]*/ const com::sun::star::i18n::ForbiddenCharacters& rForbiddenCharacters ) = 0;

    /** Get the forbidden character table and creates one if necessary.

       @returns
       the forbidden characters table.
    */
    virtual vos::ORef<SvxForbiddenCharactersTable>& getForbiddenCharacterTable() = 0;

    /** Get the forbidden character table.

       @returns
       the forbidden characters table.
    */
    virtual const vos::ORef<SvxForbiddenCharactersTable>& getForbiddenCharacterTable() const = 0;

    /** Get the current link update mode.

       @param bGlobalSettings
       [in] if set, the link update mode is obtained from the module,
            if it is set to GLOBALSETTING

       @returns
       the current link update mode.
    */
    virtual sal_uInt16 getLinkUpdateMode( /*[in]*/bool bGlobalSettings ) const = 0;

    /** Set the current link update mode.

       @param nMode
       [in] the new link update mode.
    */
    virtual void setLinkUpdateMode( /*[in]*/ sal_uInt16 nMode ) = 0;

    /** Get the current field update mode.

       @param bGlobalSettings
       [in] if set, the field update mode is obtained from the module,
            if it is set to GLOBALSETTING

       @returns
       the current field update mode.
    */
    virtual sal_uInt16 getFieldUpdateFlags( /*[in]*/bool bGlobalSettings ) const = 0;

    /** Set the current field update mode.

       @param nMode
       [in] the new field update mode.
    */
    virtual void setFieldUpdateFlags( /*[in]*/ sal_uInt16 nMode )  = 0;

    /** Get the character compression type for Asian characters.

       @returns
       the current character compression mode.
    */
    virtual SwCharCompressType getCharacterCompressionType() const = 0;

    /** Set the character compression type for Asian characters.

       @param nMode
       [in] the new character compression type.
    */
    virtual void setCharacterCompressionType( /*[in]*/SwCharCompressType nType ) = 0;

protected:
    virtual ~IDocumentSettingAccess() {};
 };

 #endif // IDOCUMENTSETTINGACCESS_HXX_INCLUDED
<commit_msg>INTEGRATION: CWS extleadfix (1.2.54); FILE MERGED 2006/10/09 13:19:34 fme 1.2.54.1: #i60945# External leading compatibility<commit_after>/*************************************************************************
 *
 *  $RCSfile: IDocumentSettingAccess.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2006-10-27 11:58:22 $
 *
 *  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 IDOCUMENTSETTINGACCESS_HXX_INCLUDED
#define IDOCUMENTSETTINGACCESS_HXX_INCLUDED

#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef _VOS_REF_HXX
#include <vos/ref.hxx>
#endif
#ifndef _CHCMPRSE_HXX
#include <chcmprse.hxx>
#endif

class SvxForbiddenCharactersTable;
namespace com { namespace sun { namespace star { namespace i18n { struct ForbiddenCharacters; } } } }

 /** Provides access to settings of a document
 */
 class IDocumentSettingAccess
 {
 public:
     enum DocumentSettingId
     {
         // COMPATIBILITY FLAGS START
         PARA_SPACE_MAX,
         PARA_SPACE_MAX_AT_PAGES,

         TAB_COMPAT,

         ADD_FLY_OFFSETS,

         OLD_NUMBERING,

         ADD_EXT_LEADING,
         USE_VIRTUAL_DEVICE,
         USE_HIRES_VIRTUAL_DEVICE,
         OLD_LINE_SPACING,
         ADD_PARA_SPACING_TO_TABLE_CELLS,
         USE_FORMER_OBJECT_POS,
         USE_FORMER_TEXT_WRAPPING,
         CONSIDER_WRAP_ON_OBJECT_POSITION,

         IGNORE_FIRST_LINE_INDENT_IN_NUMBERING,
         DO_NOT_JUSTIFY_LINES_WITH_MANUAL_BREAK,
         DO_NOT_RESET_PARA_ATTRS_FOR_NUM_FONT,
         OUTLINE_LEVEL_YIELDS_OUTLINE_RULE,

         DO_NOT_CAPTURE_DRAW_OBJS_ON_PAGE,
         TABLE_ROW_KEEP,
         IGNORE_TABS_AND_BLANKS_FOR_LINE_CALCULATION,
         CLIP_AS_CHARACTER_ANCHORED_WRITER_FLY_FRAME,

         UNIX_FORCE_ZERO_EXT_LEADING,
         // COMPATIBILITY FLAGS END

         BROWSE_MODE,
         HTML_MODE,
         GLOBAL_DOCUMENT,
         GLOBAL_DOCUMENT_SAVE_LINKS,
         LABEL_DOCUMENT,
         PURGE_OLE,
         KERN_ASIAN_PUNCTUATION
     };

 public:
    /** Return the specified document setting.

       @param id
       [in] the identifier of the document setting to be returned.
       See above for a list of valid document setting identifiers.

       @returns
       the value of the requested document setting.
    */
    virtual bool get(/*[in]*/ DocumentSettingId id) const = 0;

    /** Set the specified document setting.

        @param id
        [in] the identifier of the document setting to be set.
        See above for a list of valid document setting identifiers.

        @param value
        [in] the new value of the specified document setting.
    */
    virtual void set(/*[in]*/ DocumentSettingId id, /*[in]*/ bool value) = 0;

    /** Return the forbidden characters.

       @param nLang
       [in] the language for which the forbidden character list is returned.

       @param bLocaleData
       [in] if set and there is no user defined forbidden character list for
            language lang, the default list for language lang will be returned.

       @returns
       a list of forbidden characters.
    */
    virtual const com::sun::star::i18n::ForbiddenCharacters*
        getForbiddenCharacters(/*[in]*/ USHORT nLang, /*[in]*/ bool bLocaleData ) const = 0;

    /** Set the forbidden characters.

       @param nLang
       [in] the language for which the forbidden character list should be set.

       @param rForbiddenCharacters
       [in] the new list of forbidden characters for language lang.
    */
    virtual void setForbiddenCharacters(/*[in]*/ USHORT nLang,
                                        /*[in]*/ const com::sun::star::i18n::ForbiddenCharacters& rForbiddenCharacters ) = 0;

    /** Get the forbidden character table and creates one if necessary.

       @returns
       the forbidden characters table.
    */
    virtual vos::ORef<SvxForbiddenCharactersTable>& getForbiddenCharacterTable() = 0;

    /** Get the forbidden character table.

       @returns
       the forbidden characters table.
    */
    virtual const vos::ORef<SvxForbiddenCharactersTable>& getForbiddenCharacterTable() const = 0;

    /** Get the current link update mode.

       @param bGlobalSettings
       [in] if set, the link update mode is obtained from the module,
            if it is set to GLOBALSETTING

       @returns
       the current link update mode.
    */
    virtual sal_uInt16 getLinkUpdateMode( /*[in]*/bool bGlobalSettings ) const = 0;

    /** Set the current link update mode.

       @param nMode
       [in] the new link update mode.
    */
    virtual void setLinkUpdateMode( /*[in]*/ sal_uInt16 nMode ) = 0;

    /** Get the current field update mode.

       @param bGlobalSettings
       [in] if set, the field update mode is obtained from the module,
            if it is set to GLOBALSETTING

       @returns
       the current field update mode.
    */
    virtual sal_uInt16 getFieldUpdateFlags( /*[in]*/bool bGlobalSettings ) const = 0;

    /** Set the current field update mode.

       @param nMode
       [in] the new field update mode.
    */
    virtual void setFieldUpdateFlags( /*[in]*/ sal_uInt16 nMode )  = 0;

    /** Get the character compression type for Asian characters.

       @returns
       the current character compression mode.
    */
    virtual SwCharCompressType getCharacterCompressionType() const = 0;

    /** Set the character compression type for Asian characters.

       @param nMode
       [in] the new character compression type.
    */
    virtual void setCharacterCompressionType( /*[in]*/SwCharCompressType nType ) = 0;

protected:
    virtual ~IDocumentSettingAccess() {};
 };

 #endif // IDOCUMENTSETTINGACCESS_HXX_INCLUDED
<|endoftext|>


<commit_before>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/sensitivities/CSensProblem.cpp,v $
   $Revision: 1.6 $
   $Name:  $
   $Author: ssahle $
   $Date: 2006/06/23 11:10:25 $
   End CVS Header */

// Copyright  2005 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include <string>

#include "copasi.h"
#include "CSensProblem.h"
//#include "model/CModel.h"
//#include "model/CState.h"
#include "CopasiDataModel/CCopasiDataModel.h"

bool CSensItem::isSingleObject() const
  {
    return mIsSingleObject;
  }

const CCopasiObjectName & CSensItem::getSingleObjectCN() const
  {
    return mSingleObjectCN;
  }

std::string CSensItem::getSingleObjectDisplayName() const
  {
  }

const CObjectLists::ListType & CSensItem::getListType() const
  {
    return mListType;
  }

std::string CSensItem::getListTypeDisplayName() const
  {}

//************************ CSensProblem ***************************

const std::string CSensProblem::SubTaskName[] =
  {
    "Not Set",
    "Steady State",
    "Time Series",
    "Lyapunov Exponents",
  };

const char * CSensProblem::XMLSubTask[] =
  {
    "NotSet",
    "SteadyState",
    "TimeSeries",
    "LyapunovExponents",
  };

/**
 *  Default constructor.
 *  @param "CModel *" pModel
 */
CSensProblem::CSensProblem(const CCopasiContainer * pParent):
    CCopasiProblem(CCopasiTask::steadyState, pParent)
{
  //addParameter("JacobianRequested", CCopasiParameter::BOOL, true);
  //addParameter("StabilityAnalysisRequested", CCopasiParameter::BOOL, true);
  CONSTRUCTOR_TRACE;
}

/**
 *  Copy constructor.
 *  @param "const CSensProblem &" src
 */
CSensProblem::CSensProblem(const CSensProblem & src,
                           const CCopasiContainer * pParent):
    CCopasiProblem(src, pParent)
{CONSTRUCTOR_TRACE;}

/**
 *  Destructor.
 */
CSensProblem::~CSensProblem()
{DESTRUCTOR_TRACE;}

/**
 *   set the problem's SubTaskType:
 */
void
CSensProblem::setSubTaskType(const CSensProblem::SubTaskType & type)
{mSubTaskType = type;}

/**
 *   get the problem's SubTaskType:
 **/
const CSensProblem::SubTaskType &
CSensProblem::getSubTaskType() const {return mSubTaskType;}
<commit_msg>Added missing return values.<commit_after>/* Begin CVS Header
   $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/sensitivities/CSensProblem.cpp,v $
   $Revision: 1.7 $
   $Name:  $
   $Author: shoops $
   $Date: 2006/06/23 12:43:23 $
   End CVS Header */

// Copyright  2005 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc. and EML Research, gGmbH.
// All rights reserved.

#include <string>

#include "copasi.h"
#include "CSensProblem.h"
//#include "model/CModel.h"
//#include "model/CState.h"
#include "CopasiDataModel/CCopasiDataModel.h"

bool CSensItem::isSingleObject() const
  {
    return mIsSingleObject;
  }

const CCopasiObjectName & CSensItem::getSingleObjectCN() const
  {
    return mSingleObjectCN;
  }

std::string CSensItem::getSingleObjectDisplayName() const
  {
    return "";
  }

const CObjectLists::ListType & CSensItem::getListType() const
  {
    return mListType;
  }

std::string CSensItem::getListTypeDisplayName() const
  {
    return "";
  }

//************************ CSensProblem ***************************

const std::string CSensProblem::SubTaskName[] =
  {
    "Not Set",
    "Steady State",
    "Time Series",
    "Lyapunov Exponents",
  };

const char * CSensProblem::XMLSubTask[] =
  {
    "NotSet",
    "SteadyState",
    "TimeSeries",
    "LyapunovExponents",
  };

/**
 *  Default constructor.
 *  @param "CModel *" pModel
 */
CSensProblem::CSensProblem(const CCopasiContainer * pParent):
    CCopasiProblem(CCopasiTask::steadyState, pParent)
{
  //addParameter("JacobianRequested", CCopasiParameter::BOOL, true);
  //addParameter("StabilityAnalysisRequested", CCopasiParameter::BOOL, true);
  CONSTRUCTOR_TRACE;
}

/**
 *  Copy constructor.
 *  @param "const CSensProblem &" src
 */
CSensProblem::CSensProblem(const CSensProblem & src,
                           const CCopasiContainer * pParent):
    CCopasiProblem(src, pParent)
{CONSTRUCTOR_TRACE;}

/**
 *  Destructor.
 */
CSensProblem::~CSensProblem()
{DESTRUCTOR_TRACE;}

/**
 *   set the problem's SubTaskType:
 */
void
CSensProblem::setSubTaskType(const CSensProblem::SubTaskType & type)
{mSubTaskType = type;}

/**
 *   get the problem's SubTaskType:
 **/
const CSensProblem::SubTaskType &
CSensProblem::getSubTaskType() const {return mSubTaskType;}
<|endoftext|>


<commit_before>// Copyright 2018 Google Inc. All Rights Reserved.
//
// 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 <errno.h>
#include <nss.h>
#include <pthread.h>
#include <pwd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <syslog.h>
#include <string.h>
#include <unistd.h>
#include <sstream>

#include <fstream>

#include <compat.h>
#include <oslogin_utils.h>

using oslogin_utils::BufferManager;
using oslogin_utils::MutexLock;
using oslogin_utils::NssCache;
using oslogin_utils::GetUsersForGroup;

// File paths for the nss cache file.
static const char kDefaultFilePath[] = K_DEFAULT_PFILE_PATH;
static const char kDefaultBackupFilePath[] = K_DEFAULT_BACKUP_PFILE_PATH;
static const char kDefaultGroupPath[] = K_DEFAULT_GFILE_PATH;
static const char kDefaultBackupGroupPath[] = K_DEFAULT_BACKUP_GFILE_PATH;

// Local NSS Cache size. This affects the maximum number of passwd or group
// entries per http request.
static const uint64_t kNssGroupCacheSize = 499;
static const uint64_t kNssPasswdCacheSize = 2048;

// Passwd buffer size. We are guaranteed that a single OS Login user will not
// exceed 32k.
static const uint64_t kPasswdBufferSize = 32768;

int refreshpasswdcache() {
  syslog(LOG_INFO, "Refreshing passwd entry cache");
  int error_code = 0;
  // Temporary buffer to hold passwd entries before writing.
  char buffer[kPasswdBufferSize];
  struct passwd pwd;
  NssCache nss_cache(kNssPasswdCacheSize);

  std::ofstream cache_file(kDefaultBackupFilePath);
  if (cache_file.fail()) {
    syslog(LOG_ERR, "Failed to open file %s.", kDefaultBackupFilePath);
    return -1;
  }
  cache_file << std::unitbuf; // enable automatic flushing
  chown(kDefaultBackupFilePath, 0, 0);
  chmod(kDefaultBackupFilePath, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);

  nss_cache.Reset();
  while (!nss_cache.OnLastPage() || nss_cache.HasNextEntry()) {
    BufferManager buffer_manager(buffer, kPasswdBufferSize);
    if (!nss_cache.NssGetpwentHelper(&buffer_manager, &pwd, &error_code)) {
      if (error_code == ERANGE) {
        syslog(LOG_ERR, "passwd entry size out of range, skipping");
      } else if (error_code == EINVAL) {
        syslog(LOG_ERR, "Malformed passwd entry, skipping");
      } else if (error_code == ENOENT) {
        syslog(LOG_ERR, "Failure getting users, quitting");
        break;
      } else if (error_code == ENOMSG) {
        // ENOMSG means OS Login is not enabled.
        break;
      }
      continue;
    }
    if (strlen(pwd.pw_passwd) == 0) {
      pwd.pw_passwd = (char *)"*";
    }
    cache_file << pwd.pw_name << ":" << pwd.pw_passwd << ":" << pwd.pw_uid
               << ":" << pwd.pw_gid << ":" << pwd.pw_gecos << ":" << pwd.pw_dir
               << ":" << pwd.pw_shell << "\n";
  }
  cache_file.close();

  if (error_code == ENOMSG) {
    remove(kDefaultBackupFilePath);
    return 0;
  } else if (error_code == ENOENT) {
    syslog(LOG_ERR, "Failed to get users, not updating passwd cache file, removing %s.", kDefaultBackupFilePath);
    // If the cache file already exists, we don't want to overwrite it on a
    // server error. So remove the backup file and return here.
    struct stat buffer;
    if (stat(kDefaultFilePath, &buffer) == 0) {
      remove(kDefaultBackupFilePath);
      return 0;
    }
  }

  if (rename(kDefaultBackupFilePath, kDefaultFilePath) != 0) {
    syslog(LOG_ERR, "Error moving %s to %s.", kDefaultBackupFilePath, kDefaultFilePath);
    remove(kDefaultBackupFilePath);
  }

  return 0;
}

int refreshgroupcache() {
  syslog(LOG_INFO, "Refreshing group entry cache");
  int error_code = 0;
  // Temporary buffer to hold passwd entries before writing.
  char buffer[kPasswdBufferSize];
  NssCache nss_cache(kNssGroupCacheSize);

  std::ofstream cache_file(kDefaultBackupGroupPath);
  if (cache_file.fail()) {
    syslog(LOG_ERR, "Failed to open file %s.", kDefaultBackupGroupPath);
    return -1;
  }
  cache_file << std::unitbuf; // enable automatic flushing
  chown(kDefaultBackupGroupPath, 0, 0);
  chmod(kDefaultBackupGroupPath, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);

  struct group grp;
  nss_cache.Reset();
  std::vector<string> users;
  while (!nss_cache.OnLastPage() || nss_cache.HasNextEntry()) {
    BufferManager buffer_manager(buffer, kPasswdBufferSize);
    if (!nss_cache.NssGetgrentHelper(&buffer_manager, &grp, &error_code)) {
      if (error_code == ERANGE) {
        syslog(LOG_ERR, "Group entry size out of range, skipping");
      } else if (error_code == EINVAL) {
        syslog(LOG_ERR, "Malformed group entry, skipping");
      } else if (error_code == ENOENT) {
        syslog(LOG_ERR, "Failure getting groups, quitting");
        break;
      } else if (error_code == ENOMSG) {
        // ENOMSG means OS Login is not enabled.
        break;
      }
      continue;
    }
    std::string name(grp.gr_name);
    users.clear();
    if (!GetUsersForGroup(name, &users, &error_code)) {
      syslog(LOG_ERR,
             "Error getting users for group %s (error_code %d), skipping.",
             grp.gr_name, error_code);
      continue;
    }
    cache_file << grp.gr_name << ":" << grp.gr_passwd << ":" << grp.gr_gid << ":";
    for (int i = 0; i < (int)users.size(); i++) {
      if (i > 0) {
        cache_file << ",";
      }
      cache_file << users[i];
    }
    cache_file << "\n";
  }
  cache_file.close();

  if (error_code == ENOMSG) {
    remove(kDefaultBackupGroupPath);
    return 0;
  } else if (error_code == ENOENT) {
    syslog(LOG_ERR, "Failed to get groups, not updating passwd cache file, removing %s.", kDefaultBackupGroupPath);
    // If the cache file already exists, we don't want to overwrite it on a
    // server error. So remove the backup file and return here.
    struct stat buffer;
    if (stat(kDefaultGroupPath, &buffer) == 0) {
      remove(kDefaultBackupGroupPath);
      return 0;
    }
  }

  if (rename(kDefaultBackupGroupPath, kDefaultGroupPath) != 0) {
    syslog(LOG_ERR, "Error moving %s to %s.", kDefaultBackupGroupPath, kDefaultGroupPath);
    remove(kDefaultBackupGroupPath);
  }

  return 0;
}

int main() {
  openlog("oslogin_cache_refresh", LOG_PID|LOG_PERROR, LOG_USER);
  int u_res, g_res;
  u_res = refreshpasswdcache();
  g_res = refreshgroupcache();
  closelog();
  if (u_res != 0)
    return u_res;
  return g_res;
}
<commit_msg>throw exceptions in cache_refresh (#64)<commit_after>// Copyright 2018 Google Inc. All Rights Reserved.
//
// 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 <errno.h>
#include <nss.h>
#include <pthread.h>
#include <pwd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <syslog.h>
#include <string.h>
#include <unistd.h>
#include <sstream>

#include <fstream>

#include <compat.h>
#include <oslogin_utils.h>

using oslogin_utils::BufferManager;
using oslogin_utils::MutexLock;
using oslogin_utils::NssCache;
using oslogin_utils::GetUsersForGroup;

// File paths for the nss cache file.
static const char kDefaultFilePath[] = K_DEFAULT_PFILE_PATH;
static const char kDefaultBackupFilePath[] = K_DEFAULT_BACKUP_PFILE_PATH;
static const char kDefaultGroupPath[] = K_DEFAULT_GFILE_PATH;
static const char kDefaultBackupGroupPath[] = K_DEFAULT_BACKUP_GFILE_PATH;

// Local NSS Cache size. This affects the maximum number of passwd or group
// entries per http request.
static const uint64_t kNssGroupCacheSize = 499;
static const uint64_t kNssPasswdCacheSize = 2048;

// Passwd buffer size. We are guaranteed that a single OS Login user will not
// exceed 32k.
static const uint64_t kPasswdBufferSize = 32768;

int refreshpasswdcache() {
  syslog(LOG_INFO, "Refreshing passwd entry cache");
  int error_code = 0;
  // Temporary buffer to hold passwd entries before writing.
  char buffer[kPasswdBufferSize];
  struct passwd pwd;
  NssCache nss_cache(kNssPasswdCacheSize);

  std::ofstream cache_file(kDefaultBackupFilePath);
  if (cache_file.fail()) {
    syslog(LOG_ERR, "Failed to open file %s.", kDefaultBackupFilePath);
    return -1;
  }
  cache_file << std::unitbuf; // enable automatic flushing
  chown(kDefaultBackupFilePath, 0, 0);
  chmod(kDefaultBackupFilePath, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);

  nss_cache.Reset();
  while (!nss_cache.OnLastPage() || nss_cache.HasNextEntry()) {
    BufferManager buffer_manager(buffer, kPasswdBufferSize);
    if (!nss_cache.NssGetpwentHelper(&buffer_manager, &pwd, &error_code)) {
      if (error_code == ERANGE) {
        syslog(LOG_ERR, "passwd entry size out of range, skipping");
      } else if (error_code == EINVAL) {
        syslog(LOG_ERR, "Malformed passwd entry, skipping");
      } else if (error_code == ENOENT) {
        syslog(LOG_ERR, "Failure getting users, quitting");
        break;
      } else if (error_code == ENOMSG) {
        // ENOMSG means OS Login is not enabled.
        break;
      }
      continue;
    }
    if (strlen(pwd.pw_passwd) == 0) {
      pwd.pw_passwd = (char *)"*";
    }
    cache_file << pwd.pw_name << ":" << pwd.pw_passwd << ":" << pwd.pw_uid
               << ":" << pwd.pw_gid << ":" << pwd.pw_gecos << ":" << pwd.pw_dir
               << ":" << pwd.pw_shell << "\n";
  }
  cache_file.close();

  if (error_code == ENOMSG) {
    remove(kDefaultBackupFilePath);
    return 0;
  } else if (error_code == ENOENT) {
    syslog(LOG_ERR, "Failed to get users, not updating passwd cache file, removing %s.", kDefaultBackupFilePath);
    // If the cache file already exists, we don't want to overwrite it on a
    // server error. So remove the backup file and return here.
    struct stat buffer;
    if (stat(kDefaultFilePath, &buffer) == 0) {
      remove(kDefaultBackupFilePath);
      return 0;
    }
  }

  if (rename(kDefaultBackupFilePath, kDefaultFilePath) != 0) {
    syslog(LOG_ERR, "Error moving %s to %s.", kDefaultBackupFilePath, kDefaultFilePath);
    remove(kDefaultBackupFilePath);
  }

  return 0;
}

int refreshgroupcache() {
  syslog(LOG_INFO, "Refreshing group entry cache");
  int error_code = 0;
  // Temporary buffer to hold passwd entries before writing.
  char buffer[kPasswdBufferSize];
  NssCache nss_cache(kNssGroupCacheSize);

  std::ofstream cache_file(kDefaultBackupGroupPath);
  if (cache_file.fail()) {
    syslog(LOG_ERR, "Failed to open file %s.", kDefaultBackupGroupPath);
    return -1;
  }
  cache_file << std::unitbuf; // enable automatic flushing
  cache_file.exceptions( cache_file.exceptions() | std::ofstream::failbit | std::ofstream::badbit );
  chown(kDefaultBackupGroupPath, 0, 0);
  chmod(kDefaultBackupGroupPath, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);

  struct group grp;
  nss_cache.Reset();
  std::vector<string> users;
  while (!nss_cache.OnLastPage() || nss_cache.HasNextEntry()) {
    BufferManager buffer_manager(buffer, kPasswdBufferSize);
    if (!nss_cache.NssGetgrentHelper(&buffer_manager, &grp, &error_code)) {
      if (error_code == ERANGE) {
        syslog(LOG_ERR, "Group entry size out of range, skipping");
      } else if (error_code == EINVAL) {
        syslog(LOG_ERR, "Malformed group entry, skipping");
      } else if (error_code == ENOENT) {
        syslog(LOG_ERR, "Failure getting groups, quitting");
        break;
      } else if (error_code == ENOMSG) {
        // ENOMSG means OS Login is not enabled.
        break;
      }
      continue;
    }
    std::string name(grp.gr_name);
    users.clear();
    if (!GetUsersForGroup(name, &users, &error_code)) {
      syslog(LOG_ERR,
             "Error getting users for group %s (error_code %d), skipping.",
             grp.gr_name, error_code);
      continue;
    }
    try {
      cache_file << grp.gr_name << ":" << grp.gr_passwd << ":" << grp.gr_gid << ":";
      for (int i = 0; i < (int)users.size(); i++) {
        if (i > 0) {
          cache_file << ",";
        }
        cache_file << users[i];
      }
      cache_file << "\n";
    }
    catch (std::ofstream::failure e) {
      syslog(LOG_ERR, "Exception writing file");
      error_code = ENOENT;
      break;
    }
  }
  try {
    cache_file.close();
  }
  catch (std::ofstream::failure e) {
    syslog(LOG_ERR, "Exception closing file");
    error_code = ENOENT;
  }

  if (error_code == ENOMSG) {
    remove(kDefaultBackupGroupPath);
    return 0;
  } else if (error_code == ENOENT) {
    syslog(LOG_ERR, "Failed to get groups, not updating group cache file, removing %s.", kDefaultBackupGroupPath);
    // If the cache file already exists, we don't want to overwrite it on a
    // server error. So remove the backup file and return here.
    struct stat buffer;
    if (stat(kDefaultGroupPath, &buffer) == 0) {
      remove(kDefaultBackupGroupPath);
      return 0;
    }
  }

  if (rename(kDefaultBackupGroupPath, kDefaultGroupPath) != 0) {
    syslog(LOG_ERR, "Error moving %s to %s.", kDefaultBackupGroupPath, kDefaultGroupPath);
    remove(kDefaultBackupGroupPath);
  }

  return 0;
}

int main() {
  openlog("oslogin_cache_refresh", LOG_PID|LOG_PERROR, LOG_USER);
  int u_res, g_res;
  u_res = refreshpasswdcache();
  g_res = refreshgroupcache();
  closelog();
  if (u_res != 0)
    return u_res;
  return g_res;
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestBalloonWidget.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
//
// This example tests the vtkHoverWidget and vtkBalloonWidget.

// First include the required header files for the VTK classes we are using.
#include "vtkBalloonWidget.h"
#include "vtkBalloonRepresentation.h"
#include "vtkSphereSource.h"
#include "vtkCylinderSource.h"
#include "vtkConeSource.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkInteractorStyleTrackballCamera.h"
#include "vtkCommand.h"
#include "vtkInteractorEventRecorder.h"
#include "vtkRegressionTestImage.h"
#include "vtkDebugLeaks.h"
#include "vtkTestUtilities.h"
#include "vtkTIFFReader.h"

class vtkBalloonCallback : public vtkCommand
{
public:
  static vtkBalloonCallback *New()
    { return new vtkBalloonCallback; }
  virtual void Execute(vtkObject *caller, unsigned long, void*)
    {
      vtkBalloonWidget *balloonWidget = reinterpret_cast<vtkBalloonWidget*>(caller);
      if ( balloonWidget->GetCurrentProp() != NULL )
        {
        cout << "Prop selected\n";
        }
    }
};

int TestBalloonWidget( int argc, char *argv[] )
{
  // Create the RenderWindow, Renderer and both Actors
  //
  vtkRenderer *ren1 = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
  renWin->AddRenderer(ren1);

  vtkInteractorStyleTrackballCamera *style = vtkInteractorStyleTrackballCamera::New();
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
  iren->SetRenderWindow(renWin);
//  iren->SetInteractorStyle(style);

  // Create an image for the balloon widget
  char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/beach.tif");
  vtkTIFFReader *image1 = vtkTIFFReader::New();
  image1->SetFileName(fname);
  image1->SetOrientation( 4 );

  // Create a test pipeline
  //
  vtkSphereSource *ss = vtkSphereSource::New();
  vtkPolyDataMapper *mapper = vtkPolyDataMapper::New();
  mapper->SetInput(ss->GetOutput());
  vtkActor *sph = vtkActor::New();
  sph->SetMapper(mapper);

  vtkCylinderSource *cs = vtkCylinderSource::New();
  vtkPolyDataMapper *csMapper = vtkPolyDataMapper::New();
  csMapper->SetInput(cs->GetOutput());
  vtkActor *cyl = vtkActor::New();
  cyl->SetMapper(csMapper);
  cyl->AddPosition(5,0,0);

  vtkConeSource *coneSource = vtkConeSource::New();
  vtkPolyDataMapper *coneMapper = vtkPolyDataMapper::New();
  coneMapper->SetInput(coneSource->GetOutput());
  vtkActor *cone = vtkActor::New();
  cone->SetMapper(coneMapper);
  cone->AddPosition(0,5,0);

  // Create the widget
  vtkBalloonRepresentation *rep = vtkBalloonRepresentation::New();
  rep->SetBalloonLayoutToImageRight();

  vtkBalloonWidget *widget = vtkBalloonWidget::New();
  widget->SetInteractor(iren);
  widget->SetRepresentation(rep);
  widget->AddBalloon(sph,"This is a sphere",NULL);
  widget->AddBalloon(cyl,"This is a\ncylinder",image1->GetOutput());
  widget->AddBalloon(cone,"This is a\ncone,\na really big cone,\nyou wouldn't believe how big",image1->GetOutput());

  vtkBalloonCallback *cbk = vtkBalloonCallback::New();
  widget->AddObserver(vtkCommand::WidgetActivateEvent,cbk);

  // Add the actors to the renderer, set the background and size
  //
  ren1->AddActor(sph);
  ren1->AddActor(cyl);
  ren1->AddActor(cone);
  ren1->SetBackground(0.1, 0.2, 0.4);
  renWin->SetSize(300, 300);

  // record events
  vtkInteractorEventRecorder *recorder = vtkInteractorEventRecorder::New();
  recorder->SetInteractor(iren);
  recorder->SetFileName("c:/record.log");
//  recorder->Record();
//  recorder->ReadFromInputStringOn();
//  recorder->SetInputString(eventLog);

  // render the image
  //
  iren->Initialize();
  renWin->Render();
  widget->On();
//  recorder->Play();

  // Remove the observers so we can go interactive. Without this the "-I"
  // testing option fails.
  recorder->Off();

  int retVal = vtkRegressionTestImage( renWin );
  if ( retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }

  ss->Delete();
  mapper->Delete();
  sph->Delete();
//  ta->Delete();
  widget->RemoveObserver(cbk);
  cbk->Delete();
  widget->Off();
  widget->Delete();
  iren->Delete();
  renWin->Delete();
  ren1->Delete();
  recorder->Delete();
  delete [] fname;

  return !retVal;

}

<commit_msg>COMP: vtktiffreader API was changed<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestBalloonWidget.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
//
// This example tests the vtkHoverWidget and vtkBalloonWidget.

// First include the required header files for the VTK classes we are using.
#include "vtkBalloonWidget.h"
#include "vtkBalloonRepresentation.h"
#include "vtkSphereSource.h"
#include "vtkCylinderSource.h"
#include "vtkConeSource.h"
#include "vtkPolyDataMapper.h"
#include "vtkActor.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkInteractorStyleTrackballCamera.h"
#include "vtkCommand.h"
#include "vtkInteractorEventRecorder.h"
#include "vtkRegressionTestImage.h"
#include "vtkDebugLeaks.h"
#include "vtkTestUtilities.h"
#include "vtkTIFFReader.h"

class vtkBalloonCallback : public vtkCommand
{
public:
  static vtkBalloonCallback *New()
    { return new vtkBalloonCallback; }
  virtual void Execute(vtkObject *caller, unsigned long, void*)
    {
      vtkBalloonWidget *balloonWidget = reinterpret_cast<vtkBalloonWidget*>(caller);
      if ( balloonWidget->GetCurrentProp() != NULL )
        {
        cout << "Prop selected\n";
        }
    }
};

int TestBalloonWidget( int argc, char *argv[] )
{
  // Create the RenderWindow, Renderer and both Actors
  //
  vtkRenderer *ren1 = vtkRenderer::New();
  vtkRenderWindow *renWin = vtkRenderWindow::New();
  renWin->AddRenderer(ren1);

  vtkInteractorStyleTrackballCamera *style = vtkInteractorStyleTrackballCamera::New();
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
  iren->SetRenderWindow(renWin);
//  iren->SetInteractorStyle(style);

  // Create an image for the balloon widget
  char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/beach.tif");
  vtkTIFFReader *image1 = vtkTIFFReader::New();
  image1->SetFileName(fname);
  image1->SetOrientationType( 4 );

  // Create a test pipeline
  //
  vtkSphereSource *ss = vtkSphereSource::New();
  vtkPolyDataMapper *mapper = vtkPolyDataMapper::New();
  mapper->SetInput(ss->GetOutput());
  vtkActor *sph = vtkActor::New();
  sph->SetMapper(mapper);

  vtkCylinderSource *cs = vtkCylinderSource::New();
  vtkPolyDataMapper *csMapper = vtkPolyDataMapper::New();
  csMapper->SetInput(cs->GetOutput());
  vtkActor *cyl = vtkActor::New();
  cyl->SetMapper(csMapper);
  cyl->AddPosition(5,0,0);

  vtkConeSource *coneSource = vtkConeSource::New();
  vtkPolyDataMapper *coneMapper = vtkPolyDataMapper::New();
  coneMapper->SetInput(coneSource->GetOutput());
  vtkActor *cone = vtkActor::New();
  cone->SetMapper(coneMapper);
  cone->AddPosition(0,5,0);

  // Create the widget
  vtkBalloonRepresentation *rep = vtkBalloonRepresentation::New();
  rep->SetBalloonLayoutToImageRight();

  vtkBalloonWidget *widget = vtkBalloonWidget::New();
  widget->SetInteractor(iren);
  widget->SetRepresentation(rep);
  widget->AddBalloon(sph,"This is a sphere",NULL);
  widget->AddBalloon(cyl,"This is a\ncylinder",image1->GetOutput());
  widget->AddBalloon(cone,"This is a\ncone,\na really big cone,\nyou wouldn't believe how big",image1->GetOutput());

  vtkBalloonCallback *cbk = vtkBalloonCallback::New();
  widget->AddObserver(vtkCommand::WidgetActivateEvent,cbk);

  // Add the actors to the renderer, set the background and size
  //
  ren1->AddActor(sph);
  ren1->AddActor(cyl);
  ren1->AddActor(cone);
  ren1->SetBackground(0.1, 0.2, 0.4);
  renWin->SetSize(300, 300);

  // record events
  vtkInteractorEventRecorder *recorder = vtkInteractorEventRecorder::New();
  recorder->SetInteractor(iren);
  recorder->SetFileName("c:/record.log");
//  recorder->Record();
//  recorder->ReadFromInputStringOn();
//  recorder->SetInputString(eventLog);

  // render the image
  //
  iren->Initialize();
  renWin->Render();
  widget->On();
//  recorder->Play();

  // Remove the observers so we can go interactive. Without this the "-I"
  // testing option fails.
  recorder->Off();

  int retVal = vtkRegressionTestImage( renWin );
  if ( retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }

  ss->Delete();
  mapper->Delete();
  sph->Delete();
//  ta->Delete();
  widget->RemoveObserver(cbk);
  cbk->Delete();
  widget->Off();
  widget->Delete();
  iren->Delete();
  renWin->Delete();
  ren1->Delete();
  recorder->Delete();
  delete [] fname;

  return !retVal;

}

<|endoftext|>


<commit_before>/*
    Copyright (c) 2008 Volker Krause <vkrause@kde.org>

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

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

#include "kleojobexecutor.h"

#include <kleo/decryptverifyjob.h>
#include <kleo/importjob.h>
#include <kleo/verifydetachedjob.h>
#include <kleo/verifyopaquejob.h>

#include <kdebug.h>

#include <QBuffer>
#include <QEventLoop>

using namespace KMail;
using namespace Kleo;
using namespace GpgME;
using boost::shared_ptr;

KleoJobExecutor::KleoJobExecutor( QObject* parent ) : QObject( parent )
{
  setObjectName( "KleoJobExecutor" );
  mEventLoop = new QEventLoop( this );
}

GpgME::VerificationResult KleoJobExecutor::exec(
    Kleo::VerifyDetachedJob* job,
    const QByteArray & signature,
    const QByteArray & signedData )
{
  kDebug() << "Starting detached verification job";
  connect( job, SIGNAL(result(GpgME::VerificationResult)),
           SLOT(verificationResult(GpgME::VerificationResult)) );
  GpgME::Error err = job->start( signature, signedData );
  if ( err )
    return VerificationResult( err );
  mEventLoop->exec();
  return mVerificationResult;
}

GpgME::VerificationResult KleoJobExecutor::exec(
    Kleo::VerifyOpaqueJob * job,
    const QByteArray & signedData,
    QByteArray & plainText )
{
  kDebug() << "Starting opaque verfication job";
  connect( job, SIGNAL(result(GpgME::VerificationResult,QByteArray)),
           SLOT(verificationResult(GpgME::VerificationResult,QByteArray)) );
  GpgME::Error err = job->start( signedData );
  if ( err ) {
    plainText.clear();
    return VerificationResult( err );
  }
  mEventLoop->exec();
  plainText = mData;
  return mVerificationResult;
}

std::pair< GpgME::DecryptionResult, GpgME::VerificationResult > KleoJobExecutor::exec(
    Kleo::DecryptVerifyJob * job,
    const QByteArray & cipherText,
    QByteArray & plainText )
{
  kDebug() << "Starting decryption job";
  connect( job, SIGNAL(result(GpgME::DecryptionResult,GpgME::VerificationResult,QByteArray)),
           SLOT(decryptResult(GpgME::DecryptionResult,GpgME::VerificationResult,QByteArray)) );
  GpgME::Error err = job->start( cipherText );
  if ( err ) {
    plainText.clear();
    return std::make_pair( DecryptionResult( err ), VerificationResult( err ) );
  }
  mEventLoop->exec();
  plainText = mData;
  return std::make_pair( mDecryptResult, mVerificationResult );
}

GpgME::ImportResult KleoJobExecutor::exec(Kleo::ImportJob* job, const QByteArray & certData)
{
  connect( job, SIGNAL(result(GpgME::ImportResult)), SLOT(importResult(GpgME::ImportResult)) );
  GpgME::Error err = job->start( certData );
  if ( err )
    return ImportResult( err );
  mEventLoop->exec();
  return mImportResult;
}

void KleoJobExecutor::verificationResult(const GpgME::VerificationResult & result)
{
  kDebug() << "Detached verification job finished";
  mVerificationResult = result;
  mEventLoop->quit();
}

void KleoJobExecutor::verificationResult(const GpgME::VerificationResult & result, const QByteArray & plainText)
{
  kDebug() << "Opaque verification job finished";
  mVerificationResult = result;
  mData = plainText;
  mEventLoop->quit();
}

void KleoJobExecutor::decryptResult(
    const GpgME::DecryptionResult & decryptionresult,
    const GpgME::VerificationResult & verificationresult,
    const QByteArray & plainText )
{
  kDebug() << "Decryption job finished";
  mVerificationResult = verificationresult;
  mDecryptResult = decryptionresult;
  mData = plainText;
  mEventLoop->quit();
}

void KleoJobExecutor::importResult(const GpgME::ImportResult & result)
{
  mImportResult = result;
  mEventLoop->quit();
}

#include "kleojobexecutor.moc"
<commit_msg>Don't crash when quickly switching signed messages. The problem was that the sub-event loop of KleoJobExecutor would process user input, which made it possible to switch messages while the job was being executed. That caused trouble when returning from the sub-event loop.<commit_after>/*
    Copyright (c) 2008 Volker Krause <vkrause@kde.org>

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

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

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

#include "kleojobexecutor.h"

#include <kleo/decryptverifyjob.h>
#include <kleo/importjob.h>
#include <kleo/verifydetachedjob.h>
#include <kleo/verifyopaquejob.h>

#include <kdebug.h>

#include <QBuffer>
#include <QEventLoop>

using namespace KMail;
using namespace Kleo;
using namespace GpgME;
using boost::shared_ptr;

KleoJobExecutor::KleoJobExecutor( QObject* parent ) : QObject( parent )
{
  setObjectName( "KleoJobExecutor" );
  mEventLoop = new QEventLoop( this );
}

GpgME::VerificationResult KleoJobExecutor::exec(
    Kleo::VerifyDetachedJob* job,
    const QByteArray & signature,
    const QByteArray & signedData )
{
  kDebug() << "Starting detached verification job";
  connect( job, SIGNAL(result(GpgME::VerificationResult)),
           SLOT(verificationResult(GpgME::VerificationResult)) );
  GpgME::Error err = job->start( signature, signedData );
  if ( err )
    return VerificationResult( err );
  mEventLoop->exec( QEventLoop::ExcludeUserInputEvents );
  return mVerificationResult;
}

GpgME::VerificationResult KleoJobExecutor::exec(
    Kleo::VerifyOpaqueJob * job,
    const QByteArray & signedData,
    QByteArray & plainText )
{
  kDebug() << "Starting opaque verfication job";
  connect( job, SIGNAL(result(GpgME::VerificationResult,QByteArray)),
           SLOT(verificationResult(GpgME::VerificationResult,QByteArray)) );
  GpgME::Error err = job->start( signedData );
  if ( err ) {
    plainText.clear();
    return VerificationResult( err );
  }
  mEventLoop->exec( QEventLoop::ExcludeUserInputEvents );
  plainText = mData;
  return mVerificationResult;
}

std::pair< GpgME::DecryptionResult, GpgME::VerificationResult > KleoJobExecutor::exec(
    Kleo::DecryptVerifyJob * job,
    const QByteArray & cipherText,
    QByteArray & plainText )
{
  kDebug() << "Starting decryption job";
  connect( job, SIGNAL(result(GpgME::DecryptionResult,GpgME::VerificationResult,QByteArray)),
           SLOT(decryptResult(GpgME::DecryptionResult,GpgME::VerificationResult,QByteArray)) );
  GpgME::Error err = job->start( cipherText );
  if ( err ) {
    plainText.clear();
    return std::make_pair( DecryptionResult( err ), VerificationResult( err ) );
  }
  mEventLoop->exec( QEventLoop::ExcludeUserInputEvents );
  plainText = mData;
  return std::make_pair( mDecryptResult, mVerificationResult );
}

GpgME::ImportResult KleoJobExecutor::exec(Kleo::ImportJob* job, const QByteArray & certData)
{
  connect( job, SIGNAL(result(GpgME::ImportResult)), SLOT(importResult(GpgME::ImportResult)) );
  GpgME::Error err = job->start( certData );
  if ( err )
    return ImportResult( err );
  mEventLoop->exec( QEventLoop::ExcludeUserInputEvents );
  return mImportResult;
}

void KleoJobExecutor::verificationResult(const GpgME::VerificationResult & result)
{
  kDebug() << "Detached verification job finished";
  mVerificationResult = result;
  mEventLoop->quit();
}

void KleoJobExecutor::verificationResult(const GpgME::VerificationResult & result, const QByteArray & plainText)
{
  kDebug() << "Opaque verification job finished";
  mVerificationResult = result;
  mData = plainText;
  mEventLoop->quit();
}

void KleoJobExecutor::decryptResult(
    const GpgME::DecryptionResult & decryptionresult,
    const GpgME::VerificationResult & verificationresult,
    const QByteArray & plainText )
{
  kDebug() << "Decryption job finished";
  mVerificationResult = verificationresult;
  mDecryptResult = decryptionresult;
  mData = plainText;
  mEventLoop->quit();
}

void KleoJobExecutor::importResult(const GpgME::ImportResult & result)
{
  mImportResult = result;
  mEventLoop->quit();
}

#include "kleojobexecutor.moc"
<|endoftext|>


<commit_before>/***************************************************************************
                          FilterPMail.cxx  -  Pegasus-Mail import
                             -------------------
    begin                : Sat Jan 6 2001
    copyright            : (C) 2001 by Holger Schurig
    email                : holgerschurig@gmx.de
 ***************************************************************************/

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

#include <config.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <qregexp.h>
#include <ktempfile.h>
#include <kdebug.h>

#include "filter_pmail.hxx"

FilterPMail::FilterPMail() :
        Filter(i18n("Import Folders From Pegasus-Mail"),
               "Holger Schurig
( Filter accelerated by Danny Kukawka )
",
               i18n("
Select the Pegasus-Mail directory on your system (containing CNM, PMM and MBX files). "
                    "On many systems this is stored in C:\\PMail\\mail
"
                    "
Note: This import filter will import your folders, but not "
                    "the folder structure. But you will probably only do "
                    "this one time.
"
                    "
Note: Emails will be imported into folder with the prefix pmail-
"))
{}

FilterPMail::~FilterPMail()
{
    endImport();
}

void FilterPMail::import(FilterInfo *info)
{
    inf = info;

    // Select directory from where I have to import files
    KFileDialog *kfd;
    kfd = new KFileDialog( QDir::homeDirPath(), "", 0, "kfiledialog", true );
    kfd->setMode(KFile::Directory | KFile::LocalOnly);
    kfd->exec();
    QString chosenDir  = kfd->selectedFile();

    if (chosenDir.isEmpty()) {
        info->alert(i18n("No directory selected."));
        return;
    }

    // Count total number of files to be processed
    info->addLog(i18n("Counting files..."));
    dir.setPath (chosenDir);
    QStringList files = dir.entryList("*.[cC][nN][mM]; *.[pP][mM][mM]; *.[mM][bB][xX]", QDir::Files, QDir::Name);
    totalFiles = files.count();
    kdDebug() << "Count is " << totalFiles << endl;

    info->addLog(i18n("Importing new mail files ('.cnm')..."));
    processFiles("*.[cC][nN][mM]", &FilterPMail::importNewMessage);
    info->addLog(i18n("Importing mail folders ('.pmm')..."));
    processFiles("*.[pP][mM][mM]", &FilterPMail::importMailFolder);
    info->addLog(i18n("Importing 'UNIX' mail folders ('.mbx')..."));
    processFiles("*.[mM][bB][xX]", &FilterPMail::importUnixMailFolder);

    info->addLog( i18n("Finished importing emails from %1").arg( chosenDir ));
    info->setCurrent(100);
    info->setOverall(100);
}

/** this looks for all files with the filemask 'mask' and calls the 'workFunc' on each of them */
void FilterPMail::processFiles(const QString& mask, void(FilterPMail::* workFunc)(const QString&) )
{
    QStringList files = dir.entryList(mask, QDir::Files, QDir::Name);
    //kdDebug() << "Mask is " << mask << " count is " << files.count() << endl;
    for ( QStringList::Iterator mailFile = files.begin(); mailFile != files.end(); ++mailFile ) {
        // Notify current file
        QFileInfo mailfileinfo(*mailFile);
        inf->setFrom(mailfileinfo.fileName());

        // Clear the other fields
        inf->setTo(QString::null);
        inf->setCurrent(QString::null);
        inf->setCurrent(-1);

        // call worker function, increase progressbar
        inf->addLog(i18n("Importing %1").arg(*mailFile));
        (this->*workFunc)(dir.filePath(*mailFile));
        currentFile++;
        inf->setOverall( 100 * currentFile / totalFiles );
    }
}

/** this function imports one *.CNM message */
void FilterPMail::importNewMessage(const QString& file)
{
    QString destFolder("PMail-New Messages");
    inf->setTo(destFolder);

    /* comment by Danny Kukawka:
     * addMessage() == old function, need more time and check for duplicates
     * addMessage_fastImport == new function, faster and no check for duplicates
     */
    if(inf->removeDupMsg)
        addMessage( inf, destFolder, file );
    else
        addMessage_fastImport( inf, destFolder, file );
}

/** this function imports one mail folder file (*.PMM) */
void FilterPMail::importMailFolder(const QString& file)
{
    // Format of a PMM file:
    // First comes a header with 128 bytes. At the beginning is the name of
    // the folder. Then there are some unknown bytes (strings). At offset 128
    // the first message starts.
    //
    // Each message is terminated by a 0x1A byte. The next message follows
    // immediately.
    //
    // The last message is followed by a 0x1A, too.
    //
    // 000000 6d 61 69 6c 73 65 72 76 65 72 2d 70 72 6f 6a 65    mailserver-proje
    // 000010 63 74 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ct..............
    // 000020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ................
    // 000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ................
    // 000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ................
    // 000050 00 00 00 00 00 00 36 30 34 37 35 37 32 45 3a 36    ......6047572E:6
    // 000060 46 34 39 3a 46 4f 4c 30 31 33 35 35 00 00 00 00    F49:FOL01355....
    // 000070 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ................
    // 000080 52 65 74 75 72 6e 2d 50 61 74 68 3a 20 3c 75 72    Return-Path: <ur
    // ...
    // 000cb0 2d 2d 2d 2d 2d 2d 2d 2d 2d 2b 0d 0a 1a 52 65 74    ---------+...Ret
    // 000cc0 75 72 6e 2d 50 61 74 68 3a 20 3c 62 6f 75 6e 63    urn-Path: <bounc
    // ...
    // 04dc50 46 30 33 38 44 2e 36 31 35 44 37 34 44 30 2d 2d    F038D.615D74D0--
    // 04dc60 0d 0a 1a

    struct {
        char folder[86];
        char id[42];
    }
    pmm_head;

    int ch = 0;
    int state = 0;
    int n = 0;
    KTempFile *tempfile = 0;

    // open the message
    QFile f(file);
    f.open(IO_ReadOnly);

    // Get folder name
    f.readBlock((char *) &pmm_head, sizeof(pmm_head));
    QString folder("PMail-");
    folder.append(pmm_head.folder);
    inf->setTo(folder);
    // The folder name might contain weird characters ...
    folder.replace(QRegExp("[^a-zA-Z0-9:.-]"), ":");

    // State machine to read the data in. The fgetc usage is probably terribly slow ...
    while ((ch = f.getch()) >= 0) {
        switch (state) {

            // new message state
        case 0:
            // open temp output file
            tempfile = new KTempFile;
            state = 1;
            inf->setCurrent(i18n("Message %1").arg(n++));
            // fall through

            // inside a message state
        case 1:
            if (ch == 0x1a) {
                // close file, send it
                tempfile->close();

                if(inf->removeDupMsg)
                    addMessage( inf, folder, tempfile->name() );
                else
                    addMessage_fastImport( inf, folder, tempfile->name() );

                tempfile->unlink();
                delete tempfile;
                state = 0;
                break;
            }
            if (ch == 0x0d) {
                break;
            }
            tempfile->file()->putch(ch);
            break;
        }
    }

    // did Folder end without 0x1a at the end?
    if (state != 0) {
        tempfile->close();
        if(inf->removeDupMsg)
            addMessage( inf, folder, tempfile->name() );
        else
            addMessage_fastImport( inf, folder, tempfile->name() );

        tempfile->unlink();
        delete tempfile;
    }

    f.close();
}

/** imports a 'unix' format mail folder (*.MBX) */
void FilterPMail::importUnixMailFolder(const QString& file)
{
    #define MAX_LINE 4096
    #define MSG_SEPERATOR_START "From "
    #define MSG_SEPERATOR_REGEX "^From .*..:...*$"
    static short msgSepLen = strlen(MSG_SEPERATOR_START);

    struct {
        char folder[58];
    }
    pmg_head;
    QFile f;
    QString s(file);
    QString folder;

    QCString line(MAX_LINE);
    KTempFile *tempfile = 0;
    int n = 0;
    QRegExp regexp(MSG_SEPERATOR_REGEX);

    // Get folder name
    s.replace( QRegExp("mbx$"), "pmg");
    s.replace( QRegExp("MBX$"), "PMG");
    f.setName(s);
    f.open(IO_ReadOnly);
    f.readBlock((char *) &pmg_head, sizeof(pmg_head));
    f.close();
    folder = "PMail-";
    folder.append(pmg_head.folder);
    inf->setTo(folder);
    // The folder name might contain weird characters ...
    folder.replace(QRegExp("[^a-zA-Z0-9:.-]"), ":");

    // Read in the folder
    //
    // Messages are separated by "From " lines. We use a logic similar
    // to KMail's kmfolder.cpp to find the boundaries.

    f.setName(file);
    f.open(IO_ReadOnly);
    while (f.readLine(line.data(), MAX_LINE)) {
        // Look for separator
        if (tempfile &&                                             // when we wrote to outfile
                (strncmp(line,MSG_SEPERATOR_START, msgSepLen)==0 &&  // quick compar
                 regexp.search(line) >= 0))                            // slower regexp
        {
            tempfile->close();

            if(inf->removeDupMsg)
                addMessage( inf, folder, tempfile->name() );
            else
                addMessage_fastImport( inf, folder, tempfile->name() );

            tempfile->unlink();
            delete tempfile;
            tempfile = 0;
        }

        // Do we need to open/reopen output file?
        if (!tempfile) {
            tempfile = new KTempFile;
            // Notify progress
            n++;
            inf->setCurrent(i18n("Message %1").arg(n));
        }

        tempfile->file()->writeBlock(line.data(), line.length());
    }

    if (tempfile) {
        tempfile->close();

        if(inf->removeDupMsg)
            addMessage( inf, folder, tempfile->name() );
        else
            addMessage_fastImport( inf, folder, tempfile->name() );

        tempfile->unlink();
        delete tempfile;
    }

    f.close();
}
<commit_msg>- fixed bug #103738:   - rewritten the 'mbox'-function ( importUnixMailFolder() )   - fixed problem with cancel the import - Changed the import folder from PMail-"Folder" to PegasusMail-Import/<commit_after>/***************************************************************************
                          FilterPMail.cxx  -  Pegasus-Mail import
                             -------------------
    begin                : Sat Jan 6 2001
    copyright            : (C) 2001 by Holger Schurig
    email                : holgerschurig@gmx.de
 ***************************************************************************/

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

#include <config.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <qregexp.h>
#include <ktempfile.h>
#include <kdebug.h>

#include "filter_pmail.hxx"

FilterPMail::FilterPMail() :
        Filter(i18n("Import Folders From Pegasus-Mail"),
               "Holger Schurig
( Filter accelerated by Danny Kukawka )
",
               i18n("
Select the Pegasus-Mail directory on your system (containing CNM, PMM and MBX files). "
                    "On many systems this is stored in C:\\PMail\\mail
"
                    "
Note: This import filter will import your folders, but not "
                    "the folder structure. But you will probably only do "
                    "this one time.
"
                    "
Note: Emails will be imported into folder named \"PegasusMail-Import\".
"))
{}

FilterPMail::~FilterPMail()
{
    endImport();
}

void FilterPMail::import(FilterInfo *info)
{
    inf = info;

    // Select directory from where I have to import files
    KFileDialog *kfd;
    kfd = new KFileDialog( QDir::homeDirPath(), "", 0, "kfiledialog", true );
    kfd->setMode(KFile::Directory | KFile::LocalOnly);
    kfd->exec();
    QString chosenDir  = kfd->selectedFile();

    if (chosenDir.isEmpty()) {
        info->alert(i18n("No directory selected."));
        return;
    }

    // Count total number of files to be processed
    info->addLog(i18n("Counting files..."));
    dir.setPath (chosenDir);
    QStringList files = dir.entryList("*.[cC][nN][mM]; *.[pP][mM][mM]; *.[mM][bB][xX]", QDir::Files, QDir::Name);
    totalFiles = files.count();
    kdDebug() << "Count is " << totalFiles << endl;

    info->addLog(i18n("Importing new mail files ('.cnm')..."));
    processFiles("*.[cC][nN][mM]", &FilterPMail::importNewMessage);
    info->addLog(i18n("Importing mail folders ('.pmm')..."));
    processFiles("*.[pP][mM][mM]", &FilterPMail::importMailFolder);
    info->addLog(i18n("Importing 'UNIX' mail folders ('.mbx')..."));
    processFiles("*.[mM][bB][xX]", &FilterPMail::importUnixMailFolder);

    info->addLog( i18n("Finished importing emails from %1").arg( chosenDir ));
    info->setCurrent(100);
    info->setOverall(100);
}

/** this looks for all files with the filemask 'mask' and calls the 'workFunc' on each of them */
void FilterPMail::processFiles(const QString& mask, void(FilterPMail::* workFunc)(const QString&) )
{
    if (inf->shouldTerminate()) return;

    QStringList files = dir.entryList(mask, QDir::Files, QDir::Name);
    //kdDebug() << "Mask is " << mask << " count is " << files.count() << endl;
    for ( QStringList::Iterator mailFile = files.begin(); mailFile != files.end(); ++mailFile ) {
        // Notify current file
        QFileInfo mailfileinfo(*mailFile);
        inf->setFrom(mailfileinfo.fileName());

        // Clear the other fields
        inf->setTo(QString::null);
        inf->setCurrent(QString::null);
        inf->setCurrent(-1);

        // call worker function, increase progressbar
        inf->addLog(i18n("Importing %1").arg(*mailFile));
        (this->*workFunc)(dir.filePath(*mailFile));
        currentFile++;
        inf->setOverall( 100 * currentFile / totalFiles );
        if (inf->shouldTerminate()) return;
    }
}

/** this function imports one *.CNM message */
void FilterPMail::importNewMessage(const QString& file)
{
    QString destFolder("PegasusMail-Import/New Messages");
    inf->setTo(destFolder);

    /* comment by Danny Kukawka:
     * addMessage() == old function, need more time and check for duplicates
     * addMessage_fastImport == new function, faster and no check for duplicates
     */
    if(inf->removeDupMsg)
        addMessage( inf, destFolder, file );
    else
        addMessage_fastImport( inf, destFolder, file );
}

/** this function imports one mail folder file (*.PMM) */
void FilterPMail::importMailFolder(const QString& file)
{
    // Format of a PMM file:
    // First comes a header with 128 bytes. At the beginning is the name of
    // the folder. Then there are some unknown bytes (strings). At offset 128
    // the first message starts.
    //
    // Each message is terminated by a 0x1A byte. The next message follows
    // immediately.
    //
    // The last message is followed by a 0x1A, too.
    //
    // 000000 6d 61 69 6c 73 65 72 76 65 72 2d 70 72 6f 6a 65    mailserver-proje
    // 000010 63 74 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ct..............
    // 000020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ................
    // 000030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ................
    // 000040 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ................
    // 000050 00 00 00 00 00 00 36 30 34 37 35 37 32 45 3a 36    ......6047572E:6
    // 000060 46 34 39 3a 46 4f 4c 30 31 33 35 35 00 00 00 00    F49:FOL01355....
    // 000070 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00    ................
    // 000080 52 65 74 75 72 6e 2d 50 61 74 68 3a 20 3c 75 72    Return-Path: <ur
    // ...
    // 000cb0 2d 2d 2d 2d 2d 2d 2d 2d 2d 2b 0d 0a 1a 52 65 74    ---------+...Ret
    // 000cc0 75 72 6e 2d 50 61 74 68 3a 20 3c 62 6f 75 6e 63    urn-Path: <bounc
    // ...
    // 04dc50 46 30 33 38 44 2e 36 31 35 44 37 34 44 30 2d 2d    F038D.615D74D0--
    // 04dc60 0d 0a 1a

    struct {
        char folder[86];
        char id[42];
    }
    pmm_head;

    int ch = 0;
    int state = 0;
    int n = 0;
    KTempFile *tempfile = 0;

    // open the message
    QFile f(file);
    f.open(IO_ReadOnly);

    // Get folder name
    f.readBlock((char *) &pmm_head, sizeof(pmm_head));
    QString folder("PegasusMail-Import/");
    folder.append(pmm_head.folder);
    inf->setTo(folder);

    // State machine to read the data in. The fgetc usage is probably terribly slow ...
    while ((ch = f.getch()) >= 0) {
         if (inf->shouldTerminate()){
            tempfile->close();
            tempfile->unlink();
            return;
        }
        switch (state) {

            // new message state
        case 0:
            // open temp output file
            tempfile = new KTempFile;
            state = 1;
            inf->setCurrent(i18n("Message %1").arg(n++));
            // fall through

            // inside a message state
        case 1:
            if (ch == 0x1a) {
                // close file, send it
                tempfile->close();

                if(inf->removeDupMsg)
                    addMessage( inf, folder, tempfile->name() );
                else
                    addMessage_fastImport( inf, folder, tempfile->name() );

                tempfile->unlink();
                delete tempfile;
                state = 0;
                break;
            }
            if (ch == 0x0d) {
                break;
            }
            tempfile->file()->putch(ch);
            break;
        }
    }

    // did Folder end without 0x1a at the end?
    if (state != 0) {
        tempfile->close();
        if(inf->removeDupMsg)
            addMessage( inf, folder, tempfile->name() );
        else
            addMessage_fastImport( inf, folder, tempfile->name() );

        tempfile->unlink();
        delete tempfile;
    }

    f.close();
}

/** imports a 'unix' format mail folder (*.MBX) */
void FilterPMail::importUnixMailFolder(const QString& file)
{
    struct {
        char folder[58];
    } pmg_head;

    QFile f;
    QString folder("PegasusMail-Import/"), s(file), seperate;
    QByteArray line(MAX_LINE);
    int n = 0, l = 0;

    /** Get the folder name */
    s.replace( QRegExp("mbx$"), "pmg");
    s.replace( QRegExp("MBX$"), "PMG");
    f.setName(s);
    if (! f.open( IO_ReadOnly ) ) {
        inf->alert( i18n("Unable to open %1, skipping").arg( s ) );
        return;
    } else {
        f.readBlock((char *) &pmg_head, sizeof(pmg_head));
        f.close();

        folder.append(pmg_head.folder);
        inf->setTo(folder);
        inf->setTo(folder);
    }

    /** Read in the mbox */
    f.setName(file);
    if (! f.open( IO_ReadOnly ) ) {
        inf->alert( i18n("Unable to open %1, skipping").arg( s ) );
    } else {
        l = f.readLine( line.data(),MAX_LINE); // read the first line which is unneeded
        while ( ! f.atEnd() ) {
            KTempFile tempfile;

            // we lost the last line, which is the first line of the new message in
            // this lopp, but this is ok, because this is the seperate line with
            // "From ???@???" and we can forget them
            while ( ! f.atEnd() &&  (l = f.readLine(line.data(),MAX_LINE)) && ((seperate = line.data()).left(5) != "From ")) {
                tempfile.file()->writeBlock(line.data(), l);
                if (inf->shouldTerminate()){
                    tempfile.close();
                    tempfile.unlink();
                    return;
                }
            }
            tempfile.close();
            if(inf->removeDupMsg)
                addMessage( inf, folder, tempfile.name() );
            else
                addMessage_fastImport( inf, folder, tempfile.name() );
            tempfile.unlink();

            n++;
            inf->setCurrent(i18n("Message %1").arg(n));
            inf->setCurrent( (int) ( ( (float) f.at() / f.size() ) * 100 ) );
        }
    }
    f.close();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: xmlfonte.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-17 15:07:38 $
 *
 *  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 _COM_SUN_STAR_TEXT_XTEXTDOCUMENT_HPP_
#include <com/sun/star/text/XTextDocument.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_
#include <com/sun/star/text/XText.hpp>
#endif

#ifndef _COM_SUN_STAR_TEXT_XTEXTDOCUMENT_HPP_
#include <com/sun/star/text/XTextDocument.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_
#include <com/sun/star/text/XText.hpp>
#endif
#ifndef _XMLOFF_XMLFONTAUTOSTYLEPOOL_HXX
#include <xmloff/XMLFontAutoStylePool.hxx>
#endif
#ifndef _SVX_FONTITEM_HXX
#include <svx/fontitem.hxx>
#endif
#ifndef _UNOOBJ_HXX
#include <unoobj.hxx>
#endif
#ifndef _DOC_HXX //autogen wg. SwDoc
#include <doc.hxx>
#endif

#ifndef _XMLEXP_HXX
#include <xmlexp.hxx>
#endif

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::text;

class SwXMLFontAutoStylePool_Impl: public XMLFontAutoStylePool
{
    public:

    SwXMLFontAutoStylePool_Impl( SwXMLExport& rExport );

};

SwXMLFontAutoStylePool_Impl::SwXMLFontAutoStylePool_Impl(
    SwXMLExport& rExport ) :
    XMLFontAutoStylePool( rExport )
{
    sal_uInt16 aWhichIds[3] = { RES_CHRATR_FONT, RES_CHRATR_CJK_FONT,
                                RES_CHRATR_CTL_FONT };

    Reference < XTextDocument > xTextDoc( rExport.GetModel(), UNO_QUERY );
    Reference < XText > xText = xTextDoc->getText();
    Reference<XUnoTunnel> xTextTunnel( xText, UNO_QUERY);
    ASSERT( xTextTunnel.is(), "missing XUnoTunnel for Cursor" );
    if( !xTextTunnel.is() )
        return;

    SwXText *pText = (SwXText *)xTextTunnel->getSomething(
                                        SwXText::getUnoTunnelId() );
    ASSERT( pText, "SwXText missing" );
    if( !pText )
        return;

    const SfxItemPool& rPool = pText->GetDoc()->GetAttrPool();
    const SfxPoolItem* pItem;
    for( sal_uInt16 i=0; i<3; i++ )
    {
        sal_uInt16 nWhichId = aWhichIds[i];

        const SvxFontItem& rFont =
            (const SvxFontItem&)rPool.GetDefaultItem( nWhichId );
        Add( rFont.GetFamilyName(), rFont.GetStyleName(),
             rFont.GetFamily(), rFont.GetPitch(), rFont.GetCharSet() );
        sal_uInt16 nItems = rPool.GetItemCount( nWhichId );
        for( sal_uInt16 j = 0; j < nItems; ++j )
        {
            if( 0 != (pItem = rPool.GetItem( nWhichId, j ) ) )
            {
                const SvxFontItem *pFont =
                            (const SvxFontItem *)pItem;
                Add( pFont->GetFamilyName(), pFont->GetStyleName(),
                     pFont->GetFamily(), pFont->GetPitch(),
                     pFont->GetCharSet() );
            }
        }
    }
}

XMLFontAutoStylePool* SwXMLExport::CreateFontAutoStylePool()
{
    return new SwXMLFontAutoStylePool_Impl( *this );
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.1254); FILE MERGED 2005/09/05 13:42:51 rt 1.4.1254.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: xmlfonte.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 06:21:41 $
 *
 *  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
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _HINTIDS_HXX
#include "hintids.hxx"
#endif

#ifndef _COM_SUN_STAR_TEXT_XTEXTDOCUMENT_HPP_
#include <com/sun/star/text/XTextDocument.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_
#include <com/sun/star/text/XText.hpp>
#endif

#ifndef _COM_SUN_STAR_TEXT_XTEXTDOCUMENT_HPP_
#include <com/sun/star/text/XTextDocument.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XTEXT_HPP_
#include <com/sun/star/text/XText.hpp>
#endif
#ifndef _XMLOFF_XMLFONTAUTOSTYLEPOOL_HXX
#include <xmloff/XMLFontAutoStylePool.hxx>
#endif
#ifndef _SVX_FONTITEM_HXX
#include <svx/fontitem.hxx>
#endif
#ifndef _UNOOBJ_HXX
#include <unoobj.hxx>
#endif
#ifndef _DOC_HXX //autogen wg. SwDoc
#include <doc.hxx>
#endif

#ifndef _XMLEXP_HXX
#include <xmlexp.hxx>
#endif

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::text;

class SwXMLFontAutoStylePool_Impl: public XMLFontAutoStylePool
{
    public:

    SwXMLFontAutoStylePool_Impl( SwXMLExport& rExport );

};

SwXMLFontAutoStylePool_Impl::SwXMLFontAutoStylePool_Impl(
    SwXMLExport& rExport ) :
    XMLFontAutoStylePool( rExport )
{
    sal_uInt16 aWhichIds[3] = { RES_CHRATR_FONT, RES_CHRATR_CJK_FONT,
                                RES_CHRATR_CTL_FONT };

    Reference < XTextDocument > xTextDoc( rExport.GetModel(), UNO_QUERY );
    Reference < XText > xText = xTextDoc->getText();
    Reference<XUnoTunnel> xTextTunnel( xText, UNO_QUERY);
    ASSERT( xTextTunnel.is(), "missing XUnoTunnel for Cursor" );
    if( !xTextTunnel.is() )
        return;

    SwXText *pText = (SwXText *)xTextTunnel->getSomething(
                                        SwXText::getUnoTunnelId() );
    ASSERT( pText, "SwXText missing" );
    if( !pText )
        return;

    const SfxItemPool& rPool = pText->GetDoc()->GetAttrPool();
    const SfxPoolItem* pItem;
    for( sal_uInt16 i=0; i<3; i++ )
    {
        sal_uInt16 nWhichId = aWhichIds[i];

        const SvxFontItem& rFont =
            (const SvxFontItem&)rPool.GetDefaultItem( nWhichId );
        Add( rFont.GetFamilyName(), rFont.GetStyleName(),
             rFont.GetFamily(), rFont.GetPitch(), rFont.GetCharSet() );
        sal_uInt16 nItems = rPool.GetItemCount( nWhichId );
        for( sal_uInt16 j = 0; j < nItems; ++j )
        {
            if( 0 != (pItem = rPool.GetItem( nWhichId, j ) ) )
            {
                const SvxFontItem *pFont =
                            (const SvxFontItem *)pItem;
                Add( pFont->GetFamilyName(), pFont->GetStyleName(),
                     pFont->GetFamily(), pFont->GetPitch(),
                     pFont->GetCharSet() );
            }
        }
    }
}

XMLFontAutoStylePool* SwXMLExport::CreateFontAutoStylePool()
{
    return new SwXMLFontAutoStylePool_Impl( *this );
}
<|endoftext|>