<commit_before>/*************************************************************************
 *
 *  $RCSfile: numrule.hxx,v $
 *
 *  $Revision: 1.16 $
 *
 *  last change: $Author: kz $ $Date: 2004-06-11 15:21:07 $
 *
 *  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 _NUMRULE_HXX
#define _NUMRULE_HXX

#ifndef _LINK_HXX //autogen
#include <tools/link.hxx>
#endif
#ifndef _SV_GEN_HXX //autogen wg. Size
#include <tools/gen.hxx>
#endif
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _SVX_SVXENUM_HXX //autogen
#include <svx/svxenum.hxx>
#endif

#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _CALBCK_HXX
#include <calbck.hxx>
#endif
#ifndef _ERRHDL_HXX
#include <errhdl.hxx>       // Fuer die inline-ASSERTs
#endif
#ifndef _SWERROR_H
#include <error.h>          // Fuer die inline-ASSERTs
#endif
#ifndef _SVX_NUMITEM_HXX
#include <svx/numitem.hxx>
#endif

#include <SwBitArray.hxx> // #i27615#

class Font;
class SvxBrushItem;
class SvxNumRule;
class SwCharFmt;
class SwDoc;
class SwFmtVertOrient;
class SwNodeNum;
class SwTxtNode;

extern char __FAR_DATA sOutlineStr[];   // SWG-Filter

BYTE GetRealLevel( const BYTE nLvl );

BOOL IsNum( BYTE nLvl );

BOOL IsShowNum( BYTE nLvl );

void SetNoNum( BYTE * nLvl, BOOL nVal = TRUE );

const sal_Unicode cBulletChar   = 0x2022;   // Charakter fuer Aufzaehlungen

class SwNumFmt : public SvxNumberFormat, public SwClient
{
    SwFmtVertOrient* pVertOrient;

    void UpdateNumNodes( SwDoc* pDoc );
    virtual void NotifyGraphicArrived();
public:
    SwNumFmt();
    SwNumFmt( const SwNumFmt& );
    SwNumFmt( const SvxNumberFormat&, SwDoc* pDoc);

    virtual ~SwNumFmt();

    SwNumFmt& operator=( const SwNumFmt& );
    BOOL operator==( const SwNumFmt& ) const;
    BOOL operator!=( const SwNumFmt& r ) const { return !(*this == r); }

    const Graphic* GetGraphic() const;

    SwCharFmt* GetCharFmt() const { return (SwCharFmt*)pRegisteredIn; }
    void SetCharFmt( SwCharFmt* );
    virtual void Modify( SfxPoolItem* pOld, SfxPoolItem* pNew );

    virtual void            SetCharFmtName(const String& rSet);
    virtual const String&   GetCharFmtName()const;

    virtual void    SetGraphicBrush( const SvxBrushItem* pBrushItem, const Size* pSize = 0, const SvxFrameVertOrient* pOrient = 0);

    virtual void                SetVertOrient(SvxFrameVertOrient eSet);
    virtual SvxFrameVertOrient  GetVertOrient() const;
    const SwFmtVertOrient*      GetGraphicOrientation() const;

    BOOL IsEnumeration() const; // #i22362#
    BOOL IsItemize() const; // #i29560#
};

enum SwNumRuleType { OUTLINE_RULE = 0, NUM_RULE = 1, RULE_END = 2 };
class SwNumRule
{
    friend void _FinitCore();

    static SwNumFmt* aBaseFmts [ RULE_END ][ MAXLEVEL ];
    static USHORT aDefNumIndents[ MAXLEVEL ];
    static USHORT nRefCount;
    static Font* pDefBulletFont;
    static char* pDefOutlineName;

    SwNumFmt* aFmts[ MAXLEVEL ];

    /**
       marked levels
     */
    SwBitArray aMarkedLevels;

    String sName;
    SwNumRuleType eRuleType;
    USHORT nPoolFmtId;      // Id-fuer "automatich" erzeugte NumRules
    USHORT nPoolHelpId;     // HelpId fuer diese Pool-Vorlage
    BYTE nPoolHlpFileId;    // FilePos ans Doc auf die Vorlagen-Hilfen
    BOOL bAutoRuleFlag : 1;
    BOOL bInvalidRuleFlag : 1;
    BOOL bContinusNum : 1;  // Fortlaufende Numerierung - ohne Ebenen
    BOOL bAbsSpaces : 1;    // die Ebenen repraesentieren absol. Einzuege

    static void _MakeDefBulletFont();

public:
    SwNumRule( const String& rNm, SwNumRuleType = NUM_RULE,
                BOOL bAutoFlg = TRUE );

    SwNumRule( const SwNumRule& );
    ~SwNumRule();

    SwNumRule& operator=( const SwNumRule& );
    BOOL operator==( const SwNumRule& ) const;
    BOOL operator!=( const SwNumRule& r ) const { return !(*this == r); }

    const SwNumFmt* GetNumFmt( USHORT i ) const;
    const SwNumFmt& Get( USHORT i ) const;

    void Set( USHORT i, const SwNumFmt* );
    void Set( USHORT i, const SwNumFmt& );
    String MakeNumString( const SwNodeNum&, BOOL bInclStrings = TRUE,
                            BOOL bOnlyArabic = FALSE ) const;

    sal_Unicode GetBulletChar( const SwNodeNum& ) const;
    const Font* GetBulletFont( const SwNodeNum& ) const;
    static const Font& GetDefBulletFont();

    static char* GetOutlineRuleName() { return pDefOutlineName; }

    static USHORT GetNumIndent( BYTE nLvl );
    static USHORT GetBullIndent( BYTE nLvl );

    SwNumRuleType GetRuleType() const           { return eRuleType; }
    void SetRuleType( SwNumRuleType eNew )      { eRuleType = eNew;
                                                  bInvalidRuleFlag = TRUE; }

    // eine Art Copy-Constructor, damit die Num-Formate auch an den
    // richtigen CharFormaten eines Dokumentes haengen !!
    // (Kopiert die NumFormate und returnt sich selbst)
    SwNumRule& CopyNumRule( SwDoc*, const SwNumRule& );

    // testet ob die CharFormate aus dem angegeben Doc sind und kopiert
    // die gegebenfalls
    void CheckCharFmts( SwDoc* pDoc );

    // test ob der Einzug von dieser Numerierung kommt.
    BOOL IsRuleLSpace( SwTxtNode& rNd ) const;

    const String& GetName() const       { return sName; }
    void SetName( const String& rNm )   { sName = rNm; }

    BOOL IsAutoRule() const             { return bAutoRuleFlag; }
    void SetAutoRule( BOOL bFlag )      { bAutoRuleFlag = bFlag; }

    BOOL IsInvalidRule() const          { return bInvalidRuleFlag; }
    void SetInvalidRule( BOOL bFlag )   { bInvalidRuleFlag = bFlag; }

    BOOL IsContinusNum() const          { return bContinusNum; }
    void SetContinusNum( BOOL bFlag )   { bContinusNum = bFlag; }

    BOOL IsAbsSpaces() const            { return bAbsSpaces; }
    void SetAbsSpaces( BOOL bFlag )     { bAbsSpaces = bFlag; }

    // #115901#
    BOOL IsOutlineRule() const { return eRuleType == OUTLINE_RULE; }

    // erfragen und setzen der Poolvorlagen-Id's
    USHORT GetPoolFmtId() const         { return nPoolFmtId; }
    void SetPoolFmtId( USHORT nId )     { nPoolFmtId = nId; }

    // erfragen und setzen der Hilfe-Id's fuer die Document-Vorlagen
    USHORT GetPoolHelpId() const        { return nPoolHelpId; }
    void SetPoolHelpId( USHORT nId )    { nPoolHelpId = nId; }
    BYTE GetPoolHlpFileId() const       { return nPoolHlpFileId; }
    void SetPoolHlpFileId( BYTE nId )   { nPoolHlpFileId = nId; }

    /**
        #109308# Sets adjustment in all formats of the numbering rule.

        @param eNum adjustment to be set
    */
    void SetNumAdjust(SvxAdjust eNum);

    void        SetSvxRule(const SvxNumRule&, SwDoc* pDoc);
    SvxNumRule  MakeSvxNumRule() const;

    // -> #i27615#
    /**
       Returns if a level is marked.

       @param nLvl     level to check

       @retval TRUE    level is marked
       @retval FALSE   level is not marked
    */
    BOOL IsLevelMarked(BYTE nLvl) const { return aMarkedLevels.Get(nLvl); }

    /**
       Mark/unmark a level.

       @param nLvl     level to mark/unmark
       @param bVal     - TRUE    mark
                       - FALSE   unmark

       @return bit array in which the altered levels are marked.
    */
    SwBitArray SetLevelMarked(BYTE nLvl, BOOL bVal);

    /**
       Unmarks all levels.
    */
    void ResetMarkedLevels() { aMarkedLevels.Reset(); }
    // <- #i27615#
    // #i23726#, #i23725#
    void        Indent(short aAmount, int nLevel = -1,
                       int nReferenceLevel = -1, BOOL bRelative = TRUE,
                       BOOL bFirstLine = TRUE, BOOL bCheckGtZero = TRUE);
};

class SwNodeNum
{
    USHORT nLevelVal[ MAXLEVEL ];       // Nummern aller Levels
    USHORT nSetValue;                   // vorgegeben Nummer
    BYTE nMyLevel;                      // akt. Level
    BOOL bStartNum;                     // Numerierung neu starten
    BOOL bContNum;                      // #111955#
                                        // TRUE -> in continuous numbering

public:
    SwNodeNum( BYTE nLevel = NO_NUMBERING, USHORT nSetVal = USHRT_MAX );
    SwNodeNum& operator=( const SwNodeNum& rCpy );

    BOOL operator==( const SwNodeNum& ) const;

    BYTE GetLevel() const                   { return nMyLevel; }
    void SetLevel( BYTE nVal )              { nMyLevel = nVal; }

    BOOL IsStart() const                    { return bStartNum; }
    void SetStart( BOOL bFlag = TRUE )      { bStartNum = bFlag; }

    // -> #111955#
    BOOL IsContinuousNum() const { return bContNum; }
    void SetContinuousNum( BOOL bFlag = TRUE ) { bContNum = bFlag; }
    // <- #111955#

    BOOL HasSetValue() const { return USHRT_MAX != nSetValue; }
    USHORT GetSetValue() const              { return nSetValue; }
    void SetSetValue( USHORT nVal )         { nSetValue = nVal; }

    const USHORT* GetLevelVal() const       { return nLevelVal; }
          USHORT* GetLevelVal()             { return nLevelVal; }

    BYTE GetRealLevel() const { return ::GetRealLevel(nMyLevel); }
    BOOL IsNum() const { return ::IsNum(nMyLevel); }
    BOOL IsShowNum() const { return ::IsShowNum(nMyLevel); }

    void SetNoNum(BOOL nVal = TRUE)
    {
        nMyLevel = nVal ? nMyLevel | NO_NUMLEVEL : nMyLevel & ~NO_NUMLEVEL;
    }

};

#endif  // _NUMRULE_HXX
<commit_msg>INTEGRATION: CWS tune05 (1.16.12); FILE MERGED 2004/07/20 15:49:17 cmc 1.16.12.2: #i30554# unused GetBulletFoo varients (ran it by hb) 2004/06/25 13:20:57 cmc 1.16.12.1: #i30554# SwNumRule::IsRuleLSpace should be inside appropiate #ifndef<commit_after>/*************************************************************************
 *
 *  $RCSfile: numrule.hxx,v $
 *
 *  $Revision: 1.17 $
 *
 *  last change: $Author: obo $ $Date: 2004-08-12 12:04:49 $
 *
 *  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 _NUMRULE_HXX
#define _NUMRULE_HXX

#ifndef _LINK_HXX //autogen
#include <tools/link.hxx>
#endif
#ifndef _SV_GEN_HXX //autogen wg. Size
#include <tools/gen.hxx>
#endif
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _SVX_SVXENUM_HXX //autogen
#include <svx/svxenum.hxx>
#endif

#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _CALBCK_HXX
#include <calbck.hxx>
#endif
#ifndef _ERRHDL_HXX
#include <errhdl.hxx>       // Fuer die inline-ASSERTs
#endif
#ifndef _SWERROR_H
#include <error.h>          // Fuer die inline-ASSERTs
#endif
#ifndef _SVX_NUMITEM_HXX
#include <svx/numitem.hxx>
#endif

#include <SwBitArray.hxx> // #i27615#

class Font;
class SvxBrushItem;
class SvxNumRule;
class SwCharFmt;
class SwDoc;
class SwFmtVertOrient;
class SwNodeNum;
class SwTxtNode;

extern char __FAR_DATA sOutlineStr[];   // SWG-Filter

BYTE GetRealLevel( const BYTE nLvl );

BOOL IsNum( BYTE nLvl );

BOOL IsShowNum( BYTE nLvl );

void SetNoNum( BYTE * nLvl, BOOL nVal = TRUE );

const sal_Unicode cBulletChar   = 0x2022;   // Charakter fuer Aufzaehlungen

class SwNumFmt : public SvxNumberFormat, public SwClient
{
    SwFmtVertOrient* pVertOrient;

    void UpdateNumNodes( SwDoc* pDoc );
    virtual void NotifyGraphicArrived();
public:
    SwNumFmt();
    SwNumFmt( const SwNumFmt& );
    SwNumFmt( const SvxNumberFormat&, SwDoc* pDoc);

    virtual ~SwNumFmt();

    SwNumFmt& operator=( const SwNumFmt& );
    BOOL operator==( const SwNumFmt& ) const;
    BOOL operator!=( const SwNumFmt& r ) const { return !(*this == r); }

    const Graphic* GetGraphic() const;

    SwCharFmt* GetCharFmt() const { return (SwCharFmt*)pRegisteredIn; }
    void SetCharFmt( SwCharFmt* );
    virtual void Modify( SfxPoolItem* pOld, SfxPoolItem* pNew );

    virtual void            SetCharFmtName(const String& rSet);
    virtual const String&   GetCharFmtName()const;

    virtual void    SetGraphicBrush( const SvxBrushItem* pBrushItem, const Size* pSize = 0, const SvxFrameVertOrient* pOrient = 0);

    virtual void                SetVertOrient(SvxFrameVertOrient eSet);
    virtual SvxFrameVertOrient  GetVertOrient() const;
    const SwFmtVertOrient*      GetGraphicOrientation() const;

    BOOL IsEnumeration() const; // #i22362#
    BOOL IsItemize() const; // #i29560#
};

enum SwNumRuleType { OUTLINE_RULE = 0, NUM_RULE = 1, RULE_END = 2 };
class SwNumRule
{
    friend void _FinitCore();

    static SwNumFmt* aBaseFmts [ RULE_END ][ MAXLEVEL ];
    static USHORT aDefNumIndents[ MAXLEVEL ];
    static USHORT nRefCount;
    static Font* pDefBulletFont;
    static char* pDefOutlineName;

    SwNumFmt* aFmts[ MAXLEVEL ];

    /**
       marked levels
     */
    SwBitArray aMarkedLevels;

    String sName;
    SwNumRuleType eRuleType;
    USHORT nPoolFmtId;      // Id-fuer "automatich" erzeugte NumRules
    USHORT nPoolHelpId;     // HelpId fuer diese Pool-Vorlage
    BYTE nPoolHlpFileId;    // FilePos ans Doc auf die Vorlagen-Hilfen
    BOOL bAutoRuleFlag : 1;
    BOOL bInvalidRuleFlag : 1;
    BOOL bContinusNum : 1;  // Fortlaufende Numerierung - ohne Ebenen
    BOOL bAbsSpaces : 1;    // die Ebenen repraesentieren absol. Einzuege

    static void _MakeDefBulletFont();

public:
    SwNumRule( const String& rNm, SwNumRuleType = NUM_RULE,
                BOOL bAutoFlg = TRUE );

    SwNumRule( const SwNumRule& );
    ~SwNumRule();

    SwNumRule& operator=( const SwNumRule& );
    BOOL operator==( const SwNumRule& ) const;
    BOOL operator!=( const SwNumRule& r ) const { return !(*this == r); }

    const SwNumFmt* GetNumFmt( USHORT i ) const;
    const SwNumFmt& Get( USHORT i ) const;

    void Set( USHORT i, const SwNumFmt* );
    void Set( USHORT i, const SwNumFmt& );
    String MakeNumString( const SwNodeNum&, BOOL bInclStrings = TRUE,
                            BOOL bOnlyArabic = FALSE ) const;

    static const Font& GetDefBulletFont();

    static char* GetOutlineRuleName() { return pDefOutlineName; }

    static USHORT GetNumIndent( BYTE nLvl );
    static USHORT GetBullIndent( BYTE nLvl );

    SwNumRuleType GetRuleType() const           { return eRuleType; }
    void SetRuleType( SwNumRuleType eNew )      { eRuleType = eNew;
                                                  bInvalidRuleFlag = TRUE; }

    // eine Art Copy-Constructor, damit die Num-Formate auch an den
    // richtigen CharFormaten eines Dokumentes haengen !!
    // (Kopiert die NumFormate und returnt sich selbst)
    SwNumRule& CopyNumRule( SwDoc*, const SwNumRule& );

    // testet ob die CharFormate aus dem angegeben Doc sind und kopiert
    // die gegebenfalls
    void CheckCharFmts( SwDoc* pDoc );

#ifndef NUM_RELSPACE
    // test ob der Einzug von dieser Numerierung kommt.
    BOOL IsRuleLSpace( SwTxtNode& rNd ) const;
#endif

    const String& GetName() const       { return sName; }
    void SetName( const String& rNm )   { sName = rNm; }

    BOOL IsAutoRule() const             { return bAutoRuleFlag; }
    void SetAutoRule( BOOL bFlag )      { bAutoRuleFlag = bFlag; }

    BOOL IsInvalidRule() const          { return bInvalidRuleFlag; }
    void SetInvalidRule( BOOL bFlag )   { bInvalidRuleFlag = bFlag; }

    BOOL IsContinusNum() const          { return bContinusNum; }
    void SetContinusNum( BOOL bFlag )   { bContinusNum = bFlag; }

    BOOL IsAbsSpaces() const            { return bAbsSpaces; }
    void SetAbsSpaces( BOOL bFlag )     { bAbsSpaces = bFlag; }

    // #115901#
    BOOL IsOutlineRule() const { return eRuleType == OUTLINE_RULE; }

    // erfragen und setzen der Poolvorlagen-Id's
    USHORT GetPoolFmtId() const         { return nPoolFmtId; }
    void SetPoolFmtId( USHORT nId )     { nPoolFmtId = nId; }

    // erfragen und setzen der Hilfe-Id's fuer die Document-Vorlagen
    USHORT GetPoolHelpId() const        { return nPoolHelpId; }
    void SetPoolHelpId( USHORT nId )    { nPoolHelpId = nId; }
    BYTE GetPoolHlpFileId() const       { return nPoolHlpFileId; }
    void SetPoolHlpFileId( BYTE nId )   { nPoolHlpFileId = nId; }

    /**
        #109308# Sets adjustment in all formats of the numbering rule.

        @param eNum adjustment to be set
    */
    void SetNumAdjust(SvxAdjust eNum);

    void        SetSvxRule(const SvxNumRule&, SwDoc* pDoc);
    SvxNumRule  MakeSvxNumRule() const;

    // -> #i27615#
    /**
       Returns if a level is marked.

       @param nLvl     level to check

       @retval TRUE    level is marked
       @retval FALSE   level is not marked
    */
    BOOL IsLevelMarked(BYTE nLvl) const { return aMarkedLevels.Get(nLvl); }

    /**
       Mark/unmark a level.

       @param nLvl     level to mark/unmark
       @param bVal     - TRUE    mark
                       - FALSE   unmark

       @return bit array in which the altered levels are marked.
    */
    SwBitArray SetLevelMarked(BYTE nLvl, BOOL bVal);

    /**
       Unmarks all levels.
    */
    void ResetMarkedLevels() { aMarkedLevels.Reset(); }
    // <- #i27615#
    // #i23726#, #i23725#
    void        Indent(short aAmount, int nLevel = -1,
                       int nReferenceLevel = -1, BOOL bRelative = TRUE,
                       BOOL bFirstLine = TRUE, BOOL bCheckGtZero = TRUE);
};

class SwNodeNum
{
    USHORT nLevelVal[ MAXLEVEL ];       // Nummern aller Levels
    USHORT nSetValue;                   // vorgegeben Nummer
    BYTE nMyLevel;                      // akt. Level
    BOOL bStartNum;                     // Numerierung neu starten
    BOOL bContNum;                      // #111955#
                                        // TRUE -> in continuous numbering

public:
    SwNodeNum( BYTE nLevel = NO_NUMBERING, USHORT nSetVal = USHRT_MAX );
    SwNodeNum& operator=( const SwNodeNum& rCpy );

    BOOL operator==( const SwNodeNum& ) const;

    BYTE GetLevel() const                   { return nMyLevel; }
    void SetLevel( BYTE nVal )              { nMyLevel = nVal; }

    BOOL IsStart() const                    { return bStartNum; }
    void SetStart( BOOL bFlag = TRUE )      { bStartNum = bFlag; }

    // -> #111955#
    BOOL IsContinuousNum() const { return bContNum; }
    void SetContinuousNum( BOOL bFlag = TRUE ) { bContNum = bFlag; }
    // <- #111955#

    BOOL HasSetValue() const { return USHRT_MAX != nSetValue; }
    USHORT GetSetValue() const              { return nSetValue; }
    void SetSetValue( USHORT nVal )         { nSetValue = nVal; }

    const USHORT* GetLevelVal() const       { return nLevelVal; }
          USHORT* GetLevelVal()             { return nLevelVal; }

    BYTE GetRealLevel() const { return ::GetRealLevel(nMyLevel); }
    BOOL IsNum() const { return ::IsNum(nMyLevel); }
    BOOL IsShowNum() const { return ::IsShowNum(nMyLevel); }

    void SetNoNum(BOOL nVal = TRUE)
    {
        nMyLevel = nVal ? nMyLevel | NO_NUMLEVEL : nMyLevel & ~NO_NUMLEVEL;
    }

};

#endif  // _NUMRULE_HXX
<|endoftext|>


<commit_before>/*
 *  This program is a dummy C++ program to ensure Mbed TLS library header files
 *  can be included and built with a C++ compiler.
 *
 *  Copyright The Mbed TLS Contributors
 *  SPDX-License-Identifier: Apache-2.0
 *
 *  Licensed under the Apache License, Version 2.0 (the "License"); you may
 *  not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif

#include "mbedtls/aes.h"
#include "mbedtls/aesni.h"
#include "mbedtls/arc4.h"
#include "mbedtls/aria.h"
#include "mbedtls/asn1.h"
#include "mbedtls/asn1write.h"
#include "mbedtls/base64.h"
#include "mbedtls/bignum.h"
#include "mbedtls/blowfish.h"
#include "mbedtls/bn_mul.h"
#include "mbedtls/camellia.h"
#include "mbedtls/ccm.h"
#include "mbedtls/certs.h"
#include "mbedtls/chacha20.h"
#include "mbedtls/chachapoly.h"
#include "mbedtls/check_config.h"
#include "mbedtls/cipher.h"
#include "mbedtls/cipher_internal.h"
#include "mbedtls/cmac.h"
#include "mbedtls/compat-1.3.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/debug.h"
#include "mbedtls/des.h"
#include "mbedtls/dhm.h"
#include "mbedtls/ecdh.h"
#include "mbedtls/ecdsa.h"
#include "mbedtls/ecjpake.h"
#include "mbedtls/ecp.h"
#include "mbedtls/ecp_internal.h"
#include "mbedtls/entropy.h"
#include "mbedtls/entropy_poll.h"
#include "mbedtls/error.h"
#include "mbedtls/gcm.h"
#include "mbedtls/havege.h"
#include "mbedtls/hkdf.h"
#include "mbedtls/hmac_drbg.h"
#include "mbedtls/md.h"
#include "mbedtls/md2.h"
#include "mbedtls/md4.h"
#include "mbedtls/md5.h"
#include "mbedtls/md_internal.h"
#include "mbedtls/net.h"
#include "mbedtls/net_sockets.h"
#include "mbedtls/nist_kw.h"
#include "mbedtls/oid.h"
#include "mbedtls/padlock.h"
#include "mbedtls/pem.h"
#include "mbedtls/pk.h"
#include "mbedtls/pk_internal.h"
#include "mbedtls/pkcs11.h"
#include "mbedtls/pkcs12.h"
#include "mbedtls/pkcs5.h"
#include "mbedtls/platform_time.h"
#include "mbedtls/platform_util.h"
#include "mbedtls/poly1305.h"
#include "mbedtls/psa_util.h"
#include "mbedtls/ripemd160.h"
#include "mbedtls/rsa.h"
#include "mbedtls/rsa_internal.h"
#include "mbedtls/sha1.h"
#include "mbedtls/sha256.h"
#include "mbedtls/sha512.h"
#include "mbedtls/ssl.h"
#include "mbedtls/ssl_cache.h"
#include "mbedtls/ssl_ciphersuites.h"
#include "mbedtls/ssl_cookie.h"
#include "mbedtls/ssl_internal.h"
#include "mbedtls/ssl_ticket.h"
#include "mbedtls/threading.h"
#include "mbedtls/timing.h"
#include "mbedtls/version.h"
#include "mbedtls/x509.h"
#include "mbedtls/x509_crl.h"
#include "mbedtls/x509_crt.h"
#include "mbedtls/x509_csr.h"
#include "mbedtls/xtea.h"

#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#endif

#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
#include "mbedtls/memory_buffer_alloc.h"
#endif

int main()
{
    mbedtls_platform_context *ctx = NULL;
    mbedtls_platform_setup(ctx);
    mbedtls_printf("CPP Build test\n");
    mbedtls_platform_teardown(ctx);
}
<commit_msg>Include public and public-ish PSA headers in CPP check<commit_after>/*
 *  This program is a dummy C++ program to ensure Mbed TLS library header files
 *  can be included and built with a C++ compiler.
 *
 *  Copyright The Mbed TLS Contributors
 *  SPDX-License-Identifier: Apache-2.0
 *
 *  Licensed under the Apache License, Version 2.0 (the "License"); you may
 *  not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif

#include "mbedtls/aes.h"
#include "mbedtls/aesni.h"
#include "mbedtls/arc4.h"
#include "mbedtls/aria.h"
#include "mbedtls/asn1.h"
#include "mbedtls/asn1write.h"
#include "mbedtls/base64.h"
#include "mbedtls/bignum.h"
#include "mbedtls/blowfish.h"
#include "mbedtls/bn_mul.h"
#include "mbedtls/camellia.h"
#include "mbedtls/ccm.h"
#include "mbedtls/certs.h"
#include "mbedtls/chacha20.h"
#include "mbedtls/chachapoly.h"
#include "mbedtls/check_config.h"
#include "mbedtls/cipher.h"
#include "mbedtls/cipher_internal.h"
#include "mbedtls/cmac.h"
#include "mbedtls/compat-1.3.h"
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/debug.h"
#include "mbedtls/des.h"
#include "mbedtls/dhm.h"
#include "mbedtls/ecdh.h"
#include "mbedtls/ecdsa.h"
#include "mbedtls/ecjpake.h"
#include "mbedtls/ecp.h"
#include "mbedtls/ecp_internal.h"
#include "mbedtls/entropy.h"
#include "mbedtls/entropy_poll.h"
#include "mbedtls/error.h"
#include "mbedtls/gcm.h"
#include "mbedtls/havege.h"
#include "mbedtls/hkdf.h"
#include "mbedtls/hmac_drbg.h"
#include "mbedtls/md.h"
#include "mbedtls/md2.h"
#include "mbedtls/md4.h"
#include "mbedtls/md5.h"
#include "mbedtls/md_internal.h"
#include "mbedtls/net.h"
#include "mbedtls/net_sockets.h"
#include "mbedtls/nist_kw.h"
#include "mbedtls/oid.h"
#include "mbedtls/padlock.h"
#include "mbedtls/pem.h"
#include "mbedtls/pk.h"
#include "mbedtls/pk_internal.h"
#include "mbedtls/pkcs11.h"
#include "mbedtls/pkcs12.h"
#include "mbedtls/pkcs5.h"
#include "mbedtls/platform_time.h"
#include "mbedtls/platform_util.h"
#include "mbedtls/poly1305.h"
#include "mbedtls/psa_util.h"
#include "mbedtls/ripemd160.h"
#include "mbedtls/rsa.h"
#include "mbedtls/rsa_internal.h"
#include "mbedtls/sha1.h"
#include "mbedtls/sha256.h"
#include "mbedtls/sha512.h"
#include "mbedtls/ssl.h"
#include "mbedtls/ssl_cache.h"
#include "mbedtls/ssl_ciphersuites.h"
#include "mbedtls/ssl_cookie.h"
#include "mbedtls/ssl_internal.h"
#include "mbedtls/ssl_ticket.h"
#include "mbedtls/threading.h"
#include "mbedtls/timing.h"
#include "mbedtls/version.h"
#include "mbedtls/x509.h"
#include "mbedtls/x509_crl.h"
#include "mbedtls/x509_crt.h"
#include "mbedtls/x509_csr.h"
#include "mbedtls/xtea.h"

#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#endif

#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
#include "mbedtls/memory_buffer_alloc.h"
#endif

#include "psa/crypto.h"
#include "psa/crypto_se_driver.h"
#include "psa/crypto_entropy_driver.h"
#include "psa/crypto_accel_driver.h"
#include "../library/psa_crypto_its.h"

int main()
{
    mbedtls_platform_context *ctx = NULL;
    mbedtls_platform_setup(ctx);
    mbedtls_printf("CPP Build test\n");
    mbedtls_platform_teardown(ctx);
}
<|endoftext|>


<commit_before>#include "core/argparse.h"

#include "core/image.h"
#include "core/imagefilters.h"
#include "core/palette_all.h"

#include "core/io.h"

#include <iostream>
#include <sstream>
#include <iomanip>

using namespace euphoria::core;

int
main(int argc, char* argv[])
{
    Image image;

    auto parser = argparse::Parser {"Apply filters to images"};

    auto io_subs = parser.AddSubParsers("transfer image to/from disk");

    io_subs->Add
    (
        "open", "Load image from disk",
        [&](argparse::SubParser* sub)
        {
            std::string input;
            parser.Add("input", &input).Help("The image to apply filters to");
            return sub->OnComplete
            (
                [&]
                {
                    auto file = io::FileToChunk(input);
                    if(file == nullptr)
                    {
                        std::cerr << "Failed to open image file: '" << input << "'\n";
                        return argparse::ParseResult::Error;
                    }
                    auto ret = LoadImage(file, input, AlphaLoad::Keep);
                    if(!ret.error.empty())
                    {
                        std::cerr << ret.error << "\n";
                        return argparse::ParseResult::Error;
                    }
                    else
                    {
                        image = ret.image;
                        return argparse::ParseResult::Ok;
                    }
                }
            );
        }
    );

    io_subs->Add
    (
        "save", "Write image to disk",
        [&](argparse::SubParser* sub)
        {
            std::string output = "ret.png";
            parser.Add("-o, --output", &output).Help
            (
                "Where to write the resulting image"
            );
            return sub->OnComplete
            (
                [&]
                {
                    io::ChunkToFile(image.Write(ImageWriteFormat::PNG), output);
                    return argparse::ParseResult::Ok;
                }
            );

        }
    );

    auto filters_subs = parser.AddSubParsers("apply filter to current image");

    filters_subs->Add
    (
        "grayscale", "Apply grayscale",
        [&](argparse::SubParser* sub)
        {
            Grayscale grayscale = Grayscale::Average;
            sub->Add("-g,--grayscale", &grayscale);
            return sub->OnComplete
            (
                [&]
                {
                    MakeGrayscale(&image, grayscale);
                    return argparse::ParseResult::Ok;
                }
            );

        }
    );

    filters_subs->Add
    (
        "palswap", "Switch palette",
        [&](argparse::SubParser* sub)
        {
            palette::PaletteName palette = palette::PaletteName::OneBit;
            bool pal_dither = false;

            sub->Add("-p, --palette", &palette);
            sub->SetTrue("-d, --dither", &pal_dither);

            return sub->OnComplete
            (
                [&]
                {
                    if(pal_dither)
                    {
                        MatchPaletteDither(&image, palette::GetPalette(palette));
                    }
                    else
                    {
                        MatchPalette(&image, palette::GetPalette(palette));
                    }
                    return argparse::ParseResult::Ok;
                }
            );

        }
    );

    filters_subs->Add
    (
        "edge", "Edge detection",
        [&](argparse::SubParser* sub)
        {
            float edge_r = 0.5f;
            sub->Add("-r, --range", &edge_r);
            return sub->OnComplete
            (
                [&]
                {
                    EdgeDetection(&image, edge_r);
                    return argparse::ParseResult::Ok;
                }
            );
        }
    );

    filters_subs->Add
    (
        "color", "Detect colors",
        [&](argparse::SubParser* sub)
        {
            float edge_r = 0.5f;
            auto color_color = Color::Red;
            sub->Add("-r, --range", &edge_r);
            sub->Add("-c, --color", &color_color);
            return sub->OnComplete
            (
                [&]
                {
                    ColorDetection(&image, color_color, edge_r);
                    return argparse::ParseResult::Ok;
                }
            );
        }
    );

    filters_subs->Add
    (
        "bright", "Change brightness",
        [&](argparse::SubParser* sub)
        {
            int bright_c = 10;
            sub->Add("-c, --change", &bright_c);
            return sub->OnComplete
            (
                [&]
                {
                    ChangeBrightness(&image, bright_c);
                    return argparse::ParseResult::Ok;
                }
            );
        }
    );

    filters_subs->Add
    (
        "contrast", "Change contrast",
        [&](argparse::SubParser* sub)
        {
            float contrast = 10;
            sub->Add("-c, --change", &contrast);
            return sub->OnComplete
            (
                [&]
                {
                    ChangeContrast(&image, contrast);
                    return argparse::ParseResult::Ok;
                }
            );
        }
    );

    return argparse::ParseFromMain(&parser, argc, argv);
}
<commit_msg>adding console arguments to the correct sub<commit_after>#include "core/argparse.h"

#include "core/image.h"
#include "core/imagefilters.h"
#include "core/palette_all.h"

#include "core/io.h"

#include <iostream>
#include <sstream>
#include <iomanip>

using namespace euphoria::core;

int
main(int argc, char* argv[])
{
    Image image;

    auto parser = argparse::Parser {"Apply filters to images"};

    auto io_subs = parser.AddSubParsers("transfer image to/from disk");

    io_subs->Add
    (
        "open", "Load image from disk",
        [&](argparse::SubParser* sub)
        {
            std::string input;
            sub->Add("input", &input).Help("The image to apply filters to");
            return sub->OnComplete
            (
                [&]
                {
                    auto file = io::FileToChunk(input);
                    if(file == nullptr)
                    {
                        std::cerr << "Failed to open image file: '" << input << "'\n";
                        return argparse::ParseResult::Error;
                    }
                    auto ret = LoadImage(file, input, AlphaLoad::Keep);
                    if(!ret.error.empty())
                    {
                        std::cerr << ret.error << "\n";
                        return argparse::ParseResult::Error;
                    }
                    else
                    {
                        image = ret.image;
                        return argparse::ParseResult::Ok;
                    }
                }
            );
        }
    );

    io_subs->Add
    (
        "save", "Write image to disk",
        [&](argparse::SubParser* sub)
        {
            std::string output = "ret.png";
            sub->Add("-o, --output", &output).Help
            (
                "Where to write the resulting image"
            );
            return sub->OnComplete
            (
                [&]
                {
                    io::ChunkToFile(image.Write(ImageWriteFormat::PNG), output);
                    return argparse::ParseResult::Ok;
                }
            );

        }
    );

    auto filters_subs = parser.AddSubParsers("apply filter to current image");

    filters_subs->Add
    (
        "grayscale", "Apply grayscale",
        [&](argparse::SubParser* sub)
        {
            Grayscale grayscale = Grayscale::Average;
            sub->Add("-g,--grayscale", &grayscale);
            return sub->OnComplete
            (
                [&]
                {
                    MakeGrayscale(&image, grayscale);
                    return argparse::ParseResult::Ok;
                }
            );

        }
    );

    filters_subs->Add
    (
        "palswap", "Switch palette",
        [&](argparse::SubParser* sub)
        {
            palette::PaletteName palette = palette::PaletteName::OneBit;
            bool pal_dither = false;

            sub->Add("-p, --palette", &palette);
            sub->SetTrue("-d, --dither", &pal_dither);

            return sub->OnComplete
            (
                [&]
                {
                    if(pal_dither)
                    {
                        MatchPaletteDither(&image, palette::GetPalette(palette));
                    }
                    else
                    {
                        MatchPalette(&image, palette::GetPalette(palette));
                    }
                    return argparse::ParseResult::Ok;
                }
            );

        }
    );

    filters_subs->Add
    (
        "edge", "Edge detection",
        [&](argparse::SubParser* sub)
        {
            float edge_r = 0.5f;
            sub->Add("-r, --range", &edge_r);
            return sub->OnComplete
            (
                [&]
                {
                    EdgeDetection(&image, edge_r);
                    return argparse::ParseResult::Ok;
                }
            );
        }
    );

    filters_subs->Add
    (
        "color", "Detect colors",
        [&](argparse::SubParser* sub)
        {
            float edge_r = 0.5f;
            auto color_color = Color::Red;
            sub->Add("-r, --range", &edge_r);
            sub->Add("-c, --color", &color_color);
            return sub->OnComplete
            (
                [&]
                {
                    ColorDetection(&image, color_color, edge_r);
                    return argparse::ParseResult::Ok;
                }
            );
        }
    );

    filters_subs->Add
    (
        "bright", "Change brightness",
        [&](argparse::SubParser* sub)
        {
            int bright_c = 10;
            sub->Add("-c, --change", &bright_c);
            return sub->OnComplete
            (
                [&]
                {
                    ChangeBrightness(&image, bright_c);
                    return argparse::ParseResult::Ok;
                }
            );
        }
    );

    filters_subs->Add
    (
        "contrast", "Change contrast",
        [&](argparse::SubParser* sub)
        {
            float contrast = 10;
            sub->Add("-c, --change", &contrast);
            return sub->OnComplete
            (
                [&]
                {
                    ChangeContrast(&image, contrast);
                    return argparse::ParseResult::Ok;
                }
            );
        }
    );

    return argparse::ParseFromMain(&parser, argc, argv);
}
<|endoftext|>


<commit_before>/*
  This file is part of Ingen.
  Copyright 2007-2015 David Robillard <http://drobilla.net/>

  Ingen is free software: you can redistribute it and/or modify it under the
  terms of the GNU Affero General Public License as published by the Free
  Software Foundation, either version 3 of the License, or any later version.

  Ingen 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 Affero General Public License for details.

  You should have received a copy of the GNU Affero General Public License
  along with Ingen.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <utility>

#include "ingen/Atom.hpp"
#include "ingen/Store.hpp"
#include "ingen/URIMap.hpp"
#include "ingen/URIs.hpp"
#include "raul/Array.hpp"
#include "raul/Path.hpp"

#include "Broadcaster.hpp"
#include "BufferFactory.hpp"
#include "CreatePort.hpp"
#include "Driver.hpp"
#include "DuplexPort.hpp"
#include "Engine.hpp"
#include "GraphImpl.hpp"
#include "PortImpl.hpp"

namespace Ingen {
namespace Server {
namespace Events {

CreatePort::CreatePort(Engine&                     engine,
                       SPtr<Interface>             client,
                       int32_t                     id,
                       SampleCount                 timestamp,
                       const Raul::Path&           path,
                       bool                        is_output,
                       const Resource::Properties& properties)
	: Event(engine, client, id, timestamp)
	, _path(path)
	, _port_type(PortType::UNKNOWN)
	, _buf_type(0)
	, _graph(NULL)
	, _graph_port(NULL)
	, _ports_array(NULL)
	, _old_ports_array(NULL)
	, _engine_port(NULL)
	, _properties(properties)
	, _is_output(is_output)
{
	const Ingen::URIs& uris = _engine.world()->uris();

	typedef Resource::Properties::const_iterator Iterator;
	typedef std::pair<Iterator, Iterator>        Range;

	const Range types = properties.equal_range(uris.rdf_type);
	for (Iterator i = types.first; i != types.second; ++i) {
		const Atom& type = i->second;
		if (type == uris.lv2_AudioPort) {
			_port_type = PortType::AUDIO;
		} else if (type == uris.lv2_ControlPort) {
			_port_type = PortType::CONTROL;
		} else if (type == uris.lv2_CVPort) {
			_port_type = PortType::CV;
		} else if (type == uris.atom_AtomPort) {
			_port_type = PortType::ATOM;
		}
	}

	const Range buffer_types = properties.equal_range(uris.atom_bufferType);
	for (Iterator i = buffer_types.first; i != buffer_types.second; ++i) {
		if (uris.forge.is_uri(i->second)) {
			_buf_type = _engine.world()->uri_map().map_uri(
				uris.forge.str(i->second, false));
		}
	}
}

bool
CreatePort::pre_process()
{
	if (_port_type == PortType::UNKNOWN) {
		return Event::pre_process_done(Status::UNKNOWN_TYPE, _path);
	} else if (_path.is_root()) {
		return Event::pre_process_done(Status::BAD_URI, _path);
	} else if (_engine.store()->get(_path)) {
		return Event::pre_process_done(_status, _path);
	}

	const Raul::Path parent_path = _path.parent();
	Node* const      parent      = _engine.store()->get(parent_path);
	if (!parent) {
		return Event::pre_process_done(Status::PARENT_NOT_FOUND, parent_path);
	} else if (!(_graph = dynamic_cast<GraphImpl*>(parent))) {
		return Event::pre_process_done(Status::INVALID_PARENT, parent_path);
	}

	const URIs&    uris        = _engine.world()->uris();
	BufferFactory& bufs        = *_engine.buffer_factory();
	const uint32_t buf_size    = bufs.default_size(_buf_type);
	const int32_t  old_n_ports = _graph->num_ports_non_rt();

	typedef Resource::Properties::const_iterator PropIter;

	PropIter index_i = _properties.find(uris.lv2_index);
	if (index_i == _properties.end()) {
		// No index given, append
		index_i = _properties.insert(
			std::make_pair(uris.lv2_index,
			               _engine.world()->forge().make(old_n_ports)));
	} else if (index_i->second.type() != uris.forge.Int ||
	           index_i->second.get<int32_t>() != old_n_ports) {
		return Event::pre_process_done(Status::BAD_INDEX, _path);
	}

	const PropIter poly_i = _properties.find(uris.ingen_polyphonic);
	const bool polyphonic = (poly_i != _properties.end() &&
	                         poly_i->second.type() == uris.forge.Bool &&
	                         poly_i->second.get<int32_t>());

	// Create 0 value if the port requires one
	Atom value;
	if (_port_type == PortType::CONTROL || _port_type == PortType::CV) {
		value = bufs.forge().make(0.0f);
	}

	// Create port
	_graph_port = new DuplexPort(bufs, _graph, Raul::Symbol(_path.symbol()),
	                             _graph->num_ports_non_rt(),
	                             polyphonic,
	                             _port_type, _buf_type, buf_size,
	                             value, _is_output);

	_graph_port->properties().insert(_properties.begin(), _properties.end());

	_engine.store()->add(_graph_port);
	if (_is_output) {
		_graph->add_output(*_graph_port);
	} else {
		_graph->add_input(*_graph_port);
	}

	if (!_graph->parent()) {
		_engine_port = _engine.driver()->create_port(_graph_port);
	}

	_ports_array = new Raul::Array<PortImpl*>(old_n_ports + 1, NULL);
	_update      = _graph_port->properties();

	assert(_graph_port->index() == (uint32_t)index_i->second.get<int32_t>());
	assert(_graph->num_ports_non_rt() == (uint32_t)old_n_ports + 1);
	assert(_graph_port->index() == (uint32_t)old_n_ports);
	assert(_ports_array->size() == _graph->num_ports_non_rt());
	assert(_graph_port->index() < _ports_array->size());
	return Event::pre_process_done(Status::SUCCESS);
}

void
CreatePort::execute(ProcessContext& context)
{
	if (_status == Status::SUCCESS) {
		_old_ports_array = _graph->external_ports();
		if (_old_ports_array) {
			for (uint32_t i = 0; i < _old_ports_array->size(); ++i) {
				(*_ports_array)[i] = (*_old_ports_array)[i];
			}
		}
		assert(!(*_ports_array)[_graph_port->index()]);
		(*_ports_array)[_graph_port->index()] = _graph_port;
		_graph->external_ports(_ports_array);

		if (_engine_port) {
			_engine.driver()->add_port(context, _engine_port);
		}
	}
}

void
CreatePort::post_process()
{
	Broadcaster::Transfer t(*_engine.broadcaster());
	if (respond() == Status::SUCCESS) {
		_engine.broadcaster()->put(Node::path_to_uri(_path), _update);
	}

	delete _old_ports_array;
}

} // namespace Events
} // namespace Server
} // namespace Ingen
<commit_msg>Fix status code when port exists<commit_after>/*
  This file is part of Ingen.
  Copyright 2007-2015 David Robillard <http://drobilla.net/>

  Ingen is free software: you can redistribute it and/or modify it under the
  terms of the GNU Affero General Public License as published by the Free
  Software Foundation, either version 3 of the License, or any later version.

  Ingen 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 Affero General Public License for details.

  You should have received a copy of the GNU Affero General Public License
  along with Ingen.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <utility>

#include "ingen/Atom.hpp"
#include "ingen/Store.hpp"
#include "ingen/URIMap.hpp"
#include "ingen/URIs.hpp"
#include "raul/Array.hpp"
#include "raul/Path.hpp"

#include "Broadcaster.hpp"
#include "BufferFactory.hpp"
#include "CreatePort.hpp"
#include "Driver.hpp"
#include "DuplexPort.hpp"
#include "Engine.hpp"
#include "GraphImpl.hpp"
#include "PortImpl.hpp"

namespace Ingen {
namespace Server {
namespace Events {

CreatePort::CreatePort(Engine&                     engine,
                       SPtr<Interface>             client,
                       int32_t                     id,
                       SampleCount                 timestamp,
                       const Raul::Path&           path,
                       bool                        is_output,
                       const Resource::Properties& properties)
	: Event(engine, client, id, timestamp)
	, _path(path)
	, _port_type(PortType::UNKNOWN)
	, _buf_type(0)
	, _graph(NULL)
	, _graph_port(NULL)
	, _ports_array(NULL)
	, _old_ports_array(NULL)
	, _engine_port(NULL)
	, _properties(properties)
	, _is_output(is_output)
{
	const Ingen::URIs& uris = _engine.world()->uris();

	typedef Resource::Properties::const_iterator Iterator;
	typedef std::pair<Iterator, Iterator>        Range;

	const Range types = properties.equal_range(uris.rdf_type);
	for (Iterator i = types.first; i != types.second; ++i) {
		const Atom& type = i->second;
		if (type == uris.lv2_AudioPort) {
			_port_type = PortType::AUDIO;
		} else if (type == uris.lv2_ControlPort) {
			_port_type = PortType::CONTROL;
		} else if (type == uris.lv2_CVPort) {
			_port_type = PortType::CV;
		} else if (type == uris.atom_AtomPort) {
			_port_type = PortType::ATOM;
		}
	}

	const Range buffer_types = properties.equal_range(uris.atom_bufferType);
	for (Iterator i = buffer_types.first; i != buffer_types.second; ++i) {
		if (uris.forge.is_uri(i->second)) {
			_buf_type = _engine.world()->uri_map().map_uri(
				uris.forge.str(i->second, false));
		}
	}
}

bool
CreatePort::pre_process()
{
	if (_port_type == PortType::UNKNOWN) {
		return Event::pre_process_done(Status::UNKNOWN_TYPE, _path);
	} else if (_path.is_root()) {
		return Event::pre_process_done(Status::BAD_URI, _path);
	} else if (_engine.store()->get(_path)) {
		return Event::pre_process_done(Status::EXISTS, _path);
	}

	const Raul::Path parent_path = _path.parent();
	Node* const      parent      = _engine.store()->get(parent_path);
	if (!parent) {
		return Event::pre_process_done(Status::PARENT_NOT_FOUND, parent_path);
	} else if (!(_graph = dynamic_cast<GraphImpl*>(parent))) {
		return Event::pre_process_done(Status::INVALID_PARENT, parent_path);
	}

	const URIs&    uris        = _engine.world()->uris();
	BufferFactory& bufs        = *_engine.buffer_factory();
	const uint32_t buf_size    = bufs.default_size(_buf_type);
	const int32_t  old_n_ports = _graph->num_ports_non_rt();

	typedef Resource::Properties::const_iterator PropIter;

	PropIter index_i = _properties.find(uris.lv2_index);
	if (index_i == _properties.end()) {
		// No index given, append
		index_i = _properties.insert(
			std::make_pair(uris.lv2_index,
			               _engine.world()->forge().make(old_n_ports)));
	} else if (index_i->second.type() != uris.forge.Int ||
	           index_i->second.get<int32_t>() != old_n_ports) {
		return Event::pre_process_done(Status::BAD_INDEX, _path);
	}

	const PropIter poly_i = _properties.find(uris.ingen_polyphonic);
	const bool polyphonic = (poly_i != _properties.end() &&
	                         poly_i->second.type() == uris.forge.Bool &&
	                         poly_i->second.get<int32_t>());

	// Create 0 value if the port requires one
	Atom value;
	if (_port_type == PortType::CONTROL || _port_type == PortType::CV) {
		value = bufs.forge().make(0.0f);
	}

	// Create port
	_graph_port = new DuplexPort(bufs, _graph, Raul::Symbol(_path.symbol()),
	                             _graph->num_ports_non_rt(),
	                             polyphonic,
	                             _port_type, _buf_type, buf_size,
	                             value, _is_output);

	_graph_port->properties().insert(_properties.begin(), _properties.end());

	_engine.store()->add(_graph_port);
	if (_is_output) {
		_graph->add_output(*_graph_port);
	} else {
		_graph->add_input(*_graph_port);
	}

	if (!_graph->parent()) {
		_engine_port = _engine.driver()->create_port(_graph_port);
	}

	_ports_array = new Raul::Array<PortImpl*>(old_n_ports + 1, NULL);
	_update      = _graph_port->properties();

	assert(_graph_port->index() == (uint32_t)index_i->second.get<int32_t>());
	assert(_graph->num_ports_non_rt() == (uint32_t)old_n_ports + 1);
	assert(_graph_port->index() == (uint32_t)old_n_ports);
	assert(_ports_array->size() == _graph->num_ports_non_rt());
	assert(_graph_port->index() < _ports_array->size());
	return Event::pre_process_done(Status::SUCCESS);
}

void
CreatePort::execute(ProcessContext& context)
{
	if (_status == Status::SUCCESS) {
		_old_ports_array = _graph->external_ports();
		if (_old_ports_array) {
			for (uint32_t i = 0; i < _old_ports_array->size(); ++i) {
				(*_ports_array)[i] = (*_old_ports_array)[i];
			}
		}
		assert(!(*_ports_array)[_graph_port->index()]);
		(*_ports_array)[_graph_port->index()] = _graph_port;
		_graph->external_ports(_ports_array);

		if (_engine_port) {
			_engine.driver()->add_port(context, _engine_port);
		}
	}
}

void
CreatePort::post_process()
{
	Broadcaster::Transfer t(*_engine.broadcaster());
	if (respond() == Status::SUCCESS) {
		_engine.broadcaster()->put(Node::path_to_uri(_path), _update);
	}

	delete _old_ports_array;
}

} // namespace Events
} // namespace Server
} // namespace Ingen
<|endoftext|>


<commit_before>/*
 * 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 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 1999-2009 Soeren Sonnenburg
 * Written (W) 1999-2008 Gunnar Raetsch
 * Subset support written (W) 2011 Heiko Strathmann
 * Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society
 */

#include <shogun/features/Features.h>
#include <shogun/preprocessor/Preprocessor.h>
#include <shogun/io/SGIO.h>
#include <shogun/base/Parameter.h>

#include <string.h>

using namespace shogun;

CFeatures::CFeatures(int32_t size)
: CSGObject()
{
	init();
	cache_size = size;
}

CFeatures::CFeatures(const CFeatures& orig)
: CSGObject(orig)
{
	init();

	preproc = orig.preproc;
	num_preproc = orig.num_preproc;

	preprocessed=SG_MALLOC(bool, orig.num_preproc);
	memcpy(preprocessed, orig.preprocessed, sizeof(bool)*orig.num_preproc);
}

CFeatures::CFeatures(CFile* loader)
: CSGObject()
{
	init();

	load(loader);
	SG_INFO("Feature object loaded (%p)\n",this) ;
}

CFeatures::~CFeatures()
{
	clean_preprocessors();
	SG_UNREF(m_active_subset);
	SG_UNREF(m_subset_stack);
}

void
CFeatures::init()
{
	SG_ADD(&properties, "properties", "Feature properties", MS_NOT_AVAILABLE);
	SG_ADD(&cache_size, "cache_size", "Size of cache in MB", MS_NOT_AVAILABLE);

	/* TODO, use SGVector for arrays to be able to use SG_ADD macro */
	m_parameters->add_vector((CSGObject***) &preproc, &num_preproc, "preproc",
			"List of preprocessors");
	m_parameters->add_vector(&preprocessed, &num_preproc, "preprocessed",
			"Feature[i] is already preprocessed");

	SG_ADD((CSGObject**)&m_active_subset, "active_subset", "Subset object",
			MS_NOT_AVAILABLE);

	SG_ADD((CSGObject**)&m_subset_stack, "subset_stack",
			"Stack of subsets of indices", MS_NOT_AVAILABLE);

	m_subset_stack=new CList(true);
	SG_REF(m_subset_stack);

	m_active_subset=NULL;
	properties = FP_NONE;
	cache_size = 0;
	preproc = NULL;
	num_preproc = 0;
	preprocessed = NULL;
}

/// set preprocessor
int32_t CFeatures::add_preprocessor(CPreprocessor* p)
{
	SG_INFO( "%d preprocs currently, new preproc list is\n", num_preproc);
	ASSERT(p);

	bool* preprocd=SG_MALLOC(bool, num_preproc+1);
	CPreprocessor** pps=SG_MALLOC(CPreprocessor*, num_preproc+1);
	for (int32_t i=0; i<num_preproc; i++)
	{
		pps[i]=preproc[i];
		preprocd[i]=preprocessed[i];
	}
	SG_FREE(preproc);
	SG_FREE(preprocessed);
	preproc=pps;
	preprocessed=preprocd;
	preproc[num_preproc]=p;
	preprocessed[num_preproc]=false;

	num_preproc++;

	for (int32_t i=0; i<num_preproc; i++)
		SG_INFO( "preproc[%d]=%s %ld\n",i, preproc[i]->get_name(), preproc[i]) ;

	SG_REF(p);

	return num_preproc;
}

/// get current preprocessor
CPreprocessor* CFeatures::get_preprocessor(int32_t num)
{
	if (num<num_preproc)
	{
		SG_REF(preproc[num]);
		return preproc[num];
	}
	else
		return NULL;
}

/// get whether specified preprocessor (or all if num=1) was/were already applied
int32_t CFeatures::get_num_preprocessed()
{
	int32_t num=0;

	for (int32_t i=0; i<num_preproc; i++)
	{
		if (preprocessed[i])
			num++;
	}

	return num;
}

/// clears all preprocs
void CFeatures::clean_preprocessors()
{
	while (del_preprocessor(0));
}

/// del current preprocessor
CPreprocessor* CFeatures::del_preprocessor(int32_t num)
{
	CPreprocessor** pps=NULL;
	bool* preprocd=NULL;
	CPreprocessor* removed_preproc=NULL;

	if (num_preproc>0 && num<num_preproc)
	{
		removed_preproc=preproc[num];

		if (num_preproc>1)
		{
			pps= SG_MALLOC(CPreprocessor*, num_preproc-1);
			preprocd= SG_MALLOC(bool, num_preproc-1);

			if (pps && preprocd)
			{
				int32_t j=0;
				for (int32_t i=0; i<num_preproc; i++)
				{
					if (i!=num)
					{
						pps[j]=preproc[i];
						preprocd[j]=preprocessed[i];
						j++;
					}
				}
			}
		}

		SG_FREE(preproc);
		preproc=pps;
		SG_FREE(preprocessed);
		preprocessed=preprocd;

		num_preproc--;

		for (int32_t i=0; i<num_preproc; i++)
			SG_INFO( "preproc[%d]=%s\n",i, preproc[i]->get_name()) ;
	}

	SG_UNREF(removed_preproc);
	return removed_preproc;
}

void CFeatures::set_preprocessed(int32_t num)
{
	preprocessed[num]=true;
}

bool CFeatures::is_preprocessed(int32_t num)
{
	return preprocessed[num];
}

int32_t CFeatures::get_num_preprocessors() const
{
	return num_preproc;
}

int32_t CFeatures::get_cache_size()
{
	return cache_size;
}

bool CFeatures::reshape(int32_t num_features, int32_t num_vectors)
{
	SG_NOTIMPLEMENTED;
	return false;
}

void CFeatures::list_feature_obj()
{
	SG_INFO( "%p - ", this);
	switch (get_feature_class())
	{
		case C_UNKNOWN:
			SG_INFO( "C_UNKNOWN ");
			break;
		case C_SIMPLE:
			SG_INFO( "C_SIMPLE ");
			break;
		case C_SPARSE:
			SG_INFO( "C_SPARSE ");
			break;
		case C_STRING:
			SG_INFO( "C_STRING ");
			break;
		case C_COMBINED:
			SG_INFO( "C_COMBINED ");
			break;
		case C_COMBINED_DOT:
			SG_INFO( "C_COMBINED_DOT ");
			break;
		case C_WD:
			SG_INFO( "C_WD ");
			break;
		case C_SPEC:
			SG_INFO( "C_SPEC ");
			break;
		case C_WEIGHTEDSPEC:
			SG_INFO( "C_WEIGHTEDSPEC ");
			break;
		case C_STREAMING_SIMPLE:
			SG_INFO( "C_STREAMING_SIMPLE ");
			break;
		case C_STREAMING_SPARSE:
			SG_INFO( "C_STREAMING_SPARSE ");
			break;
		case C_STREAMING_STRING:
			SG_INFO( "C_STREAMING_STRING ");
			break;
		case C_STREAMING_VW:
			SG_INFO( "C_STREAMING_VW ");
			break;
		case C_ANY:
			SG_INFO( "C_ANY ");
			break;
		default:
         SG_ERROR( "ERROR UNKNOWN FEATURE CLASS");
	}

	switch (get_feature_type())
	{
		case F_UNKNOWN:
			SG_INFO( "F_UNKNOWN \n");
			break;
		case F_CHAR:
			SG_INFO( "F_CHAR \n");
			break;
		case F_BYTE:
			SG_INFO( "F_BYTE \n");
			break;
		case F_SHORT:
			SG_INFO( "F_SHORT \n");
			break;
		case F_WORD:
			SG_INFO( "F_WORD \n");
			break;
		case F_INT:
			SG_INFO( "F_INT \n");
			break;
		case F_UINT:
			SG_INFO( "F_UINT \n");
			break;
		case F_LONG:
			SG_INFO( "F_LONG \n");
			break;
		case F_ULONG:
			SG_INFO( "F_ULONG \n");
			break;
		case F_SHORTREAL:
			SG_INFO( "F_SHORTEAL \n");
			break;
		case F_DREAL:
			SG_INFO( "F_DREAL \n");
			break;
		case F_LONGREAL:
			SG_INFO( "F_LONGREAL \n");
			break;
		case F_ANY:
			SG_INFO( "F_ANY \n");
			break;
		default:
         SG_ERROR( "ERROR UNKNOWN FEATURE TYPE\n");
	}
}

void CFeatures::load(CFile* loader)
{
	SG_SET_LOCALE_C;
	SG_NOTIMPLEMENTED;
	SG_RESET_LOCALE;
}

void CFeatures::save(CFile* writer)
{
	SG_SET_LOCALE_C;
	SG_NOTIMPLEMENTED;
	SG_RESET_LOCALE;
}

bool CFeatures::check_feature_compatibility(CFeatures* f)
{
	bool result=false;

	if (f)
		result= ( (this->get_feature_class() == f->get_feature_class()) &&
				(this->get_feature_type() == f->get_feature_type()));
	return result;
}

bool CFeatures::has_property(EFeatureProperty p)
{
	return (properties & p) != 0;
}

void CFeatures::set_property(EFeatureProperty p)
{
	properties |= p;
}

void CFeatures::unset_property(EFeatureProperty p)
{
	properties &= (properties | p) ^ p;
}

void CFeatures::push_subset(CSubset* subset)
{
	/* do some basic consistency checks */
	if (!subset)
		SG_ERROR("CFeatures::push_subset(NULL) is illegal.\n");

	/* check for legal size (only possible if there is already a subset) */
	if (has_subsets())
	{
		index_t available=m_active_subset->get_size();
		if (subset->get_size()>available)
			SG_ERROR("Pushed subset contains more indices than available.\n");

		if (subset->get_max_index()>= available)
			SG_ERROR("Pushed subset contains index out of bounds (too large).\n");
	}

	m_subset_stack->push(subset);
	update_active_subset();
	subset_changed_post();
}

bool CFeatures::has_subsets() const
{
	return m_subset_stack->get_num_elements();
}

void CFeatures::pop_subset()
{
	m_subset_stack->pop();
	update_active_subset();
	subset_changed_post();
}

void CFeatures::remove_all_subsets()
{
	m_subset_stack->delete_all_elements();
	update_active_subset();
	subset_changed_post();
}

void CFeatures::update_active_subset()
{
	if (m_subset_stack->get_num_elements())
	{
		CSubset* last=(CSubset*)m_subset_stack->get_last_element();

		SGVector<index_t> indices=SGVector<index_t>(last->get_size());

		/* map mappings of latest subset using active subset */
		for (index_t i=0; i<last->get_size(); ++i)
		{
			indices.vector[i]=m_active_subset->subset_idx_conversion(
					last->subset_idx_conversion(i));
		}
		SG_UNREF(last);

		/* replace active subset */
		SG_UNREF(m_active_subset);
		m_active_subset=new CSubset(indices);
		SG_REF(m_active_subset);

	}
	else
	{
		SG_UNREF(m_active_subset);
		m_active_subset=NULL;
	}

}

CFeatures* CFeatures::copy_subset(SGVector<index_t> indices)
{
	SG_ERROR("copy_subset and therefore model storage of CMachine "
			"(required for cross-validation and model-selection is ",
			"not yet implemented for feature type %s\n", get_name());
	return NULL;
}
<commit_msg>memory bugfix<commit_after>/*
 * 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 3 of the License, or
 * (at your option) any later version.
 *
 * Written (W) 1999-2009 Soeren Sonnenburg
 * Written (W) 1999-2008 Gunnar Raetsch
 * Subset support written (W) 2011 Heiko Strathmann
 * Copyright (C) 1999-2009 Fraunhofer Institute FIRST and Max-Planck-Society
 */

#include <shogun/features/Features.h>
#include <shogun/preprocessor/Preprocessor.h>
#include <shogun/io/SGIO.h>
#include <shogun/base/Parameter.h>

#include <string.h>

using namespace shogun;

CFeatures::CFeatures(int32_t size)
: CSGObject()
{
	init();
	cache_size = size;
}

CFeatures::CFeatures(const CFeatures& orig)
: CSGObject(orig)
{
	init();

	preproc = orig.preproc;
	num_preproc = orig.num_preproc;

	preprocessed=SG_MALLOC(bool, orig.num_preproc);
	memcpy(preprocessed, orig.preprocessed, sizeof(bool)*orig.num_preproc);
}

CFeatures::CFeatures(CFile* loader)
: CSGObject()
{
	init();

	load(loader);
	SG_INFO("Feature object loaded (%p)\n",this) ;
}

CFeatures::~CFeatures()
{
	clean_preprocessors();
	SG_UNREF(m_active_subset);
	SG_UNREF(m_subset_stack);
}

void
CFeatures::init()
{
	SG_ADD(&properties, "properties", "Feature properties", MS_NOT_AVAILABLE);
	SG_ADD(&cache_size, "cache_size", "Size of cache in MB", MS_NOT_AVAILABLE);

	/* TODO, use SGVector for arrays to be able to use SG_ADD macro */
	m_parameters->add_vector((CSGObject***) &preproc, &num_preproc, "preproc",
			"List of preprocessors");
	m_parameters->add_vector(&preprocessed, &num_preproc, "preprocessed",
			"Feature[i] is already preprocessed");

	SG_ADD((CSGObject**)&m_active_subset, "active_subset", "Subset object",
			MS_NOT_AVAILABLE);

	SG_ADD((CSGObject**)&m_subset_stack, "subset_stack",
			"Stack of subsets of indices", MS_NOT_AVAILABLE);

	m_subset_stack=new CList(true);
	SG_REF(m_subset_stack);

	m_active_subset=NULL;
	properties = FP_NONE;
	cache_size = 0;
	preproc = NULL;
	num_preproc = 0;
	preprocessed = NULL;
}

/// set preprocessor
int32_t CFeatures::add_preprocessor(CPreprocessor* p)
{
	SG_INFO( "%d preprocs currently, new preproc list is\n", num_preproc);
	ASSERT(p);

	bool* preprocd=SG_MALLOC(bool, num_preproc+1);
	CPreprocessor** pps=SG_MALLOC(CPreprocessor*, num_preproc+1);
	for (int32_t i=0; i<num_preproc; i++)
	{
		pps[i]=preproc[i];
		preprocd[i]=preprocessed[i];
	}
	SG_FREE(preproc);
	SG_FREE(preprocessed);
	preproc=pps;
	preprocessed=preprocd;
	preproc[num_preproc]=p;
	preprocessed[num_preproc]=false;

	num_preproc++;

	for (int32_t i=0; i<num_preproc; i++)
		SG_INFO( "preproc[%d]=%s %ld\n",i, preproc[i]->get_name(), preproc[i]) ;

	SG_REF(p);

	return num_preproc;
}

/// get current preprocessor
CPreprocessor* CFeatures::get_preprocessor(int32_t num)
{
	if (num<num_preproc)
	{
		SG_REF(preproc[num]);
		return preproc[num];
	}
	else
		return NULL;
}

/// get whether specified preprocessor (or all if num=1) was/were already applied
int32_t CFeatures::get_num_preprocessed()
{
	int32_t num=0;

	for (int32_t i=0; i<num_preproc; i++)
	{
		if (preprocessed[i])
			num++;
	}

	return num;
}

/// clears all preprocs
void CFeatures::clean_preprocessors()
{
	while (del_preprocessor(0));
}

/// del current preprocessor
CPreprocessor* CFeatures::del_preprocessor(int32_t num)
{
	CPreprocessor** pps=NULL;
	bool* preprocd=NULL;
	CPreprocessor* removed_preproc=NULL;

	if (num_preproc>0 && num<num_preproc)
	{
		removed_preproc=preproc[num];

		if (num_preproc>1)
		{
			pps= SG_MALLOC(CPreprocessor*, num_preproc-1);
			preprocd= SG_MALLOC(bool, num_preproc-1);

			if (pps && preprocd)
			{
				int32_t j=0;
				for (int32_t i=0; i<num_preproc; i++)
				{
					if (i!=num)
					{
						pps[j]=preproc[i];
						preprocd[j]=preprocessed[i];
						j++;
					}
				}
			}
		}

		SG_FREE(preproc);
		preproc=pps;
		SG_FREE(preprocessed);
		preprocessed=preprocd;

		num_preproc--;

		for (int32_t i=0; i<num_preproc; i++)
			SG_INFO( "preproc[%d]=%s\n",i, preproc[i]->get_name()) ;
	}

	SG_UNREF(removed_preproc);
	return removed_preproc;
}

void CFeatures::set_preprocessed(int32_t num)
{
	preprocessed[num]=true;
}

bool CFeatures::is_preprocessed(int32_t num)
{
	return preprocessed[num];
}

int32_t CFeatures::get_num_preprocessors() const
{
	return num_preproc;
}

int32_t CFeatures::get_cache_size()
{
	return cache_size;
}

bool CFeatures::reshape(int32_t num_features, int32_t num_vectors)
{
	SG_NOTIMPLEMENTED;
	return false;
}

void CFeatures::list_feature_obj()
{
	SG_INFO( "%p - ", this);
	switch (get_feature_class())
	{
		case C_UNKNOWN:
			SG_INFO( "C_UNKNOWN ");
			break;
		case C_SIMPLE:
			SG_INFO( "C_SIMPLE ");
			break;
		case C_SPARSE:
			SG_INFO( "C_SPARSE ");
			break;
		case C_STRING:
			SG_INFO( "C_STRING ");
			break;
		case C_COMBINED:
			SG_INFO( "C_COMBINED ");
			break;
		case C_COMBINED_DOT:
			SG_INFO( "C_COMBINED_DOT ");
			break;
		case C_WD:
			SG_INFO( "C_WD ");
			break;
		case C_SPEC:
			SG_INFO( "C_SPEC ");
			break;
		case C_WEIGHTEDSPEC:
			SG_INFO( "C_WEIGHTEDSPEC ");
			break;
		case C_STREAMING_SIMPLE:
			SG_INFO( "C_STREAMING_SIMPLE ");
			break;
		case C_STREAMING_SPARSE:
			SG_INFO( "C_STREAMING_SPARSE ");
			break;
		case C_STREAMING_STRING:
			SG_INFO( "C_STREAMING_STRING ");
			break;
		case C_STREAMING_VW:
			SG_INFO( "C_STREAMING_VW ");
			break;
		case C_ANY:
			SG_INFO( "C_ANY ");
			break;
		default:
         SG_ERROR( "ERROR UNKNOWN FEATURE CLASS");
	}

	switch (get_feature_type())
	{
		case F_UNKNOWN:
			SG_INFO( "F_UNKNOWN \n");
			break;
		case F_CHAR:
			SG_INFO( "F_CHAR \n");
			break;
		case F_BYTE:
			SG_INFO( "F_BYTE \n");
			break;
		case F_SHORT:
			SG_INFO( "F_SHORT \n");
			break;
		case F_WORD:
			SG_INFO( "F_WORD \n");
			break;
		case F_INT:
			SG_INFO( "F_INT \n");
			break;
		case F_UINT:
			SG_INFO( "F_UINT \n");
			break;
		case F_LONG:
			SG_INFO( "F_LONG \n");
			break;
		case F_ULONG:
			SG_INFO( "F_ULONG \n");
			break;
		case F_SHORTREAL:
			SG_INFO( "F_SHORTEAL \n");
			break;
		case F_DREAL:
			SG_INFO( "F_DREAL \n");
			break;
		case F_LONGREAL:
			SG_INFO( "F_LONGREAL \n");
			break;
		case F_ANY:
			SG_INFO( "F_ANY \n");
			break;
		default:
         SG_ERROR( "ERROR UNKNOWN FEATURE TYPE\n");
	}
}

void CFeatures::load(CFile* loader)
{
	SG_SET_LOCALE_C;
	SG_NOTIMPLEMENTED;
	SG_RESET_LOCALE;
}

void CFeatures::save(CFile* writer)
{
	SG_SET_LOCALE_C;
	SG_NOTIMPLEMENTED;
	SG_RESET_LOCALE;
}

bool CFeatures::check_feature_compatibility(CFeatures* f)
{
	bool result=false;

	if (f)
		result= ( (this->get_feature_class() == f->get_feature_class()) &&
				(this->get_feature_type() == f->get_feature_type()));
	return result;
}

bool CFeatures::has_property(EFeatureProperty p)
{
	return (properties & p) != 0;
}

void CFeatures::set_property(EFeatureProperty p)
{
	properties |= p;
}

void CFeatures::unset_property(EFeatureProperty p)
{
	properties &= (properties | p) ^ p;
}

void CFeatures::push_subset(CSubset* subset)
{
	/* do some basic consistency checks */
	if (!subset)
		SG_ERROR("CFeatures::push_subset(NULL) is illegal.\n");

	/* check for legal size (only possible if there is already a subset) */
	if (has_subsets())
	{
		index_t available=m_active_subset->get_size();
		if (subset->get_size()>available)
			SG_ERROR("Pushed subset contains more indices than available.\n");

		if (subset->get_max_index()>= available)
			SG_ERROR("Pushed subset contains index out of bounds (too large).\n");
	}

	m_subset_stack->push(subset);
	update_active_subset();
	subset_changed_post();
}

bool CFeatures::has_subsets() const
{
	return m_subset_stack->get_num_elements();
}

void CFeatures::pop_subset()
{
	m_subset_stack->pop();
	update_active_subset();
	subset_changed_post();
}

void CFeatures::remove_all_subsets()
{
	m_subset_stack->delete_all_elements();
	update_active_subset();
	subset_changed_post();
}

void CFeatures::update_active_subset()
{
	if (m_subset_stack->get_num_elements())
	{
		CSubset* last=(CSubset*)m_subset_stack->get_last_element();

		SGVector<index_t> indices=SGVector<index_t>(last->get_size());

		/* map mappings of latest subset using active subset */
		if (m_active_subset)
		{
			for (index_t i=0; i<last->get_size(); ++i)
			{
				indices.vector[i]=m_active_subset->subset_idx_conversion(
						last->subset_idx_conversion(i));
			}
		}
		else
		{
			for (index_t i=0; i<last->get_size(); ++i)
			{
				indices.vector[i]=last->subset_idx_conversion(i);
			}
		}
		SG_UNREF(last);

		/* replace active subset */
		SG_UNREF(m_active_subset);
		m_active_subset=new CSubset(indices);
		SG_REF(m_active_subset);

	}
	else
	{
		SG_UNREF(m_active_subset);
		m_active_subset=NULL;
	}

}

CFeatures* CFeatures::copy_subset(SGVector<index_t> indices)
{
	SG_ERROR("copy_subset and therefore model storage of CMachine "
			"(required for cross-validation and model-selection is ",
			"not yet implemented for feature type %s\n", get_name());
	return NULL;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: clipboardmanager.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obr $ $Date: 2001-07-27 10:03:36 $
 *
 *  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 WARRUNTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRUNTIES 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): _______________________________________
 *
 *
 ************************************************************************/

#include <clipboardmanager.hxx>

#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif

using namespace com::sun::star::container;
using namespace com::sun::star::datatransfer;
using namespace com::sun::star::datatransfer::clipboard;
using namespace com::sun::star::lang;
using namespace com::sun::star::uno;
using namespace cppu;
using namespace osl;
using namespace std;

using ::dtrans::ClipboardManager;
using ::rtl::OUString;

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

ClipboardManager::ClipboardManager():
    m_aMutex(),
    WeakComponentImplHelper3< XClipboardManager, XEventListener, XServiceInfo > (m_aMutex),
    m_aDefaultName(OUString::createFromAscii("default"))
{
}

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

ClipboardManager::~ClipboardManager()
{
}

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

OUString SAL_CALL ClipboardManager::getImplementationName(  )
    throw(RuntimeException)
{
    return OUString::createFromAscii(CLIPBOARDMANAGER_IMPLEMENTATION_NAME);
}

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

sal_Bool SAL_CALL ClipboardManager::supportsService( const OUString& ServiceName )
    throw(RuntimeException)
{
    Sequence < OUString > SupportedServicesNames = ClipboardManager_getSupportedServiceNames();

    for ( sal_Int32 n = 0, nmax = SupportedServicesNames.getLength(); n < nmax; n++ )
        if (SupportedServicesNames[n].compareTo(ServiceName) == 0)
            return sal_True;

    return sal_False;
}

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

Sequence< OUString > SAL_CALL ClipboardManager::getSupportedServiceNames(  )
    throw(RuntimeException)
{
    return ClipboardManager_getSupportedServiceNames();
}

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

Reference< XClipboard > SAL_CALL ClipboardManager::getClipboard( const OUString& aName )
    throw(NoSuchElementException, RuntimeException)
{
    MutexGuard aGuard(m_aMutex);

    // object is disposed already
    if (rBHelper.bDisposed)
        throw DisposedException(OUString::createFromAscii("object is disposed."),
                                static_cast < XClipboardManager * > (this));

    ClipboardMap::iterator iter =
        m_aClipboardMap.find(aName.getLength() ? aName : m_aDefaultName);

    if (iter != m_aClipboardMap.end())
        return iter->second;

    throw NoSuchElementException(aName, static_cast < XClipboardManager * > (this));
}

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

void SAL_CALL ClipboardManager::addClipboard( const Reference< XClipboard >& xClipboard )
    throw(IllegalArgumentException, ElementExistException, RuntimeException)
{
    OSL_ASSERT(xClipboard.is());

    // check parameter
    if (!xClipboard.is())
        throw IllegalArgumentException(OUString::createFromAscii("empty reference"),
                                       static_cast < XClipboardManager * > (this), 1);

    // the name "default" is reserved for internal use
    OUString aName = xClipboard->getName();
    if (m_aDefaultName.compareTo(aName) == 0)
        throw IllegalArgumentException(OUString::createFromAscii("name reserved"),
                                       static_cast < XClipboardManager * > (this), 1);

    // try to add new clipboard to the list
    ClearableMutexGuard aGuard(m_aMutex);
    if (!rBHelper.bDisposed && !rBHelper.bInDispose)
    {
        pair< const OUString, Reference< XClipboard > > value (
            aName.getLength() ? aName : m_aDefaultName,
            xClipboard );

        pair< ClipboardMap::iterator, bool > p = m_aClipboardMap.insert(value);
        aGuard.clear();

        // insert failed, element must exist already
        if (!p.second)
            throw ElementExistException(aName, static_cast < XClipboardManager * > (this));

        // request disposing notifications
        Reference< XComponent > xComponent(xClipboard, UNO_QUERY);
        if (xComponent.is())
            xComponent->addEventListener(static_cast < XEventListener * > (this));
    }
}

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

void SAL_CALL ClipboardManager::removeClipboard( const OUString& aName )
     throw(RuntimeException)
{
    MutexGuard aGuard(m_aMutex);
    if (!rBHelper.bDisposed)
        m_aClipboardMap.erase(aName.getLength() ? aName : m_aDefaultName );
}

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

Sequence< OUString > SAL_CALL ClipboardManager::listClipboardNames()
    throw(RuntimeException)
{
    MutexGuard aGuard(m_aMutex);

    if (rBHelper.bDisposed)
        throw DisposedException(OUString::createFromAscii("object is disposed."),
                                static_cast < XClipboardManager * > (this));

    if (rBHelper.bInDispose)
        return Sequence< OUString > ();

    Sequence< OUString > aRet(m_aClipboardMap.size());
    ClipboardMap::iterator iter = m_aClipboardMap.begin();
    ClipboardMap::iterator imax = m_aClipboardMap.end();

    for (sal_Int32 n = 0; iter != imax; iter++)
        aRet[n++] = iter->first;

    return aRet;
}

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

void SAL_CALL ClipboardManager::dispose()
    throw(RuntimeException)
{
    ClearableMutexGuard aGuard( rBHelper.rMutex );
    if (!rBHelper.bDisposed && !rBHelper.bInDispose)
    {
        rBHelper.bInDispose = sal_True;
        aGuard.clear();

        // give everyone a chance to save his clipboard instance
        EventObject aEvt(static_cast < XClipboardManager * > (this));
        rBHelper.aLC.disposeAndClear( aEvt );

        // removeClipboard is still allowed here,  so make a copy of the
        // list (to ensure integrety) and clear the original.
        ClearableMutexGuard aGuard2( rBHelper.rMutex );
        ClipboardMap aCopy(m_aClipboardMap);
        m_aClipboardMap.clear();
        aGuard2.clear();

        // dispose all clipboards still in list
        ClipboardMap::iterator iter = aCopy.begin();
        ClipboardMap::iterator imax = aCopy.end();

        for (; iter != imax; iter++)
        {
            Reference< XComponent > xComponent(iter->second, UNO_QUERY);
            if (xComponent.is())
            {
                try
                {
                    xComponent->removeEventListener(static_cast < XEventListener * > (this));
                    xComponent->dispose();
                }

                catch(Exception e)
                {
                    // exceptions can be safely ignored here.
                }
            }
        }

        rBHelper.bDisposed = sal_True;
        rBHelper.bInDispose = sal_False;
    }
}

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

void SAL_CALL  ClipboardManager::disposing( const EventObject& event )
    throw(RuntimeException)
{
    Reference < XClipboard > xClipboard(event.Source, UNO_QUERY);

    if (xClipboard.is())
        removeClipboard(xClipboard->getName());
}

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

Reference< XInterface > SAL_CALL ClipboardManager_createInstance(
    const Reference< XMultiServiceFactory > & xMultiServiceFactory)
{
    return Reference < XInterface >( ( OWeakObject * ) new ClipboardManager());
}

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

Sequence< OUString > SAL_CALL ClipboardManager_getSupportedServiceNames()
{
    Sequence < OUString > SupportedServicesNames( 1 );
    SupportedServicesNames[0] =
        OUString::createFromAscii("com.sun.star.datatransfer.clipboard.ClipboardManager");
    return SupportedServicesNames;
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.178); FILE MERGED 2005/09/05 18:48:10 rt 1.2.178.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: clipboardmanager.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 18:11:44 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <clipboardmanager.hxx>

#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_
#include <com/sun/star/lang/DisposedException.hpp>
#endif

using namespace com::sun::star::container;
using namespace com::sun::star::datatransfer;
using namespace com::sun::star::datatransfer::clipboard;
using namespace com::sun::star::lang;
using namespace com::sun::star::uno;
using namespace cppu;
using namespace osl;
using namespace std;

using ::dtrans::ClipboardManager;
using ::rtl::OUString;

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

ClipboardManager::ClipboardManager():
    m_aMutex(),
    WeakComponentImplHelper3< XClipboardManager, XEventListener, XServiceInfo > (m_aMutex),
    m_aDefaultName(OUString::createFromAscii("default"))
{
}

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

ClipboardManager::~ClipboardManager()
{
}

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

OUString SAL_CALL ClipboardManager::getImplementationName(  )
    throw(RuntimeException)
{
    return OUString::createFromAscii(CLIPBOARDMANAGER_IMPLEMENTATION_NAME);
}

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

sal_Bool SAL_CALL ClipboardManager::supportsService( const OUString& ServiceName )
    throw(RuntimeException)
{
    Sequence < OUString > SupportedServicesNames = ClipboardManager_getSupportedServiceNames();

    for ( sal_Int32 n = 0, nmax = SupportedServicesNames.getLength(); n < nmax; n++ )
        if (SupportedServicesNames[n].compareTo(ServiceName) == 0)
            return sal_True;

    return sal_False;
}

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

Sequence< OUString > SAL_CALL ClipboardManager::getSupportedServiceNames(  )
    throw(RuntimeException)
{
    return ClipboardManager_getSupportedServiceNames();
}

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

Reference< XClipboard > SAL_CALL ClipboardManager::getClipboard( const OUString& aName )
    throw(NoSuchElementException, RuntimeException)
{
    MutexGuard aGuard(m_aMutex);

    // object is disposed already
    if (rBHelper.bDisposed)
        throw DisposedException(OUString::createFromAscii("object is disposed."),
                                static_cast < XClipboardManager * > (this));

    ClipboardMap::iterator iter =
        m_aClipboardMap.find(aName.getLength() ? aName : m_aDefaultName);

    if (iter != m_aClipboardMap.end())
        return iter->second;

    throw NoSuchElementException(aName, static_cast < XClipboardManager * > (this));
}

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

void SAL_CALL ClipboardManager::addClipboard( const Reference< XClipboard >& xClipboard )
    throw(IllegalArgumentException, ElementExistException, RuntimeException)
{
    OSL_ASSERT(xClipboard.is());

    // check parameter
    if (!xClipboard.is())
        throw IllegalArgumentException(OUString::createFromAscii("empty reference"),
                                       static_cast < XClipboardManager * > (this), 1);

    // the name "default" is reserved for internal use
    OUString aName = xClipboard->getName();
    if (m_aDefaultName.compareTo(aName) == 0)
        throw IllegalArgumentException(OUString::createFromAscii("name reserved"),
                                       static_cast < XClipboardManager * > (this), 1);

    // try to add new clipboard to the list
    ClearableMutexGuard aGuard(m_aMutex);
    if (!rBHelper.bDisposed && !rBHelper.bInDispose)
    {
        pair< const OUString, Reference< XClipboard > > value (
            aName.getLength() ? aName : m_aDefaultName,
            xClipboard );

        pair< ClipboardMap::iterator, bool > p = m_aClipboardMap.insert(value);
        aGuard.clear();

        // insert failed, element must exist already
        if (!p.second)
            throw ElementExistException(aName, static_cast < XClipboardManager * > (this));

        // request disposing notifications
        Reference< XComponent > xComponent(xClipboard, UNO_QUERY);
        if (xComponent.is())
            xComponent->addEventListener(static_cast < XEventListener * > (this));
    }
}

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

void SAL_CALL ClipboardManager::removeClipboard( const OUString& aName )
     throw(RuntimeException)
{
    MutexGuard aGuard(m_aMutex);
    if (!rBHelper.bDisposed)
        m_aClipboardMap.erase(aName.getLength() ? aName : m_aDefaultName );
}

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

Sequence< OUString > SAL_CALL ClipboardManager::listClipboardNames()
    throw(RuntimeException)
{
    MutexGuard aGuard(m_aMutex);

    if (rBHelper.bDisposed)
        throw DisposedException(OUString::createFromAscii("object is disposed."),
                                static_cast < XClipboardManager * > (this));

    if (rBHelper.bInDispose)
        return Sequence< OUString > ();

    Sequence< OUString > aRet(m_aClipboardMap.size());
    ClipboardMap::iterator iter = m_aClipboardMap.begin();
    ClipboardMap::iterator imax = m_aClipboardMap.end();

    for (sal_Int32 n = 0; iter != imax; iter++)
        aRet[n++] = iter->first;

    return aRet;
}

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

void SAL_CALL ClipboardManager::dispose()
    throw(RuntimeException)
{
    ClearableMutexGuard aGuard( rBHelper.rMutex );
    if (!rBHelper.bDisposed && !rBHelper.bInDispose)
    {
        rBHelper.bInDispose = sal_True;
        aGuard.clear();

        // give everyone a chance to save his clipboard instance
        EventObject aEvt(static_cast < XClipboardManager * > (this));
        rBHelper.aLC.disposeAndClear( aEvt );

        // removeClipboard is still allowed here,  so make a copy of the
        // list (to ensure integrety) and clear the original.
        ClearableMutexGuard aGuard2( rBHelper.rMutex );
        ClipboardMap aCopy(m_aClipboardMap);
        m_aClipboardMap.clear();
        aGuard2.clear();

        // dispose all clipboards still in list
        ClipboardMap::iterator iter = aCopy.begin();
        ClipboardMap::iterator imax = aCopy.end();

        for (; iter != imax; iter++)
        {
            Reference< XComponent > xComponent(iter->second, UNO_QUERY);
            if (xComponent.is())
            {
                try
                {
                    xComponent->removeEventListener(static_cast < XEventListener * > (this));
                    xComponent->dispose();
                }

                catch(Exception e)
                {
                    // exceptions can be safely ignored here.
                }
            }
        }

        rBHelper.bDisposed = sal_True;
        rBHelper.bInDispose = sal_False;
    }
}

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

void SAL_CALL  ClipboardManager::disposing( const EventObject& event )
    throw(RuntimeException)
{
    Reference < XClipboard > xClipboard(event.Source, UNO_QUERY);

    if (xClipboard.is())
        removeClipboard(xClipboard->getName());
}

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

Reference< XInterface > SAL_CALL ClipboardManager_createInstance(
    const Reference< XMultiServiceFactory > & xMultiServiceFactory)
{
    return Reference < XInterface >( ( OWeakObject * ) new ClipboardManager());
}

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

Sequence< OUString > SAL_CALL ClipboardManager_getSupportedServiceNames()
{
    Sequence < OUString > SupportedServicesNames( 1 );
    SupportedServicesNames[0] =
        OUString::createFromAscii("com.sun.star.datatransfer.clipboard.ClipboardManager");
    return SupportedServicesNames;
}

<|endoftext|>


<commit_before>/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        ListNode* root = head;
        while (head and head->next) {
            ListNode* next = head->next;
            if (head->val == next->val) {
                head->next = next->next;
            } else {
                head = head->next;
            }
        }
        return root;
    }
};
<commit_msg>Update remove-duplicates-from-sorted-list.cc<commit_after>/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *deleteDuplicates(ListNode *head) {
        ListNode* current = head;
        while (current and current->next) {
            ListNode* next = current->next;
            if (current->val == next->val) {
                current->next = next->next;
            } else {
                current = current->next;
            }
        }
        return head;
    }
};
<|endoftext|>


<commit_before>#include <Python.h>
#include "Quantuccia/ql/time/calendar.hpp"
#include "Quantuccia/ql/time/date.hpp"
#include "Quantuccia/ql/time/calendars/unitedkingdom.hpp"

static PyObject*
united_kingdom_is_business_day(PyObject *self, PyObject *args)
{
	int year;
	int month;
	int day;
	if (!PyArg_ParseTuple(args, "iii|", &year, &month, &day))
        return NULL;
	QuantLib::Day d(day);
	QuantLib::Month m = static_cast<QuantLib::Month>(month);
	QuantLib::Year y(year);
	QuantLib::Date date(d, m, y);
	QuantLib::UnitedKingdom calendar(QuantLib::UnitedKingdom::Exchange);
    bool result = calendar.isBusinessDay(date);
	if (result) {
		return Py_True;
	} else {
		return Py_False;
	}
}

static PyMethodDef QuantucciaMethods[] = {
	{"united_kingdom_is_business_day", (PyCFunction)united_kingdom_is_business_day, METH_VARARGS, NULL},
	{NULL, NULL, 0, NULL}
};

static struct PyModuleDef quantuccia_module_def = {
	PyModuleDef_HEAD_INIT,
	"quantuccia",
	NULL,
	-1,
	QuantucciaMethods,
	NULL,
	NULL,
	NULL,
	NULL
};

PyMODINIT_FUNC PyInit_quantuccia(void){
    PyObject *m;
    m = PyModule_Create(&quantuccia_module_def);
    return m;
}
<commit_msg>Use PyBoolFromLong.<commit_after>#include <Python.h>
#include "Quantuccia/ql/time/calendar.hpp"
#include "Quantuccia/ql/time/date.hpp"
#include "Quantuccia/ql/time/calendars/unitedkingdom.hpp"

static PyObject*
united_kingdom_is_business_day(PyObject *self, PyObject *args)
{
	int year;
	int month;
	int day;
	if (!PyArg_ParseTuple(args, "iii|", &year, &month, &day))
        return NULL;
	QuantLib::Day d(day);
	QuantLib::Month m = static_cast<QuantLib::Month>(month);
	QuantLib::Year y(year);
	QuantLib::Date date(d, m, y);
	QuantLib::UnitedKingdom calendar(QuantLib::UnitedKingdom::Exchange);
    bool result = calendar.isBusinessDay(date);
	return PyBool_FromLong(result);
}

static PyMethodDef QuantucciaMethods[] = {
	{"united_kingdom_is_business_day", (PyCFunction)united_kingdom_is_business_day, METH_VARARGS, NULL},
	{NULL, NULL, 0, NULL}
};

static struct PyModuleDef quantuccia_module_def = {
	PyModuleDef_HEAD_INIT,
	"quantuccia",
	NULL,
	-1,
	QuantucciaMethods,
	NULL,
	NULL,
	NULL,
	NULL
};

PyMODINIT_FUNC PyInit_quantuccia(void){
    PyObject *m;
    m = PyModule_Create(&quantuccia_module_def);
    return m;
}
<|endoftext|>