<commit_before>// Copyright (c) 2012, 2013 Pierre MOULON.

// 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/.
#include "openMVG/exif_IO/exif_IO_EasyExif.hpp"

#include "openMVG_Samples/sensorWidthDatabase/ParseDatabase.hpp"

#include "openMVG/image/image.hpp"

#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"

#include <iostream>
#include <fstream>
#include <memory>
#include <string>
#include <vector>

int main(int argc, char **argv)
{
  CmdLine cmd;

  std::string sImageDir;
  std::string sfileDatabase = "";
  std::string sOutputDir = "";
  double focalPixPermm = -1.0;

  cmd.add( make_option('i', sImageDir, "imageDirectory") );
  cmd.add( make_option('d', sfileDatabase, "sensorWidthDatabase") );
  cmd.add( make_option('o', sOutputDir, "outputDirectory") );
  cmd.add( make_option('f', focalPixPermm, "focal") );

  try {
      if (argc == 1) throw std::string("Invalid command line parameter.");
      cmd.process(argc, argv);
  } catch(const std::string& s) {
      std::cerr << "Usage: " << argv[0] << '\n'
      << "[-i|--imageDirectory]\n"
      << "[-d|--sensorWidthDatabase]\n"
      << "[-o|--outputDirectory]\n"
      << "[-f|--focal] (pixels)\n"
      << std::endl;

      std::cerr << s << std::endl;
      return EXIT_FAILURE;
  }

  std::cout << " You called : " <<std::endl
            << argv[0] << std::endl
            << "--imageDirectory " << sImageDir << std::endl
            << "--sensorWidthDatabase " << sfileDatabase << std::endl
            << "--outputDirectory " << sOutputDir << std::endl
            << "--focal " << focalPixPermm << std::endl;

  if ( !stlplus::folder_exists( sImageDir ) )
  {
    std::cerr << "\nThe input directory doesn't exist" << std::endl;
    return EXIT_FAILURE;
  }

  if (sOutputDir.empty())
  {
    std::cerr << "\nInvalid output directory" << std::endl;
    return EXIT_FAILURE;
  }

  if ( !stlplus::folder_exists( sOutputDir ) )
  {
    if ( !stlplus::folder_create( sOutputDir ))
    {
      std::cerr << "\nCannot create output directory" << std::endl;
      return EXIT_FAILURE;
    }
  }

  std::vector<std::string> vec_image = stlplus::folder_files( sImageDir );
  // Write the new file
  std::ofstream listTXT( stlplus::create_filespec( sOutputDir,
                                                   "lists.txt" ).c_str() );
  if ( listTXT )
  {
    std::sort(vec_image.begin(), vec_image.end());
    for ( std::vector<std::string>::const_iterator iter_image = vec_image.begin();
      iter_image != vec_image.end();
      iter_image++ )
    {
      // Read meta data to fill width height and focalPixPermm
      std::string sImageFilename = stlplus::create_filespec( sImageDir, *iter_image );

      size_t width = -1;
      size_t height = -1;

      std::auto_ptr<Exif_IO> exifReader (new Exif_IO_EasyExif() );
      exifReader->open( sImageFilename );

      // Consider the case where focal is provided

      std::ostringstream os;
      //If image do not contains meta data
      if ( !exifReader->doesHaveExifInfo() || focalPixPermm != -1)
      {
        Image<unsigned char> image;
        if (openMVG::ReadImage( sImageFilename.c_str(), &image))  {
          width = image.Width();
          height = image.Height();
        }
        else
        {
          Image<RGBColor> imageRGB;
          if (openMVG::ReadImage( sImageFilename.c_str(), &imageRGB)) {
            width = imageRGB.Width();
            height = imageRGB.Height();
          }
          else
          {
            Image<RGBAColor> imageRGBA;
            if (openMVG::ReadImage( sImageFilename.c_str(), &imageRGBA))  {
              width = imageRGBA.Width();
              height = imageRGBA.Height();
            }
            else
              continue; // image is not considered, cannot be read
          }
        }
        if ( focalPixPermm == -1)
          os << *iter_image << ";" << width << ";" << height << std::endl;
        else
          os << *iter_image << ";" << width << ";" << height << ";"
            << focalPixPermm << ";" << 0 << ";" << width/2.0 << ";"
            << 0 << ";" << focalPixPermm << ";" << height/2.0 << ";"
            << 0 << ";" << 0 << ";" << 1 << std::endl;

      }
      else // If image contains meta data
      {
        double focal = focalPixPermm;
        width = exifReader->getWidth();
        height = exifReader->getHeight();
        std::string sCamName = exifReader->getBrand();
        std::string sCamModel = exifReader->getModel();

          std::vector<Datasheet> vec_database;
          Datasheet datasheet;
          if ( parseDatabase( sfileDatabase, vec_database ) )
          {
            if ( getInfo( sCamName, sCamModel, vec_database, datasheet ) )
            {
              // The camera model was found in the database so we can compute it's approximated focal length
              double ccdw = datasheet._sensorSize;
              focal = std::max ( width, height ) * exifReader->getFocal() / ccdw;
              os << *iter_image << ";" << width << ";" << height << ";" << focal << ";" << sCamName << ";" << sCamModel << std::endl;
            }
            else
            {
              std::cout << "Camera \"" << sCamName << "\" model \"" << sCamModel << "\" doesn't exist in the database" << std::endl;
              os << *iter_image << ";" << width << ";" << height << ";" << sCamName << ";" << sCamModel << std::endl;
            }
          }
          else
          {
            std::cout << "Sensor width database \"" << sfileDatabase << "\" doesn't exist." << std::endl;
            std::cout << "Please consider add your camera model in the database." << std::endl;
            os << *iter_image << ";" << width << ";" << height << ";" << sCamName << ";" << sCamModel << std::endl;
          }
        }
      std::cout << os.str();
      listTXT << os.str();
    }
  }
  listTXT.close();
  return EXIT_SUCCESS;
}
<commit_msg>Add a -k option to set a known camera intrinsic matrix. #162<commit_after>// Copyright (c) 2012, 2013 Pierre MOULON.

// 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/.
#include "openMVG/exif_IO/exif_IO_EasyExif.hpp"

#include "openMVG_Samples/sensorWidthDatabase/ParseDatabase.hpp"

#include "openMVG/image/image.hpp"
#include "openMVG/split/split.hpp"

#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"

#include <iostream>
#include <fstream>
#include <sstream>
#include <memory>
#include <string>
#include <vector>

/// Check that Kmatrix is a string like "f;0;ppx;0;f;ppy;0;0;1"
/// With f,ppx,ppy as valid numerical value
bool checkIntrinsicStringValidity(const std::string & Kmatrix)
{
  std::vector<std::string> vec_str;
  split( Kmatrix, ";", vec_str );
  if (vec_str.size() != 9)  {
    std::cerr << "\n Missing ';' character" << std::endl;
    return false;
  }
  // Check that all K matrix value are valid numbers
  for (size_t i = 0; i < vec_str.size(); ++i) {
    double readvalue = 0.0;
    std::stringstream ss;
    ss.str(vec_str[i]);
    if (! (ss >> readvalue) )  {
      std::cerr << "\n Used an invalid not a number character" << std::endl;
      return false;
    }
  }
  return true;
}

int main(int argc, char **argv)
{
  CmdLine cmd;

  std::string sImageDir,
    sfileDatabase = "",
    sOutputDir = "",
    sKmatrix;

  double focalPixPermm = -1.0;

  cmd.add( make_option('i', sImageDir, "imageDirectory") );
  cmd.add( make_option('d', sfileDatabase, "sensorWidthDatabase") );
  cmd.add( make_option('o', sOutputDir, "outputDirectory") );
  cmd.add( make_option('f', focalPixPermm, "focal") );
  cmd.add( make_option('k', sKmatrix, "intrinsics") );

  try {
      if (argc == 1) throw std::string("Invalid command line parameter.");
      cmd.process(argc, argv);
  } catch(const std::string& s) {
      std::cerr << "Usage: " << argv[0] << '\n'
      << "[-i|--imageDirectory]\n"
      << "[-d|--sensorWidthDatabase]\n"
      << "[-o|--outputDirectory]\n"
      << "[-f|--focal] (pixels)\n"
      << "[-k|--intrinsics] Kmatrix: \"f;0;ppx;0;f;ppy;0;0;1\""
      << std::endl;

      std::cerr << s << std::endl;
      return EXIT_FAILURE;
  }

  std::cout << " You called : " <<std::endl
            << argv[0] << std::endl
            << "--imageDirectory " << sImageDir << std::endl
            << "--sensorWidthDatabase " << sfileDatabase << std::endl
            << "--outputDirectory " << sOutputDir << std::endl
            << "--focal " << focalPixPermm << std::endl
            << "--intrinsics " << sKmatrix << std::endl;

  if ( !stlplus::folder_exists( sImageDir ) )
  {
    std::cerr << "\nThe input directory doesn't exist" << std::endl;
    return EXIT_FAILURE;
  }

  if (sOutputDir.empty())
  {
    std::cerr << "\nInvalid output directory" << std::endl;
    return EXIT_FAILURE;
  }

  if ( !stlplus::folder_exists( sOutputDir ) )
  {
    if ( !stlplus::folder_create( sOutputDir ))
    {
      std::cerr << "\nCannot create output directory" << std::endl;
      return EXIT_FAILURE;
    }
  }

  if (sKmatrix.size() > 0 && !checkIntrinsicStringValidity(sKmatrix) )
  {
    std::cerr << "\nInvalid K matrix input" << std::endl;
    return EXIT_FAILURE;
  }

  if (sKmatrix.size() > 0 && focalPixPermm != -1.0)
  {
    std::cerr << "\nCannot combine -f and -k options" << std::endl;
    return EXIT_FAILURE;
  }

  std::vector<std::string> vec_image = stlplus::folder_files( sImageDir );
  // Write the new file
  std::ofstream listTXT( stlplus::create_filespec( sOutputDir,
                                                   "lists.txt" ).c_str() );
  if ( listTXT )
  {
    std::sort(vec_image.begin(), vec_image.end());
    for ( std::vector<std::string>::const_iterator iter_image = vec_image.begin();
      iter_image != vec_image.end();
      iter_image++ )
    {
      // Read meta data to fill width height and focalPixPermm
      std::string sImageFilename = stlplus::create_filespec( sImageDir, *iter_image );

      size_t width = -1;
      size_t height = -1;

      std::auto_ptr<Exif_IO> exifReader (new Exif_IO_EasyExif() );
      exifReader->open( sImageFilename );

      // Consider the case where focal is provided

      std::ostringstream os;
      //If image do not contains meta data
      if ( !exifReader->doesHaveExifInfo() || focalPixPermm != -1)
      {
        Image<unsigned char> image;
        if (openMVG::ReadImage( sImageFilename.c_str(), &image))  {
          width = image.Width();
          height = image.Height();
        }
        else
        {
          Image<RGBColor> imageRGB;
          if (openMVG::ReadImage( sImageFilename.c_str(), &imageRGB)) {
            width = imageRGB.Width();
            height = imageRGB.Height();
          }
          else
          {
            Image<RGBAColor> imageRGBA;
            if (openMVG::ReadImage( sImageFilename.c_str(), &imageRGBA))  {
              width = imageRGBA.Width();
              height = imageRGBA.Height();
            }
            else
              continue; // image is not considered, cannot be read
          }
        }
        os << *iter_image << ";" << width << ";" << height;
        if ( focalPixPermm == -1 && sKmatrix.size() == 0)
          os << std::endl;
        else
        {
          if (sKmatrix.size() > 0) // Known intrinsic matrix
          {
            os << ";" << sKmatrix << std::endl;
          }
          else
            os << ";"
              << focalPixPermm << ";" << 0 << ";" << width/2.0 << ";"
              << 0 << ";" << focalPixPermm << ";" << height/2.0 << ";"
              << 0 << ";" << 0 << ";" << 1 << std::endl;
        }

      }
      else // If image contains meta data
      {
        double focal = focalPixPermm;
        width = exifReader->getWidth();
        height = exifReader->getHeight();
        std::string sCamName = exifReader->getBrand();
        std::string sCamModel = exifReader->getModel();

          std::vector<Datasheet> vec_database;
          Datasheet datasheet;
          if ( parseDatabase( sfileDatabase, vec_database ) )
          {
            if ( getInfo( sCamName, sCamModel, vec_database, datasheet ) )
            {
              // The camera model was found in the database so we can compute it's approximated focal length
              double ccdw = datasheet._sensorSize;
              focal = std::max ( width, height ) * exifReader->getFocal() / ccdw;
              os << *iter_image << ";" << width << ";" << height << ";" << focal << ";" << sCamName << ";" << sCamModel << std::endl;
            }
            else
            {
              std::cout << "Camera \"" << sCamName << "\" model \"" << sCamModel << "\" doesn't exist in the database" << std::endl;
              os << *iter_image << ";" << width << ";" << height << ";" << sCamName << ";" << sCamModel << std::endl;
            }
          }
          else
          {
            std::cout << "Sensor width database \"" << sfileDatabase << "\" doesn't exist." << std::endl;
            std::cout << "Please consider add your camera model in the database." << std::endl;
            os << *iter_image << ";" << width << ";" << height << ";" << sCamName << ";" << sCamModel << std::endl;
          }
        }
      std::cout << os.str();
      listTXT << os.str();
    }
  }
  listTXT.close();
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>// Copyright (C) 2015 Elviss Strazdins
// This file is part of the Ouzel engine.

#include <algorithm>
#include "Engine.h"
#include "Layer.h"
#include "Node.h"
#include "Camera.h"
#include "Renderer.h"
#include "Scene.h"
#include "Matrix4.h"

namespace ouzel
{
    Layer::Layer()
    {
        _camera = std::make_shared<Camera>();
    }

    Layer::~Layer()
    {

    }

    void Layer::update(float delta)
    {
        lock();

        for (const NodePtr& child : _children)
        {
            child->update(delta);
        }

        unlock();
    }

    void Layer::draw()
    {
        _drawQueue.clear();

        // render only if there is an active camera
        if (_camera)
        {
            lock();

            for (const NodePtr child : _children)
            {
                child->visit();
                child->calculateTransformRecursive();
            }

            std::stable_sort(_drawQueue.begin(), _drawQueue.end(), [](const NodePtr& a, const NodePtr& b) {
                return a->getZ() > b->getZ();
            });

            for (const NodePtr& node : _drawQueue)
            {
                node->process();
            }

            unlock();
        }
    }

    bool Layer::addChild(const NodePtr& node)
    {
        if (NodeContainer::addChild(node))
        {
            node->addToLayer(std::static_pointer_cast<Layer>(shared_from_this()));

            node->updateTransform(Matrix4::identity());

            return true;
        }
        else
        {
            return false;
        }
    }

    void Layer::addToDrawQueue(const NodePtr& node)
    {
        _drawQueue.push_back(node);
    }

    void Layer::setCamera(const CameraPtr& camera)
    {
        _camera = camera;
    }

    Vector2 Layer::screenToWorldLocation(const Vector2& position)
    {
        if (_camera)
        {
            Matrix4 projViewMatrix = _projection * _camera->getTransform();
            Matrix4 inverseViewMatrix = projViewMatrix;
            inverseViewMatrix.invert();

            Vector3 result = Vector3(position.x, position.y, 0.0f);
            inverseViewMatrix.transformPoint(&result);

            return Vector2(result.x, result.y);
        }
        else
        {
            return Vector2();
        }
    }

    Vector2 Layer::worldToScreenLocation(const Vector2& position)
    {
        if (_camera)
        {
            Matrix4 projViewMatrix = _projection * _camera->getTransform();

            Vector3 result = Vector3(position.x, position.y, 0.0f);
            projViewMatrix.transformPoint(&result);

            return Vector2(result.x, result.y);
        }
        else
        {
            return Vector2();
        }
    }

    NodePtr Layer::pickNode(const Vector2& position)
    {
        for (std::vector<NodePtr>::const_reverse_iterator i = _drawQueue.rbegin(); i != _drawQueue.rend(); ++i)
        {
            NodePtr node = *i;

            if (node->isPickable() && node->pointOn(position))
            {
                return node;
            }
        }

        return nullptr;
    }

    std::set<NodePtr> Layer::pickNodes(const Rectangle& rectangle)
    {
        std::set<NodePtr> result;

        for (std::vector<NodePtr>::const_reverse_iterator i = _drawQueue.rbegin(); i != _drawQueue.rend(); ++i)
        {
            NodePtr node = *i;

            if (node->isPickable() && node->rectangleOverlaps(rectangle))
            {
                result.insert(node);
            }
        }

        return result;
    }

    void Layer::setScaleMode(ScaleMode scaleMode)
    {
        _scaleMode = scaleMode;
        recalculateProjection();
    }

    void Layer::setDesignSize(const Size2& designSize)
    {
        _designSize = designSize;
        recalculateProjection();
    }

    void Layer::recalculateProjection()
    {
        Size2 size = Engine::getInstance()->getRenderer()->getSize();
        Vector2 scale(1.0f, 1.0f);

        if (_designSize.width != 0.0f && _designSize.height != 0.0f &&
            size.width != 0.0f && size.height != 0.0f)
        {
            float aspectRatio = size.width / size.height;

            switch (_scaleMode)
            {
                case ScaleMode::None:
                {
                    // Do nothing
                    break;
                }
                case ScaleMode::ExactFit:
                {
                    scale.x = _designSize.width / size.width;
                    scale.y = _designSize.height / size.height;
                    break;
                }
                case ScaleMode::NoBorder:
                {
                    if (size.width / size.height > _designSize.width / _designSize.height)
                    {
                        scale.x = _designSize.width / size.width;
                        scale.y = (_designSize.width / size.height) / aspectRatio;
                    }
                    else
                    {
                        scale.x = (_designSize.height / size.width) * aspectRatio;
                        scale.y = _designSize.height / size.height;
                    }
                    break;
                }
                case ScaleMode::ShowAll:
                {
                    if (size.width / size.height < _designSize.width / _designSize.height)
                    {
                        scale.x = _designSize.width / size.width;
                        scale.y = (_designSize.width / size.height) / aspectRatio;
                    }
                    else
                    {
                        scale.x = (_designSize.height / size.width) * aspectRatio;
                        scale.y = _designSize.height / size.height;
                    }
                    break;
                }
            }
        }

        Matrix4::createOrthographic(size.width * scale.x, size.height * scale.y, -1.0f, 1.0f, &_projection);
        _inverseProjection = _projection;
        _inverseProjection.invert();
    }

    void Layer::setOrder(int32_t order)
    {
        _order = order;

        if (ScenePtr scene = _scene.lock())
        {
            scene->reorderLayers();
        }
    }

    void Layer::addToScene(const ScenePtr& scene)
    {
        _scene = scene;
    }

    void Layer::removeFromScene()
    {
        _scene.reset();
    }
}
<commit_msg>Don' t use scale for calculation projection matrix<commit_after>// Copyright (C) 2015 Elviss Strazdins
// This file is part of the Ouzel engine.

#include <algorithm>
#include "Engine.h"
#include "Layer.h"
#include "Node.h"
#include "Camera.h"
#include "Renderer.h"
#include "Scene.h"
#include "Matrix4.h"

namespace ouzel
{
    Layer::Layer()
    {
        _camera = std::make_shared<Camera>();
    }

    Layer::~Layer()
    {

    }

    void Layer::update(float delta)
    {
        lock();

        for (const NodePtr& child : _children)
        {
            child->update(delta);
        }

        unlock();
    }

    void Layer::draw()
    {
        _drawQueue.clear();

        // render only if there is an active camera
        if (_camera)
        {
            lock();

            for (const NodePtr child : _children)
            {
                child->visit();
                child->calculateTransformRecursive();
            }

            std::stable_sort(_drawQueue.begin(), _drawQueue.end(), [](const NodePtr& a, const NodePtr& b) {
                return a->getZ() > b->getZ();
            });

            for (const NodePtr& node : _drawQueue)
            {
                node->process();
            }

            unlock();
        }
    }

    bool Layer::addChild(const NodePtr& node)
    {
        if (NodeContainer::addChild(node))
        {
            node->addToLayer(std::static_pointer_cast<Layer>(shared_from_this()));

            node->updateTransform(Matrix4::identity());

            return true;
        }
        else
        {
            return false;
        }
    }

    void Layer::addToDrawQueue(const NodePtr& node)
    {
        _drawQueue.push_back(node);
    }

    void Layer::setCamera(const CameraPtr& camera)
    {
        _camera = camera;
    }

    Vector2 Layer::screenToWorldLocation(const Vector2& position)
    {
        if (_camera)
        {
            Matrix4 projViewMatrix = _projection * _camera->getTransform();
            Matrix4 inverseViewMatrix = projViewMatrix;
            inverseViewMatrix.invert();

            Vector3 result = Vector3(position.x, position.y, 0.0f);
            inverseViewMatrix.transformPoint(&result);

            return Vector2(result.x, result.y);
        }
        else
        {
            return Vector2();
        }
    }

    Vector2 Layer::worldToScreenLocation(const Vector2& position)
    {
        if (_camera)
        {
            Matrix4 projViewMatrix = _projection * _camera->getTransform();

            Vector3 result = Vector3(position.x, position.y, 0.0f);
            projViewMatrix.transformPoint(&result);

            return Vector2(result.x, result.y);
        }
        else
        {
            return Vector2();
        }
    }

    NodePtr Layer::pickNode(const Vector2& position)
    {
        for (std::vector<NodePtr>::const_reverse_iterator i = _drawQueue.rbegin(); i != _drawQueue.rend(); ++i)
        {
            NodePtr node = *i;

            if (node->isPickable() && node->pointOn(position))
            {
                return node;
            }
        }

        return nullptr;
    }

    std::set<NodePtr> Layer::pickNodes(const Rectangle& rectangle)
    {
        std::set<NodePtr> result;

        for (std::vector<NodePtr>::const_reverse_iterator i = _drawQueue.rbegin(); i != _drawQueue.rend(); ++i)
        {
            NodePtr node = *i;

            if (node->isPickable() && node->rectangleOverlaps(rectangle))
            {
                result.insert(node);
            }
        }

        return result;
    }

    void Layer::setScaleMode(ScaleMode scaleMode)
    {
        _scaleMode = scaleMode;
        recalculateProjection();
    }

    void Layer::setDesignSize(const Size2& designSize)
    {
        _designSize = designSize;
        recalculateProjection();
    }

    void Layer::recalculateProjection()
    {
        Size2 size = Engine::getInstance()->getRenderer()->getSize();

        if (_designSize.width != 0.0f && _designSize.height != 0.0f &&
            size.width != 0.0f && size.height != 0.0f)
        {
            float aspectRatio = size.width / size.height;

            switch (_scaleMode)
            {
                case ScaleMode::None:
                {
                    // Do nothing
                    break;
                }
                case ScaleMode::ExactFit:
                {
                    size.width = _designSize.width;
                    size.height = _designSize.height;
                    break;
                }
                case ScaleMode::NoBorder:
                {
                    if (size.width / size.height > _designSize.width / _designSize.height)
                    {
                        size.width = _designSize.width;
                        size.height = _designSize.width / aspectRatio;
                    }
                    else
                    {
                        size.width = _designSize.height * aspectRatio;
                        size.height = _designSize.height;
                    }
                    break;
                }
                case ScaleMode::ShowAll:
                {
                    if (size.width / size.height < _designSize.width / _designSize.height)
                    {
                        size.width = _designSize.width;
                        size.height = _designSize.width / aspectRatio;
                    }
                    else
                    {
                        size.width = _designSize.height * aspectRatio;
                        size.height = _designSize.height;
                    }
                    break;
                }
            }
        }

        Matrix4::createOrthographic(size.width, size.height, -1.0f, 1.0f, &_projection);
        _inverseProjection = _projection;
        _inverseProjection.invert();
    }

    void Layer::setOrder(int32_t order)
    {
        _order = order;

        if (ScenePtr scene = _scene.lock())
        {
            scene->reorderLayers();
        }
    }

    void Layer::addToScene(const ScenePtr& scene)
    {
        _scene = scene;
    }

    void Layer::removeFromScene()
    {
        _scene.reset();
    }
}
<|endoftext|>


<commit_before><commit_msg>coverity#708646 Uninitialized scalar field<commit_after><|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: scrwnd.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 19:39:49 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <math.h>
#include <limits.h>

#ifndef _TOOLS_TIME_HXX
#include <tools/time.hxx>
#endif
#include <tools/debug.hxx>

#ifndef _SV_SVIDS_HRC
#include <svids.hrc>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _VCL_TIMER_HXX
#include <timer.hxx>
#endif
#ifndef _VCL_EVENT_HXX
#include <event.hxx>
#endif
#ifndef _VCL_SCRWND_HXX
#include <scrwnd.hxx>
#endif

// -----------
// - Defines -
// -----------

#define WHEEL_WIDTH     25
#define WHEEL_RADIUS    ((WHEEL_WIDTH) >> 1 )
#define MAX_TIME        300
#define MIN_TIME        20
#define DEF_TIMEOUT     50

// -------------------
// - ImplWheelWindow -
// -------------------

ImplWheelWindow::ImplWheelWindow( Window* pParent ) :
            FloatingWindow  ( pParent, 0 ),
            mnRepaintTime   ( 1UL ),
            mnTimeout       ( DEF_TIMEOUT ),
            mnWheelMode     ( WHEELMODE_NONE ),
            mnActDist       ( 0UL ),
            mnActDeltaX     ( 0L ),
            mnActDeltaY     ( 0L )
{
    // we need a parent
    DBG_ASSERT( pParent, "ImplWheelWindow::ImplWheelWindow(): Parent not set!" );

    const Size      aSize( pParent->GetOutputSizePixel() );
    const USHORT    nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags;
    const BOOL      bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0;
    const BOOL      bVert = ( nFlags & AUTOSCROLL_VERT ) != 0;

    // calculate maximum speed distance
    mnMaxWidth = (ULONG) ( 0.4 * hypot( (double) aSize.Width(), aSize.Height() ) );

    // create wheel window
    SetTitleType( FLOATWIN_TITLE_NONE );
    ImplCreateImageList();
    ResMgr* pResMgr = ImplGetResMgr();
    Bitmap aBmp;
    if( pResMgr )
        aBmp = Bitmap( ResId( SV_RESID_BITMAP_SCROLLMSK, ImplGetResMgr() ) );
    ImplSetRegion( aBmp );

    // set wheel mode
    if( bHorz && bVert )
        ImplSetWheelMode( WHEELMODE_VH );
    else if( bHorz )
        ImplSetWheelMode( WHEELMODE_H );
    else
        ImplSetWheelMode( WHEELMODE_V );

    // init timer
    mpTimer = new Timer;
    mpTimer->SetTimeoutHdl( LINK( this, ImplWheelWindow, ImplScrollHdl ) );
    mpTimer->SetTimeout( mnTimeout );
    mpTimer->Start();

    CaptureMouse();
}

// ------------------------------------------------------------------------

ImplWheelWindow::~ImplWheelWindow()
{
    ReleaseMouse();
    mpTimer->Stop();
    delete mpTimer;
}

// ------------------------------------------------------------------------

void ImplWheelWindow::ImplSetRegion( const Bitmap& rRegionBmp )
{
    Point           aPos( GetPointerPosPixel() );
    const Size      aSize( rRegionBmp.GetSizePixel() );
    Point           aPoint;
    const Rectangle aRect( aPoint, aSize );

    maCenter = maLastMousePos = aPos;
    aPos.X() -= aSize.Width() >> 1;
    aPos.Y() -= aSize.Height() >> 1;

    SetPosSizePixel( aPos, aSize );
    SetWindowRegionPixel( rRegionBmp.CreateRegion( COL_BLACK, aRect ) );
}

// ------------------------------------------------------------------------

void ImplWheelWindow::ImplCreateImageList()
{
    Bitmap aImgBmp;
    ResMgr* pResMgr = ImplGetResMgr();
    if( pResMgr )
        aImgBmp = Bitmap( ResId( SV_RESID_BITMAP_SCROLLBMP, pResMgr ) );
    maImgList = ImageList( aImgBmp, 6 );
}

// ------------------------------------------------------------------------

void ImplWheelWindow::ImplSetWheelMode( ULONG nWheelMode )
{
    if( nWheelMode != mnWheelMode )
    {
        mnWheelMode = nWheelMode;

        if( WHEELMODE_NONE == mnWheelMode )
        {
            if( IsVisible() )
                Hide();
        }
        else
        {
            if( !IsVisible() )
                Show();

            ImplDrawWheel();
        }
    }
}

// ------------------------------------------------------------------------

void ImplWheelWindow::ImplDrawWheel()
{
    USHORT nId;

    switch( mnWheelMode )
    {
        case( WHEELMODE_VH ):       nId = 1; break;
        case( WHEELMODE_V    ):     nId = 2; break;
        case( WHEELMODE_H    ):     nId = 3; break;
        case( WHEELMODE_SCROLL_VH ):nId = 4; break;
        case( WHEELMODE_SCROLL_V ): nId = 5; break;
        case( WHEELMODE_SCROLL_H ): nId = 6; break;
        default:                    nId = 0; break;
    }

    if( nId )
        DrawImage( Point(), maImgList.GetImage( nId ) );
}

// ------------------------------------------------------------------------

void ImplWheelWindow::ImplRecalcScrollValues()
{
    if( mnActDist < WHEEL_RADIUS )
    {
        mnActDeltaX = mnActDeltaY = 0L;
        mnTimeout = DEF_TIMEOUT;
    }
    else
    {
        ULONG nCurTime;

        // calc current time
        if( mnMaxWidth )
        {
            const double fExp = ( (double) mnActDist / mnMaxWidth ) * log10( (double) MAX_TIME / MIN_TIME );
            nCurTime = (ULONG) ( MAX_TIME / pow( 10., fExp ) );
        }
        else
            nCurTime = MAX_TIME;

        if( !nCurTime )
            nCurTime = 1UL;

        if( mnRepaintTime <= nCurTime )
            mnTimeout = nCurTime - mnRepaintTime;
        else
        {
            long nMult = mnRepaintTime / nCurTime;

            if( !( mnRepaintTime % nCurTime ) )
                mnTimeout = 0UL;
            else
                mnTimeout = ++nMult * nCurTime - mnRepaintTime;

            double fValX = (double) mnActDeltaX * nMult;
            double fValY = (double) mnActDeltaY * nMult;

            if( fValX > LONG_MAX )
                mnActDeltaX = LONG_MAX;
            else if( fValX < LONG_MIN )
                mnActDeltaX = LONG_MIN;
            else
                mnActDeltaX = (long) fValX;

            if( fValY > LONG_MAX )
                mnActDeltaY = LONG_MAX;
            else if( fValY < LONG_MIN )
                mnActDeltaY = LONG_MIN;
            else
                mnActDeltaY = (long) fValY;
        }
    }
}

// ------------------------------------------------------------------------

PointerStyle ImplWheelWindow::ImplGetMousePointer( long nDistX, long nDistY )
{
    PointerStyle    eStyle;
    const USHORT    nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags;
    const BOOL      bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0;
    const BOOL      bVert = ( nFlags & AUTOSCROLL_VERT ) != 0;

    if( bHorz || bVert )
    {
        if( mnActDist < WHEEL_RADIUS )
        {
            if( bHorz && bVert )
                eStyle = POINTER_AUTOSCROLL_NSWE;
            else if( bHorz )
                eStyle = POINTER_AUTOSCROLL_WE;
            else
                eStyle = POINTER_AUTOSCROLL_NS;
        }
        else
        {
            double fAngle = atan2( (double) -nDistY, nDistX ) / F_PI180;

            if( fAngle < 0.0 )
                fAngle += 360.;

            if( bHorz && bVert )
            {
                if( fAngle >= 22.5 && fAngle <= 67.5 )
                    eStyle = POINTER_AUTOSCROLL_NE;
                else if( fAngle >= 67.5 && fAngle <= 112.5 )
                    eStyle = POINTER_AUTOSCROLL_N;
                else if( fAngle >= 112.5 && fAngle <= 157.5 )
                    eStyle = POINTER_AUTOSCROLL_NW;
                else if( fAngle >= 157.5 && fAngle <= 202.5 )
                    eStyle = POINTER_AUTOSCROLL_W;
                else if( fAngle >= 202.5 && fAngle <= 247.5 )
                    eStyle = POINTER_AUTOSCROLL_SW;
                else if( fAngle >= 247.5 && fAngle <= 292.5 )
                    eStyle = POINTER_AUTOSCROLL_S;
                else if( fAngle >= 292.5 && fAngle <= 337.5 )
                    eStyle = POINTER_AUTOSCROLL_SE;
                else
                    eStyle = POINTER_AUTOSCROLL_E;
            }
            else if( bHorz )
            {
                if( fAngle >= 270. || fAngle <= 90. )
                    eStyle = POINTER_AUTOSCROLL_E;
                else
                    eStyle = POINTER_AUTOSCROLL_W;
            }
            else
            {
                if( fAngle >= 0. && fAngle <= 180. )
                    eStyle = POINTER_AUTOSCROLL_N;
                else
                    eStyle = POINTER_AUTOSCROLL_S;
            }
        }
    }
    else
        eStyle = POINTER_ARROW;

    return eStyle;
}

// ------------------------------------------------------------------------

void ImplWheelWindow::Paint( const Rectangle& )
{
    ImplDrawWheel();
}

// ------------------------------------------------------------------------

void ImplWheelWindow::MouseMove( const MouseEvent& rMEvt )
{
    FloatingWindow::MouseMove( rMEvt );

    const Point aMousePos( OutputToScreenPixel( rMEvt.GetPosPixel() ) );
    const long  nDistX = aMousePos.X() - maCenter.X();
    const long  nDistY = aMousePos.Y() - maCenter.Y();

    mnActDist = (ULONG) hypot( (double) nDistX, nDistY );

    const PointerStyle  eActStyle = ImplGetMousePointer( nDistX, nDistY );
    const USHORT        nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags;
    const BOOL          bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0;
    const BOOL          bVert = ( nFlags & AUTOSCROLL_VERT ) != 0;
    const BOOL          bOuter = mnActDist > WHEEL_RADIUS;

    if( bOuter && ( maLastMousePos != aMousePos ) )
    {
        switch( eActStyle )
        {
            case( POINTER_AUTOSCROLL_N ):   mnActDeltaX = +0L, mnActDeltaY = +1L; break;
            case( POINTER_AUTOSCROLL_S ):   mnActDeltaX = +0L, mnActDeltaY = -1L; break;
            case( POINTER_AUTOSCROLL_W ):   mnActDeltaX = +1L, mnActDeltaY = +0L; break;
            case( POINTER_AUTOSCROLL_E ):   mnActDeltaX = -1L, mnActDeltaY = +0L; break;
            case( POINTER_AUTOSCROLL_NW ):  mnActDeltaX = +1L, mnActDeltaY = +1L; break;
            case( POINTER_AUTOSCROLL_NE ):  mnActDeltaX = -1L, mnActDeltaY = +1L; break;
            case( POINTER_AUTOSCROLL_SW ):  mnActDeltaX = +1L, mnActDeltaY = -1L; break;
            case( POINTER_AUTOSCROLL_SE ):  mnActDeltaX = -1L, mnActDeltaY = -1L; break;

            default:
            break;
        }
    }

    ImplRecalcScrollValues();
    maLastMousePos = aMousePos;
    SetPointer( eActStyle );

    if( bHorz && bVert )
        ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_VH : WHEELMODE_VH );
    else if( bHorz )
        ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_H : WHEELMODE_H );
    else
        ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_V : WHEELMODE_V );
}

// ------------------------------------------------------------------------

void ImplWheelWindow::MouseButtonUp( const MouseEvent& rMEvt )
{
    if( mnActDist > WHEEL_RADIUS )
        GetParent()->EndAutoScroll();
    else
        FloatingWindow::MouseButtonUp( rMEvt );
}

// ------------------------------------------------------------------------

IMPL_LINK( ImplWheelWindow, ImplScrollHdl, Timer*, EMPTYARG )
{
    if ( mnActDeltaX || mnActDeltaY )
    {
        Window*             pWindow = GetParent();
        const Point         aMousePos( pWindow->OutputToScreenPixel( pWindow->GetPointerPosPixel() ) );
        Point               aCmdMousePos( pWindow->ImplFrameToOutput( aMousePos ) );
        CommandScrollData   aScrollData( mnActDeltaX, mnActDeltaY );
        CommandEvent        aCEvt( aCmdMousePos, COMMAND_AUTOSCROLL, TRUE, &aScrollData );
        NotifyEvent         aNCmdEvt( EVENT_COMMAND, pWindow, &aCEvt );

        if ( !ImplCallPreNotify( aNCmdEvt ) )
        {
            const ULONG nTime = Time::GetSystemTicks();
            pWindow->Command( aCEvt );
            mnRepaintTime = Max( Time::GetSystemTicks() - nTime, 1UL );
            ImplRecalcScrollValues();
        }
    }

    if ( mnTimeout != mpTimer->GetTimeout() )
        mpTimer->SetTimeout( mnTimeout );
    mpTimer->Start();

    return 0L;
}
<commit_msg>INTEGRATION: CWS pchfix02 (1.7.112); FILE MERGED 2006/09/01 17:57:55 kaib 1.7.112.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: scrwnd.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 12:20:32 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"

#include <math.h>
#include <limits.h>

#ifndef _TOOLS_TIME_HXX
#include <tools/time.hxx>
#endif
#include <tools/debug.hxx>

#ifndef _SV_SVIDS_HRC
#include <svids.hrc>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _VCL_TIMER_HXX
#include <timer.hxx>
#endif
#ifndef _VCL_EVENT_HXX
#include <event.hxx>
#endif
#ifndef _VCL_SCRWND_HXX
#include <scrwnd.hxx>
#endif

// -----------
// - Defines -
// -----------

#define WHEEL_WIDTH     25
#define WHEEL_RADIUS    ((WHEEL_WIDTH) >> 1 )
#define MAX_TIME        300
#define MIN_TIME        20
#define DEF_TIMEOUT     50

// -------------------
// - ImplWheelWindow -
// -------------------

ImplWheelWindow::ImplWheelWindow( Window* pParent ) :
            FloatingWindow  ( pParent, 0 ),
            mnRepaintTime   ( 1UL ),
            mnTimeout       ( DEF_TIMEOUT ),
            mnWheelMode     ( WHEELMODE_NONE ),
            mnActDist       ( 0UL ),
            mnActDeltaX     ( 0L ),
            mnActDeltaY     ( 0L )
{
    // we need a parent
    DBG_ASSERT( pParent, "ImplWheelWindow::ImplWheelWindow(): Parent not set!" );

    const Size      aSize( pParent->GetOutputSizePixel() );
    const USHORT    nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags;
    const BOOL      bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0;
    const BOOL      bVert = ( nFlags & AUTOSCROLL_VERT ) != 0;

    // calculate maximum speed distance
    mnMaxWidth = (ULONG) ( 0.4 * hypot( (double) aSize.Width(), aSize.Height() ) );

    // create wheel window
    SetTitleType( FLOATWIN_TITLE_NONE );
    ImplCreateImageList();
    ResMgr* pResMgr = ImplGetResMgr();
    Bitmap aBmp;
    if( pResMgr )
        aBmp = Bitmap( ResId( SV_RESID_BITMAP_SCROLLMSK, ImplGetResMgr() ) );
    ImplSetRegion( aBmp );

    // set wheel mode
    if( bHorz && bVert )
        ImplSetWheelMode( WHEELMODE_VH );
    else if( bHorz )
        ImplSetWheelMode( WHEELMODE_H );
    else
        ImplSetWheelMode( WHEELMODE_V );

    // init timer
    mpTimer = new Timer;
    mpTimer->SetTimeoutHdl( LINK( this, ImplWheelWindow, ImplScrollHdl ) );
    mpTimer->SetTimeout( mnTimeout );
    mpTimer->Start();

    CaptureMouse();
}

// ------------------------------------------------------------------------

ImplWheelWindow::~ImplWheelWindow()
{
    ReleaseMouse();
    mpTimer->Stop();
    delete mpTimer;
}

// ------------------------------------------------------------------------

void ImplWheelWindow::ImplSetRegion( const Bitmap& rRegionBmp )
{
    Point           aPos( GetPointerPosPixel() );
    const Size      aSize( rRegionBmp.GetSizePixel() );
    Point           aPoint;
    const Rectangle aRect( aPoint, aSize );

    maCenter = maLastMousePos = aPos;
    aPos.X() -= aSize.Width() >> 1;
    aPos.Y() -= aSize.Height() >> 1;

    SetPosSizePixel( aPos, aSize );
    SetWindowRegionPixel( rRegionBmp.CreateRegion( COL_BLACK, aRect ) );
}

// ------------------------------------------------------------------------

void ImplWheelWindow::ImplCreateImageList()
{
    Bitmap aImgBmp;
    ResMgr* pResMgr = ImplGetResMgr();
    if( pResMgr )
        aImgBmp = Bitmap( ResId( SV_RESID_BITMAP_SCROLLBMP, pResMgr ) );
    maImgList = ImageList( aImgBmp, 6 );
}

// ------------------------------------------------------------------------

void ImplWheelWindow::ImplSetWheelMode( ULONG nWheelMode )
{
    if( nWheelMode != mnWheelMode )
    {
        mnWheelMode = nWheelMode;

        if( WHEELMODE_NONE == mnWheelMode )
        {
            if( IsVisible() )
                Hide();
        }
        else
        {
            if( !IsVisible() )
                Show();

            ImplDrawWheel();
        }
    }
}

// ------------------------------------------------------------------------

void ImplWheelWindow::ImplDrawWheel()
{
    USHORT nId;

    switch( mnWheelMode )
    {
        case( WHEELMODE_VH ):       nId = 1; break;
        case( WHEELMODE_V    ):     nId = 2; break;
        case( WHEELMODE_H    ):     nId = 3; break;
        case( WHEELMODE_SCROLL_VH ):nId = 4; break;
        case( WHEELMODE_SCROLL_V ): nId = 5; break;
        case( WHEELMODE_SCROLL_H ): nId = 6; break;
        default:                    nId = 0; break;
    }

    if( nId )
        DrawImage( Point(), maImgList.GetImage( nId ) );
}

// ------------------------------------------------------------------------

void ImplWheelWindow::ImplRecalcScrollValues()
{
    if( mnActDist < WHEEL_RADIUS )
    {
        mnActDeltaX = mnActDeltaY = 0L;
        mnTimeout = DEF_TIMEOUT;
    }
    else
    {
        ULONG nCurTime;

        // calc current time
        if( mnMaxWidth )
        {
            const double fExp = ( (double) mnActDist / mnMaxWidth ) * log10( (double) MAX_TIME / MIN_TIME );
            nCurTime = (ULONG) ( MAX_TIME / pow( 10., fExp ) );
        }
        else
            nCurTime = MAX_TIME;

        if( !nCurTime )
            nCurTime = 1UL;

        if( mnRepaintTime <= nCurTime )
            mnTimeout = nCurTime - mnRepaintTime;
        else
        {
            long nMult = mnRepaintTime / nCurTime;

            if( !( mnRepaintTime % nCurTime ) )
                mnTimeout = 0UL;
            else
                mnTimeout = ++nMult * nCurTime - mnRepaintTime;

            double fValX = (double) mnActDeltaX * nMult;
            double fValY = (double) mnActDeltaY * nMult;

            if( fValX > LONG_MAX )
                mnActDeltaX = LONG_MAX;
            else if( fValX < LONG_MIN )
                mnActDeltaX = LONG_MIN;
            else
                mnActDeltaX = (long) fValX;

            if( fValY > LONG_MAX )
                mnActDeltaY = LONG_MAX;
            else if( fValY < LONG_MIN )
                mnActDeltaY = LONG_MIN;
            else
                mnActDeltaY = (long) fValY;
        }
    }
}

// ------------------------------------------------------------------------

PointerStyle ImplWheelWindow::ImplGetMousePointer( long nDistX, long nDistY )
{
    PointerStyle    eStyle;
    const USHORT    nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags;
    const BOOL      bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0;
    const BOOL      bVert = ( nFlags & AUTOSCROLL_VERT ) != 0;

    if( bHorz || bVert )
    {
        if( mnActDist < WHEEL_RADIUS )
        {
            if( bHorz && bVert )
                eStyle = POINTER_AUTOSCROLL_NSWE;
            else if( bHorz )
                eStyle = POINTER_AUTOSCROLL_WE;
            else
                eStyle = POINTER_AUTOSCROLL_NS;
        }
        else
        {
            double fAngle = atan2( (double) -nDistY, nDistX ) / F_PI180;

            if( fAngle < 0.0 )
                fAngle += 360.;

            if( bHorz && bVert )
            {
                if( fAngle >= 22.5 && fAngle <= 67.5 )
                    eStyle = POINTER_AUTOSCROLL_NE;
                else if( fAngle >= 67.5 && fAngle <= 112.5 )
                    eStyle = POINTER_AUTOSCROLL_N;
                else if( fAngle >= 112.5 && fAngle <= 157.5 )
                    eStyle = POINTER_AUTOSCROLL_NW;
                else if( fAngle >= 157.5 && fAngle <= 202.5 )
                    eStyle = POINTER_AUTOSCROLL_W;
                else if( fAngle >= 202.5 && fAngle <= 247.5 )
                    eStyle = POINTER_AUTOSCROLL_SW;
                else if( fAngle >= 247.5 && fAngle <= 292.5 )
                    eStyle = POINTER_AUTOSCROLL_S;
                else if( fAngle >= 292.5 && fAngle <= 337.5 )
                    eStyle = POINTER_AUTOSCROLL_SE;
                else
                    eStyle = POINTER_AUTOSCROLL_E;
            }
            else if( bHorz )
            {
                if( fAngle >= 270. || fAngle <= 90. )
                    eStyle = POINTER_AUTOSCROLL_E;
                else
                    eStyle = POINTER_AUTOSCROLL_W;
            }
            else
            {
                if( fAngle >= 0. && fAngle <= 180. )
                    eStyle = POINTER_AUTOSCROLL_N;
                else
                    eStyle = POINTER_AUTOSCROLL_S;
            }
        }
    }
    else
        eStyle = POINTER_ARROW;

    return eStyle;
}

// ------------------------------------------------------------------------

void ImplWheelWindow::Paint( const Rectangle& )
{
    ImplDrawWheel();
}

// ------------------------------------------------------------------------

void ImplWheelWindow::MouseMove( const MouseEvent& rMEvt )
{
    FloatingWindow::MouseMove( rMEvt );

    const Point aMousePos( OutputToScreenPixel( rMEvt.GetPosPixel() ) );
    const long  nDistX = aMousePos.X() - maCenter.X();
    const long  nDistY = aMousePos.Y() - maCenter.Y();

    mnActDist = (ULONG) hypot( (double) nDistX, nDistY );

    const PointerStyle  eActStyle = ImplGetMousePointer( nDistX, nDistY );
    const USHORT        nFlags = ImplGetSVData()->maWinData.mnAutoScrollFlags;
    const BOOL          bHorz = ( nFlags & AUTOSCROLL_HORZ ) != 0;
    const BOOL          bVert = ( nFlags & AUTOSCROLL_VERT ) != 0;
    const BOOL          bOuter = mnActDist > WHEEL_RADIUS;

    if( bOuter && ( maLastMousePos != aMousePos ) )
    {
        switch( eActStyle )
        {
            case( POINTER_AUTOSCROLL_N ):   mnActDeltaX = +0L, mnActDeltaY = +1L; break;
            case( POINTER_AUTOSCROLL_S ):   mnActDeltaX = +0L, mnActDeltaY = -1L; break;
            case( POINTER_AUTOSCROLL_W ):   mnActDeltaX = +1L, mnActDeltaY = +0L; break;
            case( POINTER_AUTOSCROLL_E ):   mnActDeltaX = -1L, mnActDeltaY = +0L; break;
            case( POINTER_AUTOSCROLL_NW ):  mnActDeltaX = +1L, mnActDeltaY = +1L; break;
            case( POINTER_AUTOSCROLL_NE ):  mnActDeltaX = -1L, mnActDeltaY = +1L; break;
            case( POINTER_AUTOSCROLL_SW ):  mnActDeltaX = +1L, mnActDeltaY = -1L; break;
            case( POINTER_AUTOSCROLL_SE ):  mnActDeltaX = -1L, mnActDeltaY = -1L; break;

            default:
            break;
        }
    }

    ImplRecalcScrollValues();
    maLastMousePos = aMousePos;
    SetPointer( eActStyle );

    if( bHorz && bVert )
        ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_VH : WHEELMODE_VH );
    else if( bHorz )
        ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_H : WHEELMODE_H );
    else
        ImplSetWheelMode( bOuter ? WHEELMODE_SCROLL_V : WHEELMODE_V );
}

// ------------------------------------------------------------------------

void ImplWheelWindow::MouseButtonUp( const MouseEvent& rMEvt )
{
    if( mnActDist > WHEEL_RADIUS )
        GetParent()->EndAutoScroll();
    else
        FloatingWindow::MouseButtonUp( rMEvt );
}

// ------------------------------------------------------------------------

IMPL_LINK( ImplWheelWindow, ImplScrollHdl, Timer*, EMPTYARG )
{
    if ( mnActDeltaX || mnActDeltaY )
    {
        Window*             pWindow = GetParent();
        const Point         aMousePos( pWindow->OutputToScreenPixel( pWindow->GetPointerPosPixel() ) );
        Point               aCmdMousePos( pWindow->ImplFrameToOutput( aMousePos ) );
        CommandScrollData   aScrollData( mnActDeltaX, mnActDeltaY );
        CommandEvent        aCEvt( aCmdMousePos, COMMAND_AUTOSCROLL, TRUE, &aScrollData );
        NotifyEvent         aNCmdEvt( EVENT_COMMAND, pWindow, &aCEvt );

        if ( !ImplCallPreNotify( aNCmdEvt ) )
        {
            const ULONG nTime = Time::GetSystemTicks();
            pWindow->Command( aCEvt );
            mnRepaintTime = Max( Time::GetSystemTicks() - nTime, 1UL );
            ImplRecalcScrollValues();
        }
    }

    if ( mnTimeout != mpTimer->GetTimeout() )
        mpTimer->SetTimeout( mnTimeout );
    mpTimer->Start();

    return 0L;
}
<|endoftext|>


<commit_before><commit_msg>vcl: tabify WindowImpl<commit_after><|endoftext|>


<commit_before>//  Copyright (c) 2013, Facebook, Inc.  All rights reserved.
//  This source code is licensed under the BSD-style license found in the
//  LICENSE file in the root directory of this source tree. An additional grant
//  of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "db/dbformat.h"

#include <stdio.h>
#include "port/port.h"
#include "util/coding.h"
#include "util/perf_context_imp.h"

namespace rocksdb {

uint64_t PackSequenceAndType(uint64_t seq, ValueType t) {
  assert(seq <= kMaxSequenceNumber);
  assert(t <= kValueTypeForSeek);
  return (seq << 8) | t;
}

void UnPackSequenceAndType(uint64_t packed, uint64_t* seq, ValueType* t) {
  *seq = packed >> 8;
  *t = static_cast<ValueType>(packed & 0xff);

  assert(*seq <= kMaxSequenceNumber);
  assert(*t <= kValueTypeForSeek);
}

void AppendInternalKey(std::string* result, const ParsedInternalKey& key) {
  result->append(key.user_key.data(), key.user_key.size());
  PutFixed64(result, PackSequenceAndType(key.sequence, key.type));
}

std::string ParsedInternalKey::DebugString(bool hex) const {
  char buf[50];
  snprintf(buf, sizeof(buf), "' @ %llu : %d",
           (unsigned long long) sequence,
           int(type));
  std::string result = "'";
  result += user_key.ToString(hex);
  result += buf;
  return result;
}

std::string InternalKey::DebugString(bool hex) const {
  std::string result;
  ParsedInternalKey parsed;
  if (ParseInternalKey(rep_, &parsed)) {
    result = parsed.DebugString(hex);
  } else {
    result = "(bad)";
    result.append(EscapeString(rep_));
  }
  return result;
}

const char* InternalKeyComparator::Name() const {
  return name_.c_str();
}

int InternalKeyComparator::Compare(const Slice& akey, const Slice& bkey) const {
  // Order by:
  //    increasing user key (according to user-supplied comparator)
  //    decreasing sequence number
  //    decreasing type (though sequence# should be enough to disambiguate)
  int r = user_comparator_->Compare(ExtractUserKey(akey), ExtractUserKey(bkey));
  PERF_COUNTER_ADD(user_key_comparison_count, 1);
  if (r == 0) {
    const uint64_t anum = DecodeFixed64(akey.data() + akey.size() - 8);
    const uint64_t bnum = DecodeFixed64(bkey.data() + bkey.size() - 8);
    if (anum > bnum) {
      r = -1;
    } else if (anum < bnum) {
      r = +1;
    }
  }
  return r;
}

int InternalKeyComparator::Compare(const ParsedInternalKey& a,
                                   const ParsedInternalKey& b) const {
  // Order by:
  //    increasing user key (according to user-supplied comparator)
  //    decreasing sequence number
  //    decreasing type (though sequence# should be enough to disambiguate)
  int r = user_comparator_->Compare(a.user_key, b.user_key);
  PERF_COUNTER_ADD(user_key_comparison_count, 1);
  if (r == 0) {
    if (a.sequence > b.sequence) {
      r = -1;
    } else if (a.sequence < b.sequence) {
      r = +1;
    } else if (a.type > b.type) {
      r = -1;
    } else if (a.type < b.type) {
      r = +1;
    }
  }
  return r;
}

void InternalKeyComparator::FindShortestSeparator(
      std::string* start,
      const Slice& limit) const {
  // Attempt to shorten the user portion of the key
  Slice user_start = ExtractUserKey(*start);
  Slice user_limit = ExtractUserKey(limit);
  std::string tmp(user_start.data(), user_start.size());
  user_comparator_->FindShortestSeparator(&tmp, user_limit);
  if (tmp.size() < user_start.size() &&
      user_comparator_->Compare(user_start, tmp) < 0) {
    // User key has become shorter physically, but larger logically.
    // Tack on the earliest possible number to the shortened user key.
    PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek));
    assert(this->Compare(*start, tmp) < 0);
    assert(this->Compare(tmp, limit) < 0);
    start->swap(tmp);
  }
}

void InternalKeyComparator::FindShortSuccessor(std::string* key) const {
  Slice user_key = ExtractUserKey(*key);
  std::string tmp(user_key.data(), user_key.size());
  user_comparator_->FindShortSuccessor(&tmp);
  if (tmp.size() < user_key.size() &&
      user_comparator_->Compare(user_key, tmp) < 0) {
    // User key has become shorter physically, but larger logically.
    // Tack on the earliest possible number to the shortened user key.
    PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek));
    assert(this->Compare(*key, tmp) < 0);
    key->swap(tmp);
  }
}

LookupKey::LookupKey(const Slice& _user_key, SequenceNumber s) {
  size_t usize = _user_key.size();
  size_t needed = usize + 13;  // A conservative estimate
  char* dst;
  if (needed <= sizeof(space_)) {
    dst = space_;
  } else {
    dst = new char[needed];
  }
  start_ = dst;
  // NOTE: We don't support users keys of more than 2GB :)
  dst = EncodeVarint32(dst, static_cast<uint32_t>(usize + 8));
  kstart_ = dst;
  memcpy(dst, _user_key.data(), usize);
  dst += usize;
  EncodeFixed64(dst, PackSequenceAndType(s, kValueTypeForSeek));
  dst += 8;
  end_ = dst;
}

}  // namespace rocksdb
<commit_msg>Replace %llu with format macros in ParsedInternalKey::DebugString())<commit_after>//  Copyright (c) 2013, Facebook, Inc.  All rights reserved.
//  This source code is licensed under the BSD-style license found in the
//  LICENSE file in the root directory of this source tree. An additional grant
//  of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "db/dbformat.h"

#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif

#include <inttypes.h>
#include <stdio.h>
#include "port/port.h"
#include "util/coding.h"
#include "util/perf_context_imp.h"

namespace rocksdb {

uint64_t PackSequenceAndType(uint64_t seq, ValueType t) {
  assert(seq <= kMaxSequenceNumber);
  assert(t <= kValueTypeForSeek);
  return (seq << 8) | t;
}

void UnPackSequenceAndType(uint64_t packed, uint64_t* seq, ValueType* t) {
  *seq = packed >> 8;
  *t = static_cast<ValueType>(packed & 0xff);

  assert(*seq <= kMaxSequenceNumber);
  assert(*t <= kValueTypeForSeek);
}

void AppendInternalKey(std::string* result, const ParsedInternalKey& key) {
  result->append(key.user_key.data(), key.user_key.size());
  PutFixed64(result, PackSequenceAndType(key.sequence, key.type));
}

std::string ParsedInternalKey::DebugString(bool hex) const {
  char buf[50];
  snprintf(buf, sizeof(buf), "' @ %" PRIu64 ": %d", sequence,
           static_cast<int>(type));
  std::string result = "'";
  result += user_key.ToString(hex);
  result += buf;
  return result;
}

std::string InternalKey::DebugString(bool hex) const {
  std::string result;
  ParsedInternalKey parsed;
  if (ParseInternalKey(rep_, &parsed)) {
    result = parsed.DebugString(hex);
  } else {
    result = "(bad)";
    result.append(EscapeString(rep_));
  }
  return result;
}

const char* InternalKeyComparator::Name() const {
  return name_.c_str();
}

int InternalKeyComparator::Compare(const Slice& akey, const Slice& bkey) const {
  // Order by:
  //    increasing user key (according to user-supplied comparator)
  //    decreasing sequence number
  //    decreasing type (though sequence# should be enough to disambiguate)
  int r = user_comparator_->Compare(ExtractUserKey(akey), ExtractUserKey(bkey));
  PERF_COUNTER_ADD(user_key_comparison_count, 1);
  if (r == 0) {
    const uint64_t anum = DecodeFixed64(akey.data() + akey.size() - 8);
    const uint64_t bnum = DecodeFixed64(bkey.data() + bkey.size() - 8);
    if (anum > bnum) {
      r = -1;
    } else if (anum < bnum) {
      r = +1;
    }
  }
  return r;
}

int InternalKeyComparator::Compare(const ParsedInternalKey& a,
                                   const ParsedInternalKey& b) const {
  // Order by:
  //    increasing user key (according to user-supplied comparator)
  //    decreasing sequence number
  //    decreasing type (though sequence# should be enough to disambiguate)
  int r = user_comparator_->Compare(a.user_key, b.user_key);
  PERF_COUNTER_ADD(user_key_comparison_count, 1);
  if (r == 0) {
    if (a.sequence > b.sequence) {
      r = -1;
    } else if (a.sequence < b.sequence) {
      r = +1;
    } else if (a.type > b.type) {
      r = -1;
    } else if (a.type < b.type) {
      r = +1;
    }
  }
  return r;
}

void InternalKeyComparator::FindShortestSeparator(
      std::string* start,
      const Slice& limit) const {
  // Attempt to shorten the user portion of the key
  Slice user_start = ExtractUserKey(*start);
  Slice user_limit = ExtractUserKey(limit);
  std::string tmp(user_start.data(), user_start.size());
  user_comparator_->FindShortestSeparator(&tmp, user_limit);
  if (tmp.size() < user_start.size() &&
      user_comparator_->Compare(user_start, tmp) < 0) {
    // User key has become shorter physically, but larger logically.
    // Tack on the earliest possible number to the shortened user key.
    PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek));
    assert(this->Compare(*start, tmp) < 0);
    assert(this->Compare(tmp, limit) < 0);
    start->swap(tmp);
  }
}

void InternalKeyComparator::FindShortSuccessor(std::string* key) const {
  Slice user_key = ExtractUserKey(*key);
  std::string tmp(user_key.data(), user_key.size());
  user_comparator_->FindShortSuccessor(&tmp);
  if (tmp.size() < user_key.size() &&
      user_comparator_->Compare(user_key, tmp) < 0) {
    // User key has become shorter physically, but larger logically.
    // Tack on the earliest possible number to the shortened user key.
    PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek));
    assert(this->Compare(*key, tmp) < 0);
    key->swap(tmp);
  }
}

LookupKey::LookupKey(const Slice& _user_key, SequenceNumber s) {
  size_t usize = _user_key.size();
  size_t needed = usize + 13;  // A conservative estimate
  char* dst;
  if (needed <= sizeof(space_)) {
    dst = space_;
  } else {
    dst = new char[needed];
  }
  start_ = dst;
  // NOTE: We don't support users keys of more than 2GB :)
  dst = EncodeVarint32(dst, static_cast<uint32_t>(usize + 8));
  kstart_ = dst;
  memcpy(dst, _user_key.data(), usize);
  dst += usize;
  EncodeFixed64(dst, PackSequenceAndType(s, kValueTypeForSeek));
  dst += 8;
  end_ = dst;
}

}  // namespace rocksdb
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkTestingObjectFactory.h

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyrgight notice for more information.

=========================================================================*/
#ifndef __vtkTestingObjectFactory_h
#define __vtkTestingObjectFactory_h

// .NAME vtkTestingObjectFactory - Object overrides used during testing
// .SECTION Description
// Some vtk examples and tests need to perform differently when they
// are run as tests versus when they are run as individual
// programs. Many tests/examples are interactive and eventually call
// vtkRenderWindowInteration::Start() to initialie the
// interaction. But, when run as tests, these programs should
// exit. This factory overrides vtkRenderWindowInteractor so that the
// Start() method just returns.
// To use this factory:
// \code
//   #include "vtkTestingObjectFactory.h"
//   vtkTestingObjectFactory* factory = vtkTestingObjectFactory::New();
//   vtkObjectFactory::RegisterFactory(factory);
// \endcode

#include "vtkVersion.h"
#include "vtkObjectFactory.h"

#include "vtkTesting.h"            // Required for testing framework
#include "vtkTestDriver.h"         // Required for testing framework
#include "vtkTestingInteractor.h"  // Required for testing framework
#include "vtkSmartPointer.h"       // Required for testing framework
#include "vtkObjectFactoryCollection.h" // Required for testing framework
#if VTK_MAJOR_VERSION <= 5
class VTK_RENDERING_EXPORT vtkTestingObjectFactory : public vtkObjectFactory
#else
#include "vtkTestingRenderingModule.h" // For export macro
class VTKTESTINGRENDERING_EXPORT vtkTestingObjectFactory : public vtkObjectFactory
#endif
{
public:
#ifndef VTK_OVERRIDE
#define VTK_OVERRIDE
#endif
  static vtkTestingObjectFactory* New();
  vtkTypeMacro(vtkTestingObjectFactory,vtkObjectFactory);
  virtual const char* GetVTKSourceVersion() VTK_OVERRIDE;
  const char* GetDescription() VTK_OVERRIDE { return "Factory for overrides during testing"; }
  void PrintSelf(ostream& os, vtkIndent indent) VTK_OVERRIDE;

protected:
  // Description:
  // Register objects that override vtk objects whem they are run as tests.
  vtkTestingObjectFactory();

private:
  vtkTestingObjectFactory(const vtkTestingObjectFactory&); // Not implemented
  void operator=(const vtkTestingObjectFactory&);          // Not implemented
};
#endif
<commit_msg>STYLE: vtkTestingObjectFactory: Fix typo in comment<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkTestingObjectFactory.h

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyrgight notice for more information.

=========================================================================*/
#ifndef __vtkTestingObjectFactory_h
#define __vtkTestingObjectFactory_h

// .NAME vtkTestingObjectFactory - Object overrides used during testing
// .SECTION Description
// Some vtk examples and tests need to perform differently when they
// are run as tests versus when they are run as individual
// programs. Many tests/examples are interactive and eventually call
// vtkRenderWindowInteration::Start() to initialize the
// interaction. But, when run as tests, these programs should
// exit. This factory overrides vtkRenderWindowInteractor so that the
// Start() method just returns.
// To use this factory:
// \code
//   #include "vtkTestingObjectFactory.h"
//   vtkTestingObjectFactory* factory = vtkTestingObjectFactory::New();
//   vtkObjectFactory::RegisterFactory(factory);
// \endcode

#include "vtkVersion.h"
#include "vtkObjectFactory.h"

#include "vtkTesting.h"            // Required for testing framework
#include "vtkTestDriver.h"         // Required for testing framework
#include "vtkTestingInteractor.h"  // Required for testing framework
#include "vtkSmartPointer.h"       // Required for testing framework
#include "vtkObjectFactoryCollection.h" // Required for testing framework
#if VTK_MAJOR_VERSION <= 5
class VTK_RENDERING_EXPORT vtkTestingObjectFactory : public vtkObjectFactory
#else
#include "vtkTestingRenderingModule.h" // For export macro
class VTKTESTINGRENDERING_EXPORT vtkTestingObjectFactory : public vtkObjectFactory
#endif
{
public:
#ifndef VTK_OVERRIDE
#define VTK_OVERRIDE
#endif
  static vtkTestingObjectFactory* New();
  vtkTypeMacro(vtkTestingObjectFactory,vtkObjectFactory);
  virtual const char* GetVTKSourceVersion() VTK_OVERRIDE;
  const char* GetDescription() VTK_OVERRIDE { return "Factory for overrides during testing"; }
  void PrintSelf(ostream& os, vtkIndent indent) VTK_OVERRIDE;

protected:
  // Description:
  // Register objects that override vtk objects whem they are run as tests.
  vtkTestingObjectFactory();

private:
  vtkTestingObjectFactory(const vtkTestingObjectFactory&); // Not implemented
  void operator=(const vtkTestingObjectFactory&);          // Not implemented
};
#endif
<|endoftext|>


<commit_before>// $Id$
//
// Task to setup emcal related global objects.
//
// Author: C.Loizides

#include "AliEmcalSetupTask.h"
#include <TClonesArray.h>
#include <TGeoGlobalMagField.h>
#include <TGeoManager.h>
#include "AliAODEvent.h"
#include "AliAnalysisManager.h"
#include "AliCDBManager.h"
#include "AliEMCALGeometry.h"
#include "AliESDEvent.h"
#include "AliGeomManager.h"
#include "AliMagF.h"
#include "AliOADBContainer.h"

ClassImp(AliEmcalSetupTask)

//________________________________________________________________________
AliEmcalSetupTask::AliEmcalSetupTask() :
  AliAnalysisTaskSE(),
  fOcdbPath(),
  fOadbPath("$ALICE_ROOT/OADB/EMCAL"),
  fGeoPath("."),
  fIsInit(kFALSE)
{
  // Constructor.
}

//________________________________________________________________________
AliEmcalSetupTask::AliEmcalSetupTask(const char *name) :
  AliAnalysisTaskSE(name),
  fOcdbPath(),
  fOadbPath("$ALICE_ROOT/OADB/EMCAL"),
  fGeoPath("$ALICE_ROOT/OADB/EMCAL"),
  fIsInit(kFALSE)
{
  // Constructor.
  fBranchNames = "ESD:AliESDHeader.,AliESDRun.";
}

//________________________________________________________________________
AliEmcalSetupTask::~AliEmcalSetupTask()
{
  // Destructor.
}

//________________________________________________________________________
void AliEmcalSetupTask::UserExec(Option_t *)
{
  // Main loop, called for each event.

  if (fIsInit)
    return;

  AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();
  if (!am) {
    AliError("Manager zero, returning");
    return;
  }
  am->LoadBranch("AliESDRun.");
  am->LoadBranch("AliESDHeader.");

  Int_t runno = InputEvent()->GetRunNumber();
  TString geoname("EMCAL_COMPLETE12SMV1");
  Int_t year = 2013;
  if (runno<=139517) {
    year = 2010;
    geoname = "EMCAL_FIRSTYEARV1";
  } else if ((runno>139517) && (runno<=170593)) {
    year = 2011;
    geoname = "EMCAL_COMPLETEV1";
  } else if ((runno>170593) && (runno<=193766)) {
    year = 2012;
  }

  AliEMCALGeometry *geom = AliEMCALGeometry::GetInstance(geoname);
  if (!geom) {
    AliFatal(Form("Can not create geometry: %s",geoname.Data()));
    return;
  }

  AliCDBManager *man = 0;
  if (fOcdbPath.Length()>0) {
    AliInfo(Form("Setting up OCDB"));
    man = AliCDBManager::Instance();
    man->SetDefaultStorage(fOcdbPath);
    man->SetRun(runno);
  }

  TGeoManager *geo = AliGeomManager::GetGeometry();
  if (!geo) {
    TString fname(gSystem->ExpandPathName(Form("%s/geometry_%d.root", fGeoPath.Data(), year)));
    if (gSystem->AccessPathName(fname)==0) {
      AliInfo(Form("Loading geometry from %s", fname.Data()));
      AliGeomManager::LoadGeometry(fname);
    } else if (man) {
      AliInfo(Form("Loading geometry from OCDB"));
      AliGeomManager::LoadGeometry();
    }
  }
  if (geo) {
    AliGeomManager::ApplyAlignObjsFromCDB("EMCAL");
    AliInfo(Form("Locking geometry"));
    geo->LockGeometry();
  }

  if (!TGeoGlobalMagField::Instance()->GetField()) { // construct field map
    InputEvent()->InitMagneticField();
  }

  if (fOadbPath.Length()>0) {
    AliOADBContainer emcalgeoCont(Form("emcal"));
    emcalgeoCont.InitFromFile(Form("%s/EMCALlocal2master.root",fOadbPath.Data()),
                              Form("AliEMCALgeo"));
    TObjArray *mobj=dynamic_cast<TObjArray*>(emcalgeoCont.GetObject(runno,"EmcalMatrices"));
    if (mobj) {
      for(Int_t mod=0; mod < (geom->GetEMCGeometry())->GetNumberOfSuperModules(); mod++){
        //AliInfo(Form("Misalignment matrix %d", mod));
        geom->SetMisalMatrix((TGeoHMatrix*) mobj->At(mod),mod);
      }
    }
  }

  fIsInit = kTRUE;
}
<commit_msg>Apply alignment consistently<commit_after>// $Id$
//
// Task to setup emcal related global objects.
//
// Author: C.Loizides

#include "AliEmcalSetupTask.h"
#include <TClonesArray.h>
#include <TGeoGlobalMagField.h>
#include <TGeoManager.h>
#include "AliAODEvent.h"
#include "AliAnalysisManager.h"
#include "AliCDBManager.h"
#include "AliEMCALGeometry.h"
#include "AliESDEvent.h"
#include "AliGeomManager.h"
#include "AliMagF.h"
#include "AliOADBContainer.h"

ClassImp(AliEmcalSetupTask)

//________________________________________________________________________
AliEmcalSetupTask::AliEmcalSetupTask() :
  AliAnalysisTaskSE(),
  fOcdbPath(),
  fOadbPath("$ALICE_ROOT/OADB/EMCAL"),
  fGeoPath("."),
  fIsInit(kFALSE)
{
  // Constructor.
}

//________________________________________________________________________
AliEmcalSetupTask::AliEmcalSetupTask(const char *name) :
  AliAnalysisTaskSE(name),
  fOcdbPath(),
  fOadbPath("$ALICE_ROOT/OADB/EMCAL"),
  fGeoPath("$ALICE_ROOT/OADB/EMCAL"),
  fIsInit(kFALSE)
{
  // Constructor.
  fBranchNames = "ESD:AliESDHeader.,AliESDRun.";
}

//________________________________________________________________________
AliEmcalSetupTask::~AliEmcalSetupTask()
{
  // Destructor.
}

//________________________________________________________________________
void AliEmcalSetupTask::UserExec(Option_t *)
{
  // Main loop, called for each event.

  if (fIsInit)
    return;

  AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager();
  if (!am) {
    AliError("Manager zero, returning");
    return;
  }
  am->LoadBranch("AliESDRun.");
  am->LoadBranch("AliESDHeader.");

  Int_t runno = InputEvent()->GetRunNumber();
  TString geoname("EMCAL_COMPLETE12SMV1");
  Int_t year = 2013;
  if (runno<=139517) {
    year = 2010;
    geoname = "EMCAL_FIRSTYEARV1";
  } else if ((runno>139517) && (runno<=170593)) {
    year = 2011;
    geoname = "EMCAL_COMPLETEV1";
  } else if ((runno>170593) && (runno<=193766)) {
    year = 2012;
  }

  AliEMCALGeometry *geom = AliEMCALGeometry::GetInstance(geoname);
  if (!geom) {
    AliFatal(Form("Can not create geometry: %s",geoname.Data()));
    return;
  }

  AliCDBManager *man = 0;
  if (fOcdbPath.Length()>0) {
    AliInfo(Form("Setting up OCDB"));
    man = AliCDBManager::Instance();
    if (!man->IsDefaultStorageSet())
      man->SetDefaultStorage(fOcdbPath);
    if (man->GetRun()!=runno)
      man->SetRun(runno);
  }

  TGeoManager *geo = AliGeomManager::GetGeometry();
  if (!geo) {
    TString fname(gSystem->ExpandPathName(Form("%s/geometry_%d.root", fGeoPath.Data(), year)));
    if (gSystem->AccessPathName(fname)==0) {
      AliInfo(Form("Loading geometry from %s", fname.Data()));
      AliGeomManager::LoadGeometry(fname);
    } else if (man) {
      AliInfo(Form("Loading geometry from OCDB"));
      AliGeomManager::LoadGeometry();
    }
    geo = AliGeomManager::GetGeometry();
  }
  if (geo) {
    AliGeomManager::ApplyAlignObjsFromCDB("EMCAL");
    AliInfo(Form("Locking geometry"));
    geo->LockGeometry();
  }

  if (!TGeoGlobalMagField::Instance()->GetField()) { // construct field map
    InputEvent()->InitMagneticField();
  }

  if (fOadbPath.Length()>0) {
    AliOADBContainer emcalgeoCont(Form("emcal"));
    emcalgeoCont.InitFromFile(Form("%s/EMCALlocal2master.root",fOadbPath.Data()),
                              Form("AliEMCALgeo"));
    TObjArray *mobj=dynamic_cast<TObjArray*>(emcalgeoCont.GetObject(runno,"EmcalMatrices"));
    if (mobj) {
      for(Int_t mod=0; mod < (geom->GetEMCGeometry())->GetNumberOfSuperModules(); mod++){
        //AliInfo(Form("Misalignment matrix %d", mod));
        geom->SetMisalMatrix((TGeoHMatrix*) mobj->At(mod),mod);
      }
    }
  }

  fIsInit = kTRUE;
}
<|endoftext|>


<commit_before>#if ! defined (__CINT__) || defined (__MAKECINT__)
#include "AliLog.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "PWG1/TRD/AliTRDinfoGen.h"
#include "PWG1/TRD/AliTRDpwg1Helper.h"
#include "PWG1/TRD/info/AliTRDeventInfo.h"
#endif

void AddTRDinfoGen(AliAnalysisManager *mgr, Int_t /*map*/, AliAnalysisDataContainer **/*ci*/, AliAnalysisDataContainer **co)
{
  Bool_t mc=mgr->GetMCtruthEventHandler();
  //AliLog::SetClassDebugLevel("AliTRDinfoGen", 2);
  AliTRDinfoGen *info(NULL);
  mgr->AddTask(info = new AliTRDinfoGen((char*)"TRDinfoGen"));
  info->SetDebugLevel(0);
  info->SetMCdata(mc);
  info->SetLocalTrkSelection();
  info->SetOCDB("alien://folder=/alice/data/2010/OCDB");
  // settings for collisions
  info->SetCollision(/*kFALSE*/);
  if(info->IsCollision()){
    if(!mc) info->SetTrigger(
      "CINT1B-ABCE-NOPF-ALL"
      " CINT5-B-NOPF-ALL"
      " CINT1WU-B-NOPF-ALL"
      " CINT5WU-B-NOPF-ALL"
      " CSCO1-ABCE-NOPF-CENT" // cosmic SPD trigger
    );
    info->SetLocalEvSelection();
  }

  // Connect IO slots
  mgr->ConnectInput (info, 0, mgr->GetCommonInputContainer());
  co[AliTRDpwg1Helper::kEventInfo] = mgr->CreateContainer("eventInfo", AliTRDeventInfo::Class(), AliAnalysisManager::kExchangeContainer);
  co[AliTRDpwg1Helper::kTracksBarrel] = mgr->CreateContainer("tracksBarrel", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
  co[AliTRDpwg1Helper::kTracksSA] = mgr->CreateContainer("tracksSA", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
  co[AliTRDpwg1Helper::kTracksKink] = mgr->CreateContainer("tracksKink", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
  co[AliTRDpwg1Helper::kV0List] = mgr->CreateContainer("v0List", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
  for(Int_t ios(1);ios<AliTRDpwg1Helper::kNOutSlots-1;ios++) mgr->ConnectOutput(info, ios, co[ios]);

  // add last monitor container
  AliAnalysisDataContainer *mon=mgr->CreateContainer(info->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("%s:TRD_Performance",mgr->GetCommonFileName()));
  mgr->ConnectOutput(info, AliTRDpwg1Helper::kNOutSlots-1, mon);
}

<commit_msg>switch off triggers (Markus Fasel)<commit_after>#if ! defined (__CINT__) || defined (__MAKECINT__)
#include "AliLog.h"
#include "AliAnalysisManager.h"
#include "AliAnalysisDataContainer.h"
#include "PWG1/TRD/AliTRDinfoGen.h"
#include "PWG1/TRD/AliTRDpwg1Helper.h"
#include "PWG1/TRD/info/AliTRDeventInfo.h"
#endif

void AddTRDinfoGen(AliAnalysisManager *mgr, Int_t /*map*/, AliAnalysisDataContainer **/*ci*/, AliAnalysisDataContainer **co)
{
  Bool_t mc=mgr->GetMCtruthEventHandler();
  //AliLog::SetClassDebugLevel("AliTRDinfoGen", 2);
  AliTRDinfoGen *info(NULL);
  mgr->AddTask(info = new AliTRDinfoGen((char*)"TRDinfoGen"));
  info->SetDebugLevel(0);
  info->SetMCdata(mc);
  info->SetLocalTrkSelection();
  info->SetOCDB("alien://folder=/alice/data/2010/OCDB");
  // settings for collisions
  info->SetCollision(/*kFALSE*/);
  if(info->IsCollision()){
    /*
    if(!mc) info->SetTrigger(
      "CINT1B-ABCE-NOPF-ALL"
      " CINT5-B-NOPF-ALL"
      " CINT1WU-B-NOPF-ALL"
      " CINT5WU-B-NOPF-ALL"
      " CSCO1-ABCE-NOPF-CENT" // cosmic SPD trigger
    );
    */
    info->SetLocalEvSelection();
  }

  // Connect IO slots
  mgr->ConnectInput (info, 0, mgr->GetCommonInputContainer());
  co[AliTRDpwg1Helper::kEventInfo] = mgr->CreateContainer("eventInfo", AliTRDeventInfo::Class(), AliAnalysisManager::kExchangeContainer);
  co[AliTRDpwg1Helper::kTracksBarrel] = mgr->CreateContainer("tracksBarrel", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
  co[AliTRDpwg1Helper::kTracksSA] = mgr->CreateContainer("tracksSA", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
  co[AliTRDpwg1Helper::kTracksKink] = mgr->CreateContainer("tracksKink", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
  co[AliTRDpwg1Helper::kV0List] = mgr->CreateContainer("v0List", TObjArray::Class(), AliAnalysisManager::kExchangeContainer);
  for(Int_t ios(1);ios<AliTRDpwg1Helper::kNOutSlots-1;ios++) mgr->ConnectOutput(info, ios, co[ios]);

  // add last monitor container
  AliAnalysisDataContainer *mon=mgr->CreateContainer(info->GetName(), TObjArray::Class(), AliAnalysisManager::kOutputContainer, Form("%s:TRD_Performance",mgr->GetCommonFileName()));
  mgr->ConnectOutput(info, AliTRDpwg1Helper::kNOutSlots-1, mon);
}

<|endoftext|>


<commit_before>#ifndef NKLIB_MAKE_UNIQUE_HPP__
#define NKLIB_MAKE_UNIQUE_HPP__

// STL's implementation from N3656.  Part of C++14.

#include <memory>
#include <type_traits>
#include <utility>

namespace nk {

template <typename T, typename... Args>
std::unique_ptr<T> make_unique_helper(std::false_type, Args&&... args)
{
    return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}

template <typename T, typename... Args>
std::unique_ptr<T> make_unique_helper(std::true_type, Args&&... args)
{
    static_assert(std::extent<T>::value == 0,
                  "make_unique<T[N]>() is forbidden, please use make_unique<T[]>().");
    typedef typename std::remove_extent<T>::type U;
    return std::unique_ptr<T>(new U[sizeof...(Args)]{std::forward<Args>(args)...});
}

template <typename T, typename... Args> std::unique_ptr<T>
make_unique(Args&&... args)
{
    return make_unique_helper<T>(std::is_array<T>(), std::forward<Args>(args)...);
}

}

#endif /* NKLIB_MAKE_UNIQUE_HPP__ */
<commit_msg>Remove make_unique.hpp; it's integrated in C++14 stdlib.<commit_after><|endoftext|>