<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <vcl/graph.hxx>
#include <vcl/bmpacc.hxx>

class FilterConfigItem;

//============================ PBMReader ==================================

class PBMReader {

private:

    SvStream&           mrPBM;              // the PBM file to read

    bool            mbStatus;
    bool            mbRemark;           // sal_False if the stream is in a comment
    bool            mbRaw;              // RAW/ASCII MODE
    sal_uLong           mnMode;             // 0->PBM, 1->PGM, 2->PPM
    Bitmap              maBmp;
    BitmapWriteAccess*  mpAcc;
    sal_uLong           mnWidth, mnHeight;  // dimensions in pixel
    sal_uLong           mnCol;
    sal_uLong           mnMaxVal;           // max value in the <missing comment>
    bool            ImplCallback( sal_uInt16 nPercent );
    bool            ImplReadBody();
    bool            ImplReadHeader();

public:
                        PBMReader(SvStream & rPBM);
                        ~PBMReader();
    bool                ReadPBM(Graphic & rGraphic );
};

//=================== Methods of PBMReader ==============================

PBMReader::PBMReader(SvStream & rPBM)
    : mrPBM(rPBM)
    , mbStatus(true)
    , mbRemark(false)
    , mbRaw(true)
    , mnMode(0)
    , mpAcc(NULL)
    , mnWidth(0)
    , mnHeight(0)
    , mnCol(0)
    , mnMaxVal(0)
{
}

PBMReader::~PBMReader()
{
}

bool PBMReader::ImplCallback( sal_uInt16 /*nPercent*/ )
{
/*
    if ( pCallback != NULL )
    {
        if ( ( (*pCallback)( pCallerData, nPercent ) ) == sal_True )
        {
            mrPBM.SetError( SVSTREAM_FILEFORMAT_ERROR );
            return sal_True;
        }
    }
*/
    return false;
}

bool PBMReader::ReadPBM(Graphic & rGraphic )
{
    sal_uInt16 i;

    if ( mrPBM.GetError() )
        return false;

    mrPBM.SetNumberFormatInt( NUMBERFORMAT_INT_LITTLEENDIAN );

    // read header:

    if ( ( mbStatus = ImplReadHeader() ) == false )
        return false;

    if ( ( mnMaxVal == 0 ) || ( mnWidth == 0 ) || ( mnHeight == 0 ) )
        return false;

    // 0->PBM, 1->PGM, 2->PPM
    switch ( mnMode )
    {
        case 0 :
            maBmp = Bitmap( Size( mnWidth, mnHeight ), 1 );
            if ( ( mpAcc = maBmp.AcquireWriteAccess() ) == 0 )
                return false;
            mpAcc->SetPaletteEntryCount( 2 );
            mpAcc->SetPaletteColor( 0, BitmapColor( 0xff, 0xff, 0xff ) );
            mpAcc->SetPaletteColor( 1, BitmapColor( 0x00, 0x00, 0x00 ) );
            break;

        case 1 :
            if ( mnMaxVal <= 1 )
                maBmp = Bitmap( Size( mnWidth, mnHeight ), 1);
            else if ( mnMaxVal <= 15 )
                maBmp = Bitmap( Size( mnWidth, mnHeight ), 4);
            else
                maBmp = Bitmap( Size( mnWidth, mnHeight ), 8);

            if ( ( mpAcc = maBmp.AcquireWriteAccess() ) == 0 )
                return false;
            mnCol = (sal_uInt16)mnMaxVal + 1;
            if ( mnCol > 256 )
                mnCol = 256;

            mpAcc->SetPaletteEntryCount( 256 );
            for ( i = 0; i < mnCol; i++ )
            {
                sal_uLong nCount = 255 * i / mnCol;
                mpAcc->SetPaletteColor( i, BitmapColor( (sal_uInt8)nCount, (sal_uInt8)nCount, (sal_uInt8)nCount ) );
            }
            break;
        case 2 :
            maBmp = Bitmap( Size( mnWidth, mnHeight ), 24 );
            if ( ( mpAcc = maBmp.AcquireWriteAccess() ) == 0 )
                return false;
            break;
    }

    // read bitmap data
    mbStatus = ImplReadBody();

    if ( mpAcc )
    {
        maBmp.ReleaseAccess( mpAcc ), mpAcc = NULL;
    }
    if ( mbStatus )
        rGraphic = maBmp;

    return mbStatus;
}

bool PBMReader::ImplReadHeader()
{
    sal_uInt8   nID[ 2 ];
    sal_uInt8   nDat;
    sal_uInt8   nMax, nCount = 0;
    bool    bFinished = false;

    mrPBM.ReadUChar( nID[ 0 ] ).ReadUChar( nID[ 1 ] );
    if ( nID[ 0 ] != 'P' )
        return false;
    mnMaxVal = mnWidth = mnHeight = 0;
    switch ( nID[ 1 ] )
    {
        case '1' :
            mbRaw = false;
        case '4' :
            mnMode = 0;
            nMax = 2;               // number of parameters in Header
            mnMaxVal = 1;
            break;
        case '2' :
            mbRaw = false;
        case '5' :
            mnMode = 1;
            nMax = 3;
            break;
        case '3' :
            mbRaw = false;
        case '6' :
            mnMode = 2;
            nMax = 3;
            break;
        default:
            return false;
    }
    while ( bFinished == false )
    {
        if ( mrPBM.GetError() )
            return false;

        mrPBM.ReadUChar( nDat );

        if ( nDat == '#' )
        {
            mbRemark = true;
            continue;
        }
        else if ( ( nDat == 0x0d ) || ( nDat == 0x0a ) )
        {
            mbRemark = false;
            nDat = 0x20;
        }
        if ( mbRemark )
            continue;

        if ( ( nDat == 0x20 ) || ( nDat == 0x09 ) )
        {
            if ( ( nCount == 0 ) && mnWidth )
                nCount++;
            else if ( ( nCount == 1 ) && mnHeight )
            {
                if ( ++nCount == nMax )
                    bFinished = true;
            }
            else if ( ( nCount == 2 ) && mnMaxVal )
            {
                bFinished = true;
            }
            continue;
        }
        if ( ( nDat >= '0' ) && ( nDat <= '9' ) )
        {
            nDat -= '0';
            if ( nCount == 0 )
            {
                mnWidth *= 10;
                mnWidth += nDat;
            }
            else if ( nCount == 1 )
            {
                mnHeight *= 10;
                mnHeight += nDat;
            }
            else if ( nCount == 2 )
            {
                mnMaxVal *= 10;
                mnMaxVal += nDat;
            }
        }
        else
            return false;
    }
    return mbStatus;
}

bool PBMReader::ImplReadBody()
{
    bool    bPara, bFinished = false;
    sal_uInt8   nDat = 0, nCount;
    sal_uLong   nGrey, nRGB[3];
    sal_uLong   nWidth = 0;
    sal_uLong   nHeight = 0;

    if ( mbRaw )
    {
        signed char nShift = 0;
        switch ( mnMode )
        {

            // PBM
            case 0 :
                while ( nHeight != mnHeight )
                {
                    if ( mrPBM.IsEof() || mrPBM.GetError() )
                        return false;

                    if ( --nShift < 0 )
                    {
                        mrPBM.ReadUChar( nDat );
                        nShift = 7;
                    }
                    mpAcc->SetPixelIndex( nHeight, nWidth, nDat >> nShift );
                    if ( ++nWidth == mnWidth )
                    {
                        nShift = 0;
                        nWidth = 0;
                        nHeight++;
                        ImplCallback( (sal_uInt16)( ( 100 * nHeight ) / mnHeight ) );   // processing output in percent
                    }
                }
                break;

            // PGM
            case 1 :
                while ( nHeight != mnHeight )
                {
                    if ( mrPBM.IsEof() || mrPBM.GetError() )
                        return false;

                    mrPBM.ReadUChar( nDat );
                    mpAcc->SetPixelIndex( nHeight, nWidth++, nDat);

                    if ( nWidth == mnWidth )
                    {
                        nWidth = 0;
                        nHeight++;
                        ImplCallback( (sal_uInt16)( ( 100 * nHeight ) / mnHeight ) );   // processing output in percent
                    }
                }
                break;

            // PPM
            case 2 :
                while ( nHeight != mnHeight )
                {
                    if ( mrPBM.IsEof() || mrPBM.GetError() )
                        return false;

                    sal_uInt8   nR, nG, nB;
                    sal_uLong   nRed, nGreen, nBlue;
                    mrPBM.ReadUChar( nR ).ReadUChar( nG ).ReadUChar( nB );
                    nRed = 255 * nR / mnMaxVal;
                    nGreen = 255 * nG / mnMaxVal;
                    nBlue = 255 * nB / mnMaxVal;
                    mpAcc->SetPixel( nHeight, nWidth++, BitmapColor( (sal_uInt8)nRed, (sal_uInt8)nGreen, (sal_uInt8)nBlue ) );
                    if ( nWidth == mnWidth )
                    {
                        nWidth = 0;
                        nHeight++;
                        ImplCallback( (sal_uInt16) ( ( 100 * nHeight ) / mnHeight ) );  // processing output in percent
                    }
                }
                break;
        }
    }
    else switch  ( mnMode )
    {
        // PBM
        case 0 :
            while ( bFinished == false )
            {
                if ( mrPBM.IsEof() || mrPBM.GetError() )
                    return false;

                mrPBM.ReadUChar( nDat );

                if ( nDat == '#' )
                {
                    mbRemark = true;
                    continue;
                }
                else if ( ( nDat == 0x0d ) || ( nDat == 0x0a ) )
                {
                    mbRemark = false;
                    continue;
                }
                if ( mbRemark || nDat == 0x20 || nDat == 0x09 )
                    continue;

                if ( nDat == '0' || nDat == '1' )
                {
                    mpAcc->SetPixelIndex( nHeight, nWidth, static_cast<sal_uInt8>(nDat - '0') );
                    nWidth++;
                    if ( nWidth == mnWidth )
                    {
                        nWidth = 0;
                        if ( ++nHeight == mnHeight )
                            bFinished = true;
                        ImplCallback( (sal_uInt16) ( ( 100 * nHeight ) / mnHeight ) );  // processing output in percent
                    }
                }
                else
                    return false;
            }
            break;

        // PGM
        case 1 :

            bPara = false;
            nCount = 0;
            nGrey = 0;

            while ( bFinished == false )
            {
                if ( nCount )
                {
                    nCount--;
                    if ( nGrey <= mnMaxVal )
                        nGrey = 255 * nGrey / mnMaxVal;
                    mpAcc->SetPixelIndex( nHeight, nWidth++, static_cast<sal_uInt8>(nGrey) );
                    nGrey = 0;
                    if ( nWidth == mnWidth )
                    {
                        nWidth = 0;
                        if ( ++nHeight == mnHeight )
                            bFinished = true;
                        ImplCallback( (sal_uInt16) ( ( 100 * nHeight ) / mnHeight ) );  // processing output in percent
                    }
                    continue;
                }

                if ( mrPBM.IsEof() || mrPBM.GetError() )
                    return false;

                mrPBM.ReadUChar( nDat );

                if ( nDat == '#' )
                {
                    mbRemark = true;
                    if ( bPara )
                    {
                        bPara = false;
                        nCount++;
                    }
                    continue;
                }
                else if ( ( nDat == 0x0d ) || ( nDat == 0x0a ) )
                {
                    mbRemark = false;
                    if ( bPara )
                    {
                        bPara = false;
                        nCount++;
                    }
                    continue;
                }

                if ( nDat == 0x20 || nDat == 0x09 )
                {
                    if ( bPara )
                    {
                        bPara = false;
                        nCount++;
                    }
                    continue;
                }
                if ( nDat >= '0' && nDat <= '9' )
                {
                    bPara = true;
                    nGrey *= 10;
                    nGrey += nDat-'0';
                    continue;
                }
                else
                    return false;
            }
            break;

        // PPM
        case 2 :

            bPara = false;
            nCount = 0;
            nRGB[ 0 ] = nRGB[ 1 ] = nRGB[ 2 ] = 0;

            while ( bFinished == false )
            {
                if ( nCount == 3 )
                {
                    nCount = 0;
                    mpAcc->SetPixel( nHeight, nWidth++, BitmapColor( static_cast< sal_uInt8 >( ( nRGB[ 0 ] * 255 ) / mnMaxVal ),
                                                                     static_cast< sal_uInt8 >( ( nRGB[ 1 ] * 255 ) / mnMaxVal ),
                                                                     static_cast< sal_uInt8 >( ( nRGB[ 2 ] * 255 ) / mnMaxVal ) ) );
                    nCount = 0;
                    nRGB[ 0 ] = nRGB[ 1 ] = nRGB[ 2 ] = 0;
                    if ( nWidth == mnWidth )
                    {
                        nWidth = 0;
                        if ( ++nHeight == mnHeight )
                            bFinished = true;
                        ImplCallback( (sal_uInt16) ( ( 100 * nHeight ) / mnHeight ) );  // processing output in percent
                    }
                    continue;
                }

                if ( mrPBM.IsEof() || mrPBM.GetError() )
                    return false;

                mrPBM.ReadUChar( nDat );

                if ( nDat == '#' )
                {
                    mbRemark = true;
                    if ( bPara )
                    {
                        bPara = false;
                        nCount++;
                    }
                    continue;
                }
                else if ( ( nDat == 0x0d ) || ( nDat == 0x0a ) )
                {
                    mbRemark = false;
                    if ( bPara )
                    {
                        bPara = false;
                        nCount++;
                    }
                    continue;
                }

                if ( nDat == 0x20 || nDat == 0x09 )
                {
                    if ( bPara )
                    {
                        bPara = false;
                        nCount++;
                    }
                    continue;
                }
                if ( nDat >= '0' && nDat <= '9' )
                {
                    bPara = true;
                    nRGB[ nCount ] *= 10;
                    nRGB[ nCount ] += nDat-'0';
                    continue;
                }
                else
                    return false;
            }
            break;
    }
    return mbStatus;
}

//================== GraphicImport - the exported function ================

// this needs to be kept in sync with
// ImpFilterLibCacheEntry::GetImportFunction() from
// vcl/source/filter/graphicfilter.cxx
#if defined(DISABLE_DYNLOADING)
#define GraphicImport ipbGraphicImport
#endif

extern "C" SAL_DLLPUBLIC_EXPORT bool SAL_CALL
GraphicImport( SvStream & rStream, Graphic & rGraphic, FilterConfigItem* )
{
    PBMReader aPBMReader(rStream);

    return aPBMReader.ReadPBM(rGraphic );
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>cppcheck: redundantAssignment<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <vcl/graph.hxx>
#include <vcl/bmpacc.hxx>

class FilterConfigItem;

//============================ PBMReader ==================================

class PBMReader {

private:

    SvStream&           mrPBM;              // the PBM file to read

    bool            mbStatus;
    bool            mbRemark;           // sal_False if the stream is in a comment
    bool            mbRaw;              // RAW/ASCII MODE
    sal_uLong           mnMode;             // 0->PBM, 1->PGM, 2->PPM
    Bitmap              maBmp;
    BitmapWriteAccess*  mpAcc;
    sal_uLong           mnWidth, mnHeight;  // dimensions in pixel
    sal_uLong           mnCol;
    sal_uLong           mnMaxVal;           // max value in the <missing comment>
    bool            ImplCallback( sal_uInt16 nPercent );
    bool            ImplReadBody();
    bool            ImplReadHeader();

public:
                        PBMReader(SvStream & rPBM);
                        ~PBMReader();
    bool                ReadPBM(Graphic & rGraphic );
};

//=================== Methods of PBMReader ==============================

PBMReader::PBMReader(SvStream & rPBM)
    : mrPBM(rPBM)
    , mbStatus(true)
    , mbRemark(false)
    , mbRaw(true)
    , mnMode(0)
    , mpAcc(NULL)
    , mnWidth(0)
    , mnHeight(0)
    , mnCol(0)
    , mnMaxVal(0)
{
}

PBMReader::~PBMReader()
{
}

bool PBMReader::ImplCallback( sal_uInt16 /*nPercent*/ )
{
/*
    if ( pCallback != NULL )
    {
        if ( ( (*pCallback)( pCallerData, nPercent ) ) == sal_True )
        {
            mrPBM.SetError( SVSTREAM_FILEFORMAT_ERROR );
            return sal_True;
        }
    }
*/
    return false;
}

bool PBMReader::ReadPBM(Graphic & rGraphic )
{
    sal_uInt16 i;

    if ( mrPBM.GetError() )
        return false;

    mrPBM.SetNumberFormatInt( NUMBERFORMAT_INT_LITTLEENDIAN );

    // read header:

    if ( ( mbStatus = ImplReadHeader() ) == false )
        return false;

    if ( ( mnMaxVal == 0 ) || ( mnWidth == 0 ) || ( mnHeight == 0 ) )
        return false;

    // 0->PBM, 1->PGM, 2->PPM
    switch ( mnMode )
    {
        case 0 :
            maBmp = Bitmap( Size( mnWidth, mnHeight ), 1 );
            if ( ( mpAcc = maBmp.AcquireWriteAccess() ) == 0 )
                return false;
            mpAcc->SetPaletteEntryCount( 2 );
            mpAcc->SetPaletteColor( 0, BitmapColor( 0xff, 0xff, 0xff ) );
            mpAcc->SetPaletteColor( 1, BitmapColor( 0x00, 0x00, 0x00 ) );
            break;

        case 1 :
            if ( mnMaxVal <= 1 )
                maBmp = Bitmap( Size( mnWidth, mnHeight ), 1);
            else if ( mnMaxVal <= 15 )
                maBmp = Bitmap( Size( mnWidth, mnHeight ), 4);
            else
                maBmp = Bitmap( Size( mnWidth, mnHeight ), 8);

            if ( ( mpAcc = maBmp.AcquireWriteAccess() ) == 0 )
                return false;
            mnCol = (sal_uInt16)mnMaxVal + 1;
            if ( mnCol > 256 )
                mnCol = 256;

            mpAcc->SetPaletteEntryCount( 256 );
            for ( i = 0; i < mnCol; i++ )
            {
                sal_uLong nCount = 255 * i / mnCol;
                mpAcc->SetPaletteColor( i, BitmapColor( (sal_uInt8)nCount, (sal_uInt8)nCount, (sal_uInt8)nCount ) );
            }
            break;
        case 2 :
            maBmp = Bitmap( Size( mnWidth, mnHeight ), 24 );
            if ( ( mpAcc = maBmp.AcquireWriteAccess() ) == 0 )
                return false;
            break;
    }

    // read bitmap data
    mbStatus = ImplReadBody();

    if ( mpAcc )
    {
        maBmp.ReleaseAccess( mpAcc ), mpAcc = NULL;
    }
    if ( mbStatus )
        rGraphic = maBmp;

    return mbStatus;
}

bool PBMReader::ImplReadHeader()
{
    sal_uInt8   nID[ 2 ];
    sal_uInt8   nDat;
    sal_uInt8   nMax, nCount = 0;
    bool    bFinished = false;

    mrPBM.ReadUChar( nID[ 0 ] ).ReadUChar( nID[ 1 ] );
    if ( nID[ 0 ] != 'P' )
        return false;
    mnMaxVal = mnWidth = mnHeight = 0;
    switch ( nID[ 1 ] )
    {
        case '1' :
            mbRaw = false;
        case '4' :
            mnMode = 0;
            nMax = 2;               // number of parameters in Header
            mnMaxVal = 1;
            break;
        case '2' :
            mbRaw = false;
        case '5' :
            mnMode = 1;
            nMax = 3;
            break;
        case '3' :
            mbRaw = false;
        case '6' :
            mnMode = 2;
            nMax = 3;
            break;
        default:
            return false;
    }
    while ( bFinished == false )
    {
        if ( mrPBM.GetError() )
            return false;

        mrPBM.ReadUChar( nDat );

        if ( nDat == '#' )
        {
            mbRemark = true;
            continue;
        }
        else if ( ( nDat == 0x0d ) || ( nDat == 0x0a ) )
        {
            mbRemark = false;
            nDat = 0x20;
        }
        if ( mbRemark )
            continue;

        if ( ( nDat == 0x20 ) || ( nDat == 0x09 ) )
        {
            if ( ( nCount == 0 ) && mnWidth )
                nCount++;
            else if ( ( nCount == 1 ) && mnHeight )
            {
                if ( ++nCount == nMax )
                    bFinished = true;
            }
            else if ( ( nCount == 2 ) && mnMaxVal )
            {
                bFinished = true;
            }
            continue;
        }
        if ( ( nDat >= '0' ) && ( nDat <= '9' ) )
        {
            nDat -= '0';
            if ( nCount == 0 )
            {
                mnWidth *= 10;
                mnWidth += nDat;
            }
            else if ( nCount == 1 )
            {
                mnHeight *= 10;
                mnHeight += nDat;
            }
            else if ( nCount == 2 )
            {
                mnMaxVal *= 10;
                mnMaxVal += nDat;
            }
        }
        else
            return false;
    }
    return mbStatus;
}

bool PBMReader::ImplReadBody()
{
    bool    bPara, bFinished = false;
    sal_uInt8   nDat = 0, nCount;
    sal_uLong   nGrey, nRGB[3];
    sal_uLong   nWidth = 0;
    sal_uLong   nHeight = 0;

    if ( mbRaw )
    {
        signed char nShift = 0;
        switch ( mnMode )
        {

            // PBM
            case 0 :
                while ( nHeight != mnHeight )
                {
                    if ( mrPBM.IsEof() || mrPBM.GetError() )
                        return false;

                    if ( --nShift < 0 )
                    {
                        mrPBM.ReadUChar( nDat );
                        nShift = 7;
                    }
                    mpAcc->SetPixelIndex( nHeight, nWidth, nDat >> nShift );
                    if ( ++nWidth == mnWidth )
                    {
                        nShift = 0;
                        nWidth = 0;
                        nHeight++;
                        ImplCallback( (sal_uInt16)( ( 100 * nHeight ) / mnHeight ) );   // processing output in percent
                    }
                }
                break;

            // PGM
            case 1 :
                while ( nHeight != mnHeight )
                {
                    if ( mrPBM.IsEof() || mrPBM.GetError() )
                        return false;

                    mrPBM.ReadUChar( nDat );
                    mpAcc->SetPixelIndex( nHeight, nWidth++, nDat);

                    if ( nWidth == mnWidth )
                    {
                        nWidth = 0;
                        nHeight++;
                        ImplCallback( (sal_uInt16)( ( 100 * nHeight ) / mnHeight ) );   // processing output in percent
                    }
                }
                break;

            // PPM
            case 2 :
                while ( nHeight != mnHeight )
                {
                    if ( mrPBM.IsEof() || mrPBM.GetError() )
                        return false;

                    sal_uInt8   nR, nG, nB;
                    sal_uLong   nRed, nGreen, nBlue;
                    mrPBM.ReadUChar( nR ).ReadUChar( nG ).ReadUChar( nB );
                    nRed = 255 * nR / mnMaxVal;
                    nGreen = 255 * nG / mnMaxVal;
                    nBlue = 255 * nB / mnMaxVal;
                    mpAcc->SetPixel( nHeight, nWidth++, BitmapColor( (sal_uInt8)nRed, (sal_uInt8)nGreen, (sal_uInt8)nBlue ) );
                    if ( nWidth == mnWidth )
                    {
                        nWidth = 0;
                        nHeight++;
                        ImplCallback( (sal_uInt16) ( ( 100 * nHeight ) / mnHeight ) );  // processing output in percent
                    }
                }
                break;
        }
    }
    else switch  ( mnMode )
    {
        // PBM
        case 0 :
            while ( bFinished == false )
            {
                if ( mrPBM.IsEof() || mrPBM.GetError() )
                    return false;

                mrPBM.ReadUChar( nDat );

                if ( nDat == '#' )
                {
                    mbRemark = true;
                    continue;
                }
                else if ( ( nDat == 0x0d ) || ( nDat == 0x0a ) )
                {
                    mbRemark = false;
                    continue;
                }
                if ( mbRemark || nDat == 0x20 || nDat == 0x09 )
                    continue;

                if ( nDat == '0' || nDat == '1' )
                {
                    mpAcc->SetPixelIndex( nHeight, nWidth, static_cast<sal_uInt8>(nDat - '0') );
                    nWidth++;
                    if ( nWidth == mnWidth )
                    {
                        nWidth = 0;
                        if ( ++nHeight == mnHeight )
                            bFinished = true;
                        ImplCallback( (sal_uInt16) ( ( 100 * nHeight ) / mnHeight ) );  // processing output in percent
                    }
                }
                else
                    return false;
            }
            break;

        // PGM
        case 1 :

            bPara = false;
            nCount = 0;
            nGrey = 0;

            while ( bFinished == false )
            {
                if ( nCount )
                {
                    nCount--;
                    if ( nGrey <= mnMaxVal )
                        nGrey = 255 * nGrey / mnMaxVal;
                    mpAcc->SetPixelIndex( nHeight, nWidth++, static_cast<sal_uInt8>(nGrey) );
                    nGrey = 0;
                    if ( nWidth == mnWidth )
                    {
                        nWidth = 0;
                        if ( ++nHeight == mnHeight )
                            bFinished = true;
                        ImplCallback( (sal_uInt16) ( ( 100 * nHeight ) / mnHeight ) );  // processing output in percent
                    }
                    continue;
                }

                if ( mrPBM.IsEof() || mrPBM.GetError() )
                    return false;

                mrPBM.ReadUChar( nDat );

                if ( nDat == '#' )
                {
                    mbRemark = true;
                    if ( bPara )
                    {
                        bPara = false;
                        nCount++;
                    }
                    continue;
                }
                else if ( ( nDat == 0x0d ) || ( nDat == 0x0a ) )
                {
                    mbRemark = false;
                    if ( bPara )
                    {
                        bPara = false;
                        nCount++;
                    }
                    continue;
                }

                if ( nDat == 0x20 || nDat == 0x09 )
                {
                    if ( bPara )
                    {
                        bPara = false;
                        nCount++;
                    }
                    continue;
                }
                if ( nDat >= '0' && nDat <= '9' )
                {
                    bPara = true;
                    nGrey *= 10;
                    nGrey += nDat-'0';
                    continue;
                }
                else
                    return false;
            }
            break;

        // PPM
        case 2 :

            bPara = false;
            nCount = 0;
            nRGB[ 0 ] = nRGB[ 1 ] = nRGB[ 2 ] = 0;

            while ( bFinished == false )
            {
                if ( nCount == 3 )
                {
                    nCount = 0;
                    mpAcc->SetPixel( nHeight, nWidth++, BitmapColor( static_cast< sal_uInt8 >( ( nRGB[ 0 ] * 255 ) / mnMaxVal ),
                                                                     static_cast< sal_uInt8 >( ( nRGB[ 1 ] * 255 ) / mnMaxVal ),
                                                                     static_cast< sal_uInt8 >( ( nRGB[ 2 ] * 255 ) / mnMaxVal ) ) );
                    nRGB[ 0 ] = nRGB[ 1 ] = nRGB[ 2 ] = 0;
                    if ( nWidth == mnWidth )
                    {
                        nWidth = 0;
                        if ( ++nHeight == mnHeight )
                            bFinished = true;
                        ImplCallback( (sal_uInt16) ( ( 100 * nHeight ) / mnHeight ) );  // processing output in percent
                    }
                    continue;
                }

                if ( mrPBM.IsEof() || mrPBM.GetError() )
                    return false;

                mrPBM.ReadUChar( nDat );

                if ( nDat == '#' )
                {
                    mbRemark = true;
                    if ( bPara )
                    {
                        bPara = false;
                        nCount++;
                    }
                    continue;
                }
                else if ( ( nDat == 0x0d ) || ( nDat == 0x0a ) )
                {
                    mbRemark = false;
                    if ( bPara )
                    {
                        bPara = false;
                        nCount++;
                    }
                    continue;
                }

                if ( nDat == 0x20 || nDat == 0x09 )
                {
                    if ( bPara )
                    {
                        bPara = false;
                        nCount++;
                    }
                    continue;
                }
                if ( nDat >= '0' && nDat <= '9' )
                {
                    bPara = true;
                    nRGB[ nCount ] *= 10;
                    nRGB[ nCount ] += nDat-'0';
                    continue;
                }
                else
                    return false;
            }
            break;
    }
    return mbStatus;
}

//================== GraphicImport - the exported function ================

// this needs to be kept in sync with
// ImpFilterLibCacheEntry::GetImportFunction() from
// vcl/source/filter/graphicfilter.cxx
#if defined(DISABLE_DYNLOADING)
#define GraphicImport ipbGraphicImport
#endif

extern "C" SAL_DLLPUBLIC_EXPORT bool SAL_CALL
GraphicImport( SvStream & rStream, Graphic & rGraphic, FilterConfigItem* )
{
    PBMReader aPBMReader(rStream);

    return aPBMReader.ReadPBM(rGraphic );
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>/*
 *   This file only:
 *     Copyright (C) 2003  Mark Bucciarelli <mark@hubcapconsutling.com>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License along
 *   with this program; if not, write to the
 *      Free Software Foundation, Inc.
 *      59 Temple Place - Suite 330
 *      Boston, MA  02111-1307  USA.
 *
 */

// #include <iostream>

#include <qdatetime.h>
#include <qpaintdevicemetrics.h>
#include <qpainter.h>
#include <qmap.h>

#include <kglobal.h>
#include <kdebug.h>
#include <klocale.h>            // i18n
#include <event.h>

#include "karmutility.h"        // formatTime()
#include "timekard.h"
#include "task.h"
#include "taskview.h"

const int taskWidth = 40;
const int timeWidth = 6;
const int totalTimeWidth = 7;
const int reportWidth = taskWidth + (7 * timeWidth) + totalTimeWidth;

const QString cr = QString::fromLatin1("\n");

QString TimeKard::totalsAsText(TaskView* taskview, bool justThisTask)
{
  QString retval;
  QString taskhdr, totalhdr;
  QString line;
  QString buf;
  long sum;

  line.fill('-', reportWidth);
  line += cr;

  // header
  retval += i18n("Task Totals") + cr;
  retval += KGlobal::locale()->formatDateTime(QDateTime::currentDateTime());
  retval += cr + cr;
  retval += QString(QString::fromLatin1("%1    %2"))
    .arg(i18n("Time"), timeWidth)
    .arg(i18n("Task"), -taskWidth);
  retval += cr;
  retval += line;

  // tasks
  if (taskview->current_item())
  {
    if (justThisTask)
    {
      // a task's total time includes the sum of all subtask times
      sum = taskview->current_item()->totalTime();
      printTask(taskview->current_item(), retval, 0);
    }
    else
    {
      sum = 0;
      for (Task* task= taskview->current_item(); task;
          task= task->nextSibling())
      {
        sum += task->totalTime();
        printTask(task, retval, 0);
      }
    }

    // total
    buf.fill('-', timeWidth + 4);
    retval += QString(QString::fromLatin1("%1")).arg(buf, timeWidth) + cr;
    retval += QString(QString::fromLatin1("%1 %2"))
      .arg(formatTime(sum),timeWidth)
      .arg(i18n("Total"), -taskWidth);
  }
  else
    retval += i18n("No tasks!");

  return retval;
}

void TimeKard::printTask(Task *task, QString &s, int level)
{
  QString buf;

  s += buf.fill(' ', level);
  s += QString(QString::fromLatin1("%1    %2"))
    .arg(formatTime(task->totalTime()), timeWidth)
    .arg(task->name(), -taskWidth);
  s += cr;

  for (Task* subTask = task->firstChild();
      subTask;
      subTask = subTask->nextSibling())
  {
    printTask(subTask, s, level+1);
  }
}

void TimeKard::printWeekTask(const Task *task,
    const QMap<QString,long>& taskdaytotals,
    QMap<QString,long>& daytotals,
    const Week& week, const int level, QString& s)
{
  QString buf;
  QString daytaskkey, daykey;
  QDate day;
  long weeksum;

  day = week.start();
  weeksum = 0;
  for (int i = 0; i < 7; i++)
  {
    daykey = day.toString(QString::fromLatin1("yyyyMMdd"));
    daytaskkey = QString::fromLatin1("%1_%2")
      .arg(daykey)
      .arg(task->uid());

    if (taskdaytotals.contains(daytaskkey))
    {
      s += QString::fromLatin1("%1")
        .arg(formatTime(taskdaytotals[daytaskkey]/60), timeWidth);
      weeksum += taskdaytotals[daytaskkey];  // in seconds

      if (daytotals.contains(daykey))
        daytotals.replace(daykey, daytotals[daykey] + taskdaytotals[daytaskkey]);
      else
        daytotals.insert(daykey, taskdaytotals[daytaskkey]);
    }
    else
    {
      buf.fill(' ', timeWidth);
      s += buf;
    }

    day = day.addDays(1);
  }

  // Total for task this week
  s += QString::fromLatin1("%1").arg(formatTime(weeksum/60), totalTimeWidth);

  // Task name
  s += buf.fill(' ', level + 1);
  s += QString::fromLatin1("%1").arg(task->name(), -taskWidth);
  s += cr;

  for (Task* subTask = task->firstChild();
      subTask;
      subTask = subTask->nextSibling())
  {
    printWeekTask(subTask, taskdaytotals, daytotals, week, level+1, s);
  }
}

QString TimeKard::historyAsText(TaskView* taskview, const QDate& from,
    const QDate& to, bool justThisTask)
{
  QString retval;
  QString taskhdr, totalhdr;
  QString line, buf;
  long sum;

  QValueList<Week>::iterator week;
  QValueList<HistoryEvent> events;
  QValueList<HistoryEvent>::iterator event;
  QMap<QString, long> taskdaytotals;
  QMap<QString, long> daytotals;
  QString daytaskkey, daykey;
  QDate day;

  line.fill('-', reportWidth);
  line += cr;

  // header
  retval += i18n("Task History") + cr;
  retval += i18n("From %1 to %2")
    .arg(KGlobal::locale()->formatDate(from))
    .arg(KGlobal::locale()->formatDate(to));
  retval += cr;
  retval += i18n("Printed on: %1")
    .arg(KGlobal::locale()->formatDateTime(QDateTime::currentDateTime()));

  // output one time card table for each week in the date range
  QValueList<Week> weeks = Week::weeksFromDateRange(from, to);
  for (week = weeks.begin(); week != weeks.end(); ++week)
  {
    if ( (*week).start() < from )
    {
      events = taskview->getHistory( from, (*week).end());
    }
    else if ( (*week).end() > to)
    {
      events = taskview->getHistory((*week).start(), to);
    }
    else
    {
      events = taskview->getHistory((*week).start(), (*week).end());
    }

    taskdaytotals.clear();
    daytotals.clear();

    // Build lookup dictionary used to output data in table cells.  keys are
    // in this format: YYYYMMDD_NNNNNN, where Y = year, M = month, d = day and
    // NNNNN = the VTODO uid.  The value is the total seconds logged against
    // that task on that day.  Note the UID is the todo id, not the event id,
    // so times are accumulated for each task.
    for (event = events.begin(); event != events.end(); ++event)
    {
      daykey = (*event).start().date().toString(QString::fromLatin1("yyyyMMdd"));
      daytaskkey = QString(QString::fromLatin1("%1_%2"))
        .arg(daykey)
        .arg((*event).todoUid());

      if (taskdaytotals.contains(daytaskkey))
        taskdaytotals.replace(daytaskkey,
            taskdaytotals[daytaskkey] + (*event).duration());
      else
        taskdaytotals.insert(daytaskkey, (*event).duration());
    }

    // week name
    retval += cr + cr;
    buf.fill(' ', int((reportWidth - (*week).name().length()) / 2));
    retval += buf + (*week).name() + cr;

    // day headings
    for (int i = 0; i < 7; i++)
    {
      retval += QString::fromLatin1("%1")
          .arg((*week).start().addDays(i).day(), timeWidth);
    }
    retval += cr;
    retval += line;

    // the tasks
    if (events.empty())
    {
      retval += i18n("  No hours logged.");
    }
    else
    {
      sum = 0;
      if (justThisTask)
      {
        printWeekTask(taskview->current_item(), taskdaytotals, daytotals,
            (*week), 0, retval);
      }
      else
      {
        for (Task* task= taskview->current_item(); task;
            task= task->nextSibling())
        {
          printWeekTask(task, taskdaytotals, daytotals, (*week), 0, retval);
        }
      }
      retval += line;

      // totals
      sum = 0;
      day = (*week).start();
      for (int i = 0; i < 7; i++)
      {
        daykey = day.toString(QString::fromLatin1("yyyyMMdd"));

        if (daytotals.contains(daykey))
        {
          retval += QString::fromLatin1("%1")
              .arg(formatTime(daytotals[daykey]/60), timeWidth);
          sum += daytotals[daykey];  // in seconds
        }
        else
        {
          buf.fill(' ', timeWidth);
          retval += buf;
        }

        day = day.addDays(1);
      }

      retval += QString::fromLatin1("%1 %2")
        .arg(formatTime(sum/60), totalTimeWidth)
        .arg(i18n("Total"), -taskWidth);

    }
  }
  return retval;
}

Week::Week() {}

Week::Week(QDate from)
{
  _start = from;
}

QDate Week::start() const
{
  return _start;
}

QDate Week::end() const
{
  return _start.addDays(7);
}

QString Week::name() const
{
  return QString(i18n("Week of %1"))
    .arg(KGlobal::locale()->formatDate(start()));
}

QValueList<Week> Week::weeksFromDateRange(const QDate& from, const QDate& to)
{
  QDate start;
  QValueList<Week> weeks;

  // The QDate weekNumber() method always puts monday as the first day of the
  // week.
  //
  // Not that it matters here, but week 1 always includes the first Thursday
  // of the year.  For example, January 1, 2000 was a Saturday, so
  // QDate(2000,1,1).weekNumber() returns 52.

  // Since report always shows a full week, we generate a full week of dates,
  // even if from and to are the same date.  The week starts on the day
  // that is set in the locale settings.
  start = from.addDays(
      -((7 - KGlobal::locale()->weekStartDay() + from.dayOfWeek()) % 7));

  for (QDate d = start; d <= to; d = d.addDays(7))
    weeks.append(Week(d));

  return weeks;
}

<commit_msg>Get rid of all the trailing spaces (in the copy-as-text feature). Made totals report a bit less wide than the history report, doesn't need to be.<commit_after>/*
 *   This file only:
 *     Copyright (C) 2003  Mark Bucciarelli <mark@hubcapconsutling.com>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License along
 *   with this program; if not, write to the
 *      Free Software Foundation, Inc.
 *      59 Temple Place - Suite 330
 *      Boston, MA  02111-1307  USA.
 *
 */

// #include <iostream>

#include <qdatetime.h>
#include <qpaintdevicemetrics.h>
#include <qpainter.h>
#include <qmap.h>

#include <kglobal.h>
#include <kdebug.h>
#include <klocale.h>            // i18n
#include <event.h>

#include "karmutility.h"        // formatTime()
#include "timekard.h"
#include "task.h"
#include "taskview.h"

const int taskWidth = 40;
const int timeWidth = 6;
const int totalTimeWidth = 7;
const int reportWidth = taskWidth + timeWidth;
const int weekReportWidth = taskWidth + (7 * timeWidth) + totalTimeWidth;

const QString cr = QString::fromLatin1("\n");

QString TimeKard::totalsAsText(TaskView* taskview, bool justThisTask)
{
  QString retval;
  QString taskhdr, totalhdr;
  QString line;
  QString buf;
  long sum;

  line.fill('-', reportWidth);
  line += cr;

  // header
  retval += i18n("Task Totals") + cr;
  retval += KGlobal::locale()->formatDateTime(QDateTime::currentDateTime());
  retval += cr + cr;
  retval += QString(QString::fromLatin1("%1    %2"))
    .arg(i18n("Time"), timeWidth)
    .arg(i18n("Task"));
  retval += cr;
  retval += line;

  // tasks
  if (taskview->current_item())
  {
    if (justThisTask)
    {
      // a task's total time includes the sum of all subtask times
      sum = taskview->current_item()->totalTime();
      printTask(taskview->current_item(), retval, 0);
    }
    else
    {
      sum = 0;
      for (Task* task= taskview->current_item(); task;
          task= task->nextSibling())
      {
        sum += task->totalTime();
        printTask(task, retval, 0);
      }
    }

    // total
    buf.fill('-', reportWidth);
    retval += QString(QString::fromLatin1("%1")).arg(buf, timeWidth) + cr;
    retval += QString(QString::fromLatin1("%1 %2"))
      .arg(formatTime(sum),timeWidth)
      .arg(i18n("Total"));
  }
  else
    retval += i18n("No tasks!");

  return retval;
}

void TimeKard::printTask(Task *task, QString &s, int level)
{
  QString buf;

  s += buf.fill(' ', level);
  s += QString(QString::fromLatin1("%1    %2"))
    .arg(formatTime(task->totalTime()), timeWidth)
    .arg(task->name());
  s += cr;

  for (Task* subTask = task->firstChild();
      subTask;
      subTask = subTask->nextSibling())
  {
    printTask(subTask, s, level+1);
  }
}

void TimeKard::printWeekTask(const Task *task,
    const QMap<QString,long>& taskdaytotals,
    QMap<QString,long>& daytotals,
    const Week& week, const int level, QString& s)
{
  QString buf;
  QString daytaskkey, daykey;
  QDate day;
  long weeksum;

  day = week.start();
  weeksum = 0;
  for (int i = 0; i < 7; i++)
  {
    daykey = day.toString(QString::fromLatin1("yyyyMMdd"));
    daytaskkey = QString::fromLatin1("%1_%2")
      .arg(daykey)
      .arg(task->uid());

    if (taskdaytotals.contains(daytaskkey))
    {
      s += QString::fromLatin1("%1")
        .arg(formatTime(taskdaytotals[daytaskkey]/60), timeWidth);
      weeksum += taskdaytotals[daytaskkey];  // in seconds

      if (daytotals.contains(daykey))
        daytotals.replace(daykey, daytotals[daykey] + taskdaytotals[daytaskkey]);
      else
        daytotals.insert(daykey, taskdaytotals[daytaskkey]);
    }
    else
    {
      buf.fill(' ', timeWidth);
      s += buf;
    }

    day = day.addDays(1);
  }

  // Total for task this week
  s += QString::fromLatin1("%1").arg(formatTime(weeksum/60), totalTimeWidth);

  // Task name
  s += buf.fill(' ', level + 1);
  s += QString::fromLatin1("%1").arg(task->name());
  s += cr;

  for (Task* subTask = task->firstChild();
      subTask;
      subTask = subTask->nextSibling())
  {
    printWeekTask(subTask, taskdaytotals, daytotals, week, level+1, s);
  }
}

QString TimeKard::historyAsText(TaskView* taskview, const QDate& from,
    const QDate& to, bool justThisTask)
{
  QString retval;
  QString taskhdr, totalhdr;
  QString line, buf;
  long sum;

  QValueList<Week>::iterator week;
  QValueList<HistoryEvent> events;
  QValueList<HistoryEvent>::iterator event;
  QMap<QString, long> taskdaytotals;
  QMap<QString, long> daytotals;
  QString daytaskkey, daykey;
  QDate day;

  line.fill('-', weekReportWidth);
  line += cr;

  // header
  retval += i18n("Task History") + cr;
  retval += i18n("From %1 to %2")
    .arg(KGlobal::locale()->formatDate(from))
    .arg(KGlobal::locale()->formatDate(to));
  retval += cr;
  retval += i18n("Printed on: %1")
    .arg(KGlobal::locale()->formatDateTime(QDateTime::currentDateTime()));

  // output one time card table for each week in the date range
  QValueList<Week> weeks = Week::weeksFromDateRange(from, to);
  for (week = weeks.begin(); week != weeks.end(); ++week)
  {
    if ( (*week).start() < from )
    {
      events = taskview->getHistory( from, (*week).end());
    }
    else if ( (*week).end() > to)
    {
      events = taskview->getHistory((*week).start(), to);
    }
    else
    {
      events = taskview->getHistory((*week).start(), (*week).end());
    }

    taskdaytotals.clear();
    daytotals.clear();

    // Build lookup dictionary used to output data in table cells.  keys are
    // in this format: YYYYMMDD_NNNNNN, where Y = year, M = month, d = day and
    // NNNNN = the VTODO uid.  The value is the total seconds logged against
    // that task on that day.  Note the UID is the todo id, not the event id,
    // so times are accumulated for each task.
    for (event = events.begin(); event != events.end(); ++event)
    {
      daykey = (*event).start().date().toString(QString::fromLatin1("yyyyMMdd"));
      daytaskkey = QString(QString::fromLatin1("%1_%2"))
        .arg(daykey)
        .arg((*event).todoUid());

      if (taskdaytotals.contains(daytaskkey))
        taskdaytotals.replace(daytaskkey,
            taskdaytotals[daytaskkey] + (*event).duration());
      else
        taskdaytotals.insert(daytaskkey, (*event).duration());
    }

    // week name
    retval += cr + cr;
    buf.fill(' ', int((weekReportWidth - (*week).name().length()) / 2));
    retval += buf + (*week).name() + cr;

    // day headings
    for (int i = 0; i < 7; i++)
    {
      retval += QString::fromLatin1("%1")
          .arg((*week).start().addDays(i).day(), timeWidth);
    }
    retval += cr;
    retval += line;

    // the tasks
    if (events.empty())
    {
      retval += i18n("  No hours logged.");
    }
    else
    {
      sum = 0;
      if (justThisTask)
      {
        printWeekTask(taskview->current_item(), taskdaytotals, daytotals,
            (*week), 0, retval);
      }
      else
      {
        for (Task* task= taskview->current_item(); task;
            task= task->nextSibling())
        {
          printWeekTask(task, taskdaytotals, daytotals, (*week), 0, retval);
        }
      }
      retval += line;

      // totals
      sum = 0;
      day = (*week).start();
      for (int i = 0; i < 7; i++)
      {
        daykey = day.toString(QString::fromLatin1("yyyyMMdd"));

        if (daytotals.contains(daykey))
        {
          retval += QString::fromLatin1("%1")
              .arg(formatTime(daytotals[daykey]/60), timeWidth);
          sum += daytotals[daykey];  // in seconds
        }
        else
        {
          buf.fill(' ', timeWidth);
          retval += buf;
        }

        day = day.addDays(1);
      }

      retval += QString::fromLatin1("%1 %2")
        .arg(formatTime(sum/60), totalTimeWidth)
        .arg(i18n("Total"));
    }
  }
  return retval;
}

Week::Week() {}

Week::Week(QDate from)
{
  _start = from;
}

QDate Week::start() const
{
  return _start;
}

QDate Week::end() const
{
  return _start.addDays(7);
}

QString Week::name() const
{
  return QString(i18n("Week of %1"))
    .arg(KGlobal::locale()->formatDate(start()));
}

QValueList<Week> Week::weeksFromDateRange(const QDate& from, const QDate& to)
{
  QDate start;
  QValueList<Week> weeks;

  // The QDate weekNumber() method always puts monday as the first day of the
  // week.
  //
  // Not that it matters here, but week 1 always includes the first Thursday
  // of the year.  For example, January 1, 2000 was a Saturday, so
  // QDate(2000,1,1).weekNumber() returns 52.

  // Since report always shows a full week, we generate a full week of dates,
  // even if from and to are the same date.  The week starts on the day
  // that is set in the locale settings.
  start = from.addDays(
      -((7 - KGlobal::locale()->weekStartDay() + from.dayOfWeek()) % 7));

  for (QDate d = start; d <= to; d = d.addDays(7))
    weeks.append(Week(d));

  return weeks;
}

<|endoftext|>


<commit_before>/*!
  \copyright (c) RDO-Team, 2011
  \file      app/rdo_console/rdo_console_controller.cpp
  \author      (lord.tiran@gmail.com)
  \date      26.10.2011
  \brief       RDO
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
#include <vector>
#include <boost/thread/locks.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "kernel/rdokernel.h"
#include "simulator/service/rdosimwin.h"
#include "simulator/report/build_edit_line_info.h"
#include "app/rdo_console/rdo_console_controller.h"
// --------------------------------------------------------------------------------

using namespace rdo;
using namespace rdo::simulation::report;

#define MUTEXT_PROTECTION(A) boost::lock_guard<boost::mutex> lg_##__LINE__(A);

StudioConsoleController::StudioConsoleController()
	: RDOThread(_T("RDOThreadStudioConsoleController"))
	, m_state(SS_UNDEFINED)
	, m_converted(false)
	, m_buildError(false)
	, m_runtimeError(false)
	, m_convertorError(false)
	, m_exitCode(rdo::simulation::report::EC_OK)
{
	notifies.push_back(RT_REPOSITORY_MODEL_OPEN_ERROR       );
	notifies.push_back(RT_RUNTIME_MODEL_START_BEFORE        );
	notifies.push_back(RT_RUNTIME_MODEL_STOP_AFTER          );
	notifies.push_back(RT_SIMULATOR_PARSE_OK                );
	notifies.push_back(RT_SIMULATOR_PARSE_ERROR             );
	notifies.push_back(RT_SIMULATOR_PARSE_ERROR_SMR         );
	notifies.push_back(RT_SIMULATOR_PARSE_ERROR_SMR_EMPTY   );
	notifies.push_back(RT_SIMULATOR_MODEL_STOP_OK           );
	notifies.push_back(RT_SIMULATOR_MODEL_STOP_RUNTIME_ERROR);
	notifies.push_back(RT_CONVERTOR_NONE                    );
	notifies.push_back(RT_CONVERTOR_OK                      );
	notifies.push_back(RT_CONVERTOR_ERROR                   );

	after_constructor();
}

StudioConsoleController::~StudioConsoleController()
{
}

rbool StudioConsoleController::finished() const
{
	rbool res = true;
	{
		MUTEXT_PROTECTION(m_stateMutex);
		res = (m_state == SS_FINISHED);
	}
	return res;
}

rbool StudioConsoleController::converted() const
{
	return m_converted;
}

rbool StudioConsoleController::simulationSuccessfully()
{
	sendMessage(kernel->simulator(), RT_SIMULATOR_GET_MODEL_EXITCODE, &m_exitCode);
	return m_exitCode == rdo::simulation::report::EC_OK;
}

rbool StudioConsoleController::buildError () const
{
	return m_buildError;
}

rbool StudioConsoleController::runtimeError() const
{
	return m_runtimeError;
}

rbool StudioConsoleController::convertorError() const
{
	return m_convertorError;
}

void StudioConsoleController::getBuildLogList(StringList& list) const
{
	list = m_buildLogList;
}

void StudioConsoleController::proc(REF(RDOThread::RDOMessageInfo) msg)
{
	switch (msg.message)
	{
	case RDOThread::RT_REPOSITORY_MODEL_OPEN_ERROR:
		break;

	case RDOThread::RT_RUNTIME_MODEL_START_BEFORE:
		{
			MUTEXT_PROTECTION(m_stateMutex);
			m_state = SS_IN_PROGRESS;
		}
		break;

	case RDOThread::RT_RUNTIME_MODEL_STOP_AFTER:
		{
			MUTEXT_PROTECTION(m_stateMutex);
			m_state = SS_FINISHED;
		}
		break;

	case RDOThread::RT_SIMULATOR_PARSE_OK:
		break;

	case RDOThread::RT_SIMULATOR_PARSE_ERROR:
		{
			m_buildError = true;
			std::vector<FileMessage> errors;
			sendMessage(kernel->simulator(), RT_SIMULATOR_GET_ERRORS, &errors);
			fillBuildLogList(errors);
		}
		break;

	case RDOThread::RT_SIMULATOR_PARSE_ERROR_SMR:
		break;

	case RDOThread::RT_SIMULATOR_PARSE_ERROR_SMR_EMPTY:
		break;

	case RDOThread::RT_SIMULATOR_MODEL_STOP_OK:
		break;

	case RDOThread::RT_SIMULATOR_MODEL_STOP_RUNTIME_ERROR:
		m_runtimeError = true;
		break;

	case RDOThread::RT_CONVERTOR_NONE:
		m_converted = true;
		m_convertorError = false;
		break;

	case RDOThread::RT_CONVERTOR_OK:
		m_converted = true;
		m_convertorError = false;
		break;

	case RDOThread::RT_CONVERTOR_ERROR:
		m_converted = true;
		m_convertorError = true;
		break;
	}
}

void StudioConsoleController::fillBuildLogList(REF(std::vector<FileMessage>) errors)
{
	STL_FOR_ALL_CONST(errors, it)
	{
		BuildEditLineInfo info(*it);
		tstring line = info.getMessage();
		m_buildLogList.push_back(line);
	}
}
<commit_msg> - g++ warning fixed<commit_after>/*!
  \copyright (c) RDO-Team, 2011
  \file      app/rdo_console/rdo_console_controller.cpp
  \author      (lord.tiran@gmail.com)
  \date      26.10.2011
  \brief       RDO
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
#include <vector>
#include <boost/thread/locks.hpp>
// ----------------------------------------------------------------------- SYNOPSIS
#include "kernel/rdokernel.h"
#include "simulator/service/rdosimwin.h"
#include "simulator/report/build_edit_line_info.h"
#include "app/rdo_console/rdo_console_controller.h"
// --------------------------------------------------------------------------------

using namespace rdo;
using namespace rdo::simulation::report;

#define MUTEXT_PROTECTION(A) boost::lock_guard<boost::mutex> lg_##__LINE__(A);

StudioConsoleController::StudioConsoleController()
	: RDOThread(_T("RDOThreadStudioConsoleController"))
	, m_state(SS_UNDEFINED)
	, m_converted(false)
	, m_buildError(false)
	, m_runtimeError(false)
	, m_convertorError(false)
	, m_exitCode(rdo::simulation::report::EC_OK)
{
	notifies.push_back(RT_REPOSITORY_MODEL_OPEN_ERROR       );
	notifies.push_back(RT_RUNTIME_MODEL_START_BEFORE        );
	notifies.push_back(RT_RUNTIME_MODEL_STOP_AFTER          );
	notifies.push_back(RT_SIMULATOR_PARSE_OK                );
	notifies.push_back(RT_SIMULATOR_PARSE_ERROR             );
	notifies.push_back(RT_SIMULATOR_PARSE_ERROR_SMR         );
	notifies.push_back(RT_SIMULATOR_PARSE_ERROR_SMR_EMPTY   );
	notifies.push_back(RT_SIMULATOR_MODEL_STOP_OK           );
	notifies.push_back(RT_SIMULATOR_MODEL_STOP_RUNTIME_ERROR);
	notifies.push_back(RT_CONVERTOR_NONE                    );
	notifies.push_back(RT_CONVERTOR_OK                      );
	notifies.push_back(RT_CONVERTOR_ERROR                   );

	after_constructor();
}

StudioConsoleController::~StudioConsoleController()
{
}

rbool StudioConsoleController::finished() const
{
	rbool res = true;
	{
		MUTEXT_PROTECTION(m_stateMutex);
		res = (m_state == SS_FINISHED);
	}
	return res;
}

rbool StudioConsoleController::converted() const
{
	return m_converted;
}

rbool StudioConsoleController::simulationSuccessfully()
{
	sendMessage(kernel->simulator(), RT_SIMULATOR_GET_MODEL_EXITCODE, &m_exitCode);
	return m_exitCode == rdo::simulation::report::EC_OK;
}

rbool StudioConsoleController::buildError () const
{
	return m_buildError;
}

rbool StudioConsoleController::runtimeError() const
{
	return m_runtimeError;
}

rbool StudioConsoleController::convertorError() const
{
	return m_convertorError;
}

void StudioConsoleController::getBuildLogList(StringList& list) const
{
	list = m_buildLogList;
}

void StudioConsoleController::proc(REF(RDOThread::RDOMessageInfo) msg)
{
	switch (msg.message)
	{
	case RDOThread::RT_REPOSITORY_MODEL_OPEN_ERROR:
		break;

	case RDOThread::RT_RUNTIME_MODEL_START_BEFORE:
		{
			MUTEXT_PROTECTION(m_stateMutex);
			m_state = SS_IN_PROGRESS;
		}
		break;

	case RDOThread::RT_RUNTIME_MODEL_STOP_AFTER:
		{
			MUTEXT_PROTECTION(m_stateMutex);
			m_state = SS_FINISHED;
		}
		break;

	case RDOThread::RT_SIMULATOR_PARSE_OK:
		break;

	case RDOThread::RT_SIMULATOR_PARSE_ERROR:
		{
			m_buildError = true;
			std::vector<FileMessage> errors;
			sendMessage(kernel->simulator(), RT_SIMULATOR_GET_ERRORS, &errors);
			fillBuildLogList(errors);
		}
		break;

	case RDOThread::RT_SIMULATOR_PARSE_ERROR_SMR:
		break;

	case RDOThread::RT_SIMULATOR_PARSE_ERROR_SMR_EMPTY:
		break;

	case RDOThread::RT_SIMULATOR_MODEL_STOP_OK:
		break;

	case RDOThread::RT_SIMULATOR_MODEL_STOP_RUNTIME_ERROR:
		m_runtimeError = true;
		break;

	case RDOThread::RT_CONVERTOR_NONE:
		m_converted = true;
		m_convertorError = false;
		break;

	case RDOThread::RT_CONVERTOR_OK:
		m_converted = true;
		m_convertorError = false;
		break;

	case RDOThread::RT_CONVERTOR_ERROR:
		m_converted = true;
		m_convertorError = true;
		break;

	default: break;
	}
}

void StudioConsoleController::fillBuildLogList(REF(std::vector<FileMessage>) errors)
{
	STL_FOR_ALL_CONST(errors, it)
	{
		BuildEditLineInfo info(*it);
		tstring line = info.getMessage();
		m_buildLogList.push_back(line);
	}
}
<|endoftext|>


<commit_before>#include "BinaryTree.h"

template<class Node> Tree<Node>::Tree()
{
	root->x = 0;
	root->left = root->right = NULL;
}
template<class Node> Tree<Node>::Tree(Node* node)
{
	root->x = node->x;
	root->left = node->left;
	root->right = node->right;
}
template<class Node> Tree<Node>::Tree(const Tree &node)
{
	root->x = node.root->x;
	root->left = node.root->left;
	root->right = node.root->right;
}
template<class Node> int Tree<Node>::x_()const
{
	return root->x;
}
template<class Node> Node* Tree<Node>::left_()const
{
	return root->left;
}
template<class Node> Node* Tree<Node>::right_()const
{
	return root->right;
}
template<class Node> void Tree<Node>::add(Node* newEl)
{
	Node* El = NULL;
	Node* curEl = root;
	while (curEl != NULL)
	{
		El = curEl;
		if (newEl->x >= curEl->x)
			curEl = curEl->right;
		else
			curEl = curEl->left;
	}
	if (newEl->x >= El->x)
		El->right = newEl;
	else
		El->left = newEl;
}
template<class Node> Tree Tree<Node>::search(int x)
{
	Node* curEl = root;
	while (curEl != NULL)
	{
		if (curEl->x == x)
			return curEl;
		else
		{
			if (x >= curEl->x)
				curEl = curEl->right;
			else
				curEl = curEl->left;
		}
	}
	return nullptr;
}
template<class Node> void Tree<Node>::fIn(string filename)
{
	ifstream fin;
	fin.open(filename);
	Node* newEl = NULL;
	if (!fin.is_open())
		cout << "The file isn't find" << endl;
	if (fin.eof()) return;
	else fin >> root->x;
	while (!fin.eof())
	{
		fin >> newEl->x;
		add(newEl);
	}
	fin.close();
}
template<class Node> void Tree<Node>::fOut(string filename)const
{
	ofstream fout;
	fout.open(filename);
	Out(root);
	fout.close();
}
template<class Node> void Tree<Node>::Out(Node* curEl)const
{
	curEl = root;
	if (curEl != NULL)
	{
		cout << curEl->x << endl;
		Out(curEl->left);
		Out(curEl->right);
	}
}
<commit_msg>Update BinaryTree.cpp<commit_after>#include "BinaryTree.h"

template<class Node> Tree<Node>::Tree()
{
	root->x = 0;
	root->left = root->right = NULL;
}
template<class Node> int Tree<Node>::x_()const
{
	return root->x;
}
template<class Node> Node* Tree<Node>::left_()const
{
	return root->left;
}
template<class Node> Node* Tree<Node>::right_()const
{
	return root->right;
}
template<class Node> void Tree<Node>::add(Node* newEl)
{
	Node* El = NULL;
	Node* curEl = root;
	while (curEl != NULL)
	{
		El = curEl;
		if (newEl->x >= curEl->x)
			curEl = curEl->right;
		else
			curEl = curEl->left;
	}
	if (newEl->x >= El->x)
		El->right = newEl;
	else
		El->left = newEl;
}
template<class Node> Tree Tree<Node>::search(int x)
{
	Node* curEl = root;
	while (curEl != NULL)
	{
		if (curEl->x == x)
			return curEl;
		else
		{
			if (x >= curEl->x)
				curEl = curEl->right;
			else
				curEl = curEl->left;
		}
	}
	return nullptr;
}
template<class Node> void Tree<Node>::fIn(string filename)
{
	ifstream fin;
	fin.open(filename);
	Node* newEl = NULL;
	if (!fin.is_open())
		cout << "The file isn't find" << endl;
	if (fin.eof()) return;
	else fin >> root->x;
	while (!fin.eof())
	{
		fin >> newEl->x;
		add(newEl);
	}
	fin.close();
}
template<class Node> void Tree<Node>::fOut(string filename)const
{
	ofstream fout;
	fout.open(filename);
	Out(root);
	fout.close();
}
template<class Node> void Tree<Node>::Out(Node* curEl)const
{
	curEl = root;
	if (curEl != NULL)
	{
		cout << curEl->x << endl;
		Out(curEl->left);
		Out(curEl->right);
	}
}
<|endoftext|>


<commit_before>#ifndef UNICODE
#define UNICODE
#endif

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <stdlib.h> // for EXIT_ codes

#include "resource.h"

#define WND_CLASS_NAME		L"Zadacha1Sem5"
#define WND_TITLE_NAME		L"Zadacha 1 - Sem 5"

// declaration of Windows Procedure callback
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow) {
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(pCmdLine);

	// initiate window class structure and create the window
	WNDCLASSEX wcex = {};
	wcex.cbSize = sizeof(WNDCLASSEX);
	wcex.style = CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc = (WNDPROC)WindowProc;
	wcex.cbClsExtra = 0;
	wcex.cbWndExtra = 0;
	wcex.hInstance = hInstance;
	wcex.hIcon = 0;
	wcex.hCursor = LoadCursorW(NULL, IDC_ARROW);
	wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
	wcex.lpszMenuName = MAKEINTRESOURCEW(IDM_APP_MENU);
	wcex.lpszClassName = WND_CLASS_NAME;
	wcex.hIconSm = 0;
	if (!::RegisterClassExW(&wcex)) {
		// handle error code and return failure
		return EXIT_FAILURE;
	}

	// rect structure to hold width size and x,y offsets
	RECT rect = { 0, 0, 800, 600 }; // initial values for window size

	// query OS to get system metrics for screen sizes
	rect.left = (::GetSystemMetrics(SM_CXSCREEN) - rect.right) / 2;
	rect.top  = (::GetSystemMetrics(SM_CYSCREEN) - rect.bottom) / 2;

	// create the window
	HWND hWnd = ::CreateWindowExW(0L, WND_CLASS_NAME, WND_TITLE_NAME, WS_OVERLAPPEDWINDOW, rect.left, rect.top, rect.right, rect.bottom, NULL, NULL, hInstance, NULL);
	if (!hWnd) {
		// handle error code and return failure
		return EXIT_FAILURE;
	}

	// make sure our windows is frontmost
	::SetWindowPos(hWnd, HWND_TOPMOST, rect.left, rect.top, rect.right, rect.bottom, SWP_SHOWWINDOW);
	::ShowWindow(hWnd, nCmdShow);
	::UpdateWindow(hWnd);

	// handle messages loop
	BOOL bMsgFlag = 0;
	MSG pMsg = { 0 };
	while ((bMsgFlag = ::GetMessageW(&pMsg, NULL, 0, 0)) != 0) {
		if (bMsgFlag > 0) { // GetMessageW returned no error nor processed WM_QUIT message
			::TranslateMessage(&pMsg);
			::DispatchMessageW(&pMsg);
		} else { // handle error returned by GetMessageW
			// TODO: add a helper function to use GetLastError with FormatMessage for retrieve the error string
		}
	}

	// return whatever code wParam has
	return static_cast<int>(pMsg.wParam);
}

LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
	PAINTSTRUCT ps = { };
	HDC hDc = { };

	// Check any available messages from the queue
	switch (uMsg) {
		case WM_KEYDOWN:
			switch (wParam) {
				case VK_ESCAPE:
					::PostQuitMessage(0);
				break;
			}
		break;

		case WM_PAINT:
			hDc = ::BeginPaint(hWnd, &ps);
			::EndPaint(hWnd, &ps);
		break;

		case WM_COMMAND:
			if (HIWORD(wParam) == 0) { // if high word of wParam is 0, message source is MENU
				switch (LOWORD(wParam)) {
					case IDM_OPERATIONS_EXIT:
						::PostMessageW(hWnd, WM_CLOSE, 0, 0);
					break;
				}
			}
		break;

		case WM_DESTROY:
			::PostQuitMessage(0);
		break;
	}

	return ::DefWindowProc(hWnd, uMsg, wParam, lParam);
}
<commit_msg>quick hack to disable resizing of the window<commit_after>#ifndef UNICODE
#define UNICODE
#endif

#define WIN32_LEAN_AND_MEAN

#include <windows.h>
#include <stdlib.h> // for EXIT_ codes

#include "resource.h"

#define WND_CLASS_NAME		L"Zadacha1Sem5"
#define WND_TITLE_NAME		L"Zadacha 1 - Sem 5"

// declaration of Windows Procedure callback
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);

int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow) {
	UNREFERENCED_PARAMETER(hPrevInstance);
	UNREFERENCED_PARAMETER(pCmdLine);

	// initiate window class structure and create the window
	WNDCLASSEX wcex = {};
	wcex.cbSize = sizeof(WNDCLASSEX);
	wcex.style = CS_HREDRAW | CS_VREDRAW;
	wcex.lpfnWndProc = (WNDPROC)WindowProc;
	wcex.cbClsExtra = 0;
	wcex.cbWndExtra = 0;
	wcex.hInstance = hInstance;
	wcex.hIcon = 0;
	wcex.hCursor = LoadCursorW(NULL, IDC_ARROW);
	wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
	wcex.lpszMenuName = MAKEINTRESOURCEW(IDM_APP_MENU);
	wcex.lpszClassName = WND_CLASS_NAME;
	wcex.hIconSm = 0;
	if (!::RegisterClassExW(&wcex)) {
		// handle error code and return failure
		return EXIT_FAILURE;
	}

	// rect structure to hold width size and x,y offsets
	RECT rect = { 0, 0, 800, 600 }; // initial values for window size

	// query OS to get system metrics for screen sizes
	rect.left = (::GetSystemMetrics(SM_CXSCREEN) - rect.right) / 2;
	rect.top  = (::GetSystemMetrics(SM_CYSCREEN) - rect.bottom) / 2;

	// create the window
	HWND hWnd = ::CreateWindowExW(0L, WND_CLASS_NAME, WND_TITLE_NAME, WS_OVERLAPPEDWINDOW ^ WS_THICKFRAME, rect.left, rect.top, rect.right, rect.bottom, NULL, NULL, hInstance, NULL);
	if (!hWnd) {
		// handle error code and return failure
		return EXIT_FAILURE;
	}

	// make sure our windows is frontmost
	::SetWindowPos(hWnd, HWND_TOPMOST, rect.left, rect.top, rect.right, rect.bottom, SWP_SHOWWINDOW);
	::ShowWindow(hWnd, nCmdShow);
	::UpdateWindow(hWnd);

	// handle messages loop
	BOOL bMsgFlag = 0;
	MSG pMsg = { 0 };
	while ((bMsgFlag = ::GetMessageW(&pMsg, NULL, 0, 0)) != 0) {
		if (bMsgFlag > 0) { // GetMessageW returned no error nor processed WM_QUIT message
			::TranslateMessage(&pMsg);
			::DispatchMessageW(&pMsg);
		} else { // handle error returned by GetMessageW
			// TODO: add a helper function to use GetLastError with FormatMessage for retrieve the error string
		}
	}

	// return whatever code wParam has
	return static_cast<int>(pMsg.wParam);
}

LRESULT CALLBACK WindowProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
	PAINTSTRUCT ps = { };
	HDC hDc = { };

	// Check any available messages from the queue
	switch (uMsg) {
		case WM_KEYDOWN:
			switch (wParam) {
				case VK_ESCAPE:
					::PostQuitMessage(0);
				break;
			}
		break;

		case WM_PAINT:
			hDc = ::BeginPaint(hWnd, &ps);
			::EndPaint(hWnd, &ps);
		break;

		case WM_COMMAND:
			if (HIWORD(wParam) == 0) { // if high word of wParam is 0, message source is MENU
				switch (LOWORD(wParam)) {
					case IDM_OPERATIONS_EXIT:
						::PostMessageW(hWnd, WM_CLOSE, 0, 0);
					break;
				}
			}
		break;

		case WM_DESTROY:
			::PostQuitMessage(0);
		break;
	}

	return ::DefWindowProc(hWnd, uMsg, wParam, lParam);
}
<|endoftext|>


<commit_before>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Ken Zangelin
*/
#include <string>
#include <vector>

#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"

#include "ngsi/ParseData.h"
#include "ngsi/StatusCode.h"
#include "ngsi10/UpdateContextResponse.h"
#include "rest/ConnectionInfo.h"
#include "rest/uriParamNames.h"
#include "serviceRoutines/postUpdateContext.h"
#include "serviceRoutines/deleteIndividualContextEntity.h"

/* ****************************************************************************
*
* deleteIndividualContextEntity -
*
* Corresponding Standard Operation: UpdateContext/DELETE
*
* DELETE /v1/contextEntities/{entityId::id}
*
* Payload In:  None
* Payload Out: StatusCode
*
* URI parameters:
*   - entity::type=TYPE
*   - note that '!exist=entity::type' and 'exist=entity::type' are not supported by convenience operations
*     that use the standard operation UpdateContext as there is no restriction within UpdateContext.
*
* 00. URI params
* 01. Fill in UpdateContextRequest from URL-data + URI params
* 02. Call postUpdateContext standard service routine
* 03. Translate UpdateContextResponse to StatusCode
* 04. If not found, put entity info in details
* 05. Cleanup and return result
*/
std::string deleteIndividualContextEntity
(
  ConnectionInfo*            ciP,
  int                        components,
  std::vector<std::string>&  compV,
  ParseData*                 parseDataP
)
{
  std::string  answer;
  std::string  entityId   = compV[2];
  std::string  entityType = ciP->uriParam[URI_PARAM_ENTITY_TYPE];
  StatusCode   response;

  // 01. Fill in UpdateContextRequest fromURL-data + URI params
  parseDataP->upcr.res.fill(entityId, entityType, "false", "DELETE");

  LM_M(("KZ: Fill in UpdateContextRequest id:'%s', type='%s'", entityId.c_str(), entityType.c_str()));

  // 02. Call postUpdateContext standard service routine
  answer = postUpdateContext(ciP, components, compV, parseDataP);
  LM_M(("KZ: answer: '%s'", answer.c_str()));

  // 03. Translate UpdateContextResponse to StatusCode
  response.fill(parseDataP->upcrs.res);

  // 04. If not found, put entity info in details
  if ((response.code == SccContextElementNotFound) && (response.details == ""))
  {
    response.details = entityId;
  }

  // 05. Cleanup and return result
  answer = response.render(ciP->outFormat, "", false, false);
  response.release();
  return answer;
}
<commit_msg>Removed two LM_M<commit_after>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Ken Zangelin
*/
#include <string>
#include <vector>

#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"

#include "ngsi/ParseData.h"
#include "ngsi/StatusCode.h"
#include "ngsi10/UpdateContextResponse.h"
#include "rest/ConnectionInfo.h"
#include "rest/uriParamNames.h"
#include "serviceRoutines/postUpdateContext.h"
#include "serviceRoutines/deleteIndividualContextEntity.h"

/* ****************************************************************************
*
* deleteIndividualContextEntity -
*
* Corresponding Standard Operation: UpdateContext/DELETE
*
* DELETE /v1/contextEntities/{entityId::id}
*
* Payload In:  None
* Payload Out: StatusCode
*
* URI parameters:
*   - entity::type=TYPE
*   - note that '!exist=entity::type' and 'exist=entity::type' are not supported by convenience operations
*     that use the standard operation UpdateContext as there is no restriction within UpdateContext.
*
* 00. URI params
* 01. Fill in UpdateContextRequest from URL-data + URI params
* 02. Call postUpdateContext standard service routine
* 03. Translate UpdateContextResponse to StatusCode
* 04. If not found, put entity info in details
* 05. Cleanup and return result
*/
std::string deleteIndividualContextEntity
(
  ConnectionInfo*            ciP,
  int                        components,
  std::vector<std::string>&  compV,
  ParseData*                 parseDataP
)
{
  std::string  answer;
  std::string  entityId   = compV[2];
  std::string  entityType = ciP->uriParam[URI_PARAM_ENTITY_TYPE];
  StatusCode   response;

  // 01. Fill in UpdateContextRequest fromURL-data + URI params
  parseDataP->upcr.res.fill(entityId, entityType, "false", "DELETE");

  // 02. Call postUpdateContext standard service routine
  answer = postUpdateContext(ciP, components, compV, parseDataP);

  // 03. Translate UpdateContextResponse to StatusCode
  response.fill(parseDataP->upcrs.res);

  // 04. If not found, put entity info in details
  if ((response.code == SccContextElementNotFound) && (response.details == ""))
  {
    response.details = entityId;
  }

  // 05. Cleanup and return result
  answer = response.render(ciP->outFormat, "", false, false);
  response.release();
  return answer;
}
<|endoftext|>


<commit_before>#ifndef _GRAPH_HPP_
#define _GRAPH_HPP_
#include "NodeA.hpp"
#include "NodeV.hpp"

template<class T, class C>
class Graph
{
    private:
        NodeV<T,C> graph;
    public:
        Graph();
        ~Graph();

        bool isNull();

};

#endif<commit_msg>insert added<commit_after>#ifndef _GRAPH_HPP_
#define _GRAPH_HPP_
#include "NodeA.hpp"
#include "NodeV.hpp"

template<class T, class C>
class Graph
{
    private:
        NodeV<T,C> graph;
    public:
        Graph() : graph(NULL) { };
        ~Graph();

        bool isNull() const { return graph == NULL; };
        void insertV(T);
        void insertE(T, T, C);

};

#endif<|endoftext|>


<commit_before>// $Id$

#include <list>
#include "TranslationOptionCollectionLattice.h"
#include "ConfusionNet.h"
#include "WordLattice.h"
#include "DecodeGraph.h"
#include "DecodeStepTranslation.h"
#include "DecodeStepGeneration.h"
#include "FactorCollection.h"
#include "FF/InputFeature.h"
#include "TranslationModel/PhraseDictionaryTreeAdaptor.h"
#include "util/exception.hh"

using namespace std;

namespace Moses
{

/** constructor; just initialize the base class */
TranslationOptionCollectionLattice::TranslationOptionCollectionLattice(
  const WordLattice &input
  , size_t maxNoTransOptPerCoverage, float translationOptionThreshold)
  : TranslationOptionCollection(input, maxNoTransOptPerCoverage, translationOptionThreshold)
{
  UTIL_THROW_IF2(StaticData::Instance().GetUseLegacyPT(),
		  "Not for models using the legqacy binary phrase table");

  const InputFeature &inputFeature = InputFeature::Instance();
  UTIL_THROW_IF2(&inputFeature == NULL, "Input feature must be specified");

  size_t maxPhraseLength = StaticData::Instance().GetMaxPhraseLength();
  size_t size = input.GetSize();

  // 1-word phrases
  for (size_t startPos = 0; startPos < size; ++startPos) {

    const std::vector<size_t> &nextNodes = input.GetNextNodes(startPos);

    WordsRange range(startPos, startPos);
    const NonTerminalSet &labels = input.GetLabelSet(startPos, startPos);

    const ConfusionNet::Column &col = input.GetColumn(startPos);
    for (size_t i = 0; i < col.size(); ++i) {
      const Word &word = col[i].first;
      UTIL_THROW_IF2(word.IsEpsilon(), "Epsilon not supported");

      Phrase subphrase;
      subphrase.AddWord(word);

      const ScorePair &scores = col[i].second;
      ScorePair *inputScore = new ScorePair(scores);

      InputPath *path = new InputPath(subphrase, labels, range, NULL, inputScore);

      size_t nextNode = nextNodes[i];
      path->SetNextNode(nextNode);

      m_inputPathQueue.push_back(path);
    }
  }

  // iteratively extend all paths
    for (size_t endPos = 1; endPos < size; ++endPos) {
      const std::vector<size_t> &nextNodes = input.GetNextNodes(endPos);

      // loop thru every previous paths
      size_t numPrevPaths = m_inputPathQueue.size();

      for (size_t i = 0; i < numPrevPaths; ++i) {
        //for (size_t pathInd = 0; pathInd < prevPaths.size(); ++pathInd) {
        const InputPath &prevPath = *m_inputPathQueue[i];

        size_t nextNode = prevPath.GetNextNode();
        if (prevPath.GetWordsRange().GetEndPos() + nextNode != endPos) {
        	continue;
        }

        size_t startPos = prevPath.GetWordsRange().GetStartPos();

        if (endPos - startPos + 1 > maxPhraseLength) {
        	continue;
        }

        WordsRange range(startPos, endPos);
        const NonTerminalSet &labels = input.GetLabelSet(startPos, endPos);

        const Phrase &prevPhrase = prevPath.GetPhrase();
        const ScorePair *prevInputScore = prevPath.GetInputScore();
        UTIL_THROW_IF2(prevInputScore == NULL,
        		"Null previous score");

        // loop thru every word at this position
        const ConfusionNet::Column &col = input.GetColumn(endPos);

        for (size_t i = 0; i < col.size(); ++i) {
          const Word &word = col[i].first;
          Phrase subphrase(prevPhrase);
          subphrase.AddWord(word);

          const ScorePair &scores = col[i].second;
          ScorePair *inputScore = new ScorePair(*prevInputScore);
          inputScore->PlusEquals(scores);

          InputPath *path = new InputPath(subphrase, labels, range, &prevPath, inputScore);

          size_t nextNode = nextNodes[i];
          path->SetNextNode(nextNode);

          m_inputPathQueue.push_back(path);
        } // for (size_t i = 0; i < col.size(); ++i) {

      } // for (size_t i = 0; i < numPrevPaths; ++i) {
    }
}

void TranslationOptionCollectionLattice::CreateTranslationOptions()
{
  GetTargetPhraseCollectionBatch();

  VERBOSE(2,"Translation Option Collection\n " << *this << endl);
  const vector <DecodeGraph*> &decodeGraphs = StaticData::Instance().GetDecodeGraphs();
  UTIL_THROW_IF2(decodeGraphs.size() != 1, "Multiple decoder graphs not supported yet");
  const DecodeGraph &decodeGraph = *decodeGraphs[0];
  UTIL_THROW_IF2(decodeGraph.GetSize() != 1, "Factored decomposition not supported yet");

  const DecodeStep &decodeStep = **decodeGraph.begin();
  const PhraseDictionary &phraseDictionary = *decodeStep.GetPhraseDictionaryFeature();

  for (size_t i = 0; i < m_inputPathQueue.size(); ++i) {
    const InputPath &path = *m_inputPathQueue[i];

    const TargetPhraseCollection *tpColl = path.GetTargetPhrases(phraseDictionary);
    const WordsRange &range = path.GetWordsRange();

    if (tpColl && tpColl->GetSize()) {
    	TargetPhraseCollection::const_iterator iter;
    	for (iter = tpColl->begin(); iter != tpColl->end(); ++iter) {
    		const TargetPhrase &tp = **iter;
    		TranslationOption *transOpt = new TranslationOption(range, tp);
    		transOpt->SetInputPath(path);
    		transOpt->Evaluate(m_source);

    		Add(transOpt);
    	}
    }
    else if (path.GetPhrase().GetSize() == 1) {
    	// unknown word processing
    	ProcessOneUnknownWord(path, path.GetWordsRange().GetEndPos(), 1, path.GetInputScore());
    }
  }

  // Prune
  Prune();

  Sort();

  // future score matrix
  CalcFutureScore();

  // Cached lex reodering costs
  CacheLexReordering();

}

void TranslationOptionCollectionLattice::ProcessUnknownWord(size_t sourcePos)
{
	UTIL_THROW(util::Exception, "ProcessUnknownWord() not implemented for lattice");
}

void TranslationOptionCollectionLattice::CreateTranslationOptionsForRange(const DecodeGraph &decodeStepList
      , size_t startPosition
      , size_t endPosition
      , bool adhereTableLimit
      , size_t graphInd)
{
	UTIL_THROW(util::Exception, "CreateTranslationOptionsForRange() not implemented for lattice");
}

} // namespace

<commit_msg>bug in lattice decoding. Some arcs can span more than 1 node<commit_after>// $Id$

#include <list>
#include "TranslationOptionCollectionLattice.h"
#include "ConfusionNet.h"
#include "WordLattice.h"
#include "DecodeGraph.h"
#include "DecodeStepTranslation.h"
#include "DecodeStepGeneration.h"
#include "FactorCollection.h"
#include "FF/InputFeature.h"
#include "TranslationModel/PhraseDictionaryTreeAdaptor.h"
#include "util/exception.hh"

using namespace std;

namespace Moses
{

/** constructor; just initialize the base class */
TranslationOptionCollectionLattice::TranslationOptionCollectionLattice(
  const WordLattice &input
  , size_t maxNoTransOptPerCoverage, float translationOptionThreshold)
  : TranslationOptionCollection(input, maxNoTransOptPerCoverage, translationOptionThreshold)
{
  UTIL_THROW_IF2(StaticData::Instance().GetUseLegacyPT(),
		  "Not for models using the legqacy binary phrase table");

  const InputFeature &inputFeature = InputFeature::Instance();
  UTIL_THROW_IF2(&inputFeature == NULL, "Input feature must be specified");

  size_t maxPhraseLength = StaticData::Instance().GetMaxPhraseLength();
  size_t size = input.GetSize();

  // 1-word phrases
  for (size_t startPos = 0; startPos < size; ++startPos) {

    const std::vector<size_t> &nextNodes = input.GetNextNodes(startPos);

    const ConfusionNet::Column &col = input.GetColumn(startPos);
    for (size_t i = 0; i < col.size(); ++i) {
      const Word &word = col[i].first;
      UTIL_THROW_IF2(word.IsEpsilon(), "Epsilon not supported");

      size_t nextNode = nextNodes[i];
      size_t endPos = startPos + nextNode - 1;

      WordsRange range(startPos, endPos);
      const NonTerminalSet &labels = input.GetLabelSet(startPos, endPos);

      Phrase subphrase;
      subphrase.AddWord(word);

      const ScorePair &scores = col[i].second;
      ScorePair *inputScore = new ScorePair(scores);

      InputPath *path = new InputPath(subphrase, labels, range, NULL, inputScore);

      path->SetNextNode(nextNode);
      m_inputPathQueue.push_back(path);
    }
  }

  // iteratively extend all paths
    for (size_t endPos = 1; endPos < size; ++endPos) {
      const std::vector<size_t> &nextNodes = input.GetNextNodes(endPos);

      // loop thru every previous paths
      size_t numPrevPaths = m_inputPathQueue.size();

      for (size_t i = 0; i < numPrevPaths; ++i) {
        //for (size_t pathInd = 0; pathInd < prevPaths.size(); ++pathInd) {
        const InputPath &prevPath = *m_inputPathQueue[i];

        size_t nextNode = prevPath.GetNextNode();
        if (prevPath.GetWordsRange().GetEndPos() + nextNode != endPos) {
        	continue;
        }

        size_t startPos = prevPath.GetWordsRange().GetStartPos();

        if (endPos - startPos + 1 > maxPhraseLength) {
        	continue;
        }

        WordsRange range(startPos, endPos);
        const NonTerminalSet &labels = input.GetLabelSet(startPos, endPos);

        const Phrase &prevPhrase = prevPath.GetPhrase();
        const ScorePair *prevInputScore = prevPath.GetInputScore();
        UTIL_THROW_IF2(prevInputScore == NULL,
        		"Null previous score");

        // loop thru every word at this position
        const ConfusionNet::Column &col = input.GetColumn(endPos);

        for (size_t i = 0; i < col.size(); ++i) {
          const Word &word = col[i].first;
          Phrase subphrase(prevPhrase);
          subphrase.AddWord(word);

          const ScorePair &scores = col[i].second;
          ScorePair *inputScore = new ScorePair(*prevInputScore);
          inputScore->PlusEquals(scores);

          InputPath *path = new InputPath(subphrase, labels, range, &prevPath, inputScore);

          size_t nextNode = nextNodes[i];
          path->SetNextNode(nextNode);

          m_inputPathQueue.push_back(path);
        } // for (size_t i = 0; i < col.size(); ++i) {

      } // for (size_t i = 0; i < numPrevPaths; ++i) {
    }
}

void TranslationOptionCollectionLattice::CreateTranslationOptions()
{
  GetTargetPhraseCollectionBatch();

  VERBOSE(2,"Translation Option Collection\n " << *this << endl);
  const vector <DecodeGraph*> &decodeGraphs = StaticData::Instance().GetDecodeGraphs();
  UTIL_THROW_IF2(decodeGraphs.size() != 1, "Multiple decoder graphs not supported yet");
  const DecodeGraph &decodeGraph = *decodeGraphs[0];
  UTIL_THROW_IF2(decodeGraph.GetSize() != 1, "Factored decomposition not supported yet");

  const DecodeStep &decodeStep = **decodeGraph.begin();
  const PhraseDictionary &phraseDictionary = *decodeStep.GetPhraseDictionaryFeature();

  for (size_t i = 0; i < m_inputPathQueue.size(); ++i) {
    const InputPath &path = *m_inputPathQueue[i];

    const TargetPhraseCollection *tpColl = path.GetTargetPhrases(phraseDictionary);
    const WordsRange &range = path.GetWordsRange();

    if (tpColl && tpColl->GetSize()) {
		TargetPhraseCollection::const_iterator iter;
    	for (iter = tpColl->begin(); iter != tpColl->end(); ++iter) {
    		const TargetPhrase &tp = **iter;
    		TranslationOption *transOpt = new TranslationOption(range, tp);
    		transOpt->SetInputPath(path);
    		transOpt->Evaluate(m_source);

    		Add(transOpt);
    	}
    }
    else if (path.GetPhrase().GetSize() == 1) {
    	// unknown word processing
    	ProcessOneUnknownWord(path, path.GetWordsRange().GetEndPos(), 1, path.GetInputScore());
    }
  }

  // Prune
  Prune();

  Sort();

  // future score matrix
  CalcFutureScore();

  // Cached lex reodering costs
  CacheLexReordering();

}

void TranslationOptionCollectionLattice::ProcessUnknownWord(size_t sourcePos)
{
	UTIL_THROW(util::Exception, "ProcessUnknownWord() not implemented for lattice");
}

void TranslationOptionCollectionLattice::CreateTranslationOptionsForRange(const DecodeGraph &decodeStepList
      , size_t startPosition
      , size_t endPosition
      , bool adhereTableLimit
      , size_t graphInd)
{
	UTIL_THROW(util::Exception, "CreateTranslationOptionsForRange() not implemented for lattice");
}

} // namespace

<|endoftext|>


<commit_before>// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license.

#pragma once

#include <string>

namespace Pomdog {

struct GamepadCapabilities final {
    std::string Name;

    int ButtonCount = 0;

    int ThumbStickCount = 0;

    bool HasLeftXThumbStick = false;
    bool HasLeftYThumbStick = false;
    bool HasRightXThumbStick = false;
    bool HasRightYThumbStick = false;
};

} // namespace Pomdog
<commit_msg>Include the device's UUID to the gamepad capabilities<commit_after>// Copyright (c) 2013-2018 mogemimi. Distributed under the MIT license.

#pragma once

#include "Pomdog/Input/GamepadUUID.hpp"
#include <string>

namespace Pomdog {

struct GamepadCapabilities final {
    GamepadUUID DeviceUUID;
    std::string Name;

    bool HasAButton = false;
    bool HasBButton = false;
    bool HasXButton = false;
    bool HasYButton = false;
    bool HasLeftShoulderButton = false;
    bool HasRightShoulderButton = false;
    bool HasLeftMenuButton = false;
    bool HasRightMenuButton = false;
    bool HasLeftStickButton = false;
    bool HasRightStickButton = false;
    bool HasGuideButton = false;
    bool HasExtra1Button = false;
    bool HasExtra2Button = false;

    bool HasLeftTrigger = false;
    bool HasRightTrigger = false;

    bool HasLeftXThumbStick = false;
    bool HasLeftYThumbStick = false;
    bool HasRightXThumbStick = false;
    bool HasRightYThumbStick = false;
};

} // namespace Pomdog
<|endoftext|>


<commit_before>#ifndef AFFINE_INVARIANT_FEATURES_TARGET
#define AFFINE_INVARIANT_FEATURES_TARGET

#include <algorithm>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <string>
#include <vector>

#include <ros/package.h>

#include <affine_invariant_features/cv_serializable.hpp>

#include <boost/filesystem.hpp>

#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>

#include <openssl/md5.h>

namespace affine_invariant_features {

struct TargetData {
public:
  cv::Mat image;
  cv::Mat mask;
};

struct TargetDescription : public CvSerializable {
public:
  TargetDescription() {}

  virtual ~TargetDescription() {}

  TargetData toData(const bool check_md5 = false) const {
    TargetData data;

    const std::string resolved_path(resolvePath(package, path));
    if (resolved_path.empty()) {
      return data;
    }

    if (check_md5) {
      if (md5.empty() || md5 != generateMD5(resolved_path)) {
        return data;
      }
    }

    data.image = cv::imread(resolved_path);
    if (data.image.empty()) {
      return data;
    }

    if (!contour.empty()) {
      data.mask = cv::Mat::zeros(data.image.size(), CV_8UC1);
      cv::fillPoly(data.mask, std::vector< std::vector< cv::Point > >(1, contour), 255);
    }

    return data;
  }

  virtual void read(const cv::FileNode &fn) {
    fn["package"] >> package;
    fn["path"] >> path;
    fn["md5"] >> md5;
    const cv::FileNode contour_node(fn["contour"]);
    const std::size_t contour_size(contour_node.isSeq() ? contour_node.size() : 0);
    contour.resize(contour_size);
    for (std::size_t i = 0; i < contour_size; ++i) {
      contour_node[i] >> contour[i];
    }
  }

  virtual void write(cv::FileStorage &fs) const {
    fs << "{";
    fs << "package" << package;
    fs << "path" << path;
    fs << "md5" << md5;
    fs << "contour";
    fs << "[:";
    for (std::vector< cv::Point >::const_iterator point = contour.begin(); point != contour.end();
         ++point) {
      fs << *point;
    }
    fs << "]";
    fs << "}";
  }

  virtual std::string getDefaultName() const { return "TargetDescription"; }

public:
  static std::string resolvePath(const std::string &package, const std::string &path) {
    namespace bf = boost::filesystem;
    namespace rp = ros::package;

    const bf::path root_path(rp::getPath(package));
    const bf::path leaf_path(path);
    if (root_path.empty() || leaf_path.empty() || leaf_path.is_absolute()) {
      return leaf_path.string();
    }
    return (root_path / leaf_path).string();
  }

  static std::string generateMD5(const std::string &path) {
    // open the file path as a binary file
    std::ifstream ifs(path.c_str(), std::ios::binary);
    if (!ifs) {
      return std::string();
    }

    // calculate the MD5 hash using openSSL library
    unsigned char md5[MD5_DIGEST_LENGTH];
    {
      MD5_CTX ctx;
      MD5_Init(&ctx);
      char buf[4096];
      while (ifs.read(buf, 4096) || ifs.gcount()) {
        MD5_Update(&ctx, buf, ifs.gcount());
      }
      MD5_Final(md5, &ctx);
    }

    // stringaze the MD5 hash
    std::ostringstream oss;
    for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
      oss << std::hex << std::setw(2) << std::setfill('0') << static_cast< int >(md5[i]);
    }

    return oss.str();
  }

public:
  std::string package;
  std::string path;
  std::string md5;
  std::vector< cv::Point > contour;
};
}

#endif<commit_msg>avoid to get a ros package with an empty name<commit_after>#ifndef AFFINE_INVARIANT_FEATURES_TARGET
#define AFFINE_INVARIANT_FEATURES_TARGET

#include <algorithm>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <string>
#include <vector>

#include <ros/package.h>

#include <affine_invariant_features/cv_serializable.hpp>

#include <boost/filesystem.hpp>

#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>

#include <openssl/md5.h>

namespace affine_invariant_features {

struct TargetData {
public:
  cv::Mat image;
  cv::Mat mask;
};

struct TargetDescription : public CvSerializable {
public:
  TargetDescription() {}

  virtual ~TargetDescription() {}

  TargetData toData(const bool check_md5 = false) const {
    TargetData data;

    const std::string resolved_path(resolvePath(package, path));
    if (resolved_path.empty()) {
      return data;
    }

    if (check_md5) {
      if (md5.empty() || md5 != generateMD5(resolved_path)) {
        return data;
      }
    }

    data.image = cv::imread(resolved_path);
    if (data.image.empty()) {
      return data;
    }

    if (!contour.empty()) {
      data.mask = cv::Mat::zeros(data.image.size(), CV_8UC1);
      cv::fillPoly(data.mask, std::vector< std::vector< cv::Point > >(1, contour), 255);
    }

    return data;
  }

  virtual void read(const cv::FileNode &fn) {
    fn["package"] >> package;
    fn["path"] >> path;
    fn["md5"] >> md5;
    const cv::FileNode contour_node(fn["contour"]);
    const std::size_t contour_size(contour_node.isSeq() ? contour_node.size() : 0);
    contour.resize(contour_size);
    for (std::size_t i = 0; i < contour_size; ++i) {
      contour_node[i] >> contour[i];
    }
  }

  virtual void write(cv::FileStorage &fs) const {
    fs << "{";
    fs << "package" << package;
    fs << "path" << path;
    fs << "md5" << md5;
    fs << "contour";
    fs << "[:";
    for (std::vector< cv::Point >::const_iterator point = contour.begin(); point != contour.end();
         ++point) {
      fs << *point;
    }
    fs << "]";
    fs << "}";
  }

  virtual std::string getDefaultName() const { return "TargetDescription"; }

public:
  static std::string resolvePath(const std::string &package, const std::string &path) {
    namespace bf = boost::filesystem;
    namespace rp = ros::package;

    const bf::path root_path(package.empty() ? std::string() : rp::getPath(package));
    const bf::path leaf_path(path);
    if (root_path.empty() || leaf_path.empty() || leaf_path.is_absolute()) {
      return leaf_path.string();
    }
    return (root_path / leaf_path).string();
  }

  static std::string generateMD5(const std::string &path) {
    // open the file path as a binary file
    std::ifstream ifs(path.c_str(), std::ios::binary);
    if (!ifs) {
      return std::string();
    }

    // calculate the MD5 hash using openSSL library
    unsigned char md5[MD5_DIGEST_LENGTH];
    {
      MD5_CTX ctx;
      MD5_Init(&ctx);
      char buf[4096];
      while (ifs.read(buf, 4096) || ifs.gcount()) {
        MD5_Update(&ctx, buf, ifs.gcount());
      }
      MD5_Final(md5, &ctx);
    }

    // stringaze the MD5 hash
    std::ostringstream oss;
    for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
      oss << std::hex << std::setw(2) << std::setfill('0') << static_cast< int >(md5[i]);
    }

    return oss.str();
  }

public:
  std::string package;
  std::string path;
  std::string md5;
  std::vector< cv::Point > contour;
};
}

#endif<|endoftext|>