<commit_before>#include "dco.hpp"
#include "ampi_tape.hpp"

#define INT64 long int

typedef dco::ga1s<double> AD_MODE;
typedef AD_MODE::type type;

#ifndef DCO_AMPI
void ampi_interpret_tape(long int idx) {}
#endif
//long int ampi_counter=0;

void ampi_get_val(void *buf, int *i, double *x) {
    *x=static_cast<type*>(buf)[*i]._value();
}
void ampi_set_val(void* buf, int *i, double *v) {
    type &dummy= static_cast<type*>(buf)[*i];
    *const_cast<double*>(&(dummy._value())) = *v;
}

void ampi_get_idx(void *buf, int *i, INT64 *idx) {
    type &var = static_cast<type*>(buf)[*i];
    if(!var._data()._is_registered()) {
        *idx=0;
    }
    else {
        *idx = dco::tape_index(var);
    }
}

void ampi_get_adj(INT64 *idx, double *x) {
    if(*idx!=0) *x = AD_MODE::global_tape->_adjoint(*idx);
}
void ampi_set_adj(INT64 *idx, double *x) {
    if(*idx!=0) AD_MODE::global_tape->_adjoint(*idx) += *x;
}

/*extern "C" */void ampi_reset_entry(long int handle);

struct AMPI_data : AD_MODE::callback_object_t::callback_object_base  {
  void* handle;

  AMPI_data(){}
  AMPI_data(const AMPI_data *other) {
    handle=other->handle;
  }
  virtual ~AMPI_data() {
    ampi_reset_entry(handle);
  }
};

void ampi_tape_wrapper(AMPI_data *data) {
  ampi_interpret_tape(data->handle);
}

void ampi_create_tape_entry(void* handle) {
    if(AD_MODE::global_tape == NULL || !AD_MODE::global_tape->is_active()) {
//	std::cout << "tape is passive, not AMPI Callback will be created!" << std::endl;
	return;
    }
    //todo: insert an external function handler!!!
    //AD_MODE::global_tape->register_external_function(&ampi_tape_wrapper, new AMPI_data(handle));
    AMPI_data *tmp=new AMPI_data();
    tmp->handle=handle;
    AD_MODE::global_tape->insert_callback(
        &ampi_tape_wrapper,
        AD_MODE::global_tape->create_callback_object<AMPI_data>(tmp)
    );

 //   ampi_counter++;
 //   std::cout << "ampi_counter: " << ampi_counter << endl;

    //this will call ampi_interpret_tape
//std::cout << "i: " << *i << endl;
  }

void ampi_create_dummies(void *buf, int *size) {
    type *values=static_cast<type*>(buf);

    for(int i=0; i<*size; ++i) {
        type &dummy=values[i];
        dummy=0;
        AD_MODE::global_tape->register_variable(dummy);
    }
}

void ampi_create_dummies_displ(void *buf, int* displ, int *size) {
  if (NULL != AD_MODE::global_tape && AD_MODE::global_tape->is_active()){

    AD_MODE::type *values=static_cast<AD_MODE::type*>(buf);

    for(int i=0;i<*size;++i) {
      AD_MODE::type& dummy=values[*displ + i];
      dummy=0;
      AD_MODE::global_tape->register_variable(dummy);
    }
  }
}

int ampi_is_tape_active () {
    if (NULL != AD_MODE::global_tape) {
#ifdef DCO_ALLOW_TAPE_SWITCH_OFF
        return AD_MODE::global_tape->is_active();
#else
        return 1;
#endif
    } else {
        return 0;
    }
}

<commit_msg>_data() does not exist in dco anymore. tape_index returns zero for unregistered variables anyway, thus if clause can be omitted<commit_after>#include "dco.hpp"
#include "ampi_tape.hpp"

#define INT64 long int

typedef dco::ga1s<double> AD_MODE;
typedef AD_MODE::type type;

#ifndef DCO_AMPI
void ampi_interpret_tape(long int idx) {}
#endif
//long int ampi_counter=0;

void ampi_get_val(void *buf, int *i, double *x) {
    *x=static_cast<type*>(buf)[*i]._value();
}
void ampi_set_val(void* buf, int *i, double *v) {
    type &dummy= static_cast<type*>(buf)[*i];
    *const_cast<double*>(&(dummy._value())) = *v;
}

void ampi_get_idx(void *buf, int *i, INT64 *idx) {
    type &var = static_cast<type*>(buf)[*i];
    *idx = dco::tape_index(var);
}

void ampi_get_adj(INT64 *idx, double *x) {
    if(*idx!=0) *x = AD_MODE::global_tape->_adjoint(*idx);
}
void ampi_set_adj(INT64 *idx, double *x) {
    if(*idx!=0) AD_MODE::global_tape->_adjoint(*idx) += *x;
}

/*extern "C" */void ampi_reset_entry(long int handle);

struct AMPI_data : AD_MODE::callback_object_t::callback_object_base  {
  void* handle;

  AMPI_data(){}
  AMPI_data(const AMPI_data *other) {
    handle=other->handle;
  }
  virtual ~AMPI_data() {
    ampi_reset_entry(handle);
  }
};

void ampi_tape_wrapper(AMPI_data *data) {
  ampi_interpret_tape(data->handle);
}

void ampi_create_tape_entry(void* handle) {
    if(AD_MODE::global_tape == NULL || !AD_MODE::global_tape->is_active()) {
//	std::cout << "tape is passive, not AMPI Callback will be created!" << std::endl;
	return;
    }
    //todo: insert an external function handler!!!
    //AD_MODE::global_tape->register_external_function(&ampi_tape_wrapper, new AMPI_data(handle));
    AMPI_data *tmp=new AMPI_data();
    tmp->handle=handle;
    AD_MODE::global_tape->insert_callback(
        &ampi_tape_wrapper,
        AD_MODE::global_tape->create_callback_object<AMPI_data>(tmp)
    );

 //   ampi_counter++;
 //   std::cout << "ampi_counter: " << ampi_counter << endl;

    //this will call ampi_interpret_tape
//std::cout << "i: " << *i << endl;
  }

void ampi_create_dummies(void *buf, int *size) {
    type *values=static_cast<type*>(buf);

    for(int i=0; i<*size; ++i) {
        type &dummy=values[i];
        dummy=0;
        AD_MODE::global_tape->register_variable(dummy);
    }
}

void ampi_create_dummies_displ(void *buf, int* displ, int *size) {
  if (NULL != AD_MODE::global_tape && AD_MODE::global_tape->is_active()){

    AD_MODE::type *values=static_cast<AD_MODE::type*>(buf);

    for(int i=0;i<*size;++i) {
      AD_MODE::type& dummy=values[*displ + i];
      dummy=0;
      AD_MODE::global_tape->register_variable(dummy);
    }
  }
}

int ampi_is_tape_active () {
    if (NULL != AD_MODE::global_tape) {
#ifdef DCO_ALLOW_TAPE_SWITCH_OFF
        return AD_MODE::global_tape->is_active();
#else
        return 1;
#endif
    } else {
        return 0;
    }
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: epgm.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2004-09-09 11:28: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): _______________________________________
 *
 *
 ************************************************************************/

#include <vcl/svapp.hxx>
#include <vcl/graph.hxx>
#include <vcl/bmpacc.hxx>
#include <vcl/msgbox.hxx>
#include <svtools/solar.hrc>
#include <svtools/fltcall.hxx>
#include <svtools/FilterConfigItem.hxx>
#include "strings.hrc"
#include "dlgepgm.hrc"
#include "dlgepgm.hxx"

//============================ PGMWriter ==================================

class PGMWriter {

private:

    PFilterCallback     mpCallback;
    void *              mpCallerData;

    SvStream*           mpOStm;             // Die auszugebende PGM-Datei
    USHORT              mpOStmOldModus;

    BOOL                mbStatus;
    UINT32              mnMode;
    BitmapReadAccess*   mpAcc;
    ULONG               mnWidth, mnHeight;  // Bildausmass in Pixeln

    BOOL                ImplCallback( USHORT nPercent );
    BOOL                ImplWriteHeader();
    void                ImplWriteBody();
    void                ImplWriteNumber( sal_Int32 );

public:
                        PGMWriter();
                        ~PGMWriter();

    BOOL                WritePGM( const Graphic& rGraphic, SvStream& rPGM,
                                    PFilterCallback pCallback, void* pCallerdata,
                                        FilterConfigItem* pConfigItem );
};

//=================== Methoden von PGMWriter ==============================

PGMWriter::PGMWriter() :
    mbStatus    ( TRUE ),
    mpAcc       ( NULL )
{
}

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

PGMWriter::~PGMWriter()
{
}

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

BOOL PGMWriter::ImplCallback( USHORT nPercent )
{
    if ( mpCallback != NULL )
    {
        if ( ( (*mpCallback)( mpCallerData, nPercent ) ) == TRUE )
        {
            mpOStm->SetError( SVSTREAM_FILEFORMAT_ERROR );
            return TRUE;
        }
    }
    return FALSE;
}

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

BOOL PGMWriter::WritePGM( const Graphic& rGraphic, SvStream& rPGM,
                          PFilterCallback pCallback, void* pCallerdata,
                          FilterConfigItem* pConfigItem )
{

    mpOStm = &rPGM;
    mpCallback = pCallback;
    mpCallerData = pCallerdata;

    if ( pConfigItem )
        mnMode = pConfigItem->ReadInt32( String( RTL_CONSTASCII_USTRINGPARAM( "FileFormat" ) ), 0 );

    BitmapEx    aBmpEx( rGraphic.GetBitmapEx() );
    Bitmap      aBmp = aBmpEx.GetBitmap();
    aBmp.Convert( BMP_CONVERSION_8BIT_GREYS );

    mpOStmOldModus = mpOStm->GetNumberFormatInt();
    mpOStm->SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );

    mpAcc = aBmp.AcquireReadAccess();
    if( mpAcc )
    {
        if ( ImplWriteHeader() )
        {
            ImplWriteBody();
        }
        aBmp.ReleaseAccess( mpAcc );
    }
    else
        mbStatus = FALSE;

    mpOStm->SetNumberFormatInt( mpOStmOldModus );

    return mbStatus;
}

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

BOOL PGMWriter::ImplWriteHeader()
{
    mnWidth = mpAcc->Width();
    mnHeight = mpAcc->Height();
    if ( mnWidth && mnHeight )
    {
        if ( mnMode == 0 )
            *mpOStm << "P5\x0a";
        else
            *mpOStm << "P2\x0a";

        ImplWriteNumber( mnWidth );
        *mpOStm << (BYTE)32;
        ImplWriteNumber( mnHeight );
        *mpOStm << (BYTE)32;
        ImplWriteNumber( 255 );         // max. gray value
        *mpOStm << (BYTE)10;
    }
    else
        mbStatus = FALSE;

    return mbStatus;
}

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

void PGMWriter::ImplWriteBody()
{
    if ( mnMode == 0 )
    {
        for ( ULONG y = 0; y < mnHeight; y++ )
        {
            for ( ULONG x = 0; x < mnWidth; x++ )
            {
                *mpOStm << (BYTE)( mpAcc->GetPixel( y, x ) );
            }
        }
    }
    else
    {
        for ( ULONG y = 0; y < mnHeight; y++ )
        {
            int nCount = 70;
            for ( ULONG x = 0; x < mnWidth; x++ )
            {
                BYTE nDat, nNumb;
                if ( nCount < 0 )
                {
                    nCount = 69;
                    *mpOStm << (BYTE)10;
                }
                nDat = (BYTE)mpAcc->GetPixel( y, x );
                if ( ( nNumb = nDat / 100 ) )
                {
                    *mpOStm << (BYTE)( nNumb + '0' );
                    nDat -= ( nNumb * 100 );
                    nNumb = nDat / 10;
                    *mpOStm << (BYTE)( nNumb + '0' );
                    nDat -= ( nNumb * 10 );
                    *mpOStm << (BYTE)( nDat + '0' );
                    nCount -= 4;
                }
                else if ( ( nNumb = nDat / 10 ) )
                {
                    *mpOStm << (BYTE)( nNumb + '0' );
                    nDat -= ( nNumb * 10 );
                    *mpOStm << (BYTE)( nDat + '0' );
                    nCount -= 3;
                }
                else
                {
                    *mpOStm << (BYTE)( nDat + '0' );
                    nCount -= 2;
                }
                *mpOStm << (BYTE)' ';
            }
            *mpOStm << (BYTE)10;
        }
    }
}

// ------------------------------------------------------------------------
// eine Dezimalzahl im ASCII format wird in den Stream geschrieben

void PGMWriter::ImplWriteNumber( sal_Int32 nNumber )
{
    const ByteString aNum( ByteString::CreateFromInt32( nNumber ) );

    for( sal_Int16 n = 0UL, nLen = aNum.Len(); n < nLen; n++  )
        *mpOStm << aNum.GetChar( n );

}

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

// ---------------------
// - exported function -
// ---------------------

extern "C" BOOL __LOADONCALLAPI GraphicExport( SvStream& rStream, Graphic& rGraphic,
                                               PFilterCallback pCallback, void* pCallerData,
                                               FilterConfigItem* pConfigItem, BOOL )
{
    PGMWriter aPGMWriter;

    return aPGMWriter.WritePGM( rGraphic, rStream, pCallback, pCallerData, pConfigItem );
}

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

extern "C" BOOL __LOADONCALLAPI DoExportDialog( FltCallDialogParameter& rPara )
{
    BOOL bRet = FALSE;

    if ( rPara.pWindow )
    {
        ByteString  aResMgrName( "epg" );
        ResMgr* pResMgr;

        aResMgrName.Append( ByteString::CreateFromInt32( SOLARUPD ) );
        pResMgr = ResMgr::CreateResMgr( aResMgrName.GetBuffer(), Application::GetSettings().GetUILocale() );

        if( pResMgr )
        {
            rPara.pResMgr = pResMgr;
            bRet = ( DlgExportEPGM( rPara ).Execute() == RET_OK );
            delete pResMgr;
        }
        else
            bRet = TRUE;
    }

    return bRet;
}

// ------------------------------------------------------------------------
#ifndef GCC
#pragma hdrstop
#endif

// ---------------
// - Win16 trash -
// ---------------

#ifdef WIN

static HINSTANCE hDLLInst = 0;

extern "C" int CALLBACK LibMain( HINSTANCE hDLL, WORD, WORD nHeap, LPSTR )
{
    if ( nHeap )
        UnlockData( 0 );

    hDLLInst = hDLL;

    return TRUE;
}

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

extern "C" int CALLBACK WEP( int )
{
    return 1;
}

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.84); FILE MERGED 2005/09/05 15:12:21 rt 1.5.84.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: epgm.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:38:04 $
 *
 *  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 <vcl/svapp.hxx>
#include <vcl/graph.hxx>
#include <vcl/bmpacc.hxx>
#include <vcl/msgbox.hxx>
#include <svtools/solar.hrc>
#include <svtools/fltcall.hxx>
#include <svtools/FilterConfigItem.hxx>
#include "strings.hrc"
#include "dlgepgm.hrc"
#include "dlgepgm.hxx"

//============================ PGMWriter ==================================

class PGMWriter {

private:

    PFilterCallback     mpCallback;
    void *              mpCallerData;

    SvStream*           mpOStm;             // Die auszugebende PGM-Datei
    USHORT              mpOStmOldModus;

    BOOL                mbStatus;
    UINT32              mnMode;
    BitmapReadAccess*   mpAcc;
    ULONG               mnWidth, mnHeight;  // Bildausmass in Pixeln

    BOOL                ImplCallback( USHORT nPercent );
    BOOL                ImplWriteHeader();
    void                ImplWriteBody();
    void                ImplWriteNumber( sal_Int32 );

public:
                        PGMWriter();
                        ~PGMWriter();

    BOOL                WritePGM( const Graphic& rGraphic, SvStream& rPGM,
                                    PFilterCallback pCallback, void* pCallerdata,
                                        FilterConfigItem* pConfigItem );
};

//=================== Methoden von PGMWriter ==============================

PGMWriter::PGMWriter() :
    mbStatus    ( TRUE ),
    mpAcc       ( NULL )
{
}

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

PGMWriter::~PGMWriter()
{
}

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

BOOL PGMWriter::ImplCallback( USHORT nPercent )
{
    if ( mpCallback != NULL )
    {
        if ( ( (*mpCallback)( mpCallerData, nPercent ) ) == TRUE )
        {
            mpOStm->SetError( SVSTREAM_FILEFORMAT_ERROR );
            return TRUE;
        }
    }
    return FALSE;
}

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

BOOL PGMWriter::WritePGM( const Graphic& rGraphic, SvStream& rPGM,
                          PFilterCallback pCallback, void* pCallerdata,
                          FilterConfigItem* pConfigItem )
{

    mpOStm = &rPGM;
    mpCallback = pCallback;
    mpCallerData = pCallerdata;

    if ( pConfigItem )
        mnMode = pConfigItem->ReadInt32( String( RTL_CONSTASCII_USTRINGPARAM( "FileFormat" ) ), 0 );

    BitmapEx    aBmpEx( rGraphic.GetBitmapEx() );
    Bitmap      aBmp = aBmpEx.GetBitmap();
    aBmp.Convert( BMP_CONVERSION_8BIT_GREYS );

    mpOStmOldModus = mpOStm->GetNumberFormatInt();
    mpOStm->SetNumberFormatInt( NUMBERFORMAT_INT_BIGENDIAN );

    mpAcc = aBmp.AcquireReadAccess();
    if( mpAcc )
    {
        if ( ImplWriteHeader() )
        {
            ImplWriteBody();
        }
        aBmp.ReleaseAccess( mpAcc );
    }
    else
        mbStatus = FALSE;

    mpOStm->SetNumberFormatInt( mpOStmOldModus );

    return mbStatus;
}

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

BOOL PGMWriter::ImplWriteHeader()
{
    mnWidth = mpAcc->Width();
    mnHeight = mpAcc->Height();
    if ( mnWidth && mnHeight )
    {
        if ( mnMode == 0 )
            *mpOStm << "P5\x0a";
        else
            *mpOStm << "P2\x0a";

        ImplWriteNumber( mnWidth );
        *mpOStm << (BYTE)32;
        ImplWriteNumber( mnHeight );
        *mpOStm << (BYTE)32;
        ImplWriteNumber( 255 );         // max. gray value
        *mpOStm << (BYTE)10;
    }
    else
        mbStatus = FALSE;

    return mbStatus;
}

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

void PGMWriter::ImplWriteBody()
{
    if ( mnMode == 0 )
    {
        for ( ULONG y = 0; y < mnHeight; y++ )
        {
            for ( ULONG x = 0; x < mnWidth; x++ )
            {
                *mpOStm << (BYTE)( mpAcc->GetPixel( y, x ) );
            }
        }
    }
    else
    {
        for ( ULONG y = 0; y < mnHeight; y++ )
        {
            int nCount = 70;
            for ( ULONG x = 0; x < mnWidth; x++ )
            {
                BYTE nDat, nNumb;
                if ( nCount < 0 )
                {
                    nCount = 69;
                    *mpOStm << (BYTE)10;
                }
                nDat = (BYTE)mpAcc->GetPixel( y, x );
                if ( ( nNumb = nDat / 100 ) )
                {
                    *mpOStm << (BYTE)( nNumb + '0' );
                    nDat -= ( nNumb * 100 );
                    nNumb = nDat / 10;
                    *mpOStm << (BYTE)( nNumb + '0' );
                    nDat -= ( nNumb * 10 );
                    *mpOStm << (BYTE)( nDat + '0' );
                    nCount -= 4;
                }
                else if ( ( nNumb = nDat / 10 ) )
                {
                    *mpOStm << (BYTE)( nNumb + '0' );
                    nDat -= ( nNumb * 10 );
                    *mpOStm << (BYTE)( nDat + '0' );
                    nCount -= 3;
                }
                else
                {
                    *mpOStm << (BYTE)( nDat + '0' );
                    nCount -= 2;
                }
                *mpOStm << (BYTE)' ';
            }
            *mpOStm << (BYTE)10;
        }
    }
}

// ------------------------------------------------------------------------
// eine Dezimalzahl im ASCII format wird in den Stream geschrieben

void PGMWriter::ImplWriteNumber( sal_Int32 nNumber )
{
    const ByteString aNum( ByteString::CreateFromInt32( nNumber ) );

    for( sal_Int16 n = 0UL, nLen = aNum.Len(); n < nLen; n++  )
        *mpOStm << aNum.GetChar( n );

}

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

// ---------------------
// - exported function -
// ---------------------

extern "C" BOOL __LOADONCALLAPI GraphicExport( SvStream& rStream, Graphic& rGraphic,
                                               PFilterCallback pCallback, void* pCallerData,
                                               FilterConfigItem* pConfigItem, BOOL )
{
    PGMWriter aPGMWriter;

    return aPGMWriter.WritePGM( rGraphic, rStream, pCallback, pCallerData, pConfigItem );
}

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

extern "C" BOOL __LOADONCALLAPI DoExportDialog( FltCallDialogParameter& rPara )
{
    BOOL bRet = FALSE;

    if ( rPara.pWindow )
    {
        ByteString  aResMgrName( "epg" );
        ResMgr* pResMgr;

        aResMgrName.Append( ByteString::CreateFromInt32( SOLARUPD ) );
        pResMgr = ResMgr::CreateResMgr( aResMgrName.GetBuffer(), Application::GetSettings().GetUILocale() );

        if( pResMgr )
        {
            rPara.pResMgr = pResMgr;
            bRet = ( DlgExportEPGM( rPara ).Execute() == RET_OK );
            delete pResMgr;
        }
        else
            bRet = TRUE;
    }

    return bRet;
}

// ------------------------------------------------------------------------
#ifndef GCC
#pragma hdrstop
#endif

// ---------------
// - Win16 trash -
// ---------------

#ifdef WIN

static HINSTANCE hDLLInst = 0;

extern "C" int CALLBACK LibMain( HINSTANCE hDLL, WORD, WORD nHeap, LPSTR )
{
    if ( nHeap )
        UnlockData( 0 );

    hDLLInst = hDLL;

    return TRUE;
}

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

extern "C" int CALLBACK WEP( int )
{
    return 1;
}

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: main.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 02:52:49 $
 *
 *  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
 *
 ************************************************************************/

#ifndef CGM_MAIN_HXX
#define CGM_MAIN_HXX

#include <cgm.hxx>

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

#define CGM_LEVEL1                      0x0001  // VERSION 1 METAFILE
#define CGM_LEVEL2                      0x0002
#define CGM_LEVEL3                      0x0003
#define CGM_GDSF_ONLY                   0x00F0
#define CGM_UNKNOWN_LEVEL               0x00F1
#define CGM_UNKNOWN_COMMAND             0x00F2
#define CGM_DESCRIPTION                 0x00F3

#define CGM_EXTENDED_PRIMITIVES_SET     0x0100  // INDICATES PRIMITIVES WHICH ARE AVAILABLE IN
                                                // LEVEL 1 BUT ARE NOT DEFINED IN ISO 7942(GKS)
#define CGM_DRAWING_PLUS_CONTROL_SET    0x0200  // INDICATES THAT THIS IS AN ADDITIONAL LEVEL 1
                                                // ELEMENT
#define ComOut( Level, Description ) if ( mpCommentOut ) ImplComment( Level, Description );

#define BMCOL( _col ) BitmapColor( (sal_Int8)(_col >> 16 ), (sal_Int8)( _col >> 8 ), (sal_Int8)_col )
#define ALIGN2( _nElementSize ) { _nElementSize = ( _nElementSize + 1 ) & ~1; }
#define ALIGN4( _nElementSize ) { _nElementSize = ( _nElementSize + 3 ) & ~3; }
#define ALIGN8( _nElementSize ) { _nElementSize = ( _nElementSize + 7 ) & ~7; }

#include <vcl/salbtype.hxx>
#include <tools/stream.hxx>
#include <tools/list.hxx>
#include "bundles.hxx"
#include "bitmap.hxx"
#include "elements.hxx"

#endif

<commit_msg>INTEGRATION: CWS warnings01 (1.2.28); FILE MERGED 2005/10/28 09:53:13 sj 1.2.28.1: #i55991# warning free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: main.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 21:45:46 $
 *
 *  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
 *
 ************************************************************************/

#ifndef CGM_MAIN_HXX
#define CGM_MAIN_HXX

#include "cgm.hxx"

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

#define CGM_LEVEL1                      0x0001  // VERSION 1 METAFILE
#define CGM_LEVEL2                      0x0002
#define CGM_LEVEL3                      0x0003
#define CGM_GDSF_ONLY                   0x00F0
#define CGM_UNKNOWN_LEVEL               0x00F1
#define CGM_UNKNOWN_COMMAND             0x00F2
#define CGM_DESCRIPTION                 0x00F3

#define CGM_EXTENDED_PRIMITIVES_SET     0x0100  // INDICATES PRIMITIVES WHICH ARE AVAILABLE IN
                                                // LEVEL 1 BUT ARE NOT DEFINED IN ISO 7942(GKS)
#define CGM_DRAWING_PLUS_CONTROL_SET    0x0200  // INDICATES THAT THIS IS AN ADDITIONAL LEVEL 1
                                                // ELEMENT
#define ComOut( Level, Description ) if ( mpCommentOut ) ImplComment( Level, Description );

#define BMCOL( _col ) BitmapColor( (sal_Int8)(_col >> 16 ), (sal_Int8)( _col >> 8 ), (sal_Int8)_col )
#define ALIGN2( _nElementSize ) { _nElementSize = ( _nElementSize + 1 ) & ~1; }
#define ALIGN4( _nElementSize ) { _nElementSize = ( _nElementSize + 3 ) & ~3; }
#define ALIGN8( _nElementSize ) { _nElementSize = ( _nElementSize + 7 ) & ~7; }

#include <vcl/salbtype.hxx>
#include <tools/stream.hxx>
#include <tools/list.hxx>
#include "bundles.hxx"
#include "bitmap.hxx"
#include "elements.hxx"

#endif

<|endoftext|>


<commit_before><commit_msg>simplify FileSystemHelper implementation<commit_after><|endoftext|>


<commit_before>/*
 NUI3 - C++ cross-platform GUI framework for OpenGL based applications
 Copyright (C) 2002-2003 Sebastien Metrot & Vincent Caron

 licence: see nui3/LICENCE.TXT
 */

#pragma once
#include "nuiGestureRecognizer.h"

//*******************************************************************************************************************
//*******************************************************************************************************************
//
// class nuiGestureRecognizer
//

nuiGestureRecognizer::nuiGestureRecognizer()
: nuiSimpleContainer()
{
  mState = eGestureRecognizerStatePossible;
}

nuiGestureRecognizer::~nuiGestureRecognizer()
{

}

nuiGestureRecognizerState nuiGestureRecognizer::GetState() const
{
  return mState;
}

void nuiGestureRecognizer::SetState(nuiGestureRecognizerState state)
{
  mState = state;

  // send synchronous signal
  SignalStateChanged(mState);
}

// virtual
bool nuiGestureRecognizer::MouseClicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)
{
  return false;
}

// virtual
bool nuiGestureRecognizer::MouseUnclicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)
{
  return false;
}

// virtual
bool nuiGestureRecognizer::MouseMoved(nuiSize X, nuiSize Y)
{
  return false;
}

const char* nuiGetString(nuiGestureDirection dir)
{
#define F(X) case X: return #X; break;
  switch (dir)
  {
    F(nuiGestureDirectionNull);
    F(nuiGestureDirectionRight);
    F(nuiGestureDirectionLeft);
    F(nuiGestureDirectionUp);
    F(nuiGestureDirectionDown);
    F(nuiGestureDirectionUpRight);
    F(nuiGestureDirectionDownRight);
    F(nuiGestureDirectionDownLeft);
    F(nuiGestureDirectionUpLeft);
  }
#undef F
  return "unknown direction";
}

#define SWIPE_INITIATED_THRESHOLD 9
#define SWIPE_INITIATED_TIMEOUT 0.10f
#define SWIPE_ACTIVATED_THRESHOLD 70
#define SWIPE_ACTIVATED_TIMEOUT 0.15f

//************************************************************************************************************
//************************************************************************************************************
//
// class nuiSwipeGestureRecognizer
//

nuiSwipeGestureRecognizer::nuiSwipeGestureRecognizer(nuiGestureDirection direction)
: nuiGestureRecognizer()
{
  mClicked = false;
  mStartX = 0;
  mStartY = 0;

  mDirection = direction;
  mRecognizedDirection = nuiGestureDirectionNull;
}

nuiSwipeGestureRecognizer::~nuiSwipeGestureRecognizer()
{

}

void nuiSwipeGestureRecognizer::SetDirections(nuiGestureDirection direction)
{
  mDirection = direction;
}

// virtual
bool nuiSwipeGestureRecognizer::MouseClicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)
{
  bool res = nuiGestureRecognizer::MouseClicked(X, Y, Button);

  mRecognizedDirection = nuiGestureDirectionNull;

  mClicked = true;
  mTime = nglTime();
  mInitiatedTime = 0;
  mStartX = X;
  mStartY = Y;

  Grab();
  return false;
}

// virtual
bool nuiSwipeGestureRecognizer::MouseUnclicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)
{
  bool res = nuiGestureRecognizer::MouseUnclicked(X, Y, Button);

  mClicked = false;
  SetState(eGestureRecognizerStatePossible);

  mTime = nglTime();
  mInitiatedTime = 0;
  mStartX = 0;
  mStartY = 0;
  Ungrab();

  return false;
}

// virtual
bool nuiSwipeGestureRecognizer::MouseMoved(nuiSize X, nuiSize Y)
{
  bool res = nuiGestureRecognizer::MouseMoved(X, Y);

  if (!mClicked)
    return false;

  if (GetState() == eGestureRecognizerStateEnded)
    return false;

	double diffx = mStartX - X;
	double diffy = mStartY - Y;
  double currentTime = nglTime();

  // has the swipe gesture been initiated?
  if (GetState() != eGestureRecognizerStateBegan)
  {
    bool initiatedOnX = (abs(diffx) >= SWIPE_INITIATED_THRESHOLD);
    bool initiatedOnY = (abs(diffy) >= SWIPE_INITIATED_THRESHOLD);

    // yes, it's been initiated.
    if (initiatedOnX || initiatedOnY)
    {
      mRecognizedDirection = GetGestureDirection(initiatedOnX, initiatedOnY, mStartX, X, mStartY, Y);

      // is this recognizer in charge of the detected gesture?
      if ((mRecognizedDirection & mDirection)
          && ((currentTime  - mTime) < SWIPE_INITIATED_TIMEOUT))
      {
        // yes. consider that the gesture recognition has began
        mInitiatedTime = currentTime;
        SetState(eGestureRecognizerStateBegan);
      }
      // no, it's not. set data for the next call
      else
      {
        mStartX = X;
        mStartY = Y;
        mTime = currentTime;
      }
    }
  }

  // not yet. it's a simple "move" gesture.
  if (GetState() != eGestureRecognizerStateBegan)
    return false;

  // swipe has been initiated, is the gesture fully completed?
  bool activatedOnX = (abs(diffx) >= SWIPE_ACTIVATED_THRESHOLD);
  bool activatedOnY = (abs(diffy) >= SWIPE_ACTIVATED_THRESHOLD);

  if(activatedOnX || activatedOnY)
	{
    // the swipe gesture has been avorted. let's reset the data and start again
    if ((currentTime  - mInitiatedTime) > SWIPE_ACTIVATED_TIMEOUT)
    {
      mTime = nglTime();
      mInitiatedTime = 0;
      mStartX = X;
      mStartY = Y;
      SetState(eGestureRecognizerStateFailed);
      mRecognizedDirection = nuiGestureDirectionNull;

      return false;
    }

    // ok! the swipe gesture has been completed!
		SetState(eGestureRecognizerStateEnded);

    // let's assume it's no use to compute mDirection here, since it's been done when the swipe gesture has been initiated.
    // we'll see in the future if it's wrong to make that assumption.
    // mDirection = GetGesturePosition(activatedOnX, activatedOnY, mStartX, X, mStartY, Y);

    // send synchronous event
    SignalSwipe(mRecognizedDirection);
	}

  return false;
}

nuiGestureDirection nuiSwipeGestureRecognizer::GetRecognizedDirection() const
{
  return mRecognizedDirection;
}

nuiGestureDirection nuiSwipeGestureRecognizer::GetGestureDirection(bool evalOnX, bool evalOnY, nuiSize x1, nuiSize x2, nuiSize y1, nuiSize y2) const
{
  // diagonal gesture?
  if (evalOnX && evalOnY)
  {
    if (x1 < x2)
    {
      if (y1 < y2)
        return nuiGestureDirectionDownRight;
      else
        return nuiGestureDirectionUpRight;
    }
    else
    {
      if (y1 < y2)
        return nuiGestureDirectionDownLeft;
      else
        return nuiGestureDirectionUpLeft;
    }
  }
  // horizontal gesture?
  else if (evalOnX)
  {
    if (x1 < x2)
      return nuiGestureDirectionRight;
    else
      return nuiGestureDirectionLeft;
  }
  // vertical gesture?
  else if (evalOnY)
  {
    if (y1 < y2)
      return nuiGestureDirectionDown;
    else
      return nuiGestureDirectionUp;
  }

  return nuiGestureDirectionNull;
}

#define PAD_INITIATED_THRESHOLD 9
#define PAD_INITIATED_TIMEOUT 0.10f
#define PAD_ACTIVATED_THRESHOLD 70
#define PAD_ACTIVATED_TIMEOUT 0.15f
#define PAD_FRICTION 0.9f
#define PAD_ATTENUATOR_THRESHOLD 4.0f
#define PAD_THRESHOLD 1.0f

//************************************************************************************************************
//************************************************************************************************************
//
// class nuiPadGestureRecognizer
//

nuiPadGestureRecognizer::nuiPadGestureRecognizer(nuiGestureDirection direction)
: nuiGestureRecognizer(), mSink(this)
{
  mClicked = false;
  mLastX = 0;
  mLastY = 0;
  mFriction = 0.1;

  SetDirections(direction);
  mRecognizedDirection = nuiGestureDirectionNull;

  nuiTimer* pTimer = nuiAnimation::AcquireTimer();
  mSink.Connect(pTimer->Tick, &nuiPadGestureRecognizer::UpdateForces);
}

nuiPadGestureRecognizer::~nuiPadGestureRecognizer()
{

}

void nuiPadGestureRecognizer::SetDirections(nuiGestureDirection direction)
{
  mDirection = direction;

#define F(X) (std::pair<float, float>(X - 22.5, X + 22.5))

  mDirections[nuiGestureDirectionRight]     = F(0);
  mDirections[nuiGestureDirectionUpRight]   = F(45);
  mDirections[nuiGestureDirectionUp]        = F(90);
  mDirections[nuiGestureDirectionUpLeft]    = F(135);
  mDirections[nuiGestureDirectionLeft]      = F(180);
  mDirections[nuiGestureDirectionDownLeft]  = F(225);
  mDirections[nuiGestureDirectionDown]      = F(270);
  mDirections[nuiGestureDirectionDownRight] = F(315);

#undef X
}

nuiGestureDirection nuiPadGestureRecognizer::GetDirectionFromAngle(float angle) const
{
  std::map<nuiGestureDirection, std::pair<float, float> >::const_iterator it = mDirections.begin();

  if (angle > 360 - 22.5)
    angle = angle - 360;

  while (it != mDirections.end())
  {
    if (it->second.first < angle && it->second.second >= angle)
      return it->first;

    ++it;
  }

  return nuiGestureDirectionNull;
}

// virtual
bool nuiPadGestureRecognizer::MouseClicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)
{
  bool res = nuiGestureRecognizer::MouseClicked(X, Y, Button);

  mRecognizedDirection = nuiGestureDirectionNull;

  mClicked = true;
  mLastX = X;
  mLastY = Y;

  Grab();
  return false;
}

// virtual
bool nuiPadGestureRecognizer::MouseUnclicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)
{
  bool res = nuiGestureRecognizer::MouseUnclicked(X, Y, Button);

  mClicked = false;
  SetState(eGestureRecognizerStatePossible);

  mLastX = 0;
  mLastY = 0;

  Ungrab();
  return false;
}

void nuiPadGestureRecognizer::UpdateForces(const nuiEvent& rEvent)
{
  mForce *= mFriction;
  //printf("UPD norm: %f - angle: %f\n", GetStrength(), GetDegrees());

  UpdateDirection();
}

void nuiPadGestureRecognizer::UpdateDirection()
{
  nuiGestureDirection olddir = mRecognizedDirection;
  if (GetStrength() >= PAD_THRESHOLD)
  {
    // See where we're going
    mRecognizedDirection = GetDirectionFromAngle(GetDegrees());
  }
  else
  {
    mRecognizedDirection = nuiGestureDirectionNull;
  }

  if (olddir != mRecognizedDirection)
  {
    //printf("New Pad Direction: %s\n", nuiGetString(mRecognizedDirection));
    SignalDirectionChanged(mRecognizedDirection);

  }
}

const nuiVector& nuiPadGestureRecognizer::GetForce() const
{
  return mForce;
}

float nuiPadGestureRecognizer::GetStrength() const
{
  return mForce.Length();
}

float nuiPadGestureRecognizer::GetDegrees() const
{
  return 360.0 * GetRadians() / (2 * M_PI);
}

float nuiPadGestureRecognizer::GetRadians() const
{
  nuiVector n = mForce;
  n.Normalize();
  // Get angle:
  double angle = acos(-n[0]);
  if (n[1] < 0)
    angle = 2 * M_PI - angle;

  return angle;
}

float nuiPadGestureRecognizer::GetFriction() const
{
  return mFriction;
}

void nuiPadGestureRecognizer::SetFriction(float set)
{
  mFriction = set;
}

// virtual
bool nuiPadGestureRecognizer::MouseMoved(nuiSize X, nuiSize Y)
{
  bool res = nuiGestureRecognizer::MouseMoved(X, Y);

  if (!mClicked)
    return false;

	double diffx = mLastX - X;
	double diffy = mLastY - Y;
  double currentTime = nglTime();
  nuiVector v(diffx, diffy, 0);

  double l = v.Length();
  if (l > PAD_ATTENUATOR_THRESHOLD)
    mForce *= 1.0 / l;

  mForce += v;

  double length = mForce.Length();

  nuiVector n = mForce;
  //printf("NEW norm: %f - angle: %f\n", GetStrength(), GetDegrees());

  mLastX = X;
  mLastY = Y;

  UpdateDirection();

  return false;
}

nuiGestureDirection nuiPadGestureRecognizer::GetRecognizedDirection() const
{
  return mRecognizedDirection;
}

<commit_msg>removed logs<commit_after>/*
 NUI3 - C++ cross-platform GUI framework for OpenGL based applications
 Copyright (C) 2002-2003 Sebastien Metrot & Vincent Caron

 licence: see nui3/LICENCE.TXT
 */

#pragma once
#include "nuiGestureRecognizer.h"

//*******************************************************************************************************************
//*******************************************************************************************************************
//
// class nuiGestureRecognizer
//

nuiGestureRecognizer::nuiGestureRecognizer()
: nuiSimpleContainer()
{
  mState = eGestureRecognizerStatePossible;
}

nuiGestureRecognizer::~nuiGestureRecognizer()
{

}

nuiGestureRecognizerState nuiGestureRecognizer::GetState() const
{
  return mState;
}

void nuiGestureRecognizer::SetState(nuiGestureRecognizerState state)
{
  mState = state;

  // send synchronous signal
  SignalStateChanged(mState);
}

// virtual
bool nuiGestureRecognizer::MouseClicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)
{
  return false;
}

// virtual
bool nuiGestureRecognizer::MouseUnclicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)
{
  return false;
}

// virtual
bool nuiGestureRecognizer::MouseMoved(nuiSize X, nuiSize Y)
{
  return false;
}

const char* nuiGetString(nuiGestureDirection dir)
{
#define F(X) case X: return #X; break;
  switch (dir)
  {
    F(nuiGestureDirectionNull);
    F(nuiGestureDirectionRight);
    F(nuiGestureDirectionLeft);
    F(nuiGestureDirectionUp);
    F(nuiGestureDirectionDown);
    F(nuiGestureDirectionUpRight);
    F(nuiGestureDirectionDownRight);
    F(nuiGestureDirectionDownLeft);
    F(nuiGestureDirectionUpLeft);
  }
#undef F
  return "unknown direction";
}

#define SWIPE_INITIATED_THRESHOLD 9
#define SWIPE_INITIATED_TIMEOUT 0.10f
#define SWIPE_ACTIVATED_THRESHOLD 70
#define SWIPE_ACTIVATED_TIMEOUT 0.15f

//************************************************************************************************************
//************************************************************************************************************
//
// class nuiSwipeGestureRecognizer
//

nuiSwipeGestureRecognizer::nuiSwipeGestureRecognizer(nuiGestureDirection direction)
: nuiGestureRecognizer()
{
  mClicked = false;
  mStartX = 0;
  mStartY = 0;

  mDirection = direction;
  mRecognizedDirection = nuiGestureDirectionNull;
}

nuiSwipeGestureRecognizer::~nuiSwipeGestureRecognizer()
{

}

void nuiSwipeGestureRecognizer::SetDirections(nuiGestureDirection direction)
{
  mDirection = direction;
}

// virtual
bool nuiSwipeGestureRecognizer::MouseClicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)
{
  bool res = nuiGestureRecognizer::MouseClicked(X, Y, Button);

  mRecognizedDirection = nuiGestureDirectionNull;

  mClicked = true;
  mTime = nglTime();
  mInitiatedTime = 0;
  mStartX = X;
  mStartY = Y;

  Grab();
  return false;
}

// virtual
bool nuiSwipeGestureRecognizer::MouseUnclicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)
{
  bool res = nuiGestureRecognizer::MouseUnclicked(X, Y, Button);

  mClicked = false;
  SetState(eGestureRecognizerStatePossible);

  mTime = nglTime();
  mInitiatedTime = 0;
  mStartX = 0;
  mStartY = 0;
  Ungrab();

  return false;
}

// virtual
bool nuiSwipeGestureRecognizer::MouseMoved(nuiSize X, nuiSize Y)
{
  bool res = nuiGestureRecognizer::MouseMoved(X, Y);

  if (!mClicked)
    return false;

  if (GetState() == eGestureRecognizerStateEnded)
    return false;

	double diffx = mStartX - X;
	double diffy = mStartY - Y;
  double currentTime = nglTime();

  // has the swipe gesture been initiated?
  if (GetState() != eGestureRecognizerStateBegan)
  {
    bool initiatedOnX = (abs(diffx) >= SWIPE_INITIATED_THRESHOLD);
    bool initiatedOnY = (abs(diffy) >= SWIPE_INITIATED_THRESHOLD);

    // yes, it's been initiated.
    if (initiatedOnX || initiatedOnY)
    {
      mRecognizedDirection = GetGestureDirection(initiatedOnX, initiatedOnY, mStartX, X, mStartY, Y);

      // is this recognizer in charge of the detected gesture?
      if ((mRecognizedDirection & mDirection)
          && ((currentTime  - mTime) < SWIPE_INITIATED_TIMEOUT))
      {
        // yes. consider that the gesture recognition has began
        mInitiatedTime = currentTime;
        SetState(eGestureRecognizerStateBegan);
      }
      // no, it's not. set data for the next call
      else
      {
        mStartX = X;
        mStartY = Y;
        mTime = currentTime;
      }
    }
  }

  // not yet. it's a simple "move" gesture.
  if (GetState() != eGestureRecognizerStateBegan)
    return false;

  // swipe has been initiated, is the gesture fully completed?
  bool activatedOnX = (abs(diffx) >= SWIPE_ACTIVATED_THRESHOLD);
  bool activatedOnY = (abs(diffy) >= SWIPE_ACTIVATED_THRESHOLD);

  if(activatedOnX || activatedOnY)
	{
    // the swipe gesture has been avorted. let's reset the data and start again
    if ((currentTime  - mInitiatedTime) > SWIPE_ACTIVATED_TIMEOUT)
    {
      mTime = nglTime();
      mInitiatedTime = 0;
      mStartX = X;
      mStartY = Y;
      SetState(eGestureRecognizerStateFailed);
      mRecognizedDirection = nuiGestureDirectionNull;

      return false;
    }

    // ok! the swipe gesture has been completed!
		SetState(eGestureRecognizerStateEnded);

    // let's assume it's no use to compute mDirection here, since it's been done when the swipe gesture has been initiated.
    // we'll see in the future if it's wrong to make that assumption.
    // mDirection = GetGesturePosition(activatedOnX, activatedOnY, mStartX, X, mStartY, Y);

    // send synchronous event
    SignalSwipe(mRecognizedDirection);
	}

  return false;
}

nuiGestureDirection nuiSwipeGestureRecognizer::GetRecognizedDirection() const
{
  return mRecognizedDirection;
}

nuiGestureDirection nuiSwipeGestureRecognizer::GetGestureDirection(bool evalOnX, bool evalOnY, nuiSize x1, nuiSize x2, nuiSize y1, nuiSize y2) const
{
  // diagonal gesture?
  if (evalOnX && evalOnY)
  {
    if (x1 < x2)
    {
      if (y1 < y2)
        return nuiGestureDirectionDownRight;
      else
        return nuiGestureDirectionUpRight;
    }
    else
    {
      if (y1 < y2)
        return nuiGestureDirectionDownLeft;
      else
        return nuiGestureDirectionUpLeft;
    }
  }
  // horizontal gesture?
  else if (evalOnX)
  {
    if (x1 < x2)
      return nuiGestureDirectionRight;
    else
      return nuiGestureDirectionLeft;
  }
  // vertical gesture?
  else if (evalOnY)
  {
    if (y1 < y2)
      return nuiGestureDirectionDown;
    else
      return nuiGestureDirectionUp;
  }

  return nuiGestureDirectionNull;
}

#define PAD_INITIATED_THRESHOLD 9
#define PAD_INITIATED_TIMEOUT 0.10f
#define PAD_ACTIVATED_THRESHOLD 70
#define PAD_ACTIVATED_TIMEOUT 0.15f
#define PAD_FRICTION 0.9f
#define PAD_ATTENUATOR_THRESHOLD 4.0f
#define PAD_THRESHOLD 4.0f

//************************************************************************************************************
//************************************************************************************************************
//
// class nuiPadGestureRecognizer
//

nuiPadGestureRecognizer::nuiPadGestureRecognizer(nuiGestureDirection direction)
: nuiGestureRecognizer(), mSink(this)
{
  mClicked = false;
  mLastX = 0;
  mLastY = 0;
  mFriction = 0.1;

  SetDirections(direction);
  mRecognizedDirection = nuiGestureDirectionNull;

  nuiTimer* pTimer = nuiAnimation::AcquireTimer();
  mSink.Connect(pTimer->Tick, &nuiPadGestureRecognizer::UpdateForces);
}

nuiPadGestureRecognizer::~nuiPadGestureRecognizer()
{

}

void nuiPadGestureRecognizer::SetDirections(nuiGestureDirection direction)
{
  mDirection = direction;

#define F(X) (std::pair<float, float>(X - 22.5, X + 22.5))

  mDirections[nuiGestureDirectionRight]     = F(0);
  mDirections[nuiGestureDirectionUpRight]   = F(45);
  mDirections[nuiGestureDirectionUp]        = F(90);
  mDirections[nuiGestureDirectionUpLeft]    = F(135);
  mDirections[nuiGestureDirectionLeft]      = F(180);
  mDirections[nuiGestureDirectionDownLeft]  = F(225);
  mDirections[nuiGestureDirectionDown]      = F(270);
  mDirections[nuiGestureDirectionDownRight] = F(315);

#undef X
}

nuiGestureDirection nuiPadGestureRecognizer::GetDirectionFromAngle(float angle) const
{
  std::map<nuiGestureDirection, std::pair<float, float> >::const_iterator it = mDirections.begin();

  if (angle > 360 - 22.5)
    angle = angle - 360;

  while (it != mDirections.end())
  {
    if (it->second.first < angle && it->second.second >= angle)
      return it->first;

    ++it;
  }

  return nuiGestureDirectionNull;
}

// virtual
bool nuiPadGestureRecognizer::MouseClicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)
{
  bool res = nuiGestureRecognizer::MouseClicked(X, Y, Button);

  mRecognizedDirection = nuiGestureDirectionNull;

  mClicked = true;
  mLastX = X;
  mLastY = Y;

  Grab();
  return false;
}

// virtual
bool nuiPadGestureRecognizer::MouseUnclicked(nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)
{
  bool res = nuiGestureRecognizer::MouseUnclicked(X, Y, Button);

  mClicked = false;
  SetState(eGestureRecognizerStatePossible);

  mLastX = 0;
  mLastY = 0;

  Ungrab();
  return false;
}

void nuiPadGestureRecognizer::UpdateForces(const nuiEvent& rEvent)
{
  mForce *= mFriction;
  //printf("UPD norm: %f - angle: %f\n", GetStrength(), GetDegrees());

  UpdateDirection();
}

void nuiPadGestureRecognizer::UpdateDirection()
{
  nuiGestureDirection olddir = mRecognizedDirection;
  if (GetStrength() >= PAD_THRESHOLD)
  {
    // See where we're going
    mRecognizedDirection = GetDirectionFromAngle(GetDegrees());
  }
  else
  {
    mRecognizedDirection = nuiGestureDirectionNull;
  }

  if (olddir != mRecognizedDirection)
  {
    //printf("New Pad Direction: %s\n", nuiGetString(mRecognizedDirection));
    SignalDirectionChanged(mRecognizedDirection);

  }
}

const nuiVector& nuiPadGestureRecognizer::GetForce() const
{
  return mForce;
}

float nuiPadGestureRecognizer::GetStrength() const
{
  return mForce.Length();
}

float nuiPadGestureRecognizer::GetDegrees() const
{
  return 360.0 * GetRadians() / (2 * M_PI);
}

float nuiPadGestureRecognizer::GetRadians() const
{
  nuiVector n = mForce;
  n.Normalize();
  // Get angle:
  double angle = acos(-n[0]);
  if (n[1] < 0)
    angle = 2 * M_PI - angle;

  return angle;
}

float nuiPadGestureRecognizer::GetFriction() const
{
  return mFriction;
}

void nuiPadGestureRecognizer::SetFriction(float set)
{
  mFriction = set;
}

// virtual
bool nuiPadGestureRecognizer::MouseMoved(nuiSize X, nuiSize Y)
{
  bool res = nuiGestureRecognizer::MouseMoved(X, Y);

  if (!mClicked)
    return false;

	double diffx = mLastX - X;
	double diffy = mLastY - Y;
  double currentTime = nglTime();
  nuiVector v(diffx, diffy, 0);

  double l = v.Length();
  if (l > PAD_ATTENUATOR_THRESHOLD)
    mForce *= 1.0 / l;

  mForce += v;

  double length = mForce.Length();

  nuiVector n = mForce;
  //printf("NEW norm: %f - angle: %f\n", GetStrength(), GetDegrees());

  mLastX = X;
  mLastY = Y;

  UpdateDirection();

  return false;
}

nuiGestureDirection nuiPadGestureRecognizer::GetRecognizedDirection() const
{
  return mRecognizedDirection;
}

<|endoftext|>


<commit_before>

#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/algorithm/string.hpp>

#include "storage/DevicegraphImpl.h"
#include "storage/Environment.h"
#include "storage/Storage.h"
#include "storage/Action.h"
#include "storage/Devices/DeviceImpl.h"
#include "storage/Devices/BlkDevice.h"
#include "storage/Devices/Partitionable.h"
#include "storage/Devices/PartitionTable.h"
#include "storage/Devices/LvmVgImpl.h"
#include "storage/Devices/LvmPvImpl.h"
#include "storage/Devices/BcacheCsetImpl.h"
#include "storage/Filesystems/BlkFilesystem.h"
#include "storage/Filesystems/Btrfs.h"
#include "storage/Filesystems/BtrfsSubvolume.h"
#include "storage/Filesystems/MountPoint.h"
#include "testsuite/helpers/TsCmp.h"

using namespace std;

namespace storage
{

    std::ostream&
    operator<<(std::ostream& out, const TsCmp& ts_cmp)
    {
	out << endl;

	for (const string& error : ts_cmp.errors)
	    out << error << endl;

	return out;
    }

    TsCmpDevicegraph::TsCmpDevicegraph(const Devicegraph& lhs, Devicegraph& rhs)
    {
	adjust_sids(lhs, rhs);

	if (lhs != rhs)
	{
	    ostringstream tmp1;
	    lhs.get_impl().log_diff(tmp1, rhs.get_impl());
	    string tmp2 = tmp1.str();
	    boost::split(errors, tmp2, boost::is_any_of("\n"), boost::token_compress_on);
	}
    }

    /**
     * This function adjusts the sids which is needed when devices are the
     * detected in a differnet order than expected. Block devices use the name
     * for identification, most others a uuid or a path. Some types are not
     * handled at all, e.g. Nfs.
     *
     * The function makes assumptions that break in the general case and does
     * no error checking. It can even ruin the devicegraph.
     *
     * Only enable it when you know what you are doing!
     */
    void
    TsCmpDevicegraph::adjust_sids(const Devicegraph& lhs, Devicegraph& rhs) const
    {
#if 0

	for (Device* device_rhs : Device::get_all(&rhs))
	{
	    // BlkDevices

	    if (is_blk_device(device_rhs))
	    {
		BlkDevice* blk_device_rhs = to_blk_device(device_rhs);
		const BlkDevice* blk_device_lhs = BlkDevice::find_by_name(&lhs, blk_device_rhs->get_name());

		adjust_sid(blk_device_lhs, blk_device_rhs);

		// PartitionTables

		if (is_partitionable(blk_device_lhs) && is_partitionable(blk_device_rhs))
		{
		    const Partitionable* partitionable_lhs = to_partitionable(blk_device_lhs);
		    Partitionable* partitionable_rhs = to_partitionable(blk_device_rhs);

		    if (partitionable_lhs->has_partition_table() && partitionable_rhs->has_partition_table())
			adjust_sid(partitionable_lhs->get_partition_table(), partitionable_rhs->get_partition_table());
		}
	    }

	    // LvmVgs

	    if (is_lvm_vg(device_rhs))
	    {
		LvmVg* lvm_vg_rhs = to_lvm_vg(device_rhs);
		const LvmVg* lvm_vg_lhs = LvmVg::Impl::find_by_uuid(&lhs, lvm_vg_rhs->get_impl().get_uuid());

		adjust_sid(lvm_vg_lhs, lvm_vg_rhs);
	    }

	    // LvmPvs

	    if (is_lvm_pv(device_rhs))
	    {
		LvmPv* lvm_pv_rhs = to_lvm_pv(device_rhs);
		const LvmPv* lvm_pv_lhs = LvmPv::Impl::find_by_uuid(&lhs, lvm_pv_rhs->get_impl().get_uuid());

		adjust_sid(lvm_pv_lhs, lvm_pv_rhs);
	    }

	    // BcacheCset

	    if (is_bcache_cset(device_rhs))
	    {
		BcacheCset* bcache_cset_rhs = to_bcache_cset(device_rhs);
		const BcacheCset* bcache_cset_lhs = BcacheCset::Impl::find_by_uuid(&lhs, bcache_cset_rhs->get_uuid());

		adjust_sid(bcache_cset_lhs, bcache_cset_rhs);
	    }

	    // BlkFilesystems

	    if (is_blk_filesystem(device_rhs))
	    {
		BlkFilesystem* blk_filesystem_rhs = to_blk_filesystem(device_rhs);
		const BlkFilesystem* blk_filesystem_lhs = BlkFilesystem::find_by_uuid(&lhs, blk_filesystem_rhs->get_uuid()).front();

		adjust_sid(blk_filesystem_lhs, blk_filesystem_rhs);

		// BtrfsSubvolumes

		if (is_btrfs(blk_filesystem_lhs) && is_btrfs(blk_filesystem_rhs))
		{
		    const Btrfs* btrfs_lhs = to_btrfs(blk_filesystem_lhs);
		    Btrfs* btrfs_rhs = to_btrfs(blk_filesystem_rhs);

		    for (BtrfsSubvolume* btrfs_subvolume_rhs : btrfs_rhs->get_btrfs_subvolumes())
		    {
			const BtrfsSubvolume* btrfs_subvolume_lhs = btrfs_lhs->find_btrfs_subvolume_by_path(btrfs_subvolume_rhs->get_path());
			adjust_sid(btrfs_subvolume_lhs, btrfs_subvolume_rhs);
		    }
		}
	    }

	    // MountPoints

	    if (is_mount_point(device_rhs))
            {
                MountPoint* mount_point_rhs = to_mount_point(device_rhs);
                const MountPoint* mount_point_lhs = MountPoint::find_by_path(&lhs, mount_point_rhs->get_path()).front();

		adjust_sid(mount_point_lhs, mount_point_rhs);
            }
	}

#endif
    }

    void
    TsCmpDevicegraph::adjust_sid(const Device* lhs, Device* rhs) const
    {
	if (lhs->get_sid() != rhs->get_sid())
	{
	    cout << "adjust sid " << rhs->get_impl().get_classname() << " ("
		 << rhs->get_displayname() << ") " << rhs->get_sid() << " -> "
		 << lhs->get_sid() << endl;

	    rhs->get_impl().set_sid(lhs->get_sid());
	}
    }

    TsCmpActiongraph::Expected::Expected(const string& filename)
    {
	std::ifstream fin(filename);
	if (!fin)
	    ST_THROW(Exception("failed to load " + filename));

	string line;
	while (getline(fin, line))
	{
	    if (!line.empty() && !boost::starts_with(line, "#"))
		lines.push_back(line);
	}
    }

    TsCmpActiongraph::TsCmpActiongraph(const string& name)
    {
	Environment environment(true, ProbeMode::READ_DEVICEGRAPH, TargetMode::DIRECT);
	environment.set_devicegraph_filename(name + "-probed.xml");

	Storage storage(environment);
	storage.probe();
	storage.get_staging()->load(name + "-staging.xml");

	Actiongraph actiongraph(storage, storage.get_system(), storage.get_staging());

	if (access("/usr/bin/dot", X_OK) == 0)
	{
	    storage.get_probed()->write_graphviz(name + "-probed.gv", GraphvizFlags::SID);
	    system(("dot -Tsvg < " + name + "-probed.gv > " + name + "-probed.svg").c_str());

	    storage.get_staging()->write_graphviz(name + "-staging.gv", GraphvizFlags::SID);
	    system(("dot -Tsvg < " + name + "-staging.gv > " + name + "-staging.svg").c_str());

	    actiongraph.write_graphviz(name + "-action.gv", GraphvizFlags::SID);
	    system(("dot -Tsvg < " + name + "-action.gv > " + name + "-action.svg").c_str());
	}

	TsCmpActiongraph::Expected expected(name + "-expected.txt");

	const CommitData commit_data(actiongraph.get_impl(), Tense::SIMPLE_PRESENT);

	cmp(commit_data, expected);
    }

    TsCmpActiongraph::TsCmpActiongraph(const Actiongraph& actiongraph, const Expected& expected)
    {
	const CommitData commit_data(actiongraph.get_impl(), Tense::SIMPLE_PRESENT);

	cmp(commit_data, expected);
    }

    void
    TsCmpActiongraph::cmp(const CommitData& commit_data, const Expected& expected)
    {
	for (const string& line : expected.lines)
	    entries.push_back(Entry(line));

	check();

	cmp_texts(commit_data);

	if (!ok())
	    return;

	cmp_dependencies(commit_data);
    }

    TsCmpActiongraph::Entry::Entry(const string& line)
    {
	string::size_type pos1 = line.find('-');
	if (pos1 == string::npos)
	    ST_THROW(Exception("parse error, did not find '-'"));

	string::size_type pos2 = line.rfind("->");
	if (pos2 == string::npos)
	    ST_THROW(Exception("parse error, did not find '->'"));

	id = boost::trim_copy(line.substr(0, pos1), locale::classic());
	text = boost::trim_copy(line.substr(pos1 + 1, pos2 - pos1 - 1), locale::classic());

	string tmp = boost::trim_copy(line.substr(pos2 + 2), locale::classic());
	if (!tmp.empty())
	    boost::split(dep_ids, tmp, boost::is_any_of(" "), boost::token_compress_on);
    }

    void
    TsCmpActiongraph::check() const
    {
	set<string> ids;
	set<string> texts;

	for (const Entry& entry : entries)
	{
	    if (!ids.insert(entry.id).second)
		ST_THROW(Exception("duplicate id"));

	    if (!texts.insert(entry.text).second)
		ST_THROW(Exception("duplicate text"));
	}

	for (const Entry& entry : entries)
	{
	    for (const string dep_id : entry.dep_ids)
	    {
		if (ids.find(dep_id) == ids.end())
		    ST_THROW(Exception("unknown dependency-id"));
	    }
	}
    }

    string
    TsCmpActiongraph::text(const CommitData& commit_data, Actiongraph::Impl::vertex_descriptor vertex) const
    {
	const Action::Base* action = commit_data.actiongraph[vertex];

	string text = action->text(commit_data).native;

	if (action->nop)
	    text += " [nop]";

	return text;
    }

    void
    TsCmpActiongraph::cmp_texts(const CommitData& commit_data)
    {
	set<string> tmp1;
	for (Actiongraph::Impl::vertex_descriptor vertex : commit_data.actiongraph.vertices())
	    tmp1.insert(text(commit_data, vertex));

	set<string> tmp2;
	for (const Entry& entry : entries)
	    tmp2.insert(entry.text);

	if (tmp1 != tmp2)
	{
	    errors.push_back("action texts differ");

	    vector<string> diff1;
	    set_difference(tmp2.begin(), tmp2.end(), tmp1.begin(), tmp1.end(), back_inserter(diff1));
	    for (const string& error : diff1)
		errors.push_back("- " + error);

	    vector<string> diff2;
	    set_difference(tmp1.begin(), tmp1.end(), tmp2.begin(), tmp2.end(), back_inserter(diff2));
	    for (const string& error : diff2)
		errors.push_back("+ " + error);
	}
    }

    void
    TsCmpActiongraph::cmp_dependencies(const CommitData& commit_data)
    {
	map<string, string> text_to_id;
	for (const Entry& entry : entries)
	    text_to_id[entry.text] = entry.id;

	map<string, Actiongraph::Impl::vertex_descriptor> text_to_vertex;
	for (Actiongraph::Impl::vertex_descriptor vertex : commit_data.actiongraph.vertices())
	    text_to_vertex[text(commit_data, vertex)] = vertex;

	for (const Entry& entry : entries)
	{
	    Actiongraph::Impl::vertex_descriptor vertex = text_to_vertex[entry.text];

	    set<string> tmp;
	    for (Actiongraph::Impl::vertex_descriptor child : commit_data.actiongraph.children(vertex))
		tmp.insert(text_to_id[text(commit_data, child)]);

	    if (tmp != entry.dep_ids)
	    {
		errors.push_back("wrong dependencies for '" + entry.text + "'");
		errors.push_back("- " + boost::join(tmp, " "));
		errors.push_back("+ " + boost::join(entry.dep_ids, " "));
	    }
	}
    }

}
<commit_msg>- generate dot files with more information<commit_after>

#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/algorithm/string.hpp>

#include "storage/DevicegraphImpl.h"
#include "storage/Environment.h"
#include "storage/Storage.h"
#include "storage/Action.h"
#include "storage/Devices/DeviceImpl.h"
#include "storage/Devices/BlkDevice.h"
#include "storage/Devices/Partitionable.h"
#include "storage/Devices/PartitionTable.h"
#include "storage/Devices/LvmVgImpl.h"
#include "storage/Devices/LvmPvImpl.h"
#include "storage/Devices/BcacheCsetImpl.h"
#include "storage/Filesystems/BlkFilesystem.h"
#include "storage/Filesystems/Btrfs.h"
#include "storage/Filesystems/BtrfsSubvolume.h"
#include "storage/Filesystems/MountPoint.h"
#include "testsuite/helpers/TsCmp.h"

using namespace std;

namespace storage
{

    std::ostream&
    operator<<(std::ostream& out, const TsCmp& ts_cmp)
    {
	out << endl;

	for (const string& error : ts_cmp.errors)
	    out << error << endl;

	return out;
    }

    TsCmpDevicegraph::TsCmpDevicegraph(const Devicegraph& lhs, Devicegraph& rhs)
    {
	adjust_sids(lhs, rhs);

	if (lhs != rhs)
	{
	    ostringstream tmp1;
	    lhs.get_impl().log_diff(tmp1, rhs.get_impl());
	    string tmp2 = tmp1.str();
	    boost::split(errors, tmp2, boost::is_any_of("\n"), boost::token_compress_on);
	}
    }

    /**
     * This function adjusts the sids which is needed when devices are the
     * detected in a differnet order than expected. Block devices use the name
     * for identification, most others a uuid or a path. Some types are not
     * handled at all, e.g. Nfs.
     *
     * The function makes assumptions that break in the general case and does
     * no error checking. It can even ruin the devicegraph.
     *
     * Only enable it when you know what you are doing!
     */
    void
    TsCmpDevicegraph::adjust_sids(const Devicegraph& lhs, Devicegraph& rhs) const
    {
#if 0

	for (Device* device_rhs : Device::get_all(&rhs))
	{
	    // BlkDevices

	    if (is_blk_device(device_rhs))
	    {
		BlkDevice* blk_device_rhs = to_blk_device(device_rhs);
		const BlkDevice* blk_device_lhs = BlkDevice::find_by_name(&lhs, blk_device_rhs->get_name());

		adjust_sid(blk_device_lhs, blk_device_rhs);

		// PartitionTables

		if (is_partitionable(blk_device_lhs) && is_partitionable(blk_device_rhs))
		{
		    const Partitionable* partitionable_lhs = to_partitionable(blk_device_lhs);
		    Partitionable* partitionable_rhs = to_partitionable(blk_device_rhs);

		    if (partitionable_lhs->has_partition_table() && partitionable_rhs->has_partition_table())
			adjust_sid(partitionable_lhs->get_partition_table(), partitionable_rhs->get_partition_table());
		}
	    }

	    // LvmVgs

	    if (is_lvm_vg(device_rhs))
	    {
		LvmVg* lvm_vg_rhs = to_lvm_vg(device_rhs);
		const LvmVg* lvm_vg_lhs = LvmVg::Impl::find_by_uuid(&lhs, lvm_vg_rhs->get_impl().get_uuid());

		adjust_sid(lvm_vg_lhs, lvm_vg_rhs);
	    }

	    // LvmPvs

	    if (is_lvm_pv(device_rhs))
	    {
		LvmPv* lvm_pv_rhs = to_lvm_pv(device_rhs);
		const LvmPv* lvm_pv_lhs = LvmPv::Impl::find_by_uuid(&lhs, lvm_pv_rhs->get_impl().get_uuid());

		adjust_sid(lvm_pv_lhs, lvm_pv_rhs);
	    }

	    // BcacheCset

	    if (is_bcache_cset(device_rhs))
	    {
		BcacheCset* bcache_cset_rhs = to_bcache_cset(device_rhs);
		const BcacheCset* bcache_cset_lhs = BcacheCset::Impl::find_by_uuid(&lhs, bcache_cset_rhs->get_uuid());

		adjust_sid(bcache_cset_lhs, bcache_cset_rhs);
	    }

	    // BlkFilesystems

	    if (is_blk_filesystem(device_rhs))
	    {
		BlkFilesystem* blk_filesystem_rhs = to_blk_filesystem(device_rhs);
		const BlkFilesystem* blk_filesystem_lhs = BlkFilesystem::find_by_uuid(&lhs, blk_filesystem_rhs->get_uuid()).front();

		adjust_sid(blk_filesystem_lhs, blk_filesystem_rhs);

		// BtrfsSubvolumes

		if (is_btrfs(blk_filesystem_lhs) && is_btrfs(blk_filesystem_rhs))
		{
		    const Btrfs* btrfs_lhs = to_btrfs(blk_filesystem_lhs);
		    Btrfs* btrfs_rhs = to_btrfs(blk_filesystem_rhs);

		    for (BtrfsSubvolume* btrfs_subvolume_rhs : btrfs_rhs->get_btrfs_subvolumes())
		    {
			const BtrfsSubvolume* btrfs_subvolume_lhs = btrfs_lhs->find_btrfs_subvolume_by_path(btrfs_subvolume_rhs->get_path());
			adjust_sid(btrfs_subvolume_lhs, btrfs_subvolume_rhs);
		    }
		}
	    }

	    // MountPoints

	    if (is_mount_point(device_rhs))
            {
                MountPoint* mount_point_rhs = to_mount_point(device_rhs);
                const MountPoint* mount_point_lhs = MountPoint::find_by_path(&lhs, mount_point_rhs->get_path()).front();

		adjust_sid(mount_point_lhs, mount_point_rhs);
            }
	}

#endif
    }

    void
    TsCmpDevicegraph::adjust_sid(const Device* lhs, Device* rhs) const
    {
	if (lhs->get_sid() != rhs->get_sid())
	{
	    cout << "adjust sid " << rhs->get_impl().get_classname() << " ("
		 << rhs->get_displayname() << ") " << rhs->get_sid() << " -> "
		 << lhs->get_sid() << endl;

	    rhs->get_impl().set_sid(lhs->get_sid());
	}
    }

    TsCmpActiongraph::Expected::Expected(const string& filename)
    {
	std::ifstream fin(filename);
	if (!fin)
	    ST_THROW(Exception("failed to load " + filename));

	string line;
	while (getline(fin, line))
	{
	    if (!line.empty() && !boost::starts_with(line, "#"))
		lines.push_back(line);
	}
    }

    TsCmpActiongraph::TsCmpActiongraph(const string& name)
    {
	Environment environment(true, ProbeMode::READ_DEVICEGRAPH, TargetMode::DIRECT);
	environment.set_devicegraph_filename(name + "-probed.xml");

	Storage storage(environment);
	storage.probe();
	storage.get_staging()->load(name + "-staging.xml");

	Actiongraph actiongraph(storage, storage.get_system(), storage.get_staging());

	if (access("/usr/bin/dot", X_OK) == 0)
	{
	    storage.get_probed()->write_graphviz(name + "-probed.gv", GraphvizFlags::CLASSNAME |
						 GraphvizFlags::NAME | GraphvizFlags::SID |
						 GraphvizFlags::SIZE);
	    system(("dot -Tsvg < " + name + "-probed.gv > " + name + "-probed.svg").c_str());

	    storage.get_staging()->write_graphviz(name + "-staging.gv", GraphvizFlags::CLASSNAME |
						  GraphvizFlags::NAME | GraphvizFlags::SID |
						  GraphvizFlags::SIZE);
	    system(("dot -Tsvg < " + name + "-staging.gv > " + name + "-staging.svg").c_str());

	    actiongraph.write_graphviz(name + "-action.gv", GraphvizFlags::SID | GraphvizFlags::NAME);
	    system(("dot -Tsvg < " + name + "-action.gv > " + name + "-action.svg").c_str());
	}

	TsCmpActiongraph::Expected expected(name + "-expected.txt");

	const CommitData commit_data(actiongraph.get_impl(), Tense::SIMPLE_PRESENT);

	cmp(commit_data, expected);
    }

    TsCmpActiongraph::TsCmpActiongraph(const Actiongraph& actiongraph, const Expected& expected)
    {
	const CommitData commit_data(actiongraph.get_impl(), Tense::SIMPLE_PRESENT);

	cmp(commit_data, expected);
    }

    void
    TsCmpActiongraph::cmp(const CommitData& commit_data, const Expected& expected)
    {
	for (const string& line : expected.lines)
	    entries.push_back(Entry(line));

	check();

	cmp_texts(commit_data);

	if (!ok())
	    return;

	cmp_dependencies(commit_data);
    }

    TsCmpActiongraph::Entry::Entry(const string& line)
    {
	string::size_type pos1 = line.find('-');
	if (pos1 == string::npos)
	    ST_THROW(Exception("parse error, did not find '-'"));

	string::size_type pos2 = line.rfind("->");
	if (pos2 == string::npos)
	    ST_THROW(Exception("parse error, did not find '->'"));

	id = boost::trim_copy(line.substr(0, pos1), locale::classic());
	text = boost::trim_copy(line.substr(pos1 + 1, pos2 - pos1 - 1), locale::classic());

	string tmp = boost::trim_copy(line.substr(pos2 + 2), locale::classic());
	if (!tmp.empty())
	    boost::split(dep_ids, tmp, boost::is_any_of(" "), boost::token_compress_on);
    }

    void
    TsCmpActiongraph::check() const
    {
	set<string> ids;
	set<string> texts;

	for (const Entry& entry : entries)
	{
	    if (!ids.insert(entry.id).second)
		ST_THROW(Exception("duplicate id"));

	    if (!texts.insert(entry.text).second)
		ST_THROW(Exception("duplicate text"));
	}

	for (const Entry& entry : entries)
	{
	    for (const string dep_id : entry.dep_ids)
	    {
		if (ids.find(dep_id) == ids.end())
		    ST_THROW(Exception("unknown dependency-id"));
	    }
	}
    }

    string
    TsCmpActiongraph::text(const CommitData& commit_data, Actiongraph::Impl::vertex_descriptor vertex) const
    {
	const Action::Base* action = commit_data.actiongraph[vertex];

	string text = action->text(commit_data).native;

	if (action->nop)
	    text += " [nop]";

	return text;
    }

    void
    TsCmpActiongraph::cmp_texts(const CommitData& commit_data)
    {
	set<string> tmp1;
	for (Actiongraph::Impl::vertex_descriptor vertex : commit_data.actiongraph.vertices())
	    tmp1.insert(text(commit_data, vertex));

	set<string> tmp2;
	for (const Entry& entry : entries)
	    tmp2.insert(entry.text);

	if (tmp1 != tmp2)
	{
	    errors.push_back("action texts differ");

	    vector<string> diff1;
	    set_difference(tmp2.begin(), tmp2.end(), tmp1.begin(), tmp1.end(), back_inserter(diff1));
	    for (const string& error : diff1)
		errors.push_back("- " + error);

	    vector<string> diff2;
	    set_difference(tmp1.begin(), tmp1.end(), tmp2.begin(), tmp2.end(), back_inserter(diff2));
	    for (const string& error : diff2)
		errors.push_back("+ " + error);
	}
    }

    void
    TsCmpActiongraph::cmp_dependencies(const CommitData& commit_data)
    {
	map<string, string> text_to_id;
	for (const Entry& entry : entries)
	    text_to_id[entry.text] = entry.id;

	map<string, Actiongraph::Impl::vertex_descriptor> text_to_vertex;
	for (Actiongraph::Impl::vertex_descriptor vertex : commit_data.actiongraph.vertices())
	    text_to_vertex[text(commit_data, vertex)] = vertex;

	for (const Entry& entry : entries)
	{
	    Actiongraph::Impl::vertex_descriptor vertex = text_to_vertex[entry.text];

	    set<string> tmp;
	    for (Actiongraph::Impl::vertex_descriptor child : commit_data.actiongraph.children(vertex))
		tmp.insert(text_to_id[text(commit_data, child)]);

	    if (tmp != entry.dep_ids)
	    {
		errors.push_back("wrong dependencies for '" + entry.text + "'");
		errors.push_back("- " + boost::join(tmp, " "));
		errors.push_back("+ " + boost::join(entry.dep_ids, " "));
	    }
	}
    }

}
<|endoftext|>


<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
**    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
**      disclaimer.
**    * 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.
**    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
**      derived from this software without specific prior written permission.
**
**
** 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.
**
***********************************************************************************************************************/

/***********************************************************************************************************************
 * PositionLayout.cpp
 *
 *  Created on: Feb 2, 2011
 *      Author: Dimitar Asenov
 **********************************************************************************************************************/

#include "layouts/PositionLayout.h"
#include "shapes/Shape.h"
#include "../renderer/ModelRenderer.h"

#include "ModelBase/src/model/Model.h"

namespace Visualization {

ITEM_COMMON_DEFINITIONS( PositionLayout, "layout" )

PositionLayout::PositionLayout(Item* parent, const StyleType* style) :
	Layout(parent, style)
{
}

PositionLayout::~PositionLayout()
{
	for (int i = 0; i<items.size(); i++) SAFE_DELETE_ITEM( items[i]);
}

int PositionLayout::length() const
{
	return items.size();
}

bool PositionLayout::containsNode(Model::Node* node_)
{
	for(int i=0; i<items.size(); ++i)
		if (items[i]->node() == node_) return true;

	return false;
}

void PositionLayout::insert(Item* item)
{
	// Check whether this item has a node and a position associated with it
	if ( !item->hasNode() ) throw VisualizationException("Adding an Item that has no node to a PositionLayout");

	Model::ExtendableNode* extNode = dynamic_cast<Model::ExtendableNode*> (item->node());
	if (!extNode)
		throw VisualizationException("Adding an Item that does not implement ExtendableNode to a PositionLayout");

	Position* pos = extNode->extension<Position>();

	if (!pos)
		throw VisualizationException("Adding a Item whose node does not have a Position extension to a PositionLayout");

	item->setParentItem(this);
	items.append(item);
	positions.append(pos);
	setUpdateNeeded(StandardUpdate);
}

void PositionLayout::remove(int index, bool deleteItem)
{
	if (deleteItem) SAFE_DELETE_ITEM( items[index]);
	else if(items[index]) items[index]->setParentItem(nullptr);

	SAFE_DELETE( positions[index] );
	items.remove(index);
	positions.remove(index);
	setUpdateNeeded(StandardUpdate);
}

void PositionLayout::removeAll(Item* item, bool deleteItem)
{
	for (int i = items.size() - 1; i>=0; --i)
	{
		if (items.at(i) == item)
		{
			items.remove(i);
			SAFE_DELETE( positions[i] );
			positions.remove(i);
		}
	}

	if (deleteItem) SAFE_DELETE_ITEM(item);
	else if (item) item->setParentItem(nullptr);

	setUpdateNeeded(StandardUpdate);
}

void PositionLayout::clear(bool deleteItems)
{
	for (int i = 0; i<items.size(); ++i)
	{
		if (deleteItems) SAFE_DELETE_ITEM(items[i]);
		else if (items[i]) items[i]->setParentItem(nullptr);
	}

	for (int i = 0; i<positions.size(); ++i) SAFE_DELETE(positions[i]);
	items.clear();
	positions.clear();
}

void PositionLayout::swap(int i, int j)
{
	Item* t = items[i];
	items[i] = items[j];
	items[j] = t;

	Position* p = positions[i];
	positions[i] = positions[j];
	positions[j] = p;
}

void PositionLayout::synchronizeWithNodes(const QList<Model::Node*>& nodes, ModelRenderer* renderer)
{
	allNodesLackPositionInfo = items.isEmpty();

	// Inserts elements that are not yet visualized and adjusts the order to match that in 'nodes'.
	for (int i = 0; i < nodes.size(); ++i)
	{
		// Check if node has position info
		Model::ExtendableNode* extNode = dynamic_cast<Model::ExtendableNode*> (nodes[i]);
		if (extNode)
		{
			Position* pos = extNode->extension<Position>();
			if (pos)
			{
				if (pos->xNode() || pos->yNode())
					allNodesLackPositionInfo = false;
			}
		}

		if (i >= items.size() ) insert( renderer->render(this, nodes[i]));	// This node is new
		else if ( items[i]->node() == nodes[i] ) continue;	// This node is already there
		else
		{
			// This node might appear somewhere ahead, we should look for it
			bool found = false;
			for (int k = i + 1; k<items.size(); ++k)
			{
				if ( items[k]->node() == nodes[i] )
				{
					// We found this node, swap the visualizations
					swap(i, k);
					found = true;
					break;
				}
			}

			// The node was not found, insert a visualization here
			if (!found )
			{
				insert( renderer->render(this, nodes[i]) );
				swap(i, items.size()-1);
			}
		}
	}

	// Remove excess items
	while (items.size() > nodes.size()) remove(items.size()-1);
}

inline int PositionLayout::toGrid(const int& pos) const
{
	int mod = (pos >=0) ? ( pos % style()->gridSize() ) : ( (-pos) % style()->gridSize() );
	int add = (pos >=0) ? ( style()->gridSize() - mod) : mod;
	return pos + ( (mod !=0) ? add : 0 );
}

bool PositionLayout::isEmpty() const
{
	for(int i = 0; i<items.size(); ++i)
		if (!items[i]->isEmpty()) return false;

	return true;
}

void PositionLayout::updateGeometry(int, int)
{
	// Arrange items if they were all missing positions.
	if (allNodesLackPositionInfo && !items.isEmpty())
	{
		// Get averages
		double averageWidth = 0;
		double averageHeight = 0;
		for(auto i : items)
		{
			averageWidth += i->width();
			averageHeight += i->height();
		}
		averageWidth /= items.size();
		averageHeight /= items.size();

		// Get 'optimal' number of rows to achieve a square
		double prevRatio = 0;
		int rows = 1;
		for (rows = 1; rows<items.size(); ++rows)
		{
			int cols = (items.size()/rows) + ((items.size()%rows)?1:0);
			double ratio = (averageWidth*cols) / (averageHeight*rows);

			if (ratio > 1) ratio = 1/ratio;

			if (ratio > prevRatio)
			{
				prevRatio = ratio;
			}
			else
			{
				if (rows > 1) --rows;
				break;
			}
		}

		int heightLimit = rows*averageHeight;

		//Compute the columns and set the positions
		int lastBottom = 0;
		int lastRight = 0;
		int colWidth = 0;

		for(int i = 0; i<items.size(); ++i)
		{
			int x = lastRight;
			int y = lastBottom;

			if (lastBottom == 0 || (lastBottom + items[i]->height() <= heightLimit))
			{
				lastBottom += 10 + items[i]->height();
				lastBottom = toGrid(lastBottom);

				if (items[i]->width() > colWidth) colWidth =  items[i]->width();
			}
			else
			{
				y = 0;
				lastBottom = 10 + items[i]->height();

				lastRight += 10 + colWidth;
				lastRight = toGrid(lastRight);
				x = lastRight;
				colWidth = items[i]->width();
			}

			items[i]->node()->beginModification("Automatically set position");
			positions[i]->setX(x);
			positions[i]->setY(y);
			items[i]->node()->endModification();
		}

		allNodesLackPositionInfo = false;
	}

	QPoint topLeft;
	QPoint bottomRight;

	for(int i = 0; i<items.size(); ++i)
	{
		int x = positions[i]->xNode() ? toGrid(positions[i]->x()) : 0;
		int y = positions[i]->yNode() ? toGrid(positions[i]->y()) : 0;

		if (i==0 || topLeft.x() > x )
			topLeft.setX( x );
		if (i==0 || topLeft.y() > y )
			topLeft.setY( y );
		if (i==0 || bottomRight.x() < x + items[i]->width()  )
			bottomRight.setX( x + items[i]->width() );
		if (i==0 || bottomRight.y() < y + items[i]->height() )
			bottomRight.setY( y + items[i]->height() );
	}

	int sizeWidth = bottomRight.x() - topLeft.x() + style()->leftInnerMargin() + style()->rightInnerMargin();
	int sizeHeight = bottomRight.y() - topLeft.y() + style()->topInnerMargin() + style()->bottomInnerMargin();
	setInnerSize(sizeWidth, sizeHeight);

	for (int i =0; i<items.size(); ++i)
	{
		int x = positions[i]->xNode() ? toGrid(positions[i]->x()) : 0;
		int y = positions[i]->yNode() ? toGrid(positions[i]->y()) : 0;
		items[i]->setPos( xOffset() + style()->leftInnerMargin() + x - topLeft.x(),
								yOffset() + style()->topInnerMargin() + y - topLeft.y());
	}
}

int PositionLayout::focusedElementIndex() const
{
	for (int i = 0; i<items.size(); ++i)
		if ( items[i]->itemOrChildHasFocus()) return i;

	return -1;
}

}
<commit_msg>Speedup automatic positioning of nodes within a PositionLayout<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
**    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
**      disclaimer.
**    * 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.
**    * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
**      derived from this software without specific prior written permission.
**
**
** 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.
**
***********************************************************************************************************************/

/***********************************************************************************************************************
 * PositionLayout.cpp
 *
 *  Created on: Feb 2, 2011
 *      Author: Dimitar Asenov
 **********************************************************************************************************************/

#include "layouts/PositionLayout.h"
#include "shapes/Shape.h"
#include "../renderer/ModelRenderer.h"

#include "ModelBase/src/model/Model.h"

namespace Visualization {

ITEM_COMMON_DEFINITIONS( PositionLayout, "layout" )

PositionLayout::PositionLayout(Item* parent, const StyleType* style) :
	Layout(parent, style)
{
}

PositionLayout::~PositionLayout()
{
	for (int i = 0; i<items.size(); i++) SAFE_DELETE_ITEM( items[i]);
}

int PositionLayout::length() const
{
	return items.size();
}

bool PositionLayout::containsNode(Model::Node* node_)
{
	for(int i=0; i<items.size(); ++i)
		if (items[i]->node() == node_) return true;

	return false;
}

void PositionLayout::insert(Item* item)
{
	// Check whether this item has a node and a position associated with it
	if ( !item->hasNode() ) throw VisualizationException("Adding an Item that has no node to a PositionLayout");

	Model::ExtendableNode* extNode = dynamic_cast<Model::ExtendableNode*> (item->node());
	if (!extNode)
		throw VisualizationException("Adding an Item that does not implement ExtendableNode to a PositionLayout");

	Position* pos = extNode->extension<Position>();

	if (!pos)
		throw VisualizationException("Adding a Item whose node does not have a Position extension to a PositionLayout");

	item->setParentItem(this);
	items.append(item);
	positions.append(pos);
	setUpdateNeeded(StandardUpdate);
}

void PositionLayout::remove(int index, bool deleteItem)
{
	if (deleteItem) SAFE_DELETE_ITEM( items[index]);
	else if(items[index]) items[index]->setParentItem(nullptr);

	SAFE_DELETE( positions[index] );
	items.remove(index);
	positions.remove(index);
	setUpdateNeeded(StandardUpdate);
}

void PositionLayout::removeAll(Item* item, bool deleteItem)
{
	for (int i = items.size() - 1; i>=0; --i)
	{
		if (items.at(i) == item)
		{
			items.remove(i);
			SAFE_DELETE( positions[i] );
			positions.remove(i);
		}
	}

	if (deleteItem) SAFE_DELETE_ITEM(item);
	else if (item) item->setParentItem(nullptr);

	setUpdateNeeded(StandardUpdate);
}

void PositionLayout::clear(bool deleteItems)
{
	for (int i = 0; i<items.size(); ++i)
	{
		if (deleteItems) SAFE_DELETE_ITEM(items[i]);
		else if (items[i]) items[i]->setParentItem(nullptr);
	}

	for (int i = 0; i<positions.size(); ++i) SAFE_DELETE(positions[i]);
	items.clear();
	positions.clear();
}

void PositionLayout::swap(int i, int j)
{
	Item* t = items[i];
	items[i] = items[j];
	items[j] = t;

	Position* p = positions[i];
	positions[i] = positions[j];
	positions[j] = p;
}

void PositionLayout::synchronizeWithNodes(const QList<Model::Node*>& nodes, ModelRenderer* renderer)
{
	allNodesLackPositionInfo = items.isEmpty();

	// Inserts elements that are not yet visualized and adjusts the order to match that in 'nodes'.
	for (int i = 0; i < nodes.size(); ++i)
	{
		// Check if node has position info
		Model::ExtendableNode* extNode = dynamic_cast<Model::ExtendableNode*> (nodes[i]);
		if (extNode)
		{
			Position* pos = extNode->extension<Position>();
			if (pos)
			{
				if (pos->xNode() || pos->yNode())
					allNodesLackPositionInfo = false;
			}
		}

		if (i >= items.size() ) insert( renderer->render(this, nodes[i]));	// This node is new
		else if ( items[i]->node() == nodes[i] ) continue;	// This node is already there
		else
		{
			// This node might appear somewhere ahead, we should look for it
			bool found = false;
			for (int k = i + 1; k<items.size(); ++k)
			{
				if ( items[k]->node() == nodes[i] )
				{
					// We found this node, swap the visualizations
					swap(i, k);
					found = true;
					break;
				}
			}

			// The node was not found, insert a visualization here
			if (!found )
			{
				insert( renderer->render(this, nodes[i]) );
				swap(i, items.size()-1);
			}
		}
	}

	// Remove excess items
	while (items.size() > nodes.size()) remove(items.size()-1);
}

inline int PositionLayout::toGrid(const int& pos) const
{
	int mod = (pos >=0) ? ( pos % style()->gridSize() ) : ( (-pos) % style()->gridSize() );
	int add = (pos >=0) ? ( style()->gridSize() - mod) : mod;
	return pos + ( (mod !=0) ? add : 0 );
}

bool PositionLayout::isEmpty() const
{
	for(int i = 0; i<items.size(); ++i)
		if (!items[i]->isEmpty()) return false;

	return true;
}

void PositionLayout::updateGeometry(int, int)
{
	// Arrange items if they were all missing positions.
	if (allNodesLackPositionInfo && !items.isEmpty())
	{
		// Get averages
		double averageWidth = 0;
		double averageHeight = 0;
		for(auto i : items)
		{
			averageWidth += i->width();
			averageHeight += i->height();
		}
		averageWidth /= items.size();
		averageHeight /= items.size();

		// Get 'optimal' number of rows to achieve a square
		double prevRatio = 0;
		int rows = 1;
		for (rows = 1; rows<items.size(); ++rows)
		{
			int cols = (items.size()/rows) + ((items.size()%rows)?1:0);
			double ratio = (averageWidth*cols) / (averageHeight*rows);

			if (ratio > 1) ratio = 1/ratio;

			if (ratio > prevRatio)
			{
				prevRatio = ratio;
			}
			else
			{
				if (rows > 1) --rows;
				break;
			}
		}

		int heightLimit = rows*averageHeight;

		//Compute the columns and set the positions
		int lastBottom = 0;
		int lastRight = 0;
		int colWidth = 0;

		auto model = items[0]->node()->model();
		model->beginModification(items[0]->node(), "Automatically set position");
		// It is important to batch the modifications, since model::endModification() send a notification signal.

		for(int i = 0; i<items.size(); ++i)
		{
			int x = lastRight;
			int y = lastBottom;

			if (lastBottom == 0 || (lastBottom + items[i]->height() <= heightLimit))
			{
				lastBottom += 10 + items[i]->height();
				lastBottom = toGrid(lastBottom);

				if (items[i]->width() > colWidth) colWidth =  items[i]->width();
			}
			else
			{
				y = 0;
				lastBottom = 10 + items[i]->height();

				lastRight += 10 + colWidth;
				lastRight = toGrid(lastRight);
				x = lastRight;
				colWidth = items[i]->width();
			}

			model->changeModificationTarget(items[i]->node());
			positions[i]->setX(x);
			positions[i]->setY(y);
		}

		model->endModification();
		allNodesLackPositionInfo = false;
	}

	QPoint topLeft;
	QPoint bottomRight;

	for(int i = 0; i<items.size(); ++i)
	{
		int x = positions[i]->xNode() ? toGrid(positions[i]->x()) : 0;
		int y = positions[i]->yNode() ? toGrid(positions[i]->y()) : 0;

		if (i==0 || topLeft.x() > x )
			topLeft.setX( x );
		if (i==0 || topLeft.y() > y )
			topLeft.setY( y );
		if (i==0 || bottomRight.x() < x + items[i]->width()  )
			bottomRight.setX( x + items[i]->width() );
		if (i==0 || bottomRight.y() < y + items[i]->height() )
			bottomRight.setY( y + items[i]->height() );
	}

	int sizeWidth = bottomRight.x() - topLeft.x() + style()->leftInnerMargin() + style()->rightInnerMargin();
	int sizeHeight = bottomRight.y() - topLeft.y() + style()->topInnerMargin() + style()->bottomInnerMargin();
	setInnerSize(sizeWidth, sizeHeight);

	for (int i =0; i<items.size(); ++i)
	{
		int x = positions[i]->xNode() ? toGrid(positions[i]->x()) : 0;
		int y = positions[i]->yNode() ? toGrid(positions[i]->y()) : 0;
		items[i]->setPos( xOffset() + style()->leftInnerMargin() + x - topLeft.x(),
								yOffset() + style()->topInnerMargin() + y - topLeft.y());
	}
}

int PositionLayout::focusedElementIndex() const
{
	for (int i = 0; i<items.size(); ++i)
		if ( items[i]->itemOrChildHasFocus()) return i;

	return -1;
}

}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#include <algorithm>
#include "simple_strategy.hh"
#include "utils/class_registrator.hh"
#include <boost/algorithm/string.hpp>
#include "utils/sequenced_set.hh"

namespace locator {

simple_strategy::simple_strategy(const sstring& keyspace_name, token_metadata& token_metadata, snitch_ptr& snitch, const std::map<sstring, sstring>& config_options) :
        abstract_replication_strategy(keyspace_name, token_metadata, snitch, config_options, replication_strategy_type::simple) {
    for (auto& config_pair : config_options) {
        auto& key = config_pair.first;
        auto& val = config_pair.second;

        if (boost::iequals(key, "replication_factor")) {
            _replication_factor = std::stol(val);

            break;
        }
    }
}

std::vector<inet_address> simple_strategy::calculate_natural_endpoints(const token& t) {
    const std::vector<token>& tokens = _token_metadata.sorted_tokens();

    if (tokens.empty()) {
        return std::vector<inet_address>();
    }

    size_t replicas = get_replication_factor();
    utils::sequenced_set<inet_address> endpoints;
    endpoints.reserve(replicas);

    for (auto& token : _token_metadata.ring_range(t)) {
        auto ep = _token_metadata.get_endpoint(token);
        assert(ep);

        endpoints.push_back(*ep);
        if (endpoints.size() == replicas) break;
    }

    return std::move(endpoints.get_vector());
}

size_t simple_strategy::get_replication_factor() const {
    return _replication_factor;
}

using registry = class_registrator<abstract_replication_strategy, simple_strategy, const sstring&, token_metadata&, snitch_ptr&, const std::map<sstring, sstring>&>;
static registry registrator("org.apache.cassandra.locator.SimpleStrategy");
static registry registrator_short_name("SimpleStrategy");

}
<commit_msg>simple_strategy: coding convention fixes<commit_after>/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#include <algorithm>
#include "simple_strategy.hh"
#include "utils/class_registrator.hh"
#include <boost/algorithm/string.hpp>
#include "utils/sequenced_set.hh"

namespace locator {

simple_strategy::simple_strategy(const sstring& keyspace_name, token_metadata& token_metadata, snitch_ptr& snitch, const std::map<sstring, sstring>& config_options) :
        abstract_replication_strategy(keyspace_name, token_metadata, snitch, config_options, replication_strategy_type::simple) {
    for (auto& config_pair : config_options) {
        auto& key = config_pair.first;
        auto& val = config_pair.second;

        if (boost::iequals(key, "replication_factor")) {
            _replication_factor = std::stol(val);

            break;
        }
    }
}

std::vector<inet_address> simple_strategy::calculate_natural_endpoints(const token& t) {
    const std::vector<token>& tokens = _token_metadata.sorted_tokens();

    if (tokens.empty()) {
        return std::vector<inet_address>();
    }

    size_t replicas = get_replication_factor();
    utils::sequenced_set<inet_address> endpoints;
    endpoints.reserve(replicas);

    for (auto& token : _token_metadata.ring_range(t)) {
        auto ep = _token_metadata.get_endpoint(token);
        assert(ep);

        endpoints.push_back(*ep);
        if (endpoints.size() == replicas) {
           break;
        }
    }

    return std::move(endpoints.get_vector());
}

size_t simple_strategy::get_replication_factor() const {
    return _replication_factor;
}

using registry = class_registrator<abstract_replication_strategy, simple_strategy, const sstring&, token_metadata&, snitch_ptr&, const std::map<sstring, sstring>&>;
static registry registrator("org.apache.cassandra.locator.SimpleStrategy");
static registry registrator_short_name("SimpleStrategy");

}
<|endoftext|>