<commit_before>// $Id$

AliAnalysisTaskSE* AddTaskJetPreparation(
  const char*    dataType           = "ESD",
  const char*    periodstr          = "LHC11h",
  const char*    usedTracks         = "PicoTracks",
  const char*    usedMCParticles    = "MCParticlesSelected",
  const char*    usedClusters       = "CaloClusters",
  const char*    outClusName        = "CaloClustersCorr",
  const Double_t hadcorr            = 2.0,
  const Double_t Eexcl              = 0.00,
  const Double_t phiMatch           = 0.03,
  const Double_t etaMatch           = 0.015,
  const Double_t minPtEt            = 0.15,
  const UInt_t   pSel               = AliVEvent::kAny,
  const Bool_t   trackclus          = kTRUE,
  const Bool_t   doHistos           = kFALSE,
  const Bool_t   makePicoTracks     = kTRUE,
  const Bool_t   makeTrigger        = kTRUE,
  const Bool_t   isEmcalTrain       = kFALSE,
  const Double_t trackeff           = 1.0,
  const Bool_t   doAODTrackProp     = kFALSE,
  const Bool_t   useTrackPropTask   = kTRUE
)
{
  // Add task macros for all jet related helper tasks.

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
  {
    Error("AddTaskJetPreparation","No analysis manager found.");
    return 0;
  }

  // Set trackcuts according to period. Every period used should be definied here
  TString period(periodstr);
  TString clusterColName(usedClusters);
  TString particleColName(usedMCParticles);
  TString dType(dataType);

  if ((dType == "AOD") && (clusterColName == "CaloClusters"))
    clusterColName = "caloClusters";
  if ((dType == "ESD") && (clusterColName == "caloClusters"))
    clusterColName = "CaloClusters";

  if (makePicoTracks && (dType == "ESD" || dType == "AOD") )
  {
    TString inputTracks = "tracks";

    if (dType == "ESD")
    {
      inputTracks = "HybridTracks";
      TString trackCuts(Form("Hybrid_%s", period.Data()));
      // Hybrid tracks maker for ESD
      gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalEsdTpcTrack.C");
      AliEmcalEsdTpcTrackTask *hybTask = AddTaskEmcalEsdTpcTrack(inputTracks.Data(),trackCuts.Data());
      hybTask->SelectCollisionCandidates(pSel);

      if(useTrackPropTask) {
	// Track propagator to extend track to the TPC boundaries
	gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalTrackPropagator.C");
	AliEmcalTrackPropagatorTask *propTask = AddTaskEmcalTrackPropagator(inputTracks.Data(),440.);
	propTask->SelectCollisionCandidates(pSel);
      }
      else
	hybTask->SetDoPropagation(kTRUE);
    }
    if(dType == "AOD" && doAODTrackProp) {
      // Track propagator to extend track to the EMCal surface
      gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalTrackPropagatorAOD.C");
      AliEmcalTrackPropagatorTaskAOD *propTask = AddTaskEmcalTrackPropagatorAOD(inputTracks.Data(),440.);
      propTask->SelectCollisionCandidates(pSel);
    }

    // Produce PicoTracks
    gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalPicoTrackMaker.C");
    AliEmcalPicoTrackMaker *pTrackTask = AddTaskEmcalPicoTrackMaker("PicoTracks", inputTracks.Data(), period.Data());
    pTrackTask->SelectCollisionCandidates(pSel);
    pTrackTask->SetTrackEfficiency(trackeff);
  }

  // Produce particles used for hadronic correction
  gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalParticleMaker.C");
  AliEmcalParticleMaker *emcalParts = AddTaskEmcalParticleMaker(usedTracks,clusterColName.Data(),"EmcalTracks","EmcalClusters");
  emcalParts->SelectCollisionCandidates(pSel);

  // Trigger maker
  if (makeTrigger) {
    gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalTriggerMaker.C");
    AliEmcalTriggerMaker *emcalTriggers = AddTaskEmcalTriggerMaker("EmcalTriggers");
    emcalTriggers->SelectCollisionCandidates(pSel);
  }

  // Relate tracks and clusters
  gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalClusTrackMatcher.C");
  AliEmcalClusTrackMatcherTask *emcalClus =  AddTaskEmcalClusTrackMatcher("EmcalTracks","EmcalClusters",0.1);
  emcalClus->SelectCollisionCandidates(pSel);
  if (isEmcalTrain)
    RequestMemory(emcalClus,100*1024);

  gROOT->LoadMacro("$ALICE_ROOT/PWGJE/EMCALJetTasks/macros/AddTaskHadCorr.C");
  AliHadCorrTask *hCorr = AddTaskHadCorr("EmcalTracks","EmcalClusters",outClusName,hadcorr,minPtEt,phiMatch,etaMatch,Eexcl,trackclus,doHistos);
  hCorr->SelectCollisionCandidates(pSel);

  if (isEmcalTrain) {
    if (doHistos)
      RequestMemory(hCorr,500*1024);
  }

  // Produce MC particles
  if(particleColName != "")
  {
    gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskMCTrackSelector.C");
    AliEmcalMCTrackSelector *mcPartTask = AddTaskMCTrackSelector(particleColName.Data(), kFALSE, kFALSE);
    mcPartTask->SelectCollisionCandidates(pSel);
  }

  // Return one task that represents the jet preparation on LEGO trains
  return emcalParts;
}
<commit_msg>adjust jet preparation<commit_after>// $Id$

AliAnalysisTaskSE* AddTaskJetPreparation(
  const char*    dataType           = "ESD",
  const char*    periodstr          = "LHC11h",
  const char*    usedTracks         = "PicoTracks",
  const char*    usedMCParticles    = "MCParticlesSelected",
  const char*    usedClusters       = "CaloClusters",
  const char*    outClusName        = "CaloClustersCorr",
  const Double_t hadcorr            = 2.0,
  const Double_t Eexcl              = 0.00,
  const Double_t phiMatch           = 0.03,
  const Double_t etaMatch           = 0.015,
  const Double_t minPtEt            = 0.15,
  const UInt_t   pSel               = AliVEvent::kAny,
  const Bool_t   trackclus          = kTRUE,
  const Bool_t   doHistos           = kFALSE,
  const Bool_t   makePicoTracks     = kTRUE,
  const Bool_t   makeTrigger        = kTRUE,
  const Bool_t   isEmcalTrain       = kFALSE,
  const Double_t trackeff           = 1.0,
  const Bool_t   doAODTrackProp     = kFALSE
)
{
  // Add task macros for all jet related helper tasks.

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr)
  {
    Error("AddTaskJetPreparation","No analysis manager found.");
    return 0;
  }

  // Set trackcuts according to period. Every period used should be definied here
  TString period(periodstr);
  TString clusterColName(usedClusters);
  TString particleColName(usedMCParticles);
  TString dType(dataType);

  if ((dType == "AOD") && (clusterColName == "CaloClusters"))
    clusterColName = "caloClusters";
  if ((dType == "ESD") && (clusterColName == "caloClusters"))
    clusterColName = "CaloClusters";

  if (makePicoTracks && (dType == "ESD" || dType == "AOD") )
  {
    TString inputTracks = "tracks";

    if (dType == "ESD")
    {
      inputTracks = "HybridTracks";
      TString trackCuts(Form("Hybrid_%s", period.Data()));
      // Hybrid tracks maker for ESD
      gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalEsdTrackFilter.C");
      AliEmcalEsdTrackFilterTask *hybTask = AddTaskEmcalEsdTrackFilter(inputTracks.Data(),trackCuts.Data());
      hybTask->SelectCollisionCandidates(pSel);
      hybTask->SetDoPropagation(kTRUE);
    }
    if(dType == "AOD" && doAODTrackProp) {
      // Track propagator to extend track to the EMCal surface
      gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalTrackPropagatorAOD.C");
      AliEmcalTrackPropagatorTaskAOD *propTask = AddTaskEmcalTrackPropagatorAOD(inputTracks.Data(),440.);
      propTask->SelectCollisionCandidates(pSel);
    }

    // Produce PicoTracks
    gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalPicoTrackMaker.C");
    AliEmcalPicoTrackMaker *pTrackTask = AddTaskEmcalPicoTrackMaker("PicoTracks", inputTracks.Data(), period.Data());
    pTrackTask->SelectCollisionCandidates(pSel);
    pTrackTask->SetTrackEfficiency(trackeff);
  }

  // Produce particles used for hadronic correction
  gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalParticleMaker.C");
  AliEmcalParticleMaker *emcalParts = AddTaskEmcalParticleMaker(usedTracks,clusterColName.Data(),"EmcalTracks","EmcalClusters");
  emcalParts->SelectCollisionCandidates(pSel);

  // Trigger maker
  if (makeTrigger) {
    gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalTriggerMaker.C");
    AliEmcalTriggerMaker *emcalTriggers = AddTaskEmcalTriggerMaker("EmcalTriggers");
    emcalTriggers->SelectCollisionCandidates(pSel);
  }

  // Relate tracks and clusters
  gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskEmcalClusTrackMatcher.C");
  AliEmcalClusTrackMatcherTask *emcalClus =  AddTaskEmcalClusTrackMatcher("EmcalTracks","EmcalClusters",0.1);
  emcalClus->SelectCollisionCandidates(pSel);
  if (isEmcalTrain)
    RequestMemory(emcalClus,100*1024);

  gROOT->LoadMacro("$ALICE_ROOT/PWGJE/EMCALJetTasks/macros/AddTaskHadCorr.C");
  AliHadCorrTask *hCorr = AddTaskHadCorr("EmcalTracks","EmcalClusters",outClusName,hadcorr,minPtEt,phiMatch,etaMatch,Eexcl,trackclus,doHistos);
  hCorr->SelectCollisionCandidates(pSel);

  if (isEmcalTrain) {
    if (doHistos)
      RequestMemory(hCorr,500*1024);
  }

  // Produce MC particles
  if(particleColName != "")
  {
    gROOT->LoadMacro("$ALICE_ROOT/PWG/EMCAL/macros/AddTaskMCTrackSelector.C");
    AliEmcalMCTrackSelector *mcPartTask = AddTaskMCTrackSelector(particleColName.Data(), kFALSE, kFALSE);
    mcPartTask->SelectCollisionCandidates(pSel);
  }

  // Return one task that represents the jet preparation on LEGO trains
  return emcalParts;
}
<|endoftext|>


<commit_before>// Extra traits to support u64 and s64 until that patch is applied to the
// Armadillo sources.

#if ARMA_VERSION_MAJOR > 2 || \
    (ARMA_VERSION_MAJOR == 1 && ARMA_VERSION_MINOR <= 2)
// For old Armadillo versions ( <= 1.2.0 ), all we have to do is define these
// two structs which say these element types are supported.
template<> struct isnt_supported_elem_type< u64 >                  : public isnt_supported_elem_type_false {};
template<> struct isnt_supported_elem_type< s64 >                  : public isnt_supported_elem_type_false {};

#else
// For new Armadillo versions ( > 1.2.0 ) we have to get a little bit more
// tricky.  We will overload the values for the is_supported_elem_type
// structure, allowing us to redefine it to report success for u64s and s64s.
template<>
struct is_supported_elem_type<u64>
  {
  static const bool value = true;
  };

template<>
struct is_supported_elem_type<s64>
  {
  static const bool value = true;
  };
#endif
<commit_msg>Bank error in your favor.  Collect $100.<commit_after>// Extra traits to support u64 and s64 until that patch is applied to the
// Armadillo sources.

#if ARMA_VERSION_MAJOR < 1 || \
    (ARMA_VERSION_MAJOR == 1 && ARMA_VERSION_MINOR <= 2)
// For old Armadillo versions ( <= 1.2.0 ), all we have to do is define these
// two structs which say these element types are supported.
template<> struct isnt_supported_elem_type< u64 >                  : public isnt_supported_elem_type_false {};
template<> struct isnt_supported_elem_type< s64 >                  : public isnt_supported_elem_type_false {};

#else
// For new Armadillo versions ( > 1.2.0 ) we have to get a little bit more
// tricky.  We will overload the values for the is_supported_elem_type
// structure, allowing us to redefine it to report success for u64s and s64s.
template<>
struct is_supported_elem_type<u64>
  {
  static const bool value = true;
  };

template<>
struct is_supported_elem_type<s64>
  {
  static const bool value = true;
  };
#endif
<|endoftext|>


<commit_before>/*******************************************************************************
* Copyright 2018 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/

#pragma once

#include <string>
#include <vector>

#include "ngraph/node.hpp"
#include "ngraph/runtime/cpu/cpu_external_function.hpp"
#include "ngraph/runtime/cpu/cpu_tensor_view_wrapper.hpp"

#define BUILDER_DECL(op_name)                                                                      \
    build<op_name>(CPU_ExternalFunction * external_function,                                       \
                   const ngraph::Node* node,                                                       \
                   const std::vector<TensorViewWrapper>& args,                                     \
                   const std::vector<TensorViewWrapper>& out)

// Per-type kernel macro
#define SELECT_KERNEL(KV, ET, K)                                                                   \
    if (ET == element::boolean)                                                                    \
    {                                                                                \
        KV = K<char>;                                                                              \
    }                                                                                \
    else if (ET == element::f32)                                                                   \
    {                                                                                \
        KV = K<float>;                                                                             \
    }                                                                                \
    else if (ET == element::f64)                                                                   \
    {                                                                                \
        KV = K<double>;                                                                            \
    }                                                                                \
    else if (ET == element::i8)                                                                    \
    {                                                                                \
        KV = K<int8_t>;                                                                            \
    }                                                                                \
    else if (ET == element::i16)                                                                   \
    {                                                                                \
        KV = K<int16_t>;                                                                           \
    }                                                                                \
    else if (ET == element::i32)                                                                   \
    {                                                                                \
        KV = K<int32_t>;                                                                           \
    }                                                                                \
    else if (ET == element::i64)                                                                   \
    {                                                                                \
        KV = K<int64_t>;                                                                           \
    }                                                                                \
    else if (ET == element::u8)                                                                    \
    {                                                                                \
        KV = K<uint8_t>;                                                                           \
    }                                                                                \
    else if (ET == element::u16)                                                                   \
    {                                                                                \
        KV = K<uint16_t>;                                                                          \
    }                                                                                \
    else if (ET == element::u32)                                                                   \
    {                                                                                \
        KV = K<uint32_t>;                                                                          \
    }                                                                                \
    else if (ET == element::u64)                                                                   \
    {                                                                                \
        KV = K<uint64_t>;                                                                          \
    }

#define SELECT_RANK(KV, ET, R, K)                                                                  \
    if (R == 1)                                                                                \
        KV = K<ET, 1>;                                                                             \
    else if (R == 2)                                                                               \
        KV = K<ET, 2>;                                                                             \
    else if (R == 3)                                                                               \
        KV = K<ET, 3>;                                                                             \
    else if (R == 4)                                                                               \
        KV = K<ET, 4>;                                                                             \
    else if (R == 5)                                                                               \
        KV = K<ET, 5>;                                                                             \
    else if (R == 6)                                                                               \
        KV = K<ET, 6>;                                                                             \
    else if (R == 7)                                                                               \
        KV = K<ET, 7>;                                                                             \
    else if (R == 8)                                                                               \
        KV = K<ET, 8>;                                                                             \
    else if (R == 9)                                                                               \
        KV = K<ET, 9>;                                                                             \
    else if (R == 10)                                                                              \
        KV = K<ET, 10>;                                                                            \
    else if (R == 11)                                                                              \
        KV = K<ET, 11>;                                                                            \
    else if (R == 12)                                                                              \
        KV = K<ET, 12>;                                                                            \
    else if (R == 13)                                                                              \
        KV = K<ET, 13>;                                                                            \
    else if (R == 14)                                                                              \
        KV = K<ET, 14>;                                                                            \
    else if (R == 15)                                                                              \
        KV = K<ET, 15>;                                                                            \
    else if (R == 16)                                                                              \
        KV = K<ET, 16>;                                                                            \
    else                                                                                \
        throw ngraph_error("Unsupported rank " + std::to_string(R) + " for kernel " #K);

// Per-type and rank kernel macro
#define SELECT_KERNEL_BY_RANK(KV, ET, R, K)                                                        \
    if (ET == element::boolean)                                                                    \
    {                                                                                \
        SELECT_RANK(KV, char, R, K);                                                               \
    }                                                                                \
    else if (ET == element::f32)                                                                   \
    {                                                                                \
        SELECT_RANK(KV, float, R, K);                                                              \
    }                                                                                \
    else if (ET == element::f64)                                                                   \
    {                                                                                \
        SELECT_RANK(KV, double, R, K);                                                             \
    }                                                                                \
    else if (ET == element::i8)                                                                    \
    {                                                                                \
        SELECT_RANK(KV, int8_t, R, K);                                                             \
    }                                                                                \
    else if (ET == element::i16)                                                                   \
    {                                                                                \
        SELECT_RANK(KV, int16_t, R, K);                                                            \
    }                                                                                \
    else if (ET == element::i32)                                                                   \
    {                                                                                \
        SELECT_RANK(KV, int32_t, R, K);                                                            \
    }                                                                                \
    else if (ET == element::i64)                                                                   \
    {                                                                                \
        SELECT_RANK(KV, int64_t, R, K);                                                            \
    }                                                                                \
    else if (ET == element::u8)                                                                    \
    {                                                                                \
        SELECT_RANK(KV, uint8_t, R, K);                                                            \
    }                                                                                \
    else if (ET == element::u16)                                                                   \
    {                                                                                \
        SELECT_RANK(KV, uint16_t, R, K);                                                           \
    }                                                                                \
    else if (ET == element::u32)                                                                   \
    {                                                                                \
        SELECT_RANK(KV, uint32_t, R, K);                                                           \
    }                                                                                \
    else if (ET == element::u64)                                                                   \
    {                                                                                \
        SELECT_RANK(KV, uint64_t, R, K);                                                           \
    }                                                                                \
    else                                                                                \
    {                                                                                \
        throw ngraph_error("Unsupported element type " + ET.c_type_string() + " for kernel " #K);  \
    }

// Helper macros for a partial set of element types and ranks
// Useful for keeping compilation time and memory usage reasonable
// when the computed expression is complex

#define PARTIAL_SELECT_RANK(KV, ET, R, K)                                                          \
    if (R == 1)                                                                                \
        KV = K<ET, 1>;                                                                             \
    else if (R == 2)                                                                               \
        KV = K<ET, 2>;                                                                             \
    else if (R == 3)                                                                               \
        KV = K<ET, 3>;                                                                             \
    else if (R == 4)                                                                               \
        KV = K<ET, 4>;                                                                             \
    else if (R == 5)                                                                               \
        KV = K<ET, 5>;                                                                             \
    else if (R == 6)                                                                               \
        KV = K<ET, 6>;                                                                             \
    else                                                                                \
        throw ngraph_error("Unsupported rank " + std::to_string(R) + " for kernel " #K);

// Partial per-type and rank kernel macro
#define PARTIAL_SELECT_KERNEL_BY_RANK(KV, ET, R, K)                                                \
    if (ET == element::f32)                                                                        \
    {                                                                                \
        PARTIAL_SELECT_RANK(KV, float, R, K);                                                      \
    }                                                                                \
    else if (ET == element::i8)                                                                    \
    {                                                                                \
        PARTIAL_SELECT_RANK(KV, int8_t, R, K);                                                     \
    }                                                                                \
    else if (ET == element::u8)                                                                    \
    {                                                                                \
        PARTIAL_SELECT_RANK(KV, uint8_t, R, K);                                                    \
    }                                                                                \
    else                                                                                \
    {                                                                                \
        throw ngraph_error("Unsupported element type " + ET.c_type_string() + " for kernel " #K);  \
    }

#define BUILD_UNARY_ELEMWISE_FUNCTOR(OP)                                                           \
    auto& functors = external_function->get_functors();                                            \
    std::function<void(void*, void*, size_t)> kernel;                                              \
                                                                                \
    SELECT_KERNEL(kernel, args[0].get_element_type(), OP);                                         \
                                                                                \
    auto element_count = out[0].get_size();                                                        \
    auto& arg0_tensor = external_function->get_tensor_data(args[0].get_name());                    \
    auto& out0_tensor = external_function->get_tensor_data(out[0].get_name());                     \
                                                                                \
    auto functor = [&, kernel, element_count](CPURuntimeContext* ctx) {                            \
        kernel(arg0_tensor, out0_tensor, element_count);                                           \
    };                                                                                \
    functors.emplace_back(functor);

#define BUILD_BINARY_ELEMWISE_FUNCTOR(OP)                                                          \
    auto& functors = external_function->get_functors();                                            \
    std::function<void(void*, void*, void*, size_t)> kernel;                                       \
                                                                                \
    SELECT_KERNEL(kernel, args[0].get_element_type(), OP);                                         \
                                                                                \
    auto element_count = out[0].get_size();                                                        \
    auto& arg0_tensor = external_function->get_tensor_data(args[0].get_name());                    \
    auto& arg1_tensor = external_function->get_tensor_data(args[1].get_name());                    \
    auto& out0_tensor = external_function->get_tensor_data(out[0].get_name());                     \
                                                                                \
    auto functor = [&, kernel, element_count](CPURuntimeContext* ctx) {                            \
        kernel(arg0_tensor, arg1_tensor, out0_tensor, element_count);                              \
    };                                                                                \
    functors.emplace_back(functor);

#define REGISTER_OP_BUILDER(OP)                                                                    \
    static struct __register_##OP##_builder                                                        \
    {                                                                                \
        __register_##OP##_builder()                                                                \
        {                                                                                \
            build_dispatcher.insert({type_index(typeid(ngraph::op::OP)),                           \
                                     &runtime::cpu::Builder::build<ngraph::op::OP>});              \
        }                                                                                \
    } __register_##OP##_builder_instance;

namespace ngraph
{
    namespace runtime
    {
        namespace cpu
        {
            using BuildOpFunction =
                std::function<void(CPU_ExternalFunction* external_function,
                                   const ngraph::Node*,
                                   const std::vector<TensorViewWrapper>& inputs,
                                   const std::vector<TensorViewWrapper>& outputs)>;

            using BuildOpMap = std::unordered_map<std::type_index, BuildOpFunction>;

            extern BuildOpMap build_dispatcher;

            class Builder
            {
            public:
                template <typename OP>
                static void build(CPU_ExternalFunction* external_function,
                                  const ngraph::Node* node,
                                  const std::vector<TensorViewWrapper>& args,
                                  const std::vector<TensorViewWrapper>& out)
                {
                    throw std::runtime_error("Unimplemented op in CPU builder");
                }

                static void nop(CPU_ExternalFunction* external_function,
                                const ngraph::Node* node,
                                const std::vector<TensorViewWrapper>& args,
                                const std::vector<TensorViewWrapper>& out)
                {
                }
            };
        }
    }
}
<commit_msg>DEX: Support fewer ranks (#1426)<commit_after>/*******************************************************************************
* Copyright 2018 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/

#pragma once

#include <string>
#include <vector>

#include "ngraph/node.hpp"
#include "ngraph/runtime/cpu/cpu_external_function.hpp"
#include "ngraph/runtime/cpu/cpu_tensor_view_wrapper.hpp"

#define BUILDER_DECL(op_name)                                                                      \
    build<op_name>(CPU_ExternalFunction * external_function,                                       \
                   const ngraph::Node* node,                                                       \
                   const std::vector<TensorViewWrapper>& args,                                     \
                   const std::vector<TensorViewWrapper>& out)

// Per-type kernel macro
#define SELECT_KERNEL(KV, ET, K)                                                                   \
    if (ET == element::boolean)                                                                    \
    {                                                                                \
        KV = K<char>;                                                                              \
    }                                                                                \
    else if (ET == element::f32)                                                                   \
    {                                                                                \
        KV = K<float>;                                                                             \
    }                                                                                \
    else if (ET == element::f64)                                                                   \
    {                                                                                \
        KV = K<double>;                                                                            \
    }                                                                                \
    else if (ET == element::i8)                                                                    \
    {                                                                                \
        KV = K<int8_t>;                                                                            \
    }                                                                                \
    else if (ET == element::i16)                                                                   \
    {                                                                                \
        KV = K<int16_t>;                                                                           \
    }                                                                                \
    else if (ET == element::i32)                                                                   \
    {                                                                                \
        KV = K<int32_t>;                                                                           \
    }                                                                                \
    else if (ET == element::i64)                                                                   \
    {                                                                                \
        KV = K<int64_t>;                                                                           \
    }                                                                                \
    else if (ET == element::u8)                                                                    \
    {                                                                                \
        KV = K<uint8_t>;                                                                           \
    }                                                                                \
    else if (ET == element::u16)                                                                   \
    {                                                                                \
        KV = K<uint16_t>;                                                                          \
    }                                                                                \
    else if (ET == element::u32)                                                                   \
    {                                                                                \
        KV = K<uint32_t>;                                                                          \
    }                                                                                \
    else if (ET == element::u64)                                                                   \
    {                                                                                \
        KV = K<uint64_t>;                                                                          \
    }

#define SELECT_RANK(KV, ET, R, K)                                                                  \
    if (R == 1)                                                                                \
        KV = K<ET, 1>;                                                                             \
    else if (R == 2)                                                                               \
        KV = K<ET, 2>;                                                                             \
    else if (R == 3)                                                                               \
        KV = K<ET, 3>;                                                                             \
    else if (R == 4)                                                                               \
        KV = K<ET, 4>;                                                                             \
    else if (R == 5)                                                                               \
        KV = K<ET, 5>;                                                                             \
    else if (R == 6)                                                                               \
        KV = K<ET, 6>;                                                                             \
    else if (R == 7)                                                                               \
        KV = K<ET, 7>;                                                                             \
    else                                                                                \
        throw ngraph_error("Unsupported rank " + std::to_string(R) + " for kernel " #K);

// Per-type and rank kernel macro
#define SELECT_KERNEL_BY_RANK(KV, ET, R, K)                                                        \
    if (ET == element::boolean)                                                                    \
    {                                                                                \
        SELECT_RANK(KV, char, R, K);                                                               \
    }                                                                                \
    else if (ET == element::f32)                                                                   \
    {                                                                                \
        SELECT_RANK(KV, float, R, K);                                                              \
    }                                                                                \
    else if (ET == element::f64)                                                                   \
    {                                                                                \
        SELECT_RANK(KV, double, R, K);                                                             \
    }                                                                                \
    else if (ET == element::i8)                                                                    \
    {                                                                                \
        SELECT_RANK(KV, int8_t, R, K);                                                             \
    }                                                                                \
    else if (ET == element::i16)                                                                   \
    {                                                                                \
        SELECT_RANK(KV, int16_t, R, K);                                                            \
    }                                                                                \
    else if (ET == element::i32)                                                                   \
    {                                                                                \
        SELECT_RANK(KV, int32_t, R, K);                                                            \
    }                                                                                \
    else if (ET == element::i64)                                                                   \
    {                                                                                \
        SELECT_RANK(KV, int64_t, R, K);                                                            \
    }                                                                                \
    else if (ET == element::u8)                                                                    \
    {                                                                                \
        SELECT_RANK(KV, uint8_t, R, K);                                                            \
    }                                                                                \
    else if (ET == element::u16)                                                                   \
    {                                                                                \
        SELECT_RANK(KV, uint16_t, R, K);                                                           \
    }                                                                                \
    else if (ET == element::u32)                                                                   \
    {                                                                                \
        SELECT_RANK(KV, uint32_t, R, K);                                                           \
    }                                                                                \
    else if (ET == element::u64)                                                                   \
    {                                                                                \
        SELECT_RANK(KV, uint64_t, R, K);                                                           \
    }                                                                                \
    else                                                                                \
    {                                                                                \
        throw ngraph_error("Unsupported element type " + ET.c_type_string() + " for kernel " #K);  \
    }

// Helper macros for a partial set of element types and ranks
// Useful for keeping compilation time and memory usage reasonable
// when the computed expression is complex

#define PARTIAL_SELECT_RANK(KV, ET, R, K)                                                          \
    if (R == 1)                                                                                \
        KV = K<ET, 1>;                                                                             \
    else if (R == 2)                                                                               \
        KV = K<ET, 2>;                                                                             \
    else if (R == 3)                                                                               \
        KV = K<ET, 3>;                                                                             \
    else if (R == 4)                                                                               \
        KV = K<ET, 4>;                                                                             \
    else if (R == 5)                                                                               \
        KV = K<ET, 5>;                                                                             \
    else if (R == 6)                                                                               \
        KV = K<ET, 6>;                                                                             \
    else                                                                                \
        throw ngraph_error("Unsupported rank " + std::to_string(R) + " for kernel " #K);

// Partial per-type and rank kernel macro
#define PARTIAL_SELECT_KERNEL_BY_RANK(KV, ET, R, K)                                                \
    if (ET == element::f32)                                                                        \
    {                                                                                \
        PARTIAL_SELECT_RANK(KV, float, R, K);                                                      \
    }                                                                                \
    else if (ET == element::i8)                                                                    \
    {                                                                                \
        PARTIAL_SELECT_RANK(KV, int8_t, R, K);                                                     \
    }                                                                                \
    else if (ET == element::u8)                                                                    \
    {                                                                                \
        PARTIAL_SELECT_RANK(KV, uint8_t, R, K);                                                    \
    }                                                                                \
    else                                                                                \
    {                                                                                \
        throw ngraph_error("Unsupported element type " + ET.c_type_string() + " for kernel " #K);  \
    }

#define BUILD_UNARY_ELEMWISE_FUNCTOR(OP)                                                           \
    auto& functors = external_function->get_functors();                                            \
    std::function<void(void*, void*, size_t)> kernel;                                              \
                                                                                \
    SELECT_KERNEL(kernel, args[0].get_element_type(), OP);                                         \
                                                                                \
    auto element_count = out[0].get_size();                                                        \
    auto& arg0_tensor = external_function->get_tensor_data(args[0].get_name());                    \
    auto& out0_tensor = external_function->get_tensor_data(out[0].get_name());                     \
                                                                                \
    auto functor = [&, kernel, element_count](CPURuntimeContext* ctx) {                            \
        kernel(arg0_tensor, out0_tensor, element_count);                                           \
    };                                                                                \
    functors.emplace_back(functor);

#define BUILD_BINARY_ELEMWISE_FUNCTOR(OP)                                                          \
    auto& functors = external_function->get_functors();                                            \
    std::function<void(void*, void*, void*, size_t)> kernel;                                       \
                                                                                \
    SELECT_KERNEL(kernel, args[0].get_element_type(), OP);                                         \
                                                                                \
    auto element_count = out[0].get_size();                                                        \
    auto& arg0_tensor = external_function->get_tensor_data(args[0].get_name());                    \
    auto& arg1_tensor = external_function->get_tensor_data(args[1].get_name());                    \
    auto& out0_tensor = external_function->get_tensor_data(out[0].get_name());                     \
                                                                                \
    auto functor = [&, kernel, element_count](CPURuntimeContext* ctx) {                            \
        kernel(arg0_tensor, arg1_tensor, out0_tensor, element_count);                              \
    };                                                                                \
    functors.emplace_back(functor);

#define REGISTER_OP_BUILDER(OP)                                                                    \
    static struct __register_##OP##_builder                                                        \
    {                                                                                \
        __register_##OP##_builder()                                                                \
        {                                                                                \
            build_dispatcher.insert({type_index(typeid(ngraph::op::OP)),                           \
                                     &runtime::cpu::Builder::build<ngraph::op::OP>});              \
        }                                                                                \
    } __register_##OP##_builder_instance;

namespace ngraph
{
    namespace runtime
    {
        namespace cpu
        {
            using BuildOpFunction =
                std::function<void(CPU_ExternalFunction* external_function,
                                   const ngraph::Node*,
                                   const std::vector<TensorViewWrapper>& inputs,
                                   const std::vector<TensorViewWrapper>& outputs)>;

            using BuildOpMap = std::unordered_map<std::type_index, BuildOpFunction>;

            extern BuildOpMap build_dispatcher;

            class Builder
            {
            public:
                template <typename OP>
                static void build(CPU_ExternalFunction* external_function,
                                  const ngraph::Node* node,
                                  const std::vector<TensorViewWrapper>& args,
                                  const std::vector<TensorViewWrapper>& out)
                {
                    throw std::runtime_error("Unimplemented op in CPU builder");
                }

                static void nop(CPU_ExternalFunction* external_function,
                                const ngraph::Node* node,
                                const std::vector<TensorViewWrapper>& args,
                                const std::vector<TensorViewWrapper>& out)
                {
                }
            };
        }
    }
}
<|endoftext|>


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

#ifndef SVTOOLS_INC_ROADMAPWIZARD_HXX
#define SVTOOLS_INC_ROADMAPWIZARD_HXX

#ifndef INCLUDED_SVTDLLAPI_H
#include "svtools/svtdllapi.h"
#endif

#ifndef _SVTOOLS_WIZARDMACHINE_HXX_
#include <svtools/wizardmachine.hxx>
#endif

//........................................................................
namespace svt
{
//........................................................................

    struct RoadmapWizardImpl;

    struct RoadmapWizardTypes
    {
    public:
        typedef sal_Int16  PathId;
    };
    //====================================================================
    //= RoadmapWizard
    //====================================================================
    /** is - no, not a wizard for a raodmap, but the base class for wizards
        supporting a roadmap.

        The basic new concept introduced is a path:

        A path is a sequence of states, which are to be executed in a linear order.
        Elements in the path can be skipped, depending on choices the user makes.

        In the most simple wizards, you will have only one path consisting of n elements,
        which are to be visited successively.

        In a slightly more complex wizard, you will have one linear path, were certain
        steps might be skipped due to user input. For instance, the user may decide to not specify
        certain aspects of the to-be-created object (e.g. by unchecking a check box),
        and the wizard then will simply disable the step which corresponds to this step.

        In a yet more advanced wizards, you will have several paths of length n1 and
        n2, which share at least the first k states (where k
        is at least 1), and an arbitrary number of other states.
    */
    class SVT_DLLPUBLIC RoadmapWizard : public OWizardMachine, public RoadmapWizardTypes
    {
    private:
        RoadmapWizardImpl*  m_pImpl;

    public:
        RoadmapWizard( Window* _pParent, const ResId& _rRes, sal_uInt32 _nButtonFlags,
            const ResId& _rRoadmapTitleResource, sal_Bool _bCheckButtonStates = sal_False );
        ~RoadmapWizard( );

        void            SetRoadmapBitmap( const BitmapEx& _rBitmap );
        const BitmapEx& GetRoadmapBitmap( ) const;

        void            SetRoadmapSmartHelpId( const SmartId& _rId, SmartIdUpdateMode _aMode = SMART_SET_SMART );
        SmartId         GetRoadmapSmartHelpId() const;

        void            SetRoadmapInteractive( sal_Bool _bInteractive );
        sal_Bool        IsRoadmapInteractive();
        virtual void    Resize();
        virtual void    StateChanged( StateChangedType nStateChange );
        /** returns current state
         */
        bool    isStateEnabled( WizardState _nState );

    protected:
        /** declares a valid path in the wizard

            The very first path which is declared is automatically activated.

            Note that all paths which are declared must have the very first state in
            common. Also note that due to a restriction of the very base class (<type>WizardDialog</type>),
            this common first state must be 0.

            You cannot declare new paths once the wizard started, so it's recommended that
            you do all declarations within your derivee's constructor.

            @see activatePath

            @param _nId
                the unique id you wish to give this path. This id can later on be used
                to refer to the path which you just declared

            @param _nFirstState
                the first state in this path. Must not be WZS_INVALID_STATE.

                Declare an arbitrary number of states after this one, and terminate the sequence
                with a WZS_INVALID_STATE.
        */
        void    declarePath( PathId _nPathId, WizardState _nFirstState, ... );

        /** activates a path which has previously been declared with <member>declarePath</member>

            You can only activate paths which share the first k states with the path
            which is previously active (if any), where k is the index of the
            current state within the current page.

            <example>
            Say you have paths, (0,1,2,5) and (0,1,4,5). This means that after
            step 1, you either continue with state 2 or state 4,
            and after this, you finish in state 5.

            Now if the first path is active, and your current state is 1, then you can
            easily switch to the second path, since both paths start with (0,1).

            However, if your current state is 2, then you can not switch to the second
            path anymore.
            </example>

            @param _nPathId
                the id of the path. The path must have been declared (under this id) with
                <member>declarePath</member> before it can be activated.

            @param _bDecideForIt
                If <TRUE/>, the path will be completely activated, even if it is a conflicting path
                (i.e. there is another path which shares the first k states with
                the to-be-activated path.)

                If <FALSE/>, then the new path is checked for conflicts with other paths. If such
                conflicts exists, the path is not completely activated, but only up to the point
                where it does not conflict.

                With the paths in the example above, if you activate the second path (when both are
                already declared), then only steps 0 and 1 are activated,
                since they are common to both paths.
        */
        void    activatePath( PathId _nPathId, bool _bDecideForIt = false );

        /** determine the next state to travel from the given one

            This method (which is declared in <type>OWizardMachine</type> and overwritten here)
            ensures that traveling happens along the active path.

            @see activatePath
        */
        virtual WizardState     determineNextState( WizardState _nCurrentState );

        /** en- or disables a state

            In the wizard's roadmap, states to travel to can be freely chosen. To prevent
            users from selecting a state which is currently not available, you can declare this
            state as being disabled.

            A situation where you need this may be when you have a checkbox which, when checked
            by the user, enables a page with additional settings. As long as this checkbox is
            not checked, the respective state would be disabled.

            Note that in theory, you can declare multiple paths, instead of disabling states.
            For instance, if you have a path where one state can be potentially disabled, then
            you could declare a second path, which does not contain this state. However, the
            disadvantage is that then, not the complete path would be visible in the roadmap,
            but only all steps up to the point where the both paths diverge.

            Another disadvantage is that the number of needed paths grows exponentially with
            the number of states which can be potentially disabled.

            @see declarePath
        */
        void    enableState( WizardState _nState, bool _bEnable = true );

        // OWizardMachine overriables
        virtual void            enterState( WizardState _nState );

        /** returns a human readable name for a given state
            @pure
        */
        virtual String  getStateDisplayName( WizardState _nState ) = 0;

        /** asks for a new label of the wizard page

         */
        void    updateRoadmapItemLabel( WizardState _nState );

    protected:
#if OSL_DEBUG_LEVEL > 0
        const sal_Char* checkInvariants() const;
        friend const char* CheckInvariants( const void* pVoid );
#endif

    private:
        SVT_DLLPRIVATE void ResizeFixedLine();

    private:
        DECL_DLLPRIVATE_LINK( OnRoadmapItemSelected, void* );

        /** inserts an entry for the given state into the roadmap, at the given index

            This method automatically cares for the enabled/disabled state of the item,
            and for its text.
        */
        SVT_DLLPRIVATE void implInsertState( WizardState _nState, sal_Int32 _nIndex );

        /** updates the roadmap control to show the given path, as far as possible
            (modulo conflicts with other paths)
        */
        SVT_DLLPRIVATE void implUpdateRoadmap( );
    };

//........................................................................
} // namespace svt
//........................................................................

#endif // OOO_SVTOOLS_INC_ROADMAPWIZARD_HXX
<commit_msg>INTEGRATION: CWS c09tosrc (1.3.44); FILE MERGED 2007/06/20 10:41:27 as 1.3.44.1: #144874# megre changes also into the master<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: roadmapwizard.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2007-07-06 12:24:28 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SVTOOLS_INC_ROADMAPWIZARD_HXX
#define SVTOOLS_INC_ROADMAPWIZARD_HXX

#ifndef INCLUDED_SVTDLLAPI_H
#include "svtools/svtdllapi.h"
#endif

#ifndef _SVTOOLS_WIZARDMACHINE_HXX_
#include <svtools/wizardmachine.hxx>
#endif

//........................................................................
namespace svt
{
//........................................................................

    namespace
    {
        typedef ::std::vector< WizardTypes::WizardState > Path;
    }

    struct RoadmapWizardImpl;

    struct RoadmapWizardTypes
    {
    public:
        typedef sal_Int16  PathId;
    };
    //====================================================================
    //= RoadmapWizard
    //====================================================================
    /** is - no, not a wizard for a raodmap, but the base class for wizards
        supporting a roadmap.

        The basic new concept introduced is a path:

        A path is a sequence of states, which are to be executed in a linear order.
        Elements in the path can be skipped, depending on choices the user makes.

        In the most simple wizards, you will have only one path consisting of n elements,
        which are to be visited successively.

        In a slightly more complex wizard, you will have one linear path, were certain
        steps might be skipped due to user input. For instance, the user may decide to not specify
        certain aspects of the to-be-created object (e.g. by unchecking a check box),
        and the wizard then will simply disable the step which corresponds to this step.

        In a yet more advanced wizards, you will have several paths of length n1 and
        n2, which share at least the first k states (where k
        is at least 1), and an arbitrary number of other states.
    */
    class SVT_DLLPUBLIC RoadmapWizard : public OWizardMachine, public RoadmapWizardTypes
    {
    private:
        RoadmapWizardImpl*  m_pImpl;

    public:
        RoadmapWizard( Window* _pParent, const ResId& _rRes, sal_uInt32 _nButtonFlags,
            const ResId& _rRoadmapTitleResource, sal_Bool _bCheckButtonStates = sal_False );
        ~RoadmapWizard( );

        void            SetRoadmapBitmap( const BitmapEx& _rBitmap );
        const BitmapEx& GetRoadmapBitmap( ) const;

        void            SetRoadmapSmartHelpId( const SmartId& _rId, SmartIdUpdateMode _aMode = SMART_SET_SMART );
        SmartId         GetRoadmapSmartHelpId() const;

        void            SetRoadmapInteractive( sal_Bool _bInteractive );
        sal_Bool        IsRoadmapInteractive();
        virtual void    Resize();
        virtual void    StateChanged( StateChangedType nStateChange );
        /** returns current state
         */
        bool    isStateEnabled( WizardState _nState );

    protected:
        /** declares a valid path in the wizard

            The very first path which is declared is automatically activated.

            Note that all paths which are declared must have the very first state in
            common. Also note that due to a restriction of the very base class (<type>WizardDialog</type>),
            this common first state must be 0.

            You cannot declare new paths once the wizard started, so it's recommended that
            you do all declarations within your derivee's constructor.

            @see activatePath

            @param _nId
                the unique id you wish to give this path. This id can later on be used
                to refer to the path which you just declared

            @param _nFirstState
                the first state in this path. Must not be WZS_INVALID_STATE.

                Declare an arbitrary number of states after this one, and terminate the sequence
                with a WZS_INVALID_STATE.
        */
        void    declarePath( PathId _nPathId, WizardState _nFirstState, ... );
        void    declarePath( PathId _nPathId, const Path& _lWizardStates);

        /** activates a path which has previously been declared with <member>declarePath</member>

            You can only activate paths which share the first k states with the path
            which is previously active (if any), where k is the index of the
            current state within the current page.

            <example>
            Say you have paths, (0,1,2,5) and (0,1,4,5). This means that after
            step 1, you either continue with state 2 or state 4,
            and after this, you finish in state 5.

            Now if the first path is active, and your current state is 1, then you can
            easily switch to the second path, since both paths start with (0,1).

            However, if your current state is 2, then you can not switch to the second
            path anymore.
            </example>

            @param _nPathId
                the id of the path. The path must have been declared (under this id) with
                <member>declarePath</member> before it can be activated.

            @param _bDecideForIt
                If <TRUE/>, the path will be completely activated, even if it is a conflicting path
                (i.e. there is another path which shares the first k states with
                the to-be-activated path.)

                If <FALSE/>, then the new path is checked for conflicts with other paths. If such
                conflicts exists, the path is not completely activated, but only up to the point
                where it does not conflict.

                With the paths in the example above, if you activate the second path (when both are
                already declared), then only steps 0 and 1 are activated,
                since they are common to both paths.
        */
        void    activatePath( PathId _nPathId, bool _bDecideForIt = false );

        /** determine the next state to travel from the given one

            This method (which is declared in <type>OWizardMachine</type> and overwritten here)
            ensures that traveling happens along the active path.

            @see activatePath
        */
        virtual WizardState     determineNextState( WizardState _nCurrentState );

        /** en- or disables a state

            In the wizard's roadmap, states to travel to can be freely chosen. To prevent
            users from selecting a state which is currently not available, you can declare this
            state as being disabled.

            A situation where you need this may be when you have a checkbox which, when checked
            by the user, enables a page with additional settings. As long as this checkbox is
            not checked, the respective state would be disabled.

            Note that in theory, you can declare multiple paths, instead of disabling states.
            For instance, if you have a path where one state can be potentially disabled, then
            you could declare a second path, which does not contain this state. However, the
            disadvantage is that then, not the complete path would be visible in the roadmap,
            but only all steps up to the point where the both paths diverge.

            Another disadvantage is that the number of needed paths grows exponentially with
            the number of states which can be potentially disabled.

            @see declarePath
        */
        void    enableState( WizardState _nState, bool _bEnable = true );

        // OWizardMachine overriables
        virtual void            enterState( WizardState _nState );

        /** returns a human readable name for a given state
            @pure
        */
        virtual String  getStateDisplayName( WizardState _nState ) = 0;

        /** asks for a new label of the wizard page

         */
        void    updateRoadmapItemLabel( WizardState _nState );

    protected:
#if OSL_DEBUG_LEVEL > 0
        const sal_Char* checkInvariants() const;
        friend const char* CheckInvariants( const void* pVoid );
#endif

    private:
        SVT_DLLPRIVATE void ResizeFixedLine();

    private:
        DECL_DLLPRIVATE_LINK( OnRoadmapItemSelected, void* );

        /** inserts an entry for the given state into the roadmap, at the given index

            This method automatically cares for the enabled/disabled state of the item,
            and for its text.
        */
        SVT_DLLPRIVATE void implInsertState( WizardState _nState, sal_Int32 _nIndex );

        /** updates the roadmap control to show the given path, as far as possible
            (modulo conflicts with other paths)
        */
        SVT_DLLPRIVATE void implUpdateRoadmap( );
    };

//........................................................................
} // namespace svt
//........................................................................

#endif // OOO_SVTOOLS_INC_ROADMAPWIZARD_HXX
<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#include <com/sun/star/embed/XComponentSupplier.hpp>
#include <com/sun/star/embed/EmbedStates.hpp>
#include <com/sun/star/embed/XVisualObject.hpp>
#include <com/sun/star/embed/XEmbedPersist.hpp>
#include <com/sun/star/embed/NoVisualAreaSizeException.hpp>
#include <com/sun/star/datatransfer/XTransferable.hpp>
#include <com/sun/star/embed/Aspects.hpp>

#include <svtools/embedtransfer.hxx>
#include <vcl/mapunit.hxx>
#include <vcl/outdev.hxx>
#include <comphelper/storagehelper.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <unotools/streamwrap.hxx>
#include <unotools/tempfile.hxx>
#include <toolkit/helper/vclunohelper.hxx>

#include "embedhlp.hxx"

using namespace ::com::sun::star;

SvEmbedTransferHelper::SvEmbedTransferHelper( const uno::Reference< embed::XEmbeddedObject >& xObj,
                                                Graphic* pGraphic,
                                                sal_Int64 nAspect )
: m_xObj( xObj )
, m_pGraphic( pGraphic ? new Graphic( *pGraphic ) : NULL )
, m_nAspect( nAspect )
{
}

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

SvEmbedTransferHelper::~SvEmbedTransferHelper()
{
    if ( m_pGraphic )
    {
        delete m_pGraphic;
        m_pGraphic = NULL;
    }
}

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

void SvEmbedTransferHelper::AddSupportedFormats()
{
    AddFormat( SOT_FORMATSTR_ID_EMBED_SOURCE );
    AddFormat( SOT_FORMATSTR_ID_OBJECTDESCRIPTOR );
    AddFormat( FORMAT_GDIMETAFILE );
}

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

sal_Bool SvEmbedTransferHelper::GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor )
{
    sal_Bool bRet = sal_False;

    if( m_xObj.is() )
    {
        try
        {
            sal_uInt32 nFormat = SotExchange::GetFormat( rFlavor );
            if( HasFormat( nFormat ) )
            {
                if( nFormat == SOT_FORMATSTR_ID_OBJECTDESCRIPTOR )
                {
                    TransferableObjectDescriptor aDesc;
                    FillTransferableObjectDescriptor( aDesc, m_xObj, m_pGraphic, m_nAspect );
                    bRet = SetTransferableObjectDescriptor( aDesc, rFlavor );
                }
                else if( nFormat == SOT_FORMATSTR_ID_EMBED_SOURCE )
                {
                    try
                    {
                        // TODO/LATER: Propbably the graphic should be copied here as well
                        // currently it is handled by the applications
                        utl::TempFile aTmp;
                        aTmp.EnableKillingFile( TRUE );
                        uno::Reference < embed::XEmbedPersist > xPers( m_xObj, uno::UNO_QUERY );
                        if ( xPers.is() )
                        {
                            uno::Reference < embed::XStorage > xStg = comphelper::OStorageHelper::GetTemporaryStorage();
                            ::rtl::OUString aName = ::rtl::OUString::createFromAscii("Dummy");
                            SvStream* pStream = NULL;
                            BOOL bDeleteStream = FALSE;
                            uno::Sequence < beans::PropertyValue > aEmpty;
                            xPers->storeToEntry( xStg, aName, aEmpty, aEmpty );
                            if ( xStg->isStreamElement( aName ) )
                            {
                                uno::Reference < io::XStream > xStm = xStg->cloneStreamElement( aName );
                                pStream = utl::UcbStreamHelper::CreateStream( xStm );
                                bDeleteStream = TRUE;
                            }
                            else
                            {
                                pStream = aTmp.GetStream( STREAM_STD_READWRITE );
                                uno::Reference < embed::XStorage > xStor = comphelper::OStorageHelper::GetStorageFromStream( new utl::OStreamWrapper( *pStream ) );
                                xStg->openStorageElement( aName, embed::ElementModes::READ )->copyToStorage( xStor );
                            }

                            ::com::sun::star::uno::Any                  aAny;
                            const sal_uInt32                            nLen = pStream->Seek( STREAM_SEEK_TO_END );
                            ::com::sun::star::uno::Sequence< sal_Int8 > aSeq( nLen );

                            pStream->Seek( STREAM_SEEK_TO_BEGIN );
                            pStream->Read( aSeq.getArray(),  nLen );
                            if ( bDeleteStream )
                                delete pStream;

                            if( ( bRet = ( aSeq.getLength() > 0 ) ) == sal_True )
                            {
                                aAny <<= aSeq;
                                SetAny( aAny, rFlavor );
                            }
                        }
                        else
                        {
                            //TODO/LATER: how to handle objects without persistance?!
                        }
                    }
                    catch ( uno::Exception& )
                    {
                    }
                }
                else if ( nFormat == FORMAT_GDIMETAFILE && m_pGraphic )
                {
                    SvMemoryStream aMemStm( 65535, 65535 );
                    aMemStm.SetVersion( SOFFICE_FILEFORMAT_CURRENT );

                    const GDIMetaFile& aMetaFile = m_pGraphic->GetGDIMetaFile();
                    ((GDIMetaFile*)(&aMetaFile))->Write( aMemStm );
                    uno::Any aAny;
                    aAny <<= uno::Sequence< sal_Int8 >( reinterpret_cast< const sal_Int8* >( aMemStm.GetData() ),
                                                    aMemStm.Seek( STREAM_SEEK_TO_END ) );
                    SetAny( aAny, rFlavor );
                    bRet = sal_True;
                }
                else if ( m_xObj.is() && :: svt::EmbeddedObjectRef::TryRunningState( m_xObj ) )
                {
                    uno::Reference< datatransfer::XTransferable > xTransferable( m_xObj->getComponent(), uno::UNO_QUERY );
                    if ( xTransferable.is() )
                    {
                        uno::Any aAny = xTransferable->getTransferData( rFlavor );
                        SetAny( aAny, rFlavor );
                        bRet = sal_True;
                    }
                }
            }
        }
        catch( uno::Exception& )
        {
            // Error handling?
        }
    }

    return bRet;
}

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

void SvEmbedTransferHelper::ObjectReleased()
{
    m_xObj = uno::Reference< embed::XEmbeddedObject >();
}

void SvEmbedTransferHelper::FillTransferableObjectDescriptor( TransferableObjectDescriptor& rDesc,
    const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XEmbeddedObject >& xObj,
    Graphic* pGraphic,
    sal_Int64 nAspect )
{
    //TODO/LATER: need TypeName to fill it into the Descriptor (will be shown in listbox)
    ::com::sun::star::datatransfer::DataFlavor aFlavor;
    SotExchange::GetFormatDataFlavor( SOT_FORMATSTR_ID_OBJECTDESCRIPTOR, aFlavor );

    rDesc.maClassName = SvGlobalName( xObj->getClassID() );
    rDesc.maTypeName = aFlavor.HumanPresentableName;

    //TODO/LATER: the aspect size in the descriptor is wrong, unfortunately the stream
    // representation of the descriptor allows only 4 bytes for the aspect
    // so for internal transport something different should be found
    rDesc.mnViewAspect = sal::static_int_cast<sal_uInt16>( nAspect );

    //TODO/LATER: status needs to become sal_Int64
    rDesc.mnOle2Misc = sal::static_int_cast<sal_Int32>(xObj->getStatus( rDesc.mnViewAspect ));

    Size aSize;
    MapMode aMapMode( MAP_100TH_MM );
    if ( nAspect == embed::Aspects::MSOLE_ICON )
    {
        if ( pGraphic )
        {
            aMapMode = pGraphic->GetPrefMapMode();
            aSize = pGraphic->GetPrefSize();
        }
        else
            aSize = Size( 2500, 2500 );
    }
    else
    {
        try
        {
            awt::Size aSz;
            aSz = xObj->getVisualAreaSize( rDesc.mnViewAspect );
            aSize = Size( aSz.Width, aSz.Height );
        }
        catch( embed::NoVisualAreaSizeException& )
        {
            OSL_ENSURE( sal_False, "Can not get visual area size!\n" );
            aSize = Size( 5000, 5000 );
        }

        // TODO/LEAN: getMapUnit can switch object to running state
        aMapMode = MapMode( VCLUnoHelper::UnoEmbed2VCLMapUnit( xObj->getMapUnit( rDesc.mnViewAspect ) ) );
    }

    rDesc.maSize = OutputDevice::LogicToLogic( aSize, aMapMode, MapMode( MAP_100TH_MM ) );
    rDesc.maDragStartPos = Point();
    rDesc.maDisplayName = String();
    rDesc.mbCanLink = FALSE;
}

<commit_msg>INTEGRATION: CWS fwk90 (1.11.66); FILE MERGED 2008/06/02 06:25:38 mav 1.11.66.1: #i88288# move embedhlp.hxx to svtools/inc/svtools<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: embedtransfer.cxx,v $
 * $Revision: 1.12 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svtools.hxx"
#include <com/sun/star/embed/XComponentSupplier.hpp>
#include <com/sun/star/embed/EmbedStates.hpp>
#include <com/sun/star/embed/XVisualObject.hpp>
#include <com/sun/star/embed/XEmbedPersist.hpp>
#include <com/sun/star/embed/NoVisualAreaSizeException.hpp>
#include <com/sun/star/datatransfer/XTransferable.hpp>
#include <com/sun/star/embed/Aspects.hpp>

#include <svtools/embedtransfer.hxx>
#include <vcl/mapunit.hxx>
#include <vcl/outdev.hxx>
#include <comphelper/storagehelper.hxx>
#include <unotools/ucbstreamhelper.hxx>
#include <unotools/streamwrap.hxx>
#include <unotools/tempfile.hxx>
#include <toolkit/helper/vclunohelper.hxx>

#include <svtools/embedhlp.hxx>

using namespace ::com::sun::star;

SvEmbedTransferHelper::SvEmbedTransferHelper( const uno::Reference< embed::XEmbeddedObject >& xObj,
                                                Graphic* pGraphic,
                                                sal_Int64 nAspect )
: m_xObj( xObj )
, m_pGraphic( pGraphic ? new Graphic( *pGraphic ) : NULL )
, m_nAspect( nAspect )
{
}

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

SvEmbedTransferHelper::~SvEmbedTransferHelper()
{
    if ( m_pGraphic )
    {
        delete m_pGraphic;
        m_pGraphic = NULL;
    }
}

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

void SvEmbedTransferHelper::AddSupportedFormats()
{
    AddFormat( SOT_FORMATSTR_ID_EMBED_SOURCE );
    AddFormat( SOT_FORMATSTR_ID_OBJECTDESCRIPTOR );
    AddFormat( FORMAT_GDIMETAFILE );
}

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

sal_Bool SvEmbedTransferHelper::GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor )
{
    sal_Bool bRet = sal_False;

    if( m_xObj.is() )
    {
        try
        {
            sal_uInt32 nFormat = SotExchange::GetFormat( rFlavor );
            if( HasFormat( nFormat ) )
            {
                if( nFormat == SOT_FORMATSTR_ID_OBJECTDESCRIPTOR )
                {
                    TransferableObjectDescriptor aDesc;
                    FillTransferableObjectDescriptor( aDesc, m_xObj, m_pGraphic, m_nAspect );
                    bRet = SetTransferableObjectDescriptor( aDesc, rFlavor );
                }
                else if( nFormat == SOT_FORMATSTR_ID_EMBED_SOURCE )
                {
                    try
                    {
                        // TODO/LATER: Propbably the graphic should be copied here as well
                        // currently it is handled by the applications
                        utl::TempFile aTmp;
                        aTmp.EnableKillingFile( TRUE );
                        uno::Reference < embed::XEmbedPersist > xPers( m_xObj, uno::UNO_QUERY );
                        if ( xPers.is() )
                        {
                            uno::Reference < embed::XStorage > xStg = comphelper::OStorageHelper::GetTemporaryStorage();
                            ::rtl::OUString aName = ::rtl::OUString::createFromAscii("Dummy");
                            SvStream* pStream = NULL;
                            BOOL bDeleteStream = FALSE;
                            uno::Sequence < beans::PropertyValue > aEmpty;
                            xPers->storeToEntry( xStg, aName, aEmpty, aEmpty );
                            if ( xStg->isStreamElement( aName ) )
                            {
                                uno::Reference < io::XStream > xStm = xStg->cloneStreamElement( aName );
                                pStream = utl::UcbStreamHelper::CreateStream( xStm );
                                bDeleteStream = TRUE;
                            }
                            else
                            {
                                pStream = aTmp.GetStream( STREAM_STD_READWRITE );
                                uno::Reference < embed::XStorage > xStor = comphelper::OStorageHelper::GetStorageFromStream( new utl::OStreamWrapper( *pStream ) );
                                xStg->openStorageElement( aName, embed::ElementModes::READ )->copyToStorage( xStor );
                            }

                            ::com::sun::star::uno::Any                  aAny;
                            const sal_uInt32                            nLen = pStream->Seek( STREAM_SEEK_TO_END );
                            ::com::sun::star::uno::Sequence< sal_Int8 > aSeq( nLen );

                            pStream->Seek( STREAM_SEEK_TO_BEGIN );
                            pStream->Read( aSeq.getArray(),  nLen );
                            if ( bDeleteStream )
                                delete pStream;

                            if( ( bRet = ( aSeq.getLength() > 0 ) ) == sal_True )
                            {
                                aAny <<= aSeq;
                                SetAny( aAny, rFlavor );
                            }
                        }
                        else
                        {
                            //TODO/LATER: how to handle objects without persistance?!
                        }
                    }
                    catch ( uno::Exception& )
                    {
                    }
                }
                else if ( nFormat == FORMAT_GDIMETAFILE && m_pGraphic )
                {
                    SvMemoryStream aMemStm( 65535, 65535 );
                    aMemStm.SetVersion( SOFFICE_FILEFORMAT_CURRENT );

                    const GDIMetaFile& aMetaFile = m_pGraphic->GetGDIMetaFile();
                    ((GDIMetaFile*)(&aMetaFile))->Write( aMemStm );
                    uno::Any aAny;
                    aAny <<= uno::Sequence< sal_Int8 >( reinterpret_cast< const sal_Int8* >( aMemStm.GetData() ),
                                                    aMemStm.Seek( STREAM_SEEK_TO_END ) );
                    SetAny( aAny, rFlavor );
                    bRet = sal_True;
                }
                else if ( m_xObj.is() && :: svt::EmbeddedObjectRef::TryRunningState( m_xObj ) )
                {
                    uno::Reference< datatransfer::XTransferable > xTransferable( m_xObj->getComponent(), uno::UNO_QUERY );
                    if ( xTransferable.is() )
                    {
                        uno::Any aAny = xTransferable->getTransferData( rFlavor );
                        SetAny( aAny, rFlavor );
                        bRet = sal_True;
                    }
                }
            }
        }
        catch( uno::Exception& )
        {
            // Error handling?
        }
    }

    return bRet;
}

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

void SvEmbedTransferHelper::ObjectReleased()
{
    m_xObj = uno::Reference< embed::XEmbeddedObject >();
}

void SvEmbedTransferHelper::FillTransferableObjectDescriptor( TransferableObjectDescriptor& rDesc,
    const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XEmbeddedObject >& xObj,
    Graphic* pGraphic,
    sal_Int64 nAspect )
{
    //TODO/LATER: need TypeName to fill it into the Descriptor (will be shown in listbox)
    ::com::sun::star::datatransfer::DataFlavor aFlavor;
    SotExchange::GetFormatDataFlavor( SOT_FORMATSTR_ID_OBJECTDESCRIPTOR, aFlavor );

    rDesc.maClassName = SvGlobalName( xObj->getClassID() );
    rDesc.maTypeName = aFlavor.HumanPresentableName;

    //TODO/LATER: the aspect size in the descriptor is wrong, unfortunately the stream
    // representation of the descriptor allows only 4 bytes for the aspect
    // so for internal transport something different should be found
    rDesc.mnViewAspect = sal::static_int_cast<sal_uInt16>( nAspect );

    //TODO/LATER: status needs to become sal_Int64
    rDesc.mnOle2Misc = sal::static_int_cast<sal_Int32>(xObj->getStatus( rDesc.mnViewAspect ));

    Size aSize;
    MapMode aMapMode( MAP_100TH_MM );
    if ( nAspect == embed::Aspects::MSOLE_ICON )
    {
        if ( pGraphic )
        {
            aMapMode = pGraphic->GetPrefMapMode();
            aSize = pGraphic->GetPrefSize();
        }
        else
            aSize = Size( 2500, 2500 );
    }
    else
    {
        try
        {
            awt::Size aSz;
            aSz = xObj->getVisualAreaSize( rDesc.mnViewAspect );
            aSize = Size( aSz.Width, aSz.Height );
        }
        catch( embed::NoVisualAreaSizeException& )
        {
            OSL_ENSURE( sal_False, "Can not get visual area size!\n" );
            aSize = Size( 5000, 5000 );
        }

        // TODO/LEAN: getMapUnit can switch object to running state
        aMapMode = MapMode( VCLUnoHelper::UnoEmbed2VCLMapUnit( xObj->getMapUnit( rDesc.mnViewAspect ) ) );
    }

    rDesc.maSize = OutputDevice::LogicToLogic( aSize, aMapMode, MapMode( MAP_100TH_MM ) );
    rDesc.maDragStartPos = Point();
    rDesc.maDisplayName = String();
    rDesc.mbCanLink = FALSE;
}

<|endoftext|>