<commit_before>/*************************************************************************
 *
 *  $RCSfile: virdev.cxx,v $
 *
 *  $Revision: 1.13 $
 *
 *  last change: $Author: rt $ $Date: 2003-12-01 13:24:54 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#define _SV_VIRDEV_CXX

#ifndef _SV_SVSYS_HXX
#include <svsys.h>
#endif

#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SALGDI_HXX
#include <salgdi.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#ifndef _SV_SALVD_HXX
#include <salvd.hxx>
#endif

#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _SV_SETTINGS_HXX
#include <settings.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <svapp.hxx>
#endif
#ifndef _SV_WRKWIN_HXX
#include <wrkwin.hxx>
#endif
#ifndef _SV_OUTDEV_H
#include <outdev.h>
#endif
#ifndef _SV_VIRDEV_HXX
#include <virdev.hxx>
#endif

using namespace ::com::sun::star::uno;

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

void VirtualDevice::ImplInitVirDev( const OutputDevice* pOutDev,
                                    long nDX, long nDY, USHORT nBitCount )
{
    DBG_ASSERT( nBitCount <= 1,
                "VirtualDevice::VirtualDevice(): Only 0 or 1 is for BitCount allowed" );

    if ( nDX < 1 )
        nDX = 1;

    if ( nDY < 1 )
        nDY = 1;

    ImplSVData* pSVData = ImplGetSVData();

    if ( !pOutDev )
        pOutDev = ImplGetDefaultWindow();

    SalGraphics* pGraphics;
    if ( !pOutDev->mpGraphics )
        ((OutputDevice*)pOutDev)->ImplGetGraphics();
    pGraphics = pOutDev->mpGraphics;
    if ( pGraphics )
        mpVirDev = pSVData->mpDefInst->CreateVirtualDevice( pGraphics, nDX, nDY, nBitCount );
    else
        mpVirDev = NULL;
    if ( !mpVirDev )
        GetpApp()->Exception( EXC_SYSOBJNOTCREATED );

    mnBitCount      = ( nBitCount ? nBitCount : pOutDev->GetBitCount() );
    mnOutWidth      = nDX;
    mnOutHeight     = nDY;
    mbScreenComp    = TRUE;
    mbScreenComp    = FALSE;
    mnAlphaDepth    = -1;

    if( mnBitCount < 8 )
        SetAntialiasing( ANTIALIASING_DISABLE_TEXT );

    if ( pOutDev->GetOutDevType() == OUTDEV_PRINTER )
        mbScreenComp = FALSE;
    else if ( pOutDev->GetOutDevType() == OUTDEV_VIRDEV )
        mbScreenComp = ((VirtualDevice*)pOutDev)->mbScreenComp;

    meOutDevType    = OUTDEV_VIRDEV;
    mbDevOutput     = TRUE;
    mpFontList      = pSVData->maGDIData.mpScreenFontList;
    mpFontCache     = pSVData->maGDIData.mpScreenFontCache;
    mnDPIX          = pOutDev->mnDPIX;
    mnDPIY          = pOutDev->mnDPIY;
    maFont          = pOutDev->maFont;

    // Virtuelle Devices haben defaultmaessig einen weissen Hintergrund
    SetBackground( Wallpaper( Color( COL_WHITE ) ) );
    Erase();

    // VirDev in Liste eintragen
    mpNext = pSVData->maGDIData.mpFirstVirDev;
    mpPrev = NULL;
    if ( mpNext )
        mpNext->mpPrev = this;
    else
        pSVData->maGDIData.mpLastVirDev = this;
    pSVData->maGDIData.mpFirstVirDev = this;
}

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

VirtualDevice::VirtualDevice( USHORT nBitCount )
:   mpVirDev( NULL ),
    meRefDevMode( REFDEV_NONE )
{
    DBG_TRACE1( "VirtualDevice::VirtualDevice( %hu )", nBitCount );

    ImplInitVirDev( Application::GetDefaultDevice(), 1, 1, nBitCount );
}

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

VirtualDevice::VirtualDevice( const OutputDevice& rCompDev, USHORT nBitCount )
    : mpVirDev( NULL ),
    meRefDevMode( REFDEV_NONE )
{
    DBG_TRACE1( "VirtualDevice::VirtualDevice( %hu )", nBitCount );

    ImplInitVirDev( &rCompDev, 1, 1, nBitCount );
}

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

VirtualDevice::VirtualDevice( const OutputDevice& rCompDev, USHORT nBitCount, USHORT nAlphaBitCount )
    : mpVirDev( NULL )
{
    DBG_TRACE1( "VirtualDevice::VirtualDevice( %hu )", nBitCount );

    ImplInitVirDev( &rCompDev, 1, 1, nBitCount );

    // #110958# Enable alpha channel
    mnAlphaDepth = nAlphaBitCount;
}

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

VirtualDevice::~VirtualDevice()
{
    DBG_TRACE( "VirtualDevice::~VirtualDevice()" );

   ImplSVData* pSVData = ImplGetSVData();

    ImplReleaseGraphics();

    if ( mpVirDev )
        pSVData->mpDefInst->DestroyVirtualDevice( mpVirDev );

    // VirDev aus der Liste eintragen
    if( mpPrev )
        mpPrev->mpNext = mpNext;
    else
        pSVData->maGDIData.mpFirstVirDev = mpNext;

    if( mpNext )
        mpNext->mpPrev = mpPrev;
    else
        pSVData->maGDIData.mpLastVirDev = mpPrev;
}

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

BOOL VirtualDevice::ImplSetOutputSizePixel( const Size& rNewSize, BOOL bErase )
{
    DBG_TRACE3( "VirtualDevice::ImplSetOutputSizePixel( %ld, %ld, %d )", rNewSize.Width(), rNewSize.Height(), (int)bErase );

    if ( !mpVirDev )
        return FALSE;
    else if ( rNewSize == GetOutputSizePixel() )
    {
        if ( bErase )
            Erase();
        return TRUE;
    }

    BOOL bRet;
    long nNewWidth = rNewSize.Width(), nNewHeight = rNewSize.Height();

    if ( nNewWidth < 1 )
        nNewWidth = 1;

    if ( nNewHeight < 1 )
        nNewHeight = 1;

    if ( bErase )
    {
        bRet = mpVirDev->SetSize( nNewWidth, nNewHeight );

        if ( bRet )
        {
            mnOutWidth  = rNewSize.Width();
            mnOutHeight = rNewSize.Height();
            Erase();
        }
    }
    else
    {
        SalVirtualDevice*   pNewVirDev;
        ImplSVData*         pSVData = ImplGetSVData();

        // we need a graphics
        if ( !mpGraphics )
        {
            if ( !ImplGetGraphics() )
                return FALSE;
        }

        pNewVirDev = pSVData->mpDefInst->CreateVirtualDevice( mpGraphics, nNewWidth, nNewHeight, mnBitCount );
        if ( pNewVirDev )
        {
            SalGraphics* pGraphics = pNewVirDev->GetGraphics();
            if ( pGraphics )
            {
                SalTwoRect aPosAry;
                long nWidth;
                long nHeight;
                if ( mnOutWidth < nNewWidth )
                    nWidth = mnOutWidth;
                else
                    nWidth = nNewWidth;
                if ( mnOutHeight < nNewHeight )
                    nHeight = mnOutHeight;
                else
                    nHeight = nNewHeight;
                aPosAry.mnSrcX       = 0;
                aPosAry.mnSrcY       = 0;
                aPosAry.mnSrcWidth   = nWidth;
                aPosAry.mnSrcHeight  = nHeight;
                aPosAry.mnDestX      = 0;
                aPosAry.mnDestY      = 0;
                aPosAry.mnDestWidth  = nWidth;
                aPosAry.mnDestHeight = nHeight;

                pGraphics->CopyBits( &aPosAry, mpGraphics, this, this );
                pNewVirDev->ReleaseGraphics( pGraphics );
                ImplReleaseGraphics();
                pSVData->mpDefInst->DestroyVirtualDevice( mpVirDev );
                mpVirDev = pNewVirDev;
                mnOutWidth  = rNewSize.Width();
                mnOutHeight = rNewSize.Height();
                bRet = TRUE;
            }
            else
            {
                bRet = FALSE;
                pSVData->mpDefInst->DestroyVirtualDevice( pNewVirDev );
            }
        }
        else
            bRet = FALSE;
    }

    return bRet;
}

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

BOOL VirtualDevice::SetOutputSizePixel( const Size& rNewSize, BOOL bErase )
{
    if( ImplSetOutputSizePixel(rNewSize, bErase) )
    {
        if( mnAlphaDepth != -1 )
        {
            // #110958# Setup alpha bitmap
            if(mpAlphaVDev && mpAlphaVDev->GetOutputSizePixel() != rNewSize)
            {
                delete mpAlphaVDev;
                mpAlphaVDev = 0L;
            }

            if( !mpAlphaVDev )
            {
                mpAlphaVDev = new VirtualDevice( *this, mnAlphaDepth );
                mpAlphaVDev->ImplSetOutputSizePixel(rNewSize, bErase);
            }

            // TODO: copy full outdev state to new one, here. Also needed in outdev2.cxx:DrawOutDev
            if( GetLineColor() != Color( COL_TRANSPARENT ) )
                mpAlphaVDev->SetLineColor( COL_BLACK );

            if( GetFillColor() != Color( COL_TRANSPARENT ) )
                mpAlphaVDev->SetFillColor( COL_BLACK );

            mpAlphaVDev->SetMapMode( GetMapMode() );
        }

        return TRUE;
    }

    return FALSE;
}

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

void VirtualDevice::SetReferenceDevice( RefDevMode eRefDevMode )
{
    switch( eRefDevMode )
    {
    case REFDEV_NONE:
    default:
        DBG_ASSERT( FALSE, "VDev::SetRefDev illegal argument!" );
        // fall through
    case REFDEV_MODE06:
        mnDPIX = mnDPIY = 600;
        break;
    case REFDEV_MODE48:
        mnDPIX = mnDPIY = 4800;
        break;
    case REFDEV_MODE96:
        mnDPIX = mnDPIY = 9600;
        break;
    }

    EnableOutput( FALSE );  // prevent output on reference device
    mbScreenComp = FALSE;

    // invalidate currently selected fonts
    mbInitFont = TRUE;
    mbNewFont = TRUE;

    // avoid adjusting font lists when already in refdev mode
    BYTE nOldRefDevMode = meRefDevMode;
    meRefDevMode = (BYTE)eRefDevMode;
    if( nOldRefDevMode != REFDEV_NONE )
        return;

    // the reference device should have only scalable fonts
    // => clean up the original font lists before getting new ones
    if ( mpFontEntry )
    {
        mpFontCache->Release( mpFontEntry );
        mpFontEntry = NULL;
    }
    if ( mpGetDevFontList )
    {
        delete mpGetDevFontList;
        mpGetDevFontList = NULL;
    }
    if ( mpGetDevSizeList )
    {
        delete mpGetDevSizeList;
        mpGetDevSizeList = NULL;
    }

    // preserve global font lists
    ImplSVData* pSVData = ImplGetSVData();
    if( mpFontList && (mpFontList != pSVData->maGDIData.mpScreenFontList) )
        delete mpFontList;
    if( mpFontCache && (mpFontCache != pSVData->maGDIData.mpScreenFontCache) )
        delete mpFontCache;

    // get font list with scalable fonts only
    ImplGetGraphics();
    ImplDevFontList* pScalableDevFonts = new ImplDevFontList();
    ImplDevFontListData* pData = pSVData->maGDIData.mpScreenFontList->First();
    for(; pData; pData = pSVData->maGDIData.mpScreenFontList->Next() )
    {
        ImplFontData* pEntry = pData->mpFirst;
        for(; pEntry; pEntry = pEntry->mpNext )
        {
            if( (pEntry->meType != TYPE_VECTOR)
            && (pEntry->meType != TYPE_SCALABLE) )
                continue;
            ImplFontData* pNewData = new ImplFontData();
            *pNewData = *pEntry;
            pScalableDevFonts->Add( pNewData );
        }
    }

    // prepare to use new font lists
    mpFontList = pScalableDevFonts;
    mpFontCache = new ImplFontCache( FALSE );
}

// -----------------------------------------------------------------------
// eof
<commit_msg>INTEGRATION: CWS vclcleanup02 (1.13.4); FILE MERGED 2003/12/17 16:05:10 mt 1.13.4.1: #i23061# header cleanup, remove #ifdef ???_CXX and #define ???_CXX, also removed .impl files and fixed soke windows compiler warnings<commit_after>/*************************************************************************
 *
 *  $RCSfile: virdev.cxx,v $
 *
 *  $Revision: 1.14 $
 *
 *  last change: $Author: vg $ $Date: 2004-01-06 13:57:02 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SV_SVSYS_HXX
#include <svsys.h>
#endif

#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SALGDI_HXX
#include <salgdi.hxx>
#endif
#ifndef _SV_SALFRAME_HXX
#include <salframe.hxx>
#endif
#ifndef _SV_SALVD_HXX
#include <salvd.hxx>
#endif

#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _SV_SETTINGS_HXX
#include <settings.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <svapp.hxx>
#endif
#ifndef _SV_WRKWIN_HXX
#include <wrkwin.hxx>
#endif
#ifndef _SV_OUTDEV_H
#include <outdev.h>
#endif
#ifndef _SV_VIRDEV_HXX
#include <virdev.hxx>
#endif

using namespace ::com::sun::star::uno;

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

void VirtualDevice::ImplInitVirDev( const OutputDevice* pOutDev,
                                    long nDX, long nDY, USHORT nBitCount )
{
    DBG_ASSERT( nBitCount <= 1,
                "VirtualDevice::VirtualDevice(): Only 0 or 1 is for BitCount allowed" );

    if ( nDX < 1 )
        nDX = 1;

    if ( nDY < 1 )
        nDY = 1;

    ImplSVData* pSVData = ImplGetSVData();

    if ( !pOutDev )
        pOutDev = ImplGetDefaultWindow();

    SalGraphics* pGraphics;
    if ( !pOutDev->mpGraphics )
        ((OutputDevice*)pOutDev)->ImplGetGraphics();
    pGraphics = pOutDev->mpGraphics;
    if ( pGraphics )
        mpVirDev = pSVData->mpDefInst->CreateVirtualDevice( pGraphics, nDX, nDY, nBitCount );
    else
        mpVirDev = NULL;
    if ( !mpVirDev )
        GetpApp()->Exception( EXC_SYSOBJNOTCREATED );

    mnBitCount      = ( nBitCount ? nBitCount : pOutDev->GetBitCount() );
    mnOutWidth      = nDX;
    mnOutHeight     = nDY;
    mbScreenComp    = TRUE;
    mbScreenComp    = FALSE;
    mnAlphaDepth    = -1;

    if( mnBitCount < 8 )
        SetAntialiasing( ANTIALIASING_DISABLE_TEXT );

    if ( pOutDev->GetOutDevType() == OUTDEV_PRINTER )
        mbScreenComp = FALSE;
    else if ( pOutDev->GetOutDevType() == OUTDEV_VIRDEV )
        mbScreenComp = ((VirtualDevice*)pOutDev)->mbScreenComp;

    meOutDevType    = OUTDEV_VIRDEV;
    mbDevOutput     = TRUE;
    mpFontList      = pSVData->maGDIData.mpScreenFontList;
    mpFontCache     = pSVData->maGDIData.mpScreenFontCache;
    mnDPIX          = pOutDev->mnDPIX;
    mnDPIY          = pOutDev->mnDPIY;
    maFont          = pOutDev->maFont;

    // Virtuelle Devices haben defaultmaessig einen weissen Hintergrund
    SetBackground( Wallpaper( Color( COL_WHITE ) ) );
    Erase();

    // VirDev in Liste eintragen
    mpNext = pSVData->maGDIData.mpFirstVirDev;
    mpPrev = NULL;
    if ( mpNext )
        mpNext->mpPrev = this;
    else
        pSVData->maGDIData.mpLastVirDev = this;
    pSVData->maGDIData.mpFirstVirDev = this;
}

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

VirtualDevice::VirtualDevice( USHORT nBitCount )
:   mpVirDev( NULL ),
    meRefDevMode( REFDEV_NONE )
{
    DBG_TRACE1( "VirtualDevice::VirtualDevice( %hu )", nBitCount );

    ImplInitVirDev( Application::GetDefaultDevice(), 1, 1, nBitCount );
}

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

VirtualDevice::VirtualDevice( const OutputDevice& rCompDev, USHORT nBitCount )
    : mpVirDev( NULL ),
    meRefDevMode( REFDEV_NONE )
{
    DBG_TRACE1( "VirtualDevice::VirtualDevice( %hu )", nBitCount );

    ImplInitVirDev( &rCompDev, 1, 1, nBitCount );
}

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

VirtualDevice::VirtualDevice( const OutputDevice& rCompDev, USHORT nBitCount, USHORT nAlphaBitCount )
    : mpVirDev( NULL )
{
    DBG_TRACE1( "VirtualDevice::VirtualDevice( %hu )", nBitCount );

    ImplInitVirDev( &rCompDev, 1, 1, nBitCount );

    // #110958# Enable alpha channel
    mnAlphaDepth = nAlphaBitCount;
}

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

VirtualDevice::~VirtualDevice()
{
    DBG_TRACE( "VirtualDevice::~VirtualDevice()" );

   ImplSVData* pSVData = ImplGetSVData();

    ImplReleaseGraphics();

    if ( mpVirDev )
        pSVData->mpDefInst->DestroyVirtualDevice( mpVirDev );

    // VirDev aus der Liste eintragen
    if( mpPrev )
        mpPrev->mpNext = mpNext;
    else
        pSVData->maGDIData.mpFirstVirDev = mpNext;

    if( mpNext )
        mpNext->mpPrev = mpPrev;
    else
        pSVData->maGDIData.mpLastVirDev = mpPrev;
}

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

BOOL VirtualDevice::ImplSetOutputSizePixel( const Size& rNewSize, BOOL bErase )
{
    DBG_TRACE3( "VirtualDevice::ImplSetOutputSizePixel( %ld, %ld, %d )", rNewSize.Width(), rNewSize.Height(), (int)bErase );

    if ( !mpVirDev )
        return FALSE;
    else if ( rNewSize == GetOutputSizePixel() )
    {
        if ( bErase )
            Erase();
        return TRUE;
    }

    BOOL bRet;
    long nNewWidth = rNewSize.Width(), nNewHeight = rNewSize.Height();

    if ( nNewWidth < 1 )
        nNewWidth = 1;

    if ( nNewHeight < 1 )
        nNewHeight = 1;

    if ( bErase )
    {
        bRet = mpVirDev->SetSize( nNewWidth, nNewHeight );

        if ( bRet )
        {
            mnOutWidth  = rNewSize.Width();
            mnOutHeight = rNewSize.Height();
            Erase();
        }
    }
    else
    {
        SalVirtualDevice*   pNewVirDev;
        ImplSVData*         pSVData = ImplGetSVData();

        // we need a graphics
        if ( !mpGraphics )
        {
            if ( !ImplGetGraphics() )
                return FALSE;
        }

        pNewVirDev = pSVData->mpDefInst->CreateVirtualDevice( mpGraphics, nNewWidth, nNewHeight, mnBitCount );
        if ( pNewVirDev )
        {
            SalGraphics* pGraphics = pNewVirDev->GetGraphics();
            if ( pGraphics )
            {
                SalTwoRect aPosAry;
                long nWidth;
                long nHeight;
                if ( mnOutWidth < nNewWidth )
                    nWidth = mnOutWidth;
                else
                    nWidth = nNewWidth;
                if ( mnOutHeight < nNewHeight )
                    nHeight = mnOutHeight;
                else
                    nHeight = nNewHeight;
                aPosAry.mnSrcX       = 0;
                aPosAry.mnSrcY       = 0;
                aPosAry.mnSrcWidth   = nWidth;
                aPosAry.mnSrcHeight  = nHeight;
                aPosAry.mnDestX      = 0;
                aPosAry.mnDestY      = 0;
                aPosAry.mnDestWidth  = nWidth;
                aPosAry.mnDestHeight = nHeight;

                pGraphics->CopyBits( &aPosAry, mpGraphics, this, this );
                pNewVirDev->ReleaseGraphics( pGraphics );
                ImplReleaseGraphics();
                pSVData->mpDefInst->DestroyVirtualDevice( mpVirDev );
                mpVirDev = pNewVirDev;
                mnOutWidth  = rNewSize.Width();
                mnOutHeight = rNewSize.Height();
                bRet = TRUE;
            }
            else
            {
                bRet = FALSE;
                pSVData->mpDefInst->DestroyVirtualDevice( pNewVirDev );
            }
        }
        else
            bRet = FALSE;
    }

    return bRet;
}

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

BOOL VirtualDevice::SetOutputSizePixel( const Size& rNewSize, BOOL bErase )
{
    if( ImplSetOutputSizePixel(rNewSize, bErase) )
    {
        if( mnAlphaDepth != -1 )
        {
            // #110958# Setup alpha bitmap
            if(mpAlphaVDev && mpAlphaVDev->GetOutputSizePixel() != rNewSize)
            {
                delete mpAlphaVDev;
                mpAlphaVDev = 0L;
            }

            if( !mpAlphaVDev )
            {
                mpAlphaVDev = new VirtualDevice( *this, mnAlphaDepth );
                mpAlphaVDev->ImplSetOutputSizePixel(rNewSize, bErase);
            }

            // TODO: copy full outdev state to new one, here. Also needed in outdev2.cxx:DrawOutDev
            if( GetLineColor() != Color( COL_TRANSPARENT ) )
                mpAlphaVDev->SetLineColor( COL_BLACK );

            if( GetFillColor() != Color( COL_TRANSPARENT ) )
                mpAlphaVDev->SetFillColor( COL_BLACK );

            mpAlphaVDev->SetMapMode( GetMapMode() );
        }

        return TRUE;
    }

    return FALSE;
}

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

void VirtualDevice::SetReferenceDevice( RefDevMode eRefDevMode )
{
    switch( eRefDevMode )
    {
    case REFDEV_NONE:
    default:
        DBG_ASSERT( FALSE, "VDev::SetRefDev illegal argument!" );
        // fall through
    case REFDEV_MODE06:
        mnDPIX = mnDPIY = 600;
        break;
    case REFDEV_MODE48:
        mnDPIX = mnDPIY = 4800;
        break;
    case REFDEV_MODE96:
        mnDPIX = mnDPIY = 9600;
        break;
    }

    EnableOutput( FALSE );  // prevent output on reference device
    mbScreenComp = FALSE;

    // invalidate currently selected fonts
    mbInitFont = TRUE;
    mbNewFont = TRUE;

    // avoid adjusting font lists when already in refdev mode
    BYTE nOldRefDevMode = meRefDevMode;
    meRefDevMode = (BYTE)eRefDevMode;
    if( nOldRefDevMode != REFDEV_NONE )
        return;

    // the reference device should have only scalable fonts
    // => clean up the original font lists before getting new ones
    if ( mpFontEntry )
    {
        mpFontCache->Release( mpFontEntry );
        mpFontEntry = NULL;
    }
    if ( mpGetDevFontList )
    {
        delete mpGetDevFontList;
        mpGetDevFontList = NULL;
    }
    if ( mpGetDevSizeList )
    {
        delete mpGetDevSizeList;
        mpGetDevSizeList = NULL;
    }

    // preserve global font lists
    ImplSVData* pSVData = ImplGetSVData();
    if( mpFontList && (mpFontList != pSVData->maGDIData.mpScreenFontList) )
        delete mpFontList;
    if( mpFontCache && (mpFontCache != pSVData->maGDIData.mpScreenFontCache) )
        delete mpFontCache;

    // get font list with scalable fonts only
    ImplGetGraphics();
    ImplDevFontList* pScalableDevFonts = new ImplDevFontList();
    ImplDevFontListData* pData = pSVData->maGDIData.mpScreenFontList->First();
    for(; pData; pData = pSVData->maGDIData.mpScreenFontList->Next() )
    {
        ImplFontData* pEntry = pData->mpFirst;
        for(; pEntry; pEntry = pEntry->mpNext )
        {
            if( (pEntry->meType != TYPE_VECTOR)
            && (pEntry->meType != TYPE_SCALABLE) )
                continue;
            ImplFontData* pNewData = new ImplFontData();
            *pNewData = *pEntry;
            pScalableDevFonts->Add( pNewData );
        }
    }

    // prepare to use new font lists
    mpFontList = pScalableDevFonts;
    mpFontCache = new ImplFontCache( FALSE );
}

// -----------------------------------------------------------------------
// eof
<|endoftext|>


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

String GetCommandLineToken( int, const String& );
// gets one token of a unix command line style string
// doublequote, singlequote and singleleftquote protect their respective
// contents

int GetCommandLineTokenCount( const String& );
// returns number of tokens (zero if empty or whitespace only)

String WhitespaceToSpace( const String&, BOOL bProtect = TRUE );

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.3.836); FILE MERGED 2005/09/05 14:45:32 rt 1.3.836.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: strhelper.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 12:48:58 $
 *
 *  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 _SV_STRHELPER_HXX
#define _SV_STRHELPER_HXX
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif

String GetCommandLineToken( int, const String& );
// gets one token of a unix command line style string
// doublequote, singlequote and singleleftquote protect their respective
// contents

int GetCommandLineTokenCount( const String& );
// returns number of tokens (zero if empty or whitespace only)

String WhitespaceToSpace( const String&, BOOL bProtect = TRUE );

#endif
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2017, Tier IV, Inc.
 *  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 Autoware 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.
*/

#include <iostream>
#include <thread>
#include <chrono>
#include <map>

#include <ros/ros.h>
#include <std_msgs/Bool.h>
#include <geometry_msgs/TwistStamped.h>

#include "autoware_msgs/RemoteCmd.h"
#include "autoware_msgs/TwistGate.h"
#include "tablet_socket_msgs/mode_cmd.h"
#include "tablet_socket_msgs/gear_cmd.h"
#include "autoware_msgs/accel_cmd.h"
#include "autoware_msgs/brake_cmd.h"
#include "autoware_msgs/steer_cmd.h"
#include "autoware_msgs/ControlCommandStamped.h"

class TwistGate
{
  using remote_msgs_t = autoware_msgs::RemoteCmd;
  using twist_gate_msgs_t = autoware_msgs::TwistGate;

  public:
    TwistGate(const ros::NodeHandle& nh, const ros::NodeHandle& private_nh);
    ~TwistGate();
  private:
    void watchdog_timer();
    void remote_cmd_callback(const remote_msgs_t::ConstPtr& input_msg);
    void auto_cmd_twist_cmd_callback(const geometry_msgs::TwistStamped::ConstPtr& input_msg);
    void auto_cmd_mode_cmd_callback(const tablet_socket_msgs::mode_cmd::ConstPtr& input_msg);
    void auto_cmd_gear_cmd_callback(const tablet_socket_msgs::gear_cmd::ConstPtr& input_msg);
    void auto_cmd_accel_cmd_callback(const autoware_msgs::accel_cmd::ConstPtr& input_msg);
    void auto_cmd_steer_cmd_callback(const autoware_msgs::steer_cmd::ConstPtr& input_msg);
    void auto_cmd_brake_cmd_callback(const autoware_msgs::brake_cmd::ConstPtr& input_msg);
    void auto_cmd_ctrl_cmd_callback(const autoware_msgs::ControlCommandStamped::ConstPtr& input_msg);

    void reset_select_cmd_msg();

    ros::NodeHandle nh_;
    ros::NodeHandle private_nh_;
    ros::Publisher emergency_stop_pub_;
    ros::Publisher select_cmd_pub_;
    ros::Subscriber remote_cmd_sub_;
    std::map<std::string , ros::Subscriber> auto_cmd_sub_stdmap_;

    twist_gate_msgs_t twist_gate_msg_;
    std_msgs::Bool emergency_stop_msg_;
    ros::Time remote_cmd_time_;
    ros::Duration timeout_period_;

    std::thread watchdog_timer_thread_;
    enum class CommandMode{AUTO=1, REMOTE=2} command_mode_;
};

TwistGate::TwistGate(const ros::NodeHandle& nh, const ros::NodeHandle& private_nh) :
     nh_(nh)
    ,private_nh_(private_nh)
    ,timeout_period_(1.0)
    ,command_mode_(CommandMode::REMOTE)
{
  emergency_stop_pub_ = nh_.advertise<std_msgs::Bool>("/emergency_stop", 1, true);
  select_cmd_pub_ = nh_.advertise<twist_gate_msgs_t>("/select_cmd", 1, true);

  remote_cmd_sub_ = nh_.subscribe("/remote_cmd", 1, &TwistGate::remote_cmd_callback, this);

  auto_cmd_sub_stdmap_["twist_cmd"] = nh_.subscribe("/twist_cmd", 1, &TwistGate::auto_cmd_twist_cmd_callback, this);
  auto_cmd_sub_stdmap_["mode_cmd"] = nh_.subscribe("/mode_cmd", 1, &TwistGate::auto_cmd_mode_cmd_callback, this);
  auto_cmd_sub_stdmap_["gear_cmd"] = nh_.subscribe("/gear_cmd", 1, &TwistGate::auto_cmd_gear_cmd_callback, this);
  auto_cmd_sub_stdmap_["accel_cmd"] = nh_.subscribe("/accel_cmd", 1, &TwistGate::auto_cmd_accel_cmd_callback, this);
  auto_cmd_sub_stdmap_["steer_cmd"] = nh_.subscribe("/steer_cmd", 1, &TwistGate::auto_cmd_steer_cmd_callback, this);
  auto_cmd_sub_stdmap_["brake_cmd"] = nh_.subscribe("/brake_cmd", 1, &TwistGate::auto_cmd_brake_cmd_callback, this);
  auto_cmd_sub_stdmap_["ctrl_cmd"] = nh_.subscribe("/ctrl_cmd", 1, &TwistGate::auto_cmd_ctrl_cmd_callback, this);

  twist_gate_msg_.header.seq = 0;

  emergency_stop_msg_.data = false;

  remote_cmd_time_ = ros::Time::now();
  watchdog_timer_thread_ = std::thread(&TwistGate::watchdog_timer, this);
  watchdog_timer_thread_.detach();
}

TwistGate::~TwistGate()
{
}

void TwistGate::reset_select_cmd_msg()
{
  twist_gate_msg_.linear_x        = 0;
  twist_gate_msg_.angular_z       = 0;
  twist_gate_msg_.mode            = 0;
  twist_gate_msg_.gear            = 0;
  twist_gate_msg_.blinker         = 0;
  twist_gate_msg_.accel           = 0;
  twist_gate_msg_.brake           = 0;
  twist_gate_msg_.steer           = 0;
  twist_gate_msg_.linear_velocity = -1;
  twist_gate_msg_.steering_angle  = 0;
}

void TwistGate::watchdog_timer()
{
  while(1)
  {
    ros::Time now_time = ros::Time::now();
    bool emergency_flag = false;

    // if lost Communication
    if(command_mode_ == CommandMode::REMOTE && now_time - remote_cmd_time_ >  timeout_period_) {
      emergency_flag = true;
      std::cout << "Lost Communication!" << std::endl;
    }

    if(emergency_stop_msg_.data == true)
    {
      emergency_flag = true;
      std::cout << "Emergency Mode!" << std::endl;
    }

    if(emergency_flag) {
      command_mode_ = CommandMode::AUTO;
      emergency_stop_msg_.data = true;
      emergency_stop_pub_.publish(emergency_stop_msg_);
      std::cout << "Emergency Stop!" << std::endl;
    }

    std::this_thread::sleep_for(std::chrono::milliseconds(10));
    std::cout << "c_mode:"     << static_cast<int>(command_mode_)
              << " e_stop:"    << static_cast<bool>(emergency_stop_msg_.data)
              << " diff_time:" << (now_time - remote_cmd_time_).toSec()
              << std::endl;
  }
}

void TwistGate::remote_cmd_callback(const remote_msgs_t::ConstPtr& input_msg)
{
  command_mode_ = static_cast<CommandMode>(input_msg->control_mode);
  emergency_stop_msg_.data = static_cast<bool>(input_msg->emergency);
  remote_cmd_time_ = ros::Time::now();

  if(command_mode_ == CommandMode::REMOTE)
  {
    twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
    twist_gate_msg_.header.stamp = input_msg->header.stamp;
    twist_gate_msg_.header.seq++;
    twist_gate_msg_.linear_x = input_msg->accel;
    twist_gate_msg_.angular_z = input_msg->steer;
    twist_gate_msg_.steering_angle = input_msg->steer;
    twist_gate_msg_.accel = input_msg->accel;
    twist_gate_msg_.brake = input_msg->brake;
    twist_gate_msg_.steer = input_msg->steer;
    twist_gate_msg_.gear = input_msg->gear;
    twist_gate_msg_.blinker = input_msg->blinker;
    twist_gate_msg_.mode = input_msg->mode;
    twist_gate_msg_.emergency = input_msg->emergency;
    select_cmd_pub_.publish(twist_gate_msg_);
  }
}

void TwistGate::auto_cmd_twist_cmd_callback(const geometry_msgs::TwistStamped::ConstPtr& input_msg)
{
  if(command_mode_ == CommandMode::AUTO)
  {
    twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
    twist_gate_msg_.header.stamp = input_msg->header.stamp;
    twist_gate_msg_.header.seq++;
    twist_gate_msg_.linear_x = input_msg->twist.linear.x;
    twist_gate_msg_.angular_z = input_msg->twist.angular.z;
    select_cmd_pub_.publish(twist_gate_msg_);
  }
}

void TwistGate::auto_cmd_mode_cmd_callback(const tablet_socket_msgs::mode_cmd::ConstPtr& input_msg)
{
  if(command_mode_ == CommandMode::AUTO)
  {
    //TODO:check this if statement
    if(input_msg->mode == -1 || input_msg->mode == 0){
      reset_select_cmd_msg();
    }
    twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
    twist_gate_msg_.header.stamp = input_msg->header.stamp;
    twist_gate_msg_.header.seq++;
    twist_gate_msg_.mode = input_msg->mode;
    select_cmd_pub_.publish(twist_gate_msg_);
  }
}

void TwistGate::auto_cmd_gear_cmd_callback(const tablet_socket_msgs::gear_cmd::ConstPtr& input_msg)
{
  if(command_mode_ == CommandMode::AUTO)
  {
    twist_gate_msg_.gear = input_msg->gear;
    select_cmd_pub_.publish(twist_gate_msg_);
  }
}

void TwistGate::auto_cmd_accel_cmd_callback(const autoware_msgs::accel_cmd::ConstPtr& input_msg)
{
  if(command_mode_ == CommandMode::AUTO)
  {
    twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
    twist_gate_msg_.header.stamp = input_msg->header.stamp;
    twist_gate_msg_.header.seq++;
    twist_gate_msg_.accel = input_msg->accel;
    select_cmd_pub_.publish(twist_gate_msg_);
  }
}

void TwistGate::auto_cmd_steer_cmd_callback(const autoware_msgs::steer_cmd::ConstPtr& input_msg)
{
  if(command_mode_ == CommandMode::AUTO)
  {
    twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
    twist_gate_msg_.header.stamp = input_msg->header.stamp;
    twist_gate_msg_.header.seq++;
    twist_gate_msg_.steer = input_msg->steer;
    select_cmd_pub_.publish(twist_gate_msg_);
  }
}

void TwistGate::auto_cmd_brake_cmd_callback(const autoware_msgs::brake_cmd::ConstPtr& input_msg)
{
  if(command_mode_ == CommandMode::AUTO)
  {
    twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
    twist_gate_msg_.header.stamp = input_msg->header.stamp;
    twist_gate_msg_.header.seq++;
    twist_gate_msg_.brake = input_msg->brake;
    select_cmd_pub_.publish(twist_gate_msg_);
  }
}

void TwistGate::auto_cmd_ctrl_cmd_callback(const autoware_msgs::ControlCommandStamped::ConstPtr& input_msg)
{
  if(command_mode_ == CommandMode::AUTO)
  {
    twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
    twist_gate_msg_.header.stamp = input_msg->header.stamp;
    twist_gate_msg_.header.seq++;
    twist_gate_msg_.linear_velocity = input_msg->cmd.linear_velocity;
    twist_gate_msg_.steering_angle = input_msg->cmd.steering_angle;
    select_cmd_pub_.publish(twist_gate_msg_);
  }
}

int main(int argc, char** argv)
{
  ros::init(argc, argv, "twist_gate");
  ros::NodeHandle nh;
  ros::NodeHandle private_nh("~");

  TwistGate twist_gate(nh, private_nh);

  ros::spin();
  return 0;
}
<commit_msg>refactor code and add ctrl mode topic<commit_after>/*
 *  Copyright (c) 2017, Tier IV, Inc.
 *  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 Autoware 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.
*/

#include <iostream>
#include <thread>
#include <chrono>
#include <map>

#include <ros/ros.h>
#include <std_msgs/Bool.h>
#include <std_msgs/String.h>
#include <geometry_msgs/TwistStamped.h>

#include "autoware_msgs/RemoteCmd.h"
#include "autoware_msgs/TwistGate.h"
#include "tablet_socket_msgs/mode_cmd.h"
#include "tablet_socket_msgs/gear_cmd.h"
#include "autoware_msgs/accel_cmd.h"
#include "autoware_msgs/brake_cmd.h"
#include "autoware_msgs/steer_cmd.h"
#include "autoware_msgs/ControlCommandStamped.h"

class TwistGate
{
  using remote_msgs_t = autoware_msgs::RemoteCmd;
  using twist_gate_msgs_t = autoware_msgs::TwistGate;

  public:
    TwistGate(const ros::NodeHandle& nh, const ros::NodeHandle& private_nh);
    ~TwistGate();
  private:
    void watchdog_timer();
    void remote_cmd_callback(const remote_msgs_t::ConstPtr& input_msg);
    void auto_cmd_twist_cmd_callback(const geometry_msgs::TwistStamped::ConstPtr& input_msg);
    void auto_cmd_mode_cmd_callback(const tablet_socket_msgs::mode_cmd::ConstPtr& input_msg);
    void auto_cmd_gear_cmd_callback(const tablet_socket_msgs::gear_cmd::ConstPtr& input_msg);
    void auto_cmd_accel_cmd_callback(const autoware_msgs::accel_cmd::ConstPtr& input_msg);
    void auto_cmd_steer_cmd_callback(const autoware_msgs::steer_cmd::ConstPtr& input_msg);
    void auto_cmd_brake_cmd_callback(const autoware_msgs::brake_cmd::ConstPtr& input_msg);
    void auto_cmd_ctrl_cmd_callback(const autoware_msgs::ControlCommandStamped::ConstPtr& input_msg);

    void reset_select_cmd_msg();

    ros::NodeHandle nh_;
    ros::NodeHandle private_nh_;
    ros::Publisher emergency_stop_pub_;
    ros::Publisher control_command_pub_;
    ros::Publisher select_cmd_pub_;
    ros::Subscriber remote_cmd_sub_;
    std::map<std::string , ros::Subscriber> auto_cmd_sub_stdmap_;

    twist_gate_msgs_t twist_gate_msg_;
    std_msgs::Bool emergency_stop_msg_;
    ros::Time remote_cmd_time_;
    ros::Duration timeout_period_;

    std::thread watchdog_timer_thread_;
    enum class CommandMode{AUTO=1, REMOTE=2} command_mode_, previous_command_mode_;
    std_msgs::String command_mode_topic_;
};

TwistGate::TwistGate(const ros::NodeHandle& nh, const ros::NodeHandle& private_nh) :
     nh_(nh)
    ,private_nh_(private_nh)
    ,timeout_period_(1.0)
    ,command_mode_(CommandMode::AUTO)
    ,previous_command_mode_(CommandMode::AUTO)
{
  emergency_stop_pub_ = nh_.advertise<std_msgs::Bool>("/emergency_stop", 1, true);
  control_command_pub_ = nh_.advertise<std_msgs::String>("/ctrl_mode", 1);
  select_cmd_pub_ = nh_.advertise<twist_gate_msgs_t>("/select_cmd", 1, true);

  remote_cmd_sub_ = nh_.subscribe("/remote_cmd", 1, &TwistGate::remote_cmd_callback, this);

  auto_cmd_sub_stdmap_["twist_cmd"] = nh_.subscribe("/twist_cmd", 1, &TwistGate::auto_cmd_twist_cmd_callback, this);
  auto_cmd_sub_stdmap_["mode_cmd"] = nh_.subscribe("/mode_cmd", 1, &TwistGate::auto_cmd_mode_cmd_callback, this);
  auto_cmd_sub_stdmap_["gear_cmd"] = nh_.subscribe("/gear_cmd", 1, &TwistGate::auto_cmd_gear_cmd_callback, this);
  auto_cmd_sub_stdmap_["accel_cmd"] = nh_.subscribe("/accel_cmd", 1, &TwistGate::auto_cmd_accel_cmd_callback, this);
  auto_cmd_sub_stdmap_["steer_cmd"] = nh_.subscribe("/steer_cmd", 1, &TwistGate::auto_cmd_steer_cmd_callback, this);
  auto_cmd_sub_stdmap_["brake_cmd"] = nh_.subscribe("/brake_cmd", 1, &TwistGate::auto_cmd_brake_cmd_callback, this);
  auto_cmd_sub_stdmap_["ctrl_cmd"] = nh_.subscribe("/ctrl_cmd", 1, &TwistGate::auto_cmd_ctrl_cmd_callback, this);

  twist_gate_msg_.header.seq = 0;

  emergency_stop_msg_.data = false;

  remote_cmd_time_ = ros::Time::now();
  watchdog_timer_thread_ = std::thread(&TwistGate::watchdog_timer, this);
  watchdog_timer_thread_.detach();
}

TwistGate::~TwistGate()
{
}

void TwistGate::reset_select_cmd_msg()
{
  twist_gate_msg_.linear_x        = 0;
  twist_gate_msg_.angular_z       = 0;
  twist_gate_msg_.mode            = 0;
  twist_gate_msg_.gear            = 0;
  twist_gate_msg_.blinker         = 0;
  twist_gate_msg_.accel           = 0;
  twist_gate_msg_.brake           = 0;
  twist_gate_msg_.steer           = 0;
  twist_gate_msg_.linear_velocity = -1;
  twist_gate_msg_.steering_angle  = 0;
}

void TwistGate::watchdog_timer()
{
  while(1)
  {
    ros::Time now_time = ros::Time::now();
    bool emergency_flag = false;

    // check command mode
    if(previous_command_mode_ != command_mode_) {
      if(command_mode_ == CommandMode::AUTO) {
        command_mode_topic_.data = "AUTO";
      }
      else if(command_mode_ == CommandMode::REMOTE) {
        command_mode_topic_.data = "REMOTE";
      }
      else{
        command_mode_topic_.data = "UNDEFINED";
      }

      control_command_pub_.publish(command_mode_topic_);
      previous_command_mode_ = command_mode_;
    }

    // if lost Communication
    if(command_mode_ == CommandMode::REMOTE && now_time - remote_cmd_time_ >  timeout_period_) {
      emergency_flag = true;
      std::cout << "Lost Communication!" << std::endl;
    }

    // if push emergency stop button
    if(emergency_stop_msg_.data == true)
    {
      emergency_flag = true;
      std::cout << "Emergency Mode!" << std::endl;
    }

    // Emergency
    if(emergency_flag) {
      command_mode_ = CommandMode::AUTO;
      emergency_stop_msg_.data = true;
      emergency_stop_pub_.publish(emergency_stop_msg_);
      std::cout << "Emergency Stop!" << std::endl;
    }

    std::this_thread::sleep_for(std::chrono::milliseconds(10));
  }
}

void TwistGate::remote_cmd_callback(const remote_msgs_t::ConstPtr& input_msg)
{
  command_mode_ = static_cast<CommandMode>(input_msg->control_mode);
  emergency_stop_msg_.data = static_cast<bool>(input_msg->emergency);
  remote_cmd_time_ = ros::Time::now();

  if(command_mode_ == CommandMode::REMOTE)
  {
    twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
    twist_gate_msg_.header.stamp = input_msg->header.stamp;
    twist_gate_msg_.header.seq++;
    twist_gate_msg_.linear_x = input_msg->accel;
    twist_gate_msg_.angular_z = input_msg->steer;
    twist_gate_msg_.steering_angle = input_msg->steer;
    twist_gate_msg_.accel = input_msg->accel;
    twist_gate_msg_.brake = input_msg->brake;
    twist_gate_msg_.steer = input_msg->steer;
    twist_gate_msg_.gear = input_msg->gear;
    twist_gate_msg_.blinker = input_msg->blinker;
    twist_gate_msg_.mode = input_msg->mode;
    twist_gate_msg_.emergency = input_msg->emergency;
    select_cmd_pub_.publish(twist_gate_msg_);
  }
}

void TwistGate::auto_cmd_twist_cmd_callback(const geometry_msgs::TwistStamped::ConstPtr& input_msg)
{
  if(command_mode_ == CommandMode::AUTO)
  {
    twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
    twist_gate_msg_.header.stamp = input_msg->header.stamp;
    twist_gate_msg_.header.seq++;
    twist_gate_msg_.linear_x = input_msg->twist.linear.x;
    twist_gate_msg_.angular_z = input_msg->twist.angular.z;
    select_cmd_pub_.publish(twist_gate_msg_);
  }
}

void TwistGate::auto_cmd_mode_cmd_callback(const tablet_socket_msgs::mode_cmd::ConstPtr& input_msg)
{
  if(command_mode_ == CommandMode::AUTO)
  {
    //TODO:check this if statement
    if(input_msg->mode == -1 || input_msg->mode == 0){
      reset_select_cmd_msg();
    }
    twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
    twist_gate_msg_.header.stamp = input_msg->header.stamp;
    twist_gate_msg_.header.seq++;
    twist_gate_msg_.mode = input_msg->mode;
    select_cmd_pub_.publish(twist_gate_msg_);
  }
}

void TwistGate::auto_cmd_gear_cmd_callback(const tablet_socket_msgs::gear_cmd::ConstPtr& input_msg)
{
  if(command_mode_ == CommandMode::AUTO)
  {
    twist_gate_msg_.gear = input_msg->gear;
    select_cmd_pub_.publish(twist_gate_msg_);
  }
}

void TwistGate::auto_cmd_accel_cmd_callback(const autoware_msgs::accel_cmd::ConstPtr& input_msg)
{
  if(command_mode_ == CommandMode::AUTO)
  {
    twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
    twist_gate_msg_.header.stamp = input_msg->header.stamp;
    twist_gate_msg_.header.seq++;
    twist_gate_msg_.accel = input_msg->accel;
    select_cmd_pub_.publish(twist_gate_msg_);
  }
}

void TwistGate::auto_cmd_steer_cmd_callback(const autoware_msgs::steer_cmd::ConstPtr& input_msg)
{
  if(command_mode_ == CommandMode::AUTO)
  {
    twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
    twist_gate_msg_.header.stamp = input_msg->header.stamp;
    twist_gate_msg_.header.seq++;
    twist_gate_msg_.steer = input_msg->steer;
    select_cmd_pub_.publish(twist_gate_msg_);
  }
}

void TwistGate::auto_cmd_brake_cmd_callback(const autoware_msgs::brake_cmd::ConstPtr& input_msg)
{
  if(command_mode_ == CommandMode::AUTO)
  {
    twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
    twist_gate_msg_.header.stamp = input_msg->header.stamp;
    twist_gate_msg_.header.seq++;
    twist_gate_msg_.brake = input_msg->brake;
    select_cmd_pub_.publish(twist_gate_msg_);
  }
}

void TwistGate::auto_cmd_ctrl_cmd_callback(const autoware_msgs::ControlCommandStamped::ConstPtr& input_msg)
{
  if(command_mode_ == CommandMode::AUTO)
  {
    twist_gate_msg_.header.frame_id = input_msg->header.frame_id;
    twist_gate_msg_.header.stamp = input_msg->header.stamp;
    twist_gate_msg_.header.seq++;
    twist_gate_msg_.linear_velocity = input_msg->cmd.linear_velocity;
    twist_gate_msg_.steering_angle = input_msg->cmd.steering_angle;
    select_cmd_pub_.publish(twist_gate_msg_);
  }
}

int main(int argc, char** argv)
{
  ros::init(argc, argv, "twist_gate");
  ros::NodeHandle nh;
  ros::NodeHandle private_nh("~");

  TwistGate twist_gate(nh, private_nh);

  ros::spin();
  return 0;
}
<|endoftext|>


<commit_before>#include "../Flare.h"
#include "FlareSpacecraftInterface.h"
#include "FlareSpacecraftComponent.h"
#include "../Game/FlareGame.h"

/*----------------------------------------------------
	Constructor
----------------------------------------------------*/

UFlareSpacecraftInterface::UFlareSpacecraftInterface(const class FObjectInitializer& PCIP)
	: Super(PCIP)
{
}

/*----------------------------------------------------
	Content
----------------------------------------------------*/

const FSlateBrush* IFlareSpacecraftInterface::GetIcon(FFlareSpacecraftDescription* Characteristic)
{
	if (Characteristic)
	{
		if (IFlareSpacecraftInterface::IsStation(Characteristic))
		{
			return FFlareStyleSet::GetIcon("SS");
		}
		else if (IFlareSpacecraftInterface::IsMilitary(Characteristic))
		{
			if (Characteristic->Size == EFlarePartSize::S)
			{
				return FFlareStyleSet::GetIcon("MS");
			}
			else if (Characteristic->Size == EFlarePartSize::M)
			{
				return FFlareStyleSet::GetIcon("MM");
			}
			else if (Characteristic->Size == EFlarePartSize::L)
			{
				return FFlareStyleSet::GetIcon("ML");
			}
		}
		else
		{
			if (Characteristic->Size == EFlarePartSize::S)
			{
				return FFlareStyleSet::GetIcon("CS");
			}
			else if (Characteristic->Size == EFlarePartSize::M)
			{
				return FFlareStyleSet::GetIcon("CM");
			}
			else if (Characteristic->Size == EFlarePartSize::L)
			{
				return FFlareStyleSet::GetIcon("CL");
			}
		}
	}
	return NULL;
}

bool IFlareSpacecraftInterface::IsStation(FFlareSpacecraftDescription* SpacecraftDesc)
{
	return SpacecraftDesc->OrbitalEngineCount == 0;
}

bool IFlareSpacecraftInterface::IsMilitary(FFlareSpacecraftDescription* SpacecraftDesc)
{
	return SpacecraftDesc->GunSlots.Num() > 0 || SpacecraftDesc->TurretSlots.Num() > 0;
}

EFlareResourcePriceContext::Type IFlareSpacecraftInterface::GetResourceUseType(FFlareResourceDescription* Resource)
{
	// Check we're and station
	if (!IsStation())
	{
		return EFlareResourcePriceContext::Default;
	}
	FFlareSpacecraftDescription* SpacecraftDescription = GetDescription();

	// Parse factories
	for (int FactoryIndex = 0; FactoryIndex < SpacecraftDescription->Factories.Num(); FactoryIndex++)
	{
		FFlareFactoryDescription* FactoryDescription = &SpacecraftDescription->Factories[FactoryIndex]->Data;

		// Is input resource of a station ?
		for (int32 ResourceIndex = 0; ResourceIndex < FactoryDescription->CycleCost.InputResources.Num(); ResourceIndex++)
		{
			const FFlareFactoryResource* FactoryResource = &FactoryDescription->CycleCost.InputResources[ResourceIndex];
			if (&FactoryResource->Resource->Data == Resource)
			{
				return EFlareResourcePriceContext::FactoryInput;
			}
		}

		// Is output resource of a station ?
		for (int32 ResourceIndex = 0; ResourceIndex < FactoryDescription->CycleCost.OutputResources.Num(); ResourceIndex++)
		{
			const FFlareFactoryResource* FactoryResource = &FactoryDescription->CycleCost.OutputResources[ResourceIndex];
			if (&FactoryResource->Resource->Data == Resource)
			{
				return EFlareResourcePriceContext::FactoryOutput;
			}
		}
	}

	// Customer resource ?
	if (SpacecraftDescription->Capabilities.Contains(EFlareSpacecraftCapability::Consumer) && GetGame()->GetResourceCatalog()->IsCustomerResource(Resource))
	{
		return EFlareResourcePriceContext::ConsumerConsumption;
	}

	// Maintenance resource ?
	if (SpacecraftDescription->Capabilities.Contains(EFlareSpacecraftCapability::Maintenance) && GetGame()->GetResourceCatalog()->IsMaintenanceResource(Resource))
	{
		return EFlareResourcePriceContext::MaintenanceConsumption;
	}

	return EFlareResourcePriceContext::Default;
}

void IFlareSpacecraftInterface::LockResources()
{
	GetCargoBay()->UnlockAll();

	if (GetDescription()->Factories.Num() > 0)
	{
		FFlareFactoryDescription* Factory = &GetDescription()->Factories[0]->Data;

		for (int32 ResourceIndex = 0 ; ResourceIndex < Factory->CycleCost.InputResources.Num() ; ResourceIndex++)
		{
			const FFlareFactoryResource* Resource = &Factory->CycleCost.InputResources[ResourceIndex];

			if (!GetCargoBay()->LockSlot(&Resource->Resource->Data))
			{
				FLOGV("Fail to lock a slot of %s in %s", *(&Resource->Resource->Data)->Name.ToString(), *GetImmatriculation().ToString());
			}
		}

		for (int32 ResourceIndex = 0 ; ResourceIndex < Factory->CycleCost.OutputResources.Num() ; ResourceIndex++)
		{
			const FFlareFactoryResource* Resource = &Factory->CycleCost.OutputResources[ResourceIndex];

			if (!GetCargoBay()->LockSlot(&Resource->Resource->Data))
			{
				FLOGV("Fail to lock a slot of %s in %s", *(&Resource->Resource->Data)->Name.ToString(), *GetImmatriculation().ToString());
			}
		}
	}

	if (HasCapability(EFlareSpacecraftCapability::Consumer))
	{
		for (int32 ResourceIndex = 0; ResourceIndex < GetGame()->GetResourceCatalog()->ConsumerResources.Num(); ResourceIndex++)
		{
			FFlareResourceDescription* Resource = &GetGame()->GetResourceCatalog()->ConsumerResources[ResourceIndex]->Data;
			if (!GetCargoBay()->LockSlot(Resource))
			{
				FLOGV("Fail to lock a slot of %s in %s", *Resource->Name.ToString(), *GetImmatriculation().ToString());
			}
		}
	}

	if (HasCapability(EFlareSpacecraftCapability::Maintenance))
	{
		for (int32 ResourceIndex = 0; ResourceIndex < GetGame()->GetResourceCatalog()->MaintenanceResources.Num(); ResourceIndex++)
		{
			FFlareResourceDescription* Resource = &GetGame()->GetResourceCatalog()->MaintenanceResources[ResourceIndex]->Data;

			if (!GetCargoBay()->LockSlot(Resource))
			{
				FLOGV("Fail to lock a slot of %s in %s", *Resource->Name.ToString(), *GetImmatriculation().ToString());
			}
		}
	}
}
<commit_msg>Fixed build<commit_after>#include "../Flare.h"
#include "FlareSpacecraftInterface.h"
#include "FlareSpacecraftComponent.h"
#include "../Game/FlareGame.h"
#include "../Economy/FlareCargoBay.h"

/*----------------------------------------------------
	Constructor
----------------------------------------------------*/

UFlareSpacecraftInterface::UFlareSpacecraftInterface(const class FObjectInitializer& PCIP)
	: Super(PCIP)
{
}

/*----------------------------------------------------
	Content
----------------------------------------------------*/

const FSlateBrush* IFlareSpacecraftInterface::GetIcon(FFlareSpacecraftDescription* Characteristic)
{
	if (Characteristic)
	{
		if (IFlareSpacecraftInterface::IsStation(Characteristic))
		{
			return FFlareStyleSet::GetIcon("SS");
		}
		else if (IFlareSpacecraftInterface::IsMilitary(Characteristic))
		{
			if (Characteristic->Size == EFlarePartSize::S)
			{
				return FFlareStyleSet::GetIcon("MS");
			}
			else if (Characteristic->Size == EFlarePartSize::M)
			{
				return FFlareStyleSet::GetIcon("MM");
			}
			else if (Characteristic->Size == EFlarePartSize::L)
			{
				return FFlareStyleSet::GetIcon("ML");
			}
		}
		else
		{
			if (Characteristic->Size == EFlarePartSize::S)
			{
				return FFlareStyleSet::GetIcon("CS");
			}
			else if (Characteristic->Size == EFlarePartSize::M)
			{
				return FFlareStyleSet::GetIcon("CM");
			}
			else if (Characteristic->Size == EFlarePartSize::L)
			{
				return FFlareStyleSet::GetIcon("CL");
			}
		}
	}
	return NULL;
}

bool IFlareSpacecraftInterface::IsStation(FFlareSpacecraftDescription* SpacecraftDesc)
{
	return SpacecraftDesc->OrbitalEngineCount == 0;
}

bool IFlareSpacecraftInterface::IsMilitary(FFlareSpacecraftDescription* SpacecraftDesc)
{
	return SpacecraftDesc->GunSlots.Num() > 0 || SpacecraftDesc->TurretSlots.Num() > 0;
}

EFlareResourcePriceContext::Type IFlareSpacecraftInterface::GetResourceUseType(FFlareResourceDescription* Resource)
{
	// Check we're and station
	if (!IsStation())
	{
		return EFlareResourcePriceContext::Default;
	}
	FFlareSpacecraftDescription* SpacecraftDescription = GetDescription();

	// Parse factories
	for (int FactoryIndex = 0; FactoryIndex < SpacecraftDescription->Factories.Num(); FactoryIndex++)
	{
		FFlareFactoryDescription* FactoryDescription = &SpacecraftDescription->Factories[FactoryIndex]->Data;

		// Is input resource of a station ?
		for (int32 ResourceIndex = 0; ResourceIndex < FactoryDescription->CycleCost.InputResources.Num(); ResourceIndex++)
		{
			const FFlareFactoryResource* FactoryResource = &FactoryDescription->CycleCost.InputResources[ResourceIndex];
			if (&FactoryResource->Resource->Data == Resource)
			{
				return EFlareResourcePriceContext::FactoryInput;
			}
		}

		// Is output resource of a station ?
		for (int32 ResourceIndex = 0; ResourceIndex < FactoryDescription->CycleCost.OutputResources.Num(); ResourceIndex++)
		{
			const FFlareFactoryResource* FactoryResource = &FactoryDescription->CycleCost.OutputResources[ResourceIndex];
			if (&FactoryResource->Resource->Data == Resource)
			{
				return EFlareResourcePriceContext::FactoryOutput;
			}
		}
	}

	// Customer resource ?
	if (SpacecraftDescription->Capabilities.Contains(EFlareSpacecraftCapability::Consumer) && GetGame()->GetResourceCatalog()->IsCustomerResource(Resource))
	{
		return EFlareResourcePriceContext::ConsumerConsumption;
	}

	// Maintenance resource ?
	if (SpacecraftDescription->Capabilities.Contains(EFlareSpacecraftCapability::Maintenance) && GetGame()->GetResourceCatalog()->IsMaintenanceResource(Resource))
	{
		return EFlareResourcePriceContext::MaintenanceConsumption;
	}

	return EFlareResourcePriceContext::Default;
}

void IFlareSpacecraftInterface::LockResources()
{
	GetCargoBay()->UnlockAll();

	if (GetDescription()->Factories.Num() > 0)
	{
		FFlareFactoryDescription* Factory = &GetDescription()->Factories[0]->Data;

		for (int32 ResourceIndex = 0 ; ResourceIndex < Factory->CycleCost.InputResources.Num() ; ResourceIndex++)
		{
			const FFlareFactoryResource* Resource = &Factory->CycleCost.InputResources[ResourceIndex];

			if (!GetCargoBay()->LockSlot(&Resource->Resource->Data))
			{
				FLOGV("Fail to lock a slot of %s in %s", *(&Resource->Resource->Data)->Name.ToString(), *GetImmatriculation().ToString());
			}
		}

		for (int32 ResourceIndex = 0 ; ResourceIndex < Factory->CycleCost.OutputResources.Num() ; ResourceIndex++)
		{
			const FFlareFactoryResource* Resource = &Factory->CycleCost.OutputResources[ResourceIndex];

			if (!GetCargoBay()->LockSlot(&Resource->Resource->Data))
			{
				FLOGV("Fail to lock a slot of %s in %s", *(&Resource->Resource->Data)->Name.ToString(), *GetImmatriculation().ToString());
			}
		}
	}

	if (HasCapability(EFlareSpacecraftCapability::Consumer))
	{
		for (int32 ResourceIndex = 0; ResourceIndex < GetGame()->GetResourceCatalog()->ConsumerResources.Num(); ResourceIndex++)
		{
			FFlareResourceDescription* Resource = &GetGame()->GetResourceCatalog()->ConsumerResources[ResourceIndex]->Data;
			if (!GetCargoBay()->LockSlot(Resource))
			{
				FLOGV("Fail to lock a slot of %s in %s", *Resource->Name.ToString(), *GetImmatriculation().ToString());
			}
		}
	}

	if (HasCapability(EFlareSpacecraftCapability::Maintenance))
	{
		for (int32 ResourceIndex = 0; ResourceIndex < GetGame()->GetResourceCatalog()->MaintenanceResources.Num(); ResourceIndex++)
		{
			FFlareResourceDescription* Resource = &GetGame()->GetResourceCatalog()->MaintenanceResources[ResourceIndex]->Data;

			if (!GetCargoBay()->LockSlot(Resource))
			{
				FLOGV("Fail to lock a slot of %s in %s", *Resource->Name.ToString(), *GetImmatriculation().ToString());
			}
		}
	}
}
<|endoftext|>


<commit_before>/**
 * This file is part of TelepathyQt4
 *
 * @copyright Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
 * @copyright Copyright (C) 2009 Nokia Corporation
 * @license LGPL 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt4/FileTransferChannelCreationProperties>

#include <TelepathyQt4/Global>

#include "TelepathyQt4/debug-internal.h"

#include <QSharedData>
#include <QFileInfo>
#include <QUrl>

namespace Tp
{

struct TELEPATHY_QT4_NO_EXPORT FileTransferChannelCreationProperties::Private : public QSharedData
{
    Private(const QString &suggestedFileName, const QString &contentType,
            qulonglong size)
        : contentType(contentType),
          size(size),
          contentHashType(FileHashTypeNone)
    {
        QFileInfo fileInfo(suggestedFileName);
        this->suggestedFileName = fileInfo.fileName();
    }

    Private(const QString &path, const QString &contentType)
        : contentType(contentType),
          contentHashType(FileHashTypeNone)
    {
        QFileInfo fileInfo(path);

        if (fileInfo.exists()) {
            // Set mandatory parameters
            suggestedFileName = fileInfo.fileName();
            size = fileInfo.size();
            QUrl fileUri = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
            uri = fileUri.toString();

            // Set optional parameters
            lastModificationTime = fileInfo.lastModified();
        } else {
            warning() << path << "is not a local file.";
        }
    }

    /* mandatory parameters */
    QString suggestedFileName;
    QString contentType;
    qulonglong size;

    /* optional parameters */
    FileHashType contentHashType;
    QString contentHash;
    QString description;
    QDateTime lastModificationTime;
    QString uri;
};

/**
 * \class FileTransferChannelCreationProperties
 * \ingroup clientchannel
 * \headerfile TelepathyQt4/file-transfer-channel-creation-properties.h <TelepathyQt4/FileTransferChannelCreationProperties>
 *
 * \brief The FileTransferChannelCreationProperties class represents the
 * properties of a file transfer channel request.
 */

FileTransferChannelCreationProperties::FileTransferChannelCreationProperties()
{
}

FileTransferChannelCreationProperties::FileTransferChannelCreationProperties(
        const QString &suggestedFileName, const QString &contentType,
        qulonglong size)
    : mPriv(new Private(suggestedFileName, contentType, size))
{
}

FileTransferChannelCreationProperties::FileTransferChannelCreationProperties(
        const QString &path, const QString &contentType)
    : mPriv(new Private(path, contentType))
{
    if (mPriv->suggestedFileName.isEmpty()) {
        mPriv = QSharedDataPointer<Private>(NULL);
    }
}

FileTransferChannelCreationProperties::FileTransferChannelCreationProperties(
        const FileTransferChannelCreationProperties &other)
    : mPriv(other.mPriv)
{
}

FileTransferChannelCreationProperties::~FileTransferChannelCreationProperties()
{
}

FileTransferChannelCreationProperties &FileTransferChannelCreationProperties::operator=(
        const FileTransferChannelCreationProperties &other)
{
    this->mPriv = other.mPriv;
    return *this;
}

bool FileTransferChannelCreationProperties::operator==(
        const FileTransferChannelCreationProperties &other) const
{
    return mPriv == other.mPriv;
}

FileTransferChannelCreationProperties &FileTransferChannelCreationProperties::setContentHash(
        FileHashType contentHashType, const QString &contentHash)
{
    if (!isValid()) {
        // there is no point in updating content hash if not valid, as we miss filename, content
        // type and size
        return *this;
    }

    mPriv->contentHashType = contentHashType;
    mPriv->contentHash = contentHash;
    return *this;
}

FileTransferChannelCreationProperties &FileTransferChannelCreationProperties::setDescription(
        const QString &description)
{
    if (!isValid()) {
        // there is no point in updating description if not valid, as we miss filename, content
        // type and size
        return *this;
    }

    mPriv->description = description;
    return *this;
}

FileTransferChannelCreationProperties &FileTransferChannelCreationProperties::setLastModificationTime(
        const QDateTime &lastModificationTime)
{
    if (!isValid()) {
        // there is no point in updating last modification time if not valid, as we miss filename,
        // content type and size
        return *this;
    }

    mPriv->lastModificationTime = lastModificationTime;
    return *this;
}

FileTransferChannelCreationProperties &FileTransferChannelCreationProperties::setUri(
        const QString &uri)
{
    if (!isValid()) {
        // there is no point in updating uri if not valid, as we miss filename, content
        // type and size
        return *this;
    }

    mPriv->uri = uri;
    return *this;
}

QString FileTransferChannelCreationProperties::suggestedFileName() const
{
    if (!isValid()) {
        return QString();
    }

    return mPriv->suggestedFileName;
}

QString FileTransferChannelCreationProperties::contentType() const
{
    if (!isValid()) {
        return QString();
    }

    return mPriv->contentType;
}

qulonglong FileTransferChannelCreationProperties::size() const
{
    if (!isValid()) {
        return 0;
    }

    return mPriv->size;
}

bool FileTransferChannelCreationProperties::hasContentHash() const
{
    if (!isValid()) {
        return false;
    }

    return (mPriv->contentHashType != FileHashTypeNone);
}

FileHashType FileTransferChannelCreationProperties::contentHashType() const
{
    if (!isValid()) {
        return FileHashTypeNone;
    }

    return mPriv->contentHashType;
}

QString FileTransferChannelCreationProperties::contentHash() const
{
    if (!isValid()) {
        return QString();
    }

    return mPriv->contentHash;
}

bool FileTransferChannelCreationProperties::hasDescription() const
{
    if (!isValid()) {
        return false;
    }

    return (!mPriv->description.isEmpty());
}

QString FileTransferChannelCreationProperties::description() const
{
    if (!isValid()) {
        return QString();
    }

    return mPriv->description;
}

bool FileTransferChannelCreationProperties::hasLastModificationTime() const
{
    if (!isValid()) {
        return false;
    }

    return (mPriv->lastModificationTime.isValid());
}

QDateTime FileTransferChannelCreationProperties::lastModificationTime() const
{
    if (!isValid()) {
        return QDateTime();
    }

    return mPriv->lastModificationTime;
}

bool FileTransferChannelCreationProperties::hasUri() const
{
    if (!isValid()) {
        return false;
    }

    return (!mPriv->uri.isEmpty());
}

QString FileTransferChannelCreationProperties::uri() const
{
    if (!isValid()) {
        return QString();
    }

    return mPriv->uri;
}

} // Tp
<commit_msg>Add documentation for class FileTransferChannelCreationProperties<commit_after>/**
 * This file is part of TelepathyQt4
 *
 * @copyright Copyright (C) 2009 Collabora Ltd. <http://www.collabora.co.uk/>
 * @copyright Copyright (C) 2009 Nokia Corporation
 * @license LGPL 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <TelepathyQt4/FileTransferChannelCreationProperties>

#include <TelepathyQt4/Global>

#include "TelepathyQt4/debug-internal.h"

#include <QSharedData>
#include <QFileInfo>
#include <QUrl>

namespace Tp
{

struct TELEPATHY_QT4_NO_EXPORT FileTransferChannelCreationProperties::Private : public QSharedData
{
    Private(const QString &suggestedFileName, const QString &contentType,
            qulonglong size)
        : contentType(contentType),
          size(size),
          contentHashType(FileHashTypeNone)
    {
        QFileInfo fileInfo(suggestedFileName);
        this->suggestedFileName = fileInfo.fileName();
    }

    Private(const QString &path, const QString &contentType)
        : contentType(contentType),
          contentHashType(FileHashTypeNone)
    {
        QFileInfo fileInfo(path);

        if (fileInfo.exists()) {
            // Set mandatory parameters
            suggestedFileName = fileInfo.fileName();
            size = fileInfo.size();
            QUrl fileUri = QUrl::fromLocalFile(fileInfo.canonicalFilePath());
            uri = fileUri.toString();

            // Set optional parameters
            lastModificationTime = fileInfo.lastModified();
        } else {
            warning() << path << "is not a local file.";
        }
    }

    /* mandatory parameters */
    QString suggestedFileName;
    QString contentType;
    qulonglong size;

    /* optional parameters */
    FileHashType contentHashType;
    QString contentHash;
    QString description;
    QDateTime lastModificationTime;
    QString uri;
};

/**
 * \class FileTransferChannelCreationProperties
 * \ingroup clientchannel
 * \headerfile TelepathyQt4/file-transfer-channel-creation-properties.h <TelepathyQt4/FileTransferChannelCreationProperties>
 *
 * \brief The FileTransferChannelCreationProperties class represents the
 * properties of a file transfer channel request.
 */

/**
 * Create an invalid FileTransferChannelCreationProperties.
 */
FileTransferChannelCreationProperties::FileTransferChannelCreationProperties()
{
}

/**
 * Create a FileTransferChannelCreationProperties.
 *
 * If \a suggestedFileName or \a contentType are empty or if \a size is equal to
 * zero, the channel request will fail.
 * \a suggestedFileName will be cleaned of any path.
 *
 * \param suggestedFileName The name of the file on the sender's side. This is
 *                          therefore given as a suggested filename for the
 *                          receiver.
 * \param contentType The content type (MIME) of the file.
 * \param size The size of the content of the file.
 * \sa setUri()
 */
FileTransferChannelCreationProperties::FileTransferChannelCreationProperties(
        const QString &suggestedFileName, const QString &contentType,
        qulonglong size)
    : mPriv(new Private(suggestedFileName, contentType, size))
{
}

/**
 * Create a FileTransferChannelCreationProperties.
 *
 * This constructor accepts the path to a local file and sets the properties
 * that can be deducted from the file.
 * If \a path is not a local file the FileTransferChannelCreationProperties
 * will be invalid.
 *
 * \param path The path to the local file to be sent.
 */
FileTransferChannelCreationProperties::FileTransferChannelCreationProperties(
        const QString &path, const QString &contentType)
    : mPriv(new Private(path, contentType))
{
    if (mPriv->suggestedFileName.isEmpty()) {
        mPriv = QSharedDataPointer<Private>(NULL);
    }
}

/**
 * Copy constructor.
 */
FileTransferChannelCreationProperties::FileTransferChannelCreationProperties(
        const FileTransferChannelCreationProperties &other)
    : mPriv(other.mPriv)
{
}

/**
 * Class destructor.
 */
FileTransferChannelCreationProperties::~FileTransferChannelCreationProperties()
{
}

FileTransferChannelCreationProperties &FileTransferChannelCreationProperties::operator=(
        const FileTransferChannelCreationProperties &other)
{
    this->mPriv = other.mPriv;
    return *this;
}

bool FileTransferChannelCreationProperties::operator==(
        const FileTransferChannelCreationProperties &other) const
{
    return mPriv == other.mPriv;
}

/**
 * Set the content hash of the file and its type for the request.
 *
 * \param contentHashType The type of content hash.
 * \param contentHash The hash of the file, of type \a contentHashType.
 * \return This FileTransferChannelCreationProperties.
 * \sa hasContentHash(), contentHash(), contentHashType()
 */
FileTransferChannelCreationProperties &FileTransferChannelCreationProperties::setContentHash(
        FileHashType contentHashType, const QString &contentHash)
{
    if (!isValid()) {
        // there is no point in updating content hash if not valid, as we miss filename, content
        // type and size
        return *this;
    }

    mPriv->contentHashType = contentHashType;
    mPriv->contentHash = contentHash;
    return *this;
}

/**
 * Set a description of the file for the request.
 *
 * \param description The description of the file.
 * \return This FileTransferChannelCreationProperties.
 * \sa hasDescription(), description()
 */
FileTransferChannelCreationProperties &FileTransferChannelCreationProperties::setDescription(
        const QString &description)
{
    if (!isValid()) {
        // there is no point in updating description if not valid, as we miss filename, content
        // type and size
        return *this;
    }

    mPriv->description = description;
    return *this;
}

/**
 * Set the last modification time of the file for the request.
 *
 * \param lastModificationTime The last modification time of the file.
 * \return This FileTransferChannelCreationProperties.
 * \sa hasLastModificationTime(), lastModificationTime()
 */
FileTransferChannelCreationProperties &FileTransferChannelCreationProperties::setLastModificationTime(
        const QDateTime &lastModificationTime)
{
    if (!isValid()) {
        // there is no point in updating last modification time if not valid, as we miss filename,
        // content type and size
        return *this;
    }

    mPriv->lastModificationTime = lastModificationTime;
    return *this;
}

/**
 * Set the URI of the file for the request.
 *
 * \param uri The URI of the file.
 * \return This FileTransferChannelCreationProperties.
 * \sa uri()
 */
FileTransferChannelCreationProperties &FileTransferChannelCreationProperties::setUri(
        const QString &uri)
{
    if (!isValid()) {
        // there is no point in updating uri if not valid, as we miss filename, content
        // type and size
        return *this;
    }

    mPriv->uri = uri;
    return *this;
}

/**
 * Return the suggested file name for the request.
 * If the suggested file name is empty, the channel request will fail.
 *
 * \return The suggested file name for the request.
 */
QString FileTransferChannelCreationProperties::suggestedFileName() const
{
    if (!isValid()) {
        return QString();
    }

    return mPriv->suggestedFileName;
}

/**
 * Return the content type (MIME) of the file for the request.
 * If the content type is empty, the channel request will fail.
 *
 * \return The content type of the file.
 */
QString FileTransferChannelCreationProperties::contentType() const
{
    if (!isValid()) {
        return QString();
    }

    return mPriv->contentType;
}

/**
 * Return the size of the contents of the file for the request.
 * If size is zero, the channel request will fail.
 *
 * \return The size of the contents of file.
 */
qulonglong FileTransferChannelCreationProperties::size() const
{
    if (!isValid()) {
        return 0;
    }

    return mPriv->size;
}

/**
 * Return whether the request will have a content hash.
 *
 * \return \c true whether it will have a content hash, \c false otherwise.
 * \sa contentHash(), contentHashType(), setContentHash()
 */
bool FileTransferChannelCreationProperties::hasContentHash() const
{
    if (!isValid()) {
        return false;
    }

    return (mPriv->contentHashType != FileHashTypeNone);
}

/**
 * Return the type of the content hash for the request.
 *
 * \return The type of the content hash.
 * \sa hasContentHash(), contentHash(), setContentHash()
 */
FileHashType FileTransferChannelCreationProperties::contentHashType() const
{
    if (!isValid()) {
        return FileHashTypeNone;
    }

    return mPriv->contentHashType;
}

/**
 * Return the content hash of the file for the request.
 *
 * \return The hash of the contents of the file transfer, of type returned by
 *         contentHashType().
 * \sa hasContentHash(), contentHashType(), setContentHash()
 */
QString FileTransferChannelCreationProperties::contentHash() const
{
    if (!isValid()) {
        return QString();
    }

    return mPriv->contentHash;
}

/**
 * Return whether the request will have a descriprion.
 *
 * \return \c true whether it will have description, \c false otherwise.
 * \sa description(), setDescription()
 */
bool FileTransferChannelCreationProperties::hasDescription() const
{
    if (!isValid()) {
        return false;
    }

    return (!mPriv->description.isEmpty());
}

/**
 * Return the description of the file for the request.
 *
 * \return The description of the file.
 * \sa hasDescription(), setDescription()
 */
QString FileTransferChannelCreationProperties::description() const
{
    if (!isValid()) {
        return QString();
    }

    return mPriv->description;
}

/**
 * Return whether the request will have a last modification time.
 *
 * \return \c true whether it will have a last modification time, \c false
 *         otherwise.
 * \sa lastModificationTime(), setLastModificationTime()
 */
bool FileTransferChannelCreationProperties::hasLastModificationTime() const
{
    if (!isValid()) {
        return false;
    }

    return (mPriv->lastModificationTime.isValid());
}

/**
 * Return the last modification time of the file for the request.
 *
 * \return The last modification time of the file.
 * \sa hasLastModificationTime(), setLastModificationTime()
 */
QDateTime FileTransferChannelCreationProperties::lastModificationTime() const
{
    if (!isValid()) {
        return QDateTime();
    }

    return mPriv->lastModificationTime;
}

/**
 * Return whether the request will have an URI.
 *
 * \return \c true whether it will have URI, \c false otherwise.
 * \sa uri(), setUri()
 */
bool FileTransferChannelCreationProperties::hasUri() const
{
    if (!isValid()) {
        return false;
    }

    return (!mPriv->uri.isEmpty());
}

/**
 * Return the URI of the file for the request.
 * If the URI property is empty and the file transfer is handled by an handler
 * that is not this process, then it won't be able to initiate the file
 * transfer.
 *
 * \return The URI of the file.
 * \sa setUri()
 */
QString FileTransferChannelCreationProperties::uri() const
{
    if (!isValid()) {
        return QString();
    }

    return mPriv->uri;
}

} // Tp
<|endoftext|>