<commit_before>// To regenerate this list of includes run the following command from skia/include:
//
//     find core effects pathops  -maxdepth 1 -name "*.h" | sed "s#^[^\/]*\/##g" | sed "s/\(.*\)/#include \"\1\"/" | sort
//
#include "Sk1DPathEffect.h"
#include "Sk2DPathEffect.h"
#include "SkAdvancedTypefaceMetrics.h"
#include "SkAlphaThresholdFilter.h"
#include "SkAnnotation.h"
#include "SkArithmeticMode.h"
#include "SkAvoidXfermode.h"
#include "SkBBHFactory.h"
#include "SkBitmapDevice.h"
#include "SkBitmap.h"
#include "SkBitmapSource.h"
#include "SkBlitRow.h"
#include "SkBlurDrawLooper.h"
#include "SkBlurImageFilter.h"
#include "SkBlurMaskFilter.h"
#include "SkBlurTypes.h"
#include "SkCanvas.h"
#include "SkChecksum.h"
#include "SkChunkAlloc.h"
#include "SkClipStack.h"
#include "SkColorFilter.h"
#include "SkColorFilterImageFilter.h"
#include "SkColor.h"
#include "SkColorMatrixFilter.h"
#include "SkColorMatrix.h"
#include "SkColorPriv.h"
#include "SkColorShader.h"
#include "SkColorTable.h"
#include "SkComposeImageFilter.h"
#include "SkComposeShader.h"
#include "SkCornerPathEffect.h"
#include "SkDashPathEffect.h"
#include "SkData.h"
#include "SkDataTable.h"
#include "SkDeque.h"
#include "SkDevice.h"
#include "SkDeviceProperties.h"
#include "SkDiscretePathEffect.h"
#include "SkDisplacementMapEffect.h"
#include "SkDither.h"
#include "SkDocument.h"
#include "SkDrawExtraPathEffect.h"
#include "SkDrawFilter.h"
#include "SkDraw.h"
#include "SkDrawLooper.h"
#include "SkDropShadowImageFilter.h"
#include "SkDynamicAnnotations.h"
#include "SkEmbossMaskFilter.h"
#include "SkEmptyShader.h"
#include "SkEndian.h"
#include "SkError.h"
#include "SkFixed.h"
#include "SkFlate.h"
#include "SkFlattenable.h"
#include "SkFlattenableSerialization.h"
#include "SkFloatBits.h"
#include "SkFloatingPoint.h"
#include "SkFont.h"
#include "SkFontHost.h"
#include "SkFontLCDConfig.h"
#include "SkGeometry.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkImageEncoder.h"
#include "SkImageFilter.h"
#include "SkImageGenerator.h"
#include "SkImage.h"
#include "SkImageInfo.h"
#include "SkInstCnt.h"
#include "SkLayerDrawLooper.h"
#include "SkLayerRasterizer.h"
#include "SkLerpXfermode.h"
#include "SkLightingImageFilter.h"
#include "SkLineClipper.h"
#include "SkLumaColorFilter.h"
#include "SkMagnifierImageFilter.h"
#include "SkMallocPixelRef.h"
#include "SkMaskFilter.h"
#include "SkMask.h"
#include "SkMath.h"
#include "SkMatrixConvolutionImageFilter.h"
#include "SkMatrix.h"
#include "SkMatrixImageFilter.h"
#include "SkMergeImageFilter.h"
#include "SkMetaData.h"
#include "SkMorphologyImageFilter.h"
#include "SkOffsetImageFilter.h"
#include "SkOnce.h"
#include "SkOSFile.h"
#include "SkPackBits.h"
#include "SkPaintFlagsDrawFilter.h"
#include "SkPaint.h"
#include "SkPaintOptionsAndroid.h"
#include "SkPathEffect.h"
#include "SkPath.h"
#include "SkPathMeasure.h"
#include "SkPathOps.h"
#include "SkPathRef.h"
#include "SkPerlinNoiseShader.h"
#include "SkPicture.h"
#include "SkPictureImageFilter.h"
#include "SkPictureRecorder.h"
#include "SkPixelRef.h"
#include "SkPixelXorXfermode.h"
#include "SkPoint.h"
#include "SkPorterDuff.h"
#include "SkPostConfig.h"
#include "SkPreConfig.h"
#include "SkRasterizer.h"
#include "SkReadBuffer.h"
#include "SkReader32.h"
#include "SkRect.h"
#include "SkRectShaderImageFilter.h"
#include "SkRefCnt.h"
#include "SkRegion.h"
#include "SkRRect.h"
#include "SkScalar.h"
#include "SkShader.h"
#include "SkSize.h"
#include "SkStream.h"
#include "SkString.h"
#include "SkStringUtils.h"
#include "SkStrokeRec.h"
#include "SkSurface.h"
#include "SkTableColorFilter.h"
#include "SkTableMaskFilter.h"
#include "SkTArray.h"
#include "SkTDArray.h"
#include "SkTDict.h"
#include "SkTDStack.h"
#include "SkTemplates.h"
#include "SkTestImageFilters.h"
#include "SkThread.h"
#include "SkTileImageFilter.h"
#include "SkTime.h"
#include "SkTInternalLList.h"
#include "SkTLazy.h"
#include "SkTransparentShader.h"
#include "SkTRegistry.h"
#include "SkTSearch.h"
#include "SkTypeface.h"
#include "SkTypes.h"
#include "SkUnPreMultiply.h"
#include "SkUtils.h"
#include "SkVertState.h"
#include "SkWeakRefCnt.h"
#include "SkWriteBuffer.h"
#include "SkWriter32.h"
#include "SkXfermode.h"
#include "SkXfermodeImageFilter.h"

SkBitmap source;

{{.Code}}
<commit_msg>Revert "Move SkReadBuffer.h and SkReader32.h out of include."<commit_after>// To regenerate this list of includes run the following command from skia/include:
//
//     find core effects pathops  -maxdepth 1 -name "*.h" | sed "s#^[^\/]*\/##g" | sed "s/\(.*\)/#include \"\1\"/" | sort
//
#include "Sk1DPathEffect.h"
#include "Sk2DPathEffect.h"
#include "SkAdvancedTypefaceMetrics.h"
#include "SkAlphaThresholdFilter.h"
#include "SkAnnotation.h"
#include "SkArithmeticMode.h"
#include "SkAvoidXfermode.h"
#include "SkBBHFactory.h"
#include "SkBitmapDevice.h"
#include "SkBitmap.h"
#include "SkBitmapSource.h"
#include "SkBlitRow.h"
#include "SkBlurDrawLooper.h"
#include "SkBlurImageFilter.h"
#include "SkBlurMaskFilter.h"
#include "SkBlurTypes.h"
#include "SkCanvas.h"
#include "SkChecksum.h"
#include "SkChunkAlloc.h"
#include "SkClipStack.h"
#include "SkColorFilter.h"
#include "SkColorFilterImageFilter.h"
#include "SkColor.h"
#include "SkColorMatrixFilter.h"
#include "SkColorMatrix.h"
#include "SkColorPriv.h"
#include "SkColorShader.h"
#include "SkColorTable.h"
#include "SkComposeImageFilter.h"
#include "SkComposeShader.h"
#include "SkCornerPathEffect.h"
#include "SkDashPathEffect.h"
#include "SkData.h"
#include "SkDataTable.h"
#include "SkDeque.h"
#include "SkDevice.h"
#include "SkDeviceProperties.h"
#include "SkDiscretePathEffect.h"
#include "SkDisplacementMapEffect.h"
#include "SkDither.h"
#include "SkDocument.h"
#include "SkDrawExtraPathEffect.h"
#include "SkDrawFilter.h"
#include "SkDraw.h"
#include "SkDrawLooper.h"
#include "SkDropShadowImageFilter.h"
#include "SkDynamicAnnotations.h"
#include "SkEmbossMaskFilter.h"
#include "SkEmptyShader.h"
#include "SkEndian.h"
#include "SkError.h"
#include "SkFixed.h"
#include "SkFlate.h"
#include "SkFlattenableBuffers.h"
#include "SkFlattenable.h"
#include "SkFlattenableSerialization.h"
#include "SkFloatBits.h"
#include "SkFloatingPoint.h"
#include "SkFont.h"
#include "SkFontHost.h"
#include "SkFontLCDConfig.h"
#include "SkGeometry.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkImageEncoder.h"
#include "SkImageFilter.h"
#include "SkImageGenerator.h"
#include "SkImage.h"
#include "SkImageInfo.h"
#include "SkInstCnt.h"
#include "SkLayerDrawLooper.h"
#include "SkLayerRasterizer.h"
#include "SkLerpXfermode.h"
#include "SkLightingImageFilter.h"
#include "SkLineClipper.h"
#include "SkLumaColorFilter.h"
#include "SkMagnifierImageFilter.h"
#include "SkMallocPixelRef.h"
#include "SkMaskFilter.h"
#include "SkMask.h"
#include "SkMath.h"
#include "SkMatrixConvolutionImageFilter.h"
#include "SkMatrix.h"
#include "SkMatrixImageFilter.h"
#include "SkMergeImageFilter.h"
#include "SkMetaData.h"
#include "SkMorphologyImageFilter.h"
#include "SkOffsetImageFilter.h"
#include "SkOnce.h"
#include "SkOSFile.h"
#include "SkPackBits.h"
#include "SkPaintFlagsDrawFilter.h"
#include "SkPaint.h"
#include "SkPaintOptionsAndroid.h"
#include "SkPathEffect.h"
#include "SkPath.h"
#include "SkPathMeasure.h"
#include "SkPathOps.h"
#include "SkPathRef.h"
#include "SkPerlinNoiseShader.h"
#include "SkPicture.h"
#include "SkPictureImageFilter.h"
#include "SkPictureRecorder.h"
#include "SkPixelRef.h"
#include "SkPixelXorXfermode.h"
#include "SkPoint.h"
#include "SkPorterDuff.h"
#include "SkPostConfig.h"
#include "SkPreConfig.h"
#include "SkRasterizer.h"
#include "SkReadBuffer.h"
#include "SkReader32.h"
#include "SkRect.h"
#include "SkRectShaderImageFilter.h"
#include "SkRefCnt.h"
#include "SkRegion.h"
#include "SkRRect.h"
#include "SkScalar.h"
#include "SkShader.h"
#include "SkSize.h"
#include "SkStream.h"
#include "SkString.h"
#include "SkStringUtils.h"
#include "SkStrokeRec.h"
#include "SkSurface.h"
#include "SkTableColorFilter.h"
#include "SkTableMaskFilter.h"
#include "SkTArray.h"
#include "SkTDArray.h"
#include "SkTDict.h"
#include "SkTDStack.h"
#include "SkTemplates.h"
#include "SkTestImageFilters.h"
#include "SkThread.h"
#include "SkTileImageFilter.h"
#include "SkTime.h"
#include "SkTInternalLList.h"
#include "SkTLazy.h"
#include "SkTransparentShader.h"
#include "SkTRegistry.h"
#include "SkTSearch.h"
#include "SkTypeface.h"
#include "SkTypes.h"
#include "SkUnPreMultiply.h"
#include "SkUtils.h"
#include "SkVertState.h"
#include "SkWeakRefCnt.h"
#include "SkWriteBuffer.h"
#include "SkWriter32.h"
#include "SkXfermode.h"
#include "SkXfermodeImageFilter.h"

SkBitmap source;

{{.Code}}
<|endoftext|>


<commit_before>/*
Copyright (c) 2003-2010 Sony Pictures Imageworks Inc., et al.
All Rights Reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.
* Neither the name of Sony Pictures Imageworks nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER 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 <OpenColorIO/OpenColorIO.h>

#include "PyColorSpace.h"
#include "PyConstants.h"
#include "PyUtil.h"

OCIO_NAMESPACE_ENTER
{

    namespace
    {
        PyObject * PyOCIO_Constants_GetInverseTransformDirection( PyObject * self,  PyObject *args );
        PyObject * PyOCIO_Constants_CombineTransformDirections( PyObject * self,  PyObject *args );
        PyObject * PyOCIO_Constants_BitDepthIsFloat( PyObject * self,  PyObject *args );
        PyObject * PyOCIO_Constants_BitDepthToInt( PyObject * self,  PyObject *args );

        ///////////////////////////////////////////////////////////////////////
        ///

        PyMethodDef LocalModuleMethods[] = {
            {"GetInverseTransformDirection", PyOCIO_Constants_GetInverseTransformDirection, METH_VARARGS, "" },
            {"CombineTransformDirections", PyOCIO_Constants_CombineTransformDirections, METH_VARARGS, "" },
            {"BitDepthIsFloat", PyOCIO_Constants_BitDepthIsFloat, METH_VARARGS, "" },
            {"BitDepthToInt", PyOCIO_Constants_BitDepthToInt, METH_VARARGS, "" },
            {NULL, NULL, 0, NULL}        /* Sentinel */
        };

    }

    void AddConstantsModule(PyObject *enclosingModule)
    {
        // Add sub-module
        std::string moduleName = PyModule_GetName(enclosingModule);
        moduleName += ".Constants";

        PyObject * m = Py_InitModule3(const_cast<char*>(moduleName.c_str()),
            LocalModuleMethods, "");
        Py_INCREF(m);

        // Add Module Constants
        PyModule_AddStringConstant(m, "TRANSFORM_DIR_UNKNOWN",
            TransformDirectionToString(TRANSFORM_DIR_UNKNOWN));
        PyModule_AddStringConstant(m, "TRANSFORM_DIR_FORWARD",
            TransformDirectionToString(TRANSFORM_DIR_FORWARD));
        PyModule_AddStringConstant(m, "TRANSFORM_DIR_INVERSE",
            TransformDirectionToString(TRANSFORM_DIR_INVERSE));

        PyModule_AddStringConstant(m, "COLORSPACE_DIR_UNKNOWN",
            ColorSpaceDirectionToString(COLORSPACE_DIR_UNKNOWN));
        PyModule_AddStringConstant(m, "COLORSPACE_DIR_TO_REFERENCE",
            ColorSpaceDirectionToString(COLORSPACE_DIR_TO_REFERENCE));
        PyModule_AddStringConstant(m, "COLORSPACE_DIR_FROM_REFERENCE",
            ColorSpaceDirectionToString(COLORSPACE_DIR_FROM_REFERENCE));

        PyModule_AddStringConstant(m, "BIT_DEPTH_UNKNOWN",
            BitDepthToString(BIT_DEPTH_UNKNOWN));
        PyModule_AddStringConstant(m, "BIT_DEPTH_UINT8",
            BitDepthToString(BIT_DEPTH_UINT8));
        PyModule_AddStringConstant(m, "BIT_DEPTH_UINT10",
            BitDepthToString(BIT_DEPTH_UINT10));
        PyModule_AddStringConstant(m, "BIT_DEPTH_UINT12",
            BitDepthToString(BIT_DEPTH_UINT12));
        PyModule_AddStringConstant(m, "BIT_DEPTH_UINT14",
            BitDepthToString(BIT_DEPTH_UINT14));
        PyModule_AddStringConstant(m, "BIT_DEPTH_UINT16",
            BitDepthToString(BIT_DEPTH_UINT16));
        PyModule_AddStringConstant(m, "BIT_DEPTH_UINT32",
            BitDepthToString(BIT_DEPTH_UINT32));
        PyModule_AddStringConstant(m, "BIT_DEPTH_F16",
            BitDepthToString(BIT_DEPTH_F16));
        PyModule_AddStringConstant(m, "BIT_DEPTH_F32",
            BitDepthToString(BIT_DEPTH_F32));

        PyModule_AddStringConstant(m, "GPU_ALLOCATION_UNKNOWN",
            GpuAllocationToString(GPU_ALLOCATION_UNKNOWN));
        PyModule_AddStringConstant(m, "GPU_ALLOCATION_UNIFORM",
            GpuAllocationToString(GPU_ALLOCATION_UNIFORM));
        PyModule_AddStringConstant(m, "GPU_ALLOCATION_LG2",
            GpuAllocationToString(GPU_ALLOCATION_LG2));

        PyModule_AddStringConstant(m, "INTERP_UNKNOWN",
            InterpolationToString(INTERP_UNKNOWN));
        PyModule_AddStringConstant(m, "INTERP_NEAREST",
            InterpolationToString(INTERP_NEAREST));
        PyModule_AddStringConstant(m, "INTERP_LINEAR",
            InterpolationToString(INTERP_LINEAR));

        PyModule_AddStringConstant(m, "ROLE_REFERENCE", ROLE_REFERENCE);
        PyModule_AddStringConstant(m, "ROLE_DATA", ROLE_DATA);
        PyModule_AddStringConstant(m, "ROLE_COLOR_PICKING", ROLE_COLOR_PICKING);
        PyModule_AddStringConstant(m, "ROLE_SCENE_LINEAR", ROLE_SCENE_LINEAR);
        PyModule_AddStringConstant(m, "ROLE_COMPOSITING_LOG", ROLE_COMPOSITING_LOG);
        PyModule_AddStringConstant(m, "ROLE_COLOR_TIMING", ROLE_COLOR_TIMING);

        // Add the module
        PyModule_AddObject(enclosingModule, "Constants", m);
    }

    namespace
    {
        PyObject * PyOCIO_Constants_GetInverseTransformDirection( PyObject * /*module*/, PyObject * args )
        {
            try
            {
                char * s = 0;
                if (!PyArg_ParseTuple(args,"s:GetInverseTransformDirection", &s)) return NULL;

                TransformDirection dir = TransformDirectionFromString(s);
                dir = GetInverseTransformDirection(dir);
                return PyString_FromString( TransformDirectionToString(dir) );
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

        PyObject * PyOCIO_Constants_CombineTransformDirections( PyObject * /*module*/, PyObject * args )
        {
            try
            {
                char * s1 = 0;
                char * s2 = 0;
                if (!PyArg_ParseTuple(args,"ss:CombineTransformDirections", &s1, &s2)) return NULL;

                TransformDirection dir1 = TransformDirectionFromString(s1);
                TransformDirection dir2 = TransformDirectionFromString(s2);

                TransformDirection dir = CombineTransformDirections(dir1, dir2);
                return PyString_FromString( TransformDirectionToString(dir) );
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

        PyObject * PyOCIO_Constants_BitDepthIsFloat( PyObject * /*module*/, PyObject * args )
        {
            try
            {
                char * s = 0;
                if (!PyArg_ParseTuple(args,"s:BitDepthIsFloat", &s)) return NULL;

                BitDepth bitdepth = BitDepthFromString(s);
                return PyBool_FromLong( BitDepthIsFloat(bitdepth) );
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

        PyObject * PyOCIO_Constants_BitDepthToInt( PyObject * /*module*/, PyObject * args )
        {
            try
            {
                char * s = 0;
                if (!PyArg_ParseTuple(args,"s:BitDepthToInt", &s)) return NULL;

                BitDepth bitdepth = BitDepthFromString(s);
                return PyInt_FromLong( BitDepthToInt(bitdepth) );
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }
    }

}
OCIO_NAMESPACE_EXIT
<commit_msg>- Added some const_cast<char*>(..) ie. 'error: invalid conversion from ‘const char*’ to ‘char*’'<commit_after>/*
Copyright (c) 2003-2010 Sony Pictures Imageworks Inc., et al.
All Rights Reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.
* Neither the name of Sony Pictures Imageworks nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER 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 <OpenColorIO/OpenColorIO.h>

#include "PyColorSpace.h"
#include "PyConstants.h"
#include "PyUtil.h"

OCIO_NAMESPACE_ENTER
{

    namespace
    {
        PyObject * PyOCIO_Constants_GetInverseTransformDirection( PyObject * self,  PyObject *args );
        PyObject * PyOCIO_Constants_CombineTransformDirections( PyObject * self,  PyObject *args );
        PyObject * PyOCIO_Constants_BitDepthIsFloat( PyObject * self,  PyObject *args );
        PyObject * PyOCIO_Constants_BitDepthToInt( PyObject * self,  PyObject *args );

        ///////////////////////////////////////////////////////////////////////
        ///

        PyMethodDef LocalModuleMethods[] = {
            {"GetInverseTransformDirection", PyOCIO_Constants_GetInverseTransformDirection, METH_VARARGS, "" },
            {"CombineTransformDirections", PyOCIO_Constants_CombineTransformDirections, METH_VARARGS, "" },
            {"BitDepthIsFloat", PyOCIO_Constants_BitDepthIsFloat, METH_VARARGS, "" },
            {"BitDepthToInt", PyOCIO_Constants_BitDepthToInt, METH_VARARGS, "" },
            {NULL, NULL, 0, NULL}        /* Sentinel */
        };

    }

    void AddConstantsModule(PyObject *enclosingModule)
    {
        // Add sub-module
        std::string moduleName = PyModule_GetName(enclosingModule);
        moduleName += ".Constants";

        PyObject * m = Py_InitModule3(const_cast<char*>(moduleName.c_str()),
            LocalModuleMethods, "");
        Py_INCREF(m);

        // Add Module Constants
        PyModule_AddStringConstant(m, "TRANSFORM_DIR_UNKNOWN",
            const_cast<char*>(TransformDirectionToString(TRANSFORM_DIR_UNKNOWN)));
        PyModule_AddStringConstant(m, "TRANSFORM_DIR_FORWARD",
            const_cast<char*>(TransformDirectionToString(TRANSFORM_DIR_FORWARD)));
        PyModule_AddStringConstant(m, "TRANSFORM_DIR_INVERSE",
            const_cast<char*>(TransformDirectionToString(TRANSFORM_DIR_INVERSE)));

        PyModule_AddStringConstant(m, "COLORSPACE_DIR_UNKNOWN",
            const_cast<char*>(ColorSpaceDirectionToString(COLORSPACE_DIR_UNKNOWN)));
        PyModule_AddStringConstant(m, "COLORSPACE_DIR_TO_REFERENCE",
            const_cast<char*>(ColorSpaceDirectionToString(COLORSPACE_DIR_TO_REFERENCE)));
        PyModule_AddStringConstant(m, "COLORSPACE_DIR_FROM_REFERENCE",
            const_cast<char*>(ColorSpaceDirectionToString(COLORSPACE_DIR_FROM_REFERENCE)));

        PyModule_AddStringConstant(m, "BIT_DEPTH_UNKNOWN",
            const_cast<char*>(BitDepthToString(BIT_DEPTH_UNKNOWN)));
        PyModule_AddStringConstant(m, "BIT_DEPTH_UINT8",
            const_cast<char*>(BitDepthToString(BIT_DEPTH_UINT8)));
        PyModule_AddStringConstant(m, "BIT_DEPTH_UINT10",
            const_cast<char*>(BitDepthToString(BIT_DEPTH_UINT10)));
        PyModule_AddStringConstant(m, "BIT_DEPTH_UINT12",
            const_cast<char*>(BitDepthToString(BIT_DEPTH_UINT12)));
        PyModule_AddStringConstant(m, "BIT_DEPTH_UINT14",
            const_cast<char*>(BitDepthToString(BIT_DEPTH_UINT14)));
        PyModule_AddStringConstant(m, "BIT_DEPTH_UINT16",
            const_cast<char*>(BitDepthToString(BIT_DEPTH_UINT16)));
        PyModule_AddStringConstant(m, "BIT_DEPTH_UINT32",
            const_cast<char*>(BitDepthToString(BIT_DEPTH_UINT32)));
        PyModule_AddStringConstant(m, "BIT_DEPTH_F16",
            const_cast<char*>(BitDepthToString(BIT_DEPTH_F16)));
        PyModule_AddStringConstant(m, "BIT_DEPTH_F32",
            const_cast<char*>(BitDepthToString(BIT_DEPTH_F32)));

        PyModule_AddStringConstant(m, "GPU_ALLOCATION_UNKNOWN",
            const_cast<char*>(GpuAllocationToString(GPU_ALLOCATION_UNKNOWN)));
        PyModule_AddStringConstant(m, "GPU_ALLOCATION_UNIFORM",
            const_cast<char*>(GpuAllocationToString(GPU_ALLOCATION_UNIFORM)));
        PyModule_AddStringConstant(m, "GPU_ALLOCATION_LG2",
            const_cast<char*>(GpuAllocationToString(GPU_ALLOCATION_LG2)));

        PyModule_AddStringConstant(m, "INTERP_UNKNOWN",
            const_cast<char*>(InterpolationToString(INTERP_UNKNOWN)));
        PyModule_AddStringConstant(m, "INTERP_NEAREST",
            const_cast<char*>(InterpolationToString(INTERP_NEAREST)));
        PyModule_AddStringConstant(m, "INTERP_LINEAR",
            const_cast<char*>(InterpolationToString(INTERP_LINEAR)));

        PyModule_AddStringConstant(m, "ROLE_REFERENCE", const_cast<char*>(ROLE_REFERENCE));
        PyModule_AddStringConstant(m, "ROLE_DATA", const_cast<char*>(ROLE_DATA));
        PyModule_AddStringConstant(m, "ROLE_COLOR_PICKING", const_cast<char*>(ROLE_COLOR_PICKING));
        PyModule_AddStringConstant(m, "ROLE_SCENE_LINEAR", const_cast<char*>(ROLE_SCENE_LINEAR));
        PyModule_AddStringConstant(m, "ROLE_COMPOSITING_LOG", const_cast<char*>(ROLE_COMPOSITING_LOG));
        PyModule_AddStringConstant(m, "ROLE_COLOR_TIMING", const_cast<char*>(ROLE_COLOR_TIMING));

        // Add the module
        PyModule_AddObject(enclosingModule, "Constants", m);
    }

    namespace
    {
        PyObject * PyOCIO_Constants_GetInverseTransformDirection( PyObject * /*module*/, PyObject * args )
        {
            try
            {
                char * s = 0;
                if (!PyArg_ParseTuple(args,"s:GetInverseTransformDirection", &s)) return NULL;

                TransformDirection dir = TransformDirectionFromString(s);
                dir = GetInverseTransformDirection(dir);
                return PyString_FromString( TransformDirectionToString(dir) );
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

        PyObject * PyOCIO_Constants_CombineTransformDirections( PyObject * /*module*/, PyObject * args )
        {
            try
            {
                char * s1 = 0;
                char * s2 = 0;
                if (!PyArg_ParseTuple(args,"ss:CombineTransformDirections", &s1, &s2)) return NULL;

                TransformDirection dir1 = TransformDirectionFromString(s1);
                TransformDirection dir2 = TransformDirectionFromString(s2);

                TransformDirection dir = CombineTransformDirections(dir1, dir2);
                return PyString_FromString( TransformDirectionToString(dir) );
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

        PyObject * PyOCIO_Constants_BitDepthIsFloat( PyObject * /*module*/, PyObject * args )
        {
            try
            {
                char * s = 0;
                if (!PyArg_ParseTuple(args,"s:BitDepthIsFloat", &s)) return NULL;

                BitDepth bitdepth = BitDepthFromString(s);
                return PyBool_FromLong( BitDepthIsFloat(bitdepth) );
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

        PyObject * PyOCIO_Constants_BitDepthToInt( PyObject * /*module*/, PyObject * args )
        {
            try
            {
                char * s = 0;
                if (!PyArg_ParseTuple(args,"s:BitDepthToInt", &s)) return NULL;

                BitDepth bitdepth = BitDepthFromString(s);
                return PyInt_FromLong( BitDepthToInt(bitdepth) );
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }
    }

}
OCIO_NAMESPACE_EXIT
<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <gtest/gtest.h>
#include <gtest/gtest-spi.h>

#include "update_engine/terminator.h"

using std::string;
using testing::ExitedWithCode;

namespace chromeos_update_engine {

class TerminatorTest : public ::testing::Test {
 protected:
  virtual void SetUp() {
    Terminator::Init();
    ASSERT_FALSE(Terminator::exit_blocked());
    ASSERT_FALSE(Terminator::exit_requested());
  }
};

typedef TerminatorTest TerminatorDeathTest;

namespace {
void UnblockExitThroughUnblocker() {
  ScopedTerminatorExitUnblocker unblocker = ScopedTerminatorExitUnblocker();
}

void RaiseSIGTERM() {
  ASSERT_EXIT(raise(SIGTERM), ExitedWithCode(0), "");
}
}  // namespace {}

TEST_F(TerminatorTest, HandleSignalTest) {
  Terminator::set_exit_blocked(true);
  Terminator::HandleSignal(SIGTERM);
  ASSERT_TRUE(Terminator::exit_requested());
}

TEST_F(TerminatorTest, ScopedTerminatorExitUnblockerTest) {
  Terminator::set_exit_blocked(true);
  ASSERT_TRUE(Terminator::exit_blocked());
  ASSERT_FALSE(Terminator::exit_requested());
  UnblockExitThroughUnblocker();
  ASSERT_FALSE(Terminator::exit_blocked());
  ASSERT_FALSE(Terminator::exit_requested());
}

TEST_F(TerminatorDeathTest, ExitTest) {
  ASSERT_EXIT(Terminator::Exit(), ExitedWithCode(0), "");
  Terminator::set_exit_blocked(true);
  ASSERT_EXIT(Terminator::Exit(), ExitedWithCode(0), "");
}

TEST_F(TerminatorDeathTest, RaiseSignalTest) {
  RaiseSIGTERM();
  Terminator::set_exit_blocked(true);
  EXPECT_FATAL_FAILURE(RaiseSIGTERM(), "");
}

TEST_F(TerminatorDeathTest, ScopedTerminatorExitUnblockerExitTest) {
  Terminator::set_exit_blocked(true);
  Terminator::exit_requested_ = 1;
  ASSERT_EXIT(UnblockExitThroughUnblocker(), ExitedWithCode(0), "");
}

}  // namespace chromeos_update_engine
<commit_msg>AU: Make sure that subsequent non-Terminator unit tests don't exit.<commit_after>// Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <gtest/gtest.h>
#include <gtest/gtest-spi.h>

#include "update_engine/terminator.h"

using std::string;
using testing::ExitedWithCode;

namespace chromeos_update_engine {

class TerminatorTest : public ::testing::Test {
 protected:
  virtual void SetUp() {
    Terminator::Init();
    ASSERT_FALSE(Terminator::exit_blocked());
    ASSERT_FALSE(Terminator::exit_requested());
  }
  virtual void TearDown() {
    // Makes sure subsequent non-Terminator tests don't get accidentally
    // terminated.
    Terminator::Init();
  }
};

typedef TerminatorTest TerminatorDeathTest;

namespace {
void UnblockExitThroughUnblocker() {
  ScopedTerminatorExitUnblocker unblocker = ScopedTerminatorExitUnblocker();
}

void RaiseSIGTERM() {
  ASSERT_EXIT(raise(SIGTERM), ExitedWithCode(0), "");
}
}  // namespace {}

TEST_F(TerminatorTest, HandleSignalTest) {
  Terminator::set_exit_blocked(true);
  Terminator::HandleSignal(SIGTERM);
  ASSERT_TRUE(Terminator::exit_requested());
}

TEST_F(TerminatorTest, ScopedTerminatorExitUnblockerTest) {
  Terminator::set_exit_blocked(true);
  ASSERT_TRUE(Terminator::exit_blocked());
  ASSERT_FALSE(Terminator::exit_requested());
  UnblockExitThroughUnblocker();
  ASSERT_FALSE(Terminator::exit_blocked());
  ASSERT_FALSE(Terminator::exit_requested());
}

TEST_F(TerminatorDeathTest, ExitTest) {
  ASSERT_EXIT(Terminator::Exit(), ExitedWithCode(0), "");
  Terminator::set_exit_blocked(true);
  ASSERT_EXIT(Terminator::Exit(), ExitedWithCode(0), "");
}

TEST_F(TerminatorDeathTest, RaiseSignalTest) {
  RaiseSIGTERM();
  Terminator::set_exit_blocked(true);
  EXPECT_FATAL_FAILURE(RaiseSIGTERM(), "");
}

TEST_F(TerminatorDeathTest, ScopedTerminatorExitUnblockerExitTest) {
  Terminator::set_exit_blocked(true);
  Terminator::exit_requested_ = 1;
  ASSERT_EXIT(UnblockExitThroughUnblocker(), ExitedWithCode(0), "");
}

}  // namespace chromeos_update_engine
<|endoftext|>


<commit_before>#include "gtest/gtest.h"
#include "Numerics.h"
#include "THMTestUtils.h"

TEST(NumericsTest, test_absoluteFuzzyEqualVectors_True)
{
  const RealVectorValue a(1.0, 2.0, 3.0);
  const RealVectorValue b(1.0 + 1.0e-15, 2.0, 3.0);
  EXPECT_TRUE(THM::absoluteFuzzyEqualVectors(a, b));
}

TEST(NumericsTest, test_absoluteFuzzyEqualVectors_False)
{
  const RealVectorValue a(1.0, 2.0, 3.0);
  const RealVectorValue b(1.1, 2.0, 3.0);
  EXPECT_FALSE(THM::absoluteFuzzyEqualVectors(a, b));
}

TEST(NumericsTest, test_areParallelVectors_True)
{
  const RealVectorValue a(1.0, 2.0, 3.0);
  const RealVectorValue b(-2.0, -4.0, -6.0);
  EXPECT_TRUE(THM::areParallelVectors(a, b));
}

TEST(NumericsTest, test_areParallelVectors_False)
{
  const RealVectorValue a(1.0, 2.0, 3.0);
  const RealVectorValue b(2.0, 3.0, 1.0);
  EXPECT_FALSE(THM::areParallelVectors(a, b));
}

TEST(NumericsTest, test_haveSameDirection_True)
{
  const RealVectorValue a(1.0, 2.0, 3.0);
  const RealVectorValue b(2.0, 4.0, 6.0);
  EXPECT_TRUE(THM::haveSameDirection(a, b));
}

TEST(NumericsTest, test_haveSameDirection_False)
{
  const RealVectorValue a(1.0, 2.0, 3.0);
  const RealVectorValue b(-1.0, 2.0, 3.0);
  EXPECT_FALSE(THM::haveSameDirection(a, b));
}

TEST(NumericsTest, Reynolds)
{
  ABS_TEST(THM::Reynolds(0.1, 999, 0.5, 2e-2, 0.9), 1.11, 1e-13);
  ABS_TEST(THM::Reynolds(0.1, 999, -0.5, 2e-2, 0.9), 1.11, 1e-13);
}

TEST(NumericsTest, Prandtl) { ABS_TEST(THM::Prandtl(10, 0.1, 2), 0.5, 1e-13); }

TEST(NumericsTest, Grashof)
{
  ABS_TEST(THM::Grashof(0.1, 1, 2e-2, 999, 0.05, 9.81), 3.1329247392e3, 1e-13);
}

TEST(NumericsTest, Laplace) { ABS_TEST(THM::Laplace(0.001, 1, 9.81), 0.010096375546923, 1e-13); }

TEST(NumericsTest, viscosityNumber)
{
  ABS_TEST(THM::viscosityNumber(0.05, 0.02, 999, 2, 9.81), 0.062602188259, 1e-13);
}

TEST(NumericsTest, wallHeatTransferCoefficient)
{
  ABS_TEST(THM::wallHeatTransferCoefficient(2, 6, 3), 4, 1e-13);
}
<commit_msg>Adding missing unit tests for Numerics module<commit_after>#include "gtest/gtest.h"
#include "Numerics.h"
#include "THMTestUtils.h"

TEST(NumericsTest, test_absoluteFuzzyEqualVectors_True)
{
  const RealVectorValue a(1.0, 2.0, 3.0);
  const RealVectorValue b(1.0 + 1.0e-15, 2.0, 3.0);
  EXPECT_TRUE(THM::absoluteFuzzyEqualVectors(a, b));
}

TEST(NumericsTest, test_absoluteFuzzyEqualVectors_False)
{
  const RealVectorValue a(1.0, 2.0, 3.0);
  const RealVectorValue b(1.1, 2.0, 3.0);
  EXPECT_FALSE(THM::absoluteFuzzyEqualVectors(a, b));
}

TEST(NumericsTest, test_areParallelVectors_True)
{
  const RealVectorValue a(1.0, 2.0, 3.0);
  const RealVectorValue b(-2.0, -4.0, -6.0);
  EXPECT_TRUE(THM::areParallelVectors(a, b));
}

TEST(NumericsTest, test_areParallelVectors_False)
{
  const RealVectorValue a(1.0, 2.0, 3.0);
  const RealVectorValue b(2.0, 3.0, 1.0);
  EXPECT_FALSE(THM::areParallelVectors(a, b));
}

TEST(NumericsTest, test_haveSameDirection_True)
{
  const RealVectorValue a(1.0, 2.0, 3.0);
  const RealVectorValue b(2.0, 4.0, 6.0);
  EXPECT_TRUE(THM::haveSameDirection(a, b));
}

TEST(NumericsTest, test_haveSameDirection_False)
{
  const RealVectorValue a(1.0, 2.0, 3.0);
  const RealVectorValue b(-1.0, 2.0, 3.0);
  EXPECT_FALSE(THM::haveSameDirection(a, b));
}

TEST(NumericsTest, Reynolds)
{
  ABS_TEST(THM::Reynolds(0.1, 999, 0.5, 2e-2, 0.9), 1.11, 1e-13);
  ABS_TEST(THM::Reynolds(0.1, 999, -0.5, 2e-2, 0.9), 1.11, 1e-13);
}

TEST(NumericsTest, Prandtl) { ABS_TEST(THM::Prandtl(10, 0.1, 2), 0.5, 1e-13); }

TEST(NumericsTest, Grashof)
{
  ABS_TEST(THM::Grashof(0.1, 1, 2e-2, 999, 0.05, 9.81), 3.1329247392e3, 1e-13);
}

TEST(NumericsTest, Laplace) { ABS_TEST(THM::Laplace(0.001, 1, 9.81), 0.010096375546923, 1e-13); }

TEST(NumericsTest, viscosityNumber)
{
  ABS_TEST(THM::viscosityNumber(0.05, 0.02, 999, 2, 9.81), 0.062602188259, 1e-13);
}

TEST(NumericsTest, wallHeatTransferCoefficient)
{
  ABS_TEST(THM::wallHeatTransferCoefficient(2, 6, 3), 4, 1e-13);
}

TEST(NumericsTest, Dean) { ABS_TEST(THM::Dean(1, 4), 2, 1e-15); }

TEST(NumericsTest, vel)
{
  const Real arhoA = 1;
  const Real arhouA = 2;

  Real vel, dvel_darhoA, dvel_darhouA;
  THM::vel_from_arhoA_arhouA(arhoA, arhouA, vel, dvel_darhoA, dvel_darhouA);
  ABS_TEST(vel, 2., 1e-15);
  ABS_TEST(dvel_darhoA, -2, 1e-15);
  ABS_TEST(dvel_darhouA, 1., 1e-15);

  ABS_TEST(THM::dvel_darhoA(arhoA, arhouA), -2., 1e-15);
  ABS_TEST(THM::dvel_darhouA(arhoA), 1., 1e-15);
}

TEST(NumericsTest, rho)
{
  const Real arhoA = 2;
  const Real alpha = 0.1;
  const Real A = 1;

  Real rho, drho_darhoA, drho_dalpha;
  THM::rho_from_arhoA_alpha_A(arhoA, alpha, A, rho, drho_darhoA, drho_dalpha);
  ABS_TEST(rho, 20., 1e-15);
  ABS_TEST(drho_darhoA, 10., 1e-15);
  ABS_TEST(drho_dalpha, -200., 1e-13);
}

TEST(NumericsTest, specific_volume)
{
  const Real arhoA = 2;
  const Real A = 1;

  Real v, dv_drhoA;
  THM::v_from_rhoA_A(arhoA, A, v, dv_drhoA);
  ABS_TEST(v, 0.5, 1e-15);
  ABS_TEST(dv_drhoA, -0.25, 1e-15);

  const Real alpha = 0.1;
  Real dv_darhoA, dv_dalpha;
  THM::v_from_arhoA_alpha_A(arhoA, alpha, A, v, dv_darhoA, dv_dalpha);
  ABS_TEST(v, 0.05, 1e-15);
  ABS_TEST(dv_darhoA, -0.025, 1e-15);
  ABS_TEST(dv_dalpha, 0.5, 1e-13);

  const Real rho = 20;
  Real dv_drho;
  THM::v_from_rho(rho, v, dv_drho);
  ABS_TEST(v, 0.05, 1e-15);
  ABS_TEST(dv_darhoA, -0.025, 1e-15);

  ABS_TEST(THM::dv_dalpha_liquid(A, arhoA, true), 0.5, 1e-15);
  ABS_TEST(THM::dv_dalpha_liquid(A, arhoA, false), -0.5, 1e-15);

  ABS_TEST(THM::dv_darhoA(A, arhoA), -0.25, 1e-15);
}

TEST(NumericsTest, internal_energy)
{
  const Real arhoA = 2;
  const Real arhouA = 4;
  const Real arhoEA = 8;

  Real e, de_darhoA, de_darhouA, de_darhoEA;
  THM::e_from_arhoA_arhouA_arhoEA(arhoA, arhouA, arhoEA, e, de_darhoA, de_darhouA, de_darhoEA);
  ABS_TEST(e, 2., 1e-15);
  ABS_TEST(de_darhoA, 0., 1e-15);
  ABS_TEST(de_darhouA, -1., 1e-15);
  ABS_TEST(de_darhoEA, 0.5, 1e-15);

  const Real E = 10;
  const Real vel = 2;
  Real de_dE, de_dvel;
  THM::e_from_E_vel(E, vel, e, de_dE, de_dvel);
  ABS_TEST(e, 8., 1e-15);
  ABS_TEST(de_dE, 1., 1e-15);
  ABS_TEST(de_dvel, -2., 1e-15);

  ABS_TEST(THM::de_darhoA(arhoA, arhouA, arhoEA), 0., 1e-15);
  ABS_TEST(THM::de_darhouA(arhoA, arhouA), -1., 1e-15);
  ABS_TEST(THM::de_darhoEA(arhoA), 0.5, 1e-15);
}

TEST(NumericsTest, total_energy)
{
  const Real arhoA = 2.;
  const Real arhoEA = 8.;

  Real E, dE_darhoA, dE_darhoEA;
  THM::E_from_arhoA_arhoEA(arhoA, arhoEA, E, dE_darhoA, dE_darhoEA);
  ABS_TEST(E, 4., 1e-15);
  ABS_TEST(dE_darhoA, -2., 1e-15);
  ABS_TEST(dE_darhoEA, 0.5, 1e-15);

  const Real e = 4.;
  const Real vel = 2.;

  Real dE_de, dE_dvel;
  THM::E_from_e_vel(e, vel, E, dE_de, dE_dvel);

  ABS_TEST(E, 6., 1e-15);
  ABS_TEST(dE_de, 1., 1e-15);
  ABS_TEST(dE_dvel, 2., 1e-15);
}

TEST(NumericsTest, specific_enthalpy)
{
  const Real e = 6;
  const Real p = 4;
  const Real rho = 2;

  Real h, dh_de, dh_dp, dh_drho;
  THM::h_from_e_p_rho(e, p, rho, h, dh_de, dh_dp, dh_drho);
  ABS_TEST(h, 8., 1e-15);
  ABS_TEST(dh_de, 1., 1e-15);
  ABS_TEST(dh_dp, 0.5, 1e-15);
  ABS_TEST(dh_drho, -1., 1e-15);
}

TEST(NumericsTest, xlets)
{
  EXPECT_FALSE(THM::isInlet(2, 1));
  EXPECT_TRUE(THM::isInlet(2, -1));
  EXPECT_TRUE(THM::isInlet(-2, 1));
  EXPECT_FALSE(THM::isInlet(-2, -1));

  EXPECT_TRUE(THM::isOutlet(2, 1));
  EXPECT_FALSE(THM::isOutlet(2, -1));
  EXPECT_FALSE(THM::isOutlet(-2, 1));
  EXPECT_TRUE(THM::isOutlet(-2, -1));
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief test suite for StringBuffer class
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2007-2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include <boost/test/unit_test.hpp>

#include "Basics/StringBuffer.h"

using namespace triagens;
using namespace triagens::basics;
using namespace std;

// -----------------------------------------------------------------------------
// --SECTION--                                                 setup / tear-down
// -----------------------------------------------------------------------------

struct StringBufferSetup {
  StringBufferSetup () {
    BOOST_TEST_MESSAGE("setup StringBuffer");
  }

  ~StringBufferSetup () {
    BOOST_TEST_MESSAGE("tear-down StringBuffer");
  }
};

// -----------------------------------------------------------------------------
// --SECTION--                                                        test suite
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief setup
////////////////////////////////////////////////////////////////////////////////

BOOST_FIXTURE_TEST_SUITE (StringBufferTest, StringBufferSetup)

////////////////////////////////////////////////////////////////////////////////
/// @brief test_StringBuffer1
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_CASE (test_StringBuffer1) {
  StringBuffer buffer(TRI_CORE_MEM_ZONE);

  BOOST_CHECK_EQUAL(buffer.length(), (size_t) 0);
  BOOST_CHECK_EQUAL(std::string(buffer.c_str()), "");

  buffer = "";

  BOOST_CHECK_EQUAL(buffer.length(), (size_t) 0);
  BOOST_CHECK_EQUAL(std::string(buffer.c_str()), "");

  buffer = "Hallo World!";

  BOOST_CHECK_EQUAL(buffer.length(), (size_t) 12);
  BOOST_CHECK_EQUAL(std::string(buffer.c_str()), "Hallo World!");
}

////////////////////////////////////////////////////////////////////////////////
/// @brief test_StringBuffer2
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_CASE (test_StringBuffer2) {
  StringBuffer buffer(TRI_CORE_MEM_ZONE);

  BOOST_CHECK(buffer.length() == (size_t) 0);
  BOOST_CHECK(std::string(buffer.c_str()) == "");

  buffer.appendText("Hallo World");
  BOOST_CHECK(buffer.length() == (size_t) 11);
  BOOST_CHECK(std::string(buffer.c_str()) == "Hallo World");

  buffer.appendInteger4(1234);
  BOOST_CHECK(buffer.length() == (size_t) 15);
  BOOST_CHECK(std::string(buffer.c_str()) == "Hallo World1234");
}

////////////////////////////////////////////////////////////////////////////////
/// @brief test_StringBuffer3
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_CASE (test_StringBuffer3) {
  struct test_t {
      StringBuffer buffer;
  };

  BOOST_CHECK_EQUAL(offsetof(test_t, buffer), (size_t) 0);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief generate tests
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_SUITE_END()

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:
<commit_msg>offsetof only supports POD types, no C++ classes<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief test suite for StringBuffer class
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2007-2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include <boost/test/unit_test.hpp>

#include "Basics/StringBuffer.h"

using namespace triagens;
using namespace triagens::basics;
using namespace std;

// -----------------------------------------------------------------------------
// --SECTION--                                                 setup / tear-down
// -----------------------------------------------------------------------------

struct StringBufferSetup {
  StringBufferSetup () {
    BOOST_TEST_MESSAGE("setup StringBuffer");
  }

  ~StringBufferSetup () {
    BOOST_TEST_MESSAGE("tear-down StringBuffer");
  }
};

// -----------------------------------------------------------------------------
// --SECTION--                                                        test suite
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief setup
////////////////////////////////////////////////////////////////////////////////

BOOST_FIXTURE_TEST_SUITE (StringBufferTest, StringBufferSetup)

////////////////////////////////////////////////////////////////////////////////
/// @brief test_StringBuffer1
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_CASE (test_StringBuffer1) {
  StringBuffer buffer(TRI_CORE_MEM_ZONE);

  BOOST_CHECK_EQUAL(buffer.length(), (size_t) 0);
  BOOST_CHECK_EQUAL(std::string(buffer.c_str()), "");

  buffer = "";

  BOOST_CHECK_EQUAL(buffer.length(), (size_t) 0);
  BOOST_CHECK_EQUAL(std::string(buffer.c_str()), "");

  buffer = "Hallo World!";

  BOOST_CHECK_EQUAL(buffer.length(), (size_t) 12);
  BOOST_CHECK_EQUAL(std::string(buffer.c_str()), "Hallo World!");
}

////////////////////////////////////////////////////////////////////////////////
/// @brief test_StringBuffer2
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_CASE (test_StringBuffer2) {
  StringBuffer buffer(TRI_CORE_MEM_ZONE);

  BOOST_CHECK(buffer.length() == (size_t) 0);
  BOOST_CHECK(std::string(buffer.c_str()) == "");

  buffer.appendText("Hallo World");
  BOOST_CHECK(buffer.length() == (size_t) 11);
  BOOST_CHECK(std::string(buffer.c_str()) == "Hallo World");

  buffer.appendInteger4(1234);
  BOOST_CHECK(buffer.length() == (size_t) 15);
  BOOST_CHECK(std::string(buffer.c_str()) == "Hallo World1234");
}

////////////////////////////////////////////////////////////////////////////////
/// @brief generate tests
////////////////////////////////////////////////////////////////////////////////

BOOST_AUTO_TEST_SUITE_END()

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:
<|endoftext|>


<commit_before>#include "transactiondesc.h"

#include "guiutil.h"
#include "bitcoinunits.h"

#include "main.h"
#include "wallet.h"
#include "txdb.h"
#include "ui_interface.h"
#include "base58.h"

QString TransactionDesc::FormatTxStatus(const CWalletTx& wtx)
{
    if (!wtx.IsFinal())
    {
        if (wtx.nLockTime < LOCKTIME_THRESHOLD)
            return tr("Open for %n block(s)", "", nBestHeight - wtx.nLockTime);
        else
            return tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx.nLockTime));
    }
    else
    {
        int nDepth = wtx.GetDepthInMainChain();
        if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
            return tr("%1/offline").arg(nDepth);
        else if (nDepth < 6)
            return tr("%1/unconfirmed").arg(nDepth);
        else
            return tr("%1 confirmations").arg(nDepth);
    }
}

QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx)
{
    QString strHTML;

    {
        LOCK(wallet->cs_wallet);
        strHTML.reserve(4000);
        strHTML += "";

        int64 nTime = wtx.GetTxTime();
        int64 nCredit = wtx.GetCredit();
        int64 nDebit = wtx.GetDebit();
        int64 nNet = nCredit - nDebit;

        strHTML += "" + tr("Status") + ": " + FormatTxStatus(wtx);
        int nRequests = wtx.GetRequestCount();
        if (nRequests != -1)
        {
            if (nRequests == 0)
                strHTML += tr(", has not been successfully broadcast yet");
            else if (nRequests > 0)
                strHTML += tr(", broadcast through %n node(s)", "", nRequests);
        }
        strHTML += "
";

        strHTML += "" + tr("Date") + ": " + (nTime ? GUIUtil::dateTimeStr(nTime) : "") + "
";

        //
        // From
        //
        if (wtx.IsCoinBase())
        {
            strHTML += "" + tr("Source") + ": " + tr("Generated") + "
";
        }
        else if (wtx.mapValue.count("from") && !wtx.mapValue["from"].empty())
        {
            // Online transaction
            strHTML += "" + tr("From") + ": " + GUIUtil::HtmlEscape(wtx.mapValue["from"]) + "
";
        }
        else
        {
            // Offline transaction
            if (nNet > 0)
            {
                // Credit
                BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                {
                    if (wallet->IsMine(txout))
                    {
                        CTxDestination address;
                        if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address))
                        {
                            if (wallet->mapAddressBook.count(address))
                            {
                                strHTML += "" + tr("From") + ": " + tr("unknown") + "
";
                                strHTML += "" + tr("To") + ": ";
                                strHTML += GUIUtil::HtmlEscape(CBitcoinAddress(address).ToString());
                                if (!wallet->mapAddressBook[address].empty())
                                    strHTML += " (" + tr("own address") + ", " + tr("label") + ": " + GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + ")";
                                else
                                    strHTML += " (" + tr("own address") + ")";
                                strHTML += "
";
                            }
                        }
                        break;
                    }
                }
            }
        }

        //
        // To
        //
        if (wtx.mapValue.count("to") && !wtx.mapValue["to"].empty())
        {
            // Online transaction
            std::string strAddress = wtx.mapValue["to"];
            strHTML += "" + tr("To") + ": ";
            CTxDestination dest = CBitcoinAddress(strAddress).Get();
            if (wallet->mapAddressBook.count(dest) && !wallet->mapAddressBook[dest].empty())
                strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[dest]) + " ";
            strHTML += GUIUtil::HtmlEscape(strAddress) + "
";
        }

        //
        // Amount
        //
        if (wtx.IsCoinBase() && nCredit == 0)
        {
            //
            // Coinbase
            //
            int64 nUnmatured = 0;
            BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                nUnmatured += wallet->GetCredit(txout);
            strHTML += "" + tr("Credit") + ": ";
            if (wtx.IsInMainChain())
                strHTML += BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nUnmatured)+ " (" + tr("matures in %n more block(s)", "", wtx.GetBlocksToMaturity()) + ")";
            else
                strHTML += "(" + tr("not accepted") + ")";
            strHTML += "
";
        }
        else if (nNet > 0)
        {
            //
            // Credit
            //
            strHTML += "" + tr("Credit") + ": " + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nNet) + "
";
        }
        else
        {
            bool fAllFromMe = true;
            BOOST_FOREACH(const CTxIn& txin, wtx.vin)
                fAllFromMe = fAllFromMe && wallet->IsMine(txin);

            bool fAllToMe = true;
            BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                fAllToMe = fAllToMe && wallet->IsMine(txout);

            if (fAllFromMe)
            {
                //
                // Debit
                //
                BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                {
                    if (wallet->IsMine(txout))
                        continue;

                    if (!wtx.mapValue.count("to") || wtx.mapValue["to"].empty())
                    {
                        // Offline transaction
                        CTxDestination address;
                        if (ExtractDestination(txout.scriptPubKey, address))
                        {
                            strHTML += "" + tr("To") + ": ";
                            if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].empty())
                                strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + " ";
                            strHTML += GUIUtil::HtmlEscape(CBitcoinAddress(address).ToString());
                            strHTML += "
";
                        }
                    }

                    strHTML += "" + tr("Debit") + ": " + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, -txout.nValue) + "
";
                }

                if (fAllToMe)
                {
                    // Payment to self
                    int64 nChange = wtx.GetChange();
                    int64 nValue = nCredit - nChange;
                    strHTML += "" + tr("Debit") + ": " + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, -nValue) + "
";
                    strHTML += "" + tr("Credit") + ": " + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nValue) + "
";
                }

                int64 nTxFee = nDebit - wtx.GetValueOut();
                if (nTxFee > 0)
                    strHTML += "" + tr("Transaction fee") + ": " + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, -nTxFee) + "
";
            }
            else
            {
                //
                // Mixed debit transaction
                //
                BOOST_FOREACH(const CTxIn& txin, wtx.vin)
                    if (wallet->IsMine(txin))
                        strHTML += "" + tr("Debit") + ": " + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, -wallet->GetDebit(txin)) + "
";
                BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                    if (wallet->IsMine(txout))
                        strHTML += "" + tr("Credit") + ": " + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, wallet->GetCredit(txout)) + "
";
            }
        }

        strHTML += "" + tr("Net amount") + ": " + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nNet, true) + "
";

        //
        // Message
        //
        if (!wtx.mapValue["message"].empty())
             strHTML += "
" + tr("Message") + ":
" + GUIUtil::HtmlEscape(wtx.mapValue["message"], true) + "
";

		if (!wtx.mapValue["comment"].empty())
            strHTML += "
" + tr("Comment") + ":
" + GUIUtil::HtmlEscape(wtx.mapValue["comment"], true) + "
";

        strHTML += "" + tr("Transaction ID") + ": " + wtx.GetHash().ToString().c_str() + "
";

        if (wtx.IsCoinBase() || wtx.IsCoinStake())
            strHTML += "
" + tr("Generated coins must mature 50 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to \"not accepted\" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.") + "
";

        //
        // Debug view
        //
        if (fDebug)
        {
            strHTML += "

" + tr("Debug information") + "

";
            BOOST_FOREACH(const CTxIn& txin, wtx.vin)
                if(wallet->IsMine(txin))
                    strHTML += "" + tr("Debit") + ": " + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, -wallet->GetDebit(txin)) + "
";
            BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                if(wallet->IsMine(txout))
                    strHTML += "" + tr("Credit") + ": " + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, wallet->GetCredit(txout)) + "
";

            strHTML += "
" + tr("Transaction") + ":
";
            strHTML += GUIUtil::HtmlEscape(wtx.ToString(), true);

            CTxDB txdb("r"); // To fetch source txouts

            strHTML += "
" + tr("Inputs") + ":";
            strHTML += "
";

            {
                LOCK(wallet->cs_wallet);
                BOOST_FOREACH(const CTxIn& txin, wtx.vin)
                {
                    COutPoint prevout = txin.prevout;

                    CTransaction prev;
                    if(txdb.ReadDiskTx(prevout.hash, prev))
                    {
                        if (prevout.n < prev.vout.size())
                        {
                            strHTML += "
";
                            const CTxOut &vout = prev.vout[prevout.n];
                            CTxDestination address;
                            if (ExtractDestination(vout.scriptPubKey, address))
                            {
                                if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].empty())
                                    strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + " ";
                                strHTML += QString::fromStdString(CBitcoinAddress(address).ToString());
                            }
                            strHTML = strHTML + " " + tr("Amount") + "=" + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, vout.nValue);
                            strHTML = strHTML + " IsMine=" + (wallet->IsMine(vout) ? tr("true") : tr("false")) + "
";
                        }
                    }
                }
            }

            strHTML += "
";
        }

        strHTML += "";
    }
    return strHTML;
}
<commit_msg>Update Qt text for number of minting confirmations (#98)<commit_after>#include "transactiondesc.h"

#include "guiutil.h"
#include "bitcoinunits.h"

#include "main.h"
#include "wallet.h"
#include "txdb.h"
#include "ui_interface.h"
#include "base58.h"

QString TransactionDesc::FormatTxStatus(const CWalletTx& wtx)
{
    if (!wtx.IsFinal())
    {
        if (wtx.nLockTime < LOCKTIME_THRESHOLD)
            return tr("Open for %n block(s)", "", nBestHeight - wtx.nLockTime);
        else
            return tr("Open until %1").arg(GUIUtil::dateTimeStr(wtx.nLockTime));
    }
    else
    {
        int nDepth = wtx.GetDepthInMainChain();
        if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
            return tr("%1/offline").arg(nDepth);
        else if (nDepth < 6)
            return tr("%1/unconfirmed").arg(nDepth);
        else
            return tr("%1 confirmations").arg(nDepth);
    }
}

QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx)
{
    QString strHTML;

    {
        LOCK(wallet->cs_wallet);
        strHTML.reserve(4000);
        strHTML += "";

        int64 nTime = wtx.GetTxTime();
        int64 nCredit = wtx.GetCredit();
        int64 nDebit = wtx.GetDebit();
        int64 nNet = nCredit - nDebit;

        strHTML += "" + tr("Status") + ": " + FormatTxStatus(wtx);
        int nRequests = wtx.GetRequestCount();
        if (nRequests != -1)
        {
            if (nRequests == 0)
                strHTML += tr(", has not been successfully broadcast yet");
            else if (nRequests > 0)
                strHTML += tr(", broadcast through %n node(s)", "", nRequests);
        }
        strHTML += "
";

        strHTML += "" + tr("Date") + ": " + (nTime ? GUIUtil::dateTimeStr(nTime) : "") + "
";

        //
        // From
        //
        if (wtx.IsCoinBase())
        {
            strHTML += "" + tr("Source") + ": " + tr("Generated") + "
";
        }
        else if (wtx.mapValue.count("from") && !wtx.mapValue["from"].empty())
        {
            // Online transaction
            strHTML += "" + tr("From") + ": " + GUIUtil::HtmlEscape(wtx.mapValue["from"]) + "
";
        }
        else
        {
            // Offline transaction
            if (nNet > 0)
            {
                // Credit
                BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                {
                    if (wallet->IsMine(txout))
                    {
                        CTxDestination address;
                        if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address))
                        {
                            if (wallet->mapAddressBook.count(address))
                            {
                                strHTML += "" + tr("From") + ": " + tr("unknown") + "
";
                                strHTML += "" + tr("To") + ": ";
                                strHTML += GUIUtil::HtmlEscape(CBitcoinAddress(address).ToString());
                                if (!wallet->mapAddressBook[address].empty())
                                    strHTML += " (" + tr("own address") + ", " + tr("label") + ": " + GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + ")";
                                else
                                    strHTML += " (" + tr("own address") + ")";
                                strHTML += "
";
                            }
                        }
                        break;
                    }
                }
            }
        }

        //
        // To
        //
        if (wtx.mapValue.count("to") && !wtx.mapValue["to"].empty())
        {
            // Online transaction
            std::string strAddress = wtx.mapValue["to"];
            strHTML += "" + tr("To") + ": ";
            CTxDestination dest = CBitcoinAddress(strAddress).Get();
            if (wallet->mapAddressBook.count(dest) && !wallet->mapAddressBook[dest].empty())
                strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[dest]) + " ";
            strHTML += GUIUtil::HtmlEscape(strAddress) + "
";
        }

        //
        // Amount
        //
        if (wtx.IsCoinBase() && nCredit == 0)
        {
            //
            // Coinbase
            //
            int64 nUnmatured = 0;
            BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                nUnmatured += wallet->GetCredit(txout);
            strHTML += "" + tr("Credit") + ": ";
            if (wtx.IsInMainChain())
                strHTML += BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nUnmatured)+ " (" + tr("matures in %n more block(s)", "", wtx.GetBlocksToMaturity()) + ")";
            else
                strHTML += "(" + tr("not accepted") + ")";
            strHTML += "
";
        }
        else if (nNet > 0)
        {
            //
            // Credit
            //
            strHTML += "" + tr("Credit") + ": " + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nNet) + "
";
        }
        else
        {
            bool fAllFromMe = true;
            BOOST_FOREACH(const CTxIn& txin, wtx.vin)
                fAllFromMe = fAllFromMe && wallet->IsMine(txin);

            bool fAllToMe = true;
            BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                fAllToMe = fAllToMe && wallet->IsMine(txout);

            if (fAllFromMe)
            {
                //
                // Debit
                //
                BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                {
                    if (wallet->IsMine(txout))
                        continue;

                    if (!wtx.mapValue.count("to") || wtx.mapValue["to"].empty())
                    {
                        // Offline transaction
                        CTxDestination address;
                        if (ExtractDestination(txout.scriptPubKey, address))
                        {
                            strHTML += "" + tr("To") + ": ";
                            if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].empty())
                                strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + " ";
                            strHTML += GUIUtil::HtmlEscape(CBitcoinAddress(address).ToString());
                            strHTML += "
";
                        }
                    }

                    strHTML += "" + tr("Debit") + ": " + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, -txout.nValue) + "
";
                }

                if (fAllToMe)
                {
                    // Payment to self
                    int64 nChange = wtx.GetChange();
                    int64 nValue = nCredit - nChange;
                    strHTML += "" + tr("Debit") + ": " + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, -nValue) + "
";
                    strHTML += "" + tr("Credit") + ": " + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nValue) + "
";
                }

                int64 nTxFee = nDebit - wtx.GetValueOut();
                if (nTxFee > 0)
                    strHTML += "" + tr("Transaction fee") + ": " + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, -nTxFee) + "
";
            }
            else
            {
                //
                // Mixed debit transaction
                //
                BOOST_FOREACH(const CTxIn& txin, wtx.vin)
                    if (wallet->IsMine(txin))
                        strHTML += "" + tr("Debit") + ": " + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, -wallet->GetDebit(txin)) + "
";
                BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                    if (wallet->IsMine(txout))
                        strHTML += "" + tr("Credit") + ": " + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, wallet->GetCredit(txout)) + "
";
            }
        }

        strHTML += "" + tr("Net amount") + ": " + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nNet, true) + "
";

        //
        // Message
        //
        if (!wtx.mapValue["message"].empty())
             strHTML += "
" + tr("Message") + ":
" + GUIUtil::HtmlEscape(wtx.mapValue["message"], true) + "
";

		if (!wtx.mapValue["comment"].empty())
            strHTML += "
" + tr("Comment") + ":
" + GUIUtil::HtmlEscape(wtx.mapValue["comment"], true) + "
";

        strHTML += "" + tr("Transaction ID") + ": " + wtx.GetHash().ToString().c_str() + "
";

        if (wtx.IsCoinBase() || wtx.IsCoinStake())
            strHTML += "
" + tr("Generated coins must mature 60 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to \"not accepted\" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.") + "
";

        //
        // Debug view
        //
        if (fDebug)
        {
            strHTML += "

" + tr("Debug information") + "

";
            BOOST_FOREACH(const CTxIn& txin, wtx.vin)
                if(wallet->IsMine(txin))
                    strHTML += "" + tr("Debit") + ": " + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, -wallet->GetDebit(txin)) + "
";
            BOOST_FOREACH(const CTxOut& txout, wtx.vout)
                if(wallet->IsMine(txout))
                    strHTML += "" + tr("Credit") + ": " + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, wallet->GetCredit(txout)) + "
";

            strHTML += "
" + tr("Transaction") + ":
";
            strHTML += GUIUtil::HtmlEscape(wtx.ToString(), true);

            CTxDB txdb("r"); // To fetch source txouts

            strHTML += "
" + tr("Inputs") + ":";
            strHTML += "
";

            {
                LOCK(wallet->cs_wallet);
                BOOST_FOREACH(const CTxIn& txin, wtx.vin)
                {
                    COutPoint prevout = txin.prevout;

                    CTransaction prev;
                    if(txdb.ReadDiskTx(prevout.hash, prev))
                    {
                        if (prevout.n < prev.vout.size())
                        {
                            strHTML += "
";
                            const CTxOut &vout = prev.vout[prevout.n];
                            CTxDestination address;
                            if (ExtractDestination(vout.scriptPubKey, address))
                            {
                                if (wallet->mapAddressBook.count(address) && !wallet->mapAddressBook[address].empty())
                                    strHTML += GUIUtil::HtmlEscape(wallet->mapAddressBook[address]) + " ";
                                strHTML += QString::fromStdString(CBitcoinAddress(address).ToString());
                            }
                            strHTML = strHTML + " " + tr("Amount") + "=" + BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, vout.nValue);
                            strHTML = strHTML + " IsMine=" + (wallet->IsMine(vout) ? tr("true") : tr("false")) + "
";
                        }
                    }
                }
            }

            strHTML += "
";
        }

        strHTML += "";
    }
    return strHTML;
}
<|endoftext|>


<commit_before>#include <config/config_class.h>
#include <config/config_class_address.h>
#include <config/config_object.h>
#include <config/config_value.h>

ConfigClassAddress config_class_address;

bool
ConfigClassAddress::activate(ConfigObject *co)
{
	ConfigTypeAddressFamily *familyct;
	ConfigValue *familycv = co->get("family", &familyct);
	if (familycv == NULL)
		return (false);

	SocketAddressFamily family;
	if (!familyct->get(familycv, &family))
		return (false);

	if (family == SocketAddressFamilyIPv4) {
		if (co->has("path"))
			return (false);
		return (true);
	}

	if (family == SocketAddressFamilyUnix) {
		if (co->has("host") || co->has("port"))
			return (false);
		return (true);
	}

	return (false);
}
<commit_msg>Unbreak validity-checking of IPv6.<commit_after>#include <config/config_class.h>
#include <config/config_class_address.h>
#include <config/config_object.h>
#include <config/config_value.h>

ConfigClassAddress config_class_address;

bool
ConfigClassAddress::activate(ConfigObject *co)
{
	ConfigTypeAddressFamily *familyct;
	ConfigValue *familycv = co->get("family", &familyct);
	if (familycv == NULL)
		return (false);

	SocketAddressFamily family;
	if (!familyct->get(familycv, &family))
		return (false);

	if (family == SocketAddressFamilyIPv4 ||
	    family == SocketAddressFamilyIPv6) {
		if (co->has("path"))
			return (false);
		return (true);
	}

	if (family == SocketAddressFamilyUnix) {
		if (co->has("host") || co->has("port"))
			return (false);
		return (true);
	}

	return (false);
}
<|endoftext|>


<commit_before>#include "remotescreenbuffer.h"
#include "freerdphelpers.h"

#include <QImage>
#include <QDebug>
#include <QPainter>

#include <freerdp/codec/bitmap.h>

class RemoteScreenBufferPrivate {
public:
    RemoteScreenBufferPrivate(RemoteScreenBuffer *q) : q_ptr(q) {
    }

    void initBuffer() {
        Q_Q(RemoteScreenBuffer);
        Q_ASSERT(isSizeAndFormatValid());
        if (isSizeAndFormatValid()) {
            bufferData.resize(width * height * bpp);
            targetImage = q->createImage();
            targetImage.fill(0);
        }
    }

    bool isSizeAndFormatValid() const {
        return width > 0 && height > 0 && bppToImageFormat(bpp) != QImage::Format_Invalid;
    }

    QByteArray bufferData;
    quint16 width;
    quint16 height;
    quint8 bpp;
    QImage targetImage;

private:
    Q_DECLARE_PUBLIC(RemoteScreenBuffer)
    RemoteScreenBuffer* const q_ptr;
};

RemoteScreenBuffer::RemoteScreenBuffer(quint16 width, quint16 height, quint8 bpp, QObject *parent)
    : QObject(parent), d_ptr(new RemoteScreenBufferPrivate(this)) {
    Q_D(RemoteScreenBuffer);
    d->width = width;
    d->height = height;
    d->bpp = bpp;
    d->initBuffer();
}

RemoteScreenBuffer::~RemoteScreenBuffer() {
    delete d_ptr;
}

QImage RemoteScreenBuffer::createImage() const {
    Q_D(const RemoteScreenBuffer);
    return QImage((uchar*)d->bufferData.data(), d->width, d->height, bppToImageFormat(d->bpp));
}

void RemoteScreenBuffer::addRectangle(const QRect &rect, const QByteArray &data) {
    Q_D(RemoteScreenBuffer);
    // decompress update's image data to 'imgData'
    QByteArray imgData;
    imgData.resize(rect.width() * rect.height() * (d->bpp / 8));
    if (!bitmap_decompress((BYTE*)data.data(), (BYTE*)imgData.data(), rect.width(), rect.height(), data.size(), d->bpp, d->bpp)) {
        qWarning() << "Bitmap update decompression failed";
    }

    QImage rectImg((uchar*)imgData.data(), rect.width(), rect.height(), bppToImageFormat(d->bpp));

    QPainter painter(&d->targetImage);
    painter.drawImage(rect, rectImg);
}

<commit_msg>Workaround for heap corruption bug.<commit_after>#include "remotescreenbuffer.h"
#include "freerdphelpers.h"

#include <QImage>
#include <QDebug>
#include <QPainter>

#include <freerdp/codec/bitmap.h>

class RemoteScreenBufferPrivate {
public:
    RemoteScreenBufferPrivate(RemoteScreenBuffer *q) : q_ptr(q) {
    }

    void initBuffer() {
        Q_Q(RemoteScreenBuffer);
        Q_ASSERT(isSizeAndFormatValid());
        if (isSizeAndFormatValid()) {
            bufferData.resize(width * height * bpp);
            targetImage = q->createImage();
            targetImage.fill(0);
        }
    }

    bool isSizeAndFormatValid() const {
        return width > 0 && height > 0 && bppToImageFormat(bpp) != QImage::Format_Invalid;
    }

    QByteArray bufferData;
    quint16 width;
    quint16 height;
    quint8 bpp;
    QImage targetImage;

private:
    Q_DECLARE_PUBLIC(RemoteScreenBuffer)
    RemoteScreenBuffer* const q_ptr;
};

RemoteScreenBuffer::RemoteScreenBuffer(quint16 width, quint16 height, quint8 bpp, QObject *parent)
    : QObject(parent), d_ptr(new RemoteScreenBufferPrivate(this)) {
    Q_D(RemoteScreenBuffer);
    d->width = width;
    d->height = height;
    d->bpp = bpp;
    d->initBuffer();
}

RemoteScreenBuffer::~RemoteScreenBuffer() {
    delete d_ptr;
}

QImage RemoteScreenBuffer::createImage() const {
    Q_D(const RemoteScreenBuffer);
    return QImage((uchar*)d->bufferData.data(), d->width, d->height, bppToImageFormat(d->bpp));
}

void RemoteScreenBuffer::addRectangle(const QRect &rect, const QByteArray &data) {
    Q_D(RemoteScreenBuffer);
    // hack: ignore 1 pixel height rectangles as decompressing of those
    // sometimes cause a heap corruption, reason unknown
    if (rect.height() == 1) {
        return;
    }

    // decompress update's image data to 'imgData'
    QByteArray imgData;
    imgData.resize(rect.width() * rect.height() * (d->bpp / 8));
    if (!bitmap_decompress((BYTE*)data.data(), (BYTE*)imgData.data(), rect.width(), rect.height(), data.size(), d->bpp, d->bpp)) {
        qWarning() << "Bitmap update decompression failed";
    }

    QImage rectImg((uchar*)imgData.data(), rect.width(), rect.height(), bppToImageFormat(d->bpp));

    QPainter painter(&d->targetImage);
    painter.drawImage(rect, rectImg);
}

<|endoftext|>


<commit_before>/**
 * @file rodsdownloadthread.h
 * @brief Implementation of class RodsDownloadThread
 *
 * The RodsDownloadThread class extends the Qt thread management class
 * QThread and implements a worker thread for a download (get) operation.
 *
 * Copyright (C) 2014-2015 University of Jyväskylä. All rights reserved.
 * License: The BSD 3-Clause License, see LICENSE file for details.
 *
 * @author Ilari Korhonen
 */

// application class RodsDownloadThread header
#include "rodsdownloadthread.h"

RodsDownloadThread::RodsDownloadThread(Kanki::RodsConnection *theConn, Kanki::RodsObjEntryPtr theObj,
                                       const std::string &theDestPath, bool verifyChecksum, bool allowOverwrite)
    : QThread()
{
    this->conn = new Kanki::RodsConnection(theConn);
    this->objEntry = theObj;
    this->destPath = theDestPath;

    this->verify = verifyChecksum;
    this->overwrite = allowOverwrite;
}

void RodsDownloadThread::run()
{
    int status = 0;
    QString statusStr = "Initializing...";

    // signal ui to setup progress display
    progressMarquee(statusStr);

    // open the parallel connection for transfer and authenticate
    if ((status = this->conn->connect()) < 0)
    {
        reportError("Download failed", "Open parallel connection failed", status);
        return;
    }

    else if ((status = this->conn->login()) < 0)
    {
        reportError("Download failed", "Authentication failed", status);
        return;
    }

    // in the case of downloading a collection, do it recursively
    if (this->objEntry->objType == COLL_OBJ_T)
    {
        std::vector<Kanki::RodsObjEntryPtr> collObjs;
        std::string basePath = this->objEntry->collPath;

        // first item to the download object list
        collObjs.push_back(this->objEntry);

        // try to construct the download object list recursively
        if (!(status = makeCollObjList(this->objEntry, &collObjs)))
        {
            // notify ui of progress bar state (object count)
            setupProgressDisplay(statusStr, 0, collObjs.size());

            // iterate thru object list
            for (unsigned int i = 0; i < collObjs.size(); i++)
            {
                Kanki::RodsObjEntryPtr curObj = collObjs.at(i);

                std::string basePath = this->objEntry->getObjectBasePath();
                std::string objPath = curObj->getObjectFullPath();

                objPath.erase(objPath.begin(), objPath.begin() + basePath.size());
                std::string dstPath = this->destPath + objPath;

                // in the case of a data object, we do a get operation
                if (curObj->objType == DATA_OBJ_T)
                {
                    // notify ui of current operation and progress
                    statusStr = "Downloading ";
                    statusStr += curObj->getObjectName().c_str();
                    progressUpdate(statusStr, i+1);

                    // try to do a rods get operation
                    if ((status = this->downloadFile(curObj, dstPath, this->verify, this->overwrite)) < 0)
                        reportError("iRODS get file error", "Get failed", status);
                }

                // for collection objects we create the corresponding directory
                else if (curObj->objType == COLL_OBJ_T)
                {
                    // get directory name for ui
                    std::string dirName = dstPath.substr(dstPath.find_last_of('/') + 1);

                    // notify ui
                    statusStr = "Creating directory ";
                    statusStr += dirName.c_str();
                    progressUpdate(statusStr, i+1);

                    // check if directory exists and if not, make it
                    QDir dstDir(dstPath.c_str());

                    if (!dstDir.exists())
                        dstDir.mkpath(dstPath.c_str());
                }
            }
        }
    }

    // in the case of downloading a single data object, a simple get operation
    else if (this->objEntry->objType == DATA_OBJ_T)
    {
        QString statusStr = "Downloading file: ";

        statusStr += this->objEntry->getObjectName().c_str();
        std::string dstPath = this->destPath + "/" + this->objEntry->getObjectName();
        setupProgressDisplay(statusStr, 1, 1);

        // try to do a rods get operation
        if ((status = this->downloadFile(objEntry, dstPath, this->verify, this->overwrite)) < 0)
            reportError("Download failed", "Kanki data stream error", status);
    }

    this->conn->disconnect();
    delete(this->conn);
}

int RodsDownloadThread::makeCollObjList(Kanki::RodsObjEntryPtr obj, std::vector<Kanki::RodsObjEntryPtr> *objs)
{
    int status = 0;

    // we proceed only for collections
    if (obj->objType == COLL_OBJ_T)
    {
        std::vector<Kanki::RodsObjEntryPtr> curCollObjs;

        // try to read collection
        if ((status = this->conn->readColl(obj->collPath, &curCollObjs)) >= 0)
        {
            // iterate thru current collection
            for (std::vector<Kanki::RodsObjEntryPtr>::iterator i = curCollObjs.begin(); i != curCollObjs.end(); i++)
            {
                // add object to list
                Kanki::RodsObjEntryPtr curObj = *i;
                objs->push_back(curObj);

                // notify ui
                QString statusStr = "Building a list of objects (" + QVariant((int)objs->size()).toString() + ")...";
                progressMarquee(statusStr);

                // recurse on collection objects
                if (curObj->objType == COLL_OBJ_T)
                {
                    status = makeCollObjList(curObj, objs);

                    // on error, back off recursion
                    if (status < 0)
                        return (status);
                }
            }
        }
    }

    return (status);
}

int RodsDownloadThread::downloadFile(Kanki::RodsObjEntryPtr obj, std::string localPath,
                                     bool verifyChecksum, bool allowOverwrite)
{
    Kanki::RodsDataInStream inStream(this->conn, obj);
    long int status = 0, lastRead = 0, lastWrite = 0, totalRead = 0, totalWritten = 0;
    QFile localFile(localPath.c_str());
    long int readSize = __KANKI_BUFSIZE_MAX;
    void *buffer = std::malloc(readSize), *buffer2 = std::malloc(readSize);
    boost::thread *writer = NULL;

    // check if we're allowed to proceed
    if (localFile.exists() && !allowOverwrite)
        return (OVERWRITE_WITHOUT_FORCE_FLAG);

    // try to open local file and the rods data stream
    if (!localFile.open(QIODevice::WriteOnly))
        return (-1);

    // try to initiate get operation and open data stream
    if ((status = inStream.getOprInit()) < 0)
        return (status);

    if ((status = inStream.openDataObj()) < 0)
        return (status);

    else {
        // update status display only on large enough objects
        if (obj->objSize > __KANKI_BUFSIZE_INIT)
            setupSubProgressDisplay("Transferring...", 0, 100);

        std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();

        while ((lastRead = inStream.readAdaptive(buffer, readSize)) > 0)
        {
            std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
            std::chrono::milliseconds diff = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0);

            totalRead += lastRead;

            // if we had something to write, wait for it
            if (writer)
            {
                writer->join();
                delete (writer);

                // check for write errors
                if (localFile.error() == QFile::WriteError)
                {
                    reportError("Download failed", "Write error", -1);
                    verifyChecksum = false;

                    break;
                }
            }

            // (re)new writer thread
            writer = new boost::thread(boost::bind(&QFile::write, &localFile, (const char*)buffer, lastRead));

            // XOR swap buffer pointers
            buffer = (void*)((uintptr_t)buffer ^ (uintptr_t)buffer2);
            buffer2 = (void*)((uintptr_t)buffer ^ (uintptr_t)buffer2);
            buffer = (void*)((uintptr_t)buffer ^ (uintptr_t)buffer2);

            // compute and signal statistics to UI
            double speed = ((double)totalRead / 1048576) / ((double)diff.count() / 1000);
            double percentage = ceil(((double)totalRead / (double)obj->objSize) * 100);

            QString statusStr = "Transferring... " + QVariant((int)percentage).toString() + "%";
            statusStr += " at " + QString::number(speed, 'f', 2) + " MB/s";

            if (obj->objSize > __KANKI_BUFSIZE_INIT)
                subProgressUpdate(statusStr, (int)percentage);
        }
    }

    // close local file and rods data stream
    localFile.close();
    status = inStream.closeDataObj();
    inStream.getOprEnd();

    // if verify checksum was required
    if (verifyChecksum && strlen(inStream.checksum()))
    {
        subProgressUpdate("Verifying Checksum...", 100);
        status = verifyChksumLocFile((char*)localPath.c_str(), (char*)inStream.checksum(), NULL);
    }

    // free everything we have allocated
    if (writer)
        delete (writer);

    std::free(buffer);
    std::free(buffer2);

    return (status);
}
<commit_msg>removed unused variables<commit_after>/**
 * @file rodsdownloadthread.h
 * @brief Implementation of class RodsDownloadThread
 *
 * The RodsDownloadThread class extends the Qt thread management class
 * QThread and implements a worker thread for a download (get) operation.
 *
 * Copyright (C) 2014-2015 University of Jyväskylä. All rights reserved.
 * License: The BSD 3-Clause License, see LICENSE file for details.
 *
 * @author Ilari Korhonen
 */

// application class RodsDownloadThread header
#include "rodsdownloadthread.h"

RodsDownloadThread::RodsDownloadThread(Kanki::RodsConnection *theConn, Kanki::RodsObjEntryPtr theObj,
                                       const std::string &theDestPath, bool verifyChecksum, bool allowOverwrite)
    : QThread()
{
    this->conn = new Kanki::RodsConnection(theConn);
    this->objEntry = theObj;
    this->destPath = theDestPath;

    this->verify = verifyChecksum;
    this->overwrite = allowOverwrite;
}

void RodsDownloadThread::run()
{
    int status = 0;
    QString statusStr = "Initializing...";

    // signal ui to setup progress display
    progressMarquee(statusStr);

    // open the parallel connection for transfer and authenticate
    if ((status = this->conn->connect()) < 0)
    {
        reportError("Download failed", "Open parallel connection failed", status);
        return;
    }

    else if ((status = this->conn->login()) < 0)
    {
        reportError("Download failed", "Authentication failed", status);
        return;
    }

    // in the case of downloading a collection, do it recursively
    if (this->objEntry->objType == COLL_OBJ_T)
    {
        std::vector<Kanki::RodsObjEntryPtr> collObjs;
        std::string basePath = this->objEntry->collPath;

        // first item to the download object list
        collObjs.push_back(this->objEntry);

        // try to construct the download object list recursively
        if (!(status = makeCollObjList(this->objEntry, &collObjs)))
        {
            // notify ui of progress bar state (object count)
            setupProgressDisplay(statusStr, 0, collObjs.size());

            // iterate thru object list
            for (unsigned int i = 0; i < collObjs.size(); i++)
            {
                Kanki::RodsObjEntryPtr curObj = collObjs.at(i);

                std::string basePath = this->objEntry->getObjectBasePath();
                std::string objPath = curObj->getObjectFullPath();

                objPath.erase(objPath.begin(), objPath.begin() + basePath.size());
                std::string dstPath = this->destPath + objPath;

                // in the case of a data object, we do a get operation
                if (curObj->objType == DATA_OBJ_T)
                {
                    // notify ui of current operation and progress
                    statusStr = "Downloading ";
                    statusStr += curObj->getObjectName().c_str();
                    progressUpdate(statusStr, i+1);

                    // try to do a rods get operation
                    if ((status = this->downloadFile(curObj, dstPath, this->verify, this->overwrite)) < 0)
                        reportError("iRODS get file error", "Get failed", status);
                }

                // for collection objects we create the corresponding directory
                else if (curObj->objType == COLL_OBJ_T)
                {
                    // get directory name for ui
                    std::string dirName = dstPath.substr(dstPath.find_last_of('/') + 1);

                    // notify ui
                    statusStr = "Creating directory ";
                    statusStr += dirName.c_str();
                    progressUpdate(statusStr, i+1);

                    // check if directory exists and if not, make it
                    QDir dstDir(dstPath.c_str());

                    if (!dstDir.exists())
                        dstDir.mkpath(dstPath.c_str());
                }
            }
        }
    }

    // in the case of downloading a single data object, a simple get operation
    else if (this->objEntry->objType == DATA_OBJ_T)
    {
        QString statusStr = "Downloading file: ";

        statusStr += this->objEntry->getObjectName().c_str();
        std::string dstPath = this->destPath + "/" + this->objEntry->getObjectName();
        setupProgressDisplay(statusStr, 1, 1);

        // try to do a rods get operation
        if ((status = this->downloadFile(objEntry, dstPath, this->verify, this->overwrite)) < 0)
            reportError("Download failed", "Kanki data stream error", status);
    }

    this->conn->disconnect();
    delete(this->conn);
}

int RodsDownloadThread::makeCollObjList(Kanki::RodsObjEntryPtr obj, std::vector<Kanki::RodsObjEntryPtr> *objs)
{
    int status = 0;

    // we proceed only for collections
    if (obj->objType == COLL_OBJ_T)
    {
        std::vector<Kanki::RodsObjEntryPtr> curCollObjs;

        // try to read collection
        if ((status = this->conn->readColl(obj->collPath, &curCollObjs)) >= 0)
        {
            // iterate thru current collection
            for (std::vector<Kanki::RodsObjEntryPtr>::iterator i = curCollObjs.begin(); i != curCollObjs.end(); i++)
            {
                // add object to list
                Kanki::RodsObjEntryPtr curObj = *i;
                objs->push_back(curObj);

                // notify ui
                QString statusStr = "Building a list of objects (" + QVariant((int)objs->size()).toString() + ")...";
                progressMarquee(statusStr);

                // recurse on collection objects
                if (curObj->objType == COLL_OBJ_T)
                {
                    status = makeCollObjList(curObj, objs);

                    // on error, back off recursion
                    if (status < 0)
                        return (status);
                }
            }
        }
    }

    return (status);
}

int RodsDownloadThread::downloadFile(Kanki::RodsObjEntryPtr obj, std::string localPath,
                                     bool verifyChecksum, bool allowOverwrite)
{
    Kanki::RodsDataInStream inStream(this->conn, obj);
    long int status = 0, lastRead = 0, totalRead = 0;
    QFile localFile(localPath.c_str());
    long int readSize = __KANKI_BUFSIZE_MAX;
    void *buffer = std::malloc(readSize), *buffer2 = std::malloc(readSize);
    boost::thread *writer = NULL;

    // check if we're allowed to proceed
    if (localFile.exists() && !allowOverwrite)
        return (OVERWRITE_WITHOUT_FORCE_FLAG);

    // try to open local file and the rods data stream
    if (!localFile.open(QIODevice::WriteOnly))
        return (-1);

    // try to initiate get operation and open data stream
    if ((status = inStream.getOprInit()) < 0)
        return (status);

    if ((status = inStream.openDataObj()) < 0)
        return (status);

    else {
        // update status display only on large enough objects
        if (obj->objSize > __KANKI_BUFSIZE_INIT)
            setupSubProgressDisplay("Transferring...", 0, 100);

        std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now();

        while ((lastRead = inStream.readAdaptive(buffer, readSize)) > 0)
        {
            std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now();
            std::chrono::milliseconds diff = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0);

            totalRead += lastRead;

            // if we had something to write, wait for it
            if (writer)
            {
                writer->join();
                delete (writer);

                // check for write errors
                if (localFile.error() == QFile::WriteError)
                {
                    reportError("Download failed", "Write error", -1);
                    verifyChecksum = false;

                    break;
                }
            }

            // (re)new writer thread
            writer = new boost::thread(boost::bind(&QFile::write, &localFile, (const char*)buffer, lastRead));

            // XOR swap buffer pointers
            buffer = (void*)((uintptr_t)buffer ^ (uintptr_t)buffer2);
            buffer2 = (void*)((uintptr_t)buffer ^ (uintptr_t)buffer2);
            buffer = (void*)((uintptr_t)buffer ^ (uintptr_t)buffer2);

            // compute and signal statistics to UI
            double speed = ((double)totalRead / 1048576) / ((double)diff.count() / 1000);
            double percentage = ceil(((double)totalRead / (double)obj->objSize) * 100);

            QString statusStr = "Transferring... " + QVariant((int)percentage).toString() + "%";
            statusStr += " at " + QString::number(speed, 'f', 2) + " MB/s";

            if (obj->objSize > __KANKI_BUFSIZE_INIT)
                subProgressUpdate(statusStr, (int)percentage);
        }
    }

    // close local file and rods data stream
    localFile.close();
    status = inStream.closeDataObj();
    inStream.getOprEnd();

    // if verify checksum was required
    if (verifyChecksum && strlen(inStream.checksum()))
    {
        subProgressUpdate("Verifying Checksum...", 100);
        status = verifyChksumLocFile((char*)localPath.c_str(), (char*)inStream.checksum(), NULL);
    }

    // free everything we have allocated
    if (writer)
        delete (writer);

    std::free(buffer);
    std::free(buffer2);

    return (status);
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2009, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */
/**
 ** \file runner/interpreter.hxx
 ** \brief Inline implementation of runner::Interpreter.
 */

#ifndef RUNNER_INTERPRETER_HXX
# define RUNNER_INTERPRETER_HXX

#include <libport/finally.hh>

#include <ast/ast.hh>
#include <urbi/object/tag.hh>

namespace runner
{

  inline
  Interpreter::rObject
  Interpreter::result_get()
  {
    return result_;
  }

  inline
  libport::Symbol
  Interpreter::innermost_call_get() const
  {
    assert(!call_stack_.empty());
    return call_stack_.back().first;
  }

  /*----------------.
  | Regular visit.  |
  `----------------*/

#define FINALLY_Ast(DefineOrUse)                                        \
  FINALLY_ ## DefineOrUse(Ast,                                          \
                          ((const ast::Ast*&, innermost_node_))         \
                          ((const ast::Ast*, previous)),                \
                          innermost_node_ = previous);

  FINALLY_Ast(DEFINE);
  inline object::rObject
  Interpreter::operator() (const ast::Ast* e)
  {
    const ast::Ast* previous = innermost_node_;
    FINALLY_Ast(USE);
    innermost_node_ = e;
    return e->eval(*this);
  }
# undef FINALLY_AST_ARGS

} // namespace runner

#endif // RUNNER_INTERPRETER_HXX
<commit_msg>Accept empty backtraces.<commit_after>/*
 * Copyright (C) 2009, 2010, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */
/**
 ** \file runner/interpreter.hxx
 ** \brief Inline implementation of runner::Interpreter.
 */

#ifndef RUNNER_INTERPRETER_HXX
# define RUNNER_INTERPRETER_HXX

#include <libport/finally.hh>

#include <ast/ast.hh>
#include <urbi/object/tag.hh>
#include <object/symbols.hh>

namespace runner
{

  inline
  Interpreter::rObject
  Interpreter::result_get()
  {
    return result_;
  }

  inline
  libport::Symbol
  Interpreter::innermost_call_get() const
  {
    if (call_stack_.empty())
      return SYMBOL(LT_empty_GT);
    else
      return call_stack_.back().first;
  }

  /*----------------.
  | Regular visit.  |
  `----------------*/

#define FINALLY_Ast(DefineOrUse)                                        \
  FINALLY_ ## DefineOrUse(Ast,                                          \
                          ((const ast::Ast*&, innermost_node_))         \
                          ((const ast::Ast*, previous)),                \
                          innermost_node_ = previous);

  FINALLY_Ast(DEFINE);
  inline object::rObject
  Interpreter::operator() (const ast::Ast* e)
  {
    const ast::Ast* previous = innermost_node_;
    FINALLY_Ast(USE);
    innermost_node_ = e;
    return e->eval(*this);
  }
# undef FINALLY_AST_ARGS

} // namespace runner

#endif // RUNNER_INTERPRETER_HXX
<|endoftext|>