<commit_before>/*************************************************************************
 *
 *  $RCSfile: layact.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2003-04-28 15:17:17 $
 *
 *  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 _LAYACT_HXX
#define _LAYACT_HXX

#include "swtypes.hxx"
#include "swrect.hxx"

class SwRootFrm;
class SwLayoutFrm;
class SwPageFrm;
class SwFlyFrm;
class SwFlyInCntFrm;
class SwCntntFrm;
class SwTabFrm;
class SwViewImp;
class SwCntntNode;
class SwWait;

//Die Verwendung der LayAction laeuft immer gleich ab:
//
// 1. Erzeugen des LayAction-Objektes.
// 2. Einstellen des gewuenschten Verhaltens mittels der Set-Methoden
// 3. Aufruf von Action()
// 4. Baldiges Zerstoeren des Objektes.
//
// Das Objekt meldet sich im CTor beim SwViewImp an und erst im DTor
// wieder ab! Es handelt sich mithin um ein typisches Stackobjekt.

class SwLayAction
{
    SwRootFrm  *pRoot;
    SwViewImp  *pImp;   //Hier Meldet sich die Action an und ab.

    //Zur Optimierung, damit die Tabellen etwas besser am Crsr kleben beim
    //Return/Backspace davor.
    //Wenn der erste TabFrm, der sich Paintet (pro Seite) traegt sich im
    //Pointer ein. Die CntntFrms unterhalb der Seite brauchen sich
    //dann nicht mehr bei der Shell zum Painten anmelden.
    const SwTabFrm *pOptTab;

    SwWait *pWait;

    SfxProgress * pProgress;

    //Wenn ein Absatz - oder was auch immer - bei der Formatierung mehr
    //als eine Seite rueckwaerts floss traegt er seine neue Seitennummer
    //hier ein. Die Steuerung der InternalAction kann dann geeignet reagieren.
    USHORT nPreInvaPage;

    ULONG nStartTicks;  //Startzeitpunkt der Aktion, vergeht zu viel Zeit kann
                        //der WaitCrsr per CheckWaitCrsr() eingeschaltet werden.

    USHORT nInputType;  //Bei welchem Input soll die Verarbeitung abgebrochen
                        //werden?
    USHORT nEndPage;    //StatBar Steuerung.
    USHORT nCheckPageNum; //CheckPageDesc() wurde verzoegert wenn != USHRT_MAX
                          //ab dieser Seite Checken.

    BOOL bPaint;        //Painten oder nur Formatieren?
    BOOL bComplete;     //Alles bis zum sichtbaren Bereich Formatieren oder
                        //oder nur den sichtbaren Bereich?
    BOOL bCalcLayout;   //Vollstaendige Reformatierung?
    BOOL bAgain;        //Zur automatisch wiederholten Action wenn Seiten
                        //geloscht werden.
    BOOL bNextCycle;    //Wiederaufsetzen bei der ersten Ungueltigen Seite.
    BOOL bInput;        //Zum Abbrechen der Verarbeitung wenn ein Input anliegt.
    BOOL bIdle;         //True wenn die Layaction vom Idler ausgeloest wurde.
    BOOL bReschedule;   //Soll das Reschedule - abhaengig vom Progress -
                        //gerufen werden?
    BOOL bCheckPages;   //CheckPageDescs() ausfuehren oder verzoegern.
    BOOL bUpdateExpFlds;//Wird gesetzt wenn nach dem Formatierien noch eine
                        //Runde fuer den ExpFld laufen muss.
    BOOL bBrowseActionStop; //Action fruehzeitig beenden (per bInput) und den
                            //Rest dem Idler ueberlassen.
    BOOL bWaitAllowed;      //Wartecursor erlaubt?
    BOOL bPaintExtraData;   //Anzeige von Zeilennumerierung o. ae. eingeschaltet?
    BOOL bActionInProgress; // wird in Action() anfangs gesetzt und zum Schluss geloescht

    // OD 14.04.2003 #106346# - new flag for content formatting on interrupt.
    sal_Bool    mbFormatCntntOnInterrupt;
#ifdef _LAYACT_CXX

    void _AddScrollRect( const SwCntntFrm *, const SwPageFrm *,
                         const SwTwips, const SwTwips );
    void PaintCntnt( const SwCntntFrm *, const SwPageFrm *,
                     const SwRect &rOldRect, long nOldBottom );
    BOOL PaintWithoutFlys( const SwRect &, const SwCntntFrm *,
                           const SwPageFrm * );
    inline BOOL _PaintCntnt( const SwCntntFrm *, const SwPageFrm *,
                             const SwRect & );

    void ChkFlyAnchor( SwFlyFrm *, const SwPageFrm * );

    void FormatFlyLayout( const SwPageFrm * );
    BOOL FormatFlyCntnt( const SwPageFrm *, sal_Bool bDontShrink );
    BOOL _FormatFlyCntnt( const SwFlyFrm * );
    BOOL __FormatFlyCntnt( const SwCntntFrm * );
    void FormatFlyInCnt( SwFlyInCntFrm* );
    BOOL FormatLayout( SwLayoutFrm *, BOOL bAddRect = TRUE );
    BOOL FormatLayoutTab( SwTabFrm *, BOOL bAddRect = TRUE );
    BOOL FormatLayoutFly( SwFlyFrm *, BOOL bAddRect = TRUE );
    BOOL FormatCntnt( const SwPageFrm* pPage );
    void _FormatCntnt( const SwCntntFrm* pCntnt,
                       const SwPageFrm* pPage );
    BOOL IsShortCut( SwPageFrm *& );

    BOOL TurboAction();
    BOOL _TurboAction( const SwCntntFrm * );
    void InternalAction();

    SwPageFrm *CheckFirstVisPage( SwPageFrm *pPage );

    BOOL RemoveEmptyBrowserPages();

    inline void CheckIdleEnd();
    inline ULONG GetStartTicks() { return nStartTicks; }

#endif

public:
    SwLayAction( SwRootFrm *pRt, SwViewImp *pImp );
    ~SwLayAction();

#ifdef _LAYACT_CXX
    void SetIdle            ( BOOL bNew )   { bIdle = bNew; }
    void SetCheckPages      ( BOOL bNew )   { bCheckPages = bNew; }
    void SetBrowseActionStop(BOOL bNew  )   { bBrowseActionStop = bNew; }
    void SetNextCycle       ( BOOL bNew )   { bNextCycle = bNew; }

    BOOL IsWaitAllowed()        const       { return bWaitAllowed; }
    BOOL IsNextCycle()          const       { return bNextCycle; }
    BOOL IsInput()              const       { return bInput; }
    BOOL IsWait()               const       { return 0 != pWait;  }
    BOOL IsPaint()              const       { return bPaint; }
    BOOL IsIdle()               const       { return bIdle;  }
    BOOL IsReschedule()         const       { return bReschedule;  }
    BOOL IsPaintExtraData()     const       { return bPaintExtraData;}
    BOOL IsStopPrt()          const;
    BOOL IsInterrupt()        const { return IsInput() || IsStopPrt(); }

    USHORT GetInputType()    const { return nInputType; }
#endif

    //Einstellen der Action auf das gewuenschte Verhalten.
    void SetPaint       ( BOOL bNew )   { bPaint = bNew; }
    void SetComplete    ( BOOL bNew )   { bComplete = bNew; }
    void SetStatBar     ( BOOL bNew );
    void SetInputType   ( USHORT nNew ) { nInputType = nNew; }
    void SetCalcLayout  ( BOOL bNew )   { bCalcLayout = bNew; }
    void SetReschedule  ( BOOL bNew )   { bReschedule = bNew; }
    void SetWaitAllowed ( BOOL bNew )   { bWaitAllowed = bNew; }

    void SetAgain()         { bAgain = TRUE; }
    void SetUpdateExpFlds() {bUpdateExpFlds = TRUE; }
    void SetProgress(SfxProgress * _pProgress = NULL)
    { pProgress = _pProgress; }

    inline void SetCheckPageNum( USHORT nNew );
    inline void SetCheckPageNumDirect( USHORT nNew ) { nCheckPageNum = nNew; }

    void Action();  //Jetzt gehts loos...
    void Reset();   //Zurueck auf CTor-Defaults.

    BOOL IsAgain()      const { return bAgain; }
    BOOL IsComplete()   const { return bComplete; }
    BOOL IsExpFlds()    const { return bUpdateExpFlds; }
    BOOL IsCalcLayout() const { return bCalcLayout;  }
    BOOL IsCheckPages() const { return bCheckPages;  }
    BOOL IsBrowseActionStop() const { return bBrowseActionStop; }
    BOOL IsActionInProgress() const { return bActionInProgress; }

    USHORT GetCheckPageNum() const { return nCheckPageNum; }

    //Auch andere sollen den Wartecrsr einschalten koennen.
    void CheckWaitCrsr();
};

class SwLayIdle
{

    SwRootFrm *pRoot;
    SwViewImp  *pImp;           // Hier Meldet sich der Idler an und ab.
    SwCntntNode *pCntntNode;    // Hier wird die aktuelle Cursorposition
    xub_StrLen  nTxtPos;        // zwischengespeichert.
    BOOL        bPageValid;     // Konnte die Seite alles validiert werden?
    BOOL        bAllValid;      // Konnte alles validiert werden?

#ifndef PRODUCT
    BOOL bIndicator;
#endif

#ifdef _LAYACT_CXX

#ifndef PRODUCT
    void ShowIdle( ColorData eName );
#endif
    BOOL _FormatSpelling( const SwCntntFrm * );
    BOOL FormatSpelling( BOOL );

    BOOL _CollectAutoCmplWords( const SwCntntFrm *, BOOL bOnlyVisArea );
    BOOL CollectAutoCmplWords( BOOL );

#endif

public:
    SwLayIdle( SwRootFrm *pRt, SwViewImp *pImp );
    ~SwLayIdle();
};

inline void SwLayAction::SetCheckPageNum( USHORT nNew )
{
    if ( nNew < nCheckPageNum )
        nCheckPageNum = nNew;
}

#endif  //_LAYACT_HXX
<commit_msg>INTEGRATION: CWS swobjpos04 (1.4.516); FILE MERGED 2004/06/30 14:58:56 od 1.4.516.3: #i28701# - merge changes of cws swdrawpositioning 	 - further adjustments for the new object positioning 2004/06/14 13:27:05 od 1.4.516.2: #i28701# - further adjustments for the new positioning of floating 	   screen objects. 2004/05/24 13:00:57 od 1.4.516.1: #i28701# - usage of new class <SwSortedObjs>          - adjustments for the new positioning of floating screen objects<commit_after>/*************************************************************************
 *
 *  $RCSfile: layact.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2004-08-02 14:05:30 $
 *
 *  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 _LAYACT_HXX
#define _LAYACT_HXX

#include "swtypes.hxx"
#include "swrect.hxx"

class SwRootFrm;
class SwLayoutFrm;
class SwPageFrm;
class SwFlyFrm;
class SwFlyInCntFrm;
class SwCntntFrm;
class SwTabFrm;
class SwViewImp;
class SwCntntNode;
class SwWait;
// --> OD 2004-06-28 #i28701#
class SfxProgress;

//Die Verwendung der LayAction laeuft immer gleich ab:
//
// 1. Erzeugen des LayAction-Objektes.
// 2. Einstellen des gewuenschten Verhaltens mittels der Set-Methoden
// 3. Aufruf von Action()
// 4. Baldiges Zerstoeren des Objektes.
//
// Das Objekt meldet sich im CTor beim SwViewImp an und erst im DTor
// wieder ab! Es handelt sich mithin um ein typisches Stackobjekt.

class SwLayAction
{
    SwRootFrm  *pRoot;
    SwViewImp  *pImp;   //Hier Meldet sich die Action an und ab.

    //Zur Optimierung, damit die Tabellen etwas besser am Crsr kleben beim
    //Return/Backspace davor.
    //Wenn der erste TabFrm, der sich Paintet (pro Seite) traegt sich im
    //Pointer ein. Die CntntFrms unterhalb der Seite brauchen sich
    //dann nicht mehr bei der Shell zum Painten anmelden.
    const SwTabFrm *pOptTab;

    SwWait *pWait;

    SfxProgress * pProgress;

    //Wenn ein Absatz - oder was auch immer - bei der Formatierung mehr
    //als eine Seite rueckwaerts floss traegt er seine neue Seitennummer
    //hier ein. Die Steuerung der InternalAction kann dann geeignet reagieren.
    USHORT nPreInvaPage;

    ULONG nStartTicks;  //Startzeitpunkt der Aktion, vergeht zu viel Zeit kann
                        //der WaitCrsr per CheckWaitCrsr() eingeschaltet werden.

    USHORT nInputType;  //Bei welchem Input soll die Verarbeitung abgebrochen
                        //werden?
    USHORT nEndPage;    //StatBar Steuerung.
    USHORT nCheckPageNum; //CheckPageDesc() wurde verzoegert wenn != USHRT_MAX
                          //ab dieser Seite Checken.

    BOOL bPaint;        //Painten oder nur Formatieren?
    BOOL bComplete;     //Alles bis zum sichtbaren Bereich Formatieren oder
                        //oder nur den sichtbaren Bereich?
    BOOL bCalcLayout;   //Vollstaendige Reformatierung?
    BOOL bAgain;        //Zur automatisch wiederholten Action wenn Seiten
                        //geloscht werden.
    BOOL bNextCycle;    //Wiederaufsetzen bei der ersten Ungueltigen Seite.
    BOOL bInput;        //Zum Abbrechen der Verarbeitung wenn ein Input anliegt.
    BOOL bIdle;         //True wenn die Layaction vom Idler ausgeloest wurde.
    BOOL bReschedule;   //Soll das Reschedule - abhaengig vom Progress -
                        //gerufen werden?
    BOOL bCheckPages;   //CheckPageDescs() ausfuehren oder verzoegern.
    BOOL bUpdateExpFlds;//Wird gesetzt wenn nach dem Formatierien noch eine
                        //Runde fuer den ExpFld laufen muss.
    BOOL bBrowseActionStop; //Action fruehzeitig beenden (per bInput) und den
                            //Rest dem Idler ueberlassen.
    BOOL bWaitAllowed;      //Wartecursor erlaubt?
    BOOL bPaintExtraData;   //Anzeige von Zeilennumerierung o. ae. eingeschaltet?
    BOOL bActionInProgress; // wird in Action() anfangs gesetzt und zum Schluss geloescht

    // OD 14.04.2003 #106346# - new flag for content formatting on interrupt.
    sal_Bool    mbFormatCntntOnInterrupt;

    // --> OD 2004-06-14 #i28701# - new flag, indicating, if scrolling is
    // allowed during page format
    bool mbScrollingAllowed;

#ifdef _LAYACT_CXX

    void _AddScrollRect( const SwCntntFrm *, const SwPageFrm *,
                         const SwTwips, const SwTwips );
    void PaintCntnt( const SwCntntFrm *, const SwPageFrm *,
                     const SwRect &rOldRect, long nOldBottom );
    BOOL PaintWithoutFlys( const SwRect &, const SwCntntFrm *,
                           const SwPageFrm * );
    inline BOOL _PaintCntnt( const SwCntntFrm *, const SwPageFrm *,
                             const SwRect & );

    BOOL FormatLayout( SwLayoutFrm *, BOOL bAddRect = TRUE );
    BOOL FormatLayoutTab( SwTabFrm *, BOOL bAddRect = TRUE );
    BOOL FormatCntnt( const SwPageFrm* pPage );
    void _FormatCntnt( const SwCntntFrm* pCntnt,
                       const SwPageFrm* pPage );
    BOOL IsShortCut( SwPageFrm *& );

    BOOL TurboAction();
    BOOL _TurboAction( const SwCntntFrm * );
    void InternalAction();

    SwPageFrm *CheckFirstVisPage( SwPageFrm *pPage );

    BOOL RemoveEmptyBrowserPages();

    inline void CheckIdleEnd();
    inline ULONG GetStartTicks() { return nStartTicks; }

#endif

public:
    SwLayAction( SwRootFrm *pRt, SwViewImp *pImp );
    ~SwLayAction();

#ifdef _LAYACT_CXX
    void SetIdle            ( BOOL bNew )   { bIdle = bNew; }
    void SetCheckPages      ( BOOL bNew )   { bCheckPages = bNew; }
    void SetBrowseActionStop(BOOL bNew  )   { bBrowseActionStop = bNew; }
    void SetNextCycle       ( BOOL bNew )   { bNextCycle = bNew; }

    BOOL IsWaitAllowed()        const       { return bWaitAllowed; }
    BOOL IsNextCycle()          const       { return bNextCycle; }
    BOOL IsInput()              const       { return bInput; }
    BOOL IsWait()               const       { return 0 != pWait;  }
    BOOL IsPaint()              const       { return bPaint; }
    BOOL IsIdle()               const       { return bIdle;  }
    BOOL IsReschedule()         const       { return bReschedule;  }
    BOOL IsPaintExtraData()     const       { return bPaintExtraData;}
    BOOL IsStopPrt()          const;
    BOOL IsInterrupt()        const { return IsInput() || IsStopPrt(); }

    USHORT GetInputType()    const { return nInputType; }
#endif

    //Einstellen der Action auf das gewuenschte Verhalten.
    void SetPaint       ( BOOL bNew )   { bPaint = bNew; }
    void SetComplete    ( BOOL bNew )   { bComplete = bNew; }
    void SetStatBar     ( BOOL bNew );
    void SetInputType   ( USHORT nNew ) { nInputType = nNew; }
    void SetCalcLayout  ( BOOL bNew )   { bCalcLayout = bNew; }
    void SetReschedule  ( BOOL bNew )   { bReschedule = bNew; }
    void SetWaitAllowed ( BOOL bNew )   { bWaitAllowed = bNew; }

    void SetAgain()         { bAgain = TRUE; }
    void SetUpdateExpFlds() {bUpdateExpFlds = TRUE; }
    void SetProgress(SfxProgress * _pProgress = NULL)
    { pProgress = _pProgress; }

    inline void SetCheckPageNum( USHORT nNew );
    inline void SetCheckPageNumDirect( USHORT nNew ) { nCheckPageNum = nNew; }

    void Action();  //Jetzt gehts loos...
    void Reset();   //Zurueck auf CTor-Defaults.

    BOOL IsAgain()      const { return bAgain; }
    BOOL IsComplete()   const { return bComplete; }
    BOOL IsExpFlds()    const { return bUpdateExpFlds; }
    BOOL IsCalcLayout() const { return bCalcLayout;  }
    BOOL IsCheckPages() const { return bCheckPages;  }
    BOOL IsBrowseActionStop() const { return bBrowseActionStop; }
    BOOL IsActionInProgress() const { return bActionInProgress; }

    USHORT GetCheckPageNum() const { return nCheckPageNum; }

    //Auch andere sollen den Wartecrsr einschalten koennen.
    void CheckWaitCrsr();

    // --> OD 2004-06-09 #i28701# - method is now public;
    // delete 2nd parameter, because its not used;
    BOOL FormatLayoutFly( SwFlyFrm * );
    // --> OD 2004-06-09 #i28701# - method is now public
    BOOL _FormatFlyCntnt( const SwFlyFrm * );

};

class SwLayIdle
{

    SwRootFrm *pRoot;
    SwViewImp  *pImp;           // Hier Meldet sich der Idler an und ab.
    SwCntntNode *pCntntNode;    // Hier wird die aktuelle Cursorposition
    xub_StrLen  nTxtPos;        // zwischengespeichert.
    BOOL        bPageValid;     // Konnte die Seite alles validiert werden?
    BOOL        bAllValid;      // Konnte alles validiert werden?

#ifndef PRODUCT
    BOOL bIndicator;
#endif

#ifdef _LAYACT_CXX

#ifndef PRODUCT
    void ShowIdle( ColorData eName );
#endif
    BOOL _FormatSpelling( const SwCntntFrm * );
    BOOL FormatSpelling( BOOL );

    BOOL _CollectAutoCmplWords( const SwCntntFrm *, BOOL bOnlyVisArea );
    BOOL CollectAutoCmplWords( BOOL );

#endif

public:
    SwLayIdle( SwRootFrm *pRt, SwViewImp *pImp );
    ~SwLayIdle();
};

inline void SwLayAction::SetCheckPageNum( USHORT nNew )
{
    if ( nNew < nCheckPageNum )
        nCheckPageNum = nNew;
}

#endif  //_LAYACT_HXX
<|endoftext|>


<commit_before>/*
Copyright (C) 2011-2014 Yubico AB.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

   1. Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above
      copyright notice, this list of conditions and the following
      disclaimer in the documentation and/or other materials provided
      with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "yubikeyutil.h"
#include <yubikey.h>
#include <QDebug>
#ifdef Q_OS_WIN
#include "crandom.h"
#endif

YubiKeyUtil::~YubiKeyUtil() {
}

int YubiKeyUtil::hexModhexDecode(unsigned char *result, size_t *resultLen,
                                 const char *str, size_t strLen,
                                 size_t minSize, size_t maxSize,
                                 bool modhex)
{
    if ((strLen % 2 != 0) || (strLen < minSize) || (strLen > maxSize)) {
        return -1;
    }

    *resultLen = strLen / 2;
    if (modhex) {
        if (yubikey_modhex_p(str)) {
            yubikey_modhex_decode((char *)result, str, strLen);
            return 1;
        }
    } else {
        if (yubikey_hex_p(str)) {
            yubikey_hex_decode((char *)result, str, strLen);
            return 1;
        }
    }

    return 0;
}

int YubiKeyUtil::hexModhexEncode(char *result, size_t *resultLen,
                                 const unsigned char *str, size_t strLen,
                                 bool modhex)
{
    *resultLen = strLen * 2;
    if (modhex) {
        yubikey_modhex_encode((char *)result, (char *)str, strLen);
        return 1;
    } else {
        yubikey_hex_encode((char *)result, (char *)str, strLen);
        return 1;
    }

    return 0;
}

QString YubiKeyUtil::qstrHexEncode(const unsigned char *str, size_t strLen) {
    char result[strLen * 2 + 1];
    size_t resultLen = 0;
    memset(&result, 0, sizeof(result));

    int rc = hexModhexEncode(result, &resultLen, str, strLen, false);

    if(rc > 0) {
        qDebug() << "hex encoded string: " << QString(result) << sizeof(result);
        return QString::fromLocal8Bit(result);
    }

    return QString("");
}

void YubiKeyUtil::qstrHexDecode(unsigned char *result, size_t *resultLen,
                                const QString &str) {

    if(str.size() % 2 != 0) {
        return;
    }

    char hex[MAX_SIZE];
    YubiKeyUtil::qstrToRaw(hex, sizeof(hex), str);
    size_t hexLen = strlen(hex);

    //Hex decode
    hexModhexDecode(result, resultLen,
                    hex, hexLen,
                    0, MAX_SIZE,
                    false);
}

QString YubiKeyUtil::qstrModhexEncode(const unsigned char *str, size_t strLen) {
    char result[strLen * 2 + 1];
    size_t resultLen = 0;
    memset(&result, 0, sizeof(result));

    int rc = hexModhexEncode(result, &resultLen, str, strLen, true);

    if(rc > 0) {
        qDebug() << "modhex encoded string: " << QString(result) << sizeof(result);
        return QString::fromLocal8Bit(result);
    }

    return QString("");
}

void YubiKeyUtil::qstrModhexDecode(unsigned char *result, size_t *resultLen,
                                   const QString &str) {

    if(str.size() % 2 != 0) {
        return;
    }

    char modhex[MAX_SIZE];
    YubiKeyUtil::qstrToRaw(modhex, sizeof(modhex), str);
    size_t modhexLen = strlen(modhex);

    //Hex decode
    hexModhexDecode(result, resultLen,
                    modhex, modhexLen,
                    0, MAX_SIZE,
                    true);
}

void YubiKeyUtil::qstrDecDecode(unsigned char *result, size_t *resultLen,
                                const QString &str) {
    if(str.size() % 2 != 0) {
        return;
    }

    *resultLen = str.size() / 2;

    for(size_t i = 0; i < *resultLen; i++) {
        unsigned char val = str.mid(i * 2, 2).toInt();
        result[i] = ((val / 10) << 4) | (val % 10);
    }
}

void YubiKeyUtil::qstrToRaw(char *result, size_t resultLen,
                            const QString &str) {
    QByteArray strByteArr = str.toLocal8Bit();

    size_t strLen = strByteArr.size() + 1;
    strLen = (resultLen < strLen)? resultLen : strLen;

    memset(result, 0, strLen);
    strncpy(result, (char *) strByteArr.data(), strLen);
}

void YubiKeyUtil::qstrClean(QString *str, size_t maxSize, bool reverse) {
    *str = str->toLower();

    QRegExp rx("[^0-9a-f]");
    *str = str->replace(rx, QString(""));

    if(maxSize > 0) {
        if(reverse) {
            *str = str->rightJustified(maxSize, '0', true);
        } else {
            *str = str->leftJustified(maxSize, '0', true);
        }
    }
}

void YubiKeyUtil::qstrModhexClean(QString *str, size_t maxSize, bool reverse) {
    *str = str->toLower();

    QRegExp rx("[^b-lnrt-v]");
    *str = str->replace(rx, QString(""));

    if(maxSize > 0) {
        if(reverse) {
            *str = str->rightJustified(maxSize, 'c', true);
        } else {
            *str = str->leftJustified(maxSize, 'c', true);
        }
    }
}

int YubiKeyUtil::generateRandom(unsigned char *result, size_t resultLen) {
    size_t bufSize = resultLen;

    unsigned char buf[bufSize];
    memset(&buf, 0, sizeof(buf));

    size_t bufLen = 0;

#ifdef Q_OS_WIN
    CRandom random;
    random.getRand(buf, bufSize);

    bufLen = sizeof(buf);
#else
    const char *random_places[] = {
        "/dev/srandom",
        "/dev/urandom",
        "/dev/random",
        0
    };

    const char **random_place;

    for (random_place = random_places; *random_place; random_place++) {
        FILE *random_file = fopen(*random_place, "r");
        if (random_file) {
            size_t read_bytes = 0;

            while (read_bytes < bufSize) {
                size_t n = fread(&buf[read_bytes],
                                 1, bufSize - read_bytes,
                                 random_file);
                read_bytes += n;
            }

            fclose(random_file);

            bufLen = sizeof(buf);

            break; /* from for loop */
        }
    }
#endif

    if(bufLen > 0) {
        memcpy(result, buf, bufLen);
        return 1;
    }

    return 0;
}

QString YubiKeyUtil::generateRandomHex(size_t resultLen) {
    QString result("");

    if (resultLen % 2 != 0) {
        return result;
    }

    size_t bufSize = resultLen / 2;
    unsigned char buf[bufSize];
    memset(&buf, 0, sizeof(buf));

    if(generateRandom(buf, bufSize) > 0) {
        result = qstrHexEncode(buf, bufSize);
    }

    return result;
}

QString YubiKeyUtil::generateRandomModhex(size_t resultLen) {
    QString result("");

    if (resultLen % 2 != 0) {
        return result;
    }

    size_t bufSize = resultLen / 2;
    unsigned char buf[bufSize];
    memset(&buf, 0, sizeof(buf));

    if(generateRandom(buf, bufSize) > 0) {
        result = qstrModhexEncode(buf, bufSize);
    }

    return result;
}

QString YubiKeyUtil::getNextHex(size_t resultLen,
                                const QString &str, int scheme) {
    QString result("");

    qDebug() << "str = " << str
            << " len = " << str.length();

    switch(scheme) {
    case GEN_SCHEME_FIXED:
        result = str;
        break;

    case GEN_SCHEME_INCR:
        {
            //Hex clean
            QString hexStr(str);
            qstrClean(&hexStr, resultLen);

            //Hex decode
            unsigned char hexDecoded[MAX_SIZE];
            size_t hexDecodedLen = 0;
            memset(&hexDecoded, 0, sizeof(hexDecoded));

            qstrHexDecode(hexDecoded, &hexDecodedLen, hexStr);
            if(hexDecodedLen <= 0) {
                break;
            }

            qDebug() << "hexDecoded = " << QString((char*)hexDecoded)
                    << " len = " << hexDecodedLen;

            //Increment
            for (int i = hexDecodedLen; i--; ) {
                if (++hexDecoded[i]) {
                    break;
                }
            }

            //Hex encode
            result = qstrHexEncode(hexDecoded, hexDecodedLen);

            qDebug() << "hexEncoded = " << result
                    << " len = " << result.size();
        }
        break;

    case GEN_SCHEME_RAND:
        result = generateRandomHex(resultLen);
        break;
    }

    return result;
}

QString YubiKeyUtil::getNextModhex(size_t resultLen,
                                   const QString &str, int scheme) {
    QString result("");

    qDebug() << "str = " << str
            << " len = " << str.length();

    switch(scheme) {
    case GEN_SCHEME_FIXED:
        result = str;
        break;

    case GEN_SCHEME_INCR:
        {
            //Modhex clean
            QString modhexStr(str);
            qstrModhexClean(&modhexStr, resultLen);

            //Modhex decode
            unsigned char modhexDecoded[MAX_SIZE];
            size_t modhexDecodedLen = 0;
            memset(&modhexDecoded, 0, sizeof(modhexDecoded));

            qstrModhexDecode(modhexDecoded, &modhexDecodedLen, modhexStr);
            if(modhexDecodedLen <= 0) {
                break;
            }

            qDebug() << "modhexDecoded = " << QString((char*)modhexDecoded)
                    << " len = " << modhexDecodedLen;

            //Increment
            for (int i = modhexDecodedLen; i--; ) {
                if (++modhexDecoded[i]) {
                    break;
                }
            }

            //Modhex encode
            result = qstrModhexEncode(modhexDecoded, modhexDecodedLen);

            qDebug() << "modhexEncoded = " << result
                    << " len = " << result.size();
        }
        break;

    case GEN_SCHEME_RAND:
        result = generateRandomModhex(resultLen);
        break;
    }

    return result;
}

void YubiKeyUtil::hexdump(void *buffer, int size) {
    unsigned char *p = (unsigned char *)buffer;
    int i;
    for (i = 0; i < size; i++) {
        fprintf(stderr, "\\x%02x", *p);
        p++;
    }
    fprintf(stderr, "\n");
    fflush(stderr);
}
<commit_msg>include QRegExp<commit_after>/*
Copyright (C) 2011-2014 Yubico AB.  All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

   1. Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

   2. Redistributions in binary form must reproduce the above
      copyright notice, this list of conditions and the following
      disclaimer in the documentation and/or other materials provided
      with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "yubikeyutil.h"
#include <yubikey.h>
#include <QDebug>
#include <QRegExp>
#ifdef Q_OS_WIN
#include "crandom.h"
#endif

YubiKeyUtil::~YubiKeyUtil() {
}

int YubiKeyUtil::hexModhexDecode(unsigned char *result, size_t *resultLen,
                                 const char *str, size_t strLen,
                                 size_t minSize, size_t maxSize,
                                 bool modhex)
{
    if ((strLen % 2 != 0) || (strLen < minSize) || (strLen > maxSize)) {
        return -1;
    }

    *resultLen = strLen / 2;
    if (modhex) {
        if (yubikey_modhex_p(str)) {
            yubikey_modhex_decode((char *)result, str, strLen);
            return 1;
        }
    } else {
        if (yubikey_hex_p(str)) {
            yubikey_hex_decode((char *)result, str, strLen);
            return 1;
        }
    }

    return 0;
}

int YubiKeyUtil::hexModhexEncode(char *result, size_t *resultLen,
                                 const unsigned char *str, size_t strLen,
                                 bool modhex)
{
    *resultLen = strLen * 2;
    if (modhex) {
        yubikey_modhex_encode((char *)result, (char *)str, strLen);
        return 1;
    } else {
        yubikey_hex_encode((char *)result, (char *)str, strLen);
        return 1;
    }

    return 0;
}

QString YubiKeyUtil::qstrHexEncode(const unsigned char *str, size_t strLen) {
    char result[strLen * 2 + 1];
    size_t resultLen = 0;
    memset(&result, 0, sizeof(result));

    int rc = hexModhexEncode(result, &resultLen, str, strLen, false);

    if(rc > 0) {
        qDebug() << "hex encoded string: " << QString(result) << sizeof(result);
        return QString::fromLocal8Bit(result);
    }

    return QString("");
}

void YubiKeyUtil::qstrHexDecode(unsigned char *result, size_t *resultLen,
                                const QString &str) {

    if(str.size() % 2 != 0) {
        return;
    }

    char hex[MAX_SIZE];
    YubiKeyUtil::qstrToRaw(hex, sizeof(hex), str);
    size_t hexLen = strlen(hex);

    //Hex decode
    hexModhexDecode(result, resultLen,
                    hex, hexLen,
                    0, MAX_SIZE,
                    false);
}

QString YubiKeyUtil::qstrModhexEncode(const unsigned char *str, size_t strLen) {
    char result[strLen * 2 + 1];
    size_t resultLen = 0;
    memset(&result, 0, sizeof(result));

    int rc = hexModhexEncode(result, &resultLen, str, strLen, true);

    if(rc > 0) {
        qDebug() << "modhex encoded string: " << QString(result) << sizeof(result);
        return QString::fromLocal8Bit(result);
    }

    return QString("");
}

void YubiKeyUtil::qstrModhexDecode(unsigned char *result, size_t *resultLen,
                                   const QString &str) {

    if(str.size() % 2 != 0) {
        return;
    }

    char modhex[MAX_SIZE];
    YubiKeyUtil::qstrToRaw(modhex, sizeof(modhex), str);
    size_t modhexLen = strlen(modhex);

    //Hex decode
    hexModhexDecode(result, resultLen,
                    modhex, modhexLen,
                    0, MAX_SIZE,
                    true);
}

void YubiKeyUtil::qstrDecDecode(unsigned char *result, size_t *resultLen,
                                const QString &str) {
    if(str.size() % 2 != 0) {
        return;
    }

    *resultLen = str.size() / 2;

    for(size_t i = 0; i < *resultLen; i++) {
        unsigned char val = str.mid(i * 2, 2).toInt();
        result[i] = ((val / 10) << 4) | (val % 10);
    }
}

void YubiKeyUtil::qstrToRaw(char *result, size_t resultLen,
                            const QString &str) {
    QByteArray strByteArr = str.toLocal8Bit();

    size_t strLen = strByteArr.size() + 1;
    strLen = (resultLen < strLen)? resultLen : strLen;

    memset(result, 0, strLen);
    strncpy(result, (char *) strByteArr.data(), strLen);
}

void YubiKeyUtil::qstrClean(QString *str, size_t maxSize, bool reverse) {
    *str = str->toLower();

    QRegExp rx("[^0-9a-f]");
    *str = str->replace(rx, QString(""));

    if(maxSize > 0) {
        if(reverse) {
            *str = str->rightJustified(maxSize, '0', true);
        } else {
            *str = str->leftJustified(maxSize, '0', true);
        }
    }
}

void YubiKeyUtil::qstrModhexClean(QString *str, size_t maxSize, bool reverse) {
    *str = str->toLower();

    QRegExp rx("[^b-lnrt-v]");
    *str = str->replace(rx, QString(""));

    if(maxSize > 0) {
        if(reverse) {
            *str = str->rightJustified(maxSize, 'c', true);
        } else {
            *str = str->leftJustified(maxSize, 'c', true);
        }
    }
}

int YubiKeyUtil::generateRandom(unsigned char *result, size_t resultLen) {
    size_t bufSize = resultLen;

    unsigned char buf[bufSize];
    memset(&buf, 0, sizeof(buf));

    size_t bufLen = 0;

#ifdef Q_OS_WIN
    CRandom random;
    random.getRand(buf, bufSize);

    bufLen = sizeof(buf);
#else
    const char *random_places[] = {
        "/dev/srandom",
        "/dev/urandom",
        "/dev/random",
        0
    };

    const char **random_place;

    for (random_place = random_places; *random_place; random_place++) {
        FILE *random_file = fopen(*random_place, "r");
        if (random_file) {
            size_t read_bytes = 0;

            while (read_bytes < bufSize) {
                size_t n = fread(&buf[read_bytes],
                                 1, bufSize - read_bytes,
                                 random_file);
                read_bytes += n;
            }

            fclose(random_file);

            bufLen = sizeof(buf);

            break; /* from for loop */
        }
    }
#endif

    if(bufLen > 0) {
        memcpy(result, buf, bufLen);
        return 1;
    }

    return 0;
}

QString YubiKeyUtil::generateRandomHex(size_t resultLen) {
    QString result("");

    if (resultLen % 2 != 0) {
        return result;
    }

    size_t bufSize = resultLen / 2;
    unsigned char buf[bufSize];
    memset(&buf, 0, sizeof(buf));

    if(generateRandom(buf, bufSize) > 0) {
        result = qstrHexEncode(buf, bufSize);
    }

    return result;
}

QString YubiKeyUtil::generateRandomModhex(size_t resultLen) {
    QString result("");

    if (resultLen % 2 != 0) {
        return result;
    }

    size_t bufSize = resultLen / 2;
    unsigned char buf[bufSize];
    memset(&buf, 0, sizeof(buf));

    if(generateRandom(buf, bufSize) > 0) {
        result = qstrModhexEncode(buf, bufSize);
    }

    return result;
}

QString YubiKeyUtil::getNextHex(size_t resultLen,
                                const QString &str, int scheme) {
    QString result("");

    qDebug() << "str = " << str
            << " len = " << str.length();

    switch(scheme) {
    case GEN_SCHEME_FIXED:
        result = str;
        break;

    case GEN_SCHEME_INCR:
        {
            //Hex clean
            QString hexStr(str);
            qstrClean(&hexStr, resultLen);

            //Hex decode
            unsigned char hexDecoded[MAX_SIZE];
            size_t hexDecodedLen = 0;
            memset(&hexDecoded, 0, sizeof(hexDecoded));

            qstrHexDecode(hexDecoded, &hexDecodedLen, hexStr);
            if(hexDecodedLen <= 0) {
                break;
            }

            qDebug() << "hexDecoded = " << QString((char*)hexDecoded)
                    << " len = " << hexDecodedLen;

            //Increment
            for (int i = hexDecodedLen; i--; ) {
                if (++hexDecoded[i]) {
                    break;
                }
            }

            //Hex encode
            result = qstrHexEncode(hexDecoded, hexDecodedLen);

            qDebug() << "hexEncoded = " << result
                    << " len = " << result.size();
        }
        break;

    case GEN_SCHEME_RAND:
        result = generateRandomHex(resultLen);
        break;
    }

    return result;
}

QString YubiKeyUtil::getNextModhex(size_t resultLen,
                                   const QString &str, int scheme) {
    QString result("");

    qDebug() << "str = " << str
            << " len = " << str.length();

    switch(scheme) {
    case GEN_SCHEME_FIXED:
        result = str;
        break;

    case GEN_SCHEME_INCR:
        {
            //Modhex clean
            QString modhexStr(str);
            qstrModhexClean(&modhexStr, resultLen);

            //Modhex decode
            unsigned char modhexDecoded[MAX_SIZE];
            size_t modhexDecodedLen = 0;
            memset(&modhexDecoded, 0, sizeof(modhexDecoded));

            qstrModhexDecode(modhexDecoded, &modhexDecodedLen, modhexStr);
            if(modhexDecodedLen <= 0) {
                break;
            }

            qDebug() << "modhexDecoded = " << QString((char*)modhexDecoded)
                    << " len = " << modhexDecodedLen;

            //Increment
            for (int i = modhexDecodedLen; i--; ) {
                if (++modhexDecoded[i]) {
                    break;
                }
            }

            //Modhex encode
            result = qstrModhexEncode(modhexDecoded, modhexDecodedLen);

            qDebug() << "modhexEncoded = " << result
                    << " len = " << result.size();
        }
        break;

    case GEN_SCHEME_RAND:
        result = generateRandomModhex(resultLen);
        break;
    }

    return result;
}

void YubiKeyUtil::hexdump(void *buffer, int size) {
    unsigned char *p = (unsigned char *)buffer;
    int i;
    for (i = 0; i < size; i++) {
        fprintf(stderr, "\\x%02x", *p);
        p++;
    }
    fprintf(stderr, "\n");
    fflush(stderr);
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: toxhlp.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-17 14:32:43 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_I18N_XINDEXENTRYSUPPLIER_HPP_
#include <drafts/com/sun/star/i18n/XExtendedIndexEntrySupplier.hpp>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _TOXWRAP_HXX
#include <toxwrap.hxx>
#endif

IndexEntrySupplierWrapper::IndexEntrySupplierWrapper()
{
    ::com::sun::star::uno::Reference<
            ::com::sun::star::lang::XMultiServiceFactory > rxMSF =
                                    ::comphelper::getProcessServiceFactory();

    try {
        STAR_REFERENCE( uno::XInterface ) xI =
            rxMSF->createInstance( ::rtl::OUString::createFromAscii(
                                "com.sun.star.i18n.IndexEntrySupplier" ) );
        if( xI.is() )
        {
            UNO_NMSPC::Any x = xI->queryInterface( ::getCppuType(
                    (const com::sun::star::uno::Reference< drafts::com::sun::star::i18n::XExtendedIndexEntrySupplier>*)0) );
            x >>= xIES;
        }
    }
    catch ( UNO_NMSPC::Exception& e )
    {
#ifndef PRODUCT
        ByteString aMsg( "IndexEntrySupplierWrapper: Exception caught\n" );
        aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
        DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
    }
}

IndexEntrySupplierWrapper::~IndexEntrySupplierWrapper()
{
}

String IndexEntrySupplierWrapper::GetIndexKey( const String& rTxt,
                                               const String& rTxtReading,
                                               const STAR_NMSPC::lang::Locale& rLocale ) const
{
    String sRet;
    try {
        sRet = xIES->getIndexKey( rTxt, rTxtReading, rLocale );
    }
    catch ( UNO_NMSPC::Exception& e )
    {
#ifndef PRODUCT
        ByteString aMsg( "getIndexKey: Exception caught\n" );
        aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
        DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
    }
    return sRet;
}

String IndexEntrySupplierWrapper::GetFollowingText( BOOL bMorePages ) const
{
    String sRet;
    try {
        sRet = xIES->getIndexFollowPageWord( bMorePages, aLcl );
    }
    catch ( UNO_NMSPC::Exception& e )
    {
#ifndef PRODUCT
        ByteString aMsg( "getIndexFollowPageWord: Exception caught\n" );
        aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
        DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
    }
    return sRet;
}

STAR_NMSPC::uno::Sequence< ::rtl::OUString >
IndexEntrySupplierWrapper::GetAlgorithmList( const STAR_NMSPC::lang::Locale& rLcl ) const
{
    ::com::sun::star::uno::Sequence< ::rtl::OUString > sRet;

    try {
        sRet = xIES->getAlgorithmList( rLcl );
    }
    catch ( UNO_NMSPC::Exception& e )
    {
#ifndef PRODUCT
        ByteString aMsg( "getAlgorithmList: Exception caught\n" );
        aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
        DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
    }
    return sRet;
}

STAR_NMSPC::uno::Sequence < com::sun::star::lang::Locale >
IndexEntrySupplierWrapper::GetLocaleList() const
{
    ::com::sun::star::uno::Sequence< com::sun::star::lang::Locale > sRet;

    try {
        sRet = xIES->getLocaleList();
    }
    catch ( UNO_NMSPC::Exception& e )
    {
#ifndef PRODUCT
        ByteString aMsg( "getLocaleList: Exception caught\n" );
        aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
        DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
    }
    return sRet;
}

sal_Bool IndexEntrySupplierWrapper::LoadAlgorithm(
        const STAR_NMSPC::lang::Locale& rLcl,
        const String& sSortAlgorithm, long nOptions ) const
{
    sal_Bool bRet = sal_False;
    try {
        bRet = xIES->loadAlgorithm( rLcl, sSortAlgorithm, nOptions );
    }
    catch ( UNO_NMSPC::Exception& e )
    {
#ifndef PRODUCT
        ByteString aMsg( "loadAlgorithm: Exception caught\n" );
        aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
        DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
    }
    return bRet;
}

sal_Int16 IndexEntrySupplierWrapper::CompareIndexEntry(
            const String& rTxt1, const String& rTxtReading1,
            const STAR_NMSPC::lang::Locale& rLocale1,
            const String& rTxt2, const String& rTxtReading2,
            const STAR_NMSPC::lang::Locale& rLocale2 ) const
{
    sal_Int16 nRet = 0;
    try {
        nRet = xIES->compareIndexEntry( rTxt1, rTxtReading1, rLocale1,
                                        rTxt2, rTxtReading2, rLocale2 );
    }
    catch ( UNO_NMSPC::Exception& e )
    {
#ifndef PRODUCT
        ByteString aMsg( "compareIndexEntry: Exception caught\n" );
        aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
        DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
    }
    return nRet;
}
<commit_msg>INTEGRATION: CWS i18napi (1.4.164); FILE MERGED 2003/04/19 20:27:01 er 1.4.164.1: #107686# move drafts.com.sun.star.i18n to com.sun.star.i18n<commit_after>/*************************************************************************
 *
 *  $RCSfile: toxhlp.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-24 10:54:23 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_I18N_XINDEXENTRYSUPPLIER_HPP_
#include <com/sun/star/i18n/XExtendedIndexEntrySupplier.hpp>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif

#ifndef _TOXWRAP_HXX
#include <toxwrap.hxx>
#endif

IndexEntrySupplierWrapper::IndexEntrySupplierWrapper()
{
    ::com::sun::star::uno::Reference<
            ::com::sun::star::lang::XMultiServiceFactory > rxMSF =
                                    ::comphelper::getProcessServiceFactory();

    try {
        STAR_REFERENCE( uno::XInterface ) xI =
            rxMSF->createInstance( ::rtl::OUString::createFromAscii(
                                "com.sun.star.i18n.IndexEntrySupplier" ) );
        if( xI.is() )
        {
            UNO_NMSPC::Any x = xI->queryInterface( ::getCppuType(
                    (const com::sun::star::uno::Reference< com::sun::star::i18n::XExtendedIndexEntrySupplier>*)0) );
            x >>= xIES;
        }
    }
    catch ( UNO_NMSPC::Exception& e )
    {
#ifndef PRODUCT
        ByteString aMsg( "IndexEntrySupplierWrapper: Exception caught\n" );
        aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
        DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
    }
}

IndexEntrySupplierWrapper::~IndexEntrySupplierWrapper()
{
}

String IndexEntrySupplierWrapper::GetIndexKey( const String& rTxt,
                                               const String& rTxtReading,
                                               const STAR_NMSPC::lang::Locale& rLocale ) const
{
    String sRet;
    try {
        sRet = xIES->getIndexKey( rTxt, rTxtReading, rLocale );
    }
    catch ( UNO_NMSPC::Exception& e )
    {
#ifndef PRODUCT
        ByteString aMsg( "getIndexKey: Exception caught\n" );
        aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
        DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
    }
    return sRet;
}

String IndexEntrySupplierWrapper::GetFollowingText( BOOL bMorePages ) const
{
    String sRet;
    try {
        sRet = xIES->getIndexFollowPageWord( bMorePages, aLcl );
    }
    catch ( UNO_NMSPC::Exception& e )
    {
#ifndef PRODUCT
        ByteString aMsg( "getIndexFollowPageWord: Exception caught\n" );
        aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
        DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
    }
    return sRet;
}

STAR_NMSPC::uno::Sequence< ::rtl::OUString >
IndexEntrySupplierWrapper::GetAlgorithmList( const STAR_NMSPC::lang::Locale& rLcl ) const
{
    ::com::sun::star::uno::Sequence< ::rtl::OUString > sRet;

    try {
        sRet = xIES->getAlgorithmList( rLcl );
    }
    catch ( UNO_NMSPC::Exception& e )
    {
#ifndef PRODUCT
        ByteString aMsg( "getAlgorithmList: Exception caught\n" );
        aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
        DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
    }
    return sRet;
}

STAR_NMSPC::uno::Sequence < com::sun::star::lang::Locale >
IndexEntrySupplierWrapper::GetLocaleList() const
{
    ::com::sun::star::uno::Sequence< com::sun::star::lang::Locale > sRet;

    try {
        sRet = xIES->getLocaleList();
    }
    catch ( UNO_NMSPC::Exception& e )
    {
#ifndef PRODUCT
        ByteString aMsg( "getLocaleList: Exception caught\n" );
        aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
        DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
    }
    return sRet;
}

sal_Bool IndexEntrySupplierWrapper::LoadAlgorithm(
        const STAR_NMSPC::lang::Locale& rLcl,
        const String& sSortAlgorithm, long nOptions ) const
{
    sal_Bool bRet = sal_False;
    try {
        bRet = xIES->loadAlgorithm( rLcl, sSortAlgorithm, nOptions );
    }
    catch ( UNO_NMSPC::Exception& e )
    {
#ifndef PRODUCT
        ByteString aMsg( "loadAlgorithm: Exception caught\n" );
        aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
        DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
    }
    return bRet;
}

sal_Int16 IndexEntrySupplierWrapper::CompareIndexEntry(
            const String& rTxt1, const String& rTxtReading1,
            const STAR_NMSPC::lang::Locale& rLocale1,
            const String& rTxt2, const String& rTxtReading2,
            const STAR_NMSPC::lang::Locale& rLocale2 ) const
{
    sal_Int16 nRet = 0;
    try {
        nRet = xIES->compareIndexEntry( rTxt1, rTxtReading1, rLocale1,
                                        rTxt2, rTxtReading2, rLocale2 );
    }
    catch ( UNO_NMSPC::Exception& e )
    {
#ifndef PRODUCT
        ByteString aMsg( "compareIndexEntry: Exception caught\n" );
        aMsg += ByteString( String( e.Message ), RTL_TEXTENCODING_UTF8 );
        DBG_ERRORFILE( aMsg.GetBuffer() );
#endif
    }
    return nRet;
}
<|endoftext|>


<commit_before>#ifndef HYDRAULICACKUMULATOR_HPP_INCLUDED
#define HYDRAULICACKUMULATOR_HPP_INCLUDED

#include <iostream>
#include "ComponentEssentials.h"
#include "ComponentUtilities.h"
#include <math.h>

//!
//! @file HydraulicAckumulator.hpp
//! @author Petter Krus <petter.krus@liu.se>
//! @date Mon 12 Sep 2011 22:31:30
//! @brief Hydraulic lossless ackumulator
//! @ingroup HydraulicComponents
//!
//This component is generated by COMPGEN for HOPSAN-NG simulation
//from
/*{, C:, Documents and Settings, petkr14, My Documents, \
CompgenNG}/HydraulicComponentsNG.nb*/

using namespace hopsan;

class HydraulicAckumulator : public ComponentQ
{
private:
     double mp0;
     double mV0;
     double mKca;
     double mkappa;
     Port *mpP1;
     Port *mpPVa;
     Port *mpPpa;
     double delayParts1[9];
     double delayParts2[9];
     double delayParts3[9];
     double delayParts4[9];
     Matrix jacobianMatrix;
     Vec systemEquations;
     Matrix delayedPart;
     int i;
     int iter;
     int mNoiter;
     int jsyseqnweight[4];
     int order[4];
     int mNstep;
     //Port P1 variable
     double p1;
     double q1;
     double c1;
     double Zc1;
     //inputVariables
     //outputVariables
     double Va;
     double pa;
     //Port P1 pointer
     double *mpND_p1;
     double *mpND_q1;
     double *mpND_c1;
     double *mpND_Zc1;
     //Delay declarations
     //inputVariables pointers
     //outputVariables pointers
     double *mpND_Va;
     double *mpND_pa;
     Delay mDelayedPart10;
     Delay mDelayedPart20;
     Delay mDelayedPart21;
     Delay mDelayedPart30;

     EquationSystemSolver *pSolver;

public:
     static Component *Creator()
     {
        return new HydraulicAckumulator();
     }

     HydraulicAckumulator(const double p0 = 1.e7
                         ,const double V0 = 0.001
                         ,const double Kca = 1.e-8
                         ,const double kappa = 1.2
                             )
        : ComponentQ()
     {
        mNstep=9;
        jacobianMatrix.create(4,4);
        systemEquations.create(4);
        delayedPart.create(5,6);
        mNoiter=2;
        jsyseqnweight[0]=1;
        jsyseqnweight[1]=0.67;
        jsyseqnweight[2]=0.5;
        jsyseqnweight[3]=0.5;

        mp0 = p0;
        mV0 = V0;
        mKca = Kca;
        mkappa = kappa;

        //Add ports to the component
        mpP1=addPowerPort("P1","NodeHydraulic");

        //Add inputVariables ports to the component

        //Add outputVariables ports to the component
        mpPVa=addWritePort("PVa","NodeSignal", Port::NOTREQUIRED);
        mpPpa=addWritePort("Ppa","NodeSignal", Port::NOTREQUIRED);

        //Register changable parameters to the HOPSAN++ core
        registerParameter("p0", "Preload pressure", "N/m^2", mp0);
        registerParameter("V0", "Ack. Volume", "m^3", mV0);
        registerParameter("Kca", "Flow coefficent", "m^3/Pa", mKca);
        registerParameter("kappa", "polytropic exp. of gas", "", mkappa);

        pSolver = new EquationSystemSolver(this, 4);
     }

    void initialize()
     {
        //Read port variable pointers from nodes
        //Port P1
        mpND_p1=getSafeNodeDataPtr(mpP1, NodeHydraulic::PRESSURE);
        mpND_q1=getSafeNodeDataPtr(mpP1, NodeHydraulic::FLOW);
        mpND_c1=getSafeNodeDataPtr(mpP1, NodeHydraulic::WAVEVARIABLE);
        mpND_Zc1=getSafeNodeDataPtr(mpP1, NodeHydraulic::CHARIMP);
        //Read inputVariables pointers from nodes
        //Read outputVariable pointers from nodes
        mpND_Va=getSafeNodeDataPtr(mpPVa, NodeSignal::VALUE);
        mpND_pa=getSafeNodeDataPtr(mpPpa, NodeSignal::VALUE);

        //Read variables from nodes
        //Port P1
        p1 = (*mpND_p1);
        q1 = (*mpND_q1);
        c1 = (*mpND_c1);
        Zc1 = (*mpND_Zc1);

        //Read inputVariables from nodes

        //Read outputVariables from nodes
        Va = mpPVa->getStartValue(NodeSignal::VALUE);
        pa = mpPpa->getStartValue(NodeSignal::VALUE);

        //Initialize delays
        delayParts2[1] = (-2*Va - mKca*mTimestep*p1*limit(onPositive(p1 - pa) \
+ onPositive(Va),0.,1.) + mKca*mTimestep*pa*limit(onPositive(p1 - pa) + \
onPositive(Va),0.,1.))/2.;
        mDelayedPart21.initialize(mNstep,delayParts2[1]);

        delayedPart[1][1] = delayParts1[1];
        delayedPart[2][1] = delayParts2[1];
        delayedPart[3][1] = delayParts3[1];
        delayedPart[4][1] = delayParts4[1];
     }
    void simulateOneTimestep()
     {
        Vec stateVar(4);
        Vec stateVark(4);
        Vec deltaStateVar(4);

        //Read variables from nodes
        //Port P1
        c1 = (*mpND_c1);
        Zc1 = (*mpND_Zc1);

        //Read inputVariables from nodes

        //LocalExpressions

        //Initializing variable vector for Newton-Raphson
        stateVark[0] = q1;
        stateVark[1] = Va;
        stateVark[2] = pa;
        stateVark[3] = p1;

        //Iterative solution using Newton-Rapshson
        for(iter=1;iter<=mNoiter;iter++)
        {
         //Ackumulator
         //Differential-algebraic system of equation parts

          //Assemble differential-algebraic equations
          systemEquations[0] =q1 + mKca*(p1 - pa)*limit(onPositive(p1 - pa) + onPositive(Va),0.,1.);
          systemEquations[1] =Va - limit(-(mKca*mTimestep*(-p1 + pa)*limit(onPositive(p1 - pa) + onPositive(Va),0.,1.))/2. - delayedPart[2][1],0.,mV0);
          systemEquations[2] =pa - (mp0*Power(mV0,mkappa))/Power(mV0 - Va,mkappa);
          systemEquations[3] =p1 - (c1 + q1*Zc1)*onPositive(p1);

          //Jacobian matrix
          jacobianMatrix[0][0] = 1;
          jacobianMatrix[0][1] = 0;
          jacobianMatrix[0][2] = -(mKca*limit(onPositive(p1 - pa) + onPositive(Va),0.,1.));
          jacobianMatrix[0][3] = mKca*limit(onPositive(p1 - pa) + onPositive(Va),0.,1.);
          jacobianMatrix[1][0] = 0;
          jacobianMatrix[1][1] = 1;
          jacobianMatrix[1][2] = (mKca*mTimestep*dxLimit(-(mKca*mTimestep*(-p1 + pa)*limit(onPositive(p1 - pa) + onPositive(Va),0.,1.))/2. - delayedPart[2][1],0.,mV0)*limit(onPositive(p1 - pa) + onPositive(Va),0.,1.))/2.;
          jacobianMatrix[1][3] = -(mKca*mTimestep*dxLimit(-(mKca*mTimestep*(-p1 + pa)*limit(onPositive(p1 - pa) + onPositive(Va),0.,1.))/2. - delayedPart[2][1],0.,mV0)*limit(onPositive(p1 - pa) + onPositive(Va),0.,1.))/2.;
          jacobianMatrix[2][0] = 0;
          jacobianMatrix[2][1] = -(mkappa*mp0*Power(mV0,mkappa)*Power(mV0 - Va,-1 - mkappa));
          jacobianMatrix[2][2] = 1;
          jacobianMatrix[2][3] = 0;
          jacobianMatrix[3][0] = -(Zc1*onPositive(p1));
          jacobianMatrix[3][1] = 0;
          jacobianMatrix[3][2] = 0;
          jacobianMatrix[3][3] = 1;

          //Solving equation using LU-faktorisation
          pSolver->solve(jacobianMatrix, systemEquations, stateVark, iter);

        q1=stateVark[0];
        Va=stateVark[1];
        pa=stateVark[2];
        p1=stateVark[3];
        }
        //Calculate the delayed parts
        delayParts2[1] = (-2*Va - mKca*mTimestep*p1*limit(onPositive(p1 - pa) \
+ onPositive(Va),0.,1.) + mKca*mTimestep*pa*limit(onPositive(p1 - pa) + \
onPositive(Va),0.,1.))/2.;

        delayedPart[1][1] = delayParts1[1];
        delayedPart[2][1] = delayParts2[1];
        delayedPart[3][1] = delayParts3[1];
        delayedPart[4][1] = delayParts4[1];

        //Write new values to nodes
        //Port P1
        (*mpND_p1)=p1;
        (*mpND_q1)=q1;
        //outputVariables
        (*mpND_Va)=Va;
        (*mpND_pa)=pa;

        //Update the delayed variabels
        mDelayedPart21.update(delayParts2[1]);

     }
};
#endif // HYDRAULICACKUMULATOR_HPP_INCLUDED
<commit_msg>Hydraulic/HydraulicAckumulator.hpp is corrected. Behaviour when being empty was not correct before.<commit_after>#ifndef HYDRAULICACKUMULATOR_HPP_INCLUDED
#define HYDRAULICACKUMULATOR_HPP_INCLUDED

#include <iostream>
#include "ComponentEssentials.h"
#include "ComponentUtilities.h"
#include "math.h"

//!
//! @file HydraulicAckumulator.hpp
//! @author Petter Krus <petter.krus@liu.se>
//! @date Fri 13 Apr 2012 08:57:00
//! @brief Hydraulic lossless ackumulator
//! @ingroup HydraulicComponents
//!
//This component is generated by COMPGEN for HOPSAN-NG simulation
//from
/*{, C:, Documents and Settings, petkr14, My Documents, \
CompgenNG}/HydraulicComponentsNG.nb*/

using namespace hopsan;

class HydraulicAckumulator : public ComponentQ
{
private:
     double mp0;
     double mV0;
     double mKca;
     double mkappa;
     Port *mpP1;
     Port *mpPVa;
     Port *mpPpa;
     double delayParts1[9];
     double delayParts2[9];
     double delayParts3[9];
     double delayParts4[9];
     Matrix jacobianMatrix;
     Vec systemEquations;
     Matrix delayedPart;
     int i;
     int iter;
     int mNoiter;
     double jsyseqnweight[4];
     int order[4];
     int mNstep;
     //Port P1 variable
     double p1;
     double q1;
     double c1;
     double Zc1;
     //inputVariables
     //outputVariables
     double Va;
     double pa;
     //Port P1 pointer
     double *mpND_p1;
     double *mpND_q1;
     double *mpND_c1;
     double *mpND_Zc1;
     //Delay declarations
     //inputVariables pointers
     //outputVariables pointers
     double *mpND_Va;
     double *mpND_pa;
     Delay mDelayedPart10;
     Delay mDelayedPart11;
     Delay mDelayedPart20;
     Delay mDelayedPart30;
     EquationSystemSolver *mpSolver;

public:
     static Component *Creator()
     {
        return new HydraulicAckumulator();
     }

     HydraulicAckumulator() : ComponentQ()
     {
        const double p0 = 1.e7;
        const double V0 = 0.001;
        const double Kca = 1.e-8;
        const double kappa = 1.2;

        mNstep=9;
        jacobianMatrix.create(4,4);
        systemEquations.create(4);
        delayedPart.create(5,6);
        mNoiter=2;
        jsyseqnweight[0]=1;
        jsyseqnweight[1]=0.67;
        jsyseqnweight[2]=0.5;
        jsyseqnweight[3]=0.5;

        mp0 = p0;
        mV0 = V0;
        mKca = Kca;
        mkappa = kappa;

        //Add ports to the component
        mpP1=addPowerPort("P1","NodeHydraulic");

        //Add inputVariables ports to the component

        //Add outputVariables ports to the component
        mpPVa=addWritePort("PVa","NodeSignal", Port::NOTREQUIRED);
        mpPpa=addWritePort("Ppa","NodeSignal", Port::NOTREQUIRED);

        //Register changable parameters to the HOPSAN++ core
        registerParameter("p0", "Preload pressure", "N/m^2", mp0);
        registerParameter("V0", "Ack. Volume", "m^3", mV0);
        registerParameter("Kca", "Flow coefficent", "m^3/Pa", mKca);
        registerParameter("kappa", "polytropic exp. of gas", "", mkappa);
        mpSolver = new EquationSystemSolver(this,4);
     }

    void initialize()
     {
        //Read port variable pointers from nodes
        //Port P1
        mpND_p1=getSafeNodeDataPtr(mpP1, NodeHydraulic::PRESSURE);
        mpND_q1=getSafeNodeDataPtr(mpP1, NodeHydraulic::FLOW);
        mpND_c1=getSafeNodeDataPtr(mpP1, NodeHydraulic::WAVEVARIABLE);
        mpND_Zc1=getSafeNodeDataPtr(mpP1, NodeHydraulic::CHARIMP);
        //Read inputVariables pointers from nodes
        //Read outputVariable pointers from nodes
        mpND_Va=getSafeNodeDataPtr(mpPVa, NodeSignal::VALUE);
        mpND_pa=getSafeNodeDataPtr(mpPpa, NodeSignal::VALUE);

        //Read variables from nodes
        //Port P1
        p1 = (*mpND_p1);
        q1 = (*mpND_q1);
        c1 = (*mpND_c1);
        Zc1 = (*mpND_Zc1);

        //Read inputVariables from nodes

        //Read outputVariables from nodes
        Va = mpPVa->getStartValue(NodeSignal::VALUE);
        pa = mpPpa->getStartValue(NodeSignal::VALUE);

        //Initialize delays
        delayParts1[1] = (-(mKca*mTimestep*p1) + mKca*mTimestep*pa - \
2*Va)/2.;
        mDelayedPart11.initialize(mNstep,delayParts1[1]);

        delayedPart[1][1] = delayParts1[1];
        delayedPart[2][1] = delayParts2[1];
        delayedPart[3][1] = delayParts3[1];
        delayedPart[4][1] = delayParts4[1];
     }
    void simulateOneTimestep()
     {
        Vec stateVar(4);
        Vec stateVark(4);
        Vec deltaStateVar(4);

        //Read variables from nodes
        //Port P1
        c1 = (*mpND_c1);
        Zc1 = (*mpND_Zc1);

        //Read inputVariables from nodes

        //LocalExpressions

        //Initializing variable vector for Newton-Raphson
        stateVark[0] = Va;
        stateVark[1] = q1;
        stateVark[2] = pa;
        stateVark[3] = p1;

        //Iterative solution using Newton-Rapshson
        for(iter=1;iter<=mNoiter;iter++)
        {
         //Ackumulator
         //Differential-algebraic system of equation parts

          //Assemble differential-algebraic equations
          systemEquations[0] =Va - limit((mKca*mTimestep*(p1 - pa))/2. - \
delayedPart[1][1],0.,1);
          systemEquations[1] =q1 + mKca*(p1 - pa)*dxLimit((mKca*mTimestep*(p1 - pa))/2. - \
delayedPart[1][1],0.,1);
          systemEquations[2] =pa - (mp0*Power(mV0,mkappa))/Power(mV0 - \
Va,mkappa);
          systemEquations[3] =p1 - (c1 + q1*Zc1)*onPositive(p1);

          //Jacobian matrix
          jacobianMatrix[0][0] = 1;
          jacobianMatrix[0][1] = 0;
          jacobianMatrix[0][2] = (mKca*mTimestep*dxLimit((mKca*mTimestep*(p1 \
- pa))/2. - delayedPart[1][1],0.,1))/2.;
          jacobianMatrix[0][3] = -(mKca*mTimestep*dxLimit((mKca*mTimestep*(p1 \
- pa))/2. - delayedPart[1][1],0.,1))/2.;
          jacobianMatrix[1][0] = 0;
          jacobianMatrix[1][1] = 1;
          jacobianMatrix[1][2] = -(mKca*dxLimit((mKca*mTimestep*(p1 - pa))/2. - \
delayedPart[1][1],0.,1));
          jacobianMatrix[1][3] = mKca*dxLimit((mKca*mTimestep*(p1 - pa))/2. - \
delayedPart[1][1],0.,1);
          jacobianMatrix[2][0] = -(mkappa*mp0*Power(mV0,mkappa)*Power(mV0 - \
Va,-1 - mkappa));
          jacobianMatrix[2][1] = 0;
          jacobianMatrix[2][2] = 1;
          jacobianMatrix[2][3] = 0;
          jacobianMatrix[3][0] = 0;
          jacobianMatrix[3][1] = -(Zc1*onPositive(p1));
          jacobianMatrix[3][2] = 0;
          jacobianMatrix[3][3] = 1;

          //Solving equation using LU-faktorisation
          mpSolver->solve(jacobianMatrix, systemEquations, stateVark, iter);
          Va=stateVark[0];
          q1=stateVark[1];
          pa=stateVark[2];
          p1=stateVark[3];
        }

        //Calculate the delayed parts
        delayParts1[1] = (-(mKca*mTimestep*p1) + mKca*mTimestep*pa - \
2*Va)/2.;

        delayedPart[1][1] = delayParts1[1];
        delayedPart[2][1] = delayParts2[1];
        delayedPart[3][1] = delayParts3[1];
        delayedPart[4][1] = delayParts4[1];

        //Write new values to nodes
        //Port P1
        (*mpND_p1)=p1*onPositive(p1);
        (*mpND_q1)=q1;
        //outputVariables
        (*mpND_Va)=Va;
        (*mpND_pa)=pa;

        //Update the delayed variabels
        mDelayedPart11.update(delayParts1[1]);

     }
};
#endif // HYDRAULICACKUMULATOR_HPP_INCLUDED
<|endoftext|>


<commit_before>#include "Sniffer.hpp"

using namespace tin::network::sniffer;

void pcap_trampoline(u_char *param, const struct pcap_pkthdr *pkt_header, const u_char *pkt_data)
{
    Sniffer* obj = reinterpret_cast<Sniffer*>(param);
    obj->handlePacket(pkt_header, pkt_data);
}

Sniffer::Sniffer(const std::string& device, const std::string& expression):
device(device),
expression(expression)
{}

Sniffer::~Sniffer()
{
    if (this->isSniffing())
    {
        this->stopSniffing();
    }
    else if (this->snifferThread.joinable())
    {
        this->snifferThread.join();
    }
}

bool Sniffer::isSniffing() const
{
    return this->pcapHandle != nullptr;
}

void Sniffer::stopSniffing()
{
    if (!this->isSniffing())
    {
        return;
    }

    pcap_breakloop(this->pcapHandle);

    this->snifferThread.join();
}

void Sniffer::changeConfig(const std::string& device, const std::string& expression)
{
    if (this->isSniffing())
    {
        return;
    }

    this->device = device;
    this->expression = expression;
}

void Sniffer::handlePacket(const struct pcap_pkthdr *header, const u_char *packet)
{
    // declare pointers to packet headers
    const struct ethernet_header *ethernet;      // The ethernet header [1]
    const struct ip_header *ip;             // The IP header
    const struct tcp_header *tcp;           // The TCP header
    const struct pcaprec_header *pcap;      // The PCAP record header

    int size_ip;
    int size_tcp;
    int size_payload;

    this->packetCounter++;

    // define ethernet header
    ethernet = (struct ethernet_header*)(packet);
    pcap = (struct pcaprec_header*)(packet);

    long date = (long) pcap->ts_sec;
    time_t timestamp = time(&date);

    // define/compute ip header offset
    ip = (struct ip_header*) (packet + SIZE_ETHERNET);
    size_ip = IP_HL(ip)*4;
    if (size_ip < 20)
    {
        // Throw an error (Invalid IP header length: $size_ip bytes)
        return;
    }

    // if it is not TCP
    if(ip->ip_pro != IPPROTO_TCP)
    {
        auto pac = std::make_shared<tin::utils::Packet>(
            this->packetCounter,
            timestamp,
            ip->ip_src,
            ip->ip_dst,
            ip->ip_pro
        );

        this->runPacketReceivedHandlers(pac);

        // pac->printData();
        return;
    }

    // If it is TCP - we have some extra knowledge

    // Tcp header offset
    tcp = (struct tcp_header*)(packet + SIZE_ETHERNET + size_ip);
    size_tcp = TH_OFF(tcp)*4;
    if (size_tcp < 20)
    {
        // throw an error (Invalid TCP header length: $size_tcp bytes)
        return;
    }

    // compute tcp payload (segment) size
    size_payload = ntohs(ip->ip_len) + (size_ip + size_tcp);

    // create new "Packet"
    auto pac = std::make_shared<tin::utils::Packet>(
        this->packetCounter,
        timestamp,
        ip->ip_src,
        ip->ip_dst,
        ip->ip_pro,
        tcp->th_sport,
        tcp->th_dport,
        size_payload
    );

    this->runPacketReceivedHandlers(pac);

    // pac->printData();
}

void Sniffer::run()
{
	this->snifferThread = std::thread(
        &Sniffer::sniff,
        std::ref(*this)
    );
}

unsigned int Sniffer::attachPacketReceivedHandler(std::function<void(const tin::utils::Packet::ptr&)>& handler)
{
    return this->packetReceivedHandlers.insert(handler);
}

unsigned int Sniffer::attachPacketReceivedHandler(std::function<void(const tin::utils::Packet::ptr&)>&& handler)
{
    return this->packetReceivedHandlers.insert(
        std::forward<std::function<void(const tin::utils::Packet::ptr&)>>(handler)
    );
}

void Sniffer::runPacketReceivedHandlers(const tin::utils::Packet::ptr& packetPtr)
{
    for (auto iter: this->packetReceivedHandlers)
    {
        iter.second(packetPtr);
    }
}

void Sniffer::sniff()
{
    if (this->isSniffing())
    {
        return;
    }

    char errbuf[PCAP_ERRBUF_SIZE]; // error buffer
    struct bpf_program fp;         // compiled filter program (expression)
    bpf_u_int32 mask;              // subnet mask
    bpf_u_int32 net;               // ip
    int num_packets = -1;          // number of packets to capture (-1 means till error) */

    // get device
    auto dev = this->device.c_str();

    if (dev == NULL)
    {
        // Throw an error (Couldn't find default device)
        return;
    }

    // get network number and mask associated with capture device
    if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1)
    {
        // Throw an error (Couldn't get netmask for device: $device)
        net = 0;
        mask = 0;
    }

    // get an expression
    auto filter = this->expression.c_str();

    // open capture device
    this->pcapHandle = pcap_open_live(dev, SNAP_LEN, 1, 1000, errbuf);
    auto handle = this->pcapHandle;

    if (handle == NULL)
    {
        // Throw an error (Couldn't open device: $device)
        // errbuf contains error data
        return;
    }

    // make sure we're capturing on an Ethernet device [2]
    if (pcap_datalink(handle) != DLT_EN10MB)
    {
        // throw an error ($device is not an Ethernet)
        return;
    }

    // compile the filter
    if (pcap_compile(handle, &fp, filter, 0, net) == -1)
    {
        // throw an error (Could not parse filter: $expression)
        // pcap_geterr(handle)
        return;
    }

    // apply the filter
    if (pcap_setfilter(handle, &fp) == -1)
    {
        // throw an error (Could not parse filter: $expression)
        // pcap_geterr(handle)
        return;
    }

    // capturing packets
    pcap_loop(handle, num_packets, pcap_trampoline, reinterpret_cast<u_char*>(this));

    // cleanup
    pcap_freecode(&fp);
    pcap_close(handle);

    this->pcapHandle = nullptr;
}
<commit_msg>Make sure we are creating string copies<commit_after>#include "Sniffer.hpp"

using namespace tin::network::sniffer;

void pcap_trampoline(u_char *param, const struct pcap_pkthdr *pkt_header, const u_char *pkt_data)
{
    Sniffer* obj = reinterpret_cast<Sniffer*>(param);
    obj->handlePacket(pkt_header, pkt_data);
}

Sniffer::Sniffer(const std::string& device, const std::string& expression):
device(device.c_str()),
expression(expression.c_str())
{}

Sniffer::~Sniffer()
{
    if (this->isSniffing())
    {
        this->stopSniffing();
    }
    else if (this->snifferThread.joinable())
    {
        this->snifferThread.join();
    }
}

bool Sniffer::isSniffing() const
{
    return this->pcapHandle != nullptr;
}

void Sniffer::stopSniffing()
{
    if (!this->isSniffing())
    {
        return;
    }

    pcap_breakloop(this->pcapHandle);

    this->snifferThread.join();
}

void Sniffer::changeConfig(const std::string& device, const std::string& expression)
{
    if (this->isSniffing())
    {
        return;
    }

    this->device = std::string(device.c_str());
    this->expression = std::string(expression.c_str());
}

void Sniffer::handlePacket(const struct pcap_pkthdr *header, const u_char *packet)
{
    // declare pointers to packet headers
    const struct ethernet_header *ethernet;      // The ethernet header [1]
    const struct ip_header *ip;             // The IP header
    const struct tcp_header *tcp;           // The TCP header
    const struct pcaprec_header *pcap;      // The PCAP record header

    int size_ip;
    int size_tcp;
    int size_payload;

    this->packetCounter++;

    // define ethernet header
    ethernet = (struct ethernet_header*)(packet);
    pcap = (struct pcaprec_header*)(packet);

    long date = (long) pcap->ts_sec;
    time_t timestamp = time(&date);

    // define/compute ip header offset
    ip = (struct ip_header*) (packet + SIZE_ETHERNET);
    size_ip = IP_HL(ip)*4;
    if (size_ip < 20)
    {
        // Throw an error (Invalid IP header length: $size_ip bytes)
        return;
    }

    // if it is not TCP
    if(ip->ip_pro != IPPROTO_TCP)
    {
        auto pac = std::make_shared<tin::utils::Packet>(
            this->packetCounter,
            timestamp,
            ip->ip_src,
            ip->ip_dst,
            ip->ip_pro
        );

        this->runPacketReceivedHandlers(pac);

        // pac->printData();
        return;
    }

    // If it is TCP - we have some extra knowledge

    // Tcp header offset
    tcp = (struct tcp_header*)(packet + SIZE_ETHERNET + size_ip);
    size_tcp = TH_OFF(tcp)*4;
    if (size_tcp < 20)
    {
        // throw an error (Invalid TCP header length: $size_tcp bytes)
        return;
    }

    // compute tcp payload (segment) size
    size_payload = ntohs(ip->ip_len) + (size_ip + size_tcp);

    // create new "Packet"
    auto pac = std::make_shared<tin::utils::Packet>(
        this->packetCounter,
        timestamp,
        ip->ip_src,
        ip->ip_dst,
        ip->ip_pro,
        tcp->th_sport,
        tcp->th_dport,
        size_payload
    );

    this->runPacketReceivedHandlers(pac);

    // pac->printData();
}

void Sniffer::run()
{
	this->snifferThread = std::thread(
        &Sniffer::sniff,
        std::ref(*this)
    );
}

unsigned int Sniffer::attachPacketReceivedHandler(std::function<void(const tin::utils::Packet::ptr&)>& handler)
{
    return this->packetReceivedHandlers.insert(handler);
}

unsigned int Sniffer::attachPacketReceivedHandler(std::function<void(const tin::utils::Packet::ptr&)>&& handler)
{
    return this->packetReceivedHandlers.insert(
        std::forward<std::function<void(const tin::utils::Packet::ptr&)>>(handler)
    );
}

void Sniffer::runPacketReceivedHandlers(const tin::utils::Packet::ptr& packetPtr)
{
    for (auto iter: this->packetReceivedHandlers)
    {
        iter.second(packetPtr);
    }
}

void Sniffer::sniff()
{
    if (this->isSniffing())
    {
        return;
    }

    char errbuf[PCAP_ERRBUF_SIZE]; // error buffer
    struct bpf_program fp;         // compiled filter program (expression)
    bpf_u_int32 mask;              // subnet mask
    bpf_u_int32 net;               // ip
    int num_packets = -1;          // number of packets to capture (-1 means till error) */

    // get device
    auto dev = this->device.c_str();

    if (dev == NULL)
    {
        // Throw an error (Couldn't find default device)
        return;
    }

    // get network number and mask associated with capture device
    if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1)
    {
        // Throw an error (Couldn't get netmask for device: $device)
        net = 0;
        mask = 0;
    }

    // get an expression
    auto filter = this->expression.c_str();

    // open capture device
    this->pcapHandle = pcap_open_live(dev, SNAP_LEN, 1, 1000, errbuf);
    auto handle = this->pcapHandle;

    if (handle == NULL)
    {
        // Throw an error (Couldn't open device: $device)
        // errbuf contains error data
        return;
    }

    // make sure we're capturing on an Ethernet device [2]
    if (pcap_datalink(handle) != DLT_EN10MB)
    {
        // throw an error ($device is not an Ethernet)
        return;
    }

    // compile the filter
    if (pcap_compile(handle, &fp, filter, 0, net) == -1)
    {
        // throw an error (Could not parse filter: $expression)
        // pcap_geterr(handle)
        return;
    }

    // apply the filter
    if (pcap_setfilter(handle, &fp) == -1)
    {
        // throw an error (Could not parse filter: $expression)
        // pcap_geterr(handle)
        return;
    }

    // capturing packets
    pcap_loop(handle, num_packets, pcap_trampoline, reinterpret_cast<u_char*>(this));

    // cleanup
    pcap_freecode(&fp);
    pcap_close(handle);

    this->pcapHandle = nullptr;
}
<|endoftext|>