<commit_before>/*
 -----------------------------------------------------------------------------
 This source file is part of OGRE
 (Object-oriented Graphics Rendering Engine)
 For the latest info, see http://www.ogre3d.org/

 Copyright (c) 2000-2014 Torus Knot Software Ltd

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 -----------------------------------------------------------------------------
 */
#include "OgreStableHeaders.h"

#if OGRE_NO_ZIP_ARCHIVE == 0

#include "OgreDeflate.h"
#include "OgreException.h"
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS || OGRE_PLATFORM == OGRE_PLATFORM_APPLE
#include "macUtils.h"
#endif

#include <zlib.h>

namespace Ogre
{
    // memory implementations
    void* OgreZalloc(void* opaque, unsigned int items, unsigned int size)
    {
        return OGRE_MALLOC(items * size, MEMCATEGORY_GENERAL);
    }
    void OgreZfree(void* opaque, void* address)
    {
        OGRE_FREE(address, MEMCATEGORY_GENERAL);
    }
    #define OGRE_DEFLATE_TMP_SIZE 16384
    //---------------------------------------------------------------------
    DeflateStream::DeflateStream(const DataStreamPtr& compressedStream, const String& tmpFileName, size_t avail_in)
    : DataStream(compressedStream->getAccessMode())
    , mCompressedStream(compressedStream)
    , mTempFileName(tmpFileName)
    , mZStream(0)
    , mCurrentPos(0)
    , mAvailIn(avail_in)
    , mTmp(0)
    , mIsCompressedValid(true)
    {
        init();
    }
    //---------------------------------------------------------------------
    DeflateStream::DeflateStream(const String& name, const DataStreamPtr& compressedStream, const String& tmpFileName, size_t avail_in)
    : DataStream(name, compressedStream->getAccessMode())
    , mCompressedStream(compressedStream)
    , mTempFileName(tmpFileName)
    , mZStream(0)
    , mCurrentPos(0)
    , mAvailIn(avail_in)
    , mTmp(0)
    , mIsCompressedValid(true)
    {
        init();
    }
    //---------------------------------------------------------------------
    size_t DeflateStream::getAvailInForSinglePass()
    {
        size_t ret = OGRE_DEFLATE_TMP_SIZE;

        // if we are doing particial-uncompressing
        if(mAvailIn>0)
        {
            if(mAvailIn<ret)
                ret = mAvailIn;
            mAvailIn -= ret;
        }

        return ret;
    }
    //---------------------------------------------------------------------
    void DeflateStream::init()
    {
        mZStream = OGRE_ALLOC_T(z_stream, 1, MEMCATEGORY_GENERAL);
        mZStream->zalloc = OgreZalloc;
        mZStream->zfree = OgreZfree;

        if (getAccessMode() == READ)
        {
            mTmp = (unsigned char*)OGRE_MALLOC(OGRE_DEFLATE_TMP_SIZE, MEMCATEGORY_GENERAL);
            size_t restorePoint = mCompressedStream->tell();
            // read early chunk
            mZStream->next_in = mTmp;
            mZStream->avail_in = static_cast<uint>(mCompressedStream->read(mTmp, getAvailInForSinglePass()));

            if (inflateInit(mZStream) != Z_OK)
            {
                mIsCompressedValid = false;
            }
            else
                mIsCompressedValid = true;

            if (mIsCompressedValid)
            {
                // in fact, inflateInit on some implementations doesn't try to read
                // anything. We need to at least read something to test
                Bytef testOut[4];
                size_t savedIn = mZStream->avail_in;
                mZStream->avail_out = 4;
                mZStream->next_out = testOut;
                if (inflate(mZStream, Z_SYNC_FLUSH) != Z_OK)
                    mIsCompressedValid = false;
                // restore for reading
                mZStream->avail_in = static_cast<uint>(savedIn);
                mZStream->next_in = mTmp;

                inflateReset(mZStream);
            }

            if (!mIsCompressedValid)
            {
                // Not compressed data!
                // Fail gracefully, fall back on reading the underlying stream direct
                destroy();
                mCompressedStream->seek(restorePoint);
            }
        }
        else
        {
            if(mTempFileName.empty())
            {
                // Write to temp file
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
                char* tmpname = _tempnam(".", "ogre");
                if (!tmpname)
                {
                    // Having no file name here will cause various problems later.
                    OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Temporary file name generation failed.", "DeflateStream::init");
                }
                else
                {
                    mTempFileName = tmpname;
                    free(tmpname);
                }
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS || OGRE_PLATFORM == OGRE_PLATFORM_APPLE
                mTempFileName = macTempFileName();
#else
                char tmpname[L_tmpnam];
                if (!tmpnam(tmpname))
                    OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Temporary file name generation failed.", "DeflateStream::init");

                mTempFileName = tmpname;
#endif
            }

            std::fstream *f = OGRE_NEW_T(std::fstream, MEMCATEGORY_GENERAL)();
            f->open(mTempFileName.c_str(), std::ios::binary | std::ios::out);
            mTmpWriteStream = DataStreamPtr(OGRE_NEW FileStreamDataStream(f));

        }

    }
    //---------------------------------------------------------------------
    void DeflateStream::destroy()
    {
        if (getAccessMode() == READ)
            inflateEnd(mZStream);

        OGRE_FREE(mZStream, MEMCATEGORY_GENERAL);
        mZStream = 0;
        OGRE_FREE(mTmp, MEMCATEGORY_GENERAL);
        mTmp = 0;
    }
    //---------------------------------------------------------------------
    DeflateStream::~DeflateStream()
    {
        close();
        destroy();
    }
    //---------------------------------------------------------------------
    size_t DeflateStream::read(void* buf, size_t count)
    {
        if (!mIsCompressedValid)
        {
            return mCompressedStream->read(buf, count);
        }

        if (getAccessMode() & WRITE)
        {
            return mTmpWriteStream->read(buf, count);
        }
        else
        {

            size_t restorePoint = mCompressedStream->tell();
            // read from cache first
            size_t cachereads = mReadCache.read(buf, count);

            size_t newReadUncompressed = 0;

            if (cachereads < count)
            {
                mZStream->avail_out = static_cast<uint>(count - cachereads);
                mZStream->next_out = (Bytef*)buf + cachereads;

                while (mZStream->avail_out)
                {
                    // Pull next chunk of compressed data from the underlying stream
                    if (!mZStream->avail_in && !mCompressedStream->eof())
                    {
                        mZStream->avail_in = static_cast<uint>(mCompressedStream->read(mTmp, getAvailInForSinglePass()));
                        mZStream->next_in = mTmp;
                    }

                    if (mZStream->avail_in)
                    {
                        int availpre = mZStream->avail_out;
                        int status = inflate(mZStream, Z_SYNC_FLUSH);
                        size_t readUncompressed = availpre - mZStream->avail_out;
                        newReadUncompressed += readUncompressed;
                        if (status != Z_OK)
                        {
                            // End of data, or error
                            if (status != Z_STREAM_END)
                            {
                                mCompressedStream->seek(restorePoint);
                                OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
                                            "Error in compressed stream",
                                            "DeflateStrea::read");
                            }
                            else
                            {
                                // back up the stream so that it can be used from the end onwards
                                long unusedCompressed = mZStream->avail_in;
                                mCompressedStream->skip(-unusedCompressed);
                            }

                            break;
                        }
                    }
                }
            }

            // Cache the last bytes read
            mReadCache.cacheData((char*)buf + cachereads, newReadUncompressed);

            mCurrentPos += newReadUncompressed + cachereads;

            return newReadUncompressed + cachereads;
        }
    }
    //---------------------------------------------------------------------
    size_t DeflateStream::write(const void* buf, size_t count)
    {
        if ((getAccessMode() & WRITE) == 0)
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
                        "Not a writable stream", "DeflateStream::write");

        return mTmpWriteStream->write(buf, count);
    }
    //---------------------------------------------------------------------
    void DeflateStream::compressFinal()
    {
        // Close temp stream
        mTmpWriteStream->close();

        // Copy & compress
        // We do this rather than compress directly because some code seeks
        // around while writing (e.g. to update size blocks) which is not
        // possible when compressing on the fly

        int ret, flush;
        char in[OGRE_DEFLATE_TMP_SIZE];
        char out[OGRE_DEFLATE_TMP_SIZE];

        if (deflateInit(mZStream, Z_DEFAULT_COMPRESSION) != Z_OK)
        {
            destroy();
            OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
                        "Error initialising deflate compressed stream!",
                        "DeflateStream::init");
        }

        std::ifstream inFile;
        inFile.open(mTempFileName.c_str(), std::ios::in | std::ios::binary);

        do
        {
            inFile.read(in, OGRE_DEFLATE_TMP_SIZE);
            mZStream->avail_in = (uInt)inFile.gcount();
            if (inFile.bad())
            {
                deflateEnd(mZStream);
                OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
                            "Error reading temp uncompressed stream!",
                            "DeflateStream::init");
            }
            flush = inFile.eof() ? Z_FINISH : Z_NO_FLUSH;
            mZStream->next_in = (Bytef*)in;

            /* run deflate() on input until output buffer not full, finish
             compression if all of source has been read in */
            do
            {
                mZStream->avail_out = OGRE_DEFLATE_TMP_SIZE;
                mZStream->next_out = (Bytef*)out;
                ret = deflate(mZStream, flush);    /* no bad return value */
                assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
                size_t compressed = OGRE_DEFLATE_TMP_SIZE - mZStream->avail_out;
                mCompressedStream->write(out, compressed);
            } while (mZStream->avail_out == 0);
            assert(mZStream->avail_in == 0);     /* all input will be used */

            /* done when last data in file processed */
        } while (flush != Z_FINISH);
        assert(ret == Z_STREAM_END);        /* stream will be complete */
                (void)ret;
        deflateEnd(mZStream);

        inFile.close();
        remove(mTempFileName.c_str());

    }
    //---------------------------------------------------------------------
    void DeflateStream::skip(long count)
    {
        if (!mIsCompressedValid)
        {
            mCompressedStream->skip(count);
            return;
        }

        if (getAccessMode() & WRITE)
        {
            mTmpWriteStream->skip(count);
        }
        else
        {
            if (count > 0)
            {
                if (!mReadCache.ff(count))
                {
                    OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
                                "You can only skip within the cache range in a deflate stream.",
                                "DeflateStream::skip");
                }
            }
            else if (count < 0)
            {
                if (!mReadCache.rewind((size_t)(-count)))
                {
                    OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
                                "You can only skip within the cache range in a deflate stream.",
                                "DeflateStream::skip");
                }
            }
        }
        mCurrentPos = static_cast<size_t>(static_cast<long>(mCurrentPos) + count);

    }
    //---------------------------------------------------------------------
    void DeflateStream::seek( size_t pos )
    {
        if (!mIsCompressedValid)
        {
            mCompressedStream->seek(pos);
            return;
        }
        if (getAccessMode() & WRITE)
        {
            mTmpWriteStream->seek(pos);
        }
        else
        {
            if (pos == 0)
            {
                mCurrentPos = 0;
                mZStream->next_in = mTmp;
                mCompressedStream->seek(0);
                mZStream->avail_in = static_cast<uint>(mCompressedStream->read(mTmp, getAvailInForSinglePass()));
                inflateReset(mZStream);
            }
            else
            {
                skip(pos - tell());
            }
        }
    }
    //---------------------------------------------------------------------
    size_t DeflateStream::tell(void) const
    {
        if (!mIsCompressedValid)
        {
            return mCompressedStream->tell();
        }
        else if(getAccessMode() & WRITE)
        {
            return mTmpWriteStream->tell();
        }
        else
        {
            return mCurrentPos;
        }

    }
    //---------------------------------------------------------------------
    bool DeflateStream::eof(void) const
    {
        if (getAccessMode() & WRITE)
            return mTmpWriteStream->eof();
        else
        {
            if (!mIsCompressedValid)
                return mCompressedStream->eof();
            else
                return mCompressedStream->eof() && mZStream->avail_in == 0;
        }
    }
    //---------------------------------------------------------------------
    void DeflateStream::close(void)
    {
        if (getAccessMode() & WRITE)
        {
            compressFinal();
        }

        // don't close underlying compressed stream in case used for something else
    }
    //---------------------------------------------------------------------

}

#endif
<commit_msg>OgreDeflate: replace unsafe tmpnam by mkstemp for POSIX systems<commit_after>/*
 -----------------------------------------------------------------------------
 This source file is part of OGRE
 (Object-oriented Graphics Rendering Engine)
 For the latest info, see http://www.ogre3d.org/

 Copyright (c) 2000-2014 Torus Knot Software Ltd

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 -----------------------------------------------------------------------------
 */
#include "OgreStableHeaders.h"

#if OGRE_NO_ZIP_ARCHIVE == 0

#include "OgreDeflate.h"
#include "OgreException.h"
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS || OGRE_PLATFORM == OGRE_PLATFORM_APPLE
#include "macUtils.h"
#endif

#include <zlib.h>

namespace Ogre
{
    // memory implementations
    void* OgreZalloc(void* opaque, unsigned int items, unsigned int size)
    {
        return OGRE_MALLOC(items * size, MEMCATEGORY_GENERAL);
    }
    void OgreZfree(void* opaque, void* address)
    {
        OGRE_FREE(address, MEMCATEGORY_GENERAL);
    }
    #define OGRE_DEFLATE_TMP_SIZE 16384
    //---------------------------------------------------------------------
    DeflateStream::DeflateStream(const DataStreamPtr& compressedStream, const String& tmpFileName, size_t avail_in)
    : DataStream(compressedStream->getAccessMode())
    , mCompressedStream(compressedStream)
    , mTempFileName(tmpFileName)
    , mZStream(0)
    , mCurrentPos(0)
    , mAvailIn(avail_in)
    , mTmp(0)
    , mIsCompressedValid(true)
    {
        init();
    }
    //---------------------------------------------------------------------
    DeflateStream::DeflateStream(const String& name, const DataStreamPtr& compressedStream, const String& tmpFileName, size_t avail_in)
    : DataStream(name, compressedStream->getAccessMode())
    , mCompressedStream(compressedStream)
    , mTempFileName(tmpFileName)
    , mZStream(0)
    , mCurrentPos(0)
    , mAvailIn(avail_in)
    , mTmp(0)
    , mIsCompressedValid(true)
    {
        init();
    }
    //---------------------------------------------------------------------
    size_t DeflateStream::getAvailInForSinglePass()
    {
        size_t ret = OGRE_DEFLATE_TMP_SIZE;

        // if we are doing particial-uncompressing
        if(mAvailIn>0)
        {
            if(mAvailIn<ret)
                ret = mAvailIn;
            mAvailIn -= ret;
        }

        return ret;
    }
    //---------------------------------------------------------------------
    void DeflateStream::init()
    {
        mZStream = OGRE_ALLOC_T(z_stream, 1, MEMCATEGORY_GENERAL);
        mZStream->zalloc = OgreZalloc;
        mZStream->zfree = OgreZfree;

        if (getAccessMode() == READ)
        {
            mTmp = (unsigned char*)OGRE_MALLOC(OGRE_DEFLATE_TMP_SIZE, MEMCATEGORY_GENERAL);
            size_t restorePoint = mCompressedStream->tell();
            // read early chunk
            mZStream->next_in = mTmp;
            mZStream->avail_in = static_cast<uint>(mCompressedStream->read(mTmp, getAvailInForSinglePass()));

            if (inflateInit(mZStream) != Z_OK)
            {
                mIsCompressedValid = false;
            }
            else
                mIsCompressedValid = true;

            if (mIsCompressedValid)
            {
                // in fact, inflateInit on some implementations doesn't try to read
                // anything. We need to at least read something to test
                Bytef testOut[4];
                size_t savedIn = mZStream->avail_in;
                mZStream->avail_out = 4;
                mZStream->next_out = testOut;
                if (inflate(mZStream, Z_SYNC_FLUSH) != Z_OK)
                    mIsCompressedValid = false;
                // restore for reading
                mZStream->avail_in = static_cast<uint>(savedIn);
                mZStream->next_in = mTmp;

                inflateReset(mZStream);
            }

            if (!mIsCompressedValid)
            {
                // Not compressed data!
                // Fail gracefully, fall back on reading the underlying stream direct
                destroy();
                mCompressedStream->seek(restorePoint);
            }
        }
        else
        {
            if(mTempFileName.empty())
            {
                // Write to temp file
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
                char* tmpname = _tempnam(".", "ogre");
                if (!tmpname)
                {
                    // Having no file name here will cause various problems later.
                    OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Temporary file name generation failed.", "DeflateStream::init");
                }
                else
                {
                    mTempFileName = tmpname;
                    free(tmpname);
                }
#elif OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS || OGRE_PLATFORM == OGRE_PLATFORM_APPLE
                mTempFileName = macTempFileName();
#else
                char tmpname[] = "/tmp/ogreXXXXXX";
                if (mkstemp(tmpname) == -1)
                    OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Temporary file name generation failed.", "DeflateStream::init");

                mTempFileName = tmpname;
#endif
            }

            std::fstream *f = OGRE_NEW_T(std::fstream, MEMCATEGORY_GENERAL)();
            f->open(mTempFileName.c_str(), std::ios::binary | std::ios::out);
            mTmpWriteStream = DataStreamPtr(OGRE_NEW FileStreamDataStream(f));

        }

    }
    //---------------------------------------------------------------------
    void DeflateStream::destroy()
    {
        if (getAccessMode() == READ)
            inflateEnd(mZStream);

        OGRE_FREE(mZStream, MEMCATEGORY_GENERAL);
        mZStream = 0;
        OGRE_FREE(mTmp, MEMCATEGORY_GENERAL);
        mTmp = 0;
    }
    //---------------------------------------------------------------------
    DeflateStream::~DeflateStream()
    {
        close();
        destroy();
    }
    //---------------------------------------------------------------------
    size_t DeflateStream::read(void* buf, size_t count)
    {
        if (!mIsCompressedValid)
        {
            return mCompressedStream->read(buf, count);
        }

        if (getAccessMode() & WRITE)
        {
            return mTmpWriteStream->read(buf, count);
        }
        else
        {

            size_t restorePoint = mCompressedStream->tell();
            // read from cache first
            size_t cachereads = mReadCache.read(buf, count);

            size_t newReadUncompressed = 0;

            if (cachereads < count)
            {
                mZStream->avail_out = static_cast<uint>(count - cachereads);
                mZStream->next_out = (Bytef*)buf + cachereads;

                while (mZStream->avail_out)
                {
                    // Pull next chunk of compressed data from the underlying stream
                    if (!mZStream->avail_in && !mCompressedStream->eof())
                    {
                        mZStream->avail_in = static_cast<uint>(mCompressedStream->read(mTmp, getAvailInForSinglePass()));
                        mZStream->next_in = mTmp;
                    }

                    if (mZStream->avail_in)
                    {
                        int availpre = mZStream->avail_out;
                        int status = inflate(mZStream, Z_SYNC_FLUSH);
                        size_t readUncompressed = availpre - mZStream->avail_out;
                        newReadUncompressed += readUncompressed;
                        if (status != Z_OK)
                        {
                            // End of data, or error
                            if (status != Z_STREAM_END)
                            {
                                mCompressedStream->seek(restorePoint);
                                OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
                                            "Error in compressed stream",
                                            "DeflateStrea::read");
                            }
                            else
                            {
                                // back up the stream so that it can be used from the end onwards
                                long unusedCompressed = mZStream->avail_in;
                                mCompressedStream->skip(-unusedCompressed);
                            }

                            break;
                        }
                    }
                }
            }

            // Cache the last bytes read
            mReadCache.cacheData((char*)buf + cachereads, newReadUncompressed);

            mCurrentPos += newReadUncompressed + cachereads;

            return newReadUncompressed + cachereads;
        }
    }
    //---------------------------------------------------------------------
    size_t DeflateStream::write(const void* buf, size_t count)
    {
        if ((getAccessMode() & WRITE) == 0)
            OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS,
                        "Not a writable stream", "DeflateStream::write");

        return mTmpWriteStream->write(buf, count);
    }
    //---------------------------------------------------------------------
    void DeflateStream::compressFinal()
    {
        // Close temp stream
        mTmpWriteStream->close();

        // Copy & compress
        // We do this rather than compress directly because some code seeks
        // around while writing (e.g. to update size blocks) which is not
        // possible when compressing on the fly

        int ret, flush;
        char in[OGRE_DEFLATE_TMP_SIZE];
        char out[OGRE_DEFLATE_TMP_SIZE];

        if (deflateInit(mZStream, Z_DEFAULT_COMPRESSION) != Z_OK)
        {
            destroy();
            OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
                        "Error initialising deflate compressed stream!",
                        "DeflateStream::init");
        }

        std::ifstream inFile;
        inFile.open(mTempFileName.c_str(), std::ios::in | std::ios::binary);

        do
        {
            inFile.read(in, OGRE_DEFLATE_TMP_SIZE);
            mZStream->avail_in = (uInt)inFile.gcount();
            if (inFile.bad())
            {
                deflateEnd(mZStream);
                OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
                            "Error reading temp uncompressed stream!",
                            "DeflateStream::init");
            }
            flush = inFile.eof() ? Z_FINISH : Z_NO_FLUSH;
            mZStream->next_in = (Bytef*)in;

            /* run deflate() on input until output buffer not full, finish
             compression if all of source has been read in */
            do
            {
                mZStream->avail_out = OGRE_DEFLATE_TMP_SIZE;
                mZStream->next_out = (Bytef*)out;
                ret = deflate(mZStream, flush);    /* no bad return value */
                assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
                size_t compressed = OGRE_DEFLATE_TMP_SIZE - mZStream->avail_out;
                mCompressedStream->write(out, compressed);
            } while (mZStream->avail_out == 0);
            assert(mZStream->avail_in == 0);     /* all input will be used */

            /* done when last data in file processed */
        } while (flush != Z_FINISH);
        assert(ret == Z_STREAM_END);        /* stream will be complete */
                (void)ret;
        deflateEnd(mZStream);

        inFile.close();
        remove(mTempFileName.c_str());

    }
    //---------------------------------------------------------------------
    void DeflateStream::skip(long count)
    {
        if (!mIsCompressedValid)
        {
            mCompressedStream->skip(count);
            return;
        }

        if (getAccessMode() & WRITE)
        {
            mTmpWriteStream->skip(count);
        }
        else
        {
            if (count > 0)
            {
                if (!mReadCache.ff(count))
                {
                    OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
                                "You can only skip within the cache range in a deflate stream.",
                                "DeflateStream::skip");
                }
            }
            else if (count < 0)
            {
                if (!mReadCache.rewind((size_t)(-count)))
                {
                    OGRE_EXCEPT(Exception::ERR_INVALID_STATE,
                                "You can only skip within the cache range in a deflate stream.",
                                "DeflateStream::skip");
                }
            }
        }
        mCurrentPos = static_cast<size_t>(static_cast<long>(mCurrentPos) + count);

    }
    //---------------------------------------------------------------------
    void DeflateStream::seek( size_t pos )
    {
        if (!mIsCompressedValid)
        {
            mCompressedStream->seek(pos);
            return;
        }
        if (getAccessMode() & WRITE)
        {
            mTmpWriteStream->seek(pos);
        }
        else
        {
            if (pos == 0)
            {
                mCurrentPos = 0;
                mZStream->next_in = mTmp;
                mCompressedStream->seek(0);
                mZStream->avail_in = static_cast<uint>(mCompressedStream->read(mTmp, getAvailInForSinglePass()));
                inflateReset(mZStream);
            }
            else
            {
                skip(pos - tell());
            }
        }
    }
    //---------------------------------------------------------------------
    size_t DeflateStream::tell(void) const
    {
        if (!mIsCompressedValid)
        {
            return mCompressedStream->tell();
        }
        else if(getAccessMode() & WRITE)
        {
            return mTmpWriteStream->tell();
        }
        else
        {
            return mCurrentPos;
        }

    }
    //---------------------------------------------------------------------
    bool DeflateStream::eof(void) const
    {
        if (getAccessMode() & WRITE)
            return mTmpWriteStream->eof();
        else
        {
            if (!mIsCompressedValid)
                return mCompressedStream->eof();
            else
                return mCompressedStream->eof() && mZStream->avail_in == 0;
        }
    }
    //---------------------------------------------------------------------
    void DeflateStream::close(void)
    {
        if (getAccessMode() & WRITE)
        {
            compressFinal();
        }

        // don't close underlying compressed stream in case used for something else
    }
    //---------------------------------------------------------------------

}

#endif
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <stdio.h>

#include <string.h>
#include "../support/cmdline.hxx"
#include "cr_metho.hxx"
#include "cr_html.hxx"
#include "cr_index.hxx"
#include "xmlelem.hxx"
#include "xmltree.hxx"
#include "parse.hxx"
#include "../support/syshelp.hxx"
#include "../support/heap.hxx"

int                     Do_IndexCommandLine(
                            const CommandLine &     i_rCommandLine );
int                     Do_SingleFileCommandLine(
                            const CommandLine &     i_rCommandLine );
void                    Create_TypeInfo(
                            const char *            o_sOutputFile,
                            ModuleDescription &     i_rData );

int
#ifdef WNT
_cdecl
#endif
main( int       argc,
      char *    argv[] )
{
    // Variables
    CommandLine             aCommandLine(argc, argv);
    int ret = 0;

    if (! aCommandLine.IsOk())
    {
        std::cerr <<  aCommandLine.ErrorText() << std::endl ;
        return 1;
    }

    if ( aCommandLine.IsIndexCommand() )
        ret = Do_IndexCommandLine(aCommandLine);
    else
        ret = Do_SingleFileCommandLine(aCommandLine);

    return ret;
}

int
Do_SingleFileCommandLine(const CommandLine & i_rCommandLine)
{
    ModuleDescription   aDescr;
    X2CParser           aParser(aDescr);

    // Load file and create Function-file
    bool bLoadResult = aParser.LoadFile(i_rCommandLine.XmlSrcFile());
    if (! bLoadResult)
    {
        std::cerr << "Error: File %s could not be loaded." << i_rCommandLine.XmlSrcFile() << std::endl;
        return 1;
    }

    if ( strlen(i_rCommandLine.FuncFile()) > 0 )
    {
        Create_AccessMethod( i_rCommandLine.FuncFile(),
                             aParser.PureText() );

        std::cout << "File "
             << i_rCommandLine.FuncFile()
             << " with component_getDescriptionFunc() is created now."
             << std::endl;
    }

    // Parse
    aParser.Parse();

    // Produce output
    if ( strlen(i_rCommandLine.HtmlFile()) > 0 )
    {
        HtmlCreator aHtmlCreator( i_rCommandLine.HtmlFile(),
                                  aDescr,
                                  i_rCommandLine.IdlRootPath() );
        aHtmlCreator.Run();
    }

    if (strlen(i_rCommandLine.TypeInfoFile()) > 0)
    {
        Create_TypeInfo( i_rCommandLine.TypeInfoFile(),
                         aDescr );
    }

    return 0;
};

int
Do_IndexCommandLine(const CommandLine & i_rCommandLine)
{
    // Parsen files:
    List<Simstr>    aFiles;
    Index           aIndex( i_rCommandLine.OutputDirectory(),
                            i_rCommandLine.IdlRootPath(),
                            i_rCommandLine.IndexedTags() );

    std::cout << "Gather xml-files ..." << std::endl;
    GatherFileNames( aFiles, i_rCommandLine.XmlSrcDirectory() );

    std::cout << "Create output ..." << std::endl;
    aIndex.GatherData(aFiles);
    aIndex.WriteOutput( i_rCommandLine.IndexOutputFile() );

    std::cout << "... done." << std::endl;

    return 0;
};

//********************      Creating of typeinfo       ********************//

void                    Put2StdOut_TypeInfo(
                            ModuleDescription &     i_rData );
void                    Put2File_TypeInfo(
                            const char *            i_sOutputFile,
                            ModuleDescription &     i_rData );
void                    StreamOut_TypeInfo(
                            std::ostream &               o_rOut,
                            ModuleDescription &     i_rData,
                            const char *            i_sSeparator );

void
Create_TypeInfo( const char *           o_sOutputFile,
                 ModuleDescription &    i_rData )
{
    if ( strcmp(o_sOutputFile, "stdout") == 0 )
        Put2StdOut_TypeInfo(i_rData);
    else
        Put2File_TypeInfo(o_sOutputFile,i_rData);

#if 0
    std::ofstream aOut(o_sOutputFile, std::ios::out
#if defined(WNT) || defined(OS2)
                                               | std::ios::binary
#endif
    );
    if ( !aOut )
    {
        std::cerr << "Error: " << o_sOutputFile << " could not be created." << std::endl;
        return;
    }

    Heap    aTypesHeap(12);
    Simstr  sLibPrefix = i_rData.ModuleName();

    // Gather types:
    List< const MultipleTextElement * > aTypes;
    i_rData.Get_Types(aTypes);

    for ( unsigned t = 0; t < aTypes.size(); ++t )
    {
        unsigned i_max = aTypes[t]->Size();
        for ( unsigned  i = 0; i < i_max; ++i )
        {
            aTypesHeap.InsertValue( aTypes[t]->Data(i), "" );
        }  // end for
    }

    // Write types:
    WriteStr( aOut, sLibPrefix );
    WriteStr( aOut, "_XML2CMPTYPES= ");

    HeapItem * pLastHeapTop = 0;
    for ( HeapItem * pHeapTop = aTypesHeap.ReleaseTop(); pHeapTop != 0; pHeapTop = aTypesHeap.ReleaseTop() )
    {
        if (pLastHeapTop != 0)
        {
            if ( 0 == strcmp(pHeapTop->Key(), pLastHeapTop->Key()) )
                continue;
            delete pLastHeapTop;
            // pLastHeapTop = 0;
        }
        pLastHeapTop = pHeapTop;

        WriteStr( aOut, "\t\\\n\t\t" );

        const char * sEnd = strchr( pHeapTop->Key(), ' ' );
        if (sEnd != 0)
        {
            const char * sQuali = strrchr( pHeapTop->Key(), ' ' )+1;
            WriteStr( aOut, sQuali );
            WriteStr( aOut, "." );
            aOut.write( pHeapTop->Key(), sEnd - pHeapTop->Key() );
        }
        else
            WriteStr( aOut, pHeapTop->Key() );
    }   // end for

    if (pLastHeapTop != 0)
    {
        delete pLastHeapTop;
        pLastHeapTop = 0;
    }

    aOut.close();
#endif // 0
}

void
Put2StdOut_TypeInfo( ModuleDescription &    i_rData )
{
    StreamOut_TypeInfo(std::cout, i_rData, " ");
}

void
Put2File_TypeInfo( const char *            i_sOutputFile,
                   ModuleDescription &     i_rData )
{
    std::ofstream aOut(i_sOutputFile, std::ios::out
#if defined(WNT) || defined(OS2)
                                               | std::ios::binary
#endif
    );
    if ( !aOut )
    {
        std::cerr << "Error: " << i_sOutputFile << " could not be created." << std::endl;
        return;
    }

    Simstr  sLibPrefix = i_rData.ModuleName();
    WriteStr( aOut, sLibPrefix );
    WriteStr( aOut, "_XML2CMPTYPES= ");

    StreamOut_TypeInfo(aOut, i_rData, "\t\\\n\t\t");

    aOut.close();
}

void
StreamOut_TypeInfo( std::ostream &               o_rOut,
                    ModuleDescription &     i_rData,
                    const char *            i_sSeparator )
{
    Heap    aTypesHeap(12);

    // Gather types:
    List< const MultipleTextElement * > aTypes;
    i_rData.Get_Types(aTypes);

    for ( unsigned t = 0; t < aTypes.size(); ++t )
    {
        unsigned i_max = aTypes[t]->Size();
        for ( unsigned  i = 0; i < i_max; ++i )
        {
            aTypesHeap.InsertValue( aTypes[t]->Data(i), "" );
        }  // end for
    }

    // Write types:
    HeapItem * pLastHeapTop = 0;
    for ( HeapItem * pHeapTop = aTypesHeap.ReleaseTop(); pHeapTop != 0; pHeapTop = aTypesHeap.ReleaseTop() )
    {
        if (pLastHeapTop != 0)
        {
            if ( 0 == strcmp(pHeapTop->Key(), pLastHeapTop->Key()) )
                continue;
            delete pLastHeapTop;
            // pLastHeapTop = 0;
        }
        pLastHeapTop = pHeapTop;

        WriteStr( o_rOut, i_sSeparator );

        const char * sEnd = strchr( pHeapTop->Key(), ' ' );
        if (sEnd != 0)
        {
            const char * sQuali = strrchr( pHeapTop->Key(), ' ' ) + 1;
            WriteStr( o_rOut, sQuali );
            WriteStr( o_rOut, "." );
            o_rOut.write( pHeapTop->Key(), sEnd - pHeapTop->Key() );
        }
        else
            WriteStr( o_rOut, pHeapTop->Key() );
    }   // end for

    if (pLastHeapTop != 0)
    {
        delete pLastHeapTop;
        pLastHeapTop = 0;
    }
}

<commit_msg>CWS-TOOLING: integrate CWS cmcfixes78<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <stdio.h>

#include <string.h>
#include "../support/cmdline.hxx"
#include "cr_metho.hxx"
#include "cr_html.hxx"
#include "cr_index.hxx"
#include "xmlelem.hxx"
#include "xmltree.hxx"
#include "parse.hxx"
#include "../support/syshelp.hxx"
#include "../support/heap.hxx"

int                     Do_IndexCommandLine(
                            const CommandLine &     i_rCommandLine );
int                     Do_SingleFileCommandLine(
                            const CommandLine &     i_rCommandLine );
void                    Create_TypeInfo(
                            const char *            o_sOutputFile,
                            ModuleDescription &     i_rData );

int
#ifdef WNT
_cdecl
#endif
main( int       argc,
      char *    argv[] )
{
    // Variables
    CommandLine             aCommandLine(argc, argv);
    int ret = 0;

    if (! aCommandLine.IsOk())
    {
        std::cerr <<  aCommandLine.ErrorText() << std::endl ;
        return 1;
    }

    if ( aCommandLine.IsIndexCommand() )
        ret = Do_IndexCommandLine(aCommandLine);
    else
        ret = Do_SingleFileCommandLine(aCommandLine);

    return ret;
}

int
Do_SingleFileCommandLine(const CommandLine & i_rCommandLine)
{
    ModuleDescription   aDescr;
    X2CParser           aParser(aDescr);

    // Load file and create Function-file
    bool bLoadResult = aParser.LoadFile(i_rCommandLine.XmlSrcFile());
    if (! bLoadResult)
    {
        std::cerr << "Error: File " << i_rCommandLine.XmlSrcFile() << " could not be loaded." << std::endl;
        return 1;
    }

    if ( strlen(i_rCommandLine.FuncFile()) > 0 )
    {
        Create_AccessMethod( i_rCommandLine.FuncFile(),
                             aParser.PureText() );

        std::cout << "File "
             << i_rCommandLine.FuncFile()
             << " with component_getDescriptionFunc() is created now."
             << std::endl;
    }

    // Parse
    aParser.Parse();

    // Produce output
    if ( strlen(i_rCommandLine.HtmlFile()) > 0 )
    {
        HtmlCreator aHtmlCreator( i_rCommandLine.HtmlFile(),
                                  aDescr,
                                  i_rCommandLine.IdlRootPath() );
        aHtmlCreator.Run();
    }

    if (strlen(i_rCommandLine.TypeInfoFile()) > 0)
    {
        Create_TypeInfo( i_rCommandLine.TypeInfoFile(),
                         aDescr );
    }

    return 0;
};

int
Do_IndexCommandLine(const CommandLine & i_rCommandLine)
{
    // Parsen files:
    List<Simstr>    aFiles;
    Index           aIndex( i_rCommandLine.OutputDirectory(),
                            i_rCommandLine.IdlRootPath(),
                            i_rCommandLine.IndexedTags() );

    std::cout << "Gather xml-files ..." << std::endl;
    GatherFileNames( aFiles, i_rCommandLine.XmlSrcDirectory() );

    std::cout << "Create output ..." << std::endl;
    aIndex.GatherData(aFiles);
    aIndex.WriteOutput( i_rCommandLine.IndexOutputFile() );

    std::cout << "... done." << std::endl;

    return 0;
};

//********************      Creating of typeinfo       ********************//

void                    Put2StdOut_TypeInfo(
                            ModuleDescription &     i_rData );
void                    Put2File_TypeInfo(
                            const char *            i_sOutputFile,
                            ModuleDescription &     i_rData );
void                    StreamOut_TypeInfo(
                            std::ostream &               o_rOut,
                            ModuleDescription &     i_rData,
                            const char *            i_sSeparator );

void
Create_TypeInfo( const char *           o_sOutputFile,
                 ModuleDescription &    i_rData )
{
    if ( strcmp(o_sOutputFile, "stdout") == 0 )
        Put2StdOut_TypeInfo(i_rData);
    else
        Put2File_TypeInfo(o_sOutputFile,i_rData);

#if 0
    std::ofstream aOut(o_sOutputFile, std::ios::out
#if defined(WNT) || defined(OS2)
                                               | std::ios::binary
#endif
    );
    if ( !aOut )
    {
        std::cerr << "Error: " << o_sOutputFile << " could not be created." << std::endl;
        return;
    }

    Heap    aTypesHeap(12);
    Simstr  sLibPrefix = i_rData.ModuleName();

    // Gather types:
    List< const MultipleTextElement * > aTypes;
    i_rData.Get_Types(aTypes);

    for ( unsigned t = 0; t < aTypes.size(); ++t )
    {
        unsigned i_max = aTypes[t]->Size();
        for ( unsigned  i = 0; i < i_max; ++i )
        {
            aTypesHeap.InsertValue( aTypes[t]->Data(i), "" );
        }  // end for
    }

    // Write types:
    WriteStr( aOut, sLibPrefix );
    WriteStr( aOut, "_XML2CMPTYPES= ");

    HeapItem * pLastHeapTop = 0;
    for ( HeapItem * pHeapTop = aTypesHeap.ReleaseTop(); pHeapTop != 0; pHeapTop = aTypesHeap.ReleaseTop() )
    {
        if (pLastHeapTop != 0)
        {
            if ( 0 == strcmp(pHeapTop->Key(), pLastHeapTop->Key()) )
                continue;
            delete pLastHeapTop;
            // pLastHeapTop = 0;
        }
        pLastHeapTop = pHeapTop;

        WriteStr( aOut, "\t\\\n\t\t" );

        const char * sEnd = strchr( pHeapTop->Key(), ' ' );
        if (sEnd != 0)
        {
            const char * sQuali = strrchr( pHeapTop->Key(), ' ' )+1;
            WriteStr( aOut, sQuali );
            WriteStr( aOut, "." );
            aOut.write( pHeapTop->Key(), sEnd - pHeapTop->Key() );
        }
        else
            WriteStr( aOut, pHeapTop->Key() );
    }   // end for

    if (pLastHeapTop != 0)
    {
        delete pLastHeapTop;
        pLastHeapTop = 0;
    }

    aOut.close();
#endif // 0
}

void
Put2StdOut_TypeInfo( ModuleDescription &    i_rData )
{
    StreamOut_TypeInfo(std::cout, i_rData, " ");
}

void
Put2File_TypeInfo( const char *            i_sOutputFile,
                   ModuleDescription &     i_rData )
{
    std::ofstream aOut(i_sOutputFile, std::ios::out
#if defined(WNT) || defined(OS2)
                                               | std::ios::binary
#endif
    );
    if ( !aOut )
    {
        std::cerr << "Error: " << i_sOutputFile << " could not be created." << std::endl;
        return;
    }

    Simstr  sLibPrefix = i_rData.ModuleName();
    WriteStr( aOut, sLibPrefix );
    WriteStr( aOut, "_XML2CMPTYPES= ");

    StreamOut_TypeInfo(aOut, i_rData, "\t\\\n\t\t");

    aOut.close();
}

void
StreamOut_TypeInfo( std::ostream &               o_rOut,
                    ModuleDescription &     i_rData,
                    const char *            i_sSeparator )
{
    Heap    aTypesHeap(12);

    // Gather types:
    List< const MultipleTextElement * > aTypes;
    i_rData.Get_Types(aTypes);

    for ( unsigned t = 0; t < aTypes.size(); ++t )
    {
        unsigned i_max = aTypes[t]->Size();
        for ( unsigned  i = 0; i < i_max; ++i )
        {
            aTypesHeap.InsertValue( aTypes[t]->Data(i), "" );
        }  // end for
    }

    // Write types:
    HeapItem * pLastHeapTop = 0;
    for ( HeapItem * pHeapTop = aTypesHeap.ReleaseTop(); pHeapTop != 0; pHeapTop = aTypesHeap.ReleaseTop() )
    {
        if (pLastHeapTop != 0)
        {
            if ( 0 == strcmp(pHeapTop->Key(), pLastHeapTop->Key()) )
                continue;
            delete pLastHeapTop;
            // pLastHeapTop = 0;
        }
        pLastHeapTop = pHeapTop;

        WriteStr( o_rOut, i_sSeparator );

        const char * sEnd = strchr( pHeapTop->Key(), ' ' );
        if (sEnd != 0)
        {
            const char * sQuali = strrchr( pHeapTop->Key(), ' ' ) + 1;
            WriteStr( o_rOut, sQuali );
            WriteStr( o_rOut, "." );
            o_rOut.write( pHeapTop->Key(), sEnd - pHeapTop->Key() );
        }
        else
            WriteStr( o_rOut, pHeapTop->Key() );
    }   // end for

    if (pLastHeapTop != 0)
    {
        delete pLastHeapTop;
        pLastHeapTop = 0;
    }
}

<|endoftext|>


<commit_before>#ifndef HCKT_TREE_H
#define HCKT_TREE_H

#include <array>
#include <vector>
#include <bitset>
#include "direction.hpp"

template <typename ValueType>
class hckt_tree
{
protected:
    std::array<ValueType, 64> values;
    std::bitset<64> bitset;
    std::vector<hckt_tree*> children;

    size_t get_children_position(const size_t position) const
    {
        size_t c { 0 };

        for(size_t i=0; i<position; ++i) {
            if(bitset[i]) {
                ++c;
            }
        }

        return c;
    }

public:
    hckt_tree() : values { { } }, bitset { 0 }, children { }
    {
    }

    ~hckt_tree()
    {
        collapse();
    }

    /*
     * convert three part positions to memory location
     * as input: (left = 0 | right = 1) + (top = 0 | bottom = 2)
     *
     * result will be:
     * y1:x1:y2:x2:y3:x3
     *
     */
    static size_t get_position(size_t d1, size_t d2, size_t d3)
    {
        return ((1 << 0) * ((d1 & 2) >> 1))
             + ((1 << 1) * (d1 & 1))
             + ((1 << 2) * ((d2 & 2) >> 1))
             + ((1 << 3) * (d2 & 1))
             + ((1 << 4) * ((d3 & 2) >> 1))
             + ((1 << 5) * (d3 & 1));
    }

    /*
     * check if we have any children
     */
    bool empty() const
    {
        return bitset.none();
    }

    /*
     * destroy children
     * note: this does not delete prior values in array
     */
    void collapse()
    {
        for(auto child : children) {
            child->collapse();
        }

        children.clear();
        bitset.reset();
    }

    /*
     * insert an item into position of tree
     * position should be result of get_position
     */
    void insert(const size_t position, const ValueType value)
    {
        children.emplace(children.begin() + get_children_position(position), new hckt_tree<ValueType>());
        bitset.set(position);
        values[position] = value;
    }

    /*
     * removes an item from tree
     * position should be result of get_position
     */
    void remove(const size_t position)
    {
        const size_t pos = get_children_position(position);
        children[pos]->collapse();
        children.erase(children.begin() + pos);
        bitset.reset(position);
    }

    /*
     * get child node
     * position should be result of get_position
     */
    hckt_tree<ValueType> * leaf(const size_t position) const
    {
        return children[get_children_position(position)];
    }

    /*
     * sets node to specific value
     * position should be result of get_position
     */
    void set_value(const size_t position, const ValueType value)
    {
        values[position] = value;
    }

    /*
     * gets value from specific position
     * note: this does not check / concern itself if this has been collapsed
     * if so the data is stale
     * position should be result of get_position
     */
    ValueType get_value(const size_t position) const
    {
        return values[position];
    }
};

#endif
<commit_msg>formatting<commit_after>#ifndef HCKT_TREE_H
#define HCKT_TREE_H

#include <array>
#include <vector>
#include <bitset>
#include "direction.hpp"

template <typename ValueType>
class hckt_tree
{
protected:
    std::array<ValueType, 64> values;
    std::bitset<64> bitset;
    std::vector<hckt_tree*> children;

    size_t get_children_position(const size_t position) const
    {
        size_t c { 0 };

        for(size_t i=0; i<position; ++i) {
            if(bitset[i]) {
                ++c;
            }
        }

        return c;
    }

public:
    hckt_tree() : values { { } }, bitset { 0 }, children { }
    {
    }

    ~hckt_tree()
    {
        collapse();
    }

    /*
     * convert three part positions to memory location
     * as input: (left = 0 | right = 1) + (top = 0 | bottom = 2)
     *
     * result will be:
     * y1:x1:y2:x2:y3:x3
     *
     */
    static size_t get_position(size_t d1, size_t d2, size_t d3)
    {
        return ((1 << 0) * ((d1 & 2) >> 1))
             + ((1 << 1) *  (d1 & 1))
             + ((1 << 2) * ((d2 & 2) >> 1))
             + ((1 << 3) *  (d2 & 1))
             + ((1 << 4) * ((d3 & 2) >> 1))
             + ((1 << 5) *  (d3 & 1));
    }

    /*
     * check if we have any children
     */
    bool empty() const
    {
        return bitset.none();
    }

    /*
     * destroy children
     * note: this does not delete prior values in array
     */
    void collapse()
    {
        for(auto child : children) {
            child->collapse();
        }

        children.clear();
        bitset.reset();
    }

    /*
     * insert an item into position of tree
     * position should be result of get_position
     */
    void insert(const size_t position, const ValueType value)
    {
        children.emplace(children.begin() + get_children_position(position), new hckt_tree<ValueType>());
        bitset.set(position);
        values[position] = value;
    }

    /*
     * removes an item from tree
     * position should be result of get_position
     */
    void remove(const size_t position)
    {
        const size_t pos = get_children_position(position);
        children[pos]->collapse();
        children.erase(children.begin() + pos);
        bitset.reset(position);
    }

    /*
     * get child node
     * position should be result of get_position
     */
    hckt_tree<ValueType> * leaf(const size_t position) const
    {
        return children[get_children_position(position)];
    }

    /*
     * sets node to specific value
     * position should be result of get_position
     */
    void set_value(const size_t position, const ValueType value)
    {
        values[position] = value;
    }

    /*
     * gets value from specific position
     * note: this does not check / concern itself if this has been collapsed
     * if so the data is stale
     * position should be result of get_position
     */
    ValueType get_value(const size_t position) const
    {
        return values[position];
    }
};

#endif
<|endoftext|>


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

#ifndef __FRAMEWORK_DISPATCH_DISPATCHPROVIDER_HXX_
#define __FRAMEWORK_DISPATCH_DISPATCHPROVIDER_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_SERVICES_FRAME_HXX_
#include <services/frame.hxx>
#endif

#include <classes/protocolhandlercache.hxx>

#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_TRANSACTIONBASE_HXX_
#include <threadhelp/transactionbase.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif

#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_DISPATCHDESCRIPTOR_HPP_
#include <com/sun/star/frame/DispatchDescriptor.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

//_________________________________________________________________________________________________________________

/**
    @descr          We know some special dispatch objects with diffrent functionality.
                    The can be created internaly by the following DispatchProvider.
                    Here we define some identifier to force creation of the right one.

    @modified       20.08.2003 08:34, as96863
*/
enum EDispatchHelper
{
    E_DEFAULTDISPATCHER     ,
    E_MENUDISPATCHER        ,
    E_HELPAGENTDISPATCHER   ,
    E_CREATEDISPATCHER      ,
    E_BLANKDISPATCHER       ,
    E_SELFDISPATCHER        ,
    E_CLOSEDISPATCHER
};

//_________________________________________________________________________________________________________________

/**
    @short          implement a helper for XDispatchProvider interface
    @descr          The result of a queryDispatch() call depends from the owner, which use an instance of this class.
                    (frame, desktop) All of them must provides different functionality.
                    E.g:    - task can be created by the desktop only
                            - a task can have a beamer as direct child
                            - a normal frame never can create a new one by himself

    @attention      Use this class as member only! Never use it as baseclass.
                    XInterface will be ambigous and we hold a weakreference to ouer OWNER - not to ouer SUPERCLASS!

    @base           ThreadHelpBase
                        supports threadsafe mechanism
    @base           OWeakObject
                        provides ref count and weak mechanism

    @devstatus      ready to use
    @threadsafe     yes
    @modified       17.05.2002 07:56, as96863
*/
class DispatchProvider  :   // interfaces
                            public  css::lang::XTypeProvider            ,
                            public  css::frame::XDispatchProvider       ,
                            // baseclasses
                            // Order is neccessary for right initialization!
                            private ThreadHelpBase                      ,
                            private TransactionBase                     ,
                            public  ::cppu::OWeakObject
{
    /* member */
    private:
        /// reference to global service manager to create new services
        css::uno::Reference< css::lang::XMultiServiceFactory > m_xFactory;
        /// weakreference to owner frame (Don't use a hard reference. Owner can't delete us then!)
        css::uno::WeakReference< css::frame::XFrame > m_xFrame;
        /// different dispatcher to handle special dispatch calls, protocols or URLs (they will be created on demand.)
        css::uno::Reference< css::frame::XDispatch > m_xMenuDispatcher     ;
        css::uno::Reference< css::frame::XDispatch > m_xHelpAgentDispatcher;
/*      css::uno::Reference< css::frame::XDispatch > m_xBlankDispatcher    ;
        css::uno::Reference< css::frame::XDispatch > m_xSelfDispatcher     ;
        css::uno::Reference< css::frame::XDispatch > m_xDefaultDispatcher  ;*/
        /// cache of some other dispatch provider which are registered inside configuration to handle special URL protocols
        HandlerCache m_aProtocolHandlerCache;

    /* interface */
    public:
        DECLARE_XINTERFACE
        DECLARE_XTYPEPROVIDER

        DispatchProvider( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory ,
                          const css::uno::Reference< css::frame::XFrame >&              xFrame   );

        virtual css::uno::Reference< css::frame::XDispatch > SAL_CALL                       queryDispatch  ( const css::util::URL&                                       aURL             ,
                                                                                const ::rtl::OUString&                                      sTargetFrameName ,
                                                                                sal_Int32                                             nSearchFlags     ) throw( css::uno::RuntimeException );
        virtual css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL queryDispatches( const css::uno::Sequence< css::frame::DispatchDescriptor >& lDescriptions    ) throw( css::uno::RuntimeException );

    /* helper */
    protected:
        // Let him protected! So nobody can use us as base ...
        virtual ~DispatchProvider();

    private:
        css::uno::Reference< css::frame::XDispatch > implts_getOrCreateDispatchHelper   (       EDispatchHelper                            eHelper                       ,
                                                                                const css::uno::Reference< css::frame::XFrame >& xOwner                        ,
                                                                                const ::rtl::OUString&                           sTarget = ::rtl::OUString()   ,
                                                                                sal_Int32                                  nSearchFlags = 0              );
        sal_Bool                                     implts_isLoadableContent           ( const css::util::URL&                            aURL                          );
        css::uno::Reference< css::frame::XDispatch > implts_queryDesktopDispatch        ( const css::uno::Reference< css::frame::XFrame >  xDesktop                      ,
                                                                                const css::util::URL&                            aURL                          ,
                                                                                const ::rtl::OUString&                           sTargetFrameName              ,
                                                                                sal_Int32                                  nSearchFlags                  );
        css::uno::Reference< css::frame::XDispatch > implts_queryFrameDispatch          ( const css::uno::Reference< css::frame::XFrame >  xFrame                        ,
                                                                                const css::util::URL&                            aURL                          ,
                                                                                const ::rtl::OUString&                           sTargetFrameName              ,
                                                                                sal_Int32                                  nSearchFlags                  );
        css::uno::Reference< css::frame::XDispatch > implts_searchProtocolHandler       ( const css::util::URL&                            aURL                          );

}; // class DispatchProvider

} // namespace framework

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

#ifndef __FRAMEWORK_DISPATCH_DISPATCHPROVIDER_HXX_
#define __FRAMEWORK_DISPATCH_DISPATCHPROVIDER_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_SERVICES_FRAME_HXX_
#include <services/frame.hxx>
#endif

#include <classes/protocolhandlercache.hxx>

#ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_
#include <threadhelp/threadhelpbase.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_TRANSACTIONBASE_HXX_
#include <threadhelp/transactionbase.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_
#include <macros/xinterface.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_
#include <macros/xtypeprovider.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif

#ifndef __FRAMEWORK_MACROS_GENERIC_HXX_
#include <macros/generic.hxx>
#endif

#ifndef __FRAMEWORK_STDTYPES_H_
#include <stdtypes.h>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_
#include <com/sun/star/lang/XTypeProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_XDISPATCHPROVIDER_HPP_
#include <com/sun/star/frame/XDispatchProvider.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_URL_HPP_
#include <com/sun/star/util/URL.hpp>
#endif

#ifndef _COM_SUN_STAR_FRAME_DISPATCHDESCRIPTOR_HPP_
#include <com/sun/star/frame/DispatchDescriptor.hpp>
#endif

#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif

#ifndef _CPPUHELPER_WEAKREF_HXX_
#include <cppuhelper/weakref.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

//_________________________________________________________________________________________________________________

/**
    @descr          We know some special dispatch objects with diffrent functionality.
                    The can be created internaly by the following DispatchProvider.
                    Here we define some identifier to force creation of the right one.

    @modified       20.08.2003 08:34, as96863
*/
enum EDispatchHelper
{
    E_DEFAULTDISPATCHER     ,
    E_MENUDISPATCHER        ,
    E_HELPAGENTDISPATCHER   ,
    E_CREATEDISPATCHER      ,
    E_BLANKDISPATCHER       ,
    E_SELFDISPATCHER        ,
    E_CLOSEDISPATCHER
};

//_________________________________________________________________________________________________________________

/**
    @short          implement a helper for XDispatchProvider interface
    @descr          The result of a queryDispatch() call depends from the owner, which use an instance of this class.
                    (frame, desktop) All of them must provides different functionality.
                    E.g:    - task can be created by the desktop only
                            - a task can have a beamer as direct child
                            - a normal frame never can create a new one by himself

    @attention      Use this class as member only! Never use it as baseclass.
                    XInterface will be ambigous and we hold a weakreference to ouer OWNER - not to ouer SUPERCLASS!

    @base           ThreadHelpBase
                        supports threadsafe mechanism
    @base           OWeakObject
                        provides ref count and weak mechanism

    @devstatus      ready to use
    @threadsafe     yes
    @modified       17.05.2002 07:56, as96863
*/
class DispatchProvider  :   // interfaces
                            public  css::lang::XTypeProvider            ,
                            public  css::frame::XDispatchProvider       ,
                            // baseclasses
                            // Order is neccessary for right initialization!
                            private ThreadHelpBase                      ,
                            private TransactionBase                     ,
                            public  ::cppu::OWeakObject
{
    /* member */
    private:
        /// reference to global service manager to create new services
        css::uno::Reference< css::lang::XMultiServiceFactory > m_xFactory;
        /// weakreference to owner frame (Don't use a hard reference. Owner can't delete us then!)
        css::uno::WeakReference< css::frame::XFrame > m_xFrame;
        /// different dispatcher to handle special dispatch calls, protocols or URLs (they will be created on demand.)
        css::uno::Reference< css::frame::XDispatch > m_xMenuDispatcher     ;
        css::uno::Reference< css::frame::XDispatch > m_xHelpAgentDispatcher;
/*      css::uno::Reference< css::frame::XDispatch > m_xBlankDispatcher    ;
        css::uno::Reference< css::frame::XDispatch > m_xSelfDispatcher     ;
        css::uno::Reference< css::frame::XDispatch > m_xDefaultDispatcher  ;*/
        /// cache of some other dispatch provider which are registered inside configuration to handle special URL protocols
        HandlerCache m_aProtocolHandlerCache;

    /* interface */
    public:
        DECLARE_XINTERFACE
        DECLARE_XTYPEPROVIDER

        DispatchProvider( const css::uno::Reference< css::lang::XMultiServiceFactory >& xFactory ,
                          const css::uno::Reference< css::frame::XFrame >&              xFrame   );

        virtual css::uno::Reference< css::frame::XDispatch > SAL_CALL                       queryDispatch  ( const css::util::URL&                                       aURL             ,
                                                                                const ::rtl::OUString&                                      sTargetFrameName ,
                                                                                sal_Int32                                             nSearchFlags     ) throw( css::uno::RuntimeException );
        virtual css::uno::Sequence< css::uno::Reference< css::frame::XDispatch > > SAL_CALL queryDispatches( const css::uno::Sequence< css::frame::DispatchDescriptor >& lDescriptions    ) throw( css::uno::RuntimeException );

    /* helper */
    protected:
        // Let him protected! So nobody can use us as base ...
        virtual ~DispatchProvider();

    private:
        css::uno::Reference< css::frame::XDispatch > implts_getOrCreateDispatchHelper   (       EDispatchHelper                            eHelper                       ,
                                                                                const css::uno::Reference< css::frame::XFrame >& xOwner                        ,
                                                                                const ::rtl::OUString&                           sTarget = ::rtl::OUString()   ,
                                                                                sal_Int32                                  nSearchFlags = 0              );
        sal_Bool                                     implts_isLoadableContent           ( const css::util::URL&                            aURL                          );
        css::uno::Reference< css::frame::XDispatch > implts_queryDesktopDispatch        ( const css::uno::Reference< css::frame::XFrame >  xDesktop                      ,
                                                                                const css::util::URL&                            aURL                          ,
                                                                                const ::rtl::OUString&                           sTargetFrameName              ,
                                                                                sal_Int32                                  nSearchFlags                  );
        css::uno::Reference< css::frame::XDispatch > implts_queryFrameDispatch          ( const css::uno::Reference< css::frame::XFrame >  xFrame                        ,
                                                                                const css::util::URL&                            aURL                          ,
                                                                                const ::rtl::OUString&                           sTargetFrameName              ,
                                                                                sal_Int32                                  nSearchFlags                  );
        css::uno::Reference< css::frame::XDispatch > implts_searchProtocolHandler       ( const css::util::URL&                            aURL                          );

}; // class DispatchProvider

} // namespace framework

#endif // #ifndef __FRAMEWORK_DISPATCH_DISPATCHPROVIDER_HXX_
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

///////////////////////////////////////////////////////////////////////////////
// PHOS Preprocessor class. It runs by Shuttle at the end of the run,
// calculates calibration coefficients and dead/bad channels
// to be posted in OCDB
//
// Author: Boris Polichtchouk, 4 October 2006
///////////////////////////////////////////////////////////////////////////////

#include "AliPHOSPreprocessor.h"
#include "AliLog.h"
#include "AliCDBMetaData.h"
#include "AliPHOSEmcCalibData.h"
#include "TFile.h"
#include "TH1.h"
#include "TMap.h"
#include "TRandom.h"
#include "TKey.h"

ClassImp(AliPHOSPreprocessor)

//_______________________________________________________________________________________
AliPHOSPreprocessor::AliPHOSPreprocessor() :
AliPreprocessor("PHS",0)
{
  //default constructor
}

//_______________________________________________________________________________________
AliPHOSPreprocessor::AliPHOSPreprocessor(AliShuttleInterface* shuttle):
AliPreprocessor("PHS",shuttle)
{
  // Constructor
}

//_______________________________________________________________________________________
UInt_t AliPHOSPreprocessor::Process(TMap* /*valueSet*/)
{
  // process data retrieved by the Shuttle

  // The fileName with the histograms which have been produced by
  // AliPHOSCalibHistoProducer.
  // It is a responsibility of the SHUTTLE framework to form the fileName

  const char* fileName = GetFile(kDAQ, "AMPLITUDES", "GDC");
  AliInfo(Form("Got filename: %s",fileName));

  TFile f(fileName);

  if(!f.IsOpen()) {
    Log(Form("File %s is not opened, something goes wrong!",fileName));
    return 0;
  }

  const Int_t nMod=5; // 1:5 modules
  const Int_t nCol=56; //1:56 columns in each module
  const Int_t nRow=64; //1:64 rows in each module

  Double_t coeff;
  char hnam[80];
  TH1F* histo=0;

  //Get the reference histogram
  //(author: Gustavo Conesa Balbastre)

  TList * keylist = f.GetListOfKeys();
  Int_t nkeys   = f.GetNkeys();
  Bool_t ok = kFALSE;
  TKey  *key;
  TString refHistoName= "";
  Int_t ikey = 0;
  Int_t counter = 0;
  TH1F* hRef = 0;

  //Check if the file contains any histogram

  if(nkeys< 2){
    Log(Form("Not enough histograms (%d) for calibration.",nkeys));
    return 1;
  }

  while(!ok){
    ikey = gRandom->Integer(nkeys);
    key = (TKey*)keylist->At(ikey);
    refHistoName = key->GetName();
    hRef = (TH1F*)f.Get(refHistoName);
    counter++;
    // Check if the reference histogram has too little statistics
    if(hRef->GetEntries()>2) ok=kTRUE;
    if(!ok && counter >= nMod*nCol*nRow){
      Log("No histogram with enough statistics for reference.");
      return 1;
    }
  }

  Log(Form("reference histogram %s, %.1f entries, mean=%.3f, rms=%.3f.",
	 hRef->GetName(),hRef->GetEntries(),
	 hRef->GetMean(),hRef->GetRMS()));

  AliPHOSEmcCalibData calibData;
  Double_t refMean=hRef->GetMean();

  // Calculates relative calibration coefficients for all non-zero channels

  for(Int_t mod=0; mod<nMod; mod++) {
    for(Int_t col=0; col<nCol; col++) {
      for(Int_t row=0; row<nRow; row++) {
        sprintf(hnam,"mod%dcol%drow%d",mod,col,row);
        histo = (TH1F*)f.Get(hnam);
	//TODO: dead channels exclusion!
        if(histo) {
          coeff = histo->GetMean()/refMean;
	  calibData.SetADCchannelEmc(mod+1,col+1,row+1,0.001/coeff);
	  AliInfo(Form("mod %d col %d row %d  coeff %f\n",mod,col,row,coeff));
	}
        else
          calibData.SetADCchannelEmc(mod+1,col+1,row+1,0.001);
      }
    }
  }

  AliCDBMetaData metaData;
  Int_t result = Store("Calib", "EmcData", &calibData, &metaData);

  f.Close();
  return result;

}
<commit_msg>Hardcoded source file name removed.<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

///////////////////////////////////////////////////////////////////////////////
// PHOS Preprocessor class. It runs by Shuttle at the end of the run,
// calculates calibration coefficients and dead/bad channels
// to be posted in OCDB
//
// Author: Boris Polichtchouk, 4 October 2006
///////////////////////////////////////////////////////////////////////////////

#include "AliPHOSPreprocessor.h"
#include "AliLog.h"
#include "AliCDBMetaData.h"
#include "AliPHOSEmcCalibData.h"
#include "TFile.h"
#include "TH1.h"
#include "TMap.h"
#include "TRandom.h"
#include "TKey.h"
#include "TList.h"
#include "TObjString.h"

ClassImp(AliPHOSPreprocessor)

//_______________________________________________________________________________________
AliPHOSPreprocessor::AliPHOSPreprocessor() :
AliPreprocessor("PHS",0)
{
  //default constructor
}

//_______________________________________________________________________________________
AliPHOSPreprocessor::AliPHOSPreprocessor(AliShuttleInterface* shuttle):
AliPreprocessor("PHS",shuttle)
{
  // Constructor
}

//_______________________________________________________________________________________
UInt_t AliPHOSPreprocessor::Process(TMap* /*valueSet*/)
{
  // process data retrieved by the Shuttle

  // The fileName with the histograms which have been produced by
  // AliPHOSCalibHistoProducer.
  // It is a responsibility of the SHUTTLE framework to form the fileName

  AliPHOSEmcCalibData calibData;

  TList* list = GetFileSources(kDAQ, "AMPLITUDES");
  if(!list) {
    Log("Sources list not found, exit.");
    return 0;
  }

  TIter iter(list);
  TObjString *source;

  while ((source = dynamic_cast<TObjString *> (iter.Next()))) {
    AliInfo(Form("found source %s", source->String().Data()));

    TString fileName = GetFile(kDAQ, "AMPLITUDES", source->GetName());
    AliInfo(Form("Got filename: %s",fileName.Data()));

    TFile f(fileName);

    if(!f.IsOpen()) {
      Log(Form("File %s is not opened, something goes wrong!",fileName.Data()));
      return 0;
    }

    const Int_t nMod=5; // 1:5 modules
    const Int_t nCol=56; //1:56 columns in each module
    const Int_t nRow=64; //1:64 rows in each module

    Double_t coeff;
    char hnam[80];
    TH1F* histo=0;

    //Get the reference histogram
    //(author: Gustavo Conesa Balbastre)

    TList * keylist = f.GetListOfKeys();
    Int_t nkeys   = f.GetNkeys();
    Bool_t ok = kFALSE;
    TKey  *key;
    TString refHistoName= "";
    Int_t ikey = 0;
    Int_t counter = 0;
    TH1F* hRef = 0;

    //Check if the file contains any histogram

    if(nkeys< 2){
      Log(Form("Not enough histograms (%d) for calibration.",nkeys));
      return 1;
    }

    while(!ok){
      ikey = gRandom->Integer(nkeys);
      key = (TKey*)keylist->At(ikey);
      refHistoName = key->GetName();
      hRef = (TH1F*)f.Get(refHistoName);
      counter++;
      // Check if the reference histogram has too little statistics
      if(hRef->GetEntries()>2) ok=kTRUE;
      if(!ok && counter >= nMod*nCol*nRow){
	Log("No histogram with enough statistics for reference.");
	return 1;
      }
    }

    Log(Form("reference histogram %s, %.1f entries, mean=%.3f, rms=%.3f.",
	     hRef->GetName(),hRef->GetEntries(),
	     hRef->GetMean(),hRef->GetRMS()));

    Double_t refMean=hRef->GetMean();

    // Calculates relative calibration coefficients for all non-zero channels

    for(Int_t mod=0; mod<nMod; mod++) {
      for(Int_t col=0; col<nCol; col++) {
	for(Int_t row=0; row<nRow; row++) {
	  sprintf(hnam,"mod%dcol%drow%d",mod,col,row);
	  histo = (TH1F*)f.Get(hnam);
	  //TODO: dead channels exclusion!
	  if(histo) {
	    coeff = histo->GetMean()/refMean;
	    calibData.SetADCchannelEmc(mod+1,col+1,row+1,0.001/coeff);
	    AliInfo(Form("mod %d col %d row %d  coeff %f\n",mod,col,row,coeff));
	  }
	  else
	    calibData.SetADCchannelEmc(mod+1,col+1,row+1,0.001);
	}
      }
    }

    f.Close();
  }

  AliCDBMetaData metaData;
  Int_t result = Store("Calib", "EmcData", &calibData, &metaData);

  return result;

}
<|endoftext|>