<commit_before>/*
 * Copyright (C) 2006 Apple Computer, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "core/platform/image-decoders/gif/GIFImageDecoder.h"

#include <limits>
#include "core/platform/PlatformInstrumentation.h"
#include "core/platform/image-decoders/gif/GIFImageReader.h"
#include "wtf/NotFound.h"
#include "wtf/PassOwnPtr.h"

namespace WebCore {

GIFImageDecoder::GIFImageDecoder(ImageSource::AlphaOption alphaOption,
                                 ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption)
    : ImageDecoder(alphaOption, gammaAndColorProfileOption)
    , m_repetitionCount(cAnimationLoopOnce)
{
}

GIFImageDecoder::~GIFImageDecoder()
{
}

void GIFImageDecoder::setData(SharedBuffer* data, bool allDataReceived)
{
    if (failed())
        return;

    ImageDecoder::setData(data, allDataReceived);
    if (m_reader)
        m_reader->setData(data);
}

bool GIFImageDecoder::isSizeAvailable()
{
    if (!ImageDecoder::isSizeAvailable())
        parse(GIFSizeQuery);

    return ImageDecoder::isSizeAvailable();
}

size_t GIFImageDecoder::frameCount()
{
    parse(GIFFrameCountQuery);
    return m_frameBufferCache.size();
}

int GIFImageDecoder::repetitionCount() const
{
    // This value can arrive at any point in the image data stream.  Most GIFs
    // in the wild declare it near the beginning of the file, so it usually is
    // set by the time we've decoded the size, but (depending on the GIF and the
    // packets sent back by the webserver) not always.  If the reader hasn't
    // seen a loop count yet, it will return cLoopCountNotSeen, in which case we
    // should default to looping once (the initial value for
    // |m_repetitionCount|).
    //
    // There are some additional wrinkles here. First, ImageSource::clear()
    // may destroy the reader, making the result from the reader _less_
    // authoritative on future calls if the recreated reader hasn't seen the
    // loop count.  We don't need to special-case this because in this case the
    // new reader will once again return cLoopCountNotSeen, and we won't
    // overwrite the cached correct value.
    //
    // Second, a GIF might never set a loop count at all, in which case we
    // should continue to treat it as a "loop once" animation.  We don't need
    // special code here either, because in this case we'll never change
    // |m_repetitionCount| from its default value.
    //
    // Third, we use the same GIFImageReader for counting frames and we might
    // see the loop count and then encounter a decoding error which happens
    // later in the stream. It is also possible that no frames are in the
    // stream. In these cases we should just loop once.
    if (failed() || (m_reader && (!m_reader->imagesCount())))
        m_repetitionCount = cAnimationLoopOnce;
    else if (m_reader && m_reader->loopCount() != cLoopCountNotSeen)
        m_repetitionCount = m_reader->loopCount();
    return m_repetitionCount;
}

ImageFrame* GIFImageDecoder::frameBufferAtIndex(size_t index)
{
    if (index >= frameCount())
        return 0;

    ImageFrame& frame = m_frameBufferCache[index];
    if (frame.status() != ImageFrame::FrameComplete) {
        PlatformInstrumentation::willDecodeImage("GIF");
        decode(index);
        PlatformInstrumentation::didDecodeImage();
    }
    return &frame;
}

bool GIFImageDecoder::frameIsCompleteAtIndex(size_t index) const
{
    return m_reader && (index < m_reader->imagesCount()) && m_reader->frameContext(index)->isComplete();
}

float GIFImageDecoder::frameDurationAtIndex(size_t index) const
{
    return (m_reader && (index < m_reader->imagesCount()) &&
        m_reader->frameContext(index)->isHeaderDefined()) ?
        m_reader->frameContext(index)->delayTime : 0;
}

bool GIFImageDecoder::setFailed()
{
    m_reader.clear();
    return ImageDecoder::setFailed();
}

bool GIFImageDecoder::haveDecodedRow(size_t frameIndex, const Vector<unsigned char>& rowBuffer, size_t width, size_t rowNumber, unsigned repeatCount, bool writeTransparentPixels)
{
    const GIFFrameContext* frameContext = m_reader->frameContext(frameIndex);
    // The pixel data and coordinates supplied to us are relative to the frame's
    // origin within the entire image size, i.e.
    // (frameContext->xOffset, frameContext->yOffset). There is no guarantee
    // that width == (size().width() - frameContext->xOffset), so
    // we must ensure we don't run off the end of either the source data or the
    // row's X-coordinates.
    int xBegin = frameContext->xOffset;
    int yBegin = frameContext->yOffset + rowNumber;
    int xEnd = std::min(static_cast<int>(frameContext->xOffset + width), size().width());
    int yEnd = std::min(static_cast<int>(frameContext->yOffset + rowNumber + repeatCount), size().height());
    if (rowBuffer.isEmpty() || (xBegin < 0) || (yBegin < 0) || (xEnd <= xBegin) || (yEnd <= yBegin))
        return true;

    // Get the colormap.
    const unsigned char* colorMap;
    unsigned colorMapSize;
    if (frameContext->isLocalColormapDefined) {
        colorMap = m_reader->localColormap(frameContext);
        colorMapSize = m_reader->localColormapSize(frameContext);
    } else {
        colorMap = m_reader->globalColormap();
        colorMapSize = m_reader->globalColormapSize();
    }
    if (!colorMap)
        return true;

    // Initialize the frame if necessary.
    ImageFrame& buffer = m_frameBufferCache[frameIndex];
    if ((buffer.status() == ImageFrame::FrameEmpty) && !initFrameBuffer(frameIndex))
        return false;

    ImageFrame::PixelData* currentAddress = buffer.getAddr(xBegin, yBegin);
    // Write one row's worth of data into the frame.
    for (int x = xBegin; x < xEnd; ++x) {
        const unsigned char sourceValue = rowBuffer[x - frameContext->xOffset];
        if ((!frameContext->isTransparent || (sourceValue != frameContext->tpixel)) && (sourceValue < colorMapSize)) {
            const size_t colorIndex = static_cast<size_t>(sourceValue) * 3;
            buffer.setRGBA(currentAddress, colorMap[colorIndex], colorMap[colorIndex + 1], colorMap[colorIndex + 2], 255);
        } else {
            m_currentBufferSawAlpha = true;
            // We may or may not need to write transparent pixels to the buffer.
            // If we're compositing against a previous image, it's wrong, and if
            // we're writing atop a cleared, fully transparent buffer, it's
            // unnecessary; but if we're decoding an interlaced gif and
            // displaying it "Haeberli"-style, we must write these for passes
            // beyond the first, or the initial passes will "show through" the
            // later ones.
            if (writeTransparentPixels)
                buffer.setRGBA(currentAddress, 0, 0, 0, 0);
        }
        ++currentAddress;
    }

    // Tell the frame to copy the row data if need be.
    if (repeatCount > 1)
        buffer.copyRowNTimes(xBegin, xEnd, yBegin, yEnd);

    return true;
}

bool GIFImageDecoder::parseCompleted() const
{
    return m_reader && m_reader->parseCompleted();
}

bool GIFImageDecoder::frameComplete(size_t frameIndex)
{
    // Initialize the frame if necessary.  Some GIFs insert do-nothing frames,
    // in which case we never reach haveDecodedRow() before getting here.
    ImageFrame& buffer = m_frameBufferCache[frameIndex];
    if ((buffer.status() == ImageFrame::FrameEmpty) && !initFrameBuffer(frameIndex))
        return false; // initFrameBuffer() has already called setFailed().

    buffer.setStatus(ImageFrame::FrameComplete);

    if (!m_currentBufferSawAlpha) {
        // The whole frame was non-transparent, so it's possible that the entire
        // resulting buffer was non-transparent, and we can setHasAlpha(false).
        if (buffer.originalFrameRect().contains(IntRect(IntPoint(), size()))) {
            buffer.setHasAlpha(false);
            buffer.setRequiredPreviousFrameIndex(notFound);
        } else if (buffer.requiredPreviousFrameIndex() != notFound) {
            // Tricky case.  This frame does not have alpha only if everywhere
            // outside its rect doesn't have alpha.  To know whether this is
            // true, we check the start state of the frame -- if it doesn't have
            // alpha, we're safe.
            const ImageFrame* prevBuffer = &m_frameBufferCache[buffer.requiredPreviousFrameIndex()];
            ASSERT(prevBuffer->disposalMethod() != ImageFrame::DisposeOverwritePrevious);

            // Now, if we're at a DisposeNotSpecified or DisposeKeep frame, then
            // we can say we have no alpha if that frame had no alpha.  But
            // since in initFrameBuffer() we already copied that frame's alpha
            // state into the current frame's, we need do nothing at all here.
            //
            // The only remaining case is a DisposeOverwriteBgcolor frame.  If
            // it had no alpha, and its rect is contained in the current frame's
            // rect, we know the current frame has no alpha.
            if ((prevBuffer->disposalMethod() == ImageFrame::DisposeOverwriteBgcolor) && !prevBuffer->hasAlpha() && buffer.originalFrameRect().contains(prevBuffer->originalFrameRect()))
                buffer.setHasAlpha(false);
        }
    }

    return true;
}

void GIFImageDecoder::clearFrameBuffer(size_t frameIndex)
{
    if (m_reader && m_frameBufferCache[frameIndex].status() == ImageFrame::FramePartial) {
        // Reset the state of the partial frame in the reader so that the frame
        // can be decoded again when requested.
        m_reader->clearDecodeState(frameIndex);
    }
    ImageDecoder::clearFrameBuffer(frameIndex);
}

void GIFImageDecoder::parse(GIFParseQuery query)
{
    if (failed())
        return;

    if (!m_reader) {
        m_reader = adoptPtr(new GIFImageReader(this));
        m_reader->setData(m_data);
    }

    if (!m_reader->parse(query)) {
        setFailed();
        return;
    }

    const size_t oldSize = m_frameBufferCache.size();
    m_frameBufferCache.resize(m_reader->imagesCount());

    for (size_t i = oldSize; i < m_reader->imagesCount(); ++i) {
        ImageFrame& buffer = m_frameBufferCache[i];
        const GIFFrameContext* frameContext = m_reader->frameContext(i);
        buffer.setPremultiplyAlpha(m_premultiplyAlpha);
        buffer.setRequiredPreviousFrameIndex(findRequiredPreviousFrame(i));
        buffer.setDuration(frameContext->delayTime);
        buffer.setDisposalMethod(frameContext->disposalMethod);

        // Initialize the frame rect in our buffer.
        IntRect frameRect(frameContext->xOffset, frameContext->yOffset, frameContext->width, frameContext->height);

        // Make sure the frameRect doesn't extend outside the buffer.
        if (frameRect.maxX() > size().width())
            frameRect.setWidth(size().width() - frameContext->xOffset);
        if (frameRect.maxY() > size().height())
            frameRect.setHeight(size().height() - frameContext->yOffset);

        buffer.setOriginalFrameRect(frameRect);
    }
}

void GIFImageDecoder::decode(size_t frameIndex)
{
    parse(GIFFrameCountQuery);

    if (failed())
        return;

    Vector<size_t> framesToDecode;
    size_t frameToDecode = frameIndex;
    do {
        framesToDecode.append(frameToDecode);
        frameToDecode = m_frameBufferCache[frameToDecode].requiredPreviousFrameIndex();
    } while (frameToDecode != notFound && m_frameBufferCache[frameToDecode].status() != ImageFrame::FrameComplete);

    // The |rend| variable is needed by some compilers that can't correctly
    // select from const and non-const versions of overloaded functions.
    // Can remove the variable if Android compiler can compile
    // 'iter != framesToDecode.rend()'.
    Vector<size_t>::const_reverse_iterator rend = framesToDecode.rend();
    for (Vector<size_t>::const_reverse_iterator iter = framesToDecode.rbegin(); iter != rend; ++iter) {
        size_t frameIndex = *iter;
        if (!m_reader->decode(frameIndex)) {
            setFailed();
            return;
        }

        // We need more data to continue decoding.
        if (m_frameBufferCache[frameIndex].status() != ImageFrame::FrameComplete)
            break;
    }

    // It is also a fatal error if all data is received and we have decoded all
    // frames available but the file is truncated.
    if (frameIndex >= m_frameBufferCache.size() - 1 && isAllDataReceived() && m_reader && !m_reader->parseCompleted())
        setFailed();
}

bool GIFImageDecoder::initFrameBuffer(size_t frameIndex)
{
    // Initialize the frame rect in our buffer.
    const GIFFrameContext* frameContext = m_reader->frameContext(frameIndex);
    ImageFrame* const buffer = &m_frameBufferCache[frameIndex];

    size_t requiredPreviousFrameIndex = buffer->requiredPreviousFrameIndex();
    if (requiredPreviousFrameIndex == notFound) {
        // This frame doesn't rely on any previous data.
        if (!buffer->setSize(size().width(), size().height()))
            return setFailed();
    } else {
        const ImageFrame* prevBuffer = &m_frameBufferCache[requiredPreviousFrameIndex];
        ASSERT(prevBuffer->status() == ImageFrame::FrameComplete);

        // Preserve the last frame as the starting state for this frame.
        if (!buffer->copyBitmapData(*prevBuffer))
            return setFailed();

        if (prevBuffer->disposalMethod() == ImageFrame::DisposeOverwriteBgcolor) {
            // We want to clear the previous frame to transparent, without
            // affecting pixels in the image outside of the frame.
            const IntRect& prevRect = prevBuffer->originalFrameRect();
            ASSERT(!prevRect.contains(IntRect(IntPoint(), size())));
            for (int y = prevRect.y(); y < prevRect.maxY(); ++y) {
                for (int x = prevRect.x(); x < prevRect.maxX(); ++x)
                    buffer->setRGBA(x, y, 0, 0, 0, 0);
            }
            if ((prevRect.width() > 0) && (prevRect.height() > 0))
                buffer->setHasAlpha(true);
        }
    }

    // Update our status to be partially complete.
    buffer->setStatus(ImageFrame::FramePartial);

    // Reset the alpha pixel tracker for this frame.
    m_currentBufferSawAlpha = false;
    return true;
}

} // namespace WebCore
<commit_msg>GIFDecoder: Use index in place of iterator in vector iteration<commit_after>/*
 * Copyright (C) 2006 Apple Computer, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "core/platform/image-decoders/gif/GIFImageDecoder.h"

#include <limits>
#include "core/platform/PlatformInstrumentation.h"
#include "core/platform/image-decoders/gif/GIFImageReader.h"
#include "wtf/NotFound.h"
#include "wtf/PassOwnPtr.h"

namespace WebCore {

GIFImageDecoder::GIFImageDecoder(ImageSource::AlphaOption alphaOption,
                                 ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption)
    : ImageDecoder(alphaOption, gammaAndColorProfileOption)
    , m_repetitionCount(cAnimationLoopOnce)
{
}

GIFImageDecoder::~GIFImageDecoder()
{
}

void GIFImageDecoder::setData(SharedBuffer* data, bool allDataReceived)
{
    if (failed())
        return;

    ImageDecoder::setData(data, allDataReceived);
    if (m_reader)
        m_reader->setData(data);
}

bool GIFImageDecoder::isSizeAvailable()
{
    if (!ImageDecoder::isSizeAvailable())
        parse(GIFSizeQuery);

    return ImageDecoder::isSizeAvailable();
}

size_t GIFImageDecoder::frameCount()
{
    parse(GIFFrameCountQuery);
    return m_frameBufferCache.size();
}

int GIFImageDecoder::repetitionCount() const
{
    // This value can arrive at any point in the image data stream.  Most GIFs
    // in the wild declare it near the beginning of the file, so it usually is
    // set by the time we've decoded the size, but (depending on the GIF and the
    // packets sent back by the webserver) not always.  If the reader hasn't
    // seen a loop count yet, it will return cLoopCountNotSeen, in which case we
    // should default to looping once (the initial value for
    // |m_repetitionCount|).
    //
    // There are some additional wrinkles here. First, ImageSource::clear()
    // may destroy the reader, making the result from the reader _less_
    // authoritative on future calls if the recreated reader hasn't seen the
    // loop count.  We don't need to special-case this because in this case the
    // new reader will once again return cLoopCountNotSeen, and we won't
    // overwrite the cached correct value.
    //
    // Second, a GIF might never set a loop count at all, in which case we
    // should continue to treat it as a "loop once" animation.  We don't need
    // special code here either, because in this case we'll never change
    // |m_repetitionCount| from its default value.
    //
    // Third, we use the same GIFImageReader for counting frames and we might
    // see the loop count and then encounter a decoding error which happens
    // later in the stream. It is also possible that no frames are in the
    // stream. In these cases we should just loop once.
    if (failed() || (m_reader && (!m_reader->imagesCount())))
        m_repetitionCount = cAnimationLoopOnce;
    else if (m_reader && m_reader->loopCount() != cLoopCountNotSeen)
        m_repetitionCount = m_reader->loopCount();
    return m_repetitionCount;
}

ImageFrame* GIFImageDecoder::frameBufferAtIndex(size_t index)
{
    if (index >= frameCount())
        return 0;

    ImageFrame& frame = m_frameBufferCache[index];
    if (frame.status() != ImageFrame::FrameComplete) {
        PlatformInstrumentation::willDecodeImage("GIF");
        decode(index);
        PlatformInstrumentation::didDecodeImage();
    }
    return &frame;
}

bool GIFImageDecoder::frameIsCompleteAtIndex(size_t index) const
{
    return m_reader && (index < m_reader->imagesCount()) && m_reader->frameContext(index)->isComplete();
}

float GIFImageDecoder::frameDurationAtIndex(size_t index) const
{
    return (m_reader && (index < m_reader->imagesCount()) &&
        m_reader->frameContext(index)->isHeaderDefined()) ?
        m_reader->frameContext(index)->delayTime : 0;
}

bool GIFImageDecoder::setFailed()
{
    m_reader.clear();
    return ImageDecoder::setFailed();
}

bool GIFImageDecoder::haveDecodedRow(size_t frameIndex, const Vector<unsigned char>& rowBuffer, size_t width, size_t rowNumber, unsigned repeatCount, bool writeTransparentPixels)
{
    const GIFFrameContext* frameContext = m_reader->frameContext(frameIndex);
    // The pixel data and coordinates supplied to us are relative to the frame's
    // origin within the entire image size, i.e.
    // (frameContext->xOffset, frameContext->yOffset). There is no guarantee
    // that width == (size().width() - frameContext->xOffset), so
    // we must ensure we don't run off the end of either the source data or the
    // row's X-coordinates.
    int xBegin = frameContext->xOffset;
    int yBegin = frameContext->yOffset + rowNumber;
    int xEnd = std::min(static_cast<int>(frameContext->xOffset + width), size().width());
    int yEnd = std::min(static_cast<int>(frameContext->yOffset + rowNumber + repeatCount), size().height());
    if (rowBuffer.isEmpty() || (xBegin < 0) || (yBegin < 0) || (xEnd <= xBegin) || (yEnd <= yBegin))
        return true;

    // Get the colormap.
    const unsigned char* colorMap;
    unsigned colorMapSize;
    if (frameContext->isLocalColormapDefined) {
        colorMap = m_reader->localColormap(frameContext);
        colorMapSize = m_reader->localColormapSize(frameContext);
    } else {
        colorMap = m_reader->globalColormap();
        colorMapSize = m_reader->globalColormapSize();
    }
    if (!colorMap)
        return true;

    // Initialize the frame if necessary.
    ImageFrame& buffer = m_frameBufferCache[frameIndex];
    if ((buffer.status() == ImageFrame::FrameEmpty) && !initFrameBuffer(frameIndex))
        return false;

    ImageFrame::PixelData* currentAddress = buffer.getAddr(xBegin, yBegin);
    // Write one row's worth of data into the frame.
    for (int x = xBegin; x < xEnd; ++x) {
        const unsigned char sourceValue = rowBuffer[x - frameContext->xOffset];
        if ((!frameContext->isTransparent || (sourceValue != frameContext->tpixel)) && (sourceValue < colorMapSize)) {
            const size_t colorIndex = static_cast<size_t>(sourceValue) * 3;
            buffer.setRGBA(currentAddress, colorMap[colorIndex], colorMap[colorIndex + 1], colorMap[colorIndex + 2], 255);
        } else {
            m_currentBufferSawAlpha = true;
            // We may or may not need to write transparent pixels to the buffer.
            // If we're compositing against a previous image, it's wrong, and if
            // we're writing atop a cleared, fully transparent buffer, it's
            // unnecessary; but if we're decoding an interlaced gif and
            // displaying it "Haeberli"-style, we must write these for passes
            // beyond the first, or the initial passes will "show through" the
            // later ones.
            if (writeTransparentPixels)
                buffer.setRGBA(currentAddress, 0, 0, 0, 0);
        }
        ++currentAddress;
    }

    // Tell the frame to copy the row data if need be.
    if (repeatCount > 1)
        buffer.copyRowNTimes(xBegin, xEnd, yBegin, yEnd);

    return true;
}

bool GIFImageDecoder::parseCompleted() const
{
    return m_reader && m_reader->parseCompleted();
}

bool GIFImageDecoder::frameComplete(size_t frameIndex)
{
    // Initialize the frame if necessary.  Some GIFs insert do-nothing frames,
    // in which case we never reach haveDecodedRow() before getting here.
    ImageFrame& buffer = m_frameBufferCache[frameIndex];
    if ((buffer.status() == ImageFrame::FrameEmpty) && !initFrameBuffer(frameIndex))
        return false; // initFrameBuffer() has already called setFailed().

    buffer.setStatus(ImageFrame::FrameComplete);

    if (!m_currentBufferSawAlpha) {
        // The whole frame was non-transparent, so it's possible that the entire
        // resulting buffer was non-transparent, and we can setHasAlpha(false).
        if (buffer.originalFrameRect().contains(IntRect(IntPoint(), size()))) {
            buffer.setHasAlpha(false);
            buffer.setRequiredPreviousFrameIndex(notFound);
        } else if (buffer.requiredPreviousFrameIndex() != notFound) {
            // Tricky case.  This frame does not have alpha only if everywhere
            // outside its rect doesn't have alpha.  To know whether this is
            // true, we check the start state of the frame -- if it doesn't have
            // alpha, we're safe.
            const ImageFrame* prevBuffer = &m_frameBufferCache[buffer.requiredPreviousFrameIndex()];
            ASSERT(prevBuffer->disposalMethod() != ImageFrame::DisposeOverwritePrevious);

            // Now, if we're at a DisposeNotSpecified or DisposeKeep frame, then
            // we can say we have no alpha if that frame had no alpha.  But
            // since in initFrameBuffer() we already copied that frame's alpha
            // state into the current frame's, we need do nothing at all here.
            //
            // The only remaining case is a DisposeOverwriteBgcolor frame.  If
            // it had no alpha, and its rect is contained in the current frame's
            // rect, we know the current frame has no alpha.
            if ((prevBuffer->disposalMethod() == ImageFrame::DisposeOverwriteBgcolor) && !prevBuffer->hasAlpha() && buffer.originalFrameRect().contains(prevBuffer->originalFrameRect()))
                buffer.setHasAlpha(false);
        }
    }

    return true;
}

void GIFImageDecoder::clearFrameBuffer(size_t frameIndex)
{
    if (m_reader && m_frameBufferCache[frameIndex].status() == ImageFrame::FramePartial) {
        // Reset the state of the partial frame in the reader so that the frame
        // can be decoded again when requested.
        m_reader->clearDecodeState(frameIndex);
    }
    ImageDecoder::clearFrameBuffer(frameIndex);
}

void GIFImageDecoder::parse(GIFParseQuery query)
{
    if (failed())
        return;

    if (!m_reader) {
        m_reader = adoptPtr(new GIFImageReader(this));
        m_reader->setData(m_data);
    }

    if (!m_reader->parse(query)) {
        setFailed();
        return;
    }

    const size_t oldSize = m_frameBufferCache.size();
    m_frameBufferCache.resize(m_reader->imagesCount());

    for (size_t i = oldSize; i < m_reader->imagesCount(); ++i) {
        ImageFrame& buffer = m_frameBufferCache[i];
        const GIFFrameContext* frameContext = m_reader->frameContext(i);
        buffer.setPremultiplyAlpha(m_premultiplyAlpha);
        buffer.setRequiredPreviousFrameIndex(findRequiredPreviousFrame(i));
        buffer.setDuration(frameContext->delayTime);
        buffer.setDisposalMethod(frameContext->disposalMethod);

        // Initialize the frame rect in our buffer.
        IntRect frameRect(frameContext->xOffset, frameContext->yOffset, frameContext->width, frameContext->height);

        // Make sure the frameRect doesn't extend outside the buffer.
        if (frameRect.maxX() > size().width())
            frameRect.setWidth(size().width() - frameContext->xOffset);
        if (frameRect.maxY() > size().height())
            frameRect.setHeight(size().height() - frameContext->yOffset);

        buffer.setOriginalFrameRect(frameRect);
    }
}

void GIFImageDecoder::decode(size_t frameIndex)
{
    parse(GIFFrameCountQuery);

    if (failed())
        return;

    Vector<size_t> framesToDecode;
    size_t frameToDecode = frameIndex;
    do {
        framesToDecode.append(frameToDecode);
        frameToDecode = m_frameBufferCache[frameToDecode].requiredPreviousFrameIndex();
    } while (frameToDecode != notFound && m_frameBufferCache[frameToDecode].status() != ImageFrame::FrameComplete);

    for (size_t i = framesToDecode.size(); i > 0; --i) {
        size_t frameIndex = framesToDecode[i - 1];
        if (!m_reader->decode(frameIndex)) {
            setFailed();
            return;
        }

        // We need more data to continue decoding.
        if (m_frameBufferCache[frameIndex].status() != ImageFrame::FrameComplete)
            break;
    }

    // It is also a fatal error if all data is received and we have decoded all
    // frames available but the file is truncated.
    if (frameIndex >= m_frameBufferCache.size() - 1 && isAllDataReceived() && m_reader && !m_reader->parseCompleted())
        setFailed();
}

bool GIFImageDecoder::initFrameBuffer(size_t frameIndex)
{
    // Initialize the frame rect in our buffer.
    const GIFFrameContext* frameContext = m_reader->frameContext(frameIndex);
    ImageFrame* const buffer = &m_frameBufferCache[frameIndex];

    size_t requiredPreviousFrameIndex = buffer->requiredPreviousFrameIndex();
    if (requiredPreviousFrameIndex == notFound) {
        // This frame doesn't rely on any previous data.
        if (!buffer->setSize(size().width(), size().height()))
            return setFailed();
    } else {
        const ImageFrame* prevBuffer = &m_frameBufferCache[requiredPreviousFrameIndex];
        ASSERT(prevBuffer->status() == ImageFrame::FrameComplete);

        // Preserve the last frame as the starting state for this frame.
        if (!buffer->copyBitmapData(*prevBuffer))
            return setFailed();

        if (prevBuffer->disposalMethod() == ImageFrame::DisposeOverwriteBgcolor) {
            // We want to clear the previous frame to transparent, without
            // affecting pixels in the image outside of the frame.
            const IntRect& prevRect = prevBuffer->originalFrameRect();
            ASSERT(!prevRect.contains(IntRect(IntPoint(), size())));
            for (int y = prevRect.y(); y < prevRect.maxY(); ++y) {
                for (int x = prevRect.x(); x < prevRect.maxX(); ++x)
                    buffer->setRGBA(x, y, 0, 0, 0, 0);
            }
            if ((prevRect.width() > 0) && (prevRect.height() > 0))
                buffer->setHasAlpha(true);
        }
    }

    // Update our status to be partially complete.
    buffer->setStatus(ImageFrame::FramePartial);

    // Reset the alpha pixel tracker for this frame.
    m_currentBufferSawAlpha = false;
    return true;
}

} // namespace WebCore
<|endoftext|>


<commit_before>#include <iostream>
#include <iomanip>
#include <string>
#include <memory>
#include <map>
#include <algorithm>

#include <Lexer.hpp>
#include <Parser.hpp>
#include <Visitors.hpp>
#include <Checker.hpp>

#include <ExprStmt.hpp>
#include <RefExpr.hpp>
#include <IdRef.hpp>

using namespace std;

void PrintResult(string varname, double val, bool suppressed) {
    if (!suppressed) {
        cout << varname << " =" << endl << endl;
        cout << "    " << val << endl << endl;
    }
}

int main() {
    string input_line;

    auto id_table = make_shared<map<string, double>>();
    (*id_table)["ans"] = 0;

    cout << "miniMAT: It's like MATLAB, but smaller." << endl;
    cout << "Copyright (C) 2014 Federico Menozzi" << endl;
    cout << endl;

    while (true) {
        cout << ">>> ";

        getline(cin, input_line);
        if (cin.eof()) {
            cout << endl;
            break;
        }
        if (input_line == "quit" || input_line == "exit") {
            break;
        } else if (input_line == "") {
            continue;
        } else if (input_line == "who") {
            for (auto var : *id_table)
                cout << var.first << endl;
            cout  << endl;
            continue;
        } else if (input_line == "whos") {
            // Find longest var name (for formatting)
            auto w = max_element(begin(*id_table), end(*id_table), [](pair<string, double> p1, pair<string, double> p2) {
                return p1.first.size() < p2.first.size();
            })->first.size();

            for (auto var : *id_table)
                cout << setw(w) << var.first << " = " << var.second << endl;
            cout << endl;
            continue;
        }

        auto reporter = make_shared<miniMAT::reporter::ErrorReporter>();
        miniMAT::lexer::Lexer   lexer(input_line, reporter);
        miniMAT::parser::Parser parser(lexer, reporter);

        auto ast = parser.Parse();

        if (reporter->HasErrors()) {
            reporter->ReportErrors();
            cout << endl;
            continue;
        }

        miniMAT::checker::Checker checker(id_table, reporter);
        ast = checker.check(ast);

        if (reporter->HasErrors()) {
            reporter->ReportErrors();
            cout << endl;
        } else {
            double ans = ast->VisitEvaluate(id_table);
            if (ast->GetClassName() == "ExprStmt") {
                auto exprstmt = dynamic_pointer_cast<miniMAT::ast::ExprStmt>(ast);
                if (exprstmt->expr->GetClassName() == "RefExpr") {
                    auto refexpr = dynamic_pointer_cast<miniMAT::ast::RefExpr>(exprstmt->expr);
                    auto varname = dynamic_pointer_cast<miniMAT::ast::IdRef>(refexpr->ref)->id->GetSpelling();

                    PrintResult(varname, id_table->at(varname), parser.SuppressedOutput());
                } else {
                    (*id_table)["ans"] = ans;

                    PrintResult("ans", ans, parser.SuppressedOutput());
                }

            } else if (ast->GetClassName() == "AssignStmt") {
                auto assign_stmt = dynamic_pointer_cast<miniMAT::ast::AssignStmt>(ast);

                if (assign_stmt->ref->GetClassName() == "IdRef") {
                    auto idref   = dynamic_pointer_cast<miniMAT::ast::IdRef>(assign_stmt->ref);

                    auto varname = idref->id->GetSpelling();
                    auto val     = assign_stmt->val;

                    PrintResult(varname, val, parser.SuppressedOutput());
                }
            }
        }
    }

    return 0;
}
<commit_msg>Just a wee bit of cleanup<commit_after>#include <iostream>
#include <iomanip>
#include <string>
#include <memory>
#include <map>
#include <algorithm>

#include <Lexer.hpp>
#include <Parser.hpp>
#include <Visitors.hpp>
#include <Checker.hpp>

#include <ExprStmt.hpp>
#include <RefExpr.hpp>
#include <IdRef.hpp>

using namespace std;

void PrintResult(string varname, double val, bool suppressed) {
    if (!suppressed) {
        cout << varname << " =" << endl << endl;
        cout << "    " << val << endl << endl;
    }
}

int main() {
    string input_line;

    auto id_table = make_shared<map<string, double>>();
    (*id_table)["ans"] = 0;

    cout << "miniMAT: It's like MATLAB, but smaller." << endl;
    cout << "Copyright (C) 2014 Federico Menozzi" << endl;
    cout << endl;

    while (true) {
        cout << ">>> ";

        getline(cin, input_line);
        if (cin.eof()) {
            cout << endl;
            break;
        }
        if (input_line == "quit" || input_line == "exit") {
            break;
        } else if (input_line == "") {
            continue;
        } else if (input_line == "who") {
            for (auto var : *id_table)
                cout << var.first << endl;
            cout  << endl;
            continue;
        } else if (input_line == "whos") {
            // Find longest var name (for formatting)
            auto vars = *id_table;
            auto w = max_element(begin(vars), end(vars), [](pair<string, double> p1, pair<string, double> p2) {
                return p1.first.size() < p2.first.size();
            })->first.size();

            cout << endl;
            for (auto var : vars)
                cout << setw(w) << var.first << " = " << var.second << endl;
            cout << endl;
            continue;
        }

        auto reporter = make_shared<miniMAT::reporter::ErrorReporter>();
        miniMAT::lexer::Lexer   lexer(input_line, reporter);
        miniMAT::parser::Parser parser(lexer, reporter);

        auto ast = parser.Parse();

        if (reporter->HasErrors()) {
            reporter->ReportErrors();
            cout << endl;
            continue;
        }

        miniMAT::checker::Checker checker(id_table, reporter);
        ast = checker.check(ast);

        if (reporter->HasErrors()) {
            reporter->ReportErrors();
            cout << endl;
        } else {
            double ans = ast->VisitEvaluate(id_table);
            if (ast->GetClassName() == "ExprStmt") {
                auto exprstmt = dynamic_pointer_cast<miniMAT::ast::ExprStmt>(ast);
                if (exprstmt->expr->GetClassName() == "RefExpr") {
                    auto refexpr = dynamic_pointer_cast<miniMAT::ast::RefExpr>(exprstmt->expr);
                    auto varname = dynamic_pointer_cast<miniMAT::ast::IdRef>(refexpr->ref)->id->GetSpelling();

                    PrintResult(varname, id_table->at(varname), parser.SuppressedOutput());
                } else {
                    (*id_table)["ans"] = ans;

                    PrintResult("ans", ans, parser.SuppressedOutput());
                }

            } else if (ast->GetClassName() == "AssignStmt") {
                auto assign_stmt = dynamic_pointer_cast<miniMAT::ast::AssignStmt>(ast);

                if (assign_stmt->ref->GetClassName() == "IdRef") {
                    auto idref   = dynamic_pointer_cast<miniMAT::ast::IdRef>(assign_stmt->ref);

                    auto varname = idref->id->GetSpelling();
                    auto val     = assign_stmt->val;

                    PrintResult(varname, val, parser.SuppressedOutput());
                }
            }
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>/* listener.cc
   Mathieu Stefani, 12 August 2015

*/

#include <pistache/listener.h>
#include <pistache/peer.h>
#include <pistache/common.h>
#include <pistache/os.h>
#include <pistache/transport.h>
#include <pistache/errors.h>

#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <sys/epoll.h>
#include <sys/timerfd.h>

#include <chrono>
#include <memory>
#include <vector>

#include <cerrno>
#include <signal.h>

namespace Pistache {
namespace Tcp {

namespace {
    volatile sig_atomic_t g_listen_fd = -1;

    void closeListener() {
        if (g_listen_fd != -1) {
            ::close(g_listen_fd);
            g_listen_fd = -1;
        }
    }

    void handle_sigint(int) {
        closeListener();
    }
}

void setSocketOptions(Fd fd, Flags<Options> options) {
    if (options.hasFlag(Options::ReuseAddr)) {
        int one = 1;
        TRY(::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof (one)));
    }

    if (options.hasFlag(Options::Linger)) {
        struct linger opt;
        opt.l_onoff = 1;
        opt.l_linger = 1;
        TRY(::setsockopt(fd, SOL_SOCKET, SO_LINGER, &opt, sizeof (opt)));
    }

    if (options.hasFlag(Options::FastOpen)) {
        int hint = 5;
        TRY(::setsockopt(fd, SOL_TCP, TCP_FASTOPEN, &hint, sizeof (hint)));
    }
    if (options.hasFlag(Options::NoDelay)) {
        int one = 1;
        TRY(::setsockopt(fd, SOL_TCP, TCP_NODELAY, &one, sizeof (one)));
    }

}

Listener::Listener()
    : addr_()
    , listen_fd(-1)
    , backlog_(Const::MaxBacklog)
    , shutdownFd()
    , poller()
    , options_()
    , workers_(Const::DefaultWorkers)
    , reactor_()
    , transportKey()
{ }

Listener::Listener(const Address& address)
    : addr_(address)
    , listen_fd(-1)
    , backlog_(Const::MaxBacklog)
    , shutdownFd()
    , poller()
    , options_()
    , workers_(Const::DefaultWorkers)
    , reactor_()
    , transportKey()
{
}

Listener::~Listener() {
    if (isBound())
        shutdown();
    if (acceptThread.joinable())
        acceptThread.join();
}

void
Listener::init(
    size_t workers,
    Flags<Options> options, int backlog)
{
    if (workers > hardware_concurrency()) {
        // Log::warning() << "More workers than available cores"
    }

    options_ = options;
    backlog_ = backlog;

    if (options_.hasFlag(Options::InstallSignalHandler)) {
        if (signal(SIGINT, handle_sigint) == SIG_ERR) {
            throw std::runtime_error("Could not install signal handler");
        }
    }

    workers_ = workers;

}

void
Listener::setHandler(const std::shared_ptr<Handler>& handler) {
    handler_ = handler;
}

void
Listener::pinWorker(size_t worker, const CpuSet& set)
{
    UNUSED(worker)
    UNUSED(set)
#if 0
    if (ioGroup.empty()) {
        throw std::domain_error("Invalid operation, did you call init() before ?");
    }
    if (worker > ioGroup.size()) {
        throw std::invalid_argument("Trying to pin invalid worker");
    }

    auto &wrk = ioGroup[worker];
    wrk->pin(set);
#endif
}

bool
Listener::systemSupportsIpv6(){
    struct ifaddrs *ifaddr, *ifa;
    int family, n;
    bool supportsIpv6 = false;
    if (getifaddrs(&ifaddr) == -1) {
        throw std::runtime_error("Call to getifaddrs() failed");
    }

    for (ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++) {
            if (ifa->ifa_addr == NULL)
                continue;

            family = ifa->ifa_addr->sa_family;
            if (family == AF_INET6)
                continue;
    }
    freeifaddrs(ifaddr);
    return supportsIpv6;
}

void
Listener::bind() {
    bind(addr_);
}

void
Listener::bind(const Address& address) {
    if (!handler_)
        throw std::runtime_error("Call setHandler before calling bind()");
    addr_ = address;

    struct addrinfo hints;
    hints.ai_family = address.family();
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;
    hints.ai_protocol = 0;

    const auto& host = addr_.host();
    const auto& port = addr_.port().toString();
    struct addrinfo *addrs;
    TRY(::getaddrinfo(host.c_str(), port.c_str(), &hints, &addrs));

    int fd = -1;

    addrinfo *addr;
    for (addr = addrs; addr; addr = addr->ai_next) {
        fd = ::socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
        if (fd < 0) continue;

        setSocketOptions(fd, options_);

        if (::bind(fd, addr->ai_addr, addr->ai_addrlen) < 0) {
            close(fd);
            continue;
        }

        TRY(::listen(fd, backlog_));
        break;
    }

    // At this point, it is still possible that we couldn't bind any socket. If it is the case, the previous
    // loop would have exited naturally and addr will be null.
    if (addr == nullptr) {
        throw std::runtime_error(strerror(errno));
    }

    make_non_blocking(fd);
    poller.addFd(fd, Polling::NotifyOn::Read, Polling::Tag(fd));
    listen_fd = fd;
    g_listen_fd = fd;

    transport_ = std::make_shared<Transport>(handler_);

    reactor_.init(Aio::AsyncContext(workers_));
    transportKey = reactor_.addHandler(transport_);
}

bool
Listener::isBound() const {
    return listen_fd != -1;
}

// Return actual TCP port Listener is on, or 0 on error / no port.
// Notes:
// 1) Default constructor for 'Port()' sets value to 0.
// 2) Socket is created inside 'Listener::run()', which is called from
//    'Endpoint::serve()' and 'Endpoint::serveThreaded()'.  So getting the
//    port is only useful if you attempt to do so from a _different_ thread
//    than the one running 'Listener::run()'.  So for a traditional single-
//    threaded program this method is of little value.
Port
Listener::getPort() const {
    if (listen_fd == -1) {
        return Port();
    }

    struct sockaddr_in sock_addr = {0};
    socklen_t addrlen = sizeof(sock_addr);
    auto sock_addr_alias = reinterpret_cast<struct sockaddr*>(&sock_addr);

    if (-1 == getsockname(listen_fd, sock_addr_alias, &addrlen)) {
        return Port();
    }

    return Port(ntohs(sock_addr.sin_port));
}

void
Listener::run() {
    reactor_.run();

    for (;;) {
        std::vector<Polling::Event> events;

        int ready_fds = poller.poll(events, 128, std::chrono::milliseconds(-1));
        if (ready_fds == -1) {
            if (errno == EINTR && g_listen_fd == -1) return;
            throw Error::system("Polling");
        }
        for (const auto& event: events) {
            if (event.tag == shutdownFd.tag())
                return;

            if (event.flags.hasFlag(Polling::NotifyOn::Read)) {
                auto fd = event.tag.value();
                if (static_cast<ssize_t>(fd) == listen_fd) {
                    try {
                        handleNewConnection();
                    }
                    catch (SocketError& ex) {
                        std::cerr << "Server: " << ex.what() << std::endl;
                    }
                    catch (ServerError& ex) {
                        std::cerr << "Server: " << ex.what() << std::endl;
                        throw;
                    }
                }
            }
        }
    }
}

void
Listener::runThreaded() {
    shutdownFd.bind(poller);
    acceptThread = std::thread([=]() { this->run(); });
}

void
Listener::shutdown() {
    if (shutdownFd.isBound()) shutdownFd.notify();
    reactor_.shutdown();
}

Async::Promise<Listener::Load>
Listener::requestLoad(const Listener::Load& old) {
    auto handlers = reactor_.handlers(transportKey);

    std::vector<Async::Promise<rusage>> loads;
    for (const auto& handler: handlers) {
        auto transport = std::static_pointer_cast<Transport>(handler);
        loads.push_back(transport->load());
    }

    return Async::whenAll(std::begin(loads), std::end(loads)).then([=](const std::vector<rusage>& usages) {

        Load res;
        res.raw = usages;

        if (old.raw.empty()) {
            res.global = 0.0;
            for (size_t i = 0; i < handlers.size(); ++i) res.workers.push_back(0.0);
        } else {

            auto totalElapsed = [](rusage usage) {
                return (usage.ru_stime.tv_sec * 1e6 + usage.ru_stime.tv_usec)
                     + (usage.ru_utime.tv_sec * 1e6 + usage.ru_utime.tv_usec);
            };

            auto now = std::chrono::system_clock::now();
            auto diff = now - old.tick;
            auto tick = std::chrono::duration_cast<std::chrono::microseconds>(diff);
            res.tick = now;

            for (size_t i = 0; i < usages.size(); ++i) {
                auto last = old.raw[i];
                const auto& usage = usages[i];

                auto nowElapsed = totalElapsed(usage);
                auto timeElapsed = nowElapsed - totalElapsed(last);

                auto loadPct = (timeElapsed * 100.0) / tick.count();
                res.workers.push_back(loadPct);
                res.global += loadPct;

            }

            res.global /= usages.size();
        }

        return res;

     }, Async::Throw);
}

Address
Listener::address() const {
    return addr_;
}

Options
Listener::options() const {
    return options_;
}

void
Listener::handleNewConnection() {
    struct sockaddr_in peer_addr;
    socklen_t peer_addr_len = sizeof(peer_addr);
    int client_fd = ::accept(listen_fd, (struct sockaddr *)&peer_addr, &peer_addr_len);
    if (client_fd < 0) {
        if (errno == EBADF || errno == ENOTSOCK)
            throw ServerError(strerror(errno));
        else
            throw SocketError(strerror(errno));
    }

    make_non_blocking(client_fd);

    auto peer = std::make_shared<Peer>(Address::fromUnix((struct sockaddr *)&peer_addr));
    peer->associateFd(client_fd);

    dispatchPeer(peer);
}

void
Listener::dispatchPeer(const std::shared_ptr<Peer>& peer) {
    auto handlers = reactor_.handlers(transportKey);
    auto idx = peer->fd() % handlers.size();
    auto transport = std::static_pointer_cast<Transport>(handlers[idx]);

    transport->handleNewPeer(peer);

}

} // namespace Tcp
} // namespace Pistache
<commit_msg>Corrected silly mistake where boolean wasn't set<commit_after>/* listener.cc
   Mathieu Stefani, 12 August 2015

*/

#include <pistache/listener.h>
#include <pistache/peer.h>
#include <pistache/common.h>
#include <pistache/os.h>
#include <pistache/transport.h>
#include <pistache/errors.h>

#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <ifaddrs.h>
#include <netdb.h>
#include <sys/epoll.h>
#include <sys/timerfd.h>

#include <chrono>
#include <memory>
#include <vector>

#include <cerrno>
#include <signal.h>

namespace Pistache {
namespace Tcp {

namespace {
    volatile sig_atomic_t g_listen_fd = -1;

    void closeListener() {
        if (g_listen_fd != -1) {
            ::close(g_listen_fd);
            g_listen_fd = -1;
        }
    }

    void handle_sigint(int) {
        closeListener();
    }
}

void setSocketOptions(Fd fd, Flags<Options> options) {
    if (options.hasFlag(Options::ReuseAddr)) {
        int one = 1;
        TRY(::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof (one)));
    }

    if (options.hasFlag(Options::Linger)) {
        struct linger opt;
        opt.l_onoff = 1;
        opt.l_linger = 1;
        TRY(::setsockopt(fd, SOL_SOCKET, SO_LINGER, &opt, sizeof (opt)));
    }

    if (options.hasFlag(Options::FastOpen)) {
        int hint = 5;
        TRY(::setsockopt(fd, SOL_TCP, TCP_FASTOPEN, &hint, sizeof (hint)));
    }
    if (options.hasFlag(Options::NoDelay)) {
        int one = 1;
        TRY(::setsockopt(fd, SOL_TCP, TCP_NODELAY, &one, sizeof (one)));
    }

}

Listener::Listener()
    : addr_()
    , listen_fd(-1)
    , backlog_(Const::MaxBacklog)
    , shutdownFd()
    , poller()
    , options_()
    , workers_(Const::DefaultWorkers)
    , reactor_()
    , transportKey()
{ }

Listener::Listener(const Address& address)
    : addr_(address)
    , listen_fd(-1)
    , backlog_(Const::MaxBacklog)
    , shutdownFd()
    , poller()
    , options_()
    , workers_(Const::DefaultWorkers)
    , reactor_()
    , transportKey()
{
}

Listener::~Listener() {
    if (isBound())
        shutdown();
    if (acceptThread.joinable())
        acceptThread.join();
}

void
Listener::init(
    size_t workers,
    Flags<Options> options, int backlog)
{
    if (workers > hardware_concurrency()) {
        // Log::warning() << "More workers than available cores"
    }

    options_ = options;
    backlog_ = backlog;

    if (options_.hasFlag(Options::InstallSignalHandler)) {
        if (signal(SIGINT, handle_sigint) == SIG_ERR) {
            throw std::runtime_error("Could not install signal handler");
        }
    }

    workers_ = workers;

}

void
Listener::setHandler(const std::shared_ptr<Handler>& handler) {
    handler_ = handler;
}

void
Listener::pinWorker(size_t worker, const CpuSet& set)
{
    UNUSED(worker)
    UNUSED(set)
#if 0
    if (ioGroup.empty()) {
        throw std::domain_error("Invalid operation, did you call init() before ?");
    }
    if (worker > ioGroup.size()) {
        throw std::invalid_argument("Trying to pin invalid worker");
    }

    auto &wrk = ioGroup[worker];
    wrk->pin(set);
#endif
}

bool
Listener::systemSupportsIpv6(){
    struct ifaddrs *ifaddr, *ifa;
    int family, n;
    bool supportsIpv6 = false;
    if (getifaddrs(&ifaddr) == -1) {
        throw std::runtime_error("Call to getifaddrs() failed");
    }

    for (ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++) {
            if (ifa->ifa_addr == NULL)
                continue;

            family = ifa->ifa_addr->sa_family;
            if (family == AF_INET6) {
                supportsIpv6 = true;
                continue;
            }
    }
    freeifaddrs(ifaddr);
    return supportsIpv6;
}

void
Listener::bind() {
    bind(addr_);
}

void
Listener::bind(const Address& address) {
    if (!handler_)
        throw std::runtime_error("Call setHandler before calling bind()");
    addr_ = address;

    struct addrinfo hints;
    hints.ai_family = address.family();
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;
    hints.ai_protocol = 0;

    const auto& host = addr_.host();
    const auto& port = addr_.port().toString();
    struct addrinfo *addrs;
    TRY(::getaddrinfo(host.c_str(), port.c_str(), &hints, &addrs));

    int fd = -1;

    addrinfo *addr;
    for (addr = addrs; addr; addr = addr->ai_next) {
        fd = ::socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
        if (fd < 0) continue;

        setSocketOptions(fd, options_);

        if (::bind(fd, addr->ai_addr, addr->ai_addrlen) < 0) {
            close(fd);
            continue;
        }

        TRY(::listen(fd, backlog_));
        break;
    }

    // At this point, it is still possible that we couldn't bind any socket. If it is the case, the previous
    // loop would have exited naturally and addr will be null.
    if (addr == nullptr) {
        throw std::runtime_error(strerror(errno));
    }

    make_non_blocking(fd);
    poller.addFd(fd, Polling::NotifyOn::Read, Polling::Tag(fd));
    listen_fd = fd;
    g_listen_fd = fd;

    transport_ = std::make_shared<Transport>(handler_);

    reactor_.init(Aio::AsyncContext(workers_));
    transportKey = reactor_.addHandler(transport_);
}

bool
Listener::isBound() const {
    return listen_fd != -1;
}

// Return actual TCP port Listener is on, or 0 on error / no port.
// Notes:
// 1) Default constructor for 'Port()' sets value to 0.
// 2) Socket is created inside 'Listener::run()', which is called from
//    'Endpoint::serve()' and 'Endpoint::serveThreaded()'.  So getting the
//    port is only useful if you attempt to do so from a _different_ thread
//    than the one running 'Listener::run()'.  So for a traditional single-
//    threaded program this method is of little value.
Port
Listener::getPort() const {
    if (listen_fd == -1) {
        return Port();
    }

    struct sockaddr_in sock_addr = {0};
    socklen_t addrlen = sizeof(sock_addr);
    auto sock_addr_alias = reinterpret_cast<struct sockaddr*>(&sock_addr);

    if (-1 == getsockname(listen_fd, sock_addr_alias, &addrlen)) {
        return Port();
    }

    return Port(ntohs(sock_addr.sin_port));
}

void
Listener::run() {
    reactor_.run();

    for (;;) {
        std::vector<Polling::Event> events;

        int ready_fds = poller.poll(events, 128, std::chrono::milliseconds(-1));
        if (ready_fds == -1) {
            if (errno == EINTR && g_listen_fd == -1) return;
            throw Error::system("Polling");
        }
        for (const auto& event: events) {
            if (event.tag == shutdownFd.tag())
                return;

            if (event.flags.hasFlag(Polling::NotifyOn::Read)) {
                auto fd = event.tag.value();
                if (static_cast<ssize_t>(fd) == listen_fd) {
                    try {
                        handleNewConnection();
                    }
                    catch (SocketError& ex) {
                        std::cerr << "Server: " << ex.what() << std::endl;
                    }
                    catch (ServerError& ex) {
                        std::cerr << "Server: " << ex.what() << std::endl;
                        throw;
                    }
                }
            }
        }
    }
}

void
Listener::runThreaded() {
    shutdownFd.bind(poller);
    acceptThread = std::thread([=]() { this->run(); });
}

void
Listener::shutdown() {
    if (shutdownFd.isBound()) shutdownFd.notify();
    reactor_.shutdown();
}

Async::Promise<Listener::Load>
Listener::requestLoad(const Listener::Load& old) {
    auto handlers = reactor_.handlers(transportKey);

    std::vector<Async::Promise<rusage>> loads;
    for (const auto& handler: handlers) {
        auto transport = std::static_pointer_cast<Transport>(handler);
        loads.push_back(transport->load());
    }

    return Async::whenAll(std::begin(loads), std::end(loads)).then([=](const std::vector<rusage>& usages) {

        Load res;
        res.raw = usages;

        if (old.raw.empty()) {
            res.global = 0.0;
            for (size_t i = 0; i < handlers.size(); ++i) res.workers.push_back(0.0);
        } else {

            auto totalElapsed = [](rusage usage) {
                return (usage.ru_stime.tv_sec * 1e6 + usage.ru_stime.tv_usec)
                     + (usage.ru_utime.tv_sec * 1e6 + usage.ru_utime.tv_usec);
            };

            auto now = std::chrono::system_clock::now();
            auto diff = now - old.tick;
            auto tick = std::chrono::duration_cast<std::chrono::microseconds>(diff);
            res.tick = now;

            for (size_t i = 0; i < usages.size(); ++i) {
                auto last = old.raw[i];
                const auto& usage = usages[i];

                auto nowElapsed = totalElapsed(usage);
                auto timeElapsed = nowElapsed - totalElapsed(last);

                auto loadPct = (timeElapsed * 100.0) / tick.count();
                res.workers.push_back(loadPct);
                res.global += loadPct;

            }

            res.global /= usages.size();
        }

        return res;

     }, Async::Throw);
}

Address
Listener::address() const {
    return addr_;
}

Options
Listener::options() const {
    return options_;
}

void
Listener::handleNewConnection() {
    struct sockaddr_in peer_addr;
    socklen_t peer_addr_len = sizeof(peer_addr);
    int client_fd = ::accept(listen_fd, (struct sockaddr *)&peer_addr, &peer_addr_len);
    if (client_fd < 0) {
        if (errno == EBADF || errno == ENOTSOCK)
            throw ServerError(strerror(errno));
        else
            throw SocketError(strerror(errno));
    }

    make_non_blocking(client_fd);

    auto peer = std::make_shared<Peer>(Address::fromUnix((struct sockaddr *)&peer_addr));
    peer->associateFd(client_fd);

    dispatchPeer(peer);
}

void
Listener::dispatchPeer(const std::shared_ptr<Peer>& peer) {
    auto handlers = reactor_.handlers(transportKey);
    auto idx = peer->fd() % handlers.size();
    auto transport = std::static_pointer_cast<Transport>(handlers[idx]);

    transport->handleNewPeer(peer);

}

} // namespace Tcp
} // namespace Pistache
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkConjugateGradientOptimizerTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2000 National Library of Medicine
  All rights reserved.

  See COPYRIGHT.txt for copyright details.

=========================================================================*/

#include <itkConjugateGradientOptimizer.h>
#include <vnl/vnl_vector.h>
#include <vnl/vnl_matrix.h>

typedef vnl_matrix<double> MatrixType;
typedef vnl_vector<double> VectorType;

/**
 *  The objectif function is the quadratic form:
 *
 *  1/2 x^T A x - b^T x
 *
 *  Where A is represented as an itkMatrix and
 *  b is represented as a itkVector
 *
 *  The system in this example is:
 *
 *     | 3  2 ||x|   | 2|   |0|
 *     | 2  6 ||y| + |-8| = |0|
 *
 *
 *   the solution is the vector | 2 -2 |
 *
 */
class CostFunction {
public:
  enum { SpaceDimension=2 };
  CostFunction():m_A(2,2),m_b(2) {

    m_A[0][0] =  3;
    m_A[0][1] =  2;
    m_A[1][0] =  2;
    m_A[1][1] =  6;

    m_b[0]    =  2;
    m_b[1]    = -8;

  }
  double GetValue( const VectorType & v )
  {
    std::cout << "GetValue( " << v << " ) = ";
    VectorType Av = m_A * v;
    double val = ( inner_product<double>( Av , v ) )/2.0;
    val -= inner_product< double >( m_b , v );
    std::cout << val << std::endl;
    return val;
  }
  VectorType GetDerivative( const VectorType & v )
  {
    std::cout << "GetDerivative( " << v << " ) = ";
    VectorType grad = m_A * v  - m_b;
    std::cout << grad << std::endl;
    return grad;
  }

private:
  MatrixType        m_A;
  VectorType        m_b;
};

int main()
{

  typedef  itk::ConjugateGradientOptimizer<
                                CostFunction >  OptimizerType;

  typedef  OptimizerType::InternalOptimizerType  vnlOptimizerType;

  // Declaration of a itkOptimizer
  OptimizerType::Pointer  itkOptimizer = OptimizerType::New();

  // Declaration of the CostFunction adaptor
  CostFunction costFunction;

  itkOptimizer->SetCostFunction( &costFunction );

  const double F_Tolerance      = 1e-3;  // Function value tolerance
  const double G_Tolerance      = 1e-4;  // Gradient magnitude tolerance
  const double X_Tolerance      = 1e-8;  // Search space tolerance
  const double Epsilon_Function = 1e-10; // Step
  const int    Max_Iterations   =   100; // Maximum number of iterations

  vnlOptimizerType & vnlOptimizer = itkOptimizer->GetOptimizer();

  vnlOptimizer.set_f_tolerance( F_Tolerance );
  vnlOptimizer.set_g_tolerance( G_Tolerance );
  vnlOptimizer.set_x_tolerance( X_Tolerance );
  vnlOptimizer.set_epsilon_function( Epsilon_Function );
  vnlOptimizer.set_max_function_evals( Max_Iterations );

  vnlOptimizer.set_trace( true );   // activate print out per iteration
  vnlOptimizer.set_verbose( true ); // activate verbose mode

  vnlOptimizer.set_check_derivatives( 3 );

  VectorType initialValue(2);       // constructor requires vector size

  initialValue[0] =  100;             // We start not so far from  | 2 -2 |
  initialValue[1] = -100;

  itkOptimizer->StartOptimization( initialValue );

  std::cout << "End condition   = " << vnlOptimizer.get_failure_code() << std::endl;
  std::cout << "Number of iters = " << vnlOptimizer.get_num_iterations() << std::endl;
  std::cout << "Number of evals = " << vnlOptimizer.get_num_evaluations() << std::endl;

  return 0;

}

<commit_msg>ENH: Print out of the final solution added<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkConjugateGradientOptimizerTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2000 National Library of Medicine
  All rights reserved.

  See COPYRIGHT.txt for copyright details.

=========================================================================*/

#include <itkConjugateGradientOptimizer.h>
#include <vnl/vnl_vector.h>
#include <vnl/vnl_matrix.h>

typedef vnl_matrix<double> MatrixType;
typedef vnl_vector<double> VectorType;

/**
 *  The objectif function is the quadratic form:
 *
 *  1/2 x^T A x - b^T x
 *
 *  Where A is represented as an itkMatrix and
 *  b is represented as a itkVector
 *
 *  The system in this example is:
 *
 *     | 3  2 ||x|   | 2|   |0|
 *     | 2  6 ||y| + |-8| = |0|
 *
 *
 *   the solution is the vector | 2 -2 |
 *
 */
class CostFunction {
public:
  enum { SpaceDimension=2 };
  CostFunction():m_A(2,2),m_b(2) {

    m_A[0][0] =  3;
    m_A[0][1] =  2;
    m_A[1][0] =  2;
    m_A[1][1] =  6;

    m_b[0]    =  2;
    m_b[1]    = -8;

  }
  double GetValue( const VectorType & v )
  {
    std::cout << "GetValue( " << v << " ) = ";
    VectorType Av = m_A * v;
    double val = ( inner_product<double>( Av , v ) )/2.0;
    val -= inner_product< double >( m_b , v );
    std::cout << val << std::endl;
    return val;
  }
  VectorType GetDerivative( const VectorType & v )
  {
    std::cout << "GetDerivative( " << v << " ) = ";
    VectorType grad = m_A * v  - m_b;
    std::cout << grad << std::endl;
    return grad;
  }

private:
  MatrixType        m_A;
  VectorType        m_b;
};

int main()
{

  typedef  itk::ConjugateGradientOptimizer<
                                CostFunction >  OptimizerType;

  typedef  OptimizerType::InternalOptimizerType  vnlOptimizerType;

  // Declaration of a itkOptimizer
  OptimizerType::Pointer  itkOptimizer = OptimizerType::New();

  // Declaration of the CostFunction adaptor
  CostFunction costFunction;

  itkOptimizer->SetCostFunction( &costFunction );

  const double F_Tolerance      = 1e-3;  // Function value tolerance
  const double G_Tolerance      = 1e-4;  // Gradient magnitude tolerance
  const double X_Tolerance      = 1e-8;  // Search space tolerance
  const double Epsilon_Function = 1e-10; // Step
  const int    Max_Iterations   =   100; // Maximum number of iterations

  vnlOptimizerType & vnlOptimizer = itkOptimizer->GetOptimizer();

  vnlOptimizer.set_f_tolerance( F_Tolerance );
  vnlOptimizer.set_g_tolerance( G_Tolerance );
  vnlOptimizer.set_x_tolerance( X_Tolerance );
  vnlOptimizer.set_epsilon_function( Epsilon_Function );
  vnlOptimizer.set_max_function_evals( Max_Iterations );

  vnlOptimizer.set_trace( true );   // activate print out per iteration
  vnlOptimizer.set_verbose( true ); // activate verbose mode

  vnlOptimizer.set_check_derivatives( 3 );

  VectorType initialValue(2);       // constructor requires vector size

  initialValue[0] =  100;             // We start not so far from  | 2 -2 |
  initialValue[1] = -100;

  itkOptimizer->StartOptimization( initialValue );

  std::cout << "End condition   = " << vnlOptimizer.get_failure_code() << std::endl;
  std::cout << "Number of iters = " << vnlOptimizer.get_num_iterations() << std::endl;
  std::cout << "Number of evals = " << vnlOptimizer.get_num_evaluations() << std::endl;
  std::cout << std::endl;
  std::cout << "Solution        = " << initialValue << std::endl;

  return 0;

}

<|endoftext|>


<commit_before>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (c) 2010-2011 Arjen Hiemstra <ahiemstra@heimr.nl>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "mainwindow.h"

#include <unistd.h>

#include <KDE/KSplashScreen>
#include <KDE/KApplication>
#include <KDE/KAboutData>
#include <QString>
#include <KDE/KCmdLineArgs>
#include <KDE/KStandardDirs>
#include <QtDeclarative/QDeclarativeContext>
#include <QtDeclarative/QDeclarativeView>
#include <core/gluon_global.h>
#include "aboutdata.h"
#include <QDebug>

int main( int argc, char** argv )
{
    KAboutData aboutData = GluonCreator::aboutData();

    KCmdLineArgs::init( argc, argv, &aboutData );
    KCmdLineOptions options;
    options.add( "+project", ki18n( "Project to open" ) );
    KCmdLineArgs::addCmdLineOptions( options );

    KApplication app;
    KCmdLineArgs* args = KCmdLineArgs::parsedArgs();

    //Create and show a splashscreen
    KSplashScreen splash( QPixmap( KGlobal::dirs()->locate( "appdata", "gluon-creator-splash.png" ) ) );
    splash.show();
    app.processEvents();

    //Create the main window
    GluonCreator::MainWindow* window = new GluonCreator::MainWindow( args->count() > 0 ? args->arg( 0 ) : QString() );
    window->show();
    splash.finish( window );
    kapp->setActiveWindow(window);
    app.exec();
}
<commit_msg>creator: Remove the splash screen since we now have a proper welcome dialog<commit_after>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (c) 2010-2011 Arjen Hiemstra <ahiemstra@heimr.nl>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "mainwindow.h"

#include <unistd.h>

#include <KDE/KSplashScreen>
#include <KDE/KApplication>
#include <KDE/KAboutData>
#include <QString>
#include <KDE/KCmdLineArgs>
#include <KDE/KStandardDirs>
#include <QtDeclarative/QDeclarativeContext>
#include <QtDeclarative/QDeclarativeView>
#include <core/gluon_global.h>
#include "aboutdata.h"
#include <QDebug>

int main( int argc, char** argv )
{
    KAboutData aboutData = GluonCreator::aboutData();

    KCmdLineArgs::init( argc, argv, &aboutData );
    KCmdLineOptions options;
    options.add( "+project", ki18n( "Project to open" ) );
    KCmdLineArgs::addCmdLineOptions( options );

    KApplication app;
    KCmdLineArgs* args = KCmdLineArgs::parsedArgs();

    //Create the main window
    GluonCreator::MainWindow* window = new GluonCreator::MainWindow( args->count() > 0 ? args->arg( 0 ) : QString() );
    window->show();
    kapp->setActiveWindow(window);
    app.exec();
}
<|endoftext|>


<commit_before>//----------------------------------------------------------------------------
//
// "Copyright Centre National d'Etudes Spatiales"
//
// License:  LGPL
//
// See LICENSE.txt file in the top level directory for more details.
//
//----------------------------------------------------------------------------
// $Id$

#include <otb/HermiteInterpolator.h>

#include <string>
#include <cassert>
#include <cmath>

namespace ossimplugins
{

HermiteInterpolator::HermiteInterpolator():
  theNPointsAvailable(0),
  theXValues(NULL),
  theYValues(NULL),
  thedYValues(NULL),
  prodC(NULL),
  sumC(NULL),
  isComputed(false)
{
}

HermiteInterpolator::HermiteInterpolator(int nbrPoints, double* x, double* y, double* dy):
  theNPointsAvailable(nbrPoints),
  isComputed(false)
{
  if(x != NULL)
  {
    theXValues = new double[theNPointsAvailable];
    for (int i=0;i<theNPointsAvailable;i++)
    {
      theXValues[i] = x[i];
    }
  }
  else
  {
    theXValues = NULL;
  }

  if(y != NULL)
  {
    theYValues = new double[theNPointsAvailable];
    for (int i=0;i<theNPointsAvailable;i++)
    {
      theYValues[i] = y[i];
    }
  }
  else
  {
    theYValues = NULL;
  }

  if(dy != NULL)
  {
    thedYValues = new double[theNPointsAvailable];
    for (int i=0;i<theNPointsAvailable;i++)
    {
      thedYValues[i] = dy[i];
    }
  }
  else
  {
    thedYValues = NULL;
  }

  for (int i = 1 ; i < theNPointsAvailable ; i++)
  {
    /**
     * @todo Verifier que l'interpolateur n'ai pas besoin ques les abscisses soitent strictement croissantes
     */

    /*
     * Les abscisses ne sont pas croissantes
     */
//    if (theXValues[i] <= theXValues[i-1])
//      std::cerr << "WARNING: Hermite interpolation assumes increasing x values" << std::endl;
    assert(theXValues[i] > theXValues[i-1]);
  }
}

HermiteInterpolator::~HermiteInterpolator()
{
  Clear();
}

HermiteInterpolator::HermiteInterpolator(const HermiteInterpolator& rhs):
  theNPointsAvailable(rhs.theNPointsAvailable),
  isComputed(false)
{
  if(rhs.theXValues != NULL)
  {
    theXValues = new double[theNPointsAvailable];
    for (int i=0;i<theNPointsAvailable;i++)
    {
      theXValues[i] = rhs.theXValues[i];
    }
  }
  else
  {
    theXValues = NULL;
  }

  if(rhs.theYValues != NULL)
  {
    theYValues = new double[theNPointsAvailable];
    for (int i=0;i<theNPointsAvailable;i++)
    {
      theYValues[i] = rhs.theYValues[i];
    }
  }
  else
  {
    theYValues = NULL;
  }

  if(rhs.thedYValues != NULL)
  {
    thedYValues = new double[theNPointsAvailable];
    for (int i=0;i<theNPointsAvailable;i++)
    {
      thedYValues[i] = rhs.thedYValues[i];
    }
  }
  else
  {
    thedYValues = NULL;
  }
}

HermiteInterpolator& HermiteInterpolator::operator =(const HermiteInterpolator& rhs)
{
  Clear();
  theNPointsAvailable = rhs.theNPointsAvailable;
  isComputed = false;
  if(rhs.theXValues != NULL)
  {
    theXValues = new double[theNPointsAvailable];
    for (int i=0;i<theNPointsAvailable;i++)
    {
      theXValues[i] = rhs.theXValues[i];
    }
  }
  else
  {
    theXValues = NULL;
  }

  if(rhs.theYValues != NULL)
  {
    theYValues = new double[theNPointsAvailable];
    for (int i=0;i<theNPointsAvailable;i++)
    {
      theYValues[i] = rhs.theYValues[i];
    }
  }
  else
  {
    theYValues = NULL;
  }

  if(rhs.thedYValues != NULL)
  {
    thedYValues = new double[theNPointsAvailable];
    for (int i=0;i<theNPointsAvailable;i++)
    {
      thedYValues[i] = rhs.thedYValues[i];
    }
  }
  else
  {
    thedYValues = NULL;
  }

  return *this;
}

// Interpolation method for the value and the derivative
int HermiteInterpolator::Interpolate(double x, double& y, double& dy) const
{
  //NOTE assume that x is increasing

  // Not enough points to interpolate
  if (theNPointsAvailable < 2) return -1;

  y = 0.0;
  dy = 0.0;

  double epsilon = 0.0000000000001;

  //Precompute useful value if they are not available
  if (!isComputed)
  {
    Precompute();
  }

  for (int i = 0; i < theNPointsAvailable; i++)
  {
    double si = 0.0;
    double hi = 1.0;
    double ui = 0; //derivative computation
    double r = x - theXValues[i];

    // check if the point is on the list
    if ( std::abs(r/x) < epsilon )
    {
      y = theYValues[i];
      dy = thedYValues[i];
      return 0;
    }

    for (int j = 0; j < theNPointsAvailable; j++)
    {
      if (j != i)
      {
        hi = hi * (x - theXValues[j]);
        ui = ui + 1 / (x - theXValues[j]);//derivative computation
      }
    }
    hi *= prodC[i];
    si = sumC[i];

    double f = 1.0 - 2.0 * r * si;

    y += (theYValues[i] * f + thedYValues[i] * r) * hi * hi;

    ui *= hi;//derivative computation

    double fp = 2.0 * hi * (ui * (1.0 - 2.0 * si * r) - hi * si);//derivative computation
    double d = hi * (hi + 2.0 * r * ui);//derivative computation

    dy += fp * theYValues[i] + d * thedYValues[i];//derivative computation

  }

  return 0;
}

// Interpolation method for the value only
// this is about 5 times faster and should be used when time
// is a constraint.
int HermiteInterpolator::Interpolate(double x, double& y) const
{
  //NOTE assume that x is increasing

  // Not enough points to interpolate
  if (theNPointsAvailable < 2) return -1;

  y = 0.0;

  //Precompute useful value if they are not available
  if (!isComputed)
  {
    Precompute();
  }

  for (int i = 0; i < theNPointsAvailable; i++)
  {
    double si = 0.0;
    double hi = 1.0;
    double r = x - theXValues[i];

    for (int j = 0; j < theNPointsAvailable; j++)
    {
      if (j != i)
      {
        hi = hi * (x - theXValues[j]);
      }
    }
    hi *= prodC[i];
    si = sumC[i];

    double f = 1.0 - 2.0 * r * si;

    y += (theYValues[i] * f + thedYValues[i] * r) * hi * hi;

  }

  return 0;
}

int HermiteInterpolator::Precompute() const
{
  prodC = new double[theNPointsAvailable];
  sumC= new double[theNPointsAvailable];

  for (int i = 0; i < theNPointsAvailable; i++)
  {
    prodC[i] = 1;
    sumC[i] = 0;
    for (int j = 0; j < theNPointsAvailable; j++)
    {
      if (j != i)
      {
        double v = 1.0 / (theXValues[i] - theXValues[j]);
        prodC[i] *= v;
        sumC[i]  += v;
      }
    }
  }
  isComputed = true;
  return 0;
}

void HermiteInterpolator::Clear()
{
  if (theXValues != NULL)
  {
    delete[] theXValues;
    theXValues = NULL;
  }

  if (theYValues != NULL)
  {
    delete[] theYValues;
    theYValues = NULL;
  }

  if (thedYValues != NULL)
  {
    delete[] thedYValues;
    thedYValues = NULL;
  }

  if (prodC != NULL)
  {
    delete[] prodC;
    prodC = NULL;
  }

  if (sumC != NULL)
  {
    delete[] sumC;
    prodC = NULL;
  }
  isComputed = false;
  theNPointsAvailable = 0;
}
}
<commit_msg>BUG: fix Asar limit case<commit_after>//----------------------------------------------------------------------------
//
// "Copyright Centre National d'Etudes Spatiales"
//
// License:  LGPL
//
// See LICENSE.txt file in the top level directory for more details.
//
//----------------------------------------------------------------------------
// $Id$

#include <otb/HermiteInterpolator.h>

#include <string>
#include <cassert>
#include <cmath>

namespace ossimplugins
{

HermiteInterpolator::HermiteInterpolator():
  theNPointsAvailable(0),
  theXValues(NULL),
  theYValues(NULL),
  thedYValues(NULL),
  prodC(NULL),
  sumC(NULL),
  isComputed(false)
{
}

HermiteInterpolator::HermiteInterpolator(int nbrPoints, double* x, double* y, double* dy):
  theNPointsAvailable(nbrPoints),
  isComputed(false)
{
  if(x != NULL)
  {
    theXValues = new double[theNPointsAvailable];
    for (int i=0;i<theNPointsAvailable;i++)
    {
      theXValues[i] = x[i];
    }
  }
  else
  {
    theXValues = NULL;
  }

  if(y != NULL)
  {
    theYValues = new double[theNPointsAvailable];
    for (int i=0;i<theNPointsAvailable;i++)
    {
      theYValues[i] = y[i];
    }
  }
  else
  {
    theYValues = NULL;
  }

  if(dy != NULL)
  {
    thedYValues = new double[theNPointsAvailable];
    for (int i=0;i<theNPointsAvailable;i++)
    {
      thedYValues[i] = dy[i];
    }
  }
  else
  {
    thedYValues = NULL;
  }

  for (int i = 1 ; i < theNPointsAvailable ; i++)
  {
    /**
     * @todo Verifier que l'interpolateur n'ai pas besoin ques les abscisses soitent strictement croissantes
     */

    /*
     * Les abscisses ne sont pas croissantes
     */
//    if (theXValues[i] <= theXValues[i-1])
//      std::cerr << "WARNING: Hermite interpolation assumes increasing x values" << std::endl;
    assert(theXValues[i] > theXValues[i-1]);
  }
}

HermiteInterpolator::~HermiteInterpolator()
{
  Clear();
}

HermiteInterpolator::HermiteInterpolator(const HermiteInterpolator& rhs):
  theNPointsAvailable(rhs.theNPointsAvailable),
  isComputed(false)
{
  if(rhs.theXValues != NULL)
  {
    theXValues = new double[theNPointsAvailable];
    for (int i=0;i<theNPointsAvailable;i++)
    {
      theXValues[i] = rhs.theXValues[i];
    }
  }
  else
  {
    theXValues = NULL;
  }

  if(rhs.theYValues != NULL)
  {
    theYValues = new double[theNPointsAvailable];
    for (int i=0;i<theNPointsAvailable;i++)
    {
      theYValues[i] = rhs.theYValues[i];
    }
  }
  else
  {
    theYValues = NULL;
  }

  if(rhs.thedYValues != NULL)
  {
    thedYValues = new double[theNPointsAvailable];
    for (int i=0;i<theNPointsAvailable;i++)
    {
      thedYValues[i] = rhs.thedYValues[i];
    }
  }
  else
  {
    thedYValues = NULL;
  }
}

HermiteInterpolator& HermiteInterpolator::operator =(const HermiteInterpolator& rhs)
{
  Clear();
  theNPointsAvailable = rhs.theNPointsAvailable;
  isComputed = false;
  if(rhs.theXValues != NULL)
  {
    theXValues = new double[theNPointsAvailable];
    for (int i=0;i<theNPointsAvailable;i++)
    {
      theXValues[i] = rhs.theXValues[i];
    }
  }
  else
  {
    theXValues = NULL;
  }

  if(rhs.theYValues != NULL)
  {
    theYValues = new double[theNPointsAvailable];
    for (int i=0;i<theNPointsAvailable;i++)
    {
      theYValues[i] = rhs.theYValues[i];
    }
  }
  else
  {
    theYValues = NULL;
  }

  if(rhs.thedYValues != NULL)
  {
    thedYValues = new double[theNPointsAvailable];
    for (int i=0;i<theNPointsAvailable;i++)
    {
      thedYValues[i] = rhs.thedYValues[i];
    }
  }
  else
  {
    thedYValues = NULL;
  }

  return *this;
}

// Interpolation method for the value and the derivative
int HermiteInterpolator::Interpolate(double x, double& y, double& dy) const
{
  //NOTE assume that x is increasing

  // Not enough points to interpolate
  if (theNPointsAvailable < 2) return -1;

  y = 0.0;
  dy = 0.0;

  double epsilon = 0.0000000000001;

  //Precompute useful value if they are not available
  if (!isComputed)
  {
    Precompute();
  }

  for (int i = 0; i < theNPointsAvailable; i++)
  {
    double si = 0.0;
    double hi = 1.0;
    double ui = 0; //derivative computation
    double r = x - theXValues[i];

    // check if the point is on the list
    if ( std::abs(r) < epsilon )
    {
      y = theYValues[i];
      dy = thedYValues[i];
      return 0;
    }

    for (int j = 0; j < theNPointsAvailable; j++)
    {
      if (j != i)
      {
        hi = hi * (x - theXValues[j]);
        ui = ui + 1 / (x - theXValues[j]);//derivative computation
      }
    }
    hi *= prodC[i];
    si = sumC[i];

    double f = 1.0 - 2.0 * r * si;

    y += (theYValues[i] * f + thedYValues[i] * r) * hi * hi;

    ui *= hi;//derivative computation

    double fp = 2.0 * hi * (ui * (1.0 - 2.0 * si * r) - hi * si);//derivative computation
    double d = hi * (hi + 2.0 * r * ui);//derivative computation

    dy += fp * theYValues[i] + d * thedYValues[i];//derivative computation

  }

  return 0;
}

// Interpolation method for the value only
// this is about 5 times faster and should be used when time
// is a constraint.
int HermiteInterpolator::Interpolate(double x, double& y) const
{
  //NOTE assume that x is increasing

  // Not enough points to interpolate
  if (theNPointsAvailable < 2) return -1;

  y = 0.0;

  //Precompute useful value if they are not available
  if (!isComputed)
  {
    Precompute();
  }

  for (int i = 0; i < theNPointsAvailable; i++)
  {
    double si = 0.0;
    double hi = 1.0;
    double r = x - theXValues[i];

    for (int j = 0; j < theNPointsAvailable; j++)
    {
      if (j != i)
      {
        hi = hi * (x - theXValues[j]);
      }
    }
    hi *= prodC[i];
    si = sumC[i];

    double f = 1.0 - 2.0 * r * si;

    y += (theYValues[i] * f + thedYValues[i] * r) * hi * hi;

  }

  return 0;
}

int HermiteInterpolator::Precompute() const
{
  prodC = new double[theNPointsAvailable];
  sumC= new double[theNPointsAvailable];

  for (int i = 0; i < theNPointsAvailable; i++)
  {
    prodC[i] = 1;
    sumC[i] = 0;
    for (int j = 0; j < theNPointsAvailable; j++)
    {
      if (j != i)
      {
        double v = 1.0 / (theXValues[i] - theXValues[j]);
        prodC[i] *= v;
        sumC[i]  += v;
      }
    }
  }
  isComputed = true;
  return 0;
}

void HermiteInterpolator::Clear()
{
  if (theXValues != NULL)
  {
    delete[] theXValues;
    theXValues = NULL;
  }

  if (theYValues != NULL)
  {
    delete[] theYValues;
    theYValues = NULL;
  }

  if (thedYValues != NULL)
  {
    delete[] thedYValues;
    thedYValues = NULL;
  }

  if (prodC != NULL)
  {
    delete[] prodC;
    prodC = NULL;
  }

  if (sumC != NULL)
  {
    delete[] sumC;
    prodC = NULL;
  }
  isComputed = false;
  theNPointsAvailable = 0;
}
}
<|endoftext|>


<commit_before>/*************************************************************************
> File Name: CardLoader.cpp
> Project Name: Hearthstone++
> Author: Chan-Ho Chris Ohk
> Purpose: Card loader that loads data from cards.json.
> Created Time: 2017/08/13
> Copyright (c) 2017, Chan-Ho Chris Ohk
*************************************************************************/
#include <Enums/StringToEnums.h>
#include <Loaders/CardLoader.h>
#include <Models/Entities/Enchantment.h>
#include <Models/Entities/Hero.h>
#include <Models/Entities/HeroPower.h>
#include <Models/Entities/Minion.h>
#include <Models/Entities/Spell.h>
#include <Models/Entities/Weapon.h>

#include <fstream>

namespace Hearthstonepp
{
	std::vector<Card*> CardLoader::Load() const
	{
		// Read card data from JSON file
		std::ifstream cardFile(RESOURCES_DIR "cards.json");
		json j;

		if (!cardFile.is_open())
		{
			throw std::runtime_error("Can't open cards.json");
		}

		cardFile >> j;

		std::vector<Card*> cards;
		cards.reserve(j.size());

		for (auto& card : j)
		{
			const std::string id = std::move(card["id"].get<std::string>());
			const Rarity rarity = card["rarity"].is_null() ? Rarity::FREE : std::move(ConverterFromStringToRarity.at(card["rarity"].get<std::string>()));
			const Faction faction = card["faction"].is_null() ? Faction::NEUTRAL : std::move(ConverterFromStringToFaction.at(card["faction"].get<std::string>()));
			const CardSet cardSet = card["set"].is_null() ? CardSet::NONE : std::move(ConverterFromStringToCardSet.at(card["set"].get<std::string>()));
			const CardClass cardClass = card["cardClass"].is_null() ? CardClass::NEUTRAL : std::move(ConverterFromStringToCardClass.at(card["cardClass"].get<std::string>()));
			const CardType cardType = card["type"].is_null() ? CardType::INVALID : std::move(ConverterFromStringToCardType.at(card["type"].get<std::string>()));
			const Race race = card["race"].is_null() ? Race::INVALID : std::move(ConverterFromStringToRace.at(card["race"].get<std::string>()));

			const std::string name = card["name"].is_null() ? "" : std::move(card["name"]["enUS"].get<std::string>());
			const std::string text = card["text"].is_null() ? "" : std::move(card["text"]["enUS"].get<std::string>());

			const bool collectible = card["collectible"].is_null() ? false : card["collectible"].get<bool>();
			const int cost = card["cost"].is_null() ? -1 : card["cost"].get<int>();
			const int attack = card["attack"].is_null() ? -1 : card["attack"].get<int>();
			const int health = card["health"].is_null() ? -1 : card["health"].get<int>();
			const int durability = card["durability"].is_null() ? -1 : card["durability"].get<int>();

			std::vector<GameTag> mechanics;
			for (auto& mechanic : card["mechanics"])
			{
				mechanics.emplace_back(std::move(ConverterFromStringToGameTag.at(mechanic.get<std::string>())));
			}

			std::map<PlayReq, int> playRequirements;
			for (auto iter = card["playRequirements"].begin(); iter != card["playRequirements"].end(); ++iter)
			{
				playRequirements.try_emplace(std::move(ConverterFromStringToPlayReq.at(iter.key())), iter.value().get<int>());
			}

			std::vector<std::string> entourages;
			for (auto& entourage : card["entourage"])
			{
				entourages.emplace_back(std::move(entourage.get<std::string>()));
			}

			Card* c;
			switch (cardType)
			{
			case CardType::HERO:
				c = new Hero(
					id, rarity, faction, cardSet, cardClass, cardType, race,
					name, text, collectible, cost, attack, health, durability,
					mechanics, playRequirements, entourages);
				break;
			case CardType::MINION:
				c = new Minion(
					id, rarity, faction, cardSet, cardClass, cardType, race,
					name, text, collectible, cost, attack, health, durability,
					mechanics, playRequirements, entourages);
				break;
			case CardType::SPELL:
				c = new Spell(
					id, rarity, faction, cardSet, cardClass, cardType, race,
					name, text, collectible, cost, attack, health, durability,
					mechanics, playRequirements, entourages);
				break;
			case CardType::ENCHANTMENT:
				c = new Enchantment(
					id, rarity, faction, cardSet, cardClass, cardType, race,
					name, text, collectible, cost, attack, health, durability,
					mechanics, playRequirements, entourages);
				break;
			case CardType::WEAPON:
				c = new Weapon(
					id, rarity, faction, cardSet, cardClass, cardType, race,
					name, text, collectible, cost, attack, health, durability,
					mechanics, playRequirements, entourages);
				break;
			case CardType::HERO_POWER:
				c = new HeroPower(
					id, rarity, faction, cardSet, cardClass, cardType, race,
					name, text, collectible, cost, attack, health, durability,
					mechanics, playRequirements, entourages);
				break;
			default:
				// TODO: Log invalid card type
				break;
			}

			cards.emplace_back(c);
		}

		cardFile.close();

		return cards;
	}
}<commit_msg>Update CardLoader.cpp - Remove std::move for copy elision<commit_after>/*************************************************************************
> File Name: CardLoader.cpp
> Project Name: Hearthstone++
> Author: Chan-Ho Chris Ohk
> Purpose: Card loader that loads data from cards.json.
> Created Time: 2017/08/13
> Copyright (c) 2017, Chan-Ho Chris Ohk
*************************************************************************/
#include <Enums/StringToEnums.h>
#include <Loaders/CardLoader.h>
#include <Models/Entities/Enchantment.h>
#include <Models/Entities/Hero.h>
#include <Models/Entities/HeroPower.h>
#include <Models/Entities/Minion.h>
#include <Models/Entities/Spell.h>
#include <Models/Entities/Weapon.h>

#include <fstream>

namespace Hearthstonepp
{
	std::vector<Card*> CardLoader::Load() const
	{
		// Read card data from JSON file
		std::ifstream cardFile(RESOURCES_DIR "cards.json");
		json j;

		if (!cardFile.is_open())
		{
			throw std::runtime_error("Can't open cards.json");
		}

		cardFile >> j;

		std::vector<Card*> cards;
		cards.reserve(j.size());

		for (auto& card : j)
		{
			const std::string id = card["id"].get<std::string>();
			const Rarity rarity = card["rarity"].is_null() ? Rarity::FREE : std::move(ConverterFromStringToRarity.at(card["rarity"].get<std::string>()));
			const Faction faction = card["faction"].is_null() ? Faction::NEUTRAL : std::move(ConverterFromStringToFaction.at(card["faction"].get<std::string>()));
			const CardSet cardSet = card["set"].is_null() ? CardSet::NONE : std::move(ConverterFromStringToCardSet.at(card["set"].get<std::string>()));
			const CardClass cardClass = card["cardClass"].is_null() ? CardClass::NEUTRAL : std::move(ConverterFromStringToCardClass.at(card["cardClass"].get<std::string>()));
			const CardType cardType = card["type"].is_null() ? CardType::INVALID : std::move(ConverterFromStringToCardType.at(card["type"].get<std::string>()));
			const Race race = card["race"].is_null() ? Race::INVALID : std::move(ConverterFromStringToRace.at(card["race"].get<std::string>()));

			const std::string name = card["name"].is_null() ? "" : card["name"]["enUS"].get<std::string>();
			const std::string text = card["text"].is_null() ? "" : card["text"]["enUS"].get<std::string>();

			const bool collectible = card["collectible"].is_null() ? false : card["collectible"].get<bool>();
			const int cost = card["cost"].is_null() ? -1 : card["cost"].get<int>();
			const int attack = card["attack"].is_null() ? -1 : card["attack"].get<int>();
			const int health = card["health"].is_null() ? -1 : card["health"].get<int>();
			const int durability = card["durability"].is_null() ? -1 : card["durability"].get<int>();

			std::vector<GameTag> mechanics;
			for (auto& mechanic : card["mechanics"])
			{
				mechanics.emplace_back(std::move(ConverterFromStringToGameTag.at(mechanic.get<std::string>())));
			}

			std::map<PlayReq, int> playRequirements;
			for (auto iter = card["playRequirements"].begin(); iter != card["playRequirements"].end(); ++iter)
			{
				playRequirements.try_emplace(std::move(ConverterFromStringToPlayReq.at(iter.key())), iter.value().get<int>());
			}

			std::vector<std::string> entourages;
			for (auto& entourage : card["entourage"])
			{
				entourages.emplace_back(entourage.get<std::string>());
			}

			Card* c;
			switch (cardType)
			{
			case CardType::HERO:
				c = new Hero(
					id, rarity, faction, cardSet, cardClass, cardType, race,
					name, text, collectible, cost, attack, health, durability,
					mechanics, playRequirements, entourages);
				break;
			case CardType::MINION:
				c = new Minion(
					id, rarity, faction, cardSet, cardClass, cardType, race,
					name, text, collectible, cost, attack, health, durability,
					mechanics, playRequirements, entourages);
				break;
			case CardType::SPELL:
				c = new Spell(
					id, rarity, faction, cardSet, cardClass, cardType, race,
					name, text, collectible, cost, attack, health, durability,
					mechanics, playRequirements, entourages);
				break;
			case CardType::ENCHANTMENT:
				c = new Enchantment(
					id, rarity, faction, cardSet, cardClass, cardType, race,
					name, text, collectible, cost, attack, health, durability,
					mechanics, playRequirements, entourages);
				break;
			case CardType::WEAPON:
				c = new Weapon(
					id, rarity, faction, cardSet, cardClass, cardType, race,
					name, text, collectible, cost, attack, health, durability,
					mechanics, playRequirements, entourages);
				break;
			case CardType::HERO_POWER:
				c = new HeroPower(
					id, rarity, faction, cardSet, cardClass, cardType, race,
					name, text, collectible, cost, attack, health, durability,
					mechanics, playRequirements, entourages);
				break;
			default:
				// TODO: Log invalid card type
				break;
			}

			cards.emplace_back(c);
		}

		cardFile.close();

		return cards;
	}
}<|endoftext|>