<commit_before>#include "iocoom_performance_model.h"

#include "log.h"
#include "dynamic_instruction_info.h"
#include "config.hpp"
#include "simulator.h"
#include "branch_predictor.h"

IOCOOMPerformanceModel::IOCOOMPerformanceModel()
   : m_instruction_count(0)
   , m_cycle_count(0)
   , m_register_scoreboard(512)
   , m_store_buffer(0)
   , m_load_unit(0)
   , m_l1_icache(0)
   , m_l1_dcache(0)
{
   config::Config *cfg = Sim()->getCfg();

   try
   {
      m_store_buffer = new StoreBuffer(cfg->getInt("perf_model/core/num_store_buffer_entries",1));
      m_load_unit = new ExecutionUnit(cfg->getInt("perf_model/core/num_outstanding_loads",3));

      if (cfg->getBool("perf_model/l1_icache/enable", false))
      {
         m_l1_icache = new ModeledCache(cfg->getInt("perf_model/l1_icache/line_size"),
                                        cfg->getInt("perf_model/l1_icache/num_sets"),
                                        cfg->getInt("perf_model/l1_icache/associativity"),
                                        cfg->getInt("perf_model/l1_icache/victim_cache_size"),
                                        cfg->getString("perf_model/l1_icache/replacement_policy") == "lru" ? ModeledCache::LRU : ModeledCache::RANDOM);
         m_l1_icache_miss_penalty = cfg->getInt("perf_model/l1_icache/miss_penalty");
      }

      if (cfg->getBool("perf_model/l1_dcache/enable", false))
      {
         m_l1_dcache = new ModeledCache(cfg->getInt("perf_model/l1_dcache/line_size"),
                                        cfg->getInt("perf_model/l1_dcache/num_sets"),
                                        cfg->getInt("perf_model/l1_dcache/associativity"),
                                        cfg->getInt("perf_model/l1_dcache/victim_cache_size"),
                                        cfg->getString("perf_model/l1_dcache/replacement_policy") == "lru" ? ModeledCache::LRU : ModeledCache::RANDOM);
         m_l1_dcache_access_time = cfg->getInt("perf_model/l1_dcache/access_time");
      }
   }
   catch (...)
   {
      LOG_PRINT_ERROR("Config info not available.");
   }

   for (unsigned int i = 0; i < m_register_scoreboard.size(); i++)
   {
      m_register_scoreboard[i] = 0;
   }
}

IOCOOMPerformanceModel::~IOCOOMPerformanceModel()
{
   delete m_l1_dcache;
   delete m_l1_icache;
   delete m_load_unit;
   delete m_store_buffer;
}

void IOCOOMPerformanceModel::outputSummary(std::ostream &os)
{
   os << "  Instructions: " << m_instruction_count << std::endl
      << "  Cycles: " << m_cycle_count << std::endl;

   if (getBranchPredictor())
      getBranchPredictor()->outputSummary(os);
}

UInt64 IOCOOMPerformanceModel::getCycleCount()
{
   return m_cycle_count;
}

void IOCOOMPerformanceModel::setCycleCount(UInt64 time)
{
   m_cycle_count = time;
}

void IOCOOMPerformanceModel::handleInstruction(Instruction *instruction)
{
   // icache modeling
   modelIcache(instruction->getAddress());

   /*
      model instruction in the following steps:
      - find when read operations are available
      - find latency of instruction
      - update write operands
   */
   const OperandList &ops = instruction->getOperands();

   // buffer write operands to be updated after instruction executes
   DynamicInstructionInfoQueue write_info;

   // find when read operands are available
   UInt64 operands_ready = m_cycle_count;
   UInt64 write_operands_ready = m_cycle_count;

   for (unsigned int i = 0; i < ops.size(); i++)
   {
      const Operand &o = ops[i];

      if (o.m_type == Operand::MEMORY)
      {
         DynamicInstructionInfo &info = getDynamicInstructionInfo();

         if (o.m_direction == Operand::READ)
         {
            LOG_ASSERT_ERROR(info.type == DynamicInstructionInfo::MEMORY_READ,
                             "Expected memory read info, got: %d.", info.type);

            UInt64 load_ready = executeLoad(info) - m_cycle_count;

            if (load_ready > operands_ready)
               operands_ready = load_ready;
         }
         else
         {
            LOG_ASSERT_ERROR(info.type == DynamicInstructionInfo::MEMORY_WRITE,
                             "Expected memory write info, got: %d.", info.type);

            write_info.push(info);
         }

         popDynamicInstructionInfo();
      }
      else if (o.m_type == Operand::REG)
      {
         LOG_ASSERT_ERROR(o.m_value < m_register_scoreboard.size(),
                          "Register value out of range: %llu", o.m_value);

         if (o.m_direction == Operand::READ)
         {
            if (m_register_scoreboard[o.m_value] > operands_ready)
               operands_ready = m_register_scoreboard[o.m_value];
         }
         else
         {
            if (m_register_scoreboard[o.m_value] > write_operands_ready)
               write_operands_ready = m_register_scoreboard[o.m_value];
         }
      }
      else
      {
         // immediate -- do nothing
      }
   }

   // update cycle count with instruction cost
   UInt64 cost = instruction->getCost();

   m_instruction_count++;
   m_cycle_count = operands_ready + cost;

   // update write memory operands. this is done before doing register
   // operands to make sure the scoreboard is updated correctly
   for (unsigned int i = 0; i < ops.size(); i++)
   {
      const Operand &o = ops[i];

      if (o.m_direction != Operand::WRITE)
         continue;

      if (o.m_type != Operand::MEMORY)
         continue;

      const DynamicInstructionInfo &info = write_info.front();
      UInt64 store_time = executeStore(info);
      write_info.pop();

      if (store_time > m_cycle_count)
         m_cycle_count = store_time;

      if (store_time > write_operands_ready)
         write_operands_ready = store_time;
   }

   // because we are modeling an in-order machine, if we encounter a
   // register that is being updated out-of-order by a memory
   // reference, we must stall until we can write the register
   if (write_operands_ready > m_cycle_count)
      m_cycle_count = write_operands_ready;

   // update write register operands.
   for (unsigned int i = 0; i < ops.size(); i++)
   {
      const Operand &o = ops[i];

      if (o.m_direction != Operand::WRITE)
         continue;

      if (o.m_type != Operand::REG)
         continue;

      LOG_ASSERT_ERROR(m_register_scoreboard[o.m_value] <= m_cycle_count,
                       "Expected cycle count to exceed destination register times, %llu < %llu.", m_register_scoreboard[o.m_value], m_cycle_count);

      m_register_scoreboard[o.m_value] = m_cycle_count;
   }

   LOG_ASSERT_ERROR(write_info.empty(), "Some write info left over?");
}

UInt64 IOCOOMPerformanceModel::executeLoad(const DynamicInstructionInfo &info)
{
   bool l2_hit = info.memory_info.num_misses == 0;

   // similarly, a miss in the l2 with a completed entry in the store
   // buffer is treated as an invalidation
   StoreBuffer::Status status = m_store_buffer->isAddressAvailable(m_cycle_count, info.memory_info.addr);

   if ((status == StoreBuffer::VALID) || (l2_hit && status == StoreBuffer::COMPLETED))
      return m_cycle_count;

   // a miss in the l2 forces a miss in the l1 and store buffer since
   // we assume an inclusive l2 cache (a miss in the l2 generally
   // means the block has been invalidated)
   bool l1_hit = m_l1_dcache && m_l1_dcache->access(info.memory_info.addr);
   l1_hit = l1_hit && l2_hit;

   UInt64 latency  = l1_hit ? m_l1_dcache_access_time : info.memory_info.latency;

   return m_load_unit->execute(m_cycle_count, latency);
}

UInt64 IOCOOMPerformanceModel::executeStore(const DynamicInstructionInfo &info)
{
   bool l2_hit = info.memory_info.num_misses == 0;
   bool l1_hit = m_l1_dcache && m_l1_dcache->access(info.memory_info.addr);
   l1_hit = l1_hit && l2_hit;

   UInt64 latency = l1_hit ? m_l1_dcache_access_time : info.memory_info.latency;

   return m_store_buffer->executeStore(m_cycle_count, latency, info.memory_info.addr);
}

void IOCOOMPerformanceModel::modelIcache(IntPtr addr)
{
   if (!m_l1_icache)
      return;

   bool hit = m_l1_icache->access(addr);
   if (!hit)
      m_cycle_count += m_l1_icache_miss_penalty;
}

// Helper classes

IOCOOMPerformanceModel::ExecutionUnit::ExecutionUnit(unsigned int num_units)
   : m_scoreboard(num_units)
{
   for (unsigned int i = 0; i < m_scoreboard.size(); i++)
   {
      m_scoreboard[i] = 0;
   }
}

IOCOOMPerformanceModel::ExecutionUnit::~ExecutionUnit()
{
}

UInt64 IOCOOMPerformanceModel::ExecutionUnit::execute(UInt64 time, UInt64 occupancy)
{
   UInt64 unit = 0;

   for (unsigned int i = 0; i < m_scoreboard.size(); i++)
   {
      if (m_scoreboard[i] <= time)
      {
         // a unit is available
         m_scoreboard[i] = time + occupancy;
         return time;
      }
      else
      {
         if (m_scoreboard[i] < m_scoreboard[unit])
            unit = i;
      }
   }

   // update unit, return time available
   m_scoreboard[unit] += occupancy;
   return m_scoreboard[unit] - occupancy;
}

IOCOOMPerformanceModel::StoreBuffer::StoreBuffer(unsigned int num_entries)
   : m_scoreboard(num_entries)
   , m_addresses(num_entries)
{
   for (unsigned int i = 0; i < m_scoreboard.size(); i++)
   {
      m_scoreboard[i] = 0;
      m_addresses[i] = 0;
   }
}

IOCOOMPerformanceModel::StoreBuffer::~StoreBuffer()
{
}

UInt64 IOCOOMPerformanceModel::StoreBuffer::executeStore(UInt64 time, UInt64 occupancy, IntPtr addr)
{
   // Note: basically identical to ExecutionUnit, except we need to
   // track addresses as well

   // is address already in buffer?
   for (unsigned int i = 0; i < m_scoreboard.size(); i++)
   {
      if (m_addresses[i] == addr)
      {
         m_scoreboard[i] = time + occupancy;
         return time;
      }
   }

   // if not, find earliest available entry
   unsigned int unit = 0;

   for (unsigned int i = 0; i < m_scoreboard.size(); i++)
   {
      if (m_scoreboard[i] <= time)
      {
         // a unit is available
         m_scoreboard[i] = time + occupancy;
         m_addresses[i] = addr;
         return time;
      }
      else
      {
         if (m_scoreboard[i] < m_scoreboard[unit])
            unit = i;
      }
   }

   // update unit, return time available
   m_scoreboard[unit] += occupancy;
   m_addresses[unit] = addr;
   return m_scoreboard[unit] - occupancy;
}

IOCOOMPerformanceModel::StoreBuffer::Status IOCOOMPerformanceModel::StoreBuffer::isAddressAvailable(UInt64 time, IntPtr addr)
{
   for (unsigned int i = 0; i < m_scoreboard.size(); i++)
   {
      if (m_addresses[i] == addr)
      {
         if (m_scoreboard[i] >= time)
            return VALID;
         else
            return COMPLETED;
      }
   }

   return NOT_FOUND;
}
<commit_msg>[perf] Don't model dynamic instructions in the icache.<commit_after>#include "iocoom_performance_model.h"

#include "log.h"
#include "dynamic_instruction_info.h"
#include "config.hpp"
#include "simulator.h"
#include "branch_predictor.h"

IOCOOMPerformanceModel::IOCOOMPerformanceModel()
   : m_instruction_count(0)
   , m_cycle_count(0)
   , m_register_scoreboard(512)
   , m_store_buffer(0)
   , m_load_unit(0)
   , m_l1_icache(0)
   , m_l1_dcache(0)
{
   config::Config *cfg = Sim()->getCfg();

   try
   {
      m_store_buffer = new StoreBuffer(cfg->getInt("perf_model/core/num_store_buffer_entries",1));
      m_load_unit = new ExecutionUnit(cfg->getInt("perf_model/core/num_outstanding_loads",3));

      if (cfg->getBool("perf_model/l1_icache/enable", false))
      {
         m_l1_icache = new ModeledCache(cfg->getInt("perf_model/l1_icache/line_size"),
                                        cfg->getInt("perf_model/l1_icache/num_sets"),
                                        cfg->getInt("perf_model/l1_icache/associativity"),
                                        cfg->getInt("perf_model/l1_icache/victim_cache_size"),
                                        cfg->getString("perf_model/l1_icache/replacement_policy") == "lru" ? ModeledCache::LRU : ModeledCache::RANDOM);
         m_l1_icache_miss_penalty = cfg->getInt("perf_model/l1_icache/miss_penalty");
      }

      if (cfg->getBool("perf_model/l1_dcache/enable", false))
      {
         m_l1_dcache = new ModeledCache(cfg->getInt("perf_model/l1_dcache/line_size"),
                                        cfg->getInt("perf_model/l1_dcache/num_sets"),
                                        cfg->getInt("perf_model/l1_dcache/associativity"),
                                        cfg->getInt("perf_model/l1_dcache/victim_cache_size"),
                                        cfg->getString("perf_model/l1_dcache/replacement_policy") == "lru" ? ModeledCache::LRU : ModeledCache::RANDOM);
         m_l1_dcache_access_time = cfg->getInt("perf_model/l1_dcache/access_time");
      }
   }
   catch (...)
   {
      LOG_PRINT_ERROR("Config info not available.");
   }

   for (unsigned int i = 0; i < m_register_scoreboard.size(); i++)
   {
      m_register_scoreboard[i] = 0;
   }
}

IOCOOMPerformanceModel::~IOCOOMPerformanceModel()
{
   delete m_l1_dcache;
   delete m_l1_icache;
   delete m_load_unit;
   delete m_store_buffer;
}

void IOCOOMPerformanceModel::outputSummary(std::ostream &os)
{
   os << "  Instructions: " << m_instruction_count << std::endl
      << "  Cycles: " << m_cycle_count << std::endl;

   if (getBranchPredictor())
      getBranchPredictor()->outputSummary(os);
}

UInt64 IOCOOMPerformanceModel::getCycleCount()
{
   return m_cycle_count;
}

void IOCOOMPerformanceModel::setCycleCount(UInt64 time)
{
   m_cycle_count = time;
}

void IOCOOMPerformanceModel::handleInstruction(Instruction *instruction)
{
   // icache modeling
   modelIcache(instruction->getAddress());

   /*
      model instruction in the following steps:
      - find when read operations are available
      - find latency of instruction
      - update write operands
   */
   const OperandList &ops = instruction->getOperands();

   // buffer write operands to be updated after instruction executes
   DynamicInstructionInfoQueue write_info;

   // find when read operands are available
   UInt64 operands_ready = m_cycle_count;
   UInt64 write_operands_ready = m_cycle_count;

   for (unsigned int i = 0; i < ops.size(); i++)
   {
      const Operand &o = ops[i];

      if (o.m_type == Operand::MEMORY)
      {
         DynamicInstructionInfo &info = getDynamicInstructionInfo();

         if (o.m_direction == Operand::READ)
         {
            LOG_ASSERT_ERROR(info.type == DynamicInstructionInfo::MEMORY_READ,
                             "Expected memory read info, got: %d.", info.type);

            UInt64 load_ready = executeLoad(info) - m_cycle_count;

            if (load_ready > operands_ready)
               operands_ready = load_ready;
         }
         else
         {
            LOG_ASSERT_ERROR(info.type == DynamicInstructionInfo::MEMORY_WRITE,
                             "Expected memory write info, got: %d.", info.type);

            write_info.push(info);
         }

         popDynamicInstructionInfo();
      }
      else if (o.m_type == Operand::REG)
      {
         LOG_ASSERT_ERROR(o.m_value < m_register_scoreboard.size(),
                          "Register value out of range: %llu", o.m_value);

         if (o.m_direction == Operand::READ)
         {
            if (m_register_scoreboard[o.m_value] > operands_ready)
               operands_ready = m_register_scoreboard[o.m_value];
         }
         else
         {
            if (m_register_scoreboard[o.m_value] > write_operands_ready)
               write_operands_ready = m_register_scoreboard[o.m_value];
         }
      }
      else
      {
         // immediate -- do nothing
      }
   }

   // update cycle count with instruction cost
   UInt64 cost = instruction->getCost();

   m_instruction_count++;
   m_cycle_count = operands_ready + cost;

   // update write memory operands. this is done before doing register
   // operands to make sure the scoreboard is updated correctly
   for (unsigned int i = 0; i < ops.size(); i++)
   {
      const Operand &o = ops[i];

      if (o.m_direction != Operand::WRITE)
         continue;

      if (o.m_type != Operand::MEMORY)
         continue;

      const DynamicInstructionInfo &info = write_info.front();
      UInt64 store_time = executeStore(info);
      write_info.pop();

      if (store_time > m_cycle_count)
         m_cycle_count = store_time;

      if (store_time > write_operands_ready)
         write_operands_ready = store_time;
   }

   // because we are modeling an in-order machine, if we encounter a
   // register that is being updated out-of-order by a memory
   // reference, we must stall until we can write the register
   if (write_operands_ready > m_cycle_count)
      m_cycle_count = write_operands_ready;

   // update write register operands.
   for (unsigned int i = 0; i < ops.size(); i++)
   {
      const Operand &o = ops[i];

      if (o.m_direction != Operand::WRITE)
         continue;

      if (o.m_type != Operand::REG)
         continue;

      LOG_ASSERT_ERROR(m_register_scoreboard[o.m_value] <= m_cycle_count,
                       "Expected cycle count to exceed destination register times, %llu < %llu.", m_register_scoreboard[o.m_value], m_cycle_count);

      m_register_scoreboard[o.m_value] = m_cycle_count;
   }

   LOG_ASSERT_ERROR(write_info.empty(), "Some write info left over?");
}

UInt64 IOCOOMPerformanceModel::executeLoad(const DynamicInstructionInfo &info)
{
   bool l2_hit = info.memory_info.num_misses == 0;

   // similarly, a miss in the l2 with a completed entry in the store
   // buffer is treated as an invalidation
   StoreBuffer::Status status = m_store_buffer->isAddressAvailable(m_cycle_count, info.memory_info.addr);

   if ((status == StoreBuffer::VALID) || (l2_hit && status == StoreBuffer::COMPLETED))
      return m_cycle_count;

   // a miss in the l2 forces a miss in the l1 and store buffer since
   // we assume an inclusive l2 cache (a miss in the l2 generally
   // means the block has been invalidated)
   bool l1_hit = m_l1_dcache && m_l1_dcache->access(info.memory_info.addr);
   l1_hit = l1_hit && l2_hit;

   UInt64 latency  = l1_hit ? m_l1_dcache_access_time : info.memory_info.latency;

   return m_load_unit->execute(m_cycle_count, latency);
}

UInt64 IOCOOMPerformanceModel::executeStore(const DynamicInstructionInfo &info)
{
   bool l2_hit = info.memory_info.num_misses == 0;
   bool l1_hit = m_l1_dcache && m_l1_dcache->access(info.memory_info.addr);
   l1_hit = l1_hit && l2_hit;

   UInt64 latency = l1_hit ? m_l1_dcache_access_time : info.memory_info.latency;

   return m_store_buffer->executeStore(m_cycle_count, latency, info.memory_info.addr);
}

void IOCOOMPerformanceModel::modelIcache(IntPtr addr)
{
   if (!m_l1_icache || addr == 0)
      return;

   bool hit = m_l1_icache->access(addr);
   if (!hit)
      m_cycle_count += m_l1_icache_miss_penalty;
}

// Helper classes

IOCOOMPerformanceModel::ExecutionUnit::ExecutionUnit(unsigned int num_units)
   : m_scoreboard(num_units)
{
   for (unsigned int i = 0; i < m_scoreboard.size(); i++)
   {
      m_scoreboard[i] = 0;
   }
}

IOCOOMPerformanceModel::ExecutionUnit::~ExecutionUnit()
{
}

UInt64 IOCOOMPerformanceModel::ExecutionUnit::execute(UInt64 time, UInt64 occupancy)
{
   UInt64 unit = 0;

   for (unsigned int i = 0; i < m_scoreboard.size(); i++)
   {
      if (m_scoreboard[i] <= time)
      {
         // a unit is available
         m_scoreboard[i] = time + occupancy;
         return time;
      }
      else
      {
         if (m_scoreboard[i] < m_scoreboard[unit])
            unit = i;
      }
   }

   // update unit, return time available
   m_scoreboard[unit] += occupancy;
   return m_scoreboard[unit] - occupancy;
}

IOCOOMPerformanceModel::StoreBuffer::StoreBuffer(unsigned int num_entries)
   : m_scoreboard(num_entries)
   , m_addresses(num_entries)
{
   for (unsigned int i = 0; i < m_scoreboard.size(); i++)
   {
      m_scoreboard[i] = 0;
      m_addresses[i] = 0;
   }
}

IOCOOMPerformanceModel::StoreBuffer::~StoreBuffer()
{
}

UInt64 IOCOOMPerformanceModel::StoreBuffer::executeStore(UInt64 time, UInt64 occupancy, IntPtr addr)
{
   // Note: basically identical to ExecutionUnit, except we need to
   // track addresses as well

   // is address already in buffer?
   for (unsigned int i = 0; i < m_scoreboard.size(); i++)
   {
      if (m_addresses[i] == addr)
      {
         m_scoreboard[i] = time + occupancy;
         return time;
      }
   }

   // if not, find earliest available entry
   unsigned int unit = 0;

   for (unsigned int i = 0; i < m_scoreboard.size(); i++)
   {
      if (m_scoreboard[i] <= time)
      {
         // a unit is available
         m_scoreboard[i] = time + occupancy;
         m_addresses[i] = addr;
         return time;
      }
      else
      {
         if (m_scoreboard[i] < m_scoreboard[unit])
            unit = i;
      }
   }

   // update unit, return time available
   m_scoreboard[unit] += occupancy;
   m_addresses[unit] = addr;
   return m_scoreboard[unit] - occupancy;
}

IOCOOMPerformanceModel::StoreBuffer::Status IOCOOMPerformanceModel::StoreBuffer::isAddressAvailable(UInt64 time, IntPtr addr)
{
   for (unsigned int i = 0; i < m_scoreboard.size(); i++)
   {
      if (m_addresses[i] == addr)
      {
         if (m_scoreboard[i] >= time)
            return VALID;
         else
            return COMPLETED;
      }
   }

   return NOT_FOUND;
}
<|endoftext|>


<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

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.
==============================================================================*/
#include <vector>

#include "tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h"
#include "tensorflow/contrib/lite/toco/model.h"
#include "tensorflow/contrib/lite/toco/tooling_util.h"
#include "tensorflow/core/platform/logging.h"

namespace toco {

bool ConvertTrivialTransposeToReshape::Run(Model* model, std::size_t op_index) {
  auto transpose_it = model->operators.begin() + op_index;
  if (transpose_it->get()->type != OperatorType::kTranspose) {
    return false;
  }
  TransposeOperator* transpose_op =
      static_cast<TransposeOperator*>(transpose_it->get());

  const auto& output_array = model->GetArray(transpose_op->outputs[0]);
  if (!output_array.has_shape()) {
    // Yield until PropagateFixedSizes has been run on this op.
    return false;
  }
  // Note: We can assume we have error checked inputs in PropagateFixedSizes.

  // This transpose is trivial if we only have one non-unitary dimension.
  std::vector<int> const& dims = output_array.shape().dims();
  unsigned non_unitary_axis_count = 0;
  for (int i = 0; i < dims.size(); i++) {
    if (dims[i] != 1) {
      non_unitary_axis_count++;
    }
  }
  if (non_unitary_axis_count > 1) {
    // Transpose is not trivial
    return false;
  }

  // This transpose is trivial. Replace it with a Reshape op.
  auto* reshape_op = new TensorFlowReshapeOperator;

  // Copy input and output
  reshape_op->inputs.push_back(transpose_op->inputs[0]);
  reshape_op->outputs = transpose_op->outputs;

  // Create a new input array for the shape input
  string perm_array_name = transpose_op->inputs[1];
  string shape_array_name = toco::AvailableArrayName(*model, perm_array_name);
  Array& shape_array = model->GetOrCreateArray(shape_array_name);
  *(shape_array.mutable_shape()->mutable_dims()) = {
      1, static_cast<int>(dims.size())};
  reshape_op->inputs.push_back(shape_array_name);
  shape_array.data_type = ArrayDataType::kInt32;
  auto& shape_buffer = shape_array.GetMutableBuffer<ArrayDataType::kInt32>();
  shape_buffer.data = dims;

  // Delete perm array if unused
  if (IsDiscardableArray(*model, perm_array_name) &&
      CountOpsWithInput(*model, perm_array_name) == 1) {
    model->EraseArray(perm_array_name);
  }

  // Replace the operator in the graph.
  const auto reshape_it = model->operators.emplace(transpose_it, reshape_op);
  transpose_it = reshape_it + 1;
  CHECK_EQ(transpose_it->get(), transpose_op);
  model->operators.erase(transpose_it);

  return true;
}

}  // namespace toco
<commit_msg>Transposes are can be merged into reshapes when the ordering of non-one dimensions remains unchanged.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

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.
==============================================================================*/
#include <vector>

#include "tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h"
#include "tensorflow/contrib/lite/toco/model.h"
#include "tensorflow/contrib/lite/toco/tooling_util.h"
#include "tensorflow/core/platform/logging.h"

namespace toco {

namespace {

bool TransposeAffectsMemoryOrder(std::vector<int> perm,
                                 std::vector<int> in_shape) {
  CHECK_EQ(perm.size(), in_shape.size());
  // See what the ordering of the non-unary columns are before and after
  // transpose permutation. If the major indices stay in the same order (not
  // just the shape) then the flat buffer representation shouldn't change.
  std::vector<int> old_major_index_ordering;
  std::vector<int> new_major_index_ordering;
  for (int i = 0; i < in_shape.size(); i++) {
    if (in_shape[i] != 1) {
      old_major_index_ordering.push_back(i);
    }

    if (in_shape[perm[i]] != 1) {
      new_major_index_ordering.push_back(perm[i]);
    }
  }

  CHECK_EQ(new_major_index_ordering.size(), old_major_index_ordering.size());

  return old_major_index_ordering != new_major_index_ordering;
}

}  // namespace

bool ConvertTrivialTransposeToReshape::Run(Model* model, std::size_t op_index) {
  auto transpose_it = model->operators.begin() + op_index;
  if (transpose_it->get()->type != OperatorType::kTranspose) {
    return false;
  }
  TransposeOperator* transpose_op =
      static_cast<TransposeOperator*>(transpose_it->get());

  const auto& input_array = model->GetArray(transpose_op->inputs[0]);
  const auto& output_array = model->GetArray(transpose_op->outputs[0]);
  if (!input_array.has_shape() || !output_array.has_shape()) {
    // Yield until PropagateFixedSizes has been run on this op.
    return false;
  }
  // Note: We can assume we have error checked inputs in PropagateFixedSizes.

  // Check that the permutation has propogated.
  std::vector<int> const& perm = transpose_op->perm;
  if (perm.empty()) {
    return false;
  }

  // This transpose is trivial if non-unitary dimensions remain in the same
  // order.
  std::vector<int> const& input_dims = input_array.shape().dims();
  std::vector<int> const& output_dims = output_array.shape().dims();

  if (TransposeAffectsMemoryOrder(perm, input_dims)) {
    return false;
  }

  // This transpose is trivial. Replace it with a Reshape op.
  auto* reshape_op = new TensorFlowReshapeOperator;

  // Copy input and output
  reshape_op->inputs.push_back(transpose_op->inputs[0]);
  reshape_op->outputs = transpose_op->outputs;

  // Create a new input array for the shape input
  string perm_array_name = transpose_op->inputs[1];
  string shape_array_name = toco::AvailableArrayName(*model, perm_array_name);
  Array& shape_array = model->GetOrCreateArray(shape_array_name);
  *(shape_array.mutable_shape()->mutable_dims()) = {
      1, static_cast<int>(output_dims.size())};
  reshape_op->inputs.push_back(shape_array_name);
  shape_array.data_type = ArrayDataType::kInt32;
  auto& shape_buffer = shape_array.GetMutableBuffer<ArrayDataType::kInt32>();
  shape_buffer.data = output_dims;

  // Delete perm array if unused
  if (IsDiscardableArray(*model, perm_array_name) &&
      CountOpsWithInput(*model, perm_array_name) == 1) {
    model->EraseArray(perm_array_name);
  }

  // Replace the operator in the graph.
  const auto reshape_it = model->operators.emplace(transpose_it, reshape_op);
  transpose_it = reshape_it + 1;
  CHECK_EQ(transpose_it->get(), transpose_op);
  model->operators.erase(transpose_it);

  return true;
}

}  // namespace toco
<|endoftext|>


<commit_before>//==============================================================================
// CellML annotation view metadata edit details widget
//==============================================================================

#include "cellmlannotationviewlistswidget.h"
#include "cellmlannotationviewmetadataeditdetailswidget.h"
#include "cellmlannotationviewmetadatalistwidget.h"
#include "cellmlannotationviewwidget.h"
#include "coreutils.h"
#include "treeview.h"

//==============================================================================

#include "ui_cellmlannotationviewmetadataeditdetailswidget.h"

//==============================================================================

#include <QComboBox>
#include <QFormLayout>
#include <QLabel>
#include <QLineEdit>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QStackedWidget>
#include <QVariant>
#include <QVBoxLayout>

//==============================================================================

#include <QJsonParser>

//==============================================================================

namespace OpenCOR {
namespace CellMLAnnotationView {

//==============================================================================

CellmlAnnotationViewMetadataEditDetailsWidget::CellmlAnnotationViewMetadataEditDetailsWidget(CellmlAnnotationViewWidget *pParent) :
    QScrollArea(pParent),
    CommonWidget(pParent),
    mGui(new Ui::CellmlAnnotationViewMetadataEditDetailsWidget),
    mMainWidget(0),
    mMainLayout(0),
    mFormWidget(0),
    mFormLayout(0),
    mGridWidget(0),
    mGridLayout(0),
    mErrorMsg(QString()),
    mTerm(QString()),
    mTermUrl(QString()),
    mOtherTermUrl(QString())
{
    // Set up the GUI

    mGui->setupUi(this);

    // Create a stacked widget which will contain our GUI

    mWidget = new QStackedWidget(this);

    // Add our stacked widget to our scroll area

    setWidget(mWidget);

    // Create a network access manager so that we can then retrieve a list of
    // CellML models from the CellML Model Repository

    mNetworkAccessManager = new QNetworkAccessManager(this);

    // Make sure that we get told when the download of our Internet file is
    // complete

    connect(mNetworkAccessManager, SIGNAL(finished(QNetworkReply *)),
            this, SLOT(finished(QNetworkReply *)) );
}

//==============================================================================

CellmlAnnotationViewMetadataEditDetailsWidget::~CellmlAnnotationViewMetadataEditDetailsWidget()
{
    // Delete the GUI

    delete mGui;
}

//==============================================================================

void CellmlAnnotationViewMetadataEditDetailsWidget::retranslateUi()
{
    // Retranslate our GUI

    mGui->retranslateUi(this);

    // For the rest of our GUI, it's easier to just update it, so...

    updateGui();
}

//==============================================================================

void CellmlAnnotationViewMetadataEditDetailsWidget::updateGui(const bool &pPopulate)
{
    // Note: we are using certain layouts to dislay the contents of our view,
    //       but this unfortunately results in some very bad flickering on Mac
    //       OS X. This can, however, be addressed using a stacked widget, so...

    // Prevent ourselves from being updated (to avoid any flickering)

    setUpdatesEnabled(false);

    // Create a widget which will contain our GUI

    QWidget *newMainWidget = new QWidget(this);
    QVBoxLayout *newMainLayout = new QVBoxLayout(newMainWidget);

    newMainLayout->setMargin(0);

    newMainWidget->setLayout(newMainLayout);

    // Populate our GUI, but only if requested

    QWidget *newFormWidget = 0;
    QFormLayout *newFormLayout = 0;
    QWidget *newGridWidget = 0;
    QGridLayout *newGridLayout = 0;

    if (pPopulate) {
        // Deal with the form part of our GUI

        // Create a form widget which will contain our qualifier and term fields

        newFormWidget = new QWidget(newMainWidget);
        newFormLayout = new QFormLayout(newFormWidget);

        newFormWidget->setLayout(newFormLayout);

        // Add our qualifier and term fields

        QComboBox *qualifierValue = new QComboBox(newFormWidget);

        qualifierValue->addItems(CellMLSupport::CellmlFileRdfTriple::qualifiersAsStringList());

        newFormLayout->addRow(Core::newLabel(newFormWidget, tr("Qualifier:"), true),
                              qualifierValue);

        QLineEdit *termValue = new QLineEdit(newFormWidget);

        termValue->setText(mTerm);

        connect(termValue, SIGNAL(textChanged(const QString &)),
                this, SLOT(lookupTerm(const QString &)));

        newFormLayout->addRow(Core::newLabel(newFormWidget, tr("Term:"), true),
                              termValue);

        // Let people know that the GUI has been populated

        emit guiPopulated(qualifierValue, termValue);

        // Deal with the grid part of our GUI

        // Create a new widget and layout

        newGridWidget = new QWidget(newMainWidget);
        newGridLayout = new QGridLayout(newGridWidget);

        newGridWidget->setLayout(newGridLayout);

        // Populate our new layout, but only if there is at least one RDF triple
        // Note: the two calls to setRowStretch() ensures that our grid layout
        //       takes as much vertical space as possible (otherwise our form
        //       layout might take some vertical space making it look a bit odd
        //       if there are no data available)...

        newGridLayout->setRowStretch(0, 1);

        newGridLayout->addWidget(Core::newLabel(newMainWidget,
                                                tr("No data available..."),
                                                false, 1.25, Qt::AlignCenter),
                                 1, 0);

        newGridLayout->setRowStretch(2, 1);

        // Add our 'internal' widgets to our new main widget

        newMainLayout->addWidget(newFormWidget);
        newMainLayout->addWidget(Core::newLineWidget(newMainWidget));
        newMainLayout->addWidget(newGridWidget);
    }

    // Add our new widget to our stacked widget

    mWidget->addWidget(newMainWidget);

    // Remove the contents of our old form layout

    if (mFormWidget)
        for (int i = 0, iMax = mFormLayout->count(); i < iMax; ++i) {
            QLayoutItem *item = mFormLayout->takeAt(0);

            delete item->widget();
            delete item;
        }

    // Remove the contents of our old grid layout

    if (mGridWidget)
        for (int i = 0, iMax = mGridLayout->count(); i < iMax; ++i) {
            QLayoutItem *item = mGridLayout->takeAt(0);

            delete item->widget();
            delete item;
        }

    // Get rid of our old main widget and layout (and its contents)

    if (mMainWidget) {
        mWidget->removeWidget(mMainWidget);

        for (int i = 0, iMax = mMainLayout->count(); i < iMax; ++i) {
            QLayoutItem *item = mMainLayout->takeAt(0);

            delete item->widget();
            delete item;
        }

        delete mMainWidget;
    }

    // Keep track of our new main widgets and layouts

    mMainWidget = newMainWidget;
    mMainLayout = newMainLayout;

    mFormWidget = newFormWidget;
    mFormLayout = newFormLayout;

    mGridWidget = newGridWidget;
    mGridLayout = newGridLayout;

    // Allow ourselves to be updated again

    setUpdatesEnabled(true);
}

//==============================================================================

void CellmlAnnotationViewMetadataEditDetailsWidget::lookupTerm(const QString &pTerm)
{
    // Keep track of the term to lookup

    mTerm = pTerm;

    // Retrieve some possible ontological terms based on the given term

    QString termUrl = QString("http://www.semanticsbml.org/semanticSBML/annotate/search.json?q=%1&full_info=1").arg(pTerm);

    if (mTermUrl.isEmpty()) {
        // No other term is being looked up, so keep track of the given term and
        // look it up

        mTermUrl = termUrl;

        mNetworkAccessManager->get(QNetworkRequest(termUrl));
    } else {
        // Another term is already being looked up, so keep track of the given
        // term for later

        mOtherTermUrl = termUrl;
    }
}

//==============================================================================

void CellmlAnnotationViewMetadataEditDetailsWidget::finished(QNetworkReply *pNetworkReply)
{
    // Output the list of models, should we have retrieved it without any
    // problem

    if (pNetworkReply->error() == QNetworkReply::NoError) {
        // Parse the JSON code

        QJson::Parser jsonParser;
        bool parsingOk;

        QVariantMap resultMap = jsonParser.parse(pNetworkReply->readAll(), &parsingOk).toMap();

static int counter = 0;
qDebug("---[%03d]--------------------------------------", ++counter);
qDebug("URL: %s", qPrintable(pNetworkReply->url().toString()));

        if (parsingOk) {
            // Retrieve the list of CellML models

            foreach (const QVariant &ontologicalsTermVariant, resultMap["result"].toList()) {
                QVariantList ontologicalTermVariant = ontologicalsTermVariant.toList();

                for (int i = 0, iMax = ontologicalTermVariant.count(); i < iMax; ++i) {
                    QVariantMap ontologicalTermMap = ontologicalTermVariant[i].toMap();

qDebug(">>> %s ---> %s", qPrintable(ontologicalTermMap["uri"].toString()),
                         qPrintable(ontologicalTermMap["name"].toString()));
                }
            }

            // Everything went fine, so...

            mErrorMsg = QString();
        } else {
            // Something went wrong, so...

            mErrorMsg = jsonParser.errorString();
        }
    } else {
        // Something went wrong, so...

        mErrorMsg = pNetworkReply->errorString();
    }

    // We are done, so...

    mTermUrl = QString();

    // Check whether there is another term to look up

    if (!mOtherTermUrl.isEmpty()) {
        mNetworkAccessManager->get(QNetworkRequest(mOtherTermUrl));

        mOtherTermUrl = QString();
    }
}

//==============================================================================

}   // namespace CellMLAnnotationView
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some work on the addition of RDF triples (#90).<commit_after>//==============================================================================
// CellML annotation view metadata edit details widget
//==============================================================================

#include "cellmlannotationviewlistswidget.h"
#include "cellmlannotationviewmetadataeditdetailswidget.h"
#include "cellmlannotationviewmetadatalistwidget.h"
#include "cellmlannotationviewwidget.h"
#include "coreutils.h"
#include "treeview.h"

//==============================================================================

#include "ui_cellmlannotationviewmetadataeditdetailswidget.h"

//==============================================================================

#include <QComboBox>
#include <QFormLayout>
#include <QLabel>
#include <QLineEdit>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QStackedWidget>
#include <QVariant>
#include <QVBoxLayout>

//==============================================================================

#include <QJsonParser>

//==============================================================================

namespace OpenCOR {
namespace CellMLAnnotationView {

//==============================================================================

CellmlAnnotationViewMetadataEditDetailsWidget::CellmlAnnotationViewMetadataEditDetailsWidget(CellmlAnnotationViewWidget *pParent) :
    QScrollArea(pParent),
    CommonWidget(pParent),
    mGui(new Ui::CellmlAnnotationViewMetadataEditDetailsWidget),
    mMainWidget(0),
    mMainLayout(0),
    mFormWidget(0),
    mFormLayout(0),
    mGridWidget(0),
    mGridLayout(0),
    mErrorMsg(QString()),
    mTerm(QString()),
    mTermUrl(QString()),
    mOtherTermUrl(QString())
{
    // Set up the GUI

    mGui->setupUi(this);

    // Create a stacked widget which will contain our GUI

    mWidget = new QStackedWidget(this);

    // Add our stacked widget to our scroll area

    setWidget(mWidget);

    // Create a network access manager so that we can then retrieve a list of
    // CellML models from the CellML Model Repository

    mNetworkAccessManager = new QNetworkAccessManager(this);

    // Make sure that we get told when the download of our Internet file is
    // complete

    connect(mNetworkAccessManager, SIGNAL(finished(QNetworkReply *)),
            this, SLOT(finished(QNetworkReply *)) );
}

//==============================================================================

CellmlAnnotationViewMetadataEditDetailsWidget::~CellmlAnnotationViewMetadataEditDetailsWidget()
{
    // Delete the GUI

    delete mGui;
}

//==============================================================================

void CellmlAnnotationViewMetadataEditDetailsWidget::retranslateUi()
{
    // Retranslate our GUI

    mGui->retranslateUi(this);

    // For the rest of our GUI, it's easier to just update it, so...

    updateGui();
}

//==============================================================================

void CellmlAnnotationViewMetadataEditDetailsWidget::updateGui(const bool &pPopulate)
{
    // Note: we are using certain layouts to dislay the contents of our view,
    //       but this unfortunately results in some very bad flickering on Mac
    //       OS X. This can, however, be addressed using a stacked widget, so...

    // Prevent ourselves from being updated (to avoid any flickering)

    setUpdatesEnabled(false);

    // Create a widget which will contain our GUI

    QWidget *newMainWidget = new QWidget(this);
    QVBoxLayout *newMainLayout = new QVBoxLayout(newMainWidget);

    newMainLayout->setMargin(0);

    newMainWidget->setLayout(newMainLayout);

    // Populate our GUI, but only if requested

    QWidget *newFormWidget = 0;
    QFormLayout *newFormLayout = 0;
    QWidget *newGridWidget = 0;
    QGridLayout *newGridLayout = 0;

    QLineEdit *termValue = 0;

    if (pPopulate) {
        // Deal with the form part of our GUI

        // Create a form widget which will contain our qualifier and term fields

        newFormWidget = new QWidget(newMainWidget);
        newFormLayout = new QFormLayout(newFormWidget);

        newFormWidget->setLayout(newFormLayout);

        // Add our qualifier and term fields

        QComboBox *qualifierValue = new QComboBox(newFormWidget);

        qualifierValue->addItems(CellMLSupport::CellmlFileRdfTriple::qualifiersAsStringList());

        newFormLayout->addRow(Core::newLabel(newFormWidget, tr("Qualifier:"), true),
                              qualifierValue);

        termValue = new QLineEdit(newFormWidget);

        connect(termValue, SIGNAL(textChanged(const QString &)),
                this, SLOT(lookupTerm(const QString &)));

        newFormLayout->addRow(Core::newLabel(newFormWidget, tr("Term:"), true),
                              termValue);

        // Let people know that the GUI has been populated

        emit guiPopulated(qualifierValue, termValue);

        // Deal with the grid part of our GUI

        // Create a new widget and layout

        newGridWidget = new QWidget(newMainWidget);
        newGridLayout = new QGridLayout(newGridWidget);

        newGridWidget->setLayout(newGridLayout);

        // Populate our new layout, but only if there is at least one RDF triple
        // Note: the two calls to setRowStretch() ensures that our grid layout
        //       takes as much vertical space as possible (otherwise our form
        //       layout might take some vertical space making it look a bit odd
        //       if there are no data available)...

        newGridLayout->setRowStretch(0, 1);

        newGridLayout->addWidget(Core::newLabel(newMainWidget,
                                                tr("No data available..."),
                                                false, 1.25, Qt::AlignCenter),
                                 1, 0);

        newGridLayout->setRowStretch(2, 1);

        // Add our 'internal' widgets to our new main widget

        newMainLayout->addWidget(newFormWidget);
        newMainLayout->addWidget(Core::newLineWidget(newMainWidget));
        newMainLayout->addWidget(newGridWidget);
    }

    // Add our new widget to our stacked widget

    mWidget->addWidget(newMainWidget);

    // Remove the contents of our old form layout

    if (mFormWidget)
        for (int i = 0, iMax = mFormLayout->count(); i < iMax; ++i) {
            QLayoutItem *item = mFormLayout->takeAt(0);

            delete item->widget();
            delete item;
        }

    // Remove the contents of our old grid layout

    if (mGridWidget)
        for (int i = 0, iMax = mGridLayout->count(); i < iMax; ++i) {
            QLayoutItem *item = mGridLayout->takeAt(0);

            delete item->widget();
            delete item;
        }

    // Get rid of our old main widget and layout (and its contents)

    if (mMainWidget) {
        mWidget->removeWidget(mMainWidget);

        for (int i = 0, iMax = mMainLayout->count(); i < iMax; ++i) {
            QLayoutItem *item = mMainLayout->takeAt(0);

            delete item->widget();
            delete item;
        }

        delete mMainWidget;
    }

    // Keep track of our new main widgets and layouts

    mMainWidget = newMainWidget;
    mMainLayout = newMainLayout;

    mFormWidget = newFormWidget;
    mFormLayout = newFormLayout;

    mGridWidget = newGridWidget;
    mGridLayout = newGridLayout;

    // Reset the term which was being looked up, if any

    if (termValue)
        termValue->setText(mTerm);

    // Allow ourselves to be updated again

    setUpdatesEnabled(true);
}

//==============================================================================

void CellmlAnnotationViewMetadataEditDetailsWidget::lookupTerm(const QString &pTerm)
{
    // Keep track of the term to lookup

    mTerm = pTerm;

    // Retrieve some possible ontological terms based on the given term

    QString termUrl = QString("http://www.semanticsbml.org/semanticSBML/annotate/search.json?q=%1&full_info=1").arg(pTerm);

    if (mTermUrl.isEmpty()) {
        // No other term is being looked up, so keep track of the given term and
        // look it up

        mTermUrl = termUrl;

        mNetworkAccessManager->get(QNetworkRequest(termUrl));
    } else {
        // Another term is already being looked up, so keep track of the given
        // term for later

        mOtherTermUrl = termUrl;
    }
}

//==============================================================================

void CellmlAnnotationViewMetadataEditDetailsWidget::finished(QNetworkReply *pNetworkReply)
{
    // Output the list of models, should we have retrieved it without any
    // problem

    if (pNetworkReply->error() == QNetworkReply::NoError) {
        // Parse the JSON code

        QJson::Parser jsonParser;
        bool parsingOk;

        QVariantMap resultMap = jsonParser.parse(pNetworkReply->readAll(), &parsingOk).toMap();

static int counter = 0;
qDebug("---[%03d]--------------------------------------", ++counter);
qDebug("URL: %s", qPrintable(pNetworkReply->url().toString()));

        if (parsingOk) {
            // Retrieve the list of CellML models

            foreach (const QVariant &ontologicalsTermVariant, resultMap["result"].toList()) {
                QVariantList ontologicalTermVariant = ontologicalsTermVariant.toList();

                for (int i = 0, iMax = ontologicalTermVariant.count(); i < iMax; ++i) {
                    QVariantMap ontologicalTermMap = ontologicalTermVariant[i].toMap();

qDebug(">>> %s ---> %s", qPrintable(ontologicalTermMap["uri"].toString()),
                         qPrintable(ontologicalTermMap["name"].toString()));
                }
            }

            // Everything went fine, so...

            mErrorMsg = QString();
        } else {
            // Something went wrong, so...

            mErrorMsg = jsonParser.errorString();
        }
    } else {
        // Something went wrong, so...

        mErrorMsg = pNetworkReply->errorString();
    }

    // We are done, so...

    mTermUrl = QString();

    // Check whether there is another term to look up

    if (!mOtherTermUrl.isEmpty()) {
        mNetworkAccessManager->get(QNetworkRequest(mOtherTermUrl));

        mOtherTermUrl = QString();
    }
}

//==============================================================================

}   // namespace CellMLAnnotationView
}   // namespace OpenCOR

//==============================================================================
// End of file
//==============================================================================
<|endoftext|>


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

#include <precomp.h>
#include "navibar.hxx"

// NOT FULLY DEFINED SERVICES
#include <cosv/template/tpltools.hxx>
#include "nav_main.hxx"
#include "opageenv.hxx"

using namespace csi::xml;
using namespace csi::html;

namespace
{

//************************      SubRowItem      ***************************//

class SubRowItem
{
  public:
                        SubRowItem(
                            const char *        i_sText,
                            const char *        i_sLink,
                            bool                i_bActive,
                            bool                i_bFirstOfRow = false );
                        ~SubRowItem();

    void                Write2(
                            Element &           o_rOut ) const;
  private:
    udmstri             sText;
    udmstri             sLink;
    bool                bIsActive;
    bool                bFirstOfRow;
};

SubRowItem::SubRowItem( const char *        i_sText,
                        const char *        i_sLink,
                        bool                i_bActive,
                        bool                i_bFirstOfRow )
    :   sText(i_sText),
        sLink(i_sLink),
        bIsActive(i_bActive),
        bFirstOfRow(i_bFirstOfRow)
{
    csv_assert( NOT csv::no_str(i_sLink) );
}

SubRowItem::~SubRowItem()
{
}

void
SubRowItem::Write2( Element & o_rOut ) const
{
    o_rOut << new Sbr;
    if ( NOT bFirstOfRow )
        o_rOut << new XmlCode( "| " );
    else
        o_rOut << new XmlCode( " " );

    if ( bIsActive )
    {
        o_rOut
            >> *new Link( sLink.c_str() )
                >> *new AnElement( "font" )
                    << new AnAttribute("size","-2")
                    >> *new Bold
                        << sText.c_str();
    }
    else
    {
        o_rOut
            >> *new AnElement( "font" )
                << new AnAttribute("size","-2")
                << sText.c_str();
    }
}

//************************      SubRow      ***************************//

class SubRow
{
  public:
                        SubRow(
                            const char *        i_sTitle );
                        ~SubRow();

    void                AddItem(
                            const char *        i_sText,
                            const char *        i_sLink,
                            bool                i_bActive );
    void                Write2(
                            Table &             o_rOut ) const;
  private:
    typedef std::vector< DYN SubRowItem * >   List_Items;

    List_Items          aItemList;
    udmstri             sTitle;
};

SubRow::SubRow( const char * i_sTitle )
//  :   // aItemList,
        // sTitle
{
    StreamStr sUp(i_sTitle,0);
    sUp.to_upper();
    sTitle = sUp.c_str();
}

SubRow::~SubRow()
{
}

inline void
SubRow::AddItem( const char *        i_sText,
                 const char *        i_sLink,
                 bool                i_bActive )
{
    aItemList.push_back( new SubRowItem(i_sText, i_sLink, i_bActive, aItemList.empty()) );
}

void
SubRow::Write2( Table & o_rOut ) const
{
    TableRow * pRow = new TableRow;
    o_rOut << pRow;

    if (sTitle.length() > 0)
    {
        Element & rCell1 = pRow->AddCell();
        rCell1
            << new WidthAttr("20%")
            >> *new AnElement( "font" )
                    << new AnAttribute("size","-2")
                       << sTitle
                       << ":";
    }

    Element & rCell2 = pRow->AddCell();
    for ( List_Items::const_iterator it = aItemList.begin();
          it != aItemList.end();
          ++it )
    {
         (*it)->Write2( rCell2 );
    }
}

}   // anonymous namespace

//*************************      CheshireCat     ***********************//

typedef std::vector< DYN SubRow * >   List_SubRows;

struct NavigationBar::CheshireCat
{
    MainRow             aMainRow;
    List_SubRows        aSubRows;
    const OuputPage_Environment *
                        pEnv;

                        CheshireCat(
                            const OuputPage_Environment &
                                                i_rEnv );
                        ~CheshireCat();
};

NavigationBar::
CheshireCat::CheshireCat( const OuputPage_Environment & i_rEnv )
    :   aMainRow( i_rEnv ),
        pEnv( & i_rEnv )
{
}

NavigationBar::
CheshireCat::~CheshireCat()
{
    csv::erase_container_of_heap_ptrs( aSubRows );
}

//************************       NavigationBar       *******************//

NavigationBar::NavigationBar( const OuputPage_Environment & i_rEnv,
                              E_GlobalLocation              i_eLocation )
    :   pi( new CheshireCat(i_rEnv) )
{
    switch (i_eLocation)
    {
         case LOC_Overview:  pi->aMainRow.SetupItems_Overview();  break;
         case LOC_AllDefs:   pi->aMainRow.SetupItems_AllDefs();   break;
        case LOC_Index:     pi->aMainRow.SetupItems_Index();     break;
        case LOC_Help:      pi->aMainRow.SetupItems_Help();      break;
        default:
                            csv_assert(false);
    }
}

NavigationBar::NavigationBar( const OuputPage_Environment & i_rEnv,
                              const ary::CodeEntity &       i_rCe  )
    :   pi( new CheshireCat(i_rEnv) )
{
    pi->aMainRow.SetupItems_Ce( i_rCe );
}

NavigationBar::NavigationBar( const OuputPage_Environment & i_rEnv,
                              E_CeGatheringType             i_eCeGatheringType,
                              const ary::cpp::FileGroup *   i_pFile )
    :   pi( new CheshireCat(i_rEnv) )
{
    if ( i_rEnv.CurClass() != 0 )
    {
        switch (i_eCeGatheringType)
        {
             case CEGT_operations:   pi->aMainRow.SetupItems_FunctionGroup();  break;
            case CEGT_data:         pi->aMainRow.SetupItems_DataGroup();      break;
            default:
                                    csv_assert(false);
        }
    }
    else
    {
        csv_assert( i_pFile != 0 );
        switch (i_eCeGatheringType)
        {
             case CEGT_operations:   pi->aMainRow.SetupItems_FunctionGroup(*i_pFile);  break;
            case CEGT_data:         pi->aMainRow.SetupItems_DataGroup(*i_pFile);      break;
            default:
                                    csv_assert(false);
        }
    }
}

NavigationBar::NavigationBar( const OuputPage_Environment &     i_rEnv,
                              const ary::cpp::ProjectGroup *    i_pPrj,
                              const ary::cpp::FileGroup *       i_pFile )
    :   pi( new CheshireCat(i_rEnv) )
{
    if ( i_pPrj == 0 )
    {
        pi->aMainRow.SetupItems_Project();
        return;
    }
    if ( i_pFile == 0 )
    {
        pi->aMainRow.SetupItems_File( *i_pPrj );
        return;
    }

    pi->aMainRow.SetupItems_DefinitionsGroup( *i_pPrj, *i_pFile );
}

NavigationBar::~NavigationBar()
{
    csv::erase_container_of_heap_ptrs( pi->aSubRows );
}

void
NavigationBar::MakeSubRow( const char * i_sTitle )
{
    pi->aSubRows.push_back( new SubRow(i_sTitle) );
}

void
NavigationBar::AddItem( const char *        i_sName,
                        const char *        i_sLink,
                        bool                i_bValid )
{
    csv_assert( pi->aSubRows.size() > 0 );
    StreamStr sName(i_sName, 0);
    sName.to_upper();

    StreamLock aSum(100);
    pi->aSubRows.back()->AddItem( sName.c_str(),
                                  aSum() << "#" << i_sLink << c_str,
                                  i_bValid );
}

void
NavigationBar::Write( Element &  o_rOut,
                      bool       i_bWithSubRows ) const
{
    pi->aMainRow.Write2( o_rOut );

    const_cast< NavigationBar* >(this)->pSubRowsTable = new Table;
    o_rOut << pSubRowsTable;
    *pSubRowsTable
        << new AnAttribute("class", "navisub")
        << new AnAttribute( "cellpadding", "0" )
        << new AnAttribute( "cellspacing", "3" );

    if (i_bWithSubRows)
    {
        o_rOut >> *new TableRow >> *new Paragraph << " ";
        Write_SubRows();
    }
}

void
NavigationBar::Write_SubRows() const
{
    for ( List_SubRows::const_iterator it = pi->aSubRows.begin();
          it != pi->aSubRows.end();
          ++it )
    {
         (*it)->Write2( *pSubRowsTable );
    }
}

<commit_msg>INTEGRATION: CWS adc18 (1.5.2); FILE MERGED 2007/10/17 13:28:03 np 1.5.2.1: #i82716#<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: navibar.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: hr $ $Date: 2007-11-02 16:28:54 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#include <precomp.h>
#include "navibar.hxx"

// NOT FULLY DEFINED SERVICES
#include <cosv/tpl/tpltools.hxx>
#include "nav_main.hxx"
#include "opageenv.hxx"

using namespace csi::xml;
using namespace csi::html;

namespace
{

//************************      SubRowItem      ***************************//

class SubRowItem
{
  public:
                        SubRowItem(
                            const char *        i_sText,
                            const char *        i_sLink,
                            bool                i_bActive,
                            bool                i_bFirstOfRow = false );
                        ~SubRowItem();

    void                Write2(
                            Element &           o_rOut ) const;
  private:
    String              sText;
    String              sLink;
    bool                bIsActive;
    bool                bFirstOfRow;
};

SubRowItem::SubRowItem( const char *        i_sText,
                        const char *        i_sLink,
                        bool                i_bActive,
                        bool                i_bFirstOfRow )
    :   sText(i_sText),
        sLink(i_sLink),
        bIsActive(i_bActive),
        bFirstOfRow(i_bFirstOfRow)
{
    csv_assert( NOT csv::no_str(i_sLink) );
}

SubRowItem::~SubRowItem()
{
}

void
SubRowItem::Write2( Element & o_rOut ) const
{
    o_rOut << new Sbr;
    if ( NOT bFirstOfRow )
        o_rOut << new XmlCode( "| " );
    else
        o_rOut << new XmlCode( " " );

    if ( bIsActive )
    {
        o_rOut
            >> *new Link( sLink.c_str() )
                >> *new AnElement( "font" )
                    << new AnAttribute("size","-2")
                    >> *new Bold
                        << sText.c_str();
    }
    else
    {
        o_rOut
            >> *new AnElement( "font" )
                << new AnAttribute("size","-2")
                << sText.c_str();
    }
}

//************************      SubRow      ***************************//

class SubRow
{
  public:
                        SubRow(
                            const char *        i_sTitle );
                        ~SubRow();

    void                AddItem(
                            const char *        i_sText,
                            const char *        i_sLink,
                            bool                i_bActive );
    void                Write2(
                            Table &             o_rOut ) const;
  private:
    typedef std::vector< DYN SubRowItem * >   List_Items;

    List_Items          aItemList;
    String              sTitle;
};

SubRow::SubRow( const char * i_sTitle )
//  :   // aItemList,
        // sTitle
{
    StreamStr sUp(i_sTitle,0);
    sUp.to_upper();
    sTitle = sUp.c_str();
}

SubRow::~SubRow()
{
}

inline void
SubRow::AddItem( const char *        i_sText,
                 const char *        i_sLink,
                 bool                i_bActive )
{
    aItemList.push_back( new SubRowItem(i_sText, i_sLink, i_bActive, aItemList.empty()) );
}

void
SubRow::Write2( Table & o_rOut ) const
{
    TableRow * pRow = new TableRow;
    o_rOut << pRow;

    if (sTitle.length() > 0)
    {
        Element & rCell1 = pRow->AddCell();
        rCell1
            << new WidthAttr("20%")
            >> *new AnElement( "font" )
                    << new AnAttribute("size","-2")
                       << sTitle
                       << ":";
    }

    Element & rCell2 = pRow->AddCell();
    for ( List_Items::const_iterator it = aItemList.begin();
          it != aItemList.end();
          ++it )
    {
         (*it)->Write2( rCell2 );
    }
}

}   // anonymous namespace

//*************************      CheshireCat     ***********************//

typedef std::vector< DYN SubRow * >   List_SubRows;

struct NavigationBar::CheshireCat
{
    MainRow             aMainRow;
    List_SubRows        aSubRows;
    const OuputPage_Environment *
                        pEnv;

                        CheshireCat(
                            const OuputPage_Environment &
                                                i_rEnv );
                        ~CheshireCat();
};

NavigationBar::
CheshireCat::CheshireCat( const OuputPage_Environment & i_rEnv )
    :   aMainRow( i_rEnv ),
        pEnv( & i_rEnv )
{
}

NavigationBar::
CheshireCat::~CheshireCat()
{
    csv::erase_container_of_heap_ptrs( aSubRows );
}

//************************       NavigationBar       *******************//

NavigationBar::NavigationBar( const OuputPage_Environment & i_rEnv,
                              E_GlobalLocation              i_eLocation )
    :   pi( new CheshireCat(i_rEnv) )
{
    switch (i_eLocation)
    {
         case LOC_Overview:  pi->aMainRow.SetupItems_Overview();  break;
         case LOC_AllDefs:   pi->aMainRow.SetupItems_AllDefs();   break;
        case LOC_Index:     pi->aMainRow.SetupItems_Index();     break;
        case LOC_Help:      pi->aMainRow.SetupItems_Help();      break;
        default:
                            csv_assert(false);
    }
}

NavigationBar::NavigationBar( const OuputPage_Environment & i_rEnv,
                              const ary::cpp::CodeEntity &  i_rCe  )
    :   pi( new CheshireCat(i_rEnv) )
{
    pi->aMainRow.SetupItems_Ce( i_rCe );
}

NavigationBar::NavigationBar( const OuputPage_Environment & i_rEnv,
                              E_CeGatheringType             i_eCeGatheringType )
    :   pi( new CheshireCat(i_rEnv) )
{
    switch (i_eCeGatheringType)
    {
         case CEGT_operations:   pi->aMainRow.SetupItems_FunctionGroup();  break;
        case CEGT_data:         pi->aMainRow.SetupItems_DataGroup();      break;
        default:
                                csv_assert(false);
    }
}

NavigationBar::~NavigationBar()
{
    csv::erase_container_of_heap_ptrs( pi->aSubRows );
}

void
NavigationBar::MakeSubRow( const char * i_sTitle )
{
    pi->aSubRows.push_back( new SubRow(i_sTitle) );
}

void
NavigationBar::AddItem( const char *        i_sName,
                        const char *        i_sLink,
                        bool                i_bValid )
{
    csv_assert( pi->aSubRows.size() > 0 );
    StreamStr sName(i_sName, 0);
    sName.to_upper();

    StreamLock aSum(100);
    pi->aSubRows.back()->AddItem( sName.c_str(),
                                  aSum() << "#" << i_sLink << c_str,
                                  i_bValid );
}

void
NavigationBar::Write( Element &  o_rOut,
                      bool       i_bWithSubRows ) const
{
    pi->aMainRow.Write2( o_rOut );

    const_cast< NavigationBar* >(this)->pSubRowsTable = new Table;
    o_rOut << pSubRowsTable;
    *pSubRowsTable
        << new AnAttribute( "class", "navisub" )
        << new AnAttribute( "cellpadding", "0" )
        << new AnAttribute( "cellspacing", "3" );

    if (i_bWithSubRows)
    {
        Write_SubRows();
    }
}

void
NavigationBar::Write_SubRows() const
{
    for ( List_SubRows::const_iterator it = pi->aSubRows.begin();
          it != pi->aSubRows.end();
          ++it )
    {
         (*it)->Write2( *pSubRowsTable );
    }
}
<|endoftext|>


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

 Program:   Medical Imaging & Interaction Toolkit
 Language:  C++
 Date:      $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $
 Version:   $Revision: 21975 $

 Copyright (c) German Cancer Research Center, Division of Medical and
 Biological Informatics. All rights reserved.
 See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

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

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

// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>

// Qmitk
#include "QmitkFiberBundleDeveloperView.h"
#include <QmitkStdMultiWidget.h>

// Qt

// VTK
#include <vtkSmartPointer.h>
#include <vtkPointSource.h>

const std::string QmitkFiberBundleDeveloperView::VIEW_ID = "org.mitk.views.fiberbundledeveloper";
const std::string id_DataManager = "org.mitk.views.datamanager";
using namespace berry;

QmitkFiberBundleDeveloperView::QmitkFiberBundleDeveloperView()
: QmitkFunctionality()
, m_Controls( 0 )
, m_MultiWidget( NULL )
{

}

// Destructor
QmitkFiberBundleDeveloperView::~QmitkFiberBundleDeveloperView()
{

}

void QmitkFiberBundleDeveloperView::CreateQtPartControl( QWidget *parent )
{
  // build up qt view, unless already done in QtDesigner, etc.
  if ( !m_Controls )
  {
    // create GUI widgets from the Qt Designer's .ui file
    m_Controls = new Ui::QmitkFiberBundleDeveloperViewControls;
    m_Controls->setupUi( parent );

    connect( m_Controls->buttonGenerateFibers, SIGNAL(clicked()), this, SLOT(DoGenerateFibers()) );

  }

  //  Checkpoint for fiber ORIENTATION
  if ( m_DirectionRadios.empty() )
  {
    m_DirectionRadios.insert(0, m_Controls->radioButton_directionRandom);
    m_DirectionRadios.insert(1, m_Controls->radioButton_directionX);
    m_DirectionRadios.insert(2, m_Controls->radioButton_directionY);
    m_DirectionRadios.insert(3, m_Controls->radioButton_directionZ);
  }

}

void QmitkFiberBundleDeveloperView::DoGenerateFibers()
{

  // GET SELECTED FIBER DIRECTION
  QString fibDirection;
  QVector<QRadioButton*>::const_iterator i;
  for (i = m_DirectionRadios.begin(); i != m_DirectionRadios.end(); ++i)
  {

    QRadioButton* rdbtn = *i;
    if (rdbtn->isChecked())
      fibDirection = rdbtn->objectName();

  }

}

void QmitkFiberBundleDeveloperView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget)
{
  m_MultiWidget = &stdMultiWidget;
}

void QmitkFiberBundleDeveloperView::StdMultiWidgetNotAvailable()
{
  m_MultiWidget = NULL;
}

/* OnSelectionChanged is registered to SelectionService, therefore no need to
 implement SelectionService Listener explicitly */

void QmitkFiberBundleDeveloperView::OnSelectionChanged( std::vector<mitk::DataNode*> nodes )
{

}

void QmitkFiberBundleDeveloperView::Activated()
{

  MITK_INFO << "FB OPerations ACTIVATED()";

}

<commit_msg>added methods returning vtkSmartPointer PolyData of fiberstructure<commit_after>/*=========================================================================

 Program:   Medical Imaging & Interaction Toolkit
 Language:  C++
 Date:      $Date: 2010-03-31 16:40:27 +0200 (Mi, 31 Mrz 2010) $
 Version:   $Revision: 21975 $

 Copyright (c) German Cancer Research Center, Division of Medical and
 Biological Informatics. All rights reserved.
 See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

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

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

// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>

// Qmitk
#include "QmitkFiberBundleDeveloperView.h"
#include <QmitkStdMultiWidget.h>

// Qt

// VTK
#include <vtkPointSource.h>

const std::string QmitkFiberBundleDeveloperView::VIEW_ID = "org.mitk.views.fiberbundledeveloper";
const std::string id_DataManager = "org.mitk.views.datamanager";
using namespace berry;

QmitkFiberBundleDeveloperView::QmitkFiberBundleDeveloperView()
: QmitkFunctionality()
, m_Controls( 0 )
, m_MultiWidget( NULL )
{

}

// Destructor
QmitkFiberBundleDeveloperView::~QmitkFiberBundleDeveloperView()
{

}

void QmitkFiberBundleDeveloperView::CreateQtPartControl( QWidget *parent )
{
  // build up qt view, unless already done in QtDesigner, etc.
  if ( !m_Controls )
  {
    // create GUI widgets from the Qt Designer's .ui file
    m_Controls = new Ui::QmitkFiberBundleDeveloperViewControls;
    m_Controls->setupUi( parent );

    connect( m_Controls->buttonGenerateFibers, SIGNAL(clicked()), this, SLOT(DoGenerateFibers()) );

  }

  //  Checkpoint for fiber ORIENTATION
  if ( m_DirectionRadios.empty() )
  {
    m_DirectionRadios.insert(0, m_Controls->radioButton_directionRandom);
    m_DirectionRadios.insert(1, m_Controls->radioButton_directionX);
    m_DirectionRadios.insert(2, m_Controls->radioButton_directionY);
    m_DirectionRadios.insert(3, m_Controls->radioButton_directionZ);
  }

}

void QmitkFiberBundleDeveloperView::DoGenerateFibers()
{

  // GET SELECTED FIBER DIRECTION
  QString fibDirection;
  QVector<QRadioButton*>::const_iterator i;
  for (i = m_DirectionRadios.begin(); i != m_DirectionRadios.end(); ++i)
  {

    QRadioButton* rdbtn = *i;
    if (rdbtn->isChecked())
      fibDirection = rdbtn->objectName();

  }

}

vtkSmartPointer<vtkPolyData> QmitkFiberBundleDeveloperView::GenerateVtkFibersRandom()
{
  vtkSmartPointer<vtkPolyData> PDRandom = vtkSmartPointer<vtkPolyData>::New();
  //todo

  return PDRandom;
}

vtkSmartPointer<vtkPolyData> QmitkFiberBundleDeveloperView::GenerateVtkFibersDirectionX()
{
  vtkSmartPointer<vtkPolyData> PDX = vtkSmartPointer<vtkPolyData>::New();
  //todo

  return PDX;
}

vtkSmartPointer<vtkPolyData> QmitkFiberBundleDeveloperView::GenerateVtkFibersDirectionY()
{
  vtkSmartPointer<vtkPolyData> PDY = vtkSmartPointer<vtkPolyData>::New();
  //todo

  return PDY;
}

vtkSmartPointer<vtkPolyData> QmitkFiberBundleDeveloperView::GenerateVtkFibersDirectionZ()
{
  vtkSmartPointer<vtkPolyData> PDZ = vtkSmartPointer<vtkPolyData>::New();
  //todo

  return PDZ;
}

void QmitkFiberBundleDeveloperView::StdMultiWidgetAvailable (QmitkStdMultiWidget &stdMultiWidget)
{
  m_MultiWidget = &stdMultiWidget;
}

void QmitkFiberBundleDeveloperView::StdMultiWidgetNotAvailable()
{
  m_MultiWidget = NULL;
}

/* OnSelectionChanged is registered to SelectionService, therefore no need to
 implement SelectionService Listener explicitly */

void QmitkFiberBundleDeveloperView::OnSelectionChanged( std::vector<mitk::DataNode*> nodes )
{

}

void QmitkFiberBundleDeveloperView::Activated()
{

  MITK_INFO << "FB OPerations ACTIVATED()";

}

<|endoftext|>


<commit_before>#ifndef __INCLUDED_BITFIELD_HPP__
#define __INCLUDED_BITFIELD_HPP__

#include <iostream>
#include <array>

namespace bitfield {
    class bit_type {
        uint8_t v;

    public:
        constexpr bit_type(uint8_t v) : v(v) {}

        constexpr bit_type floor() const {
            return bit_type(this->v >> 3 << 3);
        }

        constexpr bit_type ceil() const {
            return bit_type((this->v + 7) >> 3 << 3);
        }

        constexpr uint32_t bit() const {
            return this->v;
        }

        constexpr uint32_t byte() const {
            return this->v >> 3;
        }

        constexpr uint32_t max_value() const {
            return this->v >= 32 ? 0xffffffff : (0x01 << this->v) - 0x01;
        }

        constexpr bit_type diff(bit_type target) const {
            return bit_type(this->v < target.v ? target.v - this->v
                                               : this->v - target.v);
        };

        template<typename T>
        constexpr uint8_t * addr(const T * addr) const {
            return (uint8_t *)addr + this->byte();
        }
    };

    template<uint32_t Size, uint32_t Offset = 0>
    class bitfield {
    public:
        static constexpr uint32_t SIZE = Size;
        static constexpr uint32_t OFFSET = Offset;
        static constexpr uint32_t NEXT_OFFSET = SIZE + OFFSET;

        static constexpr uint32_t BYTE = bit_type(SIZE).ceil().byte();
        static constexpr uint32_t PADDING = bit_type(NEXT_OFFSET).ceil().diff(NEXT_OFFSET).bit();
        static constexpr uint32_t MASK = bit_type(SIZE).max_value() << PADDING;

        template<uint32_t NextSize>
        using next_bitfield = bitfield<NextSize, NEXT_OFFSET>;
        using container_type = std::array<uint8_t, bit_type(NEXT_OFFSET).ceil().byte()>;

        // for Little-Endian
        uint32_t get() const {
            uint8_t * addr = bit_type(OFFSET).addr(this);
            uint32_t value = 0x00;

            for (uint32_t i=0; i < BYTE; ++i) {
                value |= addr[i] << ((BYTE-i-1)<<3);
            }

            value &= MASK;
            value >>= PADDING;
            return value;
        }

        // for Little-Endian
        void set(uint32_t value) {
            static constexpr uint32_t clear_mask = ~MASK;

            value <<= PADDING;
            value &= MASK;

            uint8_t * addr = bit_type(OFFSET).addr(this);
            uint8_t * value_addr = (uint8_t *)&value;
            uint8_t * clear_mask_addr = (uint8_t *)&clear_mask;

            for (uint32_t i=0; i < BYTE; ++i) {
                uint32_t j = BYTE-i-1;
                addr[i] &= clear_mask_addr[j];
                addr[i] |= value_addr[j];
            }
        }

        operator uint32_t() const {
            return this->get();
        }

        bitfield & operator =(uint32_t value) {
            this->set(value);
            return *this;
        }

        friend std::ostream & operator <<(std::ostream & out, const bitfield & v) {
            return out << v.get();
        }
    };
}

#endif // __INCLUDED_BITFIELD_HPP__
<commit_msg>Fix bitfield#get().<commit_after>#ifndef __INCLUDED_BITFIELD_HPP__
#define __INCLUDED_BITFIELD_HPP__

#include <iostream>
#include <array>

namespace bitfield {
    class bit_type {
        uint8_t v;

    public:
        constexpr bit_type(uint8_t v) : v(v) {}

        constexpr bit_type floor() const {
            return bit_type(this->v >> 3 << 3);
        }

        constexpr bit_type ceil() const {
            return bit_type((this->v + 7) >> 3 << 3);
        }

        constexpr uint32_t bit() const {
            return this->v;
        }

        constexpr uint32_t byte() const {
            return this->v >> 3;
        }

        constexpr uint32_t max_value() const {
            return this->v >= 32 ? 0xffffffff : (0x01 << this->v) - 0x01;
        }

        constexpr bit_type diff(bit_type target) const {
            return bit_type(this->v < target.v ? target.v - this->v
                                               : this->v - target.v);
        };

        template<typename T>
        constexpr uint8_t * addr(const T * addr) const {
            return (uint8_t *)addr + this->byte();
        }
    };

    template<uint32_t Size, uint32_t Offset = 0>
    class bitfield {
    public:
        static constexpr uint32_t SIZE = Size;
        static constexpr uint32_t OFFSET = Offset;
        static constexpr uint32_t NEXT_OFFSET = SIZE + OFFSET;

        static constexpr uint32_t BYTE = bit_type(SIZE).ceil().byte();
        static constexpr uint32_t PADDING = bit_type(NEXT_OFFSET).ceil().diff(NEXT_OFFSET).bit();
        static constexpr uint32_t MASK = bit_type(SIZE).max_value() << PADDING;

        template<uint32_t NextSize>
        using next_bitfield = bitfield<NextSize, NEXT_OFFSET>;
        using container_type = std::array<uint8_t, bit_type(NEXT_OFFSET).ceil().byte()>;

        // for Little-Endian
        uint32_t get() const {
            uint32_t value = 0x00;
            uint8_t * addr = bit_type(OFFSET).addr(this);
            uint8_t * value_addr = (uint8_t *)&value;

            for (uint32_t i=0; i < BYTE; ++i) {
                value_addr[BYTE-i-1] = addr[i];
            }

            value &= MASK;
            value >>= PADDING;
            return value;
        }

        // for Little-Endian
        void set(uint32_t value) {
            static constexpr uint32_t clear_mask = ~MASK;

            value <<= PADDING;
            value &= MASK;

            uint8_t * addr = bit_type(OFFSET).addr(this);
            uint8_t * value_addr = (uint8_t *)&value;
            uint8_t * clear_mask_addr = (uint8_t *)&clear_mask;

            for (uint32_t i=0; i < BYTE; ++i) {
                uint32_t j = BYTE-i-1;
                addr[i] &= clear_mask_addr[j];
                addr[i] |= value_addr[j];
            }
        }

        operator uint32_t() const {
            return this->get();
        }

        bitfield & operator =(uint32_t value) {
            this->set(value);
            return *this;
        }

        friend std::ostream & operator <<(std::ostream & out, const bitfield & v) {
            return out << v.get();
        }
    };
}

#endif // __INCLUDED_BITFIELD_HPP__
<|endoftext|>


<commit_before>/*****************************************************************************
 * This file is part of the Gluon Development Platform                       *
 * Copyright (c) 2011 Laszlo Papp <djszapi@archlinux.us>                     *
 *                                                                           *
 * This program is free software; you can redistribute it and/or modify      *
 * it under the terms of the GNU General Public License as published by      *
 * the Free Software Foundation; either version 2 of the License, or         *
 * (at your option) any later version.                                       *
 *                                                                           *
 * This program 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 General Public License for more details.                              *
 *                                                                           *
 * You should have received a copy of the GNU General Public License along   *
 * with this program; if not, write to the Free Software Foundation, Inc.,   *
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.               *
 *****************************************************************************/

#include "mainwindow.h"

#include <core/debughelper.h>
#include <engine/game.h>
#include <engine/gameproject.h>
#include <engine/scene.h>
#include <graphics/renderwidget.h>
#include <player/models/gamesmodel.h>

#include <KPushButton>
#include <KFileDialog>
#include <KUrl>
#include <KLocalizedString>

#include <QtGui/QStatusBar>
#include <QtGui/QListView>
#include <QtGui/QVBoxLayout>
#include <QLabel>
#include <QTimer>

using namespace GluonPlayer;

class MainWindow::MainWindowPrivate
{
    public:
        MainWindowPrivate() {}

        GluonEngine::GameProject* project;
        GluonGraphics::RenderWidget* widget;

        KRecentFilesAction* recentFiles;

        QAbstractItemModel* model;

        QString title;
        QString fileName;

        int msecElapsed;
        int frameCount;
};

MainWindow::MainWindow(const QString& filename )
    : KMainWindow()
    , d( new MainWindowPrivate )
{
    d->msecElapsed = 0;
    d->frameCount = 0;

    if( !filename.isEmpty() )
    {
        d->fileName = filename;
        QTimer::singleShot( 0, this, SLOT( openProject() ) );
    }
    else
    {
        QWidget* base = new QWidget( this );
        QVBoxLayout* layout = new QVBoxLayout();
        base->setLayout( layout );
        setCentralWidget( base );

        QLabel* header = new QLabel( i18n( "Please select a Project" ), base );
        header->setAlignment( Qt::AlignCenter );
        QFont font;
        font.setBold( true );
        header->setFont( font );
        layout->addWidget( header );

        QListView* view = new QListView( base );
        layout->addWidget( view );
        d->model = new GamesModel( view );
        view->setModel( d->model );
        connect( view, SIGNAL( activated( QModelIndex ) ), SLOT( activated( QModelIndex ) ) );

        KPushButton* button = new KPushButton( i18n( "Open other project..." ), base );
        layout->addWidget( button );
        connect( button, SIGNAL( clicked( bool ) ), SLOT( openClicked( bool ) ) );
    }
    resize( 500, 500 );
}

MainWindow::~MainWindow ( )
{
}

void MainWindow::activated( QModelIndex index )
{
    if( index.isValid() )
    {
        openProject( d->model->data( index ).toString() );
    }
}

void MainWindow::openClicked( bool toggled )
{
    Q_UNUSED( toggled )

    QString fileName = KFileDialog::getOpenFileName( KUrl() , i18n( "Select a Project" ), this, QString( "*.gluon|Gluon Project Files" ) );
    if( !fileName.isEmpty() )
        openProject( fileName );
}

void MainWindow::openProject( const QString& fileName )
{
    QString file = fileName;
    if( file.isEmpty() )
        file = d->fileName;

    d->widget = new GluonGraphics::RenderWidget( this );
    setCentralWidget( d->widget );
    connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), d->widget, SLOT( updateGL() ) );
    connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), SLOT( countFrames( int ) ) );
    connect( GluonEngine::Game::instance(), SIGNAL( updated( int ) ), SLOT( updateTitle( int ) ) );

    QTimer::singleShot( 100, this, SLOT( startGame() ) );

    d->fileName = file;
}

void MainWindow::startGame()
{
    GluonCore::GluonObjectFactory::instance()->loadPlugins();

    d->project = new GluonEngine::GameProject();
    d->project->loadFromFile( QUrl( d->fileName ) );

    setWindowFilePath( d->fileName );
    d->title = windowTitle();

    GluonEngine::Game::instance()->setGameProject( d->project );
    GluonEngine::Game::instance()->setCurrentScene( d->project->entryPoint() );

    GluonEngine::Game::instance()->runGame();
}

void MainWindow::closeEvent( QCloseEvent* event )
{
    GluonEngine::Game::instance()->stopGame();
    QWidget::closeEvent( event );
}

void MainWindow::updateTitle( int msec )
{
    d->msecElapsed += msec;

    static int fps = 0;
    if( d->msecElapsed > 1000 )
    {
        fps = d->frameCount;
        d->frameCount = 0;
        d->msecElapsed = 0;
    }

    setWindowTitle( d->title + QString( " (%1 FPS)" ).arg( fps ) );
}

void MainWindow::countFrames( int time )
{
    Q_UNUSED( time )
    d->frameCount++;
}
<commit_msg>KDE Simple Player: add the setFocus() method before running the game.<commit_after>/*****************************************************************************
 * This file is part of the Gluon Development Platform                       *
 * Copyright (c) 2011 Laszlo Papp <djszapi@archlinux.us>                     *
 *                                                                           *
 * This program is free software; you can redistribute it and/or modify      *
 * it under the terms of the GNU General Public License as published by      *
 * the Free Software Foundation; either version 2 of the License, or         *
 * (at your option) any later version.                                       *
 *                                                                           *
 * This program 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 General Public License for more details.                              *
 *                                                                           *
 * You should have received a copy of the GNU General Public License along   *
 * with this program; if not, write to the Free Software Foundation, Inc.,   *
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.               *
 *****************************************************************************/

#include "mainwindow.h"

#include <core/debughelper.h>
#include <engine/game.h>
#include <engine/gameproject.h>
#include <engine/scene.h>
#include <graphics/renderwidget.h>
#include <player/models/gamesmodel.h>

#include <KPushButton>
#include <KFileDialog>
#include <KUrl>
#include <KLocalizedString>

#include <QtGui/QStatusBar>
#include <QtGui/QListView>
#include <QtGui/QVBoxLayout>
#include <QLabel>
#include <QTimer>

using namespace GluonPlayer;

class MainWindow::MainWindowPrivate
{
    public:
        MainWindowPrivate() {}

        GluonEngine::GameProject* project;
        GluonGraphics::RenderWidget* widget;

        KRecentFilesAction* recentFiles;

        QAbstractItemModel* model;

        QString title;
        QString fileName;

        int msecElapsed;
        int frameCount;
};

MainWindow::MainWindow(const QString& filename )
    : KMainWindow()
    , d( new MainWindowPrivate )
{
    d->msecElapsed = 0;
    d->frameCount = 0;

    if( !filename.isEmpty() )
    {
        d->fileName = filename;
        QTimer::singleShot( 0, this, SLOT( openProject() ) );
    }
    else
    {
        QWidget* base = new QWidget( this );
        QVBoxLayout* layout = new QVBoxLayout();
        base->setLayout( layout );
        setCentralWidget( base );

        QLabel* header = new QLabel( i18n( "Please select a Project" ), base );
        header->setAlignment( Qt::AlignCenter );
        QFont font;
        font.setBold( true );
        header->setFont( font );
        layout->addWidget( header );

        QListView* view = new QListView( base );
        layout->addWidget( view );
        d->model = new GamesModel( view );
        view->setModel( d->model );
        connect( view, SIGNAL( activated( QModelIndex ) ), SLOT( activated( QModelIndex ) ) );

        KPushButton* button = new KPushButton( i18n( "Open other project..." ), base );
        layout->addWidget( button );
        connect( button, SIGNAL( clicked( bool ) ), SLOT( openClicked( bool ) ) );
    }
    resize( 500, 500 );
}

MainWindow::~MainWindow ( )
{
}

void MainWindow::activated( QModelIndex index )
{
    if( index.isValid() )
    {
        openProject( d->model->data( index ).toString() );
    }
}

void MainWindow::openClicked( bool toggled )
{
    Q_UNUSED( toggled )

    QString fileName = KFileDialog::getOpenFileName( KUrl() , i18n( "Select a Project" ), this, QString( "*.gluon|Gluon Project Files" ) );
    if( !fileName.isEmpty() )
        openProject( fileName );
}

void MainWindow::openProject( const QString& fileName )
{
    QString file = fileName;
    if( file.isEmpty() )
        file = d->fileName;

    d->widget = new GluonGraphics::RenderWidget( this );
    setCentralWidget( d->widget );
    connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), d->widget, SLOT( updateGL() ) );
    connect( GluonEngine::Game::instance(), SIGNAL( painted( int ) ), SLOT( countFrames( int ) ) );
    connect( GluonEngine::Game::instance(), SIGNAL( updated( int ) ), SLOT( updateTitle( int ) ) );

    QTimer::singleShot( 100, this, SLOT( startGame() ) );

    d->fileName = file;
}

void MainWindow::startGame()
{
    GluonCore::GluonObjectFactory::instance()->loadPlugins();

    d->project = new GluonEngine::GameProject();
    d->project->loadFromFile( QUrl( d->fileName ) );

    setWindowFilePath( d->fileName );
    d->title = windowTitle();

    GluonEngine::Game::instance()->setGameProject( d->project );
    GluonEngine::Game::instance()->setCurrentScene( d->project->entryPoint() );

    d->widget->setFocus();
    GluonEngine::Game::instance()->runGame();
}

void MainWindow::closeEvent( QCloseEvent* event )
{
    GluonEngine::Game::instance()->stopGame();
    QWidget::closeEvent( event );
}

void MainWindow::updateTitle( int msec )
{
    d->msecElapsed += msec;

    static int fps = 0;
    if( d->msecElapsed > 1000 )
    {
        fps = d->frameCount;
        d->frameCount = 0;
        d->msecElapsed = 0;
    }

    setWindowTitle( d->title + QString( " (%1 FPS)" ).arg( fps ) );
}

void MainWindow::countFrames( int time )
{
    Q_UNUSED( time )
    d->frameCount++;
}
<|endoftext|>