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

#ifndef INCLUDED_SDEXT_SOURCE_PDFIMPORT_XPDFWRAPPER_PDFIOUTDEV_GPL_HXX
#define INCLUDED_SDEXT_SOURCE_PDFIMPORT_XPDFWRAPPER_PDFIOUTDEV_GPL_HXX

#include <sal/types.h>

#if defined __GNUC__
#if HAVE_GCC_PRAGMA_DIAGNOSTIC_MODIFY
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
#elif defined __SUNPRO_CC
#pragma disable_warn
#elif defined _MSC_VER
#pragma warning(push, 1)
#endif

#include "GfxState.h"
#include "GfxFont.h"
#include "UnicodeMap.h"
#include "Link.h"
#include "Object.h"
#include "OutputDev.h"
#include "GlobalParams.h"
#include "PDFDoc.h"

#if defined __GNUC__
#if HAVE_GCC_PRAGMA_DIAGNOSTIC_MODIFY
# pragma GCC diagnostic pop
#endif
#elif defined __SUNPRO_CC
#pragma enable_warn
#elif defined _MSC_VER
#pragma warning(pop)
#endif

#include <boost/unordered_map.hpp>
#include <vector>

class GfxPath;
class GfxFont;
class PDFDoc;
#include <cpp/poppler-version.h>
#define POPPLER_CHECK_VERSION(major,minor,micro) \
  (POPPLER_VERSION_MAJOR > (major) || \
   (POPPLER_VERSION_MAJOR == (major) && POPPLER_VERSION_MINOR > (minor)) || \
   (POPPLER_VERSION_MAJOR == (major) && POPPLER_VERSION_MINOR == (minor) && POPPLER_VERSION_MICRO >= (micro)))

namespace pdfi
{
    struct FontAttributes
    {
        FontAttributes( const GooString& familyName_,
                        bool           isEmbedded_,
                        bool           isBold_,
                        bool           isItalic_,
                        bool           isUnderline_,
                        double         size_ ) :
            familyName(),
            isEmbedded(isEmbedded_),
            isBold(isBold_),
            isItalic(isItalic_),
            isUnderline(isUnderline_),
            size(size_)
        {
            familyName.append(const_cast<GooString*>(&familyName_));
        }

        FontAttributes() :
            familyName(),
            isEmbedded(false),
            isBold(false),
            isItalic(false),
            isUnderline(false),
            size(0.0)
        {}

        // xdpf goo stuff is so totally borked...
        // ...need to hand-code assignment
        FontAttributes( const FontAttributes& rSrc ) :
            familyName(),
            isEmbedded(rSrc.isEmbedded),
            isBold(rSrc.isBold),
            isItalic(rSrc.isItalic),
            isUnderline(rSrc.isUnderline),
            size(rSrc.size)
        {
            familyName.append(const_cast<GooString*>(&rSrc.familyName));
        }

        FontAttributes& operator=( const FontAttributes& rSrc )
        {
            familyName.clear();
            familyName.append(const_cast<GooString*>(&rSrc.familyName));

            isEmbedded  = rSrc.isEmbedded;
            isBold      = rSrc.isBold;
            isItalic    = rSrc.isItalic;
            isUnderline = rSrc.isUnderline;
            size        = rSrc.size;

            return *this;
        }

        bool operator==(const FontAttributes& rFont) const
        {
            return const_cast<GooString*>(&familyName)->cmp(
                const_cast<GooString*>(&rFont.familyName))==0 &&
                isEmbedded == rFont.isEmbedded &&
                isBold == rFont.isBold &&
                isItalic == rFont.isItalic &&
                isUnderline == rFont.isUnderline &&
                size == rFont.size;
        }

        GooString     familyName;
        bool        isEmbedded;
        bool        isBold;
        bool        isItalic;
        bool        isUnderline;
        double      size;
    };

    class PDFOutDev : public OutputDev
    {
        // not owned by this class
        PDFDoc*                                 m_pDoc;
        mutable boost::unordered_map< long long,
                               FontAttributes > m_aFontMap;
        UnicodeMap*                             m_pUtf8Map;

        int  parseFont( long long nNewId, GfxFont* pFont, GfxState* state ) const;
        void writeFontFile( GfxFont* gfxFont ) const;
        void printPath( GfxPath* pPath ) const;

    public:
        explicit PDFOutDev( PDFDoc* pDoc );
        ~PDFOutDev();

        //----- get info about output device

        // Does this device use upside-down coordinates?
        // (Upside-down means (0,0) is the top left corner of the page.)
        virtual GBool upsideDown() SAL_OVERRIDE { return gTrue; }

        // Does this device use drawChar() or drawString()?
        virtual GBool useDrawChar() SAL_OVERRIDE { return gTrue; }

        // Does this device use beginType3Char/endType3Char?  Otherwise,
        // text in Type 3 fonts will be drawn with drawChar/drawString.
        virtual GBool interpretType3Chars() SAL_OVERRIDE { return gFalse; }

        // Does this device need non-text content?
        virtual GBool needNonText() SAL_OVERRIDE { return gTrue; }

        //----- initialization and control

        // Set default transform matrix.
        virtual void setDefaultCTM(double *ctm) SAL_OVERRIDE;

        // Start a page.
        virtual void startPage(int pageNum, GfxState *state
#if POPPLER_CHECK_VERSION(0, 23, 0) || POPPLER_CHECK_VERSION(0, 24, 0)
                               , XRef *xref
#endif
        ) SAL_OVERRIDE;

        // End a page.
        virtual void endPage() SAL_OVERRIDE;

        //----- link borders
	#if POPPLER_CHECK_VERSION(0, 19, 0)
        virtual void processLink(AnnotLink *link) SAL_OVERRIDE;
    #elif POPPLER_CHECK_VERSION(0, 17, 0)
        virtual void processLink(AnnotLink *link, Catalog *catalog) SAL_OVERRIDE;
    #else
        virtual void processLink(Link *link, Catalog *catalog) SAL_OVERRIDE;
    #endif

        //----- save/restore graphics state
        virtual void saveState(GfxState *state) SAL_OVERRIDE;
        virtual void restoreState(GfxState *state) SAL_OVERRIDE;

        //----- update graphics state
        virtual void updateCTM(GfxState *state, double m11, double m12,
                               double m21, double m22, double m31, double m32) SAL_OVERRIDE;
        virtual void updateLineDash(GfxState *state) SAL_OVERRIDE;
        virtual void updateFlatness(GfxState *state) SAL_OVERRIDE;
        virtual void updateLineJoin(GfxState *state) SAL_OVERRIDE;
        virtual void updateLineCap(GfxState *state) SAL_OVERRIDE;
        virtual void updateMiterLimit(GfxState *state) SAL_OVERRIDE;
        virtual void updateLineWidth(GfxState *state) SAL_OVERRIDE;
        virtual void updateFillColor(GfxState *state) SAL_OVERRIDE;
        virtual void updateStrokeColor(GfxState *state) SAL_OVERRIDE;
        virtual void updateFillOpacity(GfxState *state) SAL_OVERRIDE;
        virtual void updateStrokeOpacity(GfxState *state) SAL_OVERRIDE;
        virtual void updateBlendMode(GfxState *state) SAL_OVERRIDE;

        //----- update text state
        virtual void updateFont(GfxState *state) SAL_OVERRIDE;
        virtual void updateRender(GfxState *state) SAL_OVERRIDE;

        //----- path painting
        virtual void stroke(GfxState *state) SAL_OVERRIDE;
        virtual void fill(GfxState *state) SAL_OVERRIDE;
        virtual void eoFill(GfxState *state) SAL_OVERRIDE;

        //----- path clipping
        virtual void clip(GfxState *state) SAL_OVERRIDE;
        virtual void eoClip(GfxState *state) SAL_OVERRIDE;

        //----- text drawing
        virtual void drawChar(GfxState *state, double x, double y,
                              double dx, double dy,
                              double originX, double originY,
                              CharCode code, int nBytes, Unicode *u, int uLen) SAL_OVERRIDE;
        virtual void drawString(GfxState *state, GooString *s) SAL_OVERRIDE;
        virtual void endTextObject(GfxState *state) SAL_OVERRIDE;

        //----- image drawing
        virtual void drawImageMask(GfxState *state, Object *ref, Stream *str,
                                   int width, int height, GBool invert,
#if POPPLER_CHECK_VERSION(0, 12, 0)
                                   GBool interpolate,
#endif
                                   GBool inlineImg) SAL_OVERRIDE;
        virtual void drawImage(GfxState *state, Object *ref, Stream *str,
                               int width, int height, GfxImageColorMap *colorMap,
#if POPPLER_CHECK_VERSION(0, 12, 0)
                               GBool interpolate,
#endif
                               int *maskColors, GBool inlineImg) SAL_OVERRIDE;
        virtual void drawMaskedImage(GfxState *state, Object *ref, Stream *str,
                                     int width, int height,
                                     GfxImageColorMap *colorMap,
#if POPPLER_CHECK_VERSION(0, 12, 0)
                                     GBool interpolate,
#endif
                                     Stream *maskStr, int maskWidth, int maskHeight,
                                     GBool maskInvert
#if POPPLER_CHECK_VERSION(0, 12, 0)
                                     , GBool maskInterpolate
#endif
                                    ) SAL_OVERRIDE;
        virtual void drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str,
                                         int width, int height,
                                         GfxImageColorMap *colorMap,
#if POPPLER_CHECK_VERSION(0, 12, 0)
                                         GBool interpolate,
#endif
                                         Stream *maskStr,
                                         int maskWidth, int maskHeight,
                                         GfxImageColorMap *maskColorMap
#if POPPLER_CHECK_VERSION(0, 12, 0)
                                         , GBool maskInterpolate
#endif
                                        ) SAL_OVERRIDE;

        void setPageNum( int nNumPages );
    };
}

extern FILE* g_binary_out;

// note: if you ever hcange Output_t, please keep in mind that the current code
// relies on it being of 8 bit size
typedef Guchar Output_t;
typedef std::vector< Output_t > OutputBuffer;

#endif // INCLUDED_SDEXT_SOURCE_PDFIMPORT_XPDFWRAPPER_PDFIOUTDEV_GPL_HXX

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

#ifndef INCLUDED_SDEXT_SOURCE_PDFIMPORT_XPDFWRAPPER_PDFIOUTDEV_GPL_HXX
#define INCLUDED_SDEXT_SOURCE_PDFIMPORT_XPDFWRAPPER_PDFIOUTDEV_GPL_HXX

#include <sal/types.h>

#if defined __GNUC__
#if HAVE_GCC_PRAGMA_DIAGNOSTIC_SCOPE
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
#elif defined __SUNPRO_CC
#pragma disable_warn
#elif defined _MSC_VER
#pragma warning(push, 1)
#endif

#include "GfxState.h"
#include "GfxFont.h"
#include "UnicodeMap.h"
#include "Link.h"
#include "Object.h"
#include "OutputDev.h"
#include "GlobalParams.h"
#include "PDFDoc.h"

#if defined __GNUC__
#if HAVE_GCC_PRAGMA_DIAGNOSTIC_SCOPE
# pragma GCC diagnostic pop
#endif
#elif defined __SUNPRO_CC
#pragma enable_warn
#elif defined _MSC_VER
#pragma warning(pop)
#endif

#include <boost/unordered_map.hpp>
#include <vector>

class GfxPath;
class GfxFont;
class PDFDoc;
#include <cpp/poppler-version.h>
#define POPPLER_CHECK_VERSION(major,minor,micro) \
  (POPPLER_VERSION_MAJOR > (major) || \
   (POPPLER_VERSION_MAJOR == (major) && POPPLER_VERSION_MINOR > (minor)) || \
   (POPPLER_VERSION_MAJOR == (major) && POPPLER_VERSION_MINOR == (minor) && POPPLER_VERSION_MICRO >= (micro)))

namespace pdfi
{
    struct FontAttributes
    {
        FontAttributes( const GooString& familyName_,
                        bool           isEmbedded_,
                        bool           isBold_,
                        bool           isItalic_,
                        bool           isUnderline_,
                        double         size_ ) :
            familyName(),
            isEmbedded(isEmbedded_),
            isBold(isBold_),
            isItalic(isItalic_),
            isUnderline(isUnderline_),
            size(size_)
        {
            familyName.append(const_cast<GooString*>(&familyName_));
        }

        FontAttributes() :
            familyName(),
            isEmbedded(false),
            isBold(false),
            isItalic(false),
            isUnderline(false),
            size(0.0)
        {}

        // xdpf goo stuff is so totally borked...
        // ...need to hand-code assignment
        FontAttributes( const FontAttributes& rSrc ) :
            familyName(),
            isEmbedded(rSrc.isEmbedded),
            isBold(rSrc.isBold),
            isItalic(rSrc.isItalic),
            isUnderline(rSrc.isUnderline),
            size(rSrc.size)
        {
            familyName.append(const_cast<GooString*>(&rSrc.familyName));
        }

        FontAttributes& operator=( const FontAttributes& rSrc )
        {
            familyName.clear();
            familyName.append(const_cast<GooString*>(&rSrc.familyName));

            isEmbedded  = rSrc.isEmbedded;
            isBold      = rSrc.isBold;
            isItalic    = rSrc.isItalic;
            isUnderline = rSrc.isUnderline;
            size        = rSrc.size;

            return *this;
        }

        bool operator==(const FontAttributes& rFont) const
        {
            return const_cast<GooString*>(&familyName)->cmp(
                const_cast<GooString*>(&rFont.familyName))==0 &&
                isEmbedded == rFont.isEmbedded &&
                isBold == rFont.isBold &&
                isItalic == rFont.isItalic &&
                isUnderline == rFont.isUnderline &&
                size == rFont.size;
        }

        GooString     familyName;
        bool        isEmbedded;
        bool        isBold;
        bool        isItalic;
        bool        isUnderline;
        double      size;
    };

    class PDFOutDev : public OutputDev
    {
        // not owned by this class
        PDFDoc*                                 m_pDoc;
        mutable boost::unordered_map< long long,
                               FontAttributes > m_aFontMap;
        UnicodeMap*                             m_pUtf8Map;

        int  parseFont( long long nNewId, GfxFont* pFont, GfxState* state ) const;
        void writeFontFile( GfxFont* gfxFont ) const;
        void printPath( GfxPath* pPath ) const;

    public:
        explicit PDFOutDev( PDFDoc* pDoc );
        ~PDFOutDev();

        //----- get info about output device

        // Does this device use upside-down coordinates?
        // (Upside-down means (0,0) is the top left corner of the page.)
        virtual GBool upsideDown() SAL_OVERRIDE { return gTrue; }

        // Does this device use drawChar() or drawString()?
        virtual GBool useDrawChar() SAL_OVERRIDE { return gTrue; }

        // Does this device use beginType3Char/endType3Char?  Otherwise,
        // text in Type 3 fonts will be drawn with drawChar/drawString.
        virtual GBool interpretType3Chars() SAL_OVERRIDE { return gFalse; }

        // Does this device need non-text content?
        virtual GBool needNonText() SAL_OVERRIDE { return gTrue; }

        //----- initialization and control

        // Set default transform matrix.
        virtual void setDefaultCTM(double *ctm) SAL_OVERRIDE;

        // Start a page.
        virtual void startPage(int pageNum, GfxState *state
#if POPPLER_CHECK_VERSION(0, 23, 0) || POPPLER_CHECK_VERSION(0, 24, 0)
                               , XRef *xref
#endif
        ) SAL_OVERRIDE;

        // End a page.
        virtual void endPage() SAL_OVERRIDE;

        //----- link borders
	#if POPPLER_CHECK_VERSION(0, 19, 0)
        virtual void processLink(AnnotLink *link) SAL_OVERRIDE;
    #elif POPPLER_CHECK_VERSION(0, 17, 0)
        virtual void processLink(AnnotLink *link, Catalog *catalog) SAL_OVERRIDE;
    #else
        virtual void processLink(Link *link, Catalog *catalog) SAL_OVERRIDE;
    #endif

        //----- save/restore graphics state
        virtual void saveState(GfxState *state) SAL_OVERRIDE;
        virtual void restoreState(GfxState *state) SAL_OVERRIDE;

        //----- update graphics state
        virtual void updateCTM(GfxState *state, double m11, double m12,
                               double m21, double m22, double m31, double m32) SAL_OVERRIDE;
        virtual void updateLineDash(GfxState *state) SAL_OVERRIDE;
        virtual void updateFlatness(GfxState *state) SAL_OVERRIDE;
        virtual void updateLineJoin(GfxState *state) SAL_OVERRIDE;
        virtual void updateLineCap(GfxState *state) SAL_OVERRIDE;
        virtual void updateMiterLimit(GfxState *state) SAL_OVERRIDE;
        virtual void updateLineWidth(GfxState *state) SAL_OVERRIDE;
        virtual void updateFillColor(GfxState *state) SAL_OVERRIDE;
        virtual void updateStrokeColor(GfxState *state) SAL_OVERRIDE;
        virtual void updateFillOpacity(GfxState *state) SAL_OVERRIDE;
        virtual void updateStrokeOpacity(GfxState *state) SAL_OVERRIDE;
        virtual void updateBlendMode(GfxState *state) SAL_OVERRIDE;

        //----- update text state
        virtual void updateFont(GfxState *state) SAL_OVERRIDE;
        virtual void updateRender(GfxState *state) SAL_OVERRIDE;

        //----- path painting
        virtual void stroke(GfxState *state) SAL_OVERRIDE;
        virtual void fill(GfxState *state) SAL_OVERRIDE;
        virtual void eoFill(GfxState *state) SAL_OVERRIDE;

        //----- path clipping
        virtual void clip(GfxState *state) SAL_OVERRIDE;
        virtual void eoClip(GfxState *state) SAL_OVERRIDE;

        //----- text drawing
        virtual void drawChar(GfxState *state, double x, double y,
                              double dx, double dy,
                              double originX, double originY,
                              CharCode code, int nBytes, Unicode *u, int uLen) SAL_OVERRIDE;
        virtual void drawString(GfxState *state, GooString *s) SAL_OVERRIDE;
        virtual void endTextObject(GfxState *state) SAL_OVERRIDE;

        //----- image drawing
        virtual void drawImageMask(GfxState *state, Object *ref, Stream *str,
                                   int width, int height, GBool invert,
#if POPPLER_CHECK_VERSION(0, 12, 0)
                                   GBool interpolate,
#endif
                                   GBool inlineImg) SAL_OVERRIDE;
        virtual void drawImage(GfxState *state, Object *ref, Stream *str,
                               int width, int height, GfxImageColorMap *colorMap,
#if POPPLER_CHECK_VERSION(0, 12, 0)
                               GBool interpolate,
#endif
                               int *maskColors, GBool inlineImg) SAL_OVERRIDE;
        virtual void drawMaskedImage(GfxState *state, Object *ref, Stream *str,
                                     int width, int height,
                                     GfxImageColorMap *colorMap,
#if POPPLER_CHECK_VERSION(0, 12, 0)
                                     GBool interpolate,
#endif
                                     Stream *maskStr, int maskWidth, int maskHeight,
                                     GBool maskInvert
#if POPPLER_CHECK_VERSION(0, 12, 0)
                                     , GBool maskInterpolate
#endif
                                    ) SAL_OVERRIDE;
        virtual void drawSoftMaskedImage(GfxState *state, Object *ref, Stream *str,
                                         int width, int height,
                                         GfxImageColorMap *colorMap,
#if POPPLER_CHECK_VERSION(0, 12, 0)
                                         GBool interpolate,
#endif
                                         Stream *maskStr,
                                         int maskWidth, int maskHeight,
                                         GfxImageColorMap *maskColorMap
#if POPPLER_CHECK_VERSION(0, 12, 0)
                                         , GBool maskInterpolate
#endif
                                        ) SAL_OVERRIDE;

        void setPageNum( int nNumPages );
    };
}

extern FILE* g_binary_out;

// note: if you ever hcange Output_t, please keep in mind that the current code
// relies on it being of 8 bit size
typedef Guchar Output_t;
typedef std::vector< Output_t > OutputBuffer;

#endif // INCLUDED_SDEXT_SOURCE_PDFIMPORT_XPDFWRAPPER_PDFIOUTDEV_GPL_HXX

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


<commit_before>/*
 * Copyright (c) 2012 Holger Schletz <holger.schletz@web.de>
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <QDebug>
#include <QFileInfo>
#include "adobereader.h"
#include "application.h"
#include "downloader.h"

AdobeReader::AdobeReader() :
    Package("Adobe Reader", "10.1.3")
{
}

void AdobeReader::build(NSIS *installer, Version version)
{
    isError = false;
    download(version);
    if (!isError) {
        // Compose options for msiexec command line
        QStringList msiOptions;
        if (getConfig("Suppress reboot", false).toBool()) {
            msiOptions << "REBOOT=ReallySuppress";
        }
        if (getConfig("Accept EULA", false).toBool()) {
            msiOptions << "EULA_ACCEPT=YES";
        }
        if (!getConfig("Desktop shortcut", true).toBool()) {
            msiOptions << "DISABLEDESKTOPSHORTCUT=1";
        }
        if (getConfig("Set default PDF viewer", false).toBool()) {
            msiOptions << "IW_DEFAULT_VERB=READ";
            msiOptions << "LEAVE_PDFOWNERSHIP=NO";
        } else {
            msiOptions << "LEAVE_PDFOWNERSHIP=YES";
        }
        if (!getConfig("Install synchronizer", true).toBool()) {
            msiOptions << "SYNCHRONIZER=NO";
        }
        if (!getConfig("Use automatic update", true).toBool()) {
            msiOptions << "DISABLE_ARM_SERVICE_INSTALL=1";
        }
        qDebug() << "MSI options:" << msiOptions;

        // Compose main installation routine
        Version msiVersion(version.truncate(2).pad(2));
        QString src(loadResource(":NSIS/AdobeReader/main.nsh"));
        src.replace("${VersionMajor}", msiVersion.part(1));
        src.replace("${VersionMinor}", msiVersion.part(2));
        src.replace("${MsiFile}", QFileInfo(msiFile).fileName());
        src.replace("${MsiOptions}", msiOptions.join(" "));

        // Compose patch installation if necessary
        QString header;
        if (!mspFiles.isEmpty()) {
            header = loadResource(":NSIS/AdobeReader/header.nsh");
            QPair<Version, QString> mspFile;
            foreach (mspFile, mspFiles) {
                src += loadResource(":NSIS/AdobeReader/installpatch.nsh")
                        .replace("${MspVersion}", mspFile.first)
                        .replace("${MspFile}", QFileInfo(mspFile.second).fileName())
                        ;
            }
        }

        // Add code to disable updater if requested
        if (!getConfig("Use automatic update", true).toBool()) {
            src += loadResource(":NSIS/AdobeReader/disableupdater.nsh");
        }

        installer->build(
                    objectName(),
                    getOutputFile(),
                    NSIS::Zlib,
                    300,
                    browsers() << "AcroRd32.exe",
                    tempFiles,
                    src,
                    header
                    );
    }
    cleanup();
}

void AdobeReader::download(Version version)
{
    // MSI version always has 2 parts (10.0, 10.1...)
    Version msiVersion;
    if (version.part(1).toInt() >= 11) {
        msiVersion = version.pad(2).pad(3, "00");
    } else {
        msiVersion = version.truncate(2).pad(2);
    }
    qDebug() << "MSI version" << msiVersion.toString();

    QString language(getConfig("Language", "en_US").toString());
    qDebug()<<"language:"<<language;

    // Download MSI file.
    QString msiUrl("http://ardownload.adobe.com/pub/adobe/reader/win/%1/%2/%4/AdbeRdr%3_%4.msi");
    msiFile = Downloader::get(
                msiUrl
                .arg(msiVersion.truncate(2).replace(2, "x"))
                .arg(msiVersion.pad(3))
                .arg(msiVersion.pad(3).stripDots())
                .arg(language),
                Application::getTmpDir()
                );
    if (msiFile.isEmpty()) {
        isError = true;
        return;
    }
    tempFiles << msiFile;

    // If version has 3 parts, download MSP file.
    if (version.numParts() < 3) {
        return;
    }
    QString mspUrl("http://ardownload.adobe.com/pub/adobe/reader/win/%1/%2/misc/AdbeRdrUpd%3.msp");
    QString mspFile = Downloader::get(
                    mspUrl
                    .arg(msiVersion.replace(2, "x"))
                    .arg(version)
                    .arg(version.stripDots()),
                    Application::getTmpDir()
                    );
    if (mspFile.isEmpty()) {
        isError = true;
    } else {
        // In the past, there have been releases where more than 1 MSP was
        // required for a fresh up-to-date installation. For this reason,
        // the patches are stored in a list.
        // The dependency tracking is not implemented yet (it will should it
        // ever become necessary again), but the rest of the code is already
        // prepared for multiple patches.
        mspFiles << qMakePair(version, mspFile);
        tempFiles << mspFile;
    }
}
<commit_msg>Fixed bugs in Adobe Reader download.<commit_after>/*
 * Copyright (c) 2012 Holger Schletz <holger.schletz@web.de>
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include <QDebug>
#include <QFileInfo>
#include "adobereader.h"
#include "application.h"
#include "downloader.h"

AdobeReader::AdobeReader() :
    Package("Adobe Reader", "10.1.3")
{
}

void AdobeReader::build(NSIS *installer, Version version)
{
    isError = false;
    download(version);
    if (!isError) {
        // Compose options for msiexec command line
        QStringList msiOptions;
        if (getConfig("Suppress reboot", false).toBool()) {
            msiOptions << "REBOOT=ReallySuppress";
        }
        if (getConfig("Accept EULA", false).toBool()) {
            msiOptions << "EULA_ACCEPT=YES";
        }
        if (!getConfig("Desktop shortcut", true).toBool()) {
            msiOptions << "DISABLEDESKTOPSHORTCUT=1";
        }
        if (getConfig("Set default PDF viewer", false).toBool()) {
            msiOptions << "IW_DEFAULT_VERB=READ";
            msiOptions << "LEAVE_PDFOWNERSHIP=NO";
        } else {
            msiOptions << "LEAVE_PDFOWNERSHIP=YES";
        }
        if (!getConfig("Install synchronizer", true).toBool()) {
            msiOptions << "SYNCHRONIZER=NO";
        }
        if (!getConfig("Use automatic update", true).toBool()) {
            msiOptions << "DISABLE_ARM_SERVICE_INSTALL=1";
        }
        qDebug() << "MSI options:" << msiOptions;

        // Compose main installation routine
        Version msiVersion(version.truncate(2).pad(2));
        QString src(loadResource(":NSIS/AdobeReader/main.nsh"));
        src.replace("${VersionMajor}", msiVersion.part(1));
        src.replace("${VersionMinor}", msiVersion.part(2));
        src.replace("${MsiFile}", QFileInfo(msiFile).fileName());
        src.replace("${MsiOptions}", msiOptions.join(" "));

        // Compose patch installation if necessary
        QString header;
        if (!mspFiles.isEmpty()) {
            header = loadResource(":NSIS/AdobeReader/header.nsh");
            QPair<Version, QString> mspFile;
            foreach (mspFile, mspFiles) {
                src += loadResource(":NSIS/AdobeReader/installpatch.nsh")
                        .replace("${MspVersion}", mspFile.first)
                        .replace("${MspFile}", QFileInfo(mspFile.second).fileName())
                        ;
            }
        }

        // Add code to disable updater if requested
        if (!getConfig("Use automatic update", true).toBool()) {
            src += loadResource(":NSIS/AdobeReader/disableupdater.nsh");
        }

        installer->build(
                    objectName(),
                    getOutputFile(),
                    NSIS::Zlib,
                    300,
                    browsers() << "AcroRd32.exe",
                    tempFiles,
                    src,
                    header
                    );
    }
    cleanup();
}

void AdobeReader::download(Version version)
{
    // MSI version always has 2 parts (10.0, 10.1...)
    Version msiVersion;
    if (version.part(1).toInt() >= 11) {
        msiVersion = version.truncate(2).pad(3, "00");
    } else {
        msiVersion = version.truncate(2).pad(3);
    }
    qDebug() << "MSI version" << msiVersion.toString();

    QString language(getConfig("Language", "en_US").toString());
    qDebug()<<"language:"<<language;

    // Download MSI file.
    QString msiUrl("http://ardownload.adobe.com/pub/adobe/reader/win/%1/%2/%4/AdbeRdr%3_%4.msi");
    msiFile = Downloader::get(
                msiUrl
                .arg(msiVersion.truncate(2).replace(2, "x"))
                .arg(msiVersion.pad(3))
                .arg(msiVersion.stripDots())
                .arg(language),
                Application::getTmpDir()
                );
    if (msiFile.isEmpty()) {
        isError = true;
        return;
    }
    tempFiles << msiFile;

    // If version has 3 parts, download MSP file.
    if (version.numParts() < 3) {
        return;
    }
    QString mspUrl("http://ardownload.adobe.com/pub/adobe/reader/win/%1/%2/misc/AdbeRdrUpd%3.msp");
    QString mspFile = Downloader::get(
                    mspUrl
                    .arg(msiVersion.truncate(2).replace(2, "x"))
                    .arg(version)
                    .arg(version.stripDots()),
                    Application::getTmpDir()
                    );
    if (mspFile.isEmpty()) {
        isError = true;
    } else {
        // In the past, there have been releases where more than 1 MSP was
        // required for a fresh up-to-date installation. For this reason,
        // the patches are stored in a list.
        // The dependency tracking is not implemented yet (it will should it
        // ever become necessary again), but the rest of the code is already
        // prepared for multiple patches.
        mspFiles << qMakePair(version, mspFile);
        tempFiles << mspFile;
    }
}
<|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2015 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY 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 <modules/cimg/cimgutils.h>
#include <inviwo/core/datastructures/image/layerramprecision.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/io/datawriter.h>
#include <algorithm>

#include <warn/push>
#include <warn/ignore/all>
#define cimg_verbosity 0 //Disable all cimg output
#define cimg_display 0 // Do not use any gui stuff
#include <modules/cimg/ext/cimg/CImg.h>
#include <warn/pop>

#include <warn/push>
#include <warn/ignore/switch-enum>
#include <warn/ignore/conversion>
#if (_MSC_VER)
#pragma warning(disable : 4146)
#pragma warning(disable : 4197)
#pragma warning(disable : 4297)
#pragma warning(disable : 4267)
#pragma warning(disable : 4293)
#endif

// Added in Cimg.h below struct type<float>...
/*#include <limits>
#include <half/half.hpp>

    template<> struct type < half_float::half > {
        static const char* string() { static const char *const s = "half"; return s; }
        static bool is_float() { return true; }
        static bool is_inf(const half_float::half val) {
#ifdef isinf
            return (bool)isinf(val);
#else
            return !is_nan(val) && (val<cimg::type<half_float::half>::min() ||
val>cimg::type<half_float::half>::max());
#endif
        }
        static bool is_nan(const half_float::half val) {
#ifdef isnan
            return (bool)isnan(val);
#else
            return !(val == val);
#endif
        }
        static half_float::half min() { return std::numeric_limits<half_float::half>::min(); }
        static half_float::half max() { return std::numeric_limits<half_float::half>::max(); }
        static half_float::half inf() { return (half_float::half)cimg::type<double>::inf(); }
        static half_float::half nan() { return (half_float::half)cimg::type<double>::nan(); }
        static half_float::half cut(const double val) { return val<(double)min() ? min() :
val>(double)max() ? max() : (half_float::half)val; }
        static const char* format() { return "%.16g"; }
        static double format(const half_float::half val) { return (double)val; }
    };
*/

using namespace cimg_library;

namespace inviwo {

std::unordered_map<std::string, DataFormatId> extToBaseTypeMap_ = {
    {"png", DataFormatId::UInt8}, {"jpg", DataFormatId::UInt8},   {"jpeg", DataFormatId::UInt8},
    {"bmp", DataFormatId::UInt8}, {"exr", DataFormatId::Float32}, {"hdr", DataFormatId::Float32}};

////////////////////// Templates ///////////////////////////////////////////////////

// Single channel images
template <typename T>
struct CImgToVoidConvert {
    static void* convert(void* dst, CImg<T>* img) {
        // Inviwo store pixels interleaved (RGBRGBRGB), CImg stores pixels in a planer format
        // (RRRRGGGGBBBB).
        // Permute from planer to interleaved format, does we need to specify cxyz as input instead
        // of xyzc
        if (img->spectrum() > 1) {
            img->permute_axes("cxyz");
        }

        if (!dst) {
            T* dstAlloc = new T[img->size()];
            dst = static_cast<void*>(dstAlloc);
        }
        const void* src = static_cast<const void*>(img->data());

        std::memcpy(dst, src, img->size() * sizeof(T));

        return dst;
    }
};

// Single channel images
template <typename T>
struct LayerToCImg {
    static std::unique_ptr<CImg<T>> convert(const LayerRAM* inputLayerRAM, bool permute = true) {
        // Single channel means we can do xyzc, as no permutation is needed
        auto img = util::make_unique<CImg<T>>(static_cast<const T*>(inputLayerRAM->getData()),
                                              inputLayerRAM->getDimensions().x,
                                              inputLayerRAM->getDimensions().y, 1, 1, false);

        return img;
    }
};

// Multiple channel images
template <typename T, template <typename, glm::precision> class G>
struct LayerToCImg<G<T, glm::defaultp>> {
    static std::unique_ptr<CImg<T>> convert(const LayerRAM* inputLayerRAM, bool permute = true) {
        auto dataFormat = inputLayerRAM->getDataFormat();
        auto typedDataPtr = static_cast<const G<T, glm::defaultp>*>(inputLayerRAM->getData());

        // Inviwo store pixels interleaved (RGBRGBRGB), CImg stores pixels in a planer format
        // (RRRRGGGGBBBB).
        // Permute from interleaved to planer format, does we need to specify yzcx as input instead
        // of cxyz
        auto img = util::make_unique<CImg<T>>(
            glm::value_ptr(*typedDataPtr), dataFormat->getComponents(),
            inputLayerRAM->getDimensions().x, inputLayerRAM->getDimensions().y, 1, false);

        if (permute) img->permute_axes("yzcx");

        return img;
    }
};

struct CImgNormalizedLayerDispatcher {
    using type = std::unique_ptr<std::vector<unsigned char>>;
    template <typename T>
    std::unique_ptr<std::vector<unsigned char>> dispatch(const LayerRAM* inputLayer) {
        auto img = LayerToCImg<typename T::type>::convert(inputLayer, false);

        CImg<unsigned char> normalizedImg = img->get_normalize(0, 255);
        normalizedImg.mirror('z');

        auto data = util::make_unique<std::vector<unsigned char>>(
            &normalizedImg[0], &normalizedImg[normalizedImg.size()]);

        return data;
    }
};

struct CImgLoadLayerDispatcher {
    using type = void*;
    template <typename T>
    void* dispatch(void* dst, const char* filePath, uvec2& dimensions, DataFormatId& formatId,
                   const DataFormatBase* dataFormat, bool rescaleToDim) {
        using P = typename T::primitive;

        CImg<P> img(filePath);
        size_t components = static_cast<size_t>(img.spectrum());

        if (rescaleToDim) {
            img.resize(dimensions.x, dimensions.y, -100, -100, 3);
        } else {
            dimensions = uvec2(img.width(), img.height());
        }

        auto loadedDataFormat = DataFormatBase::get(
            dataFormat->getNumericType(), components, sizeof(P) * 8);
        if (loadedDataFormat) {
            formatId = loadedDataFormat->getId();
        } else {
            throw Exception("CImgLoadLayerDispatcher, could not find proper data type");
        }

        // Image is up-side-down
        img.mirror('y');

        return CImgToVoidConvert<P>::convert(dst, &img);
    }
};

struct CImgSaveLayerDispatcher {
    using type = void;
    template <typename T>
    void dispatch(const char* filePath, const LayerRAM* inputLayer) {
        auto img = LayerToCImg<typename T::type>::convert(inputLayer);

        // Should rescale values based on output format i.e. PNG/JPG is 0-255, HDR different.
        const DataFormatBase* outFormat = DataFloat32::get();
        std::string fileExtension = filesystem::getFileExtension(filePath);
        if (extToBaseTypeMap_.find(fileExtension) != extToBaseTypeMap_.end()) {
            outFormat = DataFormatBase::get(extToBaseTypeMap_[fileExtension]);
        }

        // Image is up-side-down
        img->mirror('y');

        const DataFormatBase* inFormat = inputLayer->getDataFormat();
        double inMin = inFormat->getMin();
        double inMax = inFormat->getMax();
        double outMin = outFormat->getMin();
        double outMax = outFormat->getMax();

        // Special treatment for float data types:
        // For float input images, we assume that the range is [0,1] (which is the same as rendered
        // in a Canvas)
        // For float output images, we normalize to [0,1]
        // Note that no normalization is performed if both input and output are float images
        if (inFormat->getNumericType() == NumericType::Float) {
            inMin = 0.0;
            inMax = 1.0;
        }
        if (outFormat->getNumericType() == NumericType::Float) {
            outMin = 0.0;
            outMax = 1.0;
        }

        // The image values should be rescaled if the ranges of the input and output are different
        if (inMin != outMin || inMax != outMax) {
            typename T::primitive* data = img->data();
            double scale = (outMax - outMin) / (inMax - inMin);
            for (size_t i = 0; i < img->size(); i++) {
                auto dataValue = glm::clamp(static_cast<double>(data[i]), inMin, inMax);
                data[i] = static_cast<typename T::primitive>((dataValue - inMin) * scale + outMin);
            }
        }
        try {
            img->save(filePath);
        } catch (CImgIOException& e) {
            throw DataWriterException("Failed to save image to: " + std::string(filePath), IvwContext);
        }
    }
};

struct CImgRescaleLayerDispatcher {
    using type = void*;
    template <typename T>
    void* dispatch(const LayerRAM* inputLayerRAM, uvec2 dst_dim) {
        auto img = LayerToCImg<typename T::type>::convert(inputLayerRAM);

        img->resize(dst_dim.x, dst_dim.y, -100, -100, 3);

        return CImgToVoidConvert<typename T::primitive>::convert(nullptr, img.get());
    }
};

struct CImgLoadVolumeDispatcher {
    using type = void*;
    template <typename T>
    void* dispatch(void* dst, const char* filePath, size3_t& dimensions, DataFormatId& formatId,
                   const DataFormatBase* dataFormat) {
        CImg<typename T::primitive> img(filePath);

        size_t components = static_cast<size_t>(img.spectrum());
        dimensions = size3_t(img.width(), img.height(), img.depth());

        const DataFormatBase* loadedDataFormat = DataFormatBase::get(
            dataFormat->getNumericType(), components, sizeof(typename T::primitive) * 8);
        if (loadedDataFormat)
            formatId = loadedDataFormat->getId();
        else
            throw Exception("CImgLoadVolumeDispatcher, could not find proper data type");

        // Image is up-side-down
        img.mirror('y');

        return CImgToVoidConvert<typename T::primitive>::convert(dst, &img);
    }
};

////////////////////// CImgUtils ///////////////////////////////////////////////////

void* CImgUtils::loadLayerData(void* dst, const std::string& filePath, uvec2& dimensions,
                               DataFormatId& formatId, bool rescaleToDim) {
    std::string fileExtension = filesystem::getFileExtension(filePath);
    if (extToBaseTypeMap_.find(fileExtension) != extToBaseTypeMap_.end()) {
        formatId = extToBaseTypeMap_[fileExtension];
    } else {
        formatId = DataFormatId::Float32;
    }
    const DataFormatBase* dataFormat = DataFormatBase::get(formatId);

    CImgLoadLayerDispatcher disp;
    return dataFormat->dispatch(disp, dst, filePath.c_str(), dimensions, formatId, dataFormat,
                                rescaleToDim);
}

void* CImgUtils::loadVolumeData(void* dst, const std::string& filePath, size3_t& dimensions,
                                DataFormatId& formatId) {
    std::string fileExtension = filesystem::getFileExtension(filePath);
    if (extToBaseTypeMap_.find(fileExtension) != extToBaseTypeMap_.end()) {
        formatId = extToBaseTypeMap_[fileExtension];
    } else {
        formatId = DataFormatId::Float32;
    }
    const DataFormatBase* dataFormat = DataFormatBase::get(formatId);

    CImgLoadVolumeDispatcher disp;
    return dataFormat->dispatch(disp, dst, filePath.c_str(), dimensions, formatId, dataFormat);
}

void CImgUtils::saveLayer(const std::string& filePath, const Layer* inputLayer) {
    CImgSaveLayerDispatcher disp;
    const LayerRAM* inputLayerRam = inputLayer->getRepresentation<LayerRAM>();
    inputLayer->getDataFormat()->dispatch(disp, filePath.c_str(), inputLayerRam);
}

std::unique_ptr<std::vector<unsigned char>> CImgUtils::saveLayerToBuffer(std::string& fileType,
                                                                         const Layer* inputLayer) {
    const LayerRAM* inputLayerRam = inputLayer->getRepresentation<LayerRAM>();
    fileType = "raw";  // Can only produce raw output

    CImgNormalizedLayerDispatcher disp;
    return inputLayer->getDataFormat()->dispatch(disp, inputLayerRam);
}

void* CImgUtils::rescaleLayer(const Layer* inputLayer, uvec2 dst_dim) {
    const LayerRAM* layerRam = inputLayer->getRepresentation<LayerRAM>();
    return rescaleLayerRAM(layerRam, dst_dim);
}

void* CImgUtils::rescaleLayerRAM(const LayerRAM* srcLayerRam, uvec2 dst_dim) {
    CImgRescaleLayerDispatcher disp;
    return srcLayerRam->getDataFormat()->dispatch(disp, srcLayerRam, dst_dim);
}

}  // namespace

#include <warn/pop>
<commit_msg>CIMG: Use of lower case for file extensions, if loading an image with JPG as file extension it did not find a the default one (eg Float32) which produced incorrect results.<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2015 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY 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 <modules/cimg/cimgutils.h>
#include <inviwo/core/datastructures/image/layerramprecision.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/io/datawriter.h>
#include <algorithm>

#include <warn/push>
#include <warn/ignore/all>
#define cimg_verbosity 0 //Disable all cimg output
#define cimg_display 0 // Do not use any gui stuff
#include <modules/cimg/ext/cimg/CImg.h>
#include <warn/pop>

#include <warn/push>
#include <warn/ignore/switch-enum>
#include <warn/ignore/conversion>
#if (_MSC_VER)
#pragma warning(disable : 4146)
#pragma warning(disable : 4197)
#pragma warning(disable : 4297)
#pragma warning(disable : 4267)
#pragma warning(disable : 4293)
#endif

// Added in Cimg.h below struct type<float>...
/*#include <limits>
#include <half/half.hpp>

    template<> struct type < half_float::half > {
        static const char* string() { static const char *const s = "half"; return s; }
        static bool is_float() { return true; }
        static bool is_inf(const half_float::half val) {
#ifdef isinf
            return (bool)isinf(val);
#else
            return !is_nan(val) && (val<cimg::type<half_float::half>::min() ||
val>cimg::type<half_float::half>::max());
#endif
        }
        static bool is_nan(const half_float::half val) {
#ifdef isnan
            return (bool)isnan(val);
#else
            return !(val == val);
#endif
        }
        static half_float::half min() { return std::numeric_limits<half_float::half>::min(); }
        static half_float::half max() { return std::numeric_limits<half_float::half>::max(); }
        static half_float::half inf() { return (half_float::half)cimg::type<double>::inf(); }
        static half_float::half nan() { return (half_float::half)cimg::type<double>::nan(); }
        static half_float::half cut(const double val) { return val<(double)min() ? min() :
val>(double)max() ? max() : (half_float::half)val; }
        static const char* format() { return "%.16g"; }
        static double format(const half_float::half val) { return (double)val; }
    };
*/

using namespace cimg_library;

namespace inviwo {

std::unordered_map<std::string, DataFormatId> extToBaseTypeMap_ = {
    {"png", DataFormatId::UInt8}, {"jpg", DataFormatId::UInt8},   {"jpeg", DataFormatId::UInt8},
    {"bmp", DataFormatId::UInt8}, {"exr", DataFormatId::Float32}, {"hdr", DataFormatId::Float32}};

////////////////////// Templates ///////////////////////////////////////////////////

// Single channel images
template <typename T>
struct CImgToVoidConvert {
    static void* convert(void* dst, CImg<T>* img) {
        // Inviwo store pixels interleaved (RGBRGBRGB), CImg stores pixels in a planer format
        // (RRRRGGGGBBBB).
        // Permute from planer to interleaved format, does we need to specify cxyz as input instead
        // of xyzc
        if (img->spectrum() > 1) {
            img->permute_axes("cxyz");
        }

        if (!dst) {
            T* dstAlloc = new T[img->size()];
            dst = static_cast<void*>(dstAlloc);
        }
        const void* src = static_cast<const void*>(img->data());

        std::memcpy(dst, src, img->size() * sizeof(T));

        return dst;
    }
};

// Single channel images
template <typename T>
struct LayerToCImg {
    static std::unique_ptr<CImg<T>> convert(const LayerRAM* inputLayerRAM, bool permute = true) {
        // Single channel means we can do xyzc, as no permutation is needed
        auto img = util::make_unique<CImg<T>>(static_cast<const T*>(inputLayerRAM->getData()),
                                              inputLayerRAM->getDimensions().x,
                                              inputLayerRAM->getDimensions().y, 1, 1, false);

        return img;
    }
};

// Multiple channel images
template <typename T, template <typename, glm::precision> class G>
struct LayerToCImg<G<T, glm::defaultp>> {
    static std::unique_ptr<CImg<T>> convert(const LayerRAM* inputLayerRAM, bool permute = true) {
        auto dataFormat = inputLayerRAM->getDataFormat();
        auto typedDataPtr = static_cast<const G<T, glm::defaultp>*>(inputLayerRAM->getData());

        // Inviwo store pixels interleaved (RGBRGBRGB), CImg stores pixels in a planer format
        // (RRRRGGGGBBBB).
        // Permute from interleaved to planer format, does we need to specify yzcx as input instead
        // of cxyz
        auto img = util::make_unique<CImg<T>>(
            glm::value_ptr(*typedDataPtr), dataFormat->getComponents(),
            inputLayerRAM->getDimensions().x, inputLayerRAM->getDimensions().y, 1, false);

        if (permute) img->permute_axes("yzcx");

        return img;
    }
};

struct CImgNormalizedLayerDispatcher {
    using type = std::unique_ptr<std::vector<unsigned char>>;
    template <typename T>
    std::unique_ptr<std::vector<unsigned char>> dispatch(const LayerRAM* inputLayer) {
        auto img = LayerToCImg<typename T::type>::convert(inputLayer, false);

        CImg<unsigned char> normalizedImg = img->get_normalize(0, 255);
        normalizedImg.mirror('z');

        auto data = util::make_unique<std::vector<unsigned char>>(
            &normalizedImg[0], &normalizedImg[normalizedImg.size()]);

        return data;
    }
};

struct CImgLoadLayerDispatcher {
    using type = void*;
    template <typename T>
    void* dispatch(void* dst, const char* filePath, uvec2& dimensions, DataFormatId& formatId,
                   const DataFormatBase* dataFormat, bool rescaleToDim) {
        using P = typename T::primitive;

        CImg<P> img(filePath);
        size_t components = static_cast<size_t>(img.spectrum());

        if (rescaleToDim) {
            img.resize(dimensions.x, dimensions.y, -100, -100, 3);
        } else {
            dimensions = uvec2(img.width(), img.height());
        }

        auto loadedDataFormat = DataFormatBase::get(
            dataFormat->getNumericType(), components, sizeof(P) * 8);
        if (loadedDataFormat) {
            formatId = loadedDataFormat->getId();
        } else {
            throw Exception("CImgLoadLayerDispatcher, could not find proper data type");
        }

        // Image is up-side-down
        img.mirror('y');

        return CImgToVoidConvert<P>::convert(dst, &img);
    }
};

struct CImgSaveLayerDispatcher {
    using type = void;
    template <typename T>
    void dispatch(const char* filePath, const LayerRAM* inputLayer) {
        auto img = LayerToCImg<typename T::type>::convert(inputLayer);

        // Should rescale values based on output format i.e. PNG/JPG is 0-255, HDR different.
        const DataFormatBase* outFormat = DataFloat32::get();
        std::string fileExtension = toLower(filesystem::getFileExtension(filePath));
        if (extToBaseTypeMap_.find(fileExtension) != extToBaseTypeMap_.end()) {
            outFormat = DataFormatBase::get(extToBaseTypeMap_[fileExtension]);
        }

        // Image is up-side-down
        img->mirror('y');

        const DataFormatBase* inFormat = inputLayer->getDataFormat();
        double inMin = inFormat->getMin();
        double inMax = inFormat->getMax();
        double outMin = outFormat->getMin();
        double outMax = outFormat->getMax();

        // Special treatment for float data types:
        // For float input images, we assume that the range is [0,1] (which is the same as rendered
        // in a Canvas)
        // For float output images, we normalize to [0,1]
        // Note that no normalization is performed if both input and output are float images
        if (inFormat->getNumericType() == NumericType::Float) {
            inMin = 0.0;
            inMax = 1.0;
        }
        if (outFormat->getNumericType() == NumericType::Float) {
            outMin = 0.0;
            outMax = 1.0;
        }

        // The image values should be rescaled if the ranges of the input and output are different
        if (inMin != outMin || inMax != outMax) {
            typename T::primitive* data = img->data();
            double scale = (outMax - outMin) / (inMax - inMin);
            for (size_t i = 0; i < img->size(); i++) {
                auto dataValue = glm::clamp(static_cast<double>(data[i]), inMin, inMax);
                data[i] = static_cast<typename T::primitive>((dataValue - inMin) * scale + outMin);
            }
        }
        try {
            img->save(filePath);
        } catch (CImgIOException& e) {
            throw DataWriterException("Failed to save image to: " + std::string(filePath), IvwContext);
        }
    }
};

struct CImgRescaleLayerDispatcher {
    using type = void*;
    template <typename T>
    void* dispatch(const LayerRAM* inputLayerRAM, uvec2 dst_dim) {
        auto img = LayerToCImg<typename T::type>::convert(inputLayerRAM);

        img->resize(dst_dim.x, dst_dim.y, -100, -100, 3);

        return CImgToVoidConvert<typename T::primitive>::convert(nullptr, img.get());
    }
};

struct CImgLoadVolumeDispatcher {
    using type = void*;
    template <typename T>
    void* dispatch(void* dst, const char* filePath, size3_t& dimensions, DataFormatId& formatId,
                   const DataFormatBase* dataFormat) {
        CImg<typename T::primitive> img(filePath);

        size_t components = static_cast<size_t>(img.spectrum());
        dimensions = size3_t(img.width(), img.height(), img.depth());

        const DataFormatBase* loadedDataFormat = DataFormatBase::get(
            dataFormat->getNumericType(), components, sizeof(typename T::primitive) * 8);
        if (loadedDataFormat)
            formatId = loadedDataFormat->getId();
        else
            throw Exception("CImgLoadVolumeDispatcher, could not find proper data type");

        // Image is up-side-down
        img.mirror('y');

        return CImgToVoidConvert<typename T::primitive>::convert(dst, &img);
    }
};

////////////////////// CImgUtils ///////////////////////////////////////////////////

void* CImgUtils::loadLayerData(void* dst, const std::string& filePath, uvec2& dimensions,
    DataFormatId& formatId, bool rescaleToDim) {
    std::string fileExtension = toLower(filesystem::getFileExtension(filePath));
    if (extToBaseTypeMap_.find(fileExtension) != extToBaseTypeMap_.end()) {
        formatId = extToBaseTypeMap_[fileExtension];
    } else {
        formatId = DataFormatId::Float32;
    }
    const DataFormatBase* dataFormat = DataFormatBase::get(formatId);

    CImgLoadLayerDispatcher disp;
    return dataFormat->dispatch(disp, dst, filePath.c_str(), dimensions, formatId, dataFormat,
                                rescaleToDim);
}

void* CImgUtils::loadVolumeData(void* dst, const std::string& filePath, size3_t& dimensions,
    DataFormatId& formatId) {
    std::string fileExtension = toLower(filesystem::getFileExtension(filePath));
    if (extToBaseTypeMap_.find(fileExtension) != extToBaseTypeMap_.end()) {
        formatId = extToBaseTypeMap_[fileExtension];
    } else {
        formatId = DataFormatId::Float32;
    }
    const DataFormatBase* dataFormat = DataFormatBase::get(formatId);

    CImgLoadVolumeDispatcher disp;
    return dataFormat->dispatch(disp, dst, filePath.c_str(), dimensions, formatId, dataFormat);
}

void CImgUtils::saveLayer(const std::string& filePath, const Layer* inputLayer) {
    CImgSaveLayerDispatcher disp;
    const LayerRAM* inputLayerRam = inputLayer->getRepresentation<LayerRAM>();
    inputLayer->getDataFormat()->dispatch(disp, filePath.c_str(), inputLayerRam);
}

std::unique_ptr<std::vector<unsigned char>> CImgUtils::saveLayerToBuffer(std::string& fileType,
                                                                         const Layer* inputLayer) {
    const LayerRAM* inputLayerRam = inputLayer->getRepresentation<LayerRAM>();
    fileType = "raw";  // Can only produce raw output

    CImgNormalizedLayerDispatcher disp;
    return inputLayer->getDataFormat()->dispatch(disp, inputLayerRam);
}

void* CImgUtils::rescaleLayer(const Layer* inputLayer, uvec2 dst_dim) {
    const LayerRAM* layerRam = inputLayer->getRepresentation<LayerRAM>();
    return rescaleLayerRAM(layerRam, dst_dim);
}

void* CImgUtils::rescaleLayerRAM(const LayerRAM* srcLayerRam, uvec2 dst_dim) {
    CImgRescaleLayerDispatcher disp;
    return srcLayerRam->getDataFormat()->dispatch(disp, srcLayerRam, dst_dim);
}

}  // namespace

#include <warn/pop>
<|endoftext|>


<commit_before>#include "StdAfx.h"
#include "ByteStream.h"
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009 Klaus Post

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

    http://www.klauspost.com
*/

namespace RawSpeed {

ByteStream::ByteStream(const uchar8* _buffer, uint32 _size) :
    buffer(_buffer), size(_size), off(0) {

}

ByteStream::ByteStream(const ByteStream *b) :
    buffer(b->buffer), size(b->size), off(b->off) {

}

ByteStream::~ByteStream(void) {

}

uint32 ByteStream::peekByte() {
  return buffer[off];
}

void ByteStream::skipBytes(uint32 nbytes) {
  off += nbytes;
  if (off > size)
    throw IOException("Skipped out of buffer");
}

uchar8 ByteStream::getByte() {
  if (off >= size)
    throw IOException("getByte:Out of buffer read");
  return buffer[off++];
}

ushort16 ByteStream::getShort() {
  if (off + 1 >= size)
    throw IOException("getShort: Out of buffer read");
  return *(ushort16*)&buffer[off+=4];
  uint32 a = buffer[off++];
  uint32 b = buffer[off++];
  // !!! ENDIAN SWAP
  return (a << 8) | b;
}

int ByteStream::getInt() {
  if (off + 4 >= size)
    throw IOException("getInt:Out of buffer read");
  return *(int*)&buffer[off+=4];
}

void ByteStream::setAbsoluteOffset(uint32 offset) {
  if (offset >= size)
    throw IOException("setAbsoluteOffset:Offset set out of buffer");
  off = offset;
}

void ByteStream::skipToMarker() {
  int c = 0;
  while (!(buffer[off] == 0xFF && buffer[off+1] != 0)) {
    off++;
    c++;
    if (off >= size)
      throw IOException("No marker found inside rest of buffer");
  }
//  _RPT1(0,"Skipped %u bytes.\n", c);
}

} // namespace RawSpeed
<commit_msg>Fix byte stream in host endianness.<commit_after>#include "StdAfx.h"
#include "ByteStream.h"
/*
    RawSpeed - RAW file decoder.

    Copyright (C) 2009 Klaus Post

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

    http://www.klauspost.com
*/

namespace RawSpeed {

ByteStream::ByteStream(const uchar8* _buffer, uint32 _size) :
    buffer(_buffer), size(_size), off(0) {

}

ByteStream::ByteStream(const ByteStream *b) :
    buffer(b->buffer), size(b->size), off(b->off) {

}

ByteStream::~ByteStream(void) {

}

uint32 ByteStream::peekByte() {
  return buffer[off];
}

void ByteStream::skipBytes(uint32 nbytes) {
  off += nbytes;
  if (off > size)
    throw IOException("Skipped out of buffer");
}

uchar8 ByteStream::getByte() {
  if (off >= size)
    throw IOException("getByte:Out of buffer read");
  off++;
  return buffer[off-1];
}

ushort16 ByteStream::getShort() {
  if (off + 1 >= size)
    throw IOException("getShort: Out of buffer read");
  off +=2;
  return *(ushort16*)&buffer[off-2];
}

int ByteStream::getInt() {
  if (off + 4 >= size)
    throw IOException("getInt:Out of buffer read");
  off+=4;
  return *(int*)&buffer[off-4];
}

void ByteStream::setAbsoluteOffset(uint32 offset) {
  if (offset >= size)
    throw IOException("setAbsoluteOffset:Offset set out of buffer");
  off = offset;
}

void ByteStream::skipToMarker() {
  int c = 0;
  while (!(buffer[off] == 0xFF && buffer[off+1] != 0)) {
    off++;
    c++;
    if (off >= size)
      throw IOException("No marker found inside rest of buffer");
  }
//  _RPT1(0,"Skipped %u bytes.\n", c);
}

} // namespace RawSpeed
<|endoftext|>


<commit_before>/**
 * Exercise 5 : Read in a gph-file, computes the longest (with respect to the edge weights) shortest path from any vertex to the vertex with index 1.
 *
 * @author FirstSanny
 */

#include <iostream>
#include <fstream>
#include <utility>
#include <vector>
#include <climits>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/graph/named_function_params.hpp>

namespace {

const char* FILEEND = ".gph";

}

// declaring print
using std::cout;
using std::endl;
using std::cerr;
using std::string;

typedef boost::adjacency_list<boost::listS, boost::vecS,
  boost::undirectedS, boost::no_property,
  boost::property<boost::edge_weight_t, int>> graph;
typedef boost::graph_traits < graph >::vertex_descriptor vertex_descriptor;

int readFirstLine(int edgeCount, string& line) {

	return edgeCount;
}

/** add's fileending and opens the via ifstream */
std::ifstream openFile(char* argv[]) {
	string filename = argv[1];
	filename += FILEEND;
	cout << "Going to parse the file " << filename << endl;
	std::ifstream fileStream;
	fileStream.open(filename.c_str(), std::ios::in);
	return fileStream;
}

/** Creates a Map for boost, cause a normal vector.begin() doesn't work */
boost::iterator_property_map<__gnu_cxx:: __normal_iterator <int*,std::vector<int,std::allocator<int> > > ,boost::vec_adj_list_vertex_id_map<boost::no_property,unsigned long int> ,int,int&> getBoostMap(std::vector<int> directions, graph& g)
{
	return boost::make_iterator_property_map(directions.begin(), boost::get(boost::vertex_index, g));
}

/** Reading in a Graphfile, computes the longest shortest path */
int main(int argn, char *argv[]) {

	if (argn <= 1) {
		cerr << "ERROR : There was no filename" << endl;
		return 1;
	}

	std::ifstream fileStream = openFile(argv);

	if ( (fileStream.rdstate()) != 0 ){
		std::perror("ERROR : Encoutered Problem opening file");
		return 1;
	}

	string line;

	unsigned int edgeCount;
	unsigned int vertexCount;
	if(std::getline(fileStream, line)){
		sscanf(line.c_str(), "%d %d", &vertexCount, &edgeCount);
		cout << "Vertexcount: " << vertexCount << endl;
		cout << "Edgecount: " << edgeCount << endl;
		line.clear();
	} else {
		cerr << "ERROR : File was empty" << endl;
		return 1;
	}

	std::vector<std::pair<int, int>> edges;
	std::vector<int> weights;

	cout << "Reading edges..." << endl;
	while (getline(fileStream, line)) {
		int start;
		int end;
		int weight;
		int count = sscanf(line.c_str(), "%d %d %d", &start, &end, &weight);
		if (count != 3) {
			line.clear();
			continue;
		}
		edges.push_back(std::make_pair(start, end));
		weights.push_back(weight);
		line.clear();
	}

	cout << "Creating graph..." << endl;
	graph g{edges.begin(), edges.end(), weights.begin(), vertexCount};

	std::vector<vertex_descriptor> directions(vertexCount);
	std::vector<int> weightMap(vertexCount);

	cout << "Compute shortest paths via Dijkstra..." << endl;
	boost::dijkstra_shortest_paths(g, 1,
		boost::predecessor_map(//
				boost::make_iterator_property_map(directions.begin(), boost::get(boost::vertex_index, g))) //
			.distance_map(//
				boost::make_iterator_property_map(weightMap.begin(), boost::get(boost::vertex_index, g))));

	cout << "Search longest shortest path..." << endl;
	int vertex = 1;
	int distance = 0;
	for(unsigned int i=2; i<=vertexCount; i++){
		if(weightMap[i]>distance){
			distance = weightMap[i];
			vertex = i;
		}
	}

	cout << "RESULT VERTEX " << vertex << '\n';
	cout << "RESULT DIST " << distance << '\n';

	return 0;
}
<commit_msg>ex6 via boost libary<commit_after>/**
 * Exercise 5 : Read in a gph-file, computes the longest (with respect to the edge weights) shortest path from any vertex to the vertex with index 1.
 *
 * @author FirstSanny
 */

#include <iostream>
#include <fstream>
#include <utility>
#include <vector>
#include <climits>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>
#include <boost/graph/named_function_params.hpp>
#include <boost/timer/timer.hpp>

namespace {

const char* FILEEND = ".gph";

}

// declaring print
using std::cout;
using std::endl;
using std::cerr;
using std::string;

typedef boost::adjacency_list<boost::listS, boost::vecS,
  boost::undirectedS, boost::no_property,
  boost::property<boost::edge_weight_t, int>> graph;
typedef boost::graph_traits < graph >::vertex_descriptor vertex_descriptor;

int readFirstLine(int edgeCount, string& line) {

	return edgeCount;
}

/** add's fileending and opens the via ifstream */
std::ifstream openFile(char* argv[]) {
	string filename = argv[1];
	filename += FILEEND;
	cout << "Going to parse the file " << filename << endl;
	std::ifstream fileStream;
	fileStream.open(filename.c_str(), std::ios::in);
	return fileStream;
}

/** Reading in a Graphfile, computes the longest shortest path */
int main(int argn, char *argv[]) {
	boost::timer::auto_cpu_timer t;
	if (argn <= 1) {
		cerr << "ERROR : There was no filename" << endl;
		return 1;
	}

	std::ifstream fileStream = openFile(argv);

	if ( (fileStream.rdstate()) != 0 ){
		std::perror("ERROR : Encoutered Problem opening file");
		return 1;
	}

	string line;

	unsigned int edgeCount;
	unsigned int vertexCount;

	if(std::getline(fileStream, line)){
		sscanf(line.c_str(), "%d %d", &vertexCount, &edgeCount);
		cout << "Vertexcount: " << vertexCount << endl;
		cout << "Edgecount: " << edgeCount << endl;
		line.clear();
		vertexCount++;
	} else {
		cerr << "ERROR : File was empty" << endl;
		return 1;
	}

	std::vector<std::pair<int, int>> edges(edgeCount);
	std::vector<int> weights(edgeCount);

	cout << "Reading edges..." << endl;
	while (getline(fileStream, line)) {
		int start;
		int end;
		int weight;
		int count = sscanf(line.c_str(), "%d %d %d", &start, &end, &weight);
		if (count != 3) {
			line.clear();
			continue;
		}
		edges.push_back(std::make_pair(start, end));
		weights.push_back(weight);
		line.clear();
	}

	cout << "Creating graph..." << endl;
	graph g{edges.begin(), edges.end(), weights.begin(), vertexCount};

	std::vector<vertex_descriptor> directions(vertexCount);
	std::vector<int> weightMap(vertexCount);

	cout << "Compute shortest paths via Dijkstra..." << endl;
	boost::dijkstra_shortest_paths(g, 1,
		boost::predecessor_map(//
				boost::make_iterator_property_map(directions.begin(), boost::get(boost::vertex_index, g))) //
			.distance_map(//
				boost::make_iterator_property_map(weightMap.begin(), boost::get(boost::vertex_index, g))));

	cout << "Search longest shortest path..." << endl;
	int vertex = 1;
	int distance = 0;
	for(unsigned int i=2; i<=vertexCount; i++){
		if(weightMap[i]>distance){
			distance = weightMap[i];
			vertex = i;
		}
	}

	cout << "RESULT VERTEX " << vertex << '\n';
	cout << "RESULT DIST " << distance << '\n';

	return 0;
}
<|endoftext|>


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

//-------------------------------------------------------
//          Implementation of the TPC transformation class
//
//   Origin: Marian Ivanov   Marian.Ivanov@cern.ch
//           Magnus Mager
//
//   Class for tranformation of the coordinate frame
//   Transformation
//    local coordinate frame (sector, padrow, pad, timebine) ==>
//    rotated global (tracking) cooridnate frame (sector, lx,ly,lz)
//
//    Unisochronity  - (substract time0 - pad by pad)
//    Drift velocity - Currently common drift velocity - functionality of AliTPCParam
//    ExB effect     -
//
//    Time of flight correction -
//                   - Depends on the vertex position
//                   - by default
//
//    Usage:
//          AliTPCclustererMI::AddCluster
//          AliTPCtrackerMI::Transform
//
//-------------------------------------------------------

/* To test it:
   cdb=AliCDBManager::Instance()
   cdb->SetDefaultStorage("local:///u/mmager/mycalib1")
   c=AliTPCcalibDB::Instance()
   c->SetRun(0)
   Double_t x[]={1.0,2.0,3.0}
   Int_t i[]={4}
   AliTPCTransform trafo
   trafo.Transform(x,i,0,1)
 */

/* $Id$ */

#include "AliTPCROC.h"
#include "AliTPCCalPad.h"
#include "AliTPCCalROC.h"
#include "AliTPCcalibDB.h"
#include "AliTPCParam.h"
#include "TMath.h"
#include "AliLog.h"
#include "AliTPCExB.h"
#include "TGeoMatrix.h"
#include "AliTPCTransform.h"

ClassImp(AliTPCTransform)

  AliTPCTransform::AliTPCTransform():
    AliTransform()
{
  //
  // Speed it up a bit!
  //
  for (Int_t i=0;i<18;++i) {
    Double_t alpha=TMath::DegToRad()*(10.+20.*(i%18));
    fSins[i]=TMath::Sin(alpha);
    fCoss[i]=TMath::Cos(alpha);
  }
  fPrimVtx[0]=0;
  fPrimVtx[1]=0;
  fPrimVtx[2]=0;
}

AliTPCTransform::~AliTPCTransform() {
  //
  // Destructor
  //
}

void AliTPCTransform::SetPrimVertex(Double_t *vtx){
  //
  //
  //
  fPrimVtx[0]=vtx[0];
  fPrimVtx[1]=vtx[1];
  fPrimVtx[2]=vtx[2];
}

void AliTPCTransform::Transform(Double_t *x,Int_t *i,UInt_t /*time*/,
				Int_t /*coordinateType*/) {
  // input: x[0] - pad row
  //        x[1] - pad
  //        x[2] - time in us
  //        i[0] - sector
  // output: x[0] - x (all in the rotated global coordinate frame)
  //         x[1] - y
  //         x[2] - z
  //
  //  primvtx     - position of the primary vertex
  //                used for the TOF correction
  //                TOF of particle calculated assuming the speed-of-light and
  //                line approximation
  //

  Int_t row=TMath::Nint(x[0]);
  Int_t pad=TMath::Nint(x[1]);
  Int_t sector=i[0];
  AliTPCcalibDB*  calib=AliTPCcalibDB::Instance();
  //
  AliTPCCalPad * time0TPC = calib->GetPadTime0();
  AliTPCParam  * param    = calib->GetParameters();
  if (!time0TPC){
    AliFatal("Time unisochronity missing");
  }

  if (!param){
    AliFatal("Parameters missing");
  }

  Double_t xx[3];
  //  Apply Time0 correction - Pad by pad fluctuation
  //
  x[2]-=time0TPC->GetCalROC(sector)->GetValue(row,pad);
  //
  // Tranform from pad - time coordinate system to the rotated global (tracking) system
  //
  Local2RotatedGlobal(sector,x);
  //
  //
  //
  // Alignment
  //TODO:  calib->GetParameters()->GetClusterMatrix(sector)->LocalToMaster(x,xx);
  RotatedGlobal2Global(sector,x);
  //
  //
  // ExB correction
  //
  calib->GetExB()->Correct(x,xx);
  //
  // Time of flight correction
  //
  const Int_t kNIS=param->GetNInnerSector(), kNOS=param->GetNOuterSector();
  Float_t sign=1;
  if (sector < kNIS) {
    sign = (sector < kNIS/2) ? 1 : -1;
  } else {
    sign = ((sector-kNIS) < kNOS/2) ? 1 : -1;
  }
  Float_t deltaDr =0;
  Float_t dist=0;
  dist+=(fPrimVtx[0]-x[0])*(fPrimVtx[0]-x[0]);
  dist+=(fPrimVtx[1]-x[1])*(fPrimVtx[1]-x[1]);
  dist+=(fPrimVtx[0]-x[2])*(fPrimVtx[0]-x[2]);
  dist = TMath::Sqrt(dist);
  // drift length correction because of TOF
  // the drift velocity is in cm/s therefore multiplication by 0.01
  deltaDr = (dist*(0.01*param->GetDriftV()))/TMath::C();
  xx[2]+=sign*deltaDr;
  //
  Global2RotatedGlobal(sector,xx);
  //
  x[0]=xx[0];x[1]=xx[1];x[2]=xx[2];
}

void AliTPCTransform::Local2RotatedGlobal(Int_t sector, Double_t *x) const {
  //
  //
  // Tranform coordinate from
  // row, pad, time to x,y,z
  //
  // Drift Velocity
  // Current implementation - common drift velocity - for full chamber
  // TODO: use a map or parametrisation!
  //
  //
  //
  AliTPCcalibDB*  calib=AliTPCcalibDB::Instance();
  AliTPCParam  * param    = calib->GetParameters();
  if (!param){
    AliFatal("Parameters missing");
  }
  Int_t row=TMath::Nint(x[0]);
  //  Int_t pad=TMath::Nint(x[1]);
  //
  const Int_t kNIS=param->GetNInnerSector(), kNOS=param->GetNOuterSector();
  Double_t sign = 1.;
  Double_t zwidth    = param->GetZWidth();
  Double_t padWidth  = 0;
  Double_t padLength = 0;
  Double_t    maxPad    = 0;
  //
  if (sector < kNIS) {
    maxPad = param->GetNPadsLow(row);
    sign = (sector < kNIS/2) ? 1 : -1;
    padLength = param->GetPadPitchLength(sector,row);
    padWidth = param->GetPadPitchWidth(sector);
  } else {
    maxPad = param->GetNPadsUp(row);
    sign = ((sector-kNIS) < kNOS/2) ? 1 : -1;
    padLength = param->GetPadPitchLength(sector,row);
    padWidth  = param->GetPadPitchWidth(sector);
  }
  //
  // X coordinate
  x[0] = param->GetPadRowRadii(sector,row);  // padrow X position - ideal
  //
  // Y coordinate
  //
  x[1]=(x[1]-0.5*maxPad)*padWidth;
  // pads are mirrorred on C-side
  if (sector%36>17){
    x[1]*=-1;
  }

  //

  //
  // Z coordinate
  //
  x[2]*= zwidth;  // tranform time bin to the distance to the ROC
  x[2]-= 3.*param->GetZSigma() + param->GetNTBinsL1()*zwidth;
  // subtract the time offsets
  x[2] = sign*( param->GetZLength(sector) - x[2]);
}

void AliTPCTransform::RotatedGlobal2Global(Int_t sector,Double_t *x) const {
  //
  // transform possition rotated global to the global
  //
  Double_t cos,sin;
  GetCosAndSin(sector,cos,sin);
  Double_t tmp=x[0];
  x[0]= cos*tmp-sin*x[1];
  x[1]=+sin*tmp+cos*x[1];
}

void AliTPCTransform::Global2RotatedGlobal(Int_t sector,Double_t *x) const {
  //
  // tranform possition Global2RotatedGlobal
  //
  Double_t cos,sin;
  GetCosAndSin(sector,cos,sin);
  Double_t tmp=x[0];
  x[0]= cos*tmp+sin*x[1];
  x[1]= -sin*tmp+cos*x[1];
}

void AliTPCTransform::GetCosAndSin(Int_t sector,Double_t &cos,
					  Double_t &sin) const {
  cos=fCoss[sector%18];
  sin=fSins[sector%18];
}

<commit_msg>Bug fix - Use the proper z vertex for TOF correction -  dist+=(fPrimVtx[0]-x[2])*(fPrimVtx[0]-x[2]); +  dist+=(fPrimVtx[2]-x[2])*(fPrimVtx[2]-x[2]);<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

//-------------------------------------------------------
//          Implementation of the TPC transformation class
//
//   Origin: Marian Ivanov   Marian.Ivanov@cern.ch
//           Magnus Mager
//
//   Class for tranformation of the coordinate frame
//   Transformation
//    local coordinate frame (sector, padrow, pad, timebine) ==>
//    rotated global (tracking) cooridnate frame (sector, lx,ly,lz)
//
//    Unisochronity  - (substract time0 - pad by pad)
//    Drift velocity - Currently common drift velocity - functionality of AliTPCParam
//    ExB effect     -
//
//    Time of flight correction -
//                   - Depends on the vertex position
//                   - by default
//
//    Usage:
//          AliTPCclustererMI::AddCluster
//          AliTPCtrackerMI::Transform
//
//-------------------------------------------------------

/* To test it:
   cdb=AliCDBManager::Instance()
   cdb->SetDefaultStorage("local:///u/mmager/mycalib1")
   c=AliTPCcalibDB::Instance()
   c->SetRun(0)
   Double_t x[]={1.0,2.0,3.0}
   Int_t i[]={4}
   AliTPCTransform trafo
   trafo.Transform(x,i,0,1)
 */

/* $Id$ */

#include "AliTPCROC.h"
#include "AliTPCCalPad.h"
#include "AliTPCCalROC.h"
#include "AliTPCcalibDB.h"
#include "AliTPCParam.h"
#include "TMath.h"
#include "AliLog.h"
#include "AliTPCExB.h"
#include "TGeoMatrix.h"
#include "AliTPCTransform.h"

ClassImp(AliTPCTransform)

  AliTPCTransform::AliTPCTransform():
    AliTransform()
{
  //
  // Speed it up a bit!
  //
  for (Int_t i=0;i<18;++i) {
    Double_t alpha=TMath::DegToRad()*(10.+20.*(i%18));
    fSins[i]=TMath::Sin(alpha);
    fCoss[i]=TMath::Cos(alpha);
  }
  fPrimVtx[0]=0;
  fPrimVtx[1]=0;
  fPrimVtx[2]=0;
}

AliTPCTransform::~AliTPCTransform() {
  //
  // Destructor
  //
}

void AliTPCTransform::SetPrimVertex(Double_t *vtx){
  //
  //
  //
  fPrimVtx[0]=vtx[0];
  fPrimVtx[1]=vtx[1];
  fPrimVtx[2]=vtx[2];
}

void AliTPCTransform::Transform(Double_t *x,Int_t *i,UInt_t /*time*/,
				Int_t /*coordinateType*/) {
  // input: x[0] - pad row
  //        x[1] - pad
  //        x[2] - time in us
  //        i[0] - sector
  // output: x[0] - x (all in the rotated global coordinate frame)
  //         x[1] - y
  //         x[2] - z
  //
  //  primvtx     - position of the primary vertex
  //                used for the TOF correction
  //                TOF of particle calculated assuming the speed-of-light and
  //                line approximation
  //

  Int_t row=TMath::Nint(x[0]);
  Int_t pad=TMath::Nint(x[1]);
  Int_t sector=i[0];
  AliTPCcalibDB*  calib=AliTPCcalibDB::Instance();
  //
  AliTPCCalPad * time0TPC = calib->GetPadTime0();
  AliTPCParam  * param    = calib->GetParameters();
  if (!time0TPC){
    AliFatal("Time unisochronity missing");
  }

  if (!param){
    AliFatal("Parameters missing");
  }

  Double_t xx[3];
  //  Apply Time0 correction - Pad by pad fluctuation
  //
  x[2]-=time0TPC->GetCalROC(sector)->GetValue(row,pad);
  //
  // Tranform from pad - time coordinate system to the rotated global (tracking) system
  //
  Local2RotatedGlobal(sector,x);
  //
  //
  //
  // Alignment
  //TODO:  calib->GetParameters()->GetClusterMatrix(sector)->LocalToMaster(x,xx);
  RotatedGlobal2Global(sector,x);
  //
  //
  // ExB correction
  //
  calib->GetExB()->Correct(x,xx);
  //
  // Time of flight correction
  //
  const Int_t kNIS=param->GetNInnerSector(), kNOS=param->GetNOuterSector();
  Float_t sign=1;
  if (sector < kNIS) {
    sign = (sector < kNIS/2) ? 1 : -1;
  } else {
    sign = ((sector-kNIS) < kNOS/2) ? 1 : -1;
  }
  Float_t deltaDr =0;
  Float_t dist=0;
  dist+=(fPrimVtx[0]-x[0])*(fPrimVtx[0]-x[0]);
  dist+=(fPrimVtx[1]-x[1])*(fPrimVtx[1]-x[1]);
  dist+=(fPrimVtx[2]-x[2])*(fPrimVtx[2]-x[2]);
  dist = TMath::Sqrt(dist);
  // drift length correction because of TOF
  // the drift velocity is in cm/s therefore multiplication by 0.01
  deltaDr = (dist*(0.01*param->GetDriftV()))/TMath::C();
  xx[2]+=sign*deltaDr;
  //
  Global2RotatedGlobal(sector,xx);
  //
  x[0]=xx[0];x[1]=xx[1];x[2]=xx[2];
}

void AliTPCTransform::Local2RotatedGlobal(Int_t sector, Double_t *x) const {
  //
  //
  // Tranform coordinate from
  // row, pad, time to x,y,z
  //
  // Drift Velocity
  // Current implementation - common drift velocity - for full chamber
  // TODO: use a map or parametrisation!
  //
  //
  //
  AliTPCcalibDB*  calib=AliTPCcalibDB::Instance();
  AliTPCParam  * param    = calib->GetParameters();
  if (!param){
    AliFatal("Parameters missing");
  }
  Int_t row=TMath::Nint(x[0]);
  //  Int_t pad=TMath::Nint(x[1]);
  //
  const Int_t kNIS=param->GetNInnerSector(), kNOS=param->GetNOuterSector();
  Double_t sign = 1.;
  Double_t zwidth    = param->GetZWidth();
  Double_t padWidth  = 0;
  Double_t padLength = 0;
  Double_t    maxPad    = 0;
  //
  if (sector < kNIS) {
    maxPad = param->GetNPadsLow(row);
    sign = (sector < kNIS/2) ? 1 : -1;
    padLength = param->GetPadPitchLength(sector,row);
    padWidth = param->GetPadPitchWidth(sector);
  } else {
    maxPad = param->GetNPadsUp(row);
    sign = ((sector-kNIS) < kNOS/2) ? 1 : -1;
    padLength = param->GetPadPitchLength(sector,row);
    padWidth  = param->GetPadPitchWidth(sector);
  }
  //
  // X coordinate
  x[0] = param->GetPadRowRadii(sector,row);  // padrow X position - ideal
  //
  // Y coordinate
  //
  x[1]=(x[1]-0.5*maxPad)*padWidth;
  // pads are mirrorred on C-side
  if (sector%36>17){
    x[1]*=-1;
  }

  //

  //
  // Z coordinate
  //
  x[2]*= zwidth;  // tranform time bin to the distance to the ROC
  x[2]-= 3.*param->GetZSigma() + param->GetNTBinsL1()*zwidth;
  // subtract the time offsets
  x[2] = sign*( param->GetZLength(sector) - x[2]);
}

void AliTPCTransform::RotatedGlobal2Global(Int_t sector,Double_t *x) const {
  //
  // transform possition rotated global to the global
  //
  Double_t cos,sin;
  GetCosAndSin(sector,cos,sin);
  Double_t tmp=x[0];
  x[0]= cos*tmp-sin*x[1];
  x[1]=+sin*tmp+cos*x[1];
}

void AliTPCTransform::Global2RotatedGlobal(Int_t sector,Double_t *x) const {
  //
  // tranform possition Global2RotatedGlobal
  //
  Double_t cos,sin;
  GetCosAndSin(sector,cos,sin);
  Double_t tmp=x[0];
  x[0]= cos*tmp+sin*x[1];
  x[1]= -sin*tmp+cos*x[1];
}

void AliTPCTransform::GetCosAndSin(Int_t sector,Double_t &cos,
					  Double_t &sin) const {
  cos=fCoss[sector%18];
  sin=fSins[sector%18];
}

<|endoftext|>


<commit_before>void recTPC2007(Int_t type, const char *filename="data.root")
{
  //  .L $ALICE_ROOT/TPC/macros/recTPC2007.C

  // recTPC2007(0,"rfio:/castor/cern.ch/alice/data/2007/12/16/11/07000013151011.20.root")
  //recTPC2007(0,"alien:///alice/data/2007/LHC07w_TPC/000012674/raw/07000012674011.90.root")
  //  recTPC2007(0,"/data/test2007/07000012674011/07000012674011.90.root")

  //
  // Set path to calibration data
  //
  // type variable = 0 - cosmic test
  //               = 1 - laser test
  //
  // Set reconstruction parameters
  ////
  //gSystem->Load("/afs/cern.ch/alice/tpctest/root/HEAD/lib/libRAliEn.so");
  //gSystem->Load("$ROOTSYS/lib/libXrdClient.so")
  TGrid::Connect("alien://");
  //

  AliLog::SetClassDebugLevel("AliTPCclusterer",2);
  AliTPCRecoParam * tpcRecoParam = 0;
  if (type==0)  tpcRecoParam = AliTPCRecoParam::GetCosmicTestParam(kTRUE);
  if (type>0)  tpcRecoParam = AliTPCRecoParam::GetLaserTestParam(kTRUE);
  tpcRecoParam->SetTimeInterval(60,940);
  tpcRecoParam->Dump();
  //
  //
 //  tpcRecoParam->SetMinMaxCutAbs(4.);
//   tpcRecoParam->SetMinLeftRightCutAbs(6.);
//   tpcRecoParam->SetMinUpDownCutAbs(7.);
//   tpcRecoParam->SetMinMaxCutSigma(4.);
//   tpcRecoParam->SetMinLeftRightCutSigma(6.);
//   tpcRecoParam->SetMinUpDownCutSigma(7.);
  //
  //
  AliTPCReconstructor::SetRecoParam(tpcRecoParam);
  AliTPCReconstructor::SetStreamLevel(100);
  //
  AliReconstruction rec;
  rec.SetDefaultStorage("alien://folder=/alice/data/2007/LHC07w/OCDB/");
  rec.SetWriteESDfriend(kTRUE);
  rec.SetInput(filename);
  rec.SetRunReconstruction("TPC");
  rec.SetEquipmentIdMap("EquipmentIdMap.data");
  //
  rec.SetOption("TPC","PedestalSubtraction OldRCUFormat");
  rec.SetFillESD("TPC");
  rec.SetFillTriggerESD(kFALSE);
  rec.SetRunVertexFinder(kFALSE);
  rec.SetCleanESD(kFALSE);
  rec.Run();
}

<commit_msg>delete obsolete macro<commit_after><|endoftext|>