<commit_before>/*************************************************************************
 *
 *  $RCSfile: msfilter.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2004-02-26 12:46:39 $
 *
 *  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): cmc@openoffice.org
 *
 *
 ************************************************************************/

/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- */
/// @HTML

#ifndef SW_MS_MSFILTER_HXX
#define SW_MS_MSFILTER_HXX

#include <set>
#include <vector>

#ifndef _SWTYPES_HXX
#   include <swtypes.hxx>       //SwTwips
#endif
#ifndef WW_WWSTYLES_HXX
#   include "wwstyles.hxx"      //ww::sti
#endif
#ifndef _RTL_TEXTENC_H
#   include <rtl/textenc.h>     //rtl_TextEncoding
#endif
#ifndef _SV_GEN_HXX
#   include <tools/gen.hxx>     //Size
#endif

class SwDoc;
class SwPaM;
class String;
class SwNoTxtNode;
class SwTxtNode;
namespace
{
    template<class C> class StyleMapperImpl;
}
class SwTxtFmtColl;
class SwCharFmt;
typedef StyleMapperImpl<SwTxtFmtColl> ParaMapper;
typedef StyleMapperImpl<SwCharFmt> CharMapper;

namespace sw
{
    namespace ms
    {
        /** MSOffice appears to set the charset of unicode fonts to MS 932

            Arial Unicode MS for example is a unicode font, but word sets
            exported uses of it to the MS 932 charset

            @param eTextEncoding
                the OOo encoding to convert from

            @return
                a msoffice equivalent charset identifier

            @author
                Caolán McNamara
        */
        sal_uInt8 rtl_TextEncodingToWinCharset(rtl_TextEncoding eTextEncoding);

        /** Get the OOo rtl_TextEncoding equivalent to the closest
            textencoding word will be using

            Some of the eTextEncodings in writer will map to an encoding in
            word which does not map back to the same encoding, so get the
            encoding it would map back to

            @param eTextEncoding
                the OOo encoding to convert from

            @return
                the writer equivalent charset identifier

            @author
                Caolán McNamara
        */
        rtl_TextEncoding rtl_TextEncodingToWinCharsetAndBack(
            rtl_TextEncoding eTextEncoding);

        /** Import a MSWord XE field. Suitable for .doc and .rtf

            @param rDoc
                the document to insert into

            @param rPaM
                the position in the document to insert into

            @param rXE
                the arguments of the original word XE field

            @author
                Caolán McNamara
        */
        void ImportXE(SwDoc &rDoc, SwPaM &rPaM, const String &rXE);
    }

    namespace util
    {

        /** Clips a value to MAX/MIN 16bit value to make it safe for use
            as a position value to give to writer. i.e. +-57.8cm. Sometimes
            we see ridiculous values for positioning in rtf and word document,
            this captures such ones and clips them to values which are
            still outside the document, but of a value that doesn't cause
            problems for writer's layout, e.g. see
            http://www.openoffice.org/issues/show_bug.cgi?id=i9245

            @param nIn

            @return nIn clipped to min/max 16bit value

            @author
                Caolán McNamara
        */
        SwTwips MakeSafePositioningValue(SwTwips nIn);

        /** Knows which writer style a given word style should be imported as

            Mapping a word style to a writer style has to consider mapping
            the word builtin styles like "Normal" as the default root style
            to our default root style which is called "Default" in english,
            and "Normal" in german.

            Additionally it then has to avoid name collisions such as

            a) styles "Normal" and "Default" in a single document, where
            we can use the original distinct names "Normal" and "Default" and..
            b) styles "Normal" and "Default" in a single document, where
            we can not use the original names, and must come up with an
            alternative name for one of them..

            And it needs to report to the importer if the style being mapped to
            was already in existance, for the cut and paste/insert file mode we
            should not modify the returned style if it is already in use as it
            is does not belong to us to change.

            @author
                Caolán McNamara
        */
        class ParaStyleMapper
        {
        private:
            //I hate these things stupid pImpl things, but its warranted here
            ParaMapper *mpImpl;
        public:
            ParaStyleMapper(SwDoc &rDoc);
            ~ParaStyleMapper();

            /** StyleResult
                StyleResult is a std::pair of a pointer to a style and a flag
                which is true if the style existed previously in the document.
            */
            typedef std::pair<SwTxtFmtColl*, bool> StyleResult;

            /** Get the writer style which the word style should map to

                @param rName
                The name of the word style

                @param eSti
                The style id of the word style, we are really only interested
                in knowing if the style has either a builtin standard id, or is
                a user defined style.

                @return
                The equivalent writer style packaged as a StyleResult to use
                for this word style.

                It will only return a failure in the pathological case of
                catastropic failure elsewhere of there exist already styles
                rName and WW-rName[0..SAL_MAX_INT32], which is both unlikely
                and impossible.
            */
            StyleResult GetStyle(const String& rName, ww::sti eSti);
        };

        /** Knows which writer style a given word style should be imported as

            Mapping a word style to a writer style has to consider mapping
            the word builtin styles like "Normal" as the default root style
            to our default root style which is called "Default" in english,
            and "Normal" in german.

            Additionally it then has to avoid name collisions such as

            a) styles "Normal" and "Default" in a single document, where
            we can use the original distinct names "Normal" and "Default" and..
            b) styles "Normal" and "Default" in a single document, where
            we can not use the original names, and must come up with an
            alternative name for one of them..

            And it needs to report to the importer if the style being mapped to
            was already in existance, for the cut and paste/insert file mode we
            should not modify the returned style if it is already in use as it
            is does not belong to us to change.

            @author
                Caolán McNamara
        */
        class CharStyleMapper
        {
        private:
            //I hate these things stupid pImpl things, but its warranted here
            CharMapper *mpImpl;
        public:
            CharStyleMapper(SwDoc &rDoc);
            ~CharStyleMapper();

            /** StyleResult
                StyleResult is a std::pair of a pointer to a style and a flag
                which is true if the style existed previously in the document.
            */
            typedef std::pair<SwCharFmt*, bool> StyleResult;

            /** Get the writer style which the word style should map to

                @param rName
                The name of the word style

                @param eSti
                The style id of the word style, we are really only interested
                in knowing if the style has either a builtin standard id, or is
                a user defined style.

                @return
                The equivalent writer style packaged as a StyleResult to use
                for this word style.

                It will only return a failure in the pathological case of
                catastropic failure elsewhere of there exist already styles
                rName and WW-rName[0..SAL_MAX_INT32], which is both unlikely
                and impossible.
            */
            StyleResult GetStyle(const String& rName, ww::sti eSti);
        };

        /** Given a SwNoTxtNode (ole/graphic) get original size

            Get the uncropped and unscaled size of the underlying graphic or
            ole object associated with a given SwNoTxtNode.

            This function will swap in the graphic if it is swapped out from
            the graphic or object cache, but will swap it out if that was the
            case, i.e.  rNd is logically unchanged before and after
            GetSwappedInSize, though not physically const

            @param rNd
                the SwNoTxtNode whose objects original size we want

            @return
                the uncropped unscaled size of the SwNoTxtNode

            @author
                Caolán McNamara
        */
        Size GetSwappedInSize(const SwNoTxtNode& rNd);

        struct CharRunEntry
        {
            xub_StrLen mnEndPos;
            sal_uInt16 mnScript;
            rtl_TextEncoding meCharSet;
            bool mbRTL;
            CharRunEntry(xub_StrLen nEndPos, sal_uInt16 nScript,
                rtl_TextEncoding eCharSet, bool bRTL)
            : mnEndPos(nEndPos), mnScript(nScript), meCharSet(eCharSet),
            mbRTL(bRTL)
            {
            }
        };

        typedef std::vector<CharRunEntry> CharRuns;
        typedef CharRuns::const_iterator cCharRunIter;

        /** Collect the ranges of Text which share

            Word generally requires characters which share the same direction,
            the same script, and occasionally (depending on the format) the
            same charset to be exported in independant chunks.

            So this function finds these ranges and returns a STL container
            of CharRuns

            @param rTxtNd
                The TextNode we want to ranges from

            @param nStart
                The position in the TxtNode to start processing from

            @param bSplitOnCharSet
                Set to true is we want to split on ranges of characters that
                share a plausible charset for export to e.g. WW7- or perhaps
                RTF format, not necessary for a unicode aware format like WW8+

            @return STL container of CharRuns which describe the shared
            direction, script and optionally script of the contigious sequences
            of characters

            @author
            Caolán McNamara

            @see #i22537# for example
        */
        CharRuns GetPseudoCharRuns(const SwTxtNode& rTxtNd,
            xub_StrLen nStart = 0, bool bSplitOnCharSet = false);
    }
}

#endif
/* vi:set tabstop=4 shiftwidth=4 expandtab: */
<commit_msg>INTEGRATION: CWS westportfilterteam26 (1.5.36); FILE MERGED 2004/03/02 11:23:46 mmaher 1.5.36.3: RESYNC: (1.5-1.6); FILE MERGED 2004/03/01 12:19:53 cmc 1.5.36.2: #i25782# merge ww8 and rtf special handling for forcing table reformatting in the insert->file mode, fixes out of order table insertion for #i25782# 2004/02/17 11:46:53 cmc 1.5.36.1: #i19164# merge much of the fontsubstitution lookup code for ww8 and rtf export<commit_after>/*************************************************************************
 *
 *  $RCSfile: msfilter.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2004-04-27 14:08:01 $
 *
 *  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): cmc@openoffice.org
 *
 *
 ************************************************************************/

/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- */
/// @HTML

#ifndef SW_MS_MSFILTER_HXX
#define SW_MS_MSFILTER_HXX

#include <set>
#include <map>
#include <vector>

#ifndef _SWTYPES_HXX
#   include <swtypes.hxx>       //SwTwips
#endif
#ifndef _STRING_HXX
#   include <tools/string.hxx>  //String
#endif
#ifndef WW_WWSTYLES_HXX
#   include "wwstyles.hxx"      //ww::sti
#endif
#ifndef _RTL_TEXTENC_H
#   include <rtl/textenc.h>     //rtl_TextEncoding
#endif
#ifndef _SV_GEN_HXX
#   include <tools/gen.hxx>     //Size
#endif

class SwDoc;
class SwPaM;
class String;
class SwTableNode;
class SwNodeIndex;
class SwNoTxtNode;
class SwTxtNode;

namespace
{
    template<class C> class StyleMapperImpl;
}
class SwTxtFmtColl;
class SwCharFmt;
typedef StyleMapperImpl<SwTxtFmtColl> ParaMapper;
typedef StyleMapperImpl<SwCharFmt> CharMapper;

namespace sw
{
    namespace ms
    {
        /** MSOffice appears to set the charset of unicode fonts to MS 932

            Arial Unicode MS for example is a unicode font, but word sets
            exported uses of it to the MS 932 charset

            @param eTextEncoding
                the OOo encoding to convert from

            @return
                a msoffice equivalent charset identifier

            @author
                Caolán McNamara
        */
        sal_uInt8 rtl_TextEncodingToWinCharset(rtl_TextEncoding eTextEncoding);

        /** Get the OOo rtl_TextEncoding equivalent to the closest
            textencoding word will be using

            Some of the eTextEncodings in writer will map to an encoding in
            word which does not map back to the same encoding, so get the
            encoding it would map back to

            @param eTextEncoding
                the OOo encoding to convert from

            @return
                the writer equivalent charset identifier

            @author
                Caolán McNamara
        */
        rtl_TextEncoding rtl_TextEncodingToWinCharsetAndBack(
            rtl_TextEncoding eTextEncoding);

        /** Import a MSWord XE field. Suitable for .doc and .rtf

            @param rDoc
                the document to insert into

            @param rPaM
                the position in the document to insert into

            @param rXE
                the arguments of the original word XE field

            @author
                Caolán McNamara
        */
        void ImportXE(SwDoc &rDoc, SwPaM &rPaM, const String &rXE);
    }

    namespace util
    {

        /** Clips a value to MAX/MIN 16bit value to make it safe for use
            as a position value to give to writer. i.e. +-57.8cm. Sometimes
            we see ridiculous values for positioning in rtf and word document,
            this captures such ones and clips them to values which are
            still outside the document, but of a value that doesn't cause
            problems for writer's layout, e.g. see
            http://www.openoffice.org/issues/show_bug.cgi?id=i9245

            @param nIn

            @return nIn clipped to min/max 16bit value

            @author
                Caolán McNamara
        */
        SwTwips MakeSafePositioningValue(SwTwips nIn);

        /** Knows which writer style a given word style should be imported as

            Mapping a word style to a writer style has to consider mapping
            the word builtin styles like "Normal" as the default root style
            to our default root style which is called "Default" in english,
            and "Normal" in german.

            Additionally it then has to avoid name collisions such as

            a) styles "Normal" and "Default" in a single document, where
            we can use the original distinct names "Normal" and "Default" and..
            b) styles "Normal" and "Default" in a single document, where
            we can not use the original names, and must come up with an
            alternative name for one of them..

            And it needs to report to the importer if the style being mapped to
            was already in existance, for the cut and paste/insert file mode we
            should not modify the returned style if it is already in use as it
            is does not belong to us to change.

            @author
                Caolán McNamara
        */
        class ParaStyleMapper
        {
        private:
            //I hate these things stupid pImpl things, but its warranted here
            ParaMapper *mpImpl;
        public:
            ParaStyleMapper(SwDoc &rDoc);
            ~ParaStyleMapper();

            /** StyleResult
                StyleResult is a std::pair of a pointer to a style and a flag
                which is true if the style existed previously in the document.
            */
            typedef std::pair<SwTxtFmtColl*, bool> StyleResult;

            /** Get the writer style which the word style should map to

                @param rName
                The name of the word style

                @param eSti
                The style id of the word style, we are really only interested
                in knowing if the style has either a builtin standard id, or is
                a user defined style.

                @return
                The equivalent writer style packaged as a StyleResult to use
                for this word style.

                It will only return a failure in the pathological case of
                catastropic failure elsewhere of there exist already styles
                rName and WW-rName[0..SAL_MAX_INT32], which is both unlikely
                and impossible.
            */
            StyleResult GetStyle(const String& rName, ww::sti eSti);
        };

        /** Knows which writer style a given word style should be imported as

            Mapping a word style to a writer style has to consider mapping
            the word builtin styles like "Normal" as the default root style
            to our default root style which is called "Default" in english,
            and "Normal" in german.

            Additionally it then has to avoid name collisions such as

            a) styles "Normal" and "Default" in a single document, where
            we can use the original distinct names "Normal" and "Default" and..
            b) styles "Normal" and "Default" in a single document, where
            we can not use the original names, and must come up with an
            alternative name for one of them..

            And it needs to report to the importer if the style being mapped to
            was already in existance, for the cut and paste/insert file mode we
            should not modify the returned style if it is already in use as it
            is does not belong to us to change.

            @author
                Caolán McNamara
        */
        class CharStyleMapper
        {
        private:
            //I hate these things stupid pImpl things, but its warranted here
            CharMapper *mpImpl;
        public:
            CharStyleMapper(SwDoc &rDoc);
            ~CharStyleMapper();

            /** StyleResult
                StyleResult is a std::pair of a pointer to a style and a flag
                which is true if the style existed previously in the document.
            */
            typedef std::pair<SwCharFmt*, bool> StyleResult;

            /** Get the writer style which the word style should map to

                @param rName
                The name of the word style

                @param eSti
                The style id of the word style, we are really only interested
                in knowing if the style has either a builtin standard id, or is
                a user defined style.

                @return
                The equivalent writer style packaged as a StyleResult to use
                for this word style.

                It will only return a failure in the pathological case of
                catastropic failure elsewhere of there exist already styles
                rName and WW-rName[0..SAL_MAX_INT32], which is both unlikely
                and impossible.
            */
            StyleResult GetStyle(const String& rName, ww::sti eSti);
        };

        /** Find suitable names for exporting this font

            Given a fontname description find the best primary and secondary
            fallback font to use from MSWord's persp font

            @author
            Caolán McNamara

            @see #i10242#/#i19164# for examples
        */
        class FontMapExport
        {
        public:
            String msPrimary;
            String msSecondary;
            bool HasDistinctSecondary() const;
            FontMapExport(const String &rFontDescription);
        };

        /** Handle requirements for table formatting in insert->file mode.

            When inserting a table into a document which already has been
            formatted and laid out (e.g using insert->file) then tables
            must be handled in a special way, (or so previous comments and
            code in the filters leads me to believe).

            Before the document is finalized the new tables need to have
            their layout frms deleted and recalculated. This TableManager
            detects the necessity to do this, and all tables inserted into
            a document should be registered with this manager with
            InsertTable, and before finialization DelAndMakeTblFrms should
            be called.

            @author
            Caolán McNamara

            @see #i25782# for examples
        */
        class InsertedTablesManager
        {
        public:
            typedef std::map<SwTableNode *, SwNodeIndex *> TblMap;
            typedef TblMap::iterator TblMapIter;
            void DelAndMakeTblFrms();
            void InsertTable(SwTableNode &rTableNode, SwPaM &rPaM);
            InsertedTablesManager(const SwDoc &rDoc);
        private:
            bool mbHasRoot;
            TblMap maTables;
        };

        /** Given a SwNoTxtNode (ole/graphic) get original size

            Get the uncropped and unscaled size of the underlying graphic or
            ole object associated with a given SwNoTxtNode.

            This function will swap in the graphic if it is swapped out from
            the graphic or object cache, but will swap it out if that was the
            case, i.e.  rNd is logically unchanged before and after
            GetSwappedInSize, though not physically const

            @param rNd
                the SwNoTxtNode whose objects original size we want

            @return
                the uncropped unscaled size of the SwNoTxtNode

            @author
                Caolán McNamara
        */
        Size GetSwappedInSize(const SwNoTxtNode& rNd);

        struct CharRunEntry
        {
            xub_StrLen mnEndPos;
            sal_uInt16 mnScript;
            rtl_TextEncoding meCharSet;
            bool mbRTL;
            CharRunEntry(xub_StrLen nEndPos, sal_uInt16 nScript,
                rtl_TextEncoding eCharSet, bool bRTL)
            : mnEndPos(nEndPos), mnScript(nScript), meCharSet(eCharSet),
            mbRTL(bRTL)
            {
            }
        };

        typedef std::vector<CharRunEntry> CharRuns;
        typedef CharRuns::const_iterator cCharRunIter;

        /** Collect the ranges of Text which share

            Word generally requires characters which share the same direction,
            the same script, and occasionally (depending on the format) the
            same charset to be exported in independant chunks.

            So this function finds these ranges and returns a STL container
            of CharRuns

            @param rTxtNd
                The TextNode we want to ranges from

            @param nStart
                The position in the TxtNode to start processing from

            @param bSplitOnCharSet
                Set to true is we want to split on ranges of characters that
                share a plausible charset for export to e.g. WW7- or perhaps
                RTF format, not necessary for a unicode aware format like WW8+

            @return STL container of CharRuns which describe the shared
            direction, script and optionally script of the contigious sequences
            of characters

            @author
            Caolán McNamara

            @see #i22537# for example
        */
        CharRuns GetPseudoCharRuns(const SwTxtNode& rTxtNd,
            xub_StrLen nStart = 0, bool bSplitOnCharSet = false);
    }
}

#endif
/* vi:set tabstop=4 shiftwidth=4 expandtab: */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: wrtswtbl.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: cmc $ $Date: 2002-04-24 10:16:29 $
 *
 *  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  _WRTSWTBL_HXX
#define  _WRTSWTBL_HXX

#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif
#ifndef _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif

#ifndef _ORNTENUM_HXX
#include <orntenum.hxx>
#endif
#ifndef _HORIORNT_HXX
#include <horiornt.hxx>
#endif

class Color;
class SwTableBox;
class SwTableBoxes;
class SwTableLine;
class SwTableLines;
class SwTable;
class SwFrmFmt;
class SwHTMLTableLayout;
class SvxBrushItem;
class SvxBoxItem;
class SvxBorderLine;

//---------------------------------------------------------------------------
//       Code aus dem HTML-Filter fuers schreiben von Tabellen
//---------------------------------------------------------------------------

#define COLFUZZY 20
#define ROWFUZZY 20
#define COL_DFLT_WIDTH ((2*COLFUZZY)+1)
#define ROW_DFLT_HEIGHT (2*ROWFUZZY)+1

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

class SwWriteTableCell
{
    const SwTableBox *pBox;     // SwTableBox der Zelle
    const SvxBrushItem *pBackground;    // geerbter Hintergrund einer Zeile

    long nHeight;               // fixe/Mindest-Hoehe der Zeile

    USHORT nWidthOpt;           // Breite aus Option;

    USHORT nRow;                // Start-Zeile
    USHORT nCol;                // Start-Spalte

    USHORT nRowSpan;            // ueberspannte Zeilen
    USHORT nColSpan;            // ueberspannte Spalten

    BOOL bPrcWidthOpt;

public:

    SwWriteTableCell( const SwTableBox *pB, USHORT nR, USHORT nC,
                        USHORT nRSpan, USHORT nCSpan, long nHght,
                        const SvxBrushItem *pBGround ) :
        pBox( pB ),
        nRow( nR ), nCol( nC ),
        nRowSpan( nRSpan ), nColSpan( nCSpan ),
        nHeight( nHght ), pBackground( pBGround ),
        nWidthOpt( 0 ), bPrcWidthOpt( FALSE )
    {}

    const SwTableBox *GetBox() const { return pBox; }

    USHORT GetRow() const { return nRow; }
    USHORT GetCol() const { return nCol; }

    USHORT GetRowSpan() const { return nRowSpan; }
    USHORT GetColSpan() const { return nColSpan; }

    long GetHeight() const { return nHeight; }
    SwVertOrient GetVertOri() const;

    const SvxBrushItem *GetBackground() const { return pBackground; }

    void SetWidthOpt( USHORT nWidth, BOOL bPrc )
    {
        nWidthOpt = nWidth; bPrcWidthOpt = bPrc;
    }

    USHORT GetWidthOpt() const { return nWidthOpt; }
    BOOL HasPrcWidthOpt() const { return bPrcWidthOpt; }
};

typedef SwWriteTableCell *SwWriteTableCellPtr;
SV_DECL_PTRARR_DEL( SwWriteTableCells, SwWriteTableCellPtr, 5, 5 )

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

class SwWriteTableRow
{
    SwWriteTableCells aCells;       // Alle Zellen der Rows
    const SvxBrushItem *pBackground;// Hintergrund

    long nPos;                  // End-Position (twips) der Zeile
    BOOL mbUseLayoutHeights;
public:

    USHORT nTopBorder;              // Dicke der oberen/unteren Umrandugen
    USHORT nBottomBorder;

    BOOL bTopBorder : 1;            // Welche Umrandungen sind da?
    BOOL bBottomBorder : 1;

    SwWriteTableRow( long nPos, BOOL bUseLayoutHeights );

    SwWriteTableCell *AddCell( const SwTableBox *pBox,
                                 USHORT nRow, USHORT nCol,
                                 USHORT nRowSpan, USHORT nColSpan,
                                 long nHeight,
                                 const SvxBrushItem *pBackground );

    void SetBackground( const SvxBrushItem *pBGround )
    {
        pBackground = pBGround;
    }
    const SvxBrushItem *GetBackground() const { return pBackground; }

    BOOL HasTopBorder() const                   { return bTopBorder; }
    BOOL HasBottomBorder() const                { return bBottomBorder; }

    long GetPos() const                         { return nPos; }
    const SwWriteTableCells& GetCells() const   { return aCells; }

    inline int operator==( const SwWriteTableRow& rRow ) const;
    inline int operator<( const SwWriteTableRow& rRow2 ) const;
};

inline int SwWriteTableRow::operator==( const SwWriteTableRow& rRow ) const
{
    // etwas Unschaerfe zulassen
    return (nPos >= rRow.nPos ?  nPos - rRow.nPos : rRow.nPos - nPos ) <=
        (mbUseLayoutHeights ? 0 : ROWFUZZY);
}

inline int SwWriteTableRow::operator<( const SwWriteTableRow& rRow ) const
{
    // Da wir hier nur die Wahrheits-Grade 0 und 1 kennen, lassen wir lieber
    // auch nicht zu, dass x==y und x<y gleichzeitig gilt ;-)
    return nPos < rRow.nPos - (mbUseLayoutHeights ? 0 : ROWFUZZY);
}

typedef SwWriteTableRow *SwWriteTableRowPtr;
SV_DECL_PTRARR_SORT_DEL( SwWriteTableRows, SwWriteTableRowPtr, 5, 5 )

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

class SwWriteTableCol
{
    USHORT nPos;                        // End Position der Spalte

    USHORT nWidthOpt;

    BOOL bRelWidthOpt : 1;
    BOOL bOutWidth : 1;                 // Spaltenbreite ausgeben?

public:
    BOOL bLeftBorder : 1;               // Welche Umrandungen sind da?
    BOOL bRightBorder : 1;

    SwWriteTableCol( USHORT nPosition );

    USHORT GetPos() const                       { return nPos; }

    void SetLeftBorder( BOOL bBorder )          { bLeftBorder = bBorder; }
    BOOL HasLeftBorder() const                  { return bLeftBorder; }

    void SetRightBorder( BOOL bBorder )         { bRightBorder = bBorder; }
    BOOL HasRightBorder() const                 { return bRightBorder; }

    void SetOutWidth( BOOL bSet )               { bOutWidth = bSet; }
    BOOL GetOutWidth() const                    { return bOutWidth; }

    inline int operator==( const SwWriteTableCol& rCol ) const;
    inline int operator<( const SwWriteTableCol& rCol ) const;

    void SetWidthOpt( USHORT nWidth, BOOL bRel )
    {
        nWidthOpt = nWidth; bRelWidthOpt = bRel;
    }
    USHORT GetWidthOpt() const                  { return nWidthOpt; }
    BOOL HasRelWidthOpt() const                 { return bRelWidthOpt; }
};

inline int SwWriteTableCol::operator==( const SwWriteTableCol& rCol ) const
{
    // etwas Unschaerfe zulassen
    return (nPos >= rCol.nPos ? nPos - rCol.nPos
                                     : rCol.nPos - nPos ) <= COLFUZZY;
}

inline int SwWriteTableCol::operator<( const SwWriteTableCol& rCol ) const
{
    // Da wir hier nur die Wahrheits-Grade 0 und 1 kennen, lassen wir lieber
    // auch nicht zu, dass x==y und x<y gleichzeitig gilt ;-)
    return nPos < rCol.nPos - COLFUZZY;
}

typedef SwWriteTableCol *SwWriteTableColPtr;
SV_DECL_PTRARR_SORT_DEL( SwWriteTableCols, SwWriteTableColPtr, 5, 5 )

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

class SwWriteTable
{
protected:
    SwWriteTableCols aCols; // alle Spalten
    SwWriteTableRows aRows; // alle Zellen

    UINT32 nBorderColor;        // Umrandungsfarbe

    USHORT nCellSpacing;        // Dicke der inneren Umrandung
    USHORT nCellPadding;        // Absatnd Umrandung-Inhalt

    USHORT nBorder;             // Dicke der ausseren Umrandung
    USHORT nInnerBorder;        // Dicke der inneren Umrandung
    USHORT nBaseWidth;          // Bezugsgroesse fur Breiten SwFmtFrmSize

    USHORT nHeadEndRow;         // letzte Zeile des Tabellen-Kopfes

    USHORT nLeftSub;
    USHORT nRightSub;

    long nTabWidth;             // Absolute/Relative Breite der Tabelle

    BOOL bRelWidths : 1;        // Breiten relativ ausgeben?
    BOOL bUseLayoutHeights : 1; // Layout zur Hoehenbestimmung nehmen?
#ifndef PRODUCT
    BOOL bGetLineHeightCalled : 1;
#endif

    BOOL bColsOption : 1;
    BOOL bColTags : 1;
    BOOL bLayoutExport : 1;
    BOOL bCollectBorderWidth : 1;

    virtual BOOL ShouldExpandSub( const SwTableBox *pBox,
                                BOOL bExpandedBefore, USHORT nDepth ) const;

    void CollectTableRowsCols( long nStartRPos, USHORT nStartCPos,
                               long nParentLineHeight,
                               USHORT nParentLineWidth,
                               const SwTableLines& rLines,
                               USHORT nDepth );

    void FillTableRowsCols( long nStartRPos, USHORT nStartRow,
                            USHORT nStartCPos, USHORT nStartCol,
                            long nParentLineHeight,
                            USHORT nParentLineWidth,
                            const SwTableLines& rLines,
                            const SvxBrushItem* pLineBrush,
                            USHORT nDepth );

    void MergeBorders( const SvxBorderLine* pBorderLine, BOOL bTable );

    USHORT MergeBoxBorders( const SwTableBox *pBox, USHORT nRow, USHORT nCol,
                            USHORT nRowSpan, USHORT nColSpan,
                            USHORT &rTopBorder, USHORT &rBottomBorder );

    USHORT GetBaseWidth() const { return nBaseWidth; }

    BOOL HasRelWidths() const { return bRelWidths; }

public:
    static long GetBoxWidth( const SwTableBox *pBox );
protected:

    long GetLineHeight( const SwTableLine *pLine );
    long GetLineHeight( const SwTableBox *pBox ) const;
    const SvxBrushItem *GetLineBrush( const SwTableBox *pBox,
                                      SwWriteTableRow *pRow );

    USHORT GetLeftSpace( USHORT nCol ) const;
    USHORT GetRightSpace( USHORT nCol, USHORT nColSpan ) const;

    USHORT GetRawWidth( USHORT nCol, USHORT nColSpan ) const;
    USHORT GetAbsWidth( USHORT nCol, USHORT nColSpan ) const;
    USHORT GetRelWidth( USHORT nCol, USHORT nColSpan ) const;
    USHORT GetPrcWidth( USHORT nCol, USHORT nColSpan ) const;

    long GetAbsHeight( long nRawWidth, USHORT nRow, USHORT nRowSpan ) const;

public:
    SwWriteTable( const SwTableLines& rLines, long nWidth, USHORT nBWidth,
                    BOOL bRel, USHORT nMaxDepth = USHRT_MAX,
                    USHORT nLeftSub=0, USHORT nRightSub=0 );
    SwWriteTable( const SwHTMLTableLayout *pLayoutInfo );

    const SwWriteTableCols& GetCols() const { return aCols; }
    const SwWriteTableRows& GetRows() const { return aRows; }
};

#endif

<commit_msg>#i9055# match decl order to member init order<commit_after>/*************************************************************************
 *
 *  $RCSfile: wrtswtbl.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: cmc $ $Date: 2002-11-18 15:17:35 $
 *
 *  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  _WRTSWTBL_HXX
#define  _WRTSWTBL_HXX

#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif
#ifndef _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif

#ifndef _ORNTENUM_HXX
#include <orntenum.hxx>
#endif
#ifndef _HORIORNT_HXX
#include <horiornt.hxx>
#endif

class Color;
class SwTableBox;
class SwTableBoxes;
class SwTableLine;
class SwTableLines;
class SwTable;
class SwFrmFmt;
class SwHTMLTableLayout;
class SvxBrushItem;
class SvxBoxItem;
class SvxBorderLine;

//---------------------------------------------------------------------------
//       Code aus dem HTML-Filter fuers schreiben von Tabellen
//---------------------------------------------------------------------------

#define COLFUZZY 20
#define ROWFUZZY 20
#define COL_DFLT_WIDTH ((2*COLFUZZY)+1)
#define ROW_DFLT_HEIGHT (2*ROWFUZZY)+1

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

class SwWriteTableCell
{
    const SwTableBox *pBox;     // SwTableBox der Zelle
    const SvxBrushItem *pBackground;    // geerbter Hintergrund einer Zeile

    long nHeight;               // fixe/Mindest-Hoehe der Zeile

    USHORT nWidthOpt;           // Breite aus Option;

    USHORT nRow;                // Start-Zeile
    USHORT nCol;                // Start-Spalte

    USHORT nRowSpan;            // ueberspannte Zeilen
    USHORT nColSpan;            // ueberspannte Spalten

    BOOL bPrcWidthOpt;

public:

    SwWriteTableCell(const SwTableBox *pB, USHORT nR, USHORT nC, USHORT nRSpan,
        USHORT nCSpan, long nHght, const SvxBrushItem *pBGround)
    : pBox( pB ), pBackground( pBGround ), nHeight( nHght ), nWidthOpt( 0 ),
    nRow( nR ), nCol( nC ), nRowSpan( nRSpan ), nColSpan( nCSpan ),
    bPrcWidthOpt( FALSE )
    {}

    const SwTableBox *GetBox() const { return pBox; }

    USHORT GetRow() const { return nRow; }
    USHORT GetCol() const { return nCol; }

    USHORT GetRowSpan() const { return nRowSpan; }
    USHORT GetColSpan() const { return nColSpan; }

    long GetHeight() const { return nHeight; }
    SwVertOrient GetVertOri() const;

    const SvxBrushItem *GetBackground() const { return pBackground; }

    void SetWidthOpt( USHORT nWidth, BOOL bPrc )
    {
        nWidthOpt = nWidth; bPrcWidthOpt = bPrc;
    }

    USHORT GetWidthOpt() const { return nWidthOpt; }
    BOOL HasPrcWidthOpt() const { return bPrcWidthOpt; }
};

typedef SwWriteTableCell *SwWriteTableCellPtr;
SV_DECL_PTRARR_DEL( SwWriteTableCells, SwWriteTableCellPtr, 5, 5 )

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

class SwWriteTableRow
{
    SwWriteTableCells aCells;       // Alle Zellen der Rows
    const SvxBrushItem *pBackground;// Hintergrund

    long nPos;                  // End-Position (twips) der Zeile
    BOOL mbUseLayoutHeights;
public:

    USHORT nTopBorder;              // Dicke der oberen/unteren Umrandugen
    USHORT nBottomBorder;

    BOOL bTopBorder : 1;            // Welche Umrandungen sind da?
    BOOL bBottomBorder : 1;

    SwWriteTableRow( long nPos, BOOL bUseLayoutHeights );

    SwWriteTableCell *AddCell( const SwTableBox *pBox,
                                 USHORT nRow, USHORT nCol,
                                 USHORT nRowSpan, USHORT nColSpan,
                                 long nHeight,
                                 const SvxBrushItem *pBackground );

    void SetBackground( const SvxBrushItem *pBGround )
    {
        pBackground = pBGround;
    }
    const SvxBrushItem *GetBackground() const { return pBackground; }

    BOOL HasTopBorder() const                   { return bTopBorder; }
    BOOL HasBottomBorder() const                { return bBottomBorder; }

    long GetPos() const                         { return nPos; }
    const SwWriteTableCells& GetCells() const   { return aCells; }

    inline int operator==( const SwWriteTableRow& rRow ) const;
    inline int operator<( const SwWriteTableRow& rRow2 ) const;
};

inline int SwWriteTableRow::operator==( const SwWriteTableRow& rRow ) const
{
    // etwas Unschaerfe zulassen
    return (nPos >= rRow.nPos ?  nPos - rRow.nPos : rRow.nPos - nPos ) <=
        (mbUseLayoutHeights ? 0 : ROWFUZZY);
}

inline int SwWriteTableRow::operator<( const SwWriteTableRow& rRow ) const
{
    // Da wir hier nur die Wahrheits-Grade 0 und 1 kennen, lassen wir lieber
    // auch nicht zu, dass x==y und x<y gleichzeitig gilt ;-)
    return nPos < rRow.nPos - (mbUseLayoutHeights ? 0 : ROWFUZZY);
}

typedef SwWriteTableRow *SwWriteTableRowPtr;
SV_DECL_PTRARR_SORT_DEL( SwWriteTableRows, SwWriteTableRowPtr, 5, 5 )

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

class SwWriteTableCol
{
    USHORT nPos;                        // End Position der Spalte

    USHORT nWidthOpt;

    BOOL bRelWidthOpt : 1;
    BOOL bOutWidth : 1;                 // Spaltenbreite ausgeben?

public:
    BOOL bLeftBorder : 1;               // Welche Umrandungen sind da?
    BOOL bRightBorder : 1;

    SwWriteTableCol( USHORT nPosition );

    USHORT GetPos() const                       { return nPos; }

    void SetLeftBorder( BOOL bBorder )          { bLeftBorder = bBorder; }
    BOOL HasLeftBorder() const                  { return bLeftBorder; }

    void SetRightBorder( BOOL bBorder )         { bRightBorder = bBorder; }
    BOOL HasRightBorder() const                 { return bRightBorder; }

    void SetOutWidth( BOOL bSet )               { bOutWidth = bSet; }
    BOOL GetOutWidth() const                    { return bOutWidth; }

    inline int operator==( const SwWriteTableCol& rCol ) const;
    inline int operator<( const SwWriteTableCol& rCol ) const;

    void SetWidthOpt( USHORT nWidth, BOOL bRel )
    {
        nWidthOpt = nWidth; bRelWidthOpt = bRel;
    }
    USHORT GetWidthOpt() const                  { return nWidthOpt; }
    BOOL HasRelWidthOpt() const                 { return bRelWidthOpt; }
};

inline int SwWriteTableCol::operator==( const SwWriteTableCol& rCol ) const
{
    // etwas Unschaerfe zulassen
    return (nPos >= rCol.nPos ? nPos - rCol.nPos
                                     : rCol.nPos - nPos ) <= COLFUZZY;
}

inline int SwWriteTableCol::operator<( const SwWriteTableCol& rCol ) const
{
    // Da wir hier nur die Wahrheits-Grade 0 und 1 kennen, lassen wir lieber
    // auch nicht zu, dass x==y und x<y gleichzeitig gilt ;-)
    return nPos < rCol.nPos - COLFUZZY;
}

typedef SwWriteTableCol *SwWriteTableColPtr;
SV_DECL_PTRARR_SORT_DEL( SwWriteTableCols, SwWriteTableColPtr, 5, 5 )

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

class SwWriteTable
{
protected:
    SwWriteTableCols aCols; // alle Spalten
    SwWriteTableRows aRows; // alle Zellen

    UINT32 nBorderColor;        // Umrandungsfarbe

    USHORT nCellSpacing;        // Dicke der inneren Umrandung
    USHORT nCellPadding;        // Absatnd Umrandung-Inhalt

    USHORT nBorder;             // Dicke der ausseren Umrandung
    USHORT nInnerBorder;        // Dicke der inneren Umrandung
    USHORT nBaseWidth;          // Bezugsgroesse fur Breiten SwFmtFrmSize

    USHORT nHeadEndRow;         // letzte Zeile des Tabellen-Kopfes

    USHORT nLeftSub;
    USHORT nRightSub;

    long nTabWidth;             // Absolute/Relative Breite der Tabelle

    BOOL bRelWidths : 1;        // Breiten relativ ausgeben?
    BOOL bUseLayoutHeights : 1; // Layout zur Hoehenbestimmung nehmen?
#ifndef PRODUCT
    BOOL bGetLineHeightCalled : 1;
#endif

    BOOL bColsOption : 1;
    BOOL bColTags : 1;
    BOOL bLayoutExport : 1;
    BOOL bCollectBorderWidth : 1;

    virtual BOOL ShouldExpandSub( const SwTableBox *pBox,
                                BOOL bExpandedBefore, USHORT nDepth ) const;

    void CollectTableRowsCols( long nStartRPos, USHORT nStartCPos,
                               long nParentLineHeight,
                               USHORT nParentLineWidth,
                               const SwTableLines& rLines,
                               USHORT nDepth );

    void FillTableRowsCols( long nStartRPos, USHORT nStartRow,
                            USHORT nStartCPos, USHORT nStartCol,
                            long nParentLineHeight,
                            USHORT nParentLineWidth,
                            const SwTableLines& rLines,
                            const SvxBrushItem* pLineBrush,
                            USHORT nDepth );

    void MergeBorders( const SvxBorderLine* pBorderLine, BOOL bTable );

    USHORT MergeBoxBorders( const SwTableBox *pBox, USHORT nRow, USHORT nCol,
                            USHORT nRowSpan, USHORT nColSpan,
                            USHORT &rTopBorder, USHORT &rBottomBorder );

    USHORT GetBaseWidth() const { return nBaseWidth; }

    BOOL HasRelWidths() const { return bRelWidths; }

public:
    static long GetBoxWidth( const SwTableBox *pBox );
protected:

    long GetLineHeight( const SwTableLine *pLine );
    long GetLineHeight( const SwTableBox *pBox ) const;
    const SvxBrushItem *GetLineBrush( const SwTableBox *pBox,
                                      SwWriteTableRow *pRow );

    USHORT GetLeftSpace( USHORT nCol ) const;
    USHORT GetRightSpace( USHORT nCol, USHORT nColSpan ) const;

    USHORT GetRawWidth( USHORT nCol, USHORT nColSpan ) const;
    USHORT GetAbsWidth( USHORT nCol, USHORT nColSpan ) const;
    USHORT GetRelWidth( USHORT nCol, USHORT nColSpan ) const;
    USHORT GetPrcWidth( USHORT nCol, USHORT nColSpan ) const;

    long GetAbsHeight( long nRawWidth, USHORT nRow, USHORT nRowSpan ) const;

public:
    SwWriteTable( const SwTableLines& rLines, long nWidth, USHORT nBWidth,
                    BOOL bRel, USHORT nMaxDepth = USHRT_MAX,
                    USHORT nLeftSub=0, USHORT nRightSub=0 );
    SwWriteTable( const SwHTMLTableLayout *pLayoutInfo );

    const SwWriteTableCols& GetCols() const { return aCols; }
    const SwWriteTableRows& GetRows() const { return aRows; }
};

#endif

<|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// A general interface for filtering and only acting on classes in Chromium C++
// code.

#include "ChromeClassTester.h"

#include <sys/param.h>

#include "clang/Basic/FileManager.h"

using namespace clang;

namespace {

bool starts_with(const std::string& one, const std::string& two) {
  return one.compare(0, two.size(), two) == 0;
}

bool ends_with(const std::string& one, const std::string& two) {
  if (two.size() > one.size())
    return false;

  return one.compare(one.size() - two.size(), two.size(), two) == 0;
}

}  // namespace

ChromeClassTester::ChromeClassTester(CompilerInstance& instance)
    : instance_(instance),
      diagnostic_(instance.getDiagnostics()) {
  FigureOutSrcRoot();
  BuildBannedLists();
}

void ChromeClassTester::FigureOutSrcRoot() {
  char c_cwd[MAXPATHLEN];
  if (getcwd(c_cwd, MAXPATHLEN) > 0) {
    size_t pos = 1;
    std::string cwd = c_cwd;

    // Add a trailing '/' because the search below requires it.
    if (cwd[cwd.size() - 1] != '/')
      cwd += '/';

    // Search the directory tree downwards until we find a path that contains
    // "build/common.gypi" and assume that that is our srcroot.
    size_t next_slash = cwd.find('/', pos);
    while (next_slash != std::string::npos) {
      next_slash++;
      std::string candidate = cwd.substr(0, next_slash);

      if (ends_with(candidate, "src/")) {
        std::string common = candidate + "build/common.gypi";
        if (access(common.c_str(), F_OK) != -1) {
          src_root_ = candidate;
          break;
        }
      }

      pos = next_slash;
      next_slash = cwd.find('/', pos);
    }
  }

  if (src_root_.empty()) {
    unsigned id = diagnostic().getCustomDiagID(
        Diagnostic::Error,
        "WARNING: Can't figure out srcroot!\n");
    diagnostic().Report(id);
  }
}

void ChromeClassTester::BuildBannedLists() {
  banned_namespaces_.push_back("std");
  banned_namespaces_.push_back("__gnu_cxx");

  banned_directories_.push_back("third_party");
  banned_directories_.push_back("native_client");
  banned_directories_.push_back("breakpad");
  banned_directories_.push_back("courgette");
  banned_directories_.push_back("ppapi");
  banned_directories_.push_back("testing");
  banned_directories_.push_back("googleurl");
  banned_directories_.push_back("v8");
  banned_directories_.push_back("sdch");

  // Don't check autogenerated headers.
  banned_directories_.push_back("out");
  banned_directories_.push_back("llvm");
  banned_directories_.push_back("ninja");
  banned_directories_.push_back("xcodebuild");
  banned_directories_.push_back("clang");

  // You are standing in a mazy of twisty dependencies, all resolved by
  // putting everything in the header.
  banned_directories_.push_back("chrome/test/automation");

  // Don't check system headers.
  banned_directories_.push_back("/usr");
  banned_directories_.push_back("/Developer");

  // Used in really low level threading code that probably shouldn't be out of
  // lined.
  ignored_record_names_.insert("ThreadLocalBoolean");

  // A complicated pickle derived struct that is all packed integers.
  ignored_record_names_.insert("Header");

  // Part of the GPU system that uses multiple included header
  // weirdness. Never getting this right.
  ignored_record_names_.insert("Validators");

  // RAII class that's simple enough (media/base/callback.h).
  ignored_record_names_.insert("AutoCallbackRunner");

  // Has a UNIT_TEST only constructor. Isn't *terribly* complex...
  ignored_record_names_.insert("AutocompleteController");
  ignored_record_names_.insert("HistoryURLProvider");

  // Because of chrome frame
  ignored_record_names_.insert("ReliabilityTestSuite");

  // Used over in the net unittests. A large enough bundle of integers with 1
  // non-pod class member. Probably harmless.
  ignored_record_names_.insert("MockTransaction");

  // Used heavily in app_unittests and once in views_unittests. Fixing this
  // isn't worth the overhead of an additional library.
  ignored_record_names_.insert("TestAnimationDelegate");

  // Part of our public interface that nacl and friends use. (Arguably, this
  // should mean that this is a higher priority but fixing this looks hard.)
  ignored_record_names_.insert("PluginVersionInfo");
}

ChromeClassTester::~ChromeClassTester() {}

void ChromeClassTester::HandleTagDeclDefinition(TagDecl* tag) {
  // We handle class types here where we have semantic information. We can only
  // check structs/classes/enums here, but we get a bunch of nice semantic
  // information instead of just parsing information.

  if (CXXRecordDecl* record = dyn_cast<CXXRecordDecl>(tag)) {
    // If this is a POD or a class template or a type dependent on a
    // templated class, assume there's no ctor/dtor/virtual method
    // optimization that we can do.
    if (record->isPOD() ||
        record->getDescribedClassTemplate() ||
        record->getTemplateSpecializationKind() ||
        record->isDependentType())
      return;

    if (InBannedNamespace(record))
      return;

    SourceLocation record_location = record->getInnerLocStart();
    if (InBannedDirectory(record_location))
      return;

    // We sadly need to maintain a blacklist of types that violate these
    // rules, but do so for good reason or due to limitations of this
    // checker (i.e., we don't handle extern templates very well).
    std::string base_name = record->getNameAsString();
    if (IsIgnoredType(base_name))
      return;

    // We ignore all classes that end with "Matcher" because they're probably
    // GMock artifacts.
    if (ends_with(base_name, "Matcher"))
        return;

    CheckChromeClass(record_location, record);
  }
}

void ChromeClassTester::emitWarning(SourceLocation loc, const char* raw_error) {
  FullSourceLoc full(loc, instance().getSourceManager());
  std::string err;
  err = "[chromium-style] ";
  err += raw_error;
  Diagnostic::Level level =
      diagnostic().getWarningsAsErrors() ?
      Diagnostic::Error :
      Diagnostic::Warning;
  unsigned id = diagnostic().getCustomDiagID(level, err);
  DiagnosticBuilder B = diagnostic().Report(full, id);
}

bool ChromeClassTester::InTestingNamespace(Decl* record) {
  return GetNamespace(record).find("testing") != std::string::npos;
}

bool ChromeClassTester::InBannedNamespace(Decl* record) {
  std::string n = GetNamespace(record);
  if (n != "") {
    return std::find(banned_namespaces_.begin(), banned_namespaces_.end(), n)
        != banned_namespaces_.end();
  }

  return false;
}

std::string ChromeClassTester::GetNamespace(Decl* record) {
  return GetNamespaceImpl(record->getDeclContext(), "");
}

std::string ChromeClassTester::GetNamespaceImpl(const DeclContext* context,
                                                std::string candidate) {
  switch (context->getDeclKind()) {
    case Decl::TranslationUnit: {
      return candidate;
    }
    case Decl::Namespace: {
      const NamespaceDecl* decl = dyn_cast<NamespaceDecl>(context);
      std::string name_str;
      llvm::raw_string_ostream OS(name_str);
      if (decl->isAnonymousNamespace())
        OS << "<anonymous namespace>";
      else
        OS << decl;
      return GetNamespaceImpl(context->getParent(),
                              OS.str());
    }
    default: {
      return GetNamespaceImpl(context->getParent(), candidate);
    }
  }
}

bool ChromeClassTester::InBannedDirectory(SourceLocation loc) {
  const SourceManager &SM = instance_.getSourceManager();
  SourceLocation spelling_location = SM.getSpellingLoc(loc);
  PresumedLoc ploc = SM.getPresumedLoc(spelling_location);
  std::string buffer_name;
  if (ploc.isInvalid()) {
    // If we're in an invalid location, we're looking at things that aren't
    // actually stated in the source; treat this as a banned location instead
    // of going through our full lookup process.
    return true;
  } else {
    std::string b = ploc.getFilename();

    // We need to special case scratch space; which is where clang does its
    // macro expansion. We explicitly want to allow people to do otherwise bad
    // things through macros that were defined due to third party libraries.
    if (b == "<scratch space>")
      return true;

    // Don't complain about these things in implementation files.
    if (ends_with(b, ".cc") || ends_with(b, ".cpp") || ends_with(b, ".mm")) {
      return true;
    }

    // Don't complain about autogenerated protobuf files.
    if (ends_with(b, ".pb.h")) {
      return true;
    }

    // We need to munge the paths so that they are relative to the repository
    // srcroot. We first resolve the symlinktastic relative path and then
    // remove our known srcroot from it if needed.
    char resolvedPath[MAXPATHLEN];
    if (realpath(b.c_str(), resolvedPath)) {
      std::string resolved = resolvedPath;
      if (starts_with(resolved, src_root_)) {
        b = resolved.substr(src_root_.size());
      }
    }

    for (std::vector<std::string>::const_iterator it =
             banned_directories_.begin();
         it != banned_directories_.end(); ++it) {
      if (starts_with(b, *it)) {
        return true;
      }
    }
  }

  return false;
}

bool ChromeClassTester::IsIgnoredType(const std::string& base_name) {
  return ignored_record_names_.find(base_name) != ignored_record_names_.end();
}
<commit_msg>clang: Fix a comment pointing to app_unittests instead of ui_unittests.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// A general interface for filtering and only acting on classes in Chromium C++
// code.

#include "ChromeClassTester.h"

#include <sys/param.h>

#include "clang/Basic/FileManager.h"

using namespace clang;

namespace {

bool starts_with(const std::string& one, const std::string& two) {
  return one.compare(0, two.size(), two) == 0;
}

bool ends_with(const std::string& one, const std::string& two) {
  if (two.size() > one.size())
    return false;

  return one.compare(one.size() - two.size(), two.size(), two) == 0;
}

}  // namespace

ChromeClassTester::ChromeClassTester(CompilerInstance& instance)
    : instance_(instance),
      diagnostic_(instance.getDiagnostics()) {
  FigureOutSrcRoot();
  BuildBannedLists();
}

void ChromeClassTester::FigureOutSrcRoot() {
  char c_cwd[MAXPATHLEN];
  if (getcwd(c_cwd, MAXPATHLEN) > 0) {
    size_t pos = 1;
    std::string cwd = c_cwd;

    // Add a trailing '/' because the search below requires it.
    if (cwd[cwd.size() - 1] != '/')
      cwd += '/';

    // Search the directory tree downwards until we find a path that contains
    // "build/common.gypi" and assume that that is our srcroot.
    size_t next_slash = cwd.find('/', pos);
    while (next_slash != std::string::npos) {
      next_slash++;
      std::string candidate = cwd.substr(0, next_slash);

      if (ends_with(candidate, "src/")) {
        std::string common = candidate + "build/common.gypi";
        if (access(common.c_str(), F_OK) != -1) {
          src_root_ = candidate;
          break;
        }
      }

      pos = next_slash;
      next_slash = cwd.find('/', pos);
    }
  }

  if (src_root_.empty()) {
    unsigned id = diagnostic().getCustomDiagID(
        Diagnostic::Error,
        "WARNING: Can't figure out srcroot!\n");
    diagnostic().Report(id);
  }
}

void ChromeClassTester::BuildBannedLists() {
  banned_namespaces_.push_back("std");
  banned_namespaces_.push_back("__gnu_cxx");

  banned_directories_.push_back("third_party");
  banned_directories_.push_back("native_client");
  banned_directories_.push_back("breakpad");
  banned_directories_.push_back("courgette");
  banned_directories_.push_back("ppapi");
  banned_directories_.push_back("testing");
  banned_directories_.push_back("googleurl");
  banned_directories_.push_back("v8");
  banned_directories_.push_back("sdch");

  // Don't check autogenerated headers.
  banned_directories_.push_back("out");
  banned_directories_.push_back("llvm");
  banned_directories_.push_back("ninja");
  banned_directories_.push_back("xcodebuild");
  banned_directories_.push_back("clang");

  // You are standing in a mazy of twisty dependencies, all resolved by
  // putting everything in the header.
  banned_directories_.push_back("chrome/test/automation");

  // Don't check system headers.
  banned_directories_.push_back("/usr");
  banned_directories_.push_back("/Developer");

  // Used in really low level threading code that probably shouldn't be out of
  // lined.
  ignored_record_names_.insert("ThreadLocalBoolean");

  // A complicated pickle derived struct that is all packed integers.
  ignored_record_names_.insert("Header");

  // Part of the GPU system that uses multiple included header
  // weirdness. Never getting this right.
  ignored_record_names_.insert("Validators");

  // RAII class that's simple enough (media/base/callback.h).
  ignored_record_names_.insert("AutoCallbackRunner");

  // Has a UNIT_TEST only constructor. Isn't *terribly* complex...
  ignored_record_names_.insert("AutocompleteController");
  ignored_record_names_.insert("HistoryURLProvider");

  // Because of chrome frame
  ignored_record_names_.insert("ReliabilityTestSuite");

  // Used over in the net unittests. A large enough bundle of integers with 1
  // non-pod class member. Probably harmless.
  ignored_record_names_.insert("MockTransaction");

  // Used heavily in ui_unittests and once in views_unittests. Fixing this
  // isn't worth the overhead of an additional library.
  ignored_record_names_.insert("TestAnimationDelegate");

  // Part of our public interface that nacl and friends use. (Arguably, this
  // should mean that this is a higher priority but fixing this looks hard.)
  ignored_record_names_.insert("PluginVersionInfo");
}

ChromeClassTester::~ChromeClassTester() {}

void ChromeClassTester::HandleTagDeclDefinition(TagDecl* tag) {
  // We handle class types here where we have semantic information. We can only
  // check structs/classes/enums here, but we get a bunch of nice semantic
  // information instead of just parsing information.

  if (CXXRecordDecl* record = dyn_cast<CXXRecordDecl>(tag)) {
    // If this is a POD or a class template or a type dependent on a
    // templated class, assume there's no ctor/dtor/virtual method
    // optimization that we can do.
    if (record->isPOD() ||
        record->getDescribedClassTemplate() ||
        record->getTemplateSpecializationKind() ||
        record->isDependentType())
      return;

    if (InBannedNamespace(record))
      return;

    SourceLocation record_location = record->getInnerLocStart();
    if (InBannedDirectory(record_location))
      return;

    // We sadly need to maintain a blacklist of types that violate these
    // rules, but do so for good reason or due to limitations of this
    // checker (i.e., we don't handle extern templates very well).
    std::string base_name = record->getNameAsString();
    if (IsIgnoredType(base_name))
      return;

    // We ignore all classes that end with "Matcher" because they're probably
    // GMock artifacts.
    if (ends_with(base_name, "Matcher"))
        return;

    CheckChromeClass(record_location, record);
  }
}

void ChromeClassTester::emitWarning(SourceLocation loc, const char* raw_error) {
  FullSourceLoc full(loc, instance().getSourceManager());
  std::string err;
  err = "[chromium-style] ";
  err += raw_error;
  Diagnostic::Level level =
      diagnostic().getWarningsAsErrors() ?
      Diagnostic::Error :
      Diagnostic::Warning;
  unsigned id = diagnostic().getCustomDiagID(level, err);
  DiagnosticBuilder B = diagnostic().Report(full, id);
}

bool ChromeClassTester::InTestingNamespace(Decl* record) {
  return GetNamespace(record).find("testing") != std::string::npos;
}

bool ChromeClassTester::InBannedNamespace(Decl* record) {
  std::string n = GetNamespace(record);
  if (n != "") {
    return std::find(banned_namespaces_.begin(), banned_namespaces_.end(), n)
        != banned_namespaces_.end();
  }

  return false;
}

std::string ChromeClassTester::GetNamespace(Decl* record) {
  return GetNamespaceImpl(record->getDeclContext(), "");
}

std::string ChromeClassTester::GetNamespaceImpl(const DeclContext* context,
                                                std::string candidate) {
  switch (context->getDeclKind()) {
    case Decl::TranslationUnit: {
      return candidate;
    }
    case Decl::Namespace: {
      const NamespaceDecl* decl = dyn_cast<NamespaceDecl>(context);
      std::string name_str;
      llvm::raw_string_ostream OS(name_str);
      if (decl->isAnonymousNamespace())
        OS << "<anonymous namespace>";
      else
        OS << decl;
      return GetNamespaceImpl(context->getParent(),
                              OS.str());
    }
    default: {
      return GetNamespaceImpl(context->getParent(), candidate);
    }
  }
}

bool ChromeClassTester::InBannedDirectory(SourceLocation loc) {
  const SourceManager &SM = instance_.getSourceManager();
  SourceLocation spelling_location = SM.getSpellingLoc(loc);
  PresumedLoc ploc = SM.getPresumedLoc(spelling_location);
  std::string buffer_name;
  if (ploc.isInvalid()) {
    // If we're in an invalid location, we're looking at things that aren't
    // actually stated in the source; treat this as a banned location instead
    // of going through our full lookup process.
    return true;
  } else {
    std::string b = ploc.getFilename();

    // We need to special case scratch space; which is where clang does its
    // macro expansion. We explicitly want to allow people to do otherwise bad
    // things through macros that were defined due to third party libraries.
    if (b == "<scratch space>")
      return true;

    // Don't complain about these things in implementation files.
    if (ends_with(b, ".cc") || ends_with(b, ".cpp") || ends_with(b, ".mm")) {
      return true;
    }

    // Don't complain about autogenerated protobuf files.
    if (ends_with(b, ".pb.h")) {
      return true;
    }

    // We need to munge the paths so that they are relative to the repository
    // srcroot. We first resolve the symlinktastic relative path and then
    // remove our known srcroot from it if needed.
    char resolvedPath[MAXPATHLEN];
    if (realpath(b.c_str(), resolvedPath)) {
      std::string resolved = resolvedPath;
      if (starts_with(resolved, src_root_)) {
        b = resolved.substr(src_root_.size());
      }
    }

    for (std::vector<std::string>::const_iterator it =
             banned_directories_.begin();
         it != banned_directories_.end(); ++it) {
      if (starts_with(b, *it)) {
        return true;
      }
    }
  }

  return false;
}

bool ChromeClassTester::IsIgnoredType(const std::string& base_name) {
  return ignored_record_names_.find(base_name) != ignored_record_names_.end();
}
<|endoftext|>


<commit_before>// Copyright 2011 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
//
//     https://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.
//
// Author: jdtang@google.com (Jonathan Tang)

#include "test_utils.h"

namespace {

typedef GumboTest GumboStringPieceTest;

#define INIT_GUMBO_STRING(varname, literal) \
  GumboStringPiece varname = {literal, sizeof(literal) - 1}

TEST_F(GumboStringPieceTest, Equal) {
  INIT_GUMBO_STRING(str1, "foo");
  INIT_GUMBO_STRING(str2, "foo");
  EXPECT_TRUE(gumbo_string_equals(&str1, &str2));
}

TEST_F(GumboStringPieceTest, NotEqual_DifferingCase) {
  INIT_GUMBO_STRING(str1, "foo");
  INIT_GUMBO_STRING(str2, "Foo");
  EXPECT_FALSE(gumbo_string_equals(&str1, &str2));
}

TEST_F(GumboStringPieceTest, NotEqual_Str1Shorter) {
  INIT_GUMBO_STRING(str1, "foo");
  INIT_GUMBO_STRING(str2, "foobar");
  EXPECT_FALSE(gumbo_string_equals(&str1, &str2));
}

TEST_F(GumboStringPieceTest, NotEqual_Str2Shorter) {
  INIT_GUMBO_STRING(str1, "foobar");
  INIT_GUMBO_STRING(str2, "foo");
  EXPECT_FALSE(gumbo_string_equals(&str1, &str2));
}

TEST_F(GumboStringPieceTest, NotEqual_DifferentText) {
  INIT_GUMBO_STRING(str1, "bar");
  INIT_GUMBO_STRING(str2, "foo");
  EXPECT_FALSE(gumbo_string_equals(&str1, &str2));
}

TEST_F(GumboStringPieceTest, CaseEqual) {
  INIT_GUMBO_STRING(str1, "foo");
  INIT_GUMBO_STRING(str2, "fOO");
  EXPECT_TRUE(gumbo_string_equals_ignore_case(&str1, &str2));
}

TEST_F(GumboStringPieceTest, CaseNotEqual_Str2Shorter) {
  INIT_GUMBO_STRING(str1, "foobar");
  INIT_GUMBO_STRING(str2, "foo");
  EXPECT_FALSE(gumbo_string_equals_ignore_case(&str1, &str2));
}

}  // namespace
<commit_msg>Clean up test/parser/string_piece.cc<commit_after>// Copyright 2011 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
//
//     https://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.
//
// Author: jdtang@google.com (Jonathan Tang)

#include "test_utils.h"

namespace {

typedef GumboTest GumboStringPieceTest;

#define STRING(s) {"" s, sizeof(s) - 1}

TEST_F(GumboStringPieceTest, Equal) {
  const GumboStringPiece str1 = STRING("foo");
  const GumboStringPiece str2 = STRING("foo");
  EXPECT_TRUE(gumbo_string_equals(&str1, &str2));
}

TEST_F(GumboStringPieceTest, NotEqual_DifferingCase) {
  const GumboStringPiece str1 = STRING("foo");
  const GumboStringPiece str2 = STRING("Foo");
  EXPECT_FALSE(gumbo_string_equals(&str1, &str2));
}

TEST_F(GumboStringPieceTest, NotEqual_Str1Shorter) {
  const GumboStringPiece str1 = STRING("foo");
  const GumboStringPiece str2 = STRING("foobar");
  EXPECT_FALSE(gumbo_string_equals(&str1, &str2));
}

TEST_F(GumboStringPieceTest, NotEqual_Str2Shorter) {
  const GumboStringPiece str1 = STRING("foobar");
  const GumboStringPiece str2 = STRING("foo");
  EXPECT_FALSE(gumbo_string_equals(&str1, &str2));
}

TEST_F(GumboStringPieceTest, NotEqual_DifferentText) {
  const GumboStringPiece str1 = STRING("bar");
  const GumboStringPiece str2 = STRING("foo");
  EXPECT_FALSE(gumbo_string_equals(&str1, &str2));
}

TEST_F(GumboStringPieceTest, CaseEqual) {
  const GumboStringPiece str1 = STRING("foo");
  const GumboStringPiece str2 = STRING("fOO");
  EXPECT_TRUE(gumbo_string_equals_ignore_case(&str1, &str2));
}

TEST_F(GumboStringPieceTest, CaseNotEqual_Str2Shorter) {
  const GumboStringPiece str1 = STRING("foobar");
  const GumboStringPiece str2 = STRING("foo");
  EXPECT_FALSE(gumbo_string_equals_ignore_case(&str1, &str2));
}

}  // namespace
<|endoftext|>


<commit_before>// @(#)root/reflex:$Id: Class.cxx 20883 2007-11-19 11:52:08Z rdm $

// Include files----------------------------------------------------------------
#include "Reflex/Reflex.h"
#include "Reflex/PluginService.h"
#include "Reflex/SharedLibrary.h"
#include "../dir_manip.h"
#include <cstdlib>

#include <set>
#include <ctime>
#include <cerrno>
#include <fstream>
#include <iostream>
#include <exception>

using namespace std;
using namespace ROOT::Reflex;

class mapGenerator {
   fstream m_out;
   string m_lib;

public:
   mapGenerator(const string& file, const string& lib):
      m_out(file.c_str(), std::ios_base::out | std::ios_base::trunc),
      m_lib(lib) {}

   bool
   good() const { return m_out.good(); }

   void genHeader();
   void genFactory(const string& name,
                   const string& type);
   void genTrailer();
};

static string
currpath(string lib) {
   char buff[PATH_MAX];
   if (!::getcwd(buff, sizeof(buff))) {
      strcpy(buff, ".");
   }
   string tmp = buff;
   tmp += "/" + lib;
   return tmp;
}

static int
help(const char* cmd) {
   cout << cmd << ":  Allowed options" << endl
        << "  -help            produce this help message" << endl
        << "  -debug           increase verbosity level" << endl
        << "  -input-library   library to extract the plugins" << endl
        << "  -output-file     output file. default <input-library>.rootmap" << endl;
   return 1;
}

//--- Command main program------------------------------------------------------
int
main(int argc,
     char** argv) {
   struct stat buf;
   bool deb = false;
   string rootmap, lib, err, out;
   string::size_type idx;

   for (int i = 1; i < argc; ++i) {
      const char* opt = argv[i], * val = 0;

      if (*opt == '/' || *opt == '-') {
         if (*++opt == '/' || *opt == '-') {
            ++opt;
         }
         val = (opt[1] != '=') ? ++i < argc ? argv[i] : 0 : opt + 2;

         switch (::toupper(opt[0])) {
         case 'D':
            deb = true;
            --i;
            break;
         case 'I':
            lib = val;
            break;
         case 'O':
            rootmap = val;
            break;
         default:
            return help(argv[0]);
         }
      }
   }

   if (lib.empty()) {
      cout << "ERROR occurred: input library required" << endl;
      return help(argv[0]);
   }

   if (rootmap.empty()) {
      string flib = lib;

      while ((idx = flib.find("\\")) != string::npos)
         flib.replace(idx, 1, "/");
#ifdef _WIN32

      if (flib[1] != ':' && flib[0] != '/') {
#else

      if (!(flib[0] == '/' || flib.find('/') != string::npos)) {
#endif
         flib = currpath(flib);
      }
      rootmap = ::dirnameEx(flib);
      rootmap += "/";
      string tmp = ::basenameEx(lib);

      if (tmp.rfind('.') == std::string::npos) {
         rootmap += tmp + ".rootmap";
      } else if (tmp.find("/") != std::string::npos && tmp.rfind(".") < tmp.rfind("/")) {
         rootmap += tmp + ".rootmap";
      } else {
         rootmap += tmp.substr(0, tmp.rfind('.')) + ".rootmap";
      }
   }

   if (deb) {
      cout << "Input Library: '" << lib << "'" << endl;
      cout << "ROOT Map file: '" << rootmap << "'" << endl;
   }

   if (::stat(rootmap.c_str(), &buf) == -1 && errno == ENOENT) {
      string dir = ::dirnameEx(rootmap);

      if (deb) {
         cout << "Output directory:" << dir << "'" << endl;
      }

      if (!dir.empty() && ::stat(dir.c_str(), &buf) == -1 && errno == ENOENT) {
         if (::mkdir(dir.c_str(), S_IRWXU | S_IRGRP | S_IROTH) != 0 && errno != EEXIST) {
            cout << "ERR0R: error creating directory: '" << dir << "'" << endl;
            return 1;
         }
      }
   }
   out = rootmap;

   //--- Load the library -------------------------------------------------
   SharedLibrary sl(lib);

   if (!sl.Load()) {
      cout << "ERR0R: error loading library: '" << lib << "'" << endl
           << sl.Error() << endl;
      return 1;
   }

   mapGenerator map_gen(rootmap.c_str(), lib);

   if (!map_gen.good()) {
      cout << "ERR0R: cannot open output file: '" << rootmap << "'" << endl
           << sl.Error() << endl;
      return 1;
   }
   //--- Iterate over component factories ---------------------------------------
   Scope factories = Scope::ByName(PLUGINSVC_FACTORY_NS);

   if (factories) {
      map_gen.genHeader();
      set<string> used_names;

      try {
         for (Member_Iterator it = factories.FunctionMember_Begin();
              it != factories.FunctionMember_End(); ++it) {
            //string cname = it->Properties().PropertyAsString("name");
            string cname = it->Name();

            if (used_names.insert(cname).second) {
               map_gen.genFactory(cname, "");
            }
         }
         map_gen.genTrailer();
         return 0;
      }
      catch (std::exception& e) {
         cerr << "GENMAP: error creating map " << rootmap << ": "
              << e.what() << endl;
      }
      return 1;
   }
   cout << "library does not contain plugin factories" << endl;
   return 0;
} // main

//------------------------------------------------------------------------------
void
mapGenerator::genHeader() {
//------------------------------------------------------------------------------
   time_t rawtime;
   time(&rawtime);
   m_out << "# ROOT map file generated automatically by genmap on " << ctime(&rawtime) << endl;
}

//------------------------------------------------------------------------------
void
mapGenerator::genFactory(const string& name,
                         const string& /* type */) {
//------------------------------------------------------------------------------
   string mapname = string(PLUGINSVC_FACTORY_NS) + "@@" + PluginService::FactoryName(name);

   //  for ( string::const_iterator i = name.begin(); i != name.end(); i++) {
   //   switch(*i) {
   //     case ':': { newname += '@'; break; }
   //     case ' ': { break; }
   //     default:  { newname += *i; break; }
   //   }
   //  }
   m_out << "Library." << mapname << ": " << m_lib << endl;
}

//------------------------------------------------------------------------------
void
mapGenerator::genTrailer() {
//------------------------------------------------------------------------------
}
<commit_msg>Coverity: intentional and TOCTOU that is simply noy needed<commit_after>// @(#)root/reflex:$Id: Class.cxx 20883 2007-11-19 11:52:08Z rdm $

// Include files----------------------------------------------------------------
#include "Reflex/Reflex.h"
#include "Reflex/PluginService.h"
#include "Reflex/SharedLibrary.h"
#include "../dir_manip.h"
#include <cstdlib>

#include <set>
#include <ctime>
#include <cerrno>
#include <fstream>
#include <iostream>
#include <exception>

using namespace std;
using namespace ROOT::Reflex;

class mapGenerator {
   fstream m_out;
   string m_lib;

public:
   mapGenerator(const string& file, const string& lib):
      m_out(file.c_str(), std::ios_base::out | std::ios_base::trunc),
      m_lib(lib) {}

   bool
   good() const { return m_out.good(); }

   void genHeader();
   void genFactory(const string& name,
                   const string& type);
   void genTrailer();
};

static string
currpath(string lib) {
   char buff[PATH_MAX];
   if (!::getcwd(buff, sizeof(buff))) {
      // coverity[secure_coding] - PATH_MAX is > 2
      strcpy(buff, ".");
   }
   string tmp = buff;
   tmp += "/" + lib;
   return tmp;
}

static int
help(const char* cmd) {
   cout << cmd << ":  Allowed options" << endl
        << "  -help            produce this help message" << endl
        << "  -debug           increase verbosity level" << endl
        << "  -input-library   library to extract the plugins" << endl
        << "  -output-file     output file. default <input-library>.rootmap" << endl;
   return 1;
}

//--- Command main program------------------------------------------------------
int
main(int argc,
     char** argv) {
   struct stat buf;
   bool deb = false;
   string rootmap, lib, err, out;
   string::size_type idx;

   for (int i = 1; i < argc; ++i) {
      const char* opt = argv[i], * val = 0;

      if (*opt == '/' || *opt == '-') {
         if (*++opt == '/' || *opt == '-') {
            ++opt;
         }
         val = (opt[1] != '=') ? ++i < argc ? argv[i] : 0 : opt + 2;

         switch (::toupper(opt[0])) {
         case 'D':
            deb = true;
            --i;
            break;
         case 'I':
            lib = val;
            break;
         case 'O':
            rootmap = val;
            break;
         default:
            return help(argv[0]);
         }
      }
   }

   if (lib.empty()) {
      cout << "ERROR occurred: input library required" << endl;
      return help(argv[0]);
   }

   if (rootmap.empty()) {
      string flib = lib;

      while ((idx = flib.find("\\")) != string::npos)
         flib.replace(idx, 1, "/");
#ifdef _WIN32

      if (flib[1] != ':' && flib[0] != '/') {
#else

      if (!(flib[0] == '/' || flib.find('/') != string::npos)) {
#endif
         flib = currpath(flib);
      }
      rootmap = ::dirnameEx(flib);
      rootmap += "/";
      string tmp = ::basenameEx(lib);

      if (tmp.rfind('.') == std::string::npos) {
         rootmap += tmp + ".rootmap";
      } else if (tmp.find("/") != std::string::npos && tmp.rfind(".") < tmp.rfind("/")) {
         rootmap += tmp + ".rootmap";
      } else {
         rootmap += tmp.substr(0, tmp.rfind('.')) + ".rootmap";
      }
   }

   if (deb) {
      cout << "Input Library: '" << lib << "'" << endl;
      cout << "ROOT Map file: '" << rootmap << "'" << endl;
   }

   if (::stat(rootmap.c_str(), &buf) == -1 && errno == ENOENT) {
      string dir = ::dirnameEx(rootmap);

      if (deb) {
         cout << "Output directory:" << dir << "'" << endl;
      }

      if (!dir.empty()) {
         if (::mkdir(dir.c_str(), S_IRWXU | S_IRGRP | S_IROTH) != 0 && errno != EEXIST) {
            cout << "ERR0R: error creating directory: '" << dir << "'" << endl;
            return 1;
         }
      }
   }
   out = rootmap;

   //--- Load the library -------------------------------------------------
   SharedLibrary sl(lib);

   if (!sl.Load()) {
      cout << "ERR0R: error loading library: '" << lib << "'" << endl
           << sl.Error() << endl;
      return 1;
   }

   mapGenerator map_gen(rootmap.c_str(), lib);

   if (!map_gen.good()) {
      cout << "ERR0R: cannot open output file: '" << rootmap << "'" << endl
           << sl.Error() << endl;
      return 1;
   }
   //--- Iterate over component factories ---------------------------------------
   Scope factories = Scope::ByName(PLUGINSVC_FACTORY_NS);

   if (factories) {
      map_gen.genHeader();
      set<string> used_names;

      try {
         for (Member_Iterator it = factories.FunctionMember_Begin();
              it != factories.FunctionMember_End(); ++it) {
            //string cname = it->Properties().PropertyAsString("name");
            string cname = it->Name();

            if (used_names.insert(cname).second) {
               map_gen.genFactory(cname, "");
            }
         }
         map_gen.genTrailer();
         return 0;
      }
      catch (std::exception& e) {
         cerr << "GENMAP: error creating map " << rootmap << ": "
              << e.what() << endl;
      }
      return 1;
   }
   cout << "library does not contain plugin factories" << endl;
   return 0;
} // main

//------------------------------------------------------------------------------
void
mapGenerator::genHeader() {
//------------------------------------------------------------------------------
   time_t rawtime;
   time(&rawtime);
   m_out << "# ROOT map file generated automatically by genmap on " << ctime(&rawtime) << endl;
}

//------------------------------------------------------------------------------
void
mapGenerator::genFactory(const string& name,
                         const string& /* type */) {
//------------------------------------------------------------------------------
   string mapname = string(PLUGINSVC_FACTORY_NS) + "@@" + PluginService::FactoryName(name);

   //  for ( string::const_iterator i = name.begin(); i != name.end(); i++) {
   //   switch(*i) {
   //     case ':': { newname += '@'; break; }
   //     case ' ': { break; }
   //     default:  { newname += *i; break; }
   //   }
   //  }
   m_out << "Library." << mapname << ": " << m_lib << endl;
}

//------------------------------------------------------------------------------
void
mapGenerator::genTrailer() {
//------------------------------------------------------------------------------
}
<|endoftext|>