<commit_before>/*************************************************************************
 *
 *  $RCSfile: XMLStylesExportHelper.hxx,v $
 *
 *  $Revision: 1.23 $
 *
 *  last change: $Author: rt $ $Date: 2004-07-13 07:46:56 $
 *
 *  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 _SC_XMLSTYLESEXPORTHELPER_HXX
#define _SC_XMLSTYLESEXPORTHELPER_HXX

#ifndef __SGI_STL_VECTOR
#include <vector>
#endif
#ifndef __SGI_STL_LIST
#include <list>
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_H_
#include <com/sun/star/uno/Any.h>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLRANGEADDRESS_HPP_
#include <com/sun/star/table/CellRangeAddress.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_
#include <com/sun/star/table/CellAddress.hpp>
#endif
#ifndef _COM_SUN_STAR_SHEET_CONDITIONOPERATOR_HPP_
#include <com/sun/star/sheet/ConditionOperator.hpp>
#endif
#ifndef _COM_SUN_STAR_SHEET_VALIDATIONALERTSTYLE_HPP_
#include <com/sun/star/sheet/ValidationAlertStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_SHEET_VALIDATIONTYPE_HPP_
#include <com/sun/star/sheet/ValidationType.hpp>
#endif

class ScDocument;
class ScXMLExport;

struct ScMyValidation
{
    rtl::OUString               sName;
    rtl::OUString               sErrorMessage;
    rtl::OUString               sErrorTitle;
    rtl::OUString               sImputMessage;
    rtl::OUString               sImputTitle;
    rtl::OUString               sFormula1;
    rtl::OUString               sFormula2;
    com::sun::star::table::CellAddress          aBaseCell;
    com::sun::star::sheet::ValidationAlertStyle aAlertStyle;
    com::sun::star::sheet::ValidationType       aValidationType;
    com::sun::star::sheet::ConditionOperator    aOperator;
    sal_Int16                   nShowList;
    sal_Bool                    bShowErrorMessage;
    sal_Bool                    bShowImputMessage;
    sal_Bool                    bIgnoreBlanks;

                                ScMyValidation();
                                ~ScMyValidation();

    sal_Bool                    IsEqual(const ScMyValidation& aVal) const;
};

typedef std::vector<ScMyValidation>         ScMyValidationVec;

class ScMyValidationsContainer
{
private:
    ScMyValidationVec           aValidationVec;
    const rtl::OUString         sEmptyString;
    const rtl::OUString         sERRALSTY;
    const rtl::OUString         sIGNOREBL;
    const rtl::OUString         sSHOWLIST;
    const rtl::OUString         sTYPE;
    const rtl::OUString         sSHOWINP;
    const rtl::OUString         sSHOWERR;
    const rtl::OUString         sINPTITLE;
    const rtl::OUString         sINPMESS;
    const rtl::OUString         sERRTITLE;
    const rtl::OUString         sERRMESS;
    const rtl::OUString         sOnError;
    const rtl::OUString         sEventType;
    const rtl::OUString         sStarBasic;
    const rtl::OUString         sLibrary;
    const rtl::OUString         sMacroName;

public:
                                ScMyValidationsContainer();
                                ~ScMyValidationsContainer();
    sal_Bool                    AddValidation(const com::sun::star::uno::Any& aAny,
                                    sal_Int32& nValidationIndex);
    rtl::OUString               GetCondition(ScXMLExport& rExport, const ScMyValidation& aValidation);
    rtl::OUString               GetBaseCellAddress(ScDocument* pDoc, const com::sun::star::table::CellAddress& aCell);
    void                        WriteMessage(ScXMLExport& rExport,
                                    const rtl::OUString& sTitle, const rtl::OUString& sMessage,
                                    const sal_Bool bShowMessage, const sal_Bool bIsHelpMessage);
    void                        WriteValidations(ScXMLExport& rExport);
    const rtl::OUString&        GetValidationName(const sal_Int32 nIndex);
};

//==============================================================================

struct ScMyDefaultStyle
{
    sal_Int32   nIndex;
    sal_Int32   nRepeat;
    sal_Bool    bIsAutoStyle;

    ScMyDefaultStyle() : nIndex(-1), bIsAutoStyle(sal_True),
        nRepeat(1) {}
};

typedef std::vector<ScMyDefaultStyle> ScMyDefaultStyleList;

class ScFormatRangeStyles;

class ScMyDefaultStyles
{
    ScMyDefaultStyleList* pRowDefaults;
    ScMyDefaultStyleList* pColDefaults;

    sal_Int32 GetStyleNameIndex(const ScFormatRangeStyles* pCellStyles,
        const sal_Int32 nTable, const sal_Int32 nPos,
        const sal_Int32 i, const sal_Bool bRow, sal_Bool& bIsAutoStyle);
    void FillDefaultStyles(const sal_Int32 nTable,
        const sal_Int32 nLastRow, const sal_Int32 nLastCol,
        const ScFormatRangeStyles* pCellStyles, ScDocument* pDoc,
        const sal_Bool bRow);
public:
    ScMyDefaultStyles() : pRowDefaults(NULL), pColDefaults(NULL) {}
    ~ScMyDefaultStyles();

    void FillDefaultStyles(const sal_Int32 nTable,
        const sal_Int32 nLastRow, const sal_Int32 nLastCol,
        const ScFormatRangeStyles* pCellStyles, ScDocument* pDoc);

    const ScMyDefaultStyleList* GetRowDefaults() { return pRowDefaults; }
    const ScMyDefaultStyleList* GetColDefaults() { return pColDefaults; }
};

struct ScMyRowFormatRange
{
    sal_Int32   nStartColumn;
    sal_Int32   nRepeatColumns;
    sal_Int32   nRepeatRows;
    sal_Int32   nIndex;
    sal_Int32   nValidationIndex;
    sal_Bool    bIsAutoStyle : 1;

    ScMyRowFormatRange();
    sal_Bool operator<(const ScMyRowFormatRange& rRange) const;
};

typedef std::list<ScMyRowFormatRange> ScMyRowFormatRangesList;

class ScRowFormatRanges
{
    ScMyRowFormatRangesList     aRowFormatRanges;
    const ScMyDefaultStyleList* pRowDefaults;
    const ScMyDefaultStyleList* pColDefaults;
    sal_uInt32                  nSize;

    void AddRange(const sal_Int32 nPrevStartCol, const sal_Int32 nRepeat, const sal_Int32 nPrevIndex,
        const sal_Bool bPrevAutoStyle, const ScMyRowFormatRange& rFormatRange);

public:
    ScRowFormatRanges();
    ScRowFormatRanges(const ScRowFormatRanges* pRanges);
    ~ScRowFormatRanges();

    void SetRowDefaults(const ScMyDefaultStyleList* pDefaults) { pRowDefaults = pDefaults; }
    void SetColDefaults(const ScMyDefaultStyleList* pDefaults) { pColDefaults = pDefaults; }
    void Clear();
    void AddRange(ScMyRowFormatRange& rFormatRange, const sal_Int32 nStartRow);
    sal_Bool GetNext(ScMyRowFormatRange& rFormatRange);
    sal_Int32 GetMaxRows();
    sal_Int32 GetSize();
    void Sort();
};

typedef std::vector<rtl::OUString*>     ScMyOUStringVec;

struct ScMyFormatRange
{
    com::sun::star::table::CellRangeAddress aRangeAddress;
    sal_Int32                               nStyleNameIndex;
    sal_Int32                               nValidationIndex;
    sal_Int32                               nNumberFormat;
    sal_Bool                                bIsAutoStyle : 1;

    ScMyFormatRange();
    sal_Bool operator< (const ScMyFormatRange& rRange) const;
};

typedef std::list<ScMyFormatRange>          ScMyFormatRangeAddresses;
typedef std::vector<ScMyFormatRangeAddresses*>  ScMyFormatRangeListVec;

class ScFormatRangeStyles
{
    ScMyFormatRangeListVec      aTables;
    ScMyOUStringVec             aStyleNames;
    ScMyOUStringVec             aAutoStyleNames;
    const ScMyDefaultStyleList* pRowDefaults;
    const ScMyDefaultStyleList* pColDefaults;

public:
    ScFormatRangeStyles();
    ~ScFormatRangeStyles();

    void SetRowDefaults(const ScMyDefaultStyleList* pDefaults) { pRowDefaults = pDefaults; }
    void SetColDefaults(const ScMyDefaultStyleList* pDefaults) { pColDefaults = pDefaults; }
    void AddNewTable(const sal_Int32 nTable);
    sal_Bool AddStyleName(rtl::OUString* pString, sal_Int32& rIndex, const sal_Bool bIsAutoStyle = sal_True);
    sal_Int32 GetIndexOfStyleName(const rtl::OUString& rString, const rtl::OUString& rPrefix, sal_Bool& bIsAutoStyle);
    // does not delete ranges
    sal_Int32 GetStyleNameIndex(const sal_Int32 nTable, const sal_Int32 nColumn, const sal_Int32 nRow,
        sal_Bool& bIsAutoStyle) const;
    // deletes not necessary ranges if wanted
    sal_Int32 GetStyleNameIndex(const sal_Int32 nTable, const sal_Int32 nColumn, const sal_Int32 nRow,
        sal_Bool& bIsAutoStyle, sal_Int32& nValidationIndex, sal_Int32& nNumberFormat, const sal_Bool bRemoveRange = sal_True );
    void GetFormatRanges(const sal_Int32 nStartColumn, const sal_Int32 nEndColumn, const sal_Int32 nRow,
                    const sal_Int32 nTable, ScRowFormatRanges* pFormatRanges);
    void AddRangeStyleName(const com::sun::star::table::CellRangeAddress aCellRangeAddress, const sal_Int32 nStringIndex,
                    const sal_Bool bIsAutoStyle, const sal_Int32 nValidationIndex, const sal_Int32 nNumberFormat);
    rtl::OUString* GetStyleNameByIndex(const sal_Int32 nIndex, const sal_Bool bIsAutoStyle);
    void Sort();
};

class ScColumnRowStylesBase
{
    ScMyOUStringVec             aStyleNames;

public:
    ScColumnRowStylesBase();
    ~ScColumnRowStylesBase();

    virtual void AddNewTable(const sal_Int32 nTable, const sal_Int32 nFields) = 0;
    sal_Int32 AddStyleName(rtl::OUString* pString);
    sal_Int32 GetIndexOfStyleName(const rtl::OUString& rString, const rtl::OUString& rPrefix);
    virtual rtl::OUString* GetStyleName(const sal_Int32 nTable, const sal_Int32 nField) = 0;
    rtl::OUString* GetStyleNameByIndex(const sal_Int32 nIndex);
};

struct ScColumnStyle
{
    sal_Int32   nIndex;
    sal_Bool    bIsVisible : 1;

    ScColumnStyle() : nIndex(-1), bIsVisible(sal_True) {}
};

typedef std::vector<ScColumnStyle>  ScMyColumnStyleVec;
typedef std::vector<ScMyColumnStyleVec> ScMyColumnVectorVec;

class ScColumnStyles : public ScColumnRowStylesBase
{
    ScMyColumnVectorVec             aTables;

public:
    ScColumnStyles();
    ~ScColumnStyles();

    virtual void AddNewTable(const sal_Int32 nTable, const sal_Int32 nFields);
    sal_Int32 GetStyleNameIndex(const sal_Int32 nTable, const sal_Int32 nField,
        sal_Bool& bIsVisible);
    void AddFieldStyleName(const sal_Int32 nTable, const sal_Int32 nField, const sal_Int32 nStringIndex, const sal_Bool bIsVisible);
    virtual rtl::OUString* GetStyleName(const sal_Int32 nTable, const sal_Int32 nField);
};

typedef std::vector<sal_Int32>  ScMysalInt32Vec;
typedef std::vector<ScMysalInt32Vec>    ScMyRowVectorVec;

class ScRowStyles : public ScColumnRowStylesBase
{
    ScMyRowVectorVec                aTables;

public:
    ScRowStyles();
    ~ScRowStyles();

    virtual void AddNewTable(const sal_Int32 nTable, const sal_Int32 nFields);
    sal_Int32 GetStyleNameIndex(const sal_Int32 nTable, const sal_Int32 nField);
    void AddFieldStyleName(const sal_Int32 nTable, const sal_Int32 nField, const sal_Int32 nStringIndex);
    virtual rtl::OUString* GetStyleName(const sal_Int32 nTable, const sal_Int32 nField);
};

#endif

<commit_msg>INTEGRATION: CWS calcuno01 (1.21.76); FILE MERGED 2004/10/13 12:42:07 sab 1.21.76.2: RESYNC: (1.21-1.23); FILE MERGED 2004/01/05 11:55:52 sab 1.21.76.1: #i22706#; improve API using<commit_after>/*************************************************************************
 *
 *  $RCSfile: XMLStylesExportHelper.hxx,v $
 *
 *  $Revision: 1.24 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-23 12:51:15 $
 *
 *  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 _SC_XMLSTYLESEXPORTHELPER_HXX
#define _SC_XMLSTYLESEXPORTHELPER_HXX

#ifndef __SGI_STL_VECTOR
#include <vector>
#endif
#ifndef __SGI_STL_LIST
#include <list>
#endif

#ifndef _COM_SUN_STAR_UNO_ANY_H_
#include <com/sun/star/uno/Any.h>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLRANGEADDRESS_HPP_
#include <com/sun/star/table/CellRangeAddress.hpp>
#endif
#ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_
#include <com/sun/star/table/CellAddress.hpp>
#endif
#ifndef _COM_SUN_STAR_SHEET_CONDITIONOPERATOR_HPP_
#include <com/sun/star/sheet/ConditionOperator.hpp>
#endif
#ifndef _COM_SUN_STAR_SHEET_VALIDATIONALERTSTYLE_HPP_
#include <com/sun/star/sheet/ValidationAlertStyle.hpp>
#endif
#ifndef _COM_SUN_STAR_SHEET_VALIDATIONTYPE_HPP_
#include <com/sun/star/sheet/ValidationType.hpp>
#endif

class ScDocument;
class ScXMLExport;

struct ScMyValidation
{
    rtl::OUString               sName;
    rtl::OUString               sErrorMessage;
    rtl::OUString               sErrorTitle;
    rtl::OUString               sImputMessage;
    rtl::OUString               sImputTitle;
    rtl::OUString               sFormula1;
    rtl::OUString               sFormula2;
    com::sun::star::table::CellAddress          aBaseCell;
    com::sun::star::sheet::ValidationAlertStyle aAlertStyle;
    com::sun::star::sheet::ValidationType       aValidationType;
    com::sun::star::sheet::ConditionOperator    aOperator;
    sal_Int16                   nShowList;
    sal_Bool                    bShowErrorMessage;
    sal_Bool                    bShowImputMessage;
    sal_Bool                    bIgnoreBlanks;

                                ScMyValidation();
                                ~ScMyValidation();

    sal_Bool                    IsEqual(const ScMyValidation& aVal) const;
};

typedef std::vector<ScMyValidation>         ScMyValidationVec;

class ScMyValidationsContainer
{
private:
    ScMyValidationVec           aValidationVec;
    const rtl::OUString         sEmptyString;
    const rtl::OUString         sERRALSTY;
    const rtl::OUString         sIGNOREBL;
    const rtl::OUString         sSHOWLIST;
    const rtl::OUString         sTYPE;
    const rtl::OUString         sSHOWINP;
    const rtl::OUString         sSHOWERR;
    const rtl::OUString         sINPTITLE;
    const rtl::OUString         sINPMESS;
    const rtl::OUString         sERRTITLE;
    const rtl::OUString         sERRMESS;
    const rtl::OUString         sOnError;
    const rtl::OUString         sEventType;
    const rtl::OUString         sStarBasic;
    const rtl::OUString         sLibrary;
    const rtl::OUString         sMacroName;

public:
                                ScMyValidationsContainer();
                                ~ScMyValidationsContainer();
    sal_Bool                    AddValidation(const com::sun::star::uno::Any& aAny,
                                    sal_Int32& nValidationIndex);
    rtl::OUString               GetCondition(ScXMLExport& rExport, const ScMyValidation& aValidation);
    rtl::OUString               GetBaseCellAddress(ScDocument* pDoc, const com::sun::star::table::CellAddress& aCell);
    void                        WriteMessage(ScXMLExport& rExport,
                                    const rtl::OUString& sTitle, const rtl::OUString& sMessage,
                                    const sal_Bool bShowMessage, const sal_Bool bIsHelpMessage);
    void                        WriteValidations(ScXMLExport& rExport);
    const rtl::OUString&        GetValidationName(const sal_Int32 nIndex);
};

//==============================================================================

struct ScMyDefaultStyle
{
    sal_Int32   nIndex;
    sal_Int32   nRepeat;
    sal_Bool    bIsAutoStyle;

    ScMyDefaultStyle() : nIndex(-1), bIsAutoStyle(sal_True),
        nRepeat(1) {}
};

typedef std::vector<ScMyDefaultStyle> ScMyDefaultStyleList;

class ScFormatRangeStyles;

class ScMyDefaultStyles
{
    ScMyDefaultStyleList* pRowDefaults;
    ScMyDefaultStyleList* pColDefaults;

    sal_Int32 GetStyleNameIndex(const ScFormatRangeStyles* pCellStyles,
        const sal_Int32 nTable, const sal_Int32 nPos,
        const sal_Int32 i, const sal_Bool bRow, sal_Bool& bIsAutoStyle);
    void FillDefaultStyles(const sal_Int32 nTable,
        const sal_Int32 nLastRow, const sal_Int32 nLastCol,
        const ScFormatRangeStyles* pCellStyles, ScDocument* pDoc,
        const sal_Bool bRow);
public:
    ScMyDefaultStyles() : pRowDefaults(NULL), pColDefaults(NULL) {}
    ~ScMyDefaultStyles();

    void FillDefaultStyles(const sal_Int32 nTable,
        const sal_Int32 nLastRow, const sal_Int32 nLastCol,
        const ScFormatRangeStyles* pCellStyles, ScDocument* pDoc);

    const ScMyDefaultStyleList* GetRowDefaults() { return pRowDefaults; }
    const ScMyDefaultStyleList* GetColDefaults() { return pColDefaults; }
};

struct ScMyRowFormatRange
{
    sal_Int32   nStartColumn;
    sal_Int32   nRepeatColumns;
    sal_Int32   nRepeatRows;
    sal_Int32   nIndex;
    sal_Int32   nValidationIndex;
    sal_Bool    bIsAutoStyle;

    ScMyRowFormatRange();
    sal_Bool operator<(const ScMyRowFormatRange& rRange) const;
};

typedef std::list<ScMyRowFormatRange> ScMyRowFormatRangesList;

class ScRowFormatRanges
{
    ScMyRowFormatRangesList     aRowFormatRanges;
    const ScMyDefaultStyleList* pRowDefaults;
    const ScMyDefaultStyleList* pColDefaults;
    sal_uInt32                  nSize;

    void AddRange(const sal_Int32 nPrevStartCol, const sal_Int32 nRepeat, const sal_Int32 nPrevIndex,
        const sal_Bool bPrevAutoStyle, const ScMyRowFormatRange& rFormatRange);

public:
    ScRowFormatRanges();
    ScRowFormatRanges(const ScRowFormatRanges* pRanges);
    ~ScRowFormatRanges();

    void SetRowDefaults(const ScMyDefaultStyleList* pDefaults) { pRowDefaults = pDefaults; }
    void SetColDefaults(const ScMyDefaultStyleList* pDefaults) { pColDefaults = pDefaults; }
    void Clear();
    void AddRange(ScMyRowFormatRange& rFormatRange, const sal_Int32 nStartRow);
    sal_Bool GetNext(ScMyRowFormatRange& rFormatRange);
    sal_Int32 GetMaxRows();
    sal_Int32 GetSize();
    void Sort();
};

typedef std::vector<rtl::OUString*>     ScMyOUStringVec;

struct ScMyFormatRange
{
    com::sun::star::table::CellRangeAddress aRangeAddress;
    sal_Int32                               nStyleNameIndex;
    sal_Int32                               nValidationIndex;
    sal_Int32                               nNumberFormat;
    sal_Bool                                bIsAutoStyle;

    ScMyFormatRange();
    sal_Bool operator< (const ScMyFormatRange& rRange) const;
};

typedef std::list<ScMyFormatRange>          ScMyFormatRangeAddresses;
typedef std::vector<ScMyFormatRangeAddresses*>  ScMyFormatRangeListVec;

class ScFormatRangeStyles
{
    ScMyFormatRangeListVec      aTables;
    ScMyOUStringVec             aStyleNames;
    ScMyOUStringVec             aAutoStyleNames;
    const ScMyDefaultStyleList* pRowDefaults;
    const ScMyDefaultStyleList* pColDefaults;

public:
    ScFormatRangeStyles();
    ~ScFormatRangeStyles();

    void SetRowDefaults(const ScMyDefaultStyleList* pDefaults) { pRowDefaults = pDefaults; }
    void SetColDefaults(const ScMyDefaultStyleList* pDefaults) { pColDefaults = pDefaults; }
    void AddNewTable(const sal_Int32 nTable);
    sal_Bool AddStyleName(rtl::OUString* pString, sal_Int32& rIndex, const sal_Bool bIsAutoStyle = sal_True);
    sal_Int32 GetIndexOfStyleName(const rtl::OUString& rString, const rtl::OUString& rPrefix, sal_Bool& bIsAutoStyle);
    // does not delete ranges
    sal_Int32 GetStyleNameIndex(const sal_Int32 nTable, const sal_Int32 nColumn, const sal_Int32 nRow,
        sal_Bool& bIsAutoStyle) const;
    // deletes not necessary ranges if wanted
    sal_Int32 GetStyleNameIndex(const sal_Int32 nTable, const sal_Int32 nColumn, const sal_Int32 nRow,
        sal_Bool& bIsAutoStyle, sal_Int32& nValidationIndex, sal_Int32& nNumberFormat, const sal_Bool bRemoveRange = sal_True );
    void GetFormatRanges(const sal_Int32 nStartColumn, const sal_Int32 nEndColumn, const sal_Int32 nRow,
                    const sal_Int32 nTable, ScRowFormatRanges* pFormatRanges);
    void AddRangeStyleName(const com::sun::star::table::CellRangeAddress aCellRangeAddress, const sal_Int32 nStringIndex,
                    const sal_Bool bIsAutoStyle, const sal_Int32 nValidationIndex, const sal_Int32 nNumberFormat);
    rtl::OUString* GetStyleNameByIndex(const sal_Int32 nIndex, const sal_Bool bIsAutoStyle);
    void Sort();
};

class ScColumnRowStylesBase
{
    ScMyOUStringVec             aStyleNames;

public:
    ScColumnRowStylesBase();
    ~ScColumnRowStylesBase();

    virtual void AddNewTable(const sal_Int32 nTable, const sal_Int32 nFields) = 0;
    sal_Int32 AddStyleName(rtl::OUString* pString);
    sal_Int32 GetIndexOfStyleName(const rtl::OUString& rString, const rtl::OUString& rPrefix);
    virtual rtl::OUString* GetStyleName(const sal_Int32 nTable, const sal_Int32 nField) = 0;
    rtl::OUString* GetStyleNameByIndex(const sal_Int32 nIndex);
};

struct ScColumnStyle
{
    sal_Int32   nIndex;
    sal_Bool    bIsVisible;

    ScColumnStyle() : nIndex(-1), bIsVisible(sal_True) {}
};

typedef std::vector<ScColumnStyle>  ScMyColumnStyleVec;
typedef std::vector<ScMyColumnStyleVec> ScMyColumnVectorVec;

class ScColumnStyles : public ScColumnRowStylesBase
{
    ScMyColumnVectorVec             aTables;

public:
    ScColumnStyles();
    ~ScColumnStyles();

    virtual void AddNewTable(const sal_Int32 nTable, const sal_Int32 nFields);
    sal_Int32 GetStyleNameIndex(const sal_Int32 nTable, const sal_Int32 nField,
        sal_Bool& bIsVisible);
    void AddFieldStyleName(const sal_Int32 nTable, const sal_Int32 nField, const sal_Int32 nStringIndex, const sal_Bool bIsVisible);
    virtual rtl::OUString* GetStyleName(const sal_Int32 nTable, const sal_Int32 nField);
};

typedef std::vector<sal_Int32>  ScMysalInt32Vec;
typedef std::vector<ScMysalInt32Vec>    ScMyRowVectorVec;

class ScRowStyles : public ScColumnRowStylesBase
{
    ScMyRowVectorVec                aTables;

public:
    ScRowStyles();
    ~ScRowStyles();

    virtual void AddNewTable(const sal_Int32 nTable, const sal_Int32 nFields);
    sal_Int32 GetStyleNameIndex(const sal_Int32 nTable, const sal_Int32 nField);
    void AddFieldStyleName(const sal_Int32 nTable, const sal_Int32 nField, const sal_Int32 nStringIndex);
    virtual rtl::OUString* GetStyleName(const sal_Int32 nTable, const sal_Int32 nField);
};

#endif

<|endoftext|>


<commit_before>#include <atlbase.h>

#include <map>

#include "base/logging.h"
#include "base/string_util.h"

#include "setup_strings.h"

namespace {

// Gets the language from the OS.  If we're unable to get the system language,
// defaults to en-us.
std::wstring GetSystemLanguage() {
  static std::wstring language;
  if (!language.empty())
    return language;
  // We don't have ICU at this point, so we use win32 apis.
  LCID id = GetThreadLocale();
  int length = GetLocaleInfo(id, LOCALE_SISO639LANGNAME, 0, 0);
  if (0 == length)
    return false;
  length = GetLocaleInfo(id, LOCALE_SISO639LANGNAME,
                         WriteInto(&language, length), length);
  DCHECK(length == language.length() + 1);
  StringToLowerASCII(&language);

  // Add the country if we need it.
  std::wstring country;
  length = GetLocaleInfo(id, LOCALE_SISO3166CTRYNAME, 0, 0);
  if (0 != length) {
    length = GetLocaleInfo(id, LOCALE_SISO3166CTRYNAME,
                           WriteInto(&country, length), length);
    DCHECK(length == country.length() + 1);
    StringToLowerASCII(&country);
    if (L"en" == language) {
      if (L"gb" == country) {
        language.append(L"-gb");
      } else {
        language.append(L"-us");
      }
    } else if (L"es" == language && L"es" != country) {
      language.append(L"-419");
    } else if (L"pt" == language) {
      if (L"br" == country) {
        language.append(L"-br");
      } else {
        language.append(L"-pt");
      }
    } else if (L"zh" == language) {
      if (L"tw" == country) {
        language.append(L"-tw");
      } else {
        language.append(L"-cn");
      }
    }
  }

  if (language.empty())
    language = L"en-us";

  return language;
}

// This method returns the appropriate language offset given the language as a
// string.  Note: This method is not thread safe because of how we create
// |offset_map|.
int GetLanguageOffset(const std::wstring& language) {
  static std::map<std::wstring, int> offset_map;
  if (offset_map.empty()) {
    offset_map[L"ar"] = IDS_L10N_OFFSET_AR;
    offset_map[L"bg"] = IDS_L10N_OFFSET_BG;
    offset_map[L"ca"] = IDS_L10N_OFFSET_CA;
    offset_map[L"cs"] = IDS_L10N_OFFSET_CS;
    offset_map[L"da"] = IDS_L10N_OFFSET_DA;
    offset_map[L"de"] = IDS_L10N_OFFSET_DE;
    offset_map[L"el"] = IDS_L10N_OFFSET_EL;
    offset_map[L"en-gb"] = IDS_L10N_OFFSET_EN_GB;
    offset_map[L"en-us"] = IDS_L10N_OFFSET_EN_US;
    offset_map[L"es"] = IDS_L10N_OFFSET_ES;
    offset_map[L"es-419"] = IDS_L10N_OFFSET_ES_419;
    offset_map[L"et"] = IDS_L10N_OFFSET_ET;
    offset_map[L"fi"] = IDS_L10N_OFFSET_FI;
    offset_map[L"fil"] = IDS_L10N_OFFSET_FIL;
    offset_map[L"fr"] = IDS_L10N_OFFSET_FR;
    offset_map[L"he"] = IDS_L10N_OFFSET_HE;
    offset_map[L"hi"] = IDS_L10N_OFFSET_HI;
    offset_map[L"hr"] = IDS_L10N_OFFSET_HR;
    offset_map[L"hu"] = IDS_L10N_OFFSET_HU;
    offset_map[L"id"] = IDS_L10N_OFFSET_ID;
    offset_map[L"it"] = IDS_L10N_OFFSET_IT;
    offset_map[L"ja"] = IDS_L10N_OFFSET_JA;
    offset_map[L"ko"] = IDS_L10N_OFFSET_KO;
    offset_map[L"lt"] = IDS_L10N_OFFSET_LT;
    offset_map[L"lv"] = IDS_L10N_OFFSET_LV;
    // Google web properties use no for nb. Handle both just to be safe.
    offset_map[L"nb"] = IDS_L10N_OFFSET_NO;
    offset_map[L"nl"] = IDS_L10N_OFFSET_NL;
    offset_map[L"no"] = IDS_L10N_OFFSET_NO;
    offset_map[L"pl"] = IDS_L10N_OFFSET_PL;
    offset_map[L"pt-br"] = IDS_L10N_OFFSET_PT_BR;
    offset_map[L"pt-pt"] = IDS_L10N_OFFSET_PT_PT;
    offset_map[L"ro"] = IDS_L10N_OFFSET_RO;
    offset_map[L"ru"] = IDS_L10N_OFFSET_RU;
    offset_map[L"sk"] = IDS_L10N_OFFSET_SK;
    offset_map[L"sl"] = IDS_L10N_OFFSET_SL;
    offset_map[L"sr"] = IDS_L10N_OFFSET_SR;
    offset_map[L"sv"] = IDS_L10N_OFFSET_SV;
    offset_map[L"th"] = IDS_L10N_OFFSET_TH;
    offset_map[L"tr"] = IDS_L10N_OFFSET_TR;
    offset_map[L"uk"] = IDS_L10N_OFFSET_UK;
    offset_map[L"vi"] = IDS_L10N_OFFSET_VI;
    offset_map[L"zh-cn"] = IDS_L10N_OFFSET_ZH_CN;
    offset_map[L"zh-tw"] = IDS_L10N_OFFSET_ZH_TW;
  }

  std::map<std::wstring, int>::iterator it = offset_map.find(
      StringToLowerASCII(language));
  if (it != offset_map.end())
    return it->second;

  NOTREACHED() << "unknown system language-country";

  // Fallback on the en-US offset just in case.
  return IDS_L10N_OFFSET_EN_US;
}

}  // namespace

namespace installer_util {

std::wstring GetLocalizedString(int base_message_id) {
  std::wstring language = GetSystemLanguage();
  std::wstring localized_string;

  int message_id = base_message_id + GetLanguageOffset(language);
  const ATLSTRINGRESOURCEIMAGE* image = AtlGetStringResourceImage(
      _AtlBaseModule.GetModuleInstance(), message_id);
  if (image) {
    localized_string = std::wstring(image->achString, image->nLength);
  } else {
    NOTREACHED() << "Unable to find resource id " << message_id;
  }

  return localized_string;
}

}  // namespace installer_util
<commit_msg>Instead of returning false we should default to en-us when we fail to get locale.<commit_after>#include <atlbase.h>

#include <map>

#include "base/logging.h"
#include "base/string_util.h"

#include "setup_strings.h"

namespace {

// Gets the language from the OS.  If we're unable to get the system language,
// defaults to en-us.
std::wstring GetSystemLanguage() {
  static std::wstring language;
  if (!language.empty())
    return language;
  // We don't have ICU at this point, so we use win32 apis.
  LCID id = GetThreadLocale();
  int length = GetLocaleInfo(id, LOCALE_SISO639LANGNAME, 0, 0);
  if (0 == length) {
    language = L"en-us";
    return language;
  }
  length = GetLocaleInfo(id, LOCALE_SISO639LANGNAME,
                         WriteInto(&language, length), length);
  DCHECK(length == language.length() + 1);
  StringToLowerASCII(&language);

  // Add the country if we need it.
  std::wstring country;
  length = GetLocaleInfo(id, LOCALE_SISO3166CTRYNAME, 0, 0);
  if (0 != length) {
    length = GetLocaleInfo(id, LOCALE_SISO3166CTRYNAME,
                           WriteInto(&country, length), length);
    DCHECK(length == country.length() + 1);
    StringToLowerASCII(&country);
    if (L"en" == language) {
      if (L"gb" == country) {
        language.append(L"-gb");
      } else {
        language.append(L"-us");
      }
    } else if (L"es" == language && L"es" != country) {
      language.append(L"-419");
    } else if (L"pt" == language) {
      if (L"br" == country) {
        language.append(L"-br");
      } else {
        language.append(L"-pt");
      }
    } else if (L"zh" == language) {
      if (L"tw" == country) {
        language.append(L"-tw");
      } else {
        language.append(L"-cn");
      }
    }
  }

  if (language.empty())
    language = L"en-us";

  return language;
}

// This method returns the appropriate language offset given the language as a
// string.  Note: This method is not thread safe because of how we create
// |offset_map|.
int GetLanguageOffset(const std::wstring& language) {
  static std::map<std::wstring, int> offset_map;
  if (offset_map.empty()) {
    offset_map[L"ar"] = IDS_L10N_OFFSET_AR;
    offset_map[L"bg"] = IDS_L10N_OFFSET_BG;
    offset_map[L"ca"] = IDS_L10N_OFFSET_CA;
    offset_map[L"cs"] = IDS_L10N_OFFSET_CS;
    offset_map[L"da"] = IDS_L10N_OFFSET_DA;
    offset_map[L"de"] = IDS_L10N_OFFSET_DE;
    offset_map[L"el"] = IDS_L10N_OFFSET_EL;
    offset_map[L"en-gb"] = IDS_L10N_OFFSET_EN_GB;
    offset_map[L"en-us"] = IDS_L10N_OFFSET_EN_US;
    offset_map[L"es"] = IDS_L10N_OFFSET_ES;
    offset_map[L"es-419"] = IDS_L10N_OFFSET_ES_419;
    offset_map[L"et"] = IDS_L10N_OFFSET_ET;
    offset_map[L"fi"] = IDS_L10N_OFFSET_FI;
    offset_map[L"fil"] = IDS_L10N_OFFSET_FIL;
    offset_map[L"fr"] = IDS_L10N_OFFSET_FR;
    offset_map[L"he"] = IDS_L10N_OFFSET_HE;
    offset_map[L"hi"] = IDS_L10N_OFFSET_HI;
    offset_map[L"hr"] = IDS_L10N_OFFSET_HR;
    offset_map[L"hu"] = IDS_L10N_OFFSET_HU;
    offset_map[L"id"] = IDS_L10N_OFFSET_ID;
    offset_map[L"it"] = IDS_L10N_OFFSET_IT;
    offset_map[L"ja"] = IDS_L10N_OFFSET_JA;
    offset_map[L"ko"] = IDS_L10N_OFFSET_KO;
    offset_map[L"lt"] = IDS_L10N_OFFSET_LT;
    offset_map[L"lv"] = IDS_L10N_OFFSET_LV;
    // Google web properties use no for nb. Handle both just to be safe.
    offset_map[L"nb"] = IDS_L10N_OFFSET_NO;
    offset_map[L"nl"] = IDS_L10N_OFFSET_NL;
    offset_map[L"no"] = IDS_L10N_OFFSET_NO;
    offset_map[L"pl"] = IDS_L10N_OFFSET_PL;
    offset_map[L"pt-br"] = IDS_L10N_OFFSET_PT_BR;
    offset_map[L"pt-pt"] = IDS_L10N_OFFSET_PT_PT;
    offset_map[L"ro"] = IDS_L10N_OFFSET_RO;
    offset_map[L"ru"] = IDS_L10N_OFFSET_RU;
    offset_map[L"sk"] = IDS_L10N_OFFSET_SK;
    offset_map[L"sl"] = IDS_L10N_OFFSET_SL;
    offset_map[L"sr"] = IDS_L10N_OFFSET_SR;
    offset_map[L"sv"] = IDS_L10N_OFFSET_SV;
    offset_map[L"th"] = IDS_L10N_OFFSET_TH;
    offset_map[L"tr"] = IDS_L10N_OFFSET_TR;
    offset_map[L"uk"] = IDS_L10N_OFFSET_UK;
    offset_map[L"vi"] = IDS_L10N_OFFSET_VI;
    offset_map[L"zh-cn"] = IDS_L10N_OFFSET_ZH_CN;
    offset_map[L"zh-tw"] = IDS_L10N_OFFSET_ZH_TW;
  }

  std::map<std::wstring, int>::iterator it = offset_map.find(
      StringToLowerASCII(language));
  if (it != offset_map.end())
    return it->second;

  NOTREACHED() << "unknown system language-country";

  // Fallback on the en-US offset just in case.
  return IDS_L10N_OFFSET_EN_US;
}

}  // namespace

namespace installer_util {

std::wstring GetLocalizedString(int base_message_id) {
  std::wstring language = GetSystemLanguage();
  std::wstring localized_string;

  int message_id = base_message_id + GetLanguageOffset(language);
  const ATLSTRINGRESOURCEIMAGE* image = AtlGetStringResourceImage(
      _AtlBaseModule.GetModuleInstance(), message_id);
  if (image) {
    localized_string = std::wstring(image->achString, image->nLength);
  } else {
    NOTREACHED() << "Unable to find resource id " << message_id;
  }

  return localized_string;
}

}  // namespace installer_util
<|endoftext|>


<commit_before>// Copyright (c) 2010 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.

#include "base/compiler_specific.h"
#include "base/message_loop.h"
#include "base/process_util.h"
#include "base/test/multiprocess_test.h"
#include "base/test/test_timeouts.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/main_function_params.h"
#include "ipc/ipc_channel.h"
#include "ipc/ipc_switches.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/multiprocess_func_list.h"

// TODO(port): Bring up this test this on other platforms.
#if defined(OS_POSIX)

using base::ProcessHandle;

const char kRendererTestChannelName[] = "test";

extern int RendererMain(const MainFunctionParams& parameters);

// TODO(port): The IPC Channel tests have a class with extremely similar
// functionality, we should combine them.
class RendererMainTest : public base::MultiProcessTest {
 protected:
  RendererMainTest() {}

  // Create a new MessageLoopForIO For each test.
  virtual void SetUp();
  virtual void TearDown();

  // Spawns a child process of the specified type
  base::ProcessHandle SpawnChild(const std::string& procname,
                                 IPC::Channel* channel);

  virtual CommandLine MakeCmdLine(const std::string& procname,
                                  bool debug_on_start) OVERRIDE;

  // Created around each test instantiation.
  MessageLoopForIO *message_loop_;
};

void RendererMainTest::SetUp() {
  MultiProcessTest::SetUp();

  // Construct a fresh IO Message loop for the duration of each test.
  message_loop_ = new MessageLoopForIO();
}

void RendererMainTest::TearDown() {
  delete message_loop_;
  message_loop_ = NULL;

  MultiProcessTest::TearDown();
}

ProcessHandle RendererMainTest::SpawnChild(const std::string& procname,
                                           IPC::Channel* channel) {
  base::file_handle_mapping_vector fds_to_map;
  const int ipcfd = channel->GetClientFileDescriptor();
  if (ipcfd > -1) {
    fds_to_map.push_back(std::pair<int,int>(ipcfd, 3));
  }

  return MultiProcessTest::SpawnChild(procname, fds_to_map, false);
}

CommandLine RendererMainTest::MakeCmdLine(const std::string& procname,
                                          bool debug_on_start) {
  CommandLine command_line =
      MultiProcessTest::MakeCmdLine(procname, debug_on_start);
#if defined(USE_SECCOMP_SANDBOX)
  // Turn off seccomp for this test.  It's just a problem of refactoring,
  // not a bug.
  // http://code.google.com/p/chromium/issues/detail?id=59376
  command_line.AppendSwitch(switches::kDisableSeccompSandbox);
#endif
  return command_line;
}

// Listener class that kills the message loop when it connects.
class SuicidalListener : public IPC::Channel::Listener {
 public:
  void OnChannelConnected(int32 peer_pid) {
    MessageLoop::current()->Quit();
  }

  void OnMessageReceived(const IPC::Message& message) {
    // We shouldn't receive any messages
    ASSERT_TRUE(false);
  }
};

MULTIPROCESS_TEST_MAIN(SimpleRenderer) {
  SandboxInitWrapper dummy_sandbox_init;
  CommandLine cl(*CommandLine::ForCurrentProcess());
  cl.AppendSwitchASCII(switches::kProcessChannelID, kRendererTestChannelName);

  MainFunctionParams dummy_params(cl, dummy_sandbox_init, NULL);
  return RendererMain(dummy_params);
}

TEST_F(RendererMainTest, CreateDestroy) {
  SuicidalListener listener;
  IPC::Channel control_channel(kRendererTestChannelName,
                               IPC::Channel::MODE_SERVER,
                               &listener);
  base::ProcessHandle renderer_pid = SpawnChild("SimpleRenderer",
                                                &control_channel);

  ASSERT_TRUE(control_channel.Connect());

  MessageLoop::current()->PostDelayedTask(FROM_HERE, new MessageLoop::QuitTask,
                                          TestTimeouts::action_timeout_ms());
  MessageLoop::current()->Run();

  // The renderer should exit when we close the channel.
  control_channel.Close();

  EXPECT_TRUE(base::WaitForSingleProcess(renderer_pid,
                                         TestTimeouts::action_timeout_ms()));
}
#endif  // defined(OS_POSIX)
<commit_msg>Revert more of my change to RendererMainTest.<commit_after>// Copyright (c) 2010 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.

#include "base/compiler_specific.h"
#include "base/message_loop.h"
#include "base/process_util.h"
#include "base/test/multiprocess_test.h"
#include "base/test/test_timeouts.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/main_function_params.h"
#include "ipc/ipc_channel.h"
#include "ipc/ipc_switches.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/multiprocess_func_list.h"

// TODO(port): Bring up this test this on other platforms.
#if defined(OS_POSIX)

using base::ProcessHandle;

const char kRendererTestChannelName[] = "test";

extern int RendererMain(const MainFunctionParams& parameters);

// TODO(port): The IPC Channel tests have a class with extremely similar
// functionality, we should combine them.
class RendererMainTest : public base::MultiProcessTest {
 protected:
  RendererMainTest() {}

  // Create a new MessageLoopForIO For each test.
  virtual void SetUp();
  virtual void TearDown();

  // Spawns a child process of the specified type
  base::ProcessHandle SpawnChild(const std::string& procname,
                                 IPC::Channel* channel);

  virtual CommandLine MakeCmdLine(const std::string& procname,
                                  bool debug_on_start) OVERRIDE;

  // Created around each test instantiation.
  MessageLoopForIO *message_loop_;
};

void RendererMainTest::SetUp() {
  MultiProcessTest::SetUp();

  // Construct a fresh IO Message loop for the duration of each test.
  message_loop_ = new MessageLoopForIO();
}

void RendererMainTest::TearDown() {
  delete message_loop_;
  message_loop_ = NULL;

  MultiProcessTest::TearDown();
}

ProcessHandle RendererMainTest::SpawnChild(const std::string& procname,
                                           IPC::Channel* channel) {
  base::file_handle_mapping_vector fds_to_map;
  const int ipcfd = channel->GetClientFileDescriptor();
  if (ipcfd > -1) {
    fds_to_map.push_back(std::pair<int,int>(ipcfd, 3));
  }

  return MultiProcessTest::SpawnChild(procname, fds_to_map, false);
}

CommandLine RendererMainTest::MakeCmdLine(const std::string& procname,
                                          bool debug_on_start) {
  CommandLine command_line =
      MultiProcessTest::MakeCmdLine(procname, debug_on_start);
#if defined(USE_SECCOMP_SANDBOX)
  // Turn off seccomp for this test.  It's just a problem of refactoring,
  // not a bug.
  // http://code.google.com/p/chromium/issues/detail?id=59376
  command_line.AppendSwitch(switches::kDisableSeccompSandbox);
#endif
  return command_line;
}

// Listener class that kills the message loop when it connects.
class SuicidalListener : public IPC::Channel::Listener {
 public:
  void OnChannelConnected(int32 peer_pid) {
    MessageLoop::current()->Quit();
  }

  void OnMessageReceived(const IPC::Message& message) {
    // We shouldn't receive any messages
    ASSERT_TRUE(false);
  }
};

MULTIPROCESS_TEST_MAIN(SimpleRenderer) {
  SandboxInitWrapper dummy_sandbox_init;
  CommandLine cl(*CommandLine::ForCurrentProcess());
  cl.AppendSwitchASCII(switches::kProcessChannelID, kRendererTestChannelName);

  MainFunctionParams dummy_params(cl, dummy_sandbox_init, NULL);
  return RendererMain(dummy_params);
}

TEST_F(RendererMainTest, CreateDestroy) {
  SuicidalListener listener;
  IPC::Channel control_channel(kRendererTestChannelName,
                               IPC::Channel::MODE_SERVER,
                               &listener);
  base::ProcessHandle renderer_pid = SpawnChild("SimpleRenderer",
                                                &control_channel);

  ASSERT_TRUE(control_channel.Connect());

  MessageLoop::current()->Run();

  // The renderer should exit when we close the channel.
  control_channel.Close();

  EXPECT_TRUE(base::WaitForSingleProcess(renderer_pid,
                                         TestTimeouts::action_timeout_ms()));
}
#endif  // defined(OS_POSIX)
<|endoftext|>


<commit_before>/*
* Copyright (C) 2008-2013 The Communi Project
*
* 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.
*/

#include "commandparser.h"

CommandParser::CommandParser(QObject* parent) : IrcCommandParser(parent)
{
    connect(this, SIGNAL(commandsChanged(QStringList)), this, SIGNAL(availableCommandsChanged()));

    addCommand(IrcCommand::CtcpAction, "ACTION <target> <message...>");
    addCommand(IrcCommand::Admin, "ADMIN (<server>)");
    addCommand(IrcCommand::Away, "AWAY (<reason...>)");
    addCommand(IrcCommand::Info, "INFO (<server>)");
    addCommand(IrcCommand::Invite, "INVITE <user> (<#channel>)");
    addCommand(IrcCommand::Join, "JOIN <#channel> (<key>)");
    addCommand(IrcCommand::Kick, "KICK (<#channel>) <user> (<reason...>)");
    addCommand(IrcCommand::Knock, "KNOCK <#channel> (<message...>)");
    addCommand(IrcCommand::List, "LIST (<channels>) (<server>)");
    addCommand(IrcCommand::CtcpAction, "ME [target] <message...>");
    addCommand(IrcCommand::Mode, "MODE (<channel/user>) (<mode>) (<arg>)");
    addCommand(IrcCommand::Motd, "MOTD (<server>)");
    addCommand(IrcCommand::Names, "NAMES (<#channel>)");
    addCommand(IrcCommand::Nick, "NICK <nick>");
    addCommand(IrcCommand::Notice, "NOTICE <#channel/user> <message...>");
    addCommand(IrcCommand::Part, "PART (<#channel>) (<message...>)");
    addCommand(IrcCommand::Ping, "PING (<user>)");
    addCommand(IrcCommand::Quit, "QUIT (<message...>)");
    addCommand(IrcCommand::Quote, "QUOTE <command> (<parameters...>)");
    addCommand(IrcCommand::Stats, "STATS <query> (<server>)");
    addCommand(IrcCommand::Time, "TIME (<user>)");
    addCommand(IrcCommand::Topic, "TOPIC (<#channel>) (<topic...>)");
    addCommand(IrcCommand::Trace, "TRACE (<target>)");
    addCommand(IrcCommand::Users, "USERS (<server>)");
    addCommand(IrcCommand::Version, "VERSION (<user>)");
    addCommand(IrcCommand::Who, "WHO <user>");
    addCommand(IrcCommand::Whois, "WHOIS <user>");
    addCommand(IrcCommand::Whowas, "WHOWAS <user>");

    addCommand(IrcCommand::Custom, "CLEAR");
    addCommand(IrcCommand::Custom, "QUERY <user>");
    addCommand(IrcCommand::Custom, "MSG <user/channel> <message...>");
}

QStringList CommandParser::availableCommands() const
{
    QStringList commands = IrcCommandParser::commands();
    commands += d.aliases.keys();
    qSort(commands);
    return commands;
}

QString CommandParser::visualSyntax(const QString& command) const
{
    if (d.aliases.contains(command))
        return expandAlias(command);
    QString syntax = IrcCommandParser::syntax(command);
    return syntax.replace(QRegExp("\\[[^\\]]+\\]"), "").simplified();
}

QStringList CommandParser::suggestedCommands(const QString& command, const QStringList& params) const
{
    QStringList suggestions;
    foreach (const QString& available, availableCommands()) {
        if (!command.compare(available, Qt::CaseInsensitive) || (params.isEmpty() && available.startsWith(command, Qt::CaseInsensitive)))
            suggestions += available;
    }
    return suggestions;
}

QMap<QString, QString> CommandParser::aliases() const
{
    return d.aliases;
}

void CommandParser::setAliases(const QMap<QString, QString>& aliases)
{
    d.aliases.clear();
    QMapIterator<QString, QString> it(aliases);
    while (it.hasNext()) {
        it.next();
        d.aliases[it.key().toUpper()] = it.value();
    }
}

IrcCommand* CommandParser::parseCommand(const QString& input) const
{
    return IrcCommandParser::parse(expandAlias(input));
}

QString CommandParser::expandAlias(const QString& input) const
{
    QStringList words = input.split(QRegExp("\\s+"), QString::SkipEmptyParts);
    QString alias = words.takeFirst().toUpper();
    if (d.aliases.contains(alias)) {
        int pos = 0;
        QRegExp regExp("\\$(\\d+)");
        QString command = d.aliases.value(alias);
        while ((pos = regExp.indexIn(command)) != -1)
        {
            int index = regExp.cap(1).toInt();
            command.replace(pos, regExp.matchedLength(), words.value(index - 1));
        }
        command.replace("$*", words.join(" "));
        command.replace("$?", currentTarget());
        return command;
    }
    return input;
}
<commit_msg>Fix WHO <user> -> <mask><commit_after>/*
* Copyright (C) 2008-2013 The Communi Project
*
* 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.
*/

#include "commandparser.h"

CommandParser::CommandParser(QObject* parent) : IrcCommandParser(parent)
{
    connect(this, SIGNAL(commandsChanged(QStringList)), this, SIGNAL(availableCommandsChanged()));

    addCommand(IrcCommand::CtcpAction, "ACTION <target> <message...>");
    addCommand(IrcCommand::Admin, "ADMIN (<server>)");
    addCommand(IrcCommand::Away, "AWAY (<reason...>)");
    addCommand(IrcCommand::Info, "INFO (<server>)");
    addCommand(IrcCommand::Invite, "INVITE <user> (<#channel>)");
    addCommand(IrcCommand::Join, "JOIN <#channel> (<key>)");
    addCommand(IrcCommand::Kick, "KICK (<#channel>) <user> (<reason...>)");
    addCommand(IrcCommand::Knock, "KNOCK <#channel> (<message...>)");
    addCommand(IrcCommand::List, "LIST (<channels>) (<server>)");
    addCommand(IrcCommand::CtcpAction, "ME [target] <message...>");
    addCommand(IrcCommand::Mode, "MODE (<channel/user>) (<mode>) (<arg>)");
    addCommand(IrcCommand::Motd, "MOTD (<server>)");
    addCommand(IrcCommand::Names, "NAMES (<#channel>)");
    addCommand(IrcCommand::Nick, "NICK <nick>");
    addCommand(IrcCommand::Notice, "NOTICE <#channel/user> <message...>");
    addCommand(IrcCommand::Part, "PART (<#channel>) (<message...>)");
    addCommand(IrcCommand::Ping, "PING (<user>)");
    addCommand(IrcCommand::Quit, "QUIT (<message...>)");
    addCommand(IrcCommand::Quote, "QUOTE <command> (<parameters...>)");
    addCommand(IrcCommand::Stats, "STATS <query> (<server>)");
    addCommand(IrcCommand::Time, "TIME (<user>)");
    addCommand(IrcCommand::Topic, "TOPIC (<#channel>) (<topic...>)");
    addCommand(IrcCommand::Trace, "TRACE (<target>)");
    addCommand(IrcCommand::Users, "USERS (<server>)");
    addCommand(IrcCommand::Version, "VERSION (<user>)");
    addCommand(IrcCommand::Who, "WHO <mask>");
    addCommand(IrcCommand::Whois, "WHOIS <user>");
    addCommand(IrcCommand::Whowas, "WHOWAS <user>");

    addCommand(IrcCommand::Custom, "CLEAR");
    addCommand(IrcCommand::Custom, "QUERY <user>");
    addCommand(IrcCommand::Custom, "MSG <user/channel> <message...>");
}

QStringList CommandParser::availableCommands() const
{
    QStringList commands = IrcCommandParser::commands();
    commands += d.aliases.keys();
    qSort(commands);
    return commands;
}

QString CommandParser::visualSyntax(const QString& command) const
{
    if (d.aliases.contains(command))
        return expandAlias(command);
    QString syntax = IrcCommandParser::syntax(command);
    return syntax.replace(QRegExp("\\[[^\\]]+\\]"), "").simplified();
}

QStringList CommandParser::suggestedCommands(const QString& command, const QStringList& params) const
{
    QStringList suggestions;
    foreach (const QString& available, availableCommands()) {
        if (!command.compare(available, Qt::CaseInsensitive) || (params.isEmpty() && available.startsWith(command, Qt::CaseInsensitive)))
            suggestions += available;
    }
    return suggestions;
}

QMap<QString, QString> CommandParser::aliases() const
{
    return d.aliases;
}

void CommandParser::setAliases(const QMap<QString, QString>& aliases)
{
    d.aliases.clear();
    QMapIterator<QString, QString> it(aliases);
    while (it.hasNext()) {
        it.next();
        d.aliases[it.key().toUpper()] = it.value();
    }
}

IrcCommand* CommandParser::parseCommand(const QString& input) const
{
    return IrcCommandParser::parse(expandAlias(input));
}

QString CommandParser::expandAlias(const QString& input) const
{
    QStringList words = input.split(QRegExp("\\s+"), QString::SkipEmptyParts);
    QString alias = words.takeFirst().toUpper();
    if (d.aliases.contains(alias)) {
        int pos = 0;
        QRegExp regExp("\\$(\\d+)");
        QString command = d.aliases.value(alias);
        while ((pos = regExp.indexIn(command)) != -1)
        {
            int index = regExp.cap(1).toInt();
            command.replace(pos, regExp.matchedLength(), words.value(index - 1));
        }
        command.replace("$*", words.join(" "));
        command.replace("$?", currentTarget());
        return command;
    }
    return input;
}
<|endoftext|>


<commit_before>#include "helper.h"

#include <exiv2/exiv2.hpp>

#include <stdio.h>

#define DEFINE_STRUCT(name,wrapped_type,member_name) \
struct _##name { \
	_##name(wrapped_type member_name) \
		: member_name(member_name) {} \
	wrapped_type member_name; \
};

#define DEFINE_FREE_FUNCTION(name,type) \
void name##_free(type x) \
{ \
	delete x; \
}

DEFINE_STRUCT(Exiv2ImageFactory, Exiv2::ImageFactory*, factory);
DEFINE_STRUCT(Exiv2Image, Exiv2::Image::AutoPtr, image);
DEFINE_STRUCT(Exiv2ExifData, const Exiv2::ExifData&, data);
DEFINE_STRUCT(Exiv2ExifDatum, const Exiv2::Exifdatum&, datum);

struct _Exiv2Error {
	_Exiv2Error(const Exiv2::Error &error);

	int code;
	char *what;
};

_Exiv2Error::_Exiv2Error(const Exiv2::Error &error)
	: code(error.code())
	, what(strdup(error.what()))
{
}

Exiv2Image*
exiv2_image_factory_open(const char *path, Exiv2Error **error)
{
	Exiv2Image *p = 0;

	try {
		p = new Exiv2Image(Exiv2::ImageFactory::open(path));
		return p;
	} catch (Exiv2::Error &e) {
		delete p;

		if (error) {
			*error = new Exiv2Error(e);
		}
	}

	return 0;
}

void
exiv2_image_read_metadata(Exiv2Image *img, Exiv2Error **error)
{
	try {
		img->image->readMetadata();
	} catch (Exiv2::Error &e) {
		if (error) {
			*error = new Exiv2Error(e);
		}
	}
}

Exiv2ExifData*
exiv2_image_get_exif_data(const Exiv2Image *img)
{
	return new Exiv2ExifData(img->image->exifData());
}

DEFINE_FREE_FUNCTION(exiv2_image, Exiv2Image*);

Exiv2ExifDatum*
exiv2_exif_data_find_key(const Exiv2ExifData *data, const char *key, Exiv2Error **error)
{
	try {
		const Exiv2::ExifData::const_iterator it = data->data.findKey(Exiv2::ExifKey(key));
		if (it == data->data.end()) {
			return 0;
		}

		return new Exiv2ExifDatum(*it);
	} catch (Exiv2::Error &e) {
		if (error) {
			*error = new Exiv2Error(e);
			return 0;
		}
	}
}

DEFINE_FREE_FUNCTION(exiv2_exif_data, Exiv2ExifData*);

char*
exiv2_exif_datum_to_string(const Exiv2ExifDatum *datum)
{
	const std::string strval = datum->datum.toString();
	return strdup(strval.c_str());
}

DEFINE_FREE_FUNCTION(exiv2_exif_datum, Exiv2ExifDatum*);

int
exiv2_error_code(const Exiv2Error *error)
{
	return error->code;
}

const char*
exiv2_error_what(const Exiv2Error *error)
{
	return error->what;
}

void
exiv2_error_free(Exiv2Error *e)
{
	if (e == 0) {
		return;
	}

	free(e->what);
	delete e;
}
<commit_msg>Fix compatibility with older versions of Exiv<commit_after>#include "helper.h"

#include <exiv2/image.hpp>

#include <stdio.h>

#define DEFINE_STRUCT(name,wrapped_type,member_name) \
struct _##name { \
	_##name(wrapped_type member_name) \
		: member_name(member_name) {} \
	wrapped_type member_name; \
};

#define DEFINE_FREE_FUNCTION(name,type) \
void name##_free(type x) \
{ \
	delete x; \
}

DEFINE_STRUCT(Exiv2ImageFactory, Exiv2::ImageFactory*, factory);
DEFINE_STRUCT(Exiv2Image, Exiv2::Image::AutoPtr, image);
DEFINE_STRUCT(Exiv2ExifData, const Exiv2::ExifData&, data);
DEFINE_STRUCT(Exiv2ExifDatum, const Exiv2::Exifdatum&, datum);

struct _Exiv2Error {
	_Exiv2Error(const Exiv2::Error &error);

	int code;
	char *what;
};

_Exiv2Error::_Exiv2Error(const Exiv2::Error &error)
	: code(error.code())
	, what(strdup(error.what()))
{
}

Exiv2Image*
exiv2_image_factory_open(const char *path, Exiv2Error **error)
{
	Exiv2Image *p = 0;

	try {
		p = new Exiv2Image(Exiv2::ImageFactory::open(path));
		return p;
	} catch (Exiv2::Error &e) {
		delete p;

		if (error) {
			*error = new Exiv2Error(e);
		}
	}

	return 0;
}

void
exiv2_image_read_metadata(Exiv2Image *img, Exiv2Error **error)
{
	try {
		img->image->readMetadata();
	} catch (Exiv2::Error &e) {
		if (error) {
			*error = new Exiv2Error(e);
		}
	}
}

Exiv2ExifData*
exiv2_image_get_exif_data(const Exiv2Image *img)
{
	return new Exiv2ExifData(img->image->exifData());
}

DEFINE_FREE_FUNCTION(exiv2_image, Exiv2Image*);

Exiv2ExifDatum*
exiv2_exif_data_find_key(const Exiv2ExifData *data, const char *key, Exiv2Error **error)
{
	try {
		const Exiv2::ExifData::const_iterator it = data->data.findKey(Exiv2::ExifKey(key));
		if (it == data->data.end()) {
			return 0;
		}

		return new Exiv2ExifDatum(*it);
	} catch (Exiv2::Error &e) {
		if (error) {
			*error = new Exiv2Error(e);
			return 0;
		}
	}
}

DEFINE_FREE_FUNCTION(exiv2_exif_data, Exiv2ExifData*);

char*
exiv2_exif_datum_to_string(const Exiv2ExifDatum *datum)
{
	const std::string strval = datum->datum.toString();
	return strdup(strval.c_str());
}

DEFINE_FREE_FUNCTION(exiv2_exif_datum, Exiv2ExifDatum*);

int
exiv2_error_code(const Exiv2Error *error)
{
	return error->code;
}

const char*
exiv2_error_what(const Exiv2Error *error)
{
	return error->what;
}

void
exiv2_error_free(Exiv2Error *e)
{
	if (e == 0) {
		return;
	}

	free(e->what);
	delete e;
}
<|endoftext|>


<commit_before>// @(#)root/reflex:$Id$
// Author: Stefan Roiser 2004

// Copyright CERN, CH-1211 Geneva 23, 2004-2010, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.

#ifndef REFLEX_BUILD
# define REFLEX_BUILD
#endif

#include "ClassTemplateInstance.h"

#include "Reflex/Scope.h"

#include "TemplateInstance.h"
#include "Reflex/Tools.h"

#include <vector>
#include <string>
#include <sstream>

//-------------------------------------------------------------------------------
Reflex::ClassTemplateInstance::
ClassTemplateInstance(const char* typ,
                      size_t size,
                      const std::type_info& ti,
                      unsigned int modifiers):
   Class(typ,
         size,
         ti,
         modifiers,
         TYPETEMPLATEINSTANCE),
   TemplateInstance(Tools::GetTemplateArguments(typ)),
   fTemplateFamily(TypeTemplate()) {
//-------------------------------------------------------------------------------
// Construct a template class instance dictionary information. This constructor
// takes case of deducing the template parameter names and generates the info for
// a template family if necessary.
   Scope s = DeclaringScope();

   std::string templateName = Tools::GetTemplateName(typ);

//    for ( size_t i = 0; i < s.SubTypeTemplateSize(); ++i ) {
//       TypeTemplate ttl = s.SubTypeTemplateAt( i );
//       if ( ttl.Name(SCOPED) == templateName ) {
//          fTemplateFamily = ttl;
//          break;
//       }
//    }

   fTemplateFamily = TypeTemplate::ByName(templateName, TemplateArgumentSize());

   if (!fTemplateFamily) {
      std::vector<std::string> parameterNames = std::vector<std::string>();

      for (size_t i = 65; i < 65 + TemplateArgumentSize(); ++i) {
         parameterNames.push_back("typename " + char (i));
      }
      TypeTemplateImpl* tti = new TypeTemplateImpl(templateName.c_str(),
                                                   s,
                                                   parameterNames);
      fTemplateFamily = tti->ThisTypeTemplate();
      s.AddSubTypeTemplate(fTemplateFamily);
   }

   fTemplateFamily.AddTemplateInstance((Type) (*this));
}

//-------------------------------------------------------------------------------
std::string
Reflex::ClassTemplateInstance::Name(unsigned int mod) const {
//-------------------------------------------------------------------------------
// Return the name of the template class.
   return Class::Name(mod);
}

//-------------------------------------------------------------------------------
const char*
Reflex::ClassTemplateInstance::SimpleName(size_t& pos,
                                          unsigned int mod) const {
//-------------------------------------------------------------------------------
// Return the name of the template class.
   return Class::SimpleName(pos, mod);
}

//-------------------------------------------------------------------------------
Reflex::Type
Reflex::ClassTemplateInstance::TemplateArgumentAt(size_t nth) const {
//-------------------------------------------------------------------------------
// Return the nth template argument type.
   return TemplateInstance::TemplateArgumentAt(nth);
}
<commit_msg>Fix nasty bug discovered by Coverity (with a very valid "Note"): Overrunning static array of size 10 bytes at byte position 65 by accessing with pointer "&"typename "[(char)i]" through dereference in call to "std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const *, std::allocator<char> const &)". Note: These bugs are often difficult to see at first glance. Coverity recommends a close inspection of the events leading to this overrun.<commit_after>// @(#)root/reflex:$Id$
// Author: Stefan Roiser 2004

// Copyright CERN, CH-1211 Geneva 23, 2004-2010, All rights reserved.
//
// Permission to use, copy, modify, and distribute this software for any
// purpose is hereby granted without fee, provided that this copyright and
// permissions notice appear in all copies and derivatives.
//
// This software is provided "as is" without express or implied warranty.

#ifndef REFLEX_BUILD
# define REFLEX_BUILD
#endif

#include "ClassTemplateInstance.h"

#include "Reflex/Scope.h"

#include "TemplateInstance.h"
#include "Reflex/Tools.h"

#include <vector>
#include <string>
#include <sstream>

//-------------------------------------------------------------------------------
Reflex::ClassTemplateInstance::
ClassTemplateInstance(const char* typ,
                      size_t size,
                      const std::type_info& ti,
                      unsigned int modifiers):
   Class(typ,
         size,
         ti,
         modifiers,
         TYPETEMPLATEINSTANCE),
   TemplateInstance(Tools::GetTemplateArguments(typ)),
   fTemplateFamily(TypeTemplate()) {
//-------------------------------------------------------------------------------
// Construct a template class instance dictionary information. This constructor
// takes case of deducing the template parameter names and generates the info for
// a template family if necessary.
   Scope s = DeclaringScope();

   std::string templateName = Tools::GetTemplateName(typ);

//    for ( size_t i = 0; i < s.SubTypeTemplateSize(); ++i ) {
//       TypeTemplate ttl = s.SubTypeTemplateAt( i );
//       if ( ttl.Name(SCOPED) == templateName ) {
//          fTemplateFamily = ttl;
//          break;
//       }
//    }

   fTemplateFamily = TypeTemplate::ByName(templateName, TemplateArgumentSize());

   if (!fTemplateFamily) {
      std::vector<std::string> parameterNames = std::vector<std::string>();

      std::string typenameP("typename X");
      for (size_t i = 65; i < 65 + TemplateArgumentSize(); ++i) {
         typenameP[9] = (char) i;
         parameterNames.push_back(typenameP);
      }
      TypeTemplateImpl* tti = new TypeTemplateImpl(templateName.c_str(),
                                                   s,
                                                   parameterNames);
      fTemplateFamily = tti->ThisTypeTemplate();
      s.AddSubTypeTemplate(fTemplateFamily);
   }

   fTemplateFamily.AddTemplateInstance((Type) (*this));
}

//-------------------------------------------------------------------------------
std::string
Reflex::ClassTemplateInstance::Name(unsigned int mod) const {
//-------------------------------------------------------------------------------
// Return the name of the template class.
   return Class::Name(mod);
}

//-------------------------------------------------------------------------------
const char*
Reflex::ClassTemplateInstance::SimpleName(size_t& pos,
                                          unsigned int mod) const {
//-------------------------------------------------------------------------------
// Return the name of the template class.
   return Class::SimpleName(pos, mod);
}

//-------------------------------------------------------------------------------
Reflex::Type
Reflex::ClassTemplateInstance::TemplateArgumentAt(size_t nth) const {
//-------------------------------------------------------------------------------
// Return the nth template argument type.
   return TemplateInstance::TemplateArgumentAt(nth);
}
<|endoftext|>


<commit_before>/* fs_utils.cc
   Wolfgang Sourdeau, February 2014
   Copyright (c) 2014 Datacratic.  All rights reserved.

   A set of file-system abstraction functions intended to support common
   operations among different fs types or alikes.
*/

#include <libgen.h>
#include <unistd.h>

#include <memory>
#include <map>
#include <mutex>

#include "boost/filesystem.hpp"
#include "googleurl/src/url_util.h"

#include "fs_utils.h"
#include "jml/utils/guard.h"
#include "jml/utils/file_functions.h"
#include "jml/utils/string_functions.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

using namespace std;
using namespace Datacratic;
namespace fs = boost::filesystem;

namespace {

/* registry */

struct Registry
{
    std::mutex mutex;
    map<string, std::unique_ptr<const UrlFsHandler> > handlers;
};

Registry& getRegistry()
{
    static Registry* registry = new Registry;
    return *registry;
}

} // file scope

namespace Datacratic {

/* LOCALURLFSHANDLER */

static FsObjectInfo extractInfo(const struct stat & stats)
{
    FsObjectInfo objectInfo;

    objectInfo.exists = true;
    objectInfo.lastModified = Date::fromTimespec(stats.st_mtim);
    objectInfo.size = stats.st_size;
    objectInfo.etag = ML::format("%d-%d-%d",
                                 stats.st_ino, stats.st_mtime,
                                 stats.st_blocks);

    return objectInfo;
}

struct LocalUrlFsHandler : public UrlFsHandler {

    virtual FsObjectInfo getInfo(const Url & url) const
    {
        struct stat stats;
        string path = url.path();

        // cerr << "fs info on path: " + path + "\n";
        int res = ::stat(path.c_str(), &stats);
        if (res == -1) {
            if (errno == ENOENT) {
                return FsObjectInfo();
            }
            throw ML::Exception(errno, "stat");
        }

        // TODO: owner ID (uid) and name (uname)

        return extractInfo(stats);
    }

    virtual FsObjectInfo tryGetInfo(const Url & url) const
    {
        struct stat stats;
        string path = url.path();

        // cerr << "fs info on path: " + path + "\n";
        int res = ::stat(path.c_str(), &stats);
        if (res == -1) {
            return FsObjectInfo();
        }

        return extractInfo(stats);
    }

    virtual void makeDirectory(const Url & url) const
    {
        boost::system::error_code ec;
        string path = url.path();
        if (!fs::exists(path) && !fs::create_directories(path, ec)) {
            if (!fs::exists(path)) {
                throw ML::Exception("could not create directory ("
                                    + ec.message() + "): "
                                    + url.toString());
            }
        }
    }

    virtual bool erase(const Url & url, bool throwException) const
    {
        string path = url.path();
        int res = ::unlink(path.c_str());
        if (res == -1) {
            if (throwException) {
                throw ML::Exception(errno, "unlink");
            }
            else return false;
        }
        return true;
    }

    virtual bool forEach(const Url & prefix,
                         const OnUriObject & onObject,
                         const OnUriSubdir & onSubdir,
                         const std::string & delimiter,
                         const std::string & startAt) const
    {
        using namespace ML;

        if (startAt != "")
            throw ML::Exception("not implemented: startAt for local files");
        if (delimiter != "/")
            throw ML::Exception("not implemented: delimiters other than '/' "
                                "for local files");

        bool result = true;
        auto onFileFound = [&] (const std::string & dir,
                                const std::string & basename,
                                const struct stat & stats,
                                FileType type,
                                int depth) -> ML::FileAction
            {
                if (type == FT_FILE) {
                    result = onObject(dir + "/" + basename,
                                      extractInfo(stats),
                                      depth);
                    if (!result)
                        return FA_STOP;
                    else return FA_CONTINUE;
                }
                else if (type == FT_DIR) {
                    if (!onSubdir)
                        return FA_CONTINUE;
                    else if (onSubdir(dir + "/" + basename,
                                      depth))
                        return FA_CONTINUE;
                    else return FA_SKIP_SUBTREE;
                }
                else return FA_CONTINUE;
            };

        scanFiles(prefix.path(), onFileFound, -1);

        return result;
    }
};

const UrlFsHandler * findFsHandler(const string & scheme)
{
    auto& registry = getRegistry();

    std::unique_lock<std::mutex> guard(registry.mutex);
    auto handler = registry.handlers.find(scheme);
    if (handler == registry.handlers.end()) {
        throw ML::Exception("no handler found for scheme: " + scheme);
    }
    return handler->second.get();
}

struct AtInit {
    AtInit() {
        registerUrlFsHandler("file", new LocalUrlFsHandler());
    }
} atInit;

/* ensures that local filenames are represented as urls */
Url makeUrl(const string & urlStr)
{
    if (urlStr.empty())
        throw ML::Exception("can't makeUrl on empty url");

    /* scheme is specified */
    if (urlStr.find("://") != string::npos) {
        return Url(urlStr);
    }
    /* absolute local filenames */
    else if (urlStr[0] == '/') {
        return Url("file://" + urlStr);
    }
    /* relative filenames */
    else {
        char cCurDir[PATH_MAX + 1];
        string filename(getcwd(cCurDir, sizeof(cCurDir)));
        filename += "/" + urlStr;

        return Url("file://" + filename);
    }
}

}

namespace Datacratic {

/* URLFSHANDLER */

size_t
UrlFsHandler::
getSize(const Url & url) const
{
    return getInfo(url).size;
}

string
UrlFsHandler::
getEtag(const Url & url) const
{
    return getInfo(url).etag;
}

/* registry */

void registerUrlFsHandler(const std::string & scheme,
                          UrlFsHandler * handler)
{
    auto& registry = getRegistry();

    if (registry.handlers.find(scheme) != registry.handlers.end()) {
        throw ML::Exception("fs handler already registered");
    }

    /* this enables googleuri to parse our urls properly */
    url_util::AddStandardScheme(scheme.c_str());

    registry.handlers[scheme].reset(handler);
}

FsObjectInfo
tryGetUriObjectInfo(const std::string & url)
{
    Url realUrl = makeUrl(url);
    return findFsHandler(realUrl.scheme())->tryGetInfo(realUrl);
}

FsObjectInfo
getUriObjectInfo(const std::string & url)
{
    Url realUrl = makeUrl(url);
    return findFsHandler(realUrl.scheme())->getInfo(realUrl);
}

size_t
getUriSize(const std::string & url)
{
    Url realUrl = makeUrl(url);
    return findFsHandler(realUrl.scheme())->getSize(realUrl);
}

std::string
getUriEtag(const std::string & url)
{
    Url realUrl = makeUrl(url);
    return findFsHandler(realUrl.scheme())->getEtag(realUrl);
}

void
makeUriDirectory(const std::string & url)
{
    string dirUrl(url);
    size_t slashIdx = dirUrl.rfind('/');
    if (slashIdx == string::npos) {
        throw ML::Exception("makeUriDirectory cannot work on filenames: instead of " + url + " you should probably write file://" + url);
    }
    dirUrl.resize(slashIdx);

    // cerr << "url: " + url + "/dirUrl: " + dirUrl + "\n";

    Url realUrl = makeUrl(dirUrl);
    findFsHandler(realUrl.scheme())->makeDirectory(realUrl);
}

bool
eraseUriObject(const std::string & url, bool throwException)
{
    Url realUrl = makeUrl(url);
    return findFsHandler(realUrl.scheme())->erase(realUrl, throwException);
}

bool
tryEraseUriObject(const std::string & uri)
{
    return eraseUriObject(uri, false);
}

bool forEachUriObject(const std::string & urlPrefix,
                      const OnUriObject & onObject,
                      const OnUriSubdir & onSubdir,
                      const std::string & delimiter,
                      const std::string & startAt)
{
    Url realUrl = makeUrl(urlPrefix);
    return findFsHandler(realUrl.scheme())
        ->forEach(realUrl, onObject, onSubdir, delimiter, startAt);
}

string
baseName(const std::string & filename)
{
    char *fnCopy = ::strdup(filename.c_str());
    ML::Call_Guard guard([&] {
        ::free(fnCopy);
    });
    char *dirNameC = ::basename(fnCopy);
    string dirname(dirNameC);

    return dirname;
}

string
dirName(const std::string & filename)
{
    char *fnCopy = ::strdup(filename.c_str());
    ML::Call_Guard guard([&] {
        ::free(fnCopy);
    });
    char *dirNameC = ::dirname(fnCopy);
    string dirname(dirNameC);

    return dirname;
}

string
getCurrentWorkingDirectory()
{
    char cwd[PATH_MAX];
    char * cwdPtr = ::getcwd(cwd, PATH_MAX - 1);
    if (!cwdPtr) {
        throw ML::Exception(errno, "getcwd");
    }

    return string(cwdPtr);
}

/****************************************************************************/
/* FILE COMMITER                                                            */
/****************************************************************************/

FileCommiter::
~FileCommiter()
{
    if (!commited_) {
        tryEraseUriObject(fileUrl_);
    }
}

} // namespace Datacratic
<commit_msg>fs_utils.cc: wrap the Registry ptr in a std::unique_ptr<commit_after>/* fs_utils.cc
   Wolfgang Sourdeau, February 2014
   Copyright (c) 2014 Datacratic.  All rights reserved.

   A set of file-system abstraction functions intended to support common
   operations among different fs types or alikes.
*/

#include <libgen.h>
#include <unistd.h>

#include <memory>
#include <map>
#include <mutex>

#include "boost/filesystem.hpp"
#include "googleurl/src/url_util.h"

#include "fs_utils.h"
#include "jml/utils/guard.h"
#include "jml/utils/file_functions.h"
#include "jml/utils/string_functions.h"

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

using namespace std;
using namespace Datacratic;
namespace fs = boost::filesystem;

namespace {

/* registry */

struct Registry
{
    std::mutex mutex;
    map<string, std::unique_ptr<const UrlFsHandler> > handlers;
};

Registry & getRegistry()
{
    static std::unique_ptr<Registry> registry(new Registry());
    return *registry;
}

} // file scope

namespace Datacratic {

/* LOCALURLFSHANDLER */

static FsObjectInfo extractInfo(const struct stat & stats)
{
    FsObjectInfo objectInfo;

    objectInfo.exists = true;
    objectInfo.lastModified = Date::fromTimespec(stats.st_mtim);
    objectInfo.size = stats.st_size;
    objectInfo.etag = ML::format("%d-%d-%d",
                                 stats.st_ino, stats.st_mtime,
                                 stats.st_blocks);

    return objectInfo;
}

struct LocalUrlFsHandler : public UrlFsHandler {

    virtual FsObjectInfo getInfo(const Url & url) const
    {
        struct stat stats;
        string path = url.path();

        // cerr << "fs info on path: " + path + "\n";
        int res = ::stat(path.c_str(), &stats);
        if (res == -1) {
            if (errno == ENOENT) {
                return FsObjectInfo();
            }
            throw ML::Exception(errno, "stat");
        }

        // TODO: owner ID (uid) and name (uname)

        return extractInfo(stats);
    }

    virtual FsObjectInfo tryGetInfo(const Url & url) const
    {
        struct stat stats;
        string path = url.path();

        // cerr << "fs info on path: " + path + "\n";
        int res = ::stat(path.c_str(), &stats);
        if (res == -1) {
            return FsObjectInfo();
        }

        return extractInfo(stats);
    }

    virtual void makeDirectory(const Url & url) const
    {
        boost::system::error_code ec;
        string path = url.path();
        if (!fs::exists(path) && !fs::create_directories(path, ec)) {
            if (!fs::exists(path)) {
                throw ML::Exception("could not create directory ("
                                    + ec.message() + "): "
                                    + url.toString());
            }
        }
    }

    virtual bool erase(const Url & url, bool throwException) const
    {
        string path = url.path();
        int res = ::unlink(path.c_str());
        if (res == -1) {
            if (throwException) {
                throw ML::Exception(errno, "unlink");
            }
            else return false;
        }
        return true;
    }

    virtual bool forEach(const Url & prefix,
                         const OnUriObject & onObject,
                         const OnUriSubdir & onSubdir,
                         const std::string & delimiter,
                         const std::string & startAt) const
    {
        using namespace ML;

        if (startAt != "")
            throw ML::Exception("not implemented: startAt for local files");
        if (delimiter != "/")
            throw ML::Exception("not implemented: delimiters other than '/' "
                                "for local files");

        bool result = true;
        auto onFileFound = [&] (const std::string & dir,
                                const std::string & basename,
                                const struct stat & stats,
                                FileType type,
                                int depth) -> ML::FileAction
            {
                if (type == FT_FILE) {
                    result = onObject(dir + "/" + basename,
                                      extractInfo(stats),
                                      depth);
                    if (!result)
                        return FA_STOP;
                    else return FA_CONTINUE;
                }
                else if (type == FT_DIR) {
                    if (!onSubdir)
                        return FA_CONTINUE;
                    else if (onSubdir(dir + "/" + basename,
                                      depth))
                        return FA_CONTINUE;
                    else return FA_SKIP_SUBTREE;
                }
                else return FA_CONTINUE;
            };

        scanFiles(prefix.path(), onFileFound, -1);

        return result;
    }
};

const UrlFsHandler * findFsHandler(const string & scheme)
{
    auto& registry = getRegistry();

    std::unique_lock<std::mutex> guard(registry.mutex);
    auto handler = registry.handlers.find(scheme);
    if (handler == registry.handlers.end()) {
        throw ML::Exception("no handler found for scheme: " + scheme);
    }
    return handler->second.get();
}

struct AtInit {
    AtInit() {
        registerUrlFsHandler("file", new LocalUrlFsHandler());
    }
} atInit;

/* ensures that local filenames are represented as urls */
Url makeUrl(const string & urlStr)
{
    if (urlStr.empty())
        throw ML::Exception("can't makeUrl on empty url");

    /* scheme is specified */
    if (urlStr.find("://") != string::npos) {
        return Url(urlStr);
    }
    /* absolute local filenames */
    else if (urlStr[0] == '/') {
        return Url("file://" + urlStr);
    }
    /* relative filenames */
    else {
        char cCurDir[PATH_MAX + 1];
        string filename(getcwd(cCurDir, sizeof(cCurDir)));
        filename += "/" + urlStr;

        return Url("file://" + filename);
    }
}

}

namespace Datacratic {

/* URLFSHANDLER */

size_t
UrlFsHandler::
getSize(const Url & url) const
{
    return getInfo(url).size;
}

string
UrlFsHandler::
getEtag(const Url & url) const
{
    return getInfo(url).etag;
}

/* registry */

void registerUrlFsHandler(const std::string & scheme,
                          UrlFsHandler * handler)
{
    auto& registry = getRegistry();

    if (registry.handlers.find(scheme) != registry.handlers.end()) {
        throw ML::Exception("fs handler already registered");
    }

    /* this enables googleuri to parse our urls properly */
    url_util::AddStandardScheme(scheme.c_str());

    registry.handlers[scheme].reset(handler);
}

FsObjectInfo
tryGetUriObjectInfo(const std::string & url)
{
    Url realUrl = makeUrl(url);
    return findFsHandler(realUrl.scheme())->tryGetInfo(realUrl);
}

FsObjectInfo
getUriObjectInfo(const std::string & url)
{
    Url realUrl = makeUrl(url);
    return findFsHandler(realUrl.scheme())->getInfo(realUrl);
}

size_t
getUriSize(const std::string & url)
{
    Url realUrl = makeUrl(url);
    return findFsHandler(realUrl.scheme())->getSize(realUrl);
}

std::string
getUriEtag(const std::string & url)
{
    Url realUrl = makeUrl(url);
    return findFsHandler(realUrl.scheme())->getEtag(realUrl);
}

void
makeUriDirectory(const std::string & url)
{
    string dirUrl(url);
    size_t slashIdx = dirUrl.rfind('/');
    if (slashIdx == string::npos) {
        throw ML::Exception("makeUriDirectory cannot work on filenames: instead of " + url + " you should probably write file://" + url);
    }
    dirUrl.resize(slashIdx);

    // cerr << "url: " + url + "/dirUrl: " + dirUrl + "\n";

    Url realUrl = makeUrl(dirUrl);
    findFsHandler(realUrl.scheme())->makeDirectory(realUrl);
}

bool
eraseUriObject(const std::string & url, bool throwException)
{
    Url realUrl = makeUrl(url);
    return findFsHandler(realUrl.scheme())->erase(realUrl, throwException);
}

bool
tryEraseUriObject(const std::string & uri)
{
    return eraseUriObject(uri, false);
}

bool forEachUriObject(const std::string & urlPrefix,
                      const OnUriObject & onObject,
                      const OnUriSubdir & onSubdir,
                      const std::string & delimiter,
                      const std::string & startAt)
{
    Url realUrl = makeUrl(urlPrefix);
    return findFsHandler(realUrl.scheme())
        ->forEach(realUrl, onObject, onSubdir, delimiter, startAt);
}

string
baseName(const std::string & filename)
{
    char *fnCopy = ::strdup(filename.c_str());
    ML::Call_Guard guard([&] {
        ::free(fnCopy);
    });
    char *dirNameC = ::basename(fnCopy);
    string dirname(dirNameC);

    return dirname;
}

string
dirName(const std::string & filename)
{
    char *fnCopy = ::strdup(filename.c_str());
    ML::Call_Guard guard([&] {
        ::free(fnCopy);
    });
    char *dirNameC = ::dirname(fnCopy);
    string dirname(dirNameC);

    return dirname;
}

string
getCurrentWorkingDirectory()
{
    char cwd[PATH_MAX];
    char * cwdPtr = ::getcwd(cwd, PATH_MAX - 1);
    if (!cwdPtr) {
        throw ML::Exception(errno, "getcwd");
    }

    return string(cwdPtr);
}

/****************************************************************************/
/* FILE COMMITER                                                            */
/****************************************************************************/

FileCommiter::
~FileCommiter()
{
    if (!commited_) {
        tryEraseUriObject(fileUrl_);
    }
}

} // namespace Datacratic
<|endoftext|>


<commit_before><commit_msg>When the resource bundle is not available, the UI font family and the UI font size should follow the OS settings. <commit_after><|endoftext|>