<commit_before>#include <iostream>
#include <mutex>
#include <condition_variable>
#include "protocol.h"
#include "verbose.h"
#include "RF33_adapter.hpp"

// RFSwitch library only accepts C function pointer.
static std::mutex m;
static std::condition_variable cv;

void transmissionHandler() {
  // A signal is being received, wake up program
  cv.notify_all();
}

int RF33Adapter::init(int pin) {
  // Init wiring PI
  if(wiringPiSetupSys() == -1) {
    std::cerr << "wiringPiSetup failed, exiting..." << std::endl;
    return 1;
  }
  // Init RF Switch
  // if (pulseLength != 0) _rfSwitch.setPulseLength(pulseLength);
  _rfSwitch.enableReceive(pin);
  _rfSwitch.registerCustomInterruptHandler(transmissionHandler);
  return 0;
}

int RF33Adapter::receiveMessage(std::function<void(const packet_s &)> callback) {
  bool receiving_first = true;
  uint64_t previous_value = 0;
  uint64_t value = 0;
  uint64_t count = 0;
  packet_t raw_packet = 0;
  VERBOSE(std::cout << "listening..." << std::endl);
  while(1) {
    std::unique_lock<std::mutex> lk(m);
    cv.wait(lk);

    if (_rfSwitch.available()) {
      value = _rfSwitch.getReceivedValue();
      // std::cout << value << std::endl;
      _rfSwitch.resetAvailable();
      count++;
      VERBOSE(std::cout << "value received (" << count << "): " << value << std::endl);
      if (value == previous_value)
        continue; // If we receive the same value, this is just a repeat
      previous_value = value;
      raw_packet |= value;
      // If we are receiving the first part of the packet, shift the value by
      // 32 to let room for the second half
      if (receiving_first) {
        raw_packet <<= 32;
        receiving_first = false;
      } else {
        // We received the second part, process it
        packet_s packet;
        int ret = read_packet(raw_packet, &packet);
        if (ret == WRONG_MAGIC_ERROR) {
          std::cout << "DEBUG: Wrong magic number, dismiss message" << std::endl;
          continue;
        } else if (ret == PARITY_ERROR) {
          std::cerr << "ERROR: Parity error in message, tread lightly" << std::endl;
        }
        callback(packet);
        receiving_first = true;
        raw_packet = 0;
        value = 0;
      }
    }
  }

}

<commit_msg>Use new one word protocol.<commit_after>#include <iostream>
#include <mutex>
#include <condition_variable>
#include "protocol.h"
#include "verbose.h"
#include "RF33_adapter.hpp"

// RFSwitch library only accepts C function pointer.
static std::mutex m;
static std::condition_variable cv;

void transmissionHandler() {
  // A signal is being received, wake up program
  cv.notify_all();
}

int RF33Adapter::init(int pin) {
  // Init wiring PI
  if(wiringPiSetupSys() == -1) {
    std::cerr << "wiringPiSetup failed, exiting..." << std::endl;
    return 1;
  }
  // Init RF Switch
  // if (pulseLength != 0) _rfSwitch.setPulseLength(pulseLength);
  _rfSwitch.enableReceive(pin);
  _rfSwitch.registerCustomInterruptHandler(transmissionHandler);
  return 0;
}

int RF33Adapter::receiveMessage(std::function<void(const packet_s &)> callback) {
  bool receiving_first = true;
  packet_t value = 0;
  packet_t previous_value = 0;
  uint64_t count = 0;
  VERBOSE(std::cout << "listening..." << std::endl);
  while(1) {
    std::unique_lock<std::mutex> lk(m);
    cv.wait(lk);

    if (_rfSwitch.available()) {
      value = _rfSwitch.getReceivedValue();
      // std::cout << value << std::endl;
      _rfSwitch.resetAvailable();
      count++;
      VERBOSE(std::cout << "value received (" << count << "): " << value << std::endl);
      if (value == previous_value)
        continue; // If we receive the same value, this is just a repeat
      previous_value = value;
      // Now unpack it
      packet_s packet;
      int ret = read_packet(value, &packet);
      if (ret == WRONG_MAGIC_ERROR) {
        std::cout << "DEBUG: Wrong magic number, dismiss message" << std::endl;
        continue;
      } else if (ret == PARITY_ERROR) {
        std::cerr << "ERROR: Parity error in message, tread lightly" << std::endl;
      }
      callback(packet);
      value = 0;
    }
  }

}

<|endoftext|>


<commit_before>#include <sstream>

#include "Flow.hpp"

Flow::Flow(ContentElement* content, PonUser destination, SimTime eta,
        uint chunkId, FlowType flowType, PonUser source) {
  this->source = source;
  this->destination = destination;
  this->content = content;
  this->eta = eta;
  this->bandwidth = 0;
  this->sizeDownloaded = 0;
  this->start = INF_TIME;
  this->lastUpdate = start;
  this->P2PFlow = true;
  this->flowType = flowType;
  this->chunkId = chunkId;
}

Flow::~Flow() {
  content = nullptr;
}

// debug method
std::string Flow::toString() const {
  std::stringstream ss;
  ss << "s" << this->getSource().first << "d" << this->getDestination().first <<
          ", c" << this->getContent()->getName() << ":" << this->getChunkId() <<
          ", t:" << this->getStart() <<  "-" << this->getEta() << "; dl "
          << this->getSizeDownloaded() << " @" << this->lastUpdate
          << ", bw:" << this->getBandwidth() << ", type: "
          << (int) this->getFlowType();
  return ss.str();
}

void Flow::updateSizeDownloaded(SimTime now) {
  if (now > this->lastUpdate)
    this->sizeDownloaded += ((now - this->lastUpdate) * this->bandwidth);
  if (this->sizeDownloaded > this->getChunkSize()) {
    /* This is inevitable due to approximations and having a discrete time scale
     */
    this->sizeDownloaded = this->getChunkSize();
  }
  this->setLastUpdate(now);
}<commit_msg>First batch of Doxygen documentation added.<commit_after>#include <sstream>

#include "Flow.hpp"

Flow::Flow(ContentElement* content, PonUser destination, SimTime eta,
        uint chunkId, FlowType flowType, PonUser source) {
  this->source = source;
  this->destination = destination;
  this->content = content;
  this->eta = eta;
  this->bandwidth = 0;
  this->sizeDownloaded = 0;
  this->start = INF_TIME;
  this->lastUpdate = start;
  this->P2PFlow = true;
  this->flowType = flowType;
  this->chunkId = chunkId;
}

Flow::~Flow() {
  content = nullptr;
}

/**
 * @deprecated Debug method, no longer used.
 * @return A string with a concatation of some of the interal fields of the class.
 */
std::string Flow::toString() const {
  std::stringstream ss;
  ss << "s" << this->getSource().first << "d" << this->getDestination().first <<
          ", c" << this->getContent()->getName() << ":" << this->getChunkId() <<
          ", t:" << this->getStart() <<  "-" << this->getEta() << "; dl "
          << this->getSizeDownloaded() << " @" << this->lastUpdate
          << ", bw:" << this->getBandwidth() << ", type: "
          << (int) this->getFlowType();
  return ss.str();
}

/**
 * Updates Flow::sizeDownloaded by taking the previous value and adding to it
 * the Capacity that has been downloaded with the current Flow::bandwidth
 * between Flow::lastUpdate and now.
 * @param now current SimTime.
 */
void Flow::updateSizeDownloaded(SimTime now) {
  if (now > this->lastUpdate)
    this->sizeDownloaded += ((now - this->lastUpdate) * this->bandwidth);
  if (this->sizeDownloaded > this->getChunkSize()) {
    /* This is inevitable due to approximations and having a discrete time scale
     */
    this->sizeDownloaded = this->getChunkSize();
  }
  this->setLastUpdate(now);
}<|endoftext|>


<commit_before>// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/base/division-by-constant.h"

#include <stdint.h>

#include "src/base/logging.h"
#include "src/base/macros.h"

namespace v8 {
namespace base {

template <class T>
bool MagicNumbersForDivision<T>::operator==(
    const MagicNumbersForDivision& rhs) const {
  return multiplier == rhs.multiplier && shift == rhs.shift && add == rhs.add;
}

template <class T>
MagicNumbersForDivision<T> SignedDivisionByConstant(T d) {
  STATIC_ASSERT(static_cast<T>(0) < static_cast<T>(-1));
  DCHECK(d != static_cast<T>(-1) && d != 0 && d != 1);
  const unsigned bits = static_cast<unsigned>(sizeof(T)) * 8;
  const T min = (static_cast<T>(1) << (bits - 1));
  const bool neg = (min & d) != 0;
  const T ad = neg ? (0 - d) : d;
  const T t = min + (d >> (bits - 1));
  const T anc = t - 1 - t % ad;  // Absolute value of nc
  unsigned p = bits - 1;         // Init. p.
  T q1 = min / anc;              // Init. q1 = 2**p/|nc|.
  T r1 = min - q1 * anc;         // Init. r1 = rem(2**p, |nc|).
  T q2 = min / ad;               // Init. q2 = 2**p/|d|.
  T r2 = min - q2 * ad;          // Init. r2 = rem(2**p, |d|).
  T delta;
  do {
    p = p + 1;
    q1 = 2 * q1;      // Update q1 = 2**p/|nc|.
    r1 = 2 * r1;      // Update r1 = rem(2**p, |nc|).
    if (r1 >= anc) {  // Must be an unsigned comparison here.
      q1 = q1 + 1;
      r1 = r1 - anc;
    }
    q2 = 2 * q2;     // Update q2 = 2**p/|d|.
    r2 = 2 * r2;     // Update r2 = rem(2**p, |d|).
    if (r2 >= ad) {  // Must be an unsigned comparison here.
      q2 = q2 + 1;
      r2 = r2 - ad;
    }
    delta = ad - r2;
  } while (q1 < delta || (q1 == delta && r1 == 0));
  T mul = q2 + 1;
  return {neg ? (0 - mul) : mul, p - bits, false};
}

template <class T>
MagicNumbersForDivision<T> UnsignedDivisionByConstant(T d,
                                                      unsigned leading_zeros) {
  STATIC_ASSERT(static_cast<T>(0) < static_cast<T>(-1));
  DCHECK(d != 0);
  const unsigned bits = static_cast<unsigned>(sizeof(T)) * 8;
  const T ones = ~static_cast<T>(0) >> leading_zeros;
  const T min = static_cast<T>(1) << (bits - 1);
  const T max = ~static_cast<T>(0) >> 1;
  const T nc = ones - (ones - d) % d;
  bool a = false;         // Init. "add" indicator.
  unsigned p = bits - 1;  // Init. p.
  T q1 = min / nc;        // Init. q1 = 2**p/nc
  T r1 = min - q1 * nc;   // Init. r1 = rem(2**p,nc)
  T q2 = max / d;         // Init. q2 = (2**p - 1)/d.
  T r2 = max - q2 * d;    // Init. r2 = rem(2**p - 1, d).
  T delta;
  do {
    p = p + 1;
    if (r1 >= nc - r1) {
      q1 = 2 * q1 + 1;
      r1 = 2 * r1 - nc;
    } else {
      q1 = 2 * q1;
      r1 = 2 * r1;
    }
    if (r2 + 1 >= d - r2) {
      if (q2 >= max) a = true;
      q2 = 2 * q2 + 1;
      r2 = 2 * r2 + 1 - d;
    } else {
      if (q2 >= min) a = true;
      q2 = 2 * q2;
      r2 = 2 * r2 + 1;
    }
    delta = d - 1 - r2;
  } while (p < bits * 2 && (q1 < delta || (q1 == delta && r1 == 0)));
  return {q2 + 1, p - bits, a};
}

// -----------------------------------------------------------------------------
// Instantiations.

template struct MagicNumbersForDivision<uint32_t>;
template struct MagicNumbersForDivision<uint64_t>;

template MagicNumbersForDivision<uint32_t> SignedDivisionByConstant(uint32_t d);
template MagicNumbersForDivision<uint64_t> SignedDivisionByConstant(uint64_t d);

template MagicNumbersForDivision<uint32_t> UnsignedDivisionByConstant(
    uint32_t d, unsigned leading_zeros);
template MagicNumbersForDivision<uint64_t> UnsignedDivisionByConstant(
    uint64_t d, unsigned leading_zeros);

}  // namespace base
}  // namespace v8
<commit_msg>Fixed compilation with older clang versions.<commit_after>// Copyright 2014 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/base/division-by-constant.h"

#include <stdint.h>

#include "src/base/logging.h"
#include "src/base/macros.h"

namespace v8 {
namespace base {

template <class T>
bool MagicNumbersForDivision<T>::operator==(
    const MagicNumbersForDivision& rhs) const {
  return multiplier == rhs.multiplier && shift == rhs.shift && add == rhs.add;
}

template <class T>
MagicNumbersForDivision<T> SignedDivisionByConstant(T d) {
  STATIC_ASSERT(static_cast<T>(0) < static_cast<T>(-1));
  DCHECK(d != static_cast<T>(-1) && d != 0 && d != 1);
  const unsigned bits = static_cast<unsigned>(sizeof(T)) * 8;
  const T min = (static_cast<T>(1) << (bits - 1));
  const bool neg = (min & d) != 0;
  const T ad = neg ? (0 - d) : d;
  const T t = min + (d >> (bits - 1));
  const T anc = t - 1 - t % ad;  // Absolute value of nc
  unsigned p = bits - 1;         // Init. p.
  T q1 = min / anc;              // Init. q1 = 2**p/|nc|.
  T r1 = min - q1 * anc;         // Init. r1 = rem(2**p, |nc|).
  T q2 = min / ad;               // Init. q2 = 2**p/|d|.
  T r2 = min - q2 * ad;          // Init. r2 = rem(2**p, |d|).
  T delta;
  do {
    p = p + 1;
    q1 = 2 * q1;      // Update q1 = 2**p/|nc|.
    r1 = 2 * r1;      // Update r1 = rem(2**p, |nc|).
    if (r1 >= anc) {  // Must be an unsigned comparison here.
      q1 = q1 + 1;
      r1 = r1 - anc;
    }
    q2 = 2 * q2;     // Update q2 = 2**p/|d|.
    r2 = 2 * r2;     // Update r2 = rem(2**p, |d|).
    if (r2 >= ad) {  // Must be an unsigned comparison here.
      q2 = q2 + 1;
      r2 = r2 - ad;
    }
    delta = ad - r2;
  } while (q1 < delta || (q1 == delta && r1 == 0));
  T mul = q2 + 1;
  return MagicNumbersForDivision<T>(neg ? (0 - mul) : mul, p - bits, false);
}

template <class T>
MagicNumbersForDivision<T> UnsignedDivisionByConstant(T d,
                                                      unsigned leading_zeros) {
  STATIC_ASSERT(static_cast<T>(0) < static_cast<T>(-1));
  DCHECK(d != 0);
  const unsigned bits = static_cast<unsigned>(sizeof(T)) * 8;
  const T ones = ~static_cast<T>(0) >> leading_zeros;
  const T min = static_cast<T>(1) << (bits - 1);
  const T max = ~static_cast<T>(0) >> 1;
  const T nc = ones - (ones - d) % d;
  bool a = false;         // Init. "add" indicator.
  unsigned p = bits - 1;  // Init. p.
  T q1 = min / nc;        // Init. q1 = 2**p/nc
  T r1 = min - q1 * nc;   // Init. r1 = rem(2**p,nc)
  T q2 = max / d;         // Init. q2 = (2**p - 1)/d.
  T r2 = max - q2 * d;    // Init. r2 = rem(2**p - 1, d).
  T delta;
  do {
    p = p + 1;
    if (r1 >= nc - r1) {
      q1 = 2 * q1 + 1;
      r1 = 2 * r1 - nc;
    } else {
      q1 = 2 * q1;
      r1 = 2 * r1;
    }
    if (r2 + 1 >= d - r2) {
      if (q2 >= max) a = true;
      q2 = 2 * q2 + 1;
      r2 = 2 * r2 + 1 - d;
    } else {
      if (q2 >= min) a = true;
      q2 = 2 * q2;
      r2 = 2 * r2 + 1;
    }
    delta = d - 1 - r2;
  } while (p < bits * 2 && (q1 < delta || (q1 == delta && r1 == 0)));
  return MagicNumbersForDivision<T>(q2 + 1, p - bits, a);
}

// -----------------------------------------------------------------------------
// Instantiations.

template struct MagicNumbersForDivision<uint32_t>;
template struct MagicNumbersForDivision<uint64_t>;

template MagicNumbersForDivision<uint32_t> SignedDivisionByConstant(uint32_t d);
template MagicNumbersForDivision<uint64_t> SignedDivisionByConstant(uint64_t d);

template MagicNumbersForDivision<uint32_t> UnsignedDivisionByConstant(
    uint32_t d, unsigned leading_zeros);
template MagicNumbersForDivision<uint64_t> UnsignedDivisionByConstant(
    uint64_t d, unsigned leading_zeros);

}  // namespace base
}  // namespace v8
<|endoftext|>


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

Program:   Robarts Visualization Toolkit

Copyright (c) John Stuart Haberl Baxter, Robarts Research Institute

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

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

#include "vtkBMPReader.h"
#include "vtkDataSetAttributes.h"
#include "vtkDirectedAcyclicGraphMaxFlowSegmentation.h"
#include "vtkFloatArray.h"
#include "vtkImageCast.h"
#include "vtkImageData.h"
#include "vtkImageExtractComponents.h"
#include "vtkMetaImageWriter.h"
#include "vtkMutableDirectedGraph.h"
#include "vtkRootedDirectedAcyclicGraph.h"
#include "vtkRootedDirectedAcyclicGraphBackwardIterator.h"
#include "vtkRootedDirectedAcyclicGraphForwardIterator.h"
#include "vtkRootedDirectedAcyclicGraphIterator.h"
#include "vtksys/CommandLineArguments.hxx"
#include "vtksys/SystemTools.hxx"
#include <iostream>
#include <vtkSmartPointer.h>
#include <vtkVersion.h>

int main(int argc, char** argv)
{
  // Check command line arguments.
  bool printHelp(false);
  std::string outputDirectory;

  vtksys::CommandLineArguments args;
  args.Initialize( argc, argv );

  args.AddArgument("--help", vtksys::CommandLineArguments::NO_ARGUMENT, &printHelp, "Print this help.");
  args.AddArgument( "--output-dir", vtksys::CommandLineArguments::EQUAL_ARGUMENT, &outputDirectory, "Name of the output directory." );

  if ( !args.Parse() )
  {
    std::cerr << "Problem parsing arguments." << std::endl;
    std::cout << "Help: " << args.GetHelp() << std::endl;
    exit(EXIT_FAILURE);
  }

  if ( printHelp )
  {
    std::cout << args.GetHelp() << std::endl;
    exit(EXIT_SUCCESS);
  }

  if( !vtksys::SystemTools::FileExists(outputDirectory.c_str(), false) && !vtksys::SystemTools::MakeDirectory(outputDirectory) )
  {
    std::cerr << "Output directory doesn't exist and can't be created." << std::endl;
  }

  vtkSmartPointer<vtkMutableDirectedGraph> mut = vtkSmartPointer<vtkMutableDirectedGraph>::New();
  vtkIdType source = mut->AddVertex();
  vtkIdType bkg = mut->AddVertex();
  vtkIdType c1 = mut->AddVertex();
  vtkIdType c2 = mut->AddVertex();
  vtkIdType l1 = mut->AddVertex();
  vtkIdType l2 = mut->AddVertex();
  vtkIdType l3 = mut->AddVertex();

  vtkSmartPointer<vtkFloatArray> Weights = vtkSmartPointer<vtkFloatArray>::New();
  Weights->SetName("Weights");
  Weights->InsertValue((mut->AddEdge(source,bkg)).Id,1.0f);
  Weights->InsertValue((mut->AddEdge(source,c1)).Id,1.0f);
  Weights->InsertValue((mut->AddEdge(source,c2)).Id,1.0f);
  Weights->InsertValue((mut->AddEdge(source,l1)).Id,0.5f);
  Weights->InsertValue((mut->AddEdge(source,l2)).Id,0.5f);
  Weights->InsertValue((mut->AddEdge(c1,l1)).Id,0.5f);
  Weights->InsertValue((mut->AddEdge(c2,l2)).Id,0.5f);
  Weights->InsertValue((mut->AddEdge(c1,l3)).Id,0.5f);
  Weights->InsertValue((mut->AddEdge(c2,l3)).Id,0.5f);

  vtkSmartPointer<vtkRootedDirectedAcyclicGraph> DAG = vtkSmartPointer<vtkRootedDirectedAcyclicGraph>::New();
  DAG->CheckedShallowCopy(mut);

  vtkSmartPointer<vtkBMPReader> cost0 = vtkSmartPointer<vtkBMPReader>::New();
  cost0->SetFileName( std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "/cost0.bmp").c_str() );
  vtkSmartPointer<vtkBMPReader> cost1 = vtkSmartPointer<vtkBMPReader>::New();
  cost1->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "/cost1.bmp").c_str());
  vtkSmartPointer<vtkBMPReader> cost2 = vtkSmartPointer<vtkBMPReader>::New();
  cost2->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "/cost2.bmp").c_str());
  vtkSmartPointer<vtkBMPReader> cost3 = vtkSmartPointer<vtkBMPReader>::New();
  cost3->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "/cost3.bmp").c_str());

  vtkSmartPointer<vtkImageExtractComponents> extract0 = vtkSmartPointer<vtkImageExtractComponents>::New();
  extract0->SetComponents(0);
  extract0->SetInputConnection(cost0->GetOutputPort());
  vtkSmartPointer<vtkImageCast> cast0 = vtkSmartPointer<vtkImageCast>::New();
  cast0->SetOutputScalarTypeToFloat();
  cast0->SetInputConnection(extract0->GetOutputPort());
  vtkSmartPointer<vtkImageExtractComponents> extract1 = vtkSmartPointer<vtkImageExtractComponents>::New();
  extract1->SetComponents(0);
  extract1->SetInputConnection(cost1->GetOutputPort());
  vtkSmartPointer<vtkImageCast> cast1 = vtkSmartPointer<vtkImageCast>::New();
  cast1->SetOutputScalarTypeToFloat();
  cast1->SetInputConnection(extract1->GetOutputPort());
  vtkSmartPointer<vtkImageExtractComponents> extract2 = vtkSmartPointer<vtkImageExtractComponents>::New();
  extract2->SetComponents(0);
  extract2->SetInputConnection(cost2->GetOutputPort());
  vtkSmartPointer<vtkImageCast> cast2 = vtkSmartPointer<vtkImageCast>::New();
  cast2->SetOutputScalarTypeToFloat();
  cast2->SetInputConnection(extract2->GetOutputPort());
  vtkSmartPointer<vtkImageExtractComponents> extract3 = vtkSmartPointer<vtkImageExtractComponents>::New();
  extract3->SetComponents(0);
  extract3->SetInputConnection(cost3->GetOutputPort());
  vtkSmartPointer<vtkImageCast> cast3 = vtkSmartPointer<vtkImageCast>::New();
  cast3->SetOutputScalarTypeToFloat();
  cast3->SetInputConnection(extract3->GetOutputPort());

  //cast0->Update();
  //cast1->Update();
  //cast2->Update();
  //cast3->Update();

  vtkSmartPointer<vtkDirectedAcyclicGraphMaxFlowSegmentation> dagmf =
    vtkSmartPointer<vtkDirectedAcyclicGraphMaxFlowSegmentation>::New();
  dagmf->SetStructure(DAG);
  dagmf->SetDataInputConnection(bkg,cast0->GetOutputPort());
  dagmf->SetDataInputConnection(l1,cast1->GetOutputPort());
  dagmf->SetDataInputConnection(l2,cast2->GetOutputPort());
  dagmf->SetDataInputConnection(l3,cast3->GetOutputPort());
  dagmf->AddSmoothnessScalar(bkg,0.01);
  dagmf->AddSmoothnessScalar(l1, 0.01);
  dagmf->AddSmoothnessScalar(l2, 0.01);
  dagmf->AddSmoothnessScalar(l3, 0.01);
  dagmf->AddSmoothnessScalar(c1, 50);
  dagmf->AddSmoothnessScalar(c2, 50);
  dagmf->SetCC(0.01);
  dagmf->SetStepSize(0.1);
  dagmf->SetNumberOfIterations(100);
  //dagmf->Update();

  vtkSmartPointer<vtkMetaImageWriter> writer = vtkSmartPointer<vtkMetaImageWriter>::New();
  writer->SetInputConnection(dagmf->GetOutputPort(bkg));
  writer->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "\\l0.mhd").c_str());
  writer->SetRAWFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "\\l0.raw").c_str());
  writer->Update();
  writer->Write();
  writer->SetInputConnection(dagmf->GetOutputPort(l1));
  writer->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "\\l1.mhd").c_str());
  writer->SetRAWFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "\\l1.raw").c_str());
  writer->Update();
  writer->Write();
  writer->SetInputConnection(dagmf->GetOutputPort(l2));
  writer->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "\\l2.mhd").c_str());
  writer->SetRAWFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "\\l2.raw").c_str());
  writer->Update();
  writer->Write();
  writer->SetInputConnection(dagmf->GetOutputPort(l3));
  writer->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "\\l3.mhd").c_str());
  writer->SetRAWFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "\\l3.raw").c_str());
  writer->Update();
  writer->Write();

  return 0;
}
<commit_msg>Cleaned up old commented out code no longer in use<commit_after>/*=========================================================================

Program:   Robarts Visualization Toolkit

Copyright (c) John Stuart Haberl Baxter, Robarts Research Institute

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

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

#include "vtkBMPReader.h"
#include "vtkDataSetAttributes.h"
#include "vtkDirectedAcyclicGraphMaxFlowSegmentation.h"
#include "vtkFloatArray.h"
#include "vtkImageCast.h"
#include "vtkImageData.h"
#include "vtkImageExtractComponents.h"
#include "vtkMetaImageWriter.h"
#include "vtkMutableDirectedGraph.h"
#include "vtkRootedDirectedAcyclicGraph.h"
#include "vtkRootedDirectedAcyclicGraphBackwardIterator.h"
#include "vtkRootedDirectedAcyclicGraphForwardIterator.h"
#include "vtkRootedDirectedAcyclicGraphIterator.h"
#include "vtksys/CommandLineArguments.hxx"
#include "vtksys/SystemTools.hxx"
#include <iostream>
#include <vtkSmartPointer.h>
#include <vtkVersion.h>

int main(int argc, char** argv)
{
  // Check command line arguments.
  bool printHelp(false);
  std::string outputDirectory;

  vtksys::CommandLineArguments args;
  args.Initialize( argc, argv );

  args.AddArgument("--help", vtksys::CommandLineArguments::NO_ARGUMENT, &printHelp, "Print this help.");
  args.AddArgument( "--output-dir", vtksys::CommandLineArguments::EQUAL_ARGUMENT, &outputDirectory, "Name of the output directory." );

  if ( !args.Parse() )
  {
    std::cerr << "Problem parsing arguments." << std::endl;
    std::cout << "Help: " << args.GetHelp() << std::endl;
    exit(EXIT_FAILURE);
  }

  if ( printHelp )
  {
    std::cout << args.GetHelp() << std::endl;
    exit(EXIT_SUCCESS);
  }

  if( !vtksys::SystemTools::FileExists(outputDirectory.c_str(), false) && !vtksys::SystemTools::MakeDirectory(outputDirectory) )
  {
    std::cerr << "Output directory doesn't exist and can't be created." << std::endl;
  }

  vtkSmartPointer<vtkMutableDirectedGraph> mut = vtkSmartPointer<vtkMutableDirectedGraph>::New();
  vtkIdType source = mut->AddVertex();
  vtkIdType bkg = mut->AddVertex();
  vtkIdType c1 = mut->AddVertex();
  vtkIdType c2 = mut->AddVertex();
  vtkIdType l1 = mut->AddVertex();
  vtkIdType l2 = mut->AddVertex();
  vtkIdType l3 = mut->AddVertex();

  vtkSmartPointer<vtkFloatArray> Weights = vtkSmartPointer<vtkFloatArray>::New();
  Weights->SetName("Weights");
  Weights->InsertValue((mut->AddEdge(source,bkg)).Id,1.0f);
  Weights->InsertValue((mut->AddEdge(source,c1)).Id,1.0f);
  Weights->InsertValue((mut->AddEdge(source,c2)).Id,1.0f);
  Weights->InsertValue((mut->AddEdge(source,l1)).Id,0.5f);
  Weights->InsertValue((mut->AddEdge(source,l2)).Id,0.5f);
  Weights->InsertValue((mut->AddEdge(c1,l1)).Id,0.5f);
  Weights->InsertValue((mut->AddEdge(c2,l2)).Id,0.5f);
  Weights->InsertValue((mut->AddEdge(c1,l3)).Id,0.5f);
  Weights->InsertValue((mut->AddEdge(c2,l3)).Id,0.5f);

  vtkSmartPointer<vtkRootedDirectedAcyclicGraph> DAG = vtkSmartPointer<vtkRootedDirectedAcyclicGraph>::New();
  DAG->CheckedShallowCopy(mut);

  vtkSmartPointer<vtkBMPReader> cost0 = vtkSmartPointer<vtkBMPReader>::New();
  cost0->SetFileName( std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "/cost0.bmp").c_str() );
  vtkSmartPointer<vtkBMPReader> cost1 = vtkSmartPointer<vtkBMPReader>::New();
  cost1->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "/cost1.bmp").c_str());
  vtkSmartPointer<vtkBMPReader> cost2 = vtkSmartPointer<vtkBMPReader>::New();
  cost2->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "/cost2.bmp").c_str());
  vtkSmartPointer<vtkBMPReader> cost3 = vtkSmartPointer<vtkBMPReader>::New();
  cost3->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "/cost3.bmp").c_str());

  vtkSmartPointer<vtkImageExtractComponents> extract0 = vtkSmartPointer<vtkImageExtractComponents>::New();
  extract0->SetComponents(0);
  extract0->SetInputConnection(cost0->GetOutputPort());
  vtkSmartPointer<vtkImageCast> cast0 = vtkSmartPointer<vtkImageCast>::New();
  cast0->SetOutputScalarTypeToFloat();
  cast0->SetInputConnection(extract0->GetOutputPort());
  vtkSmartPointer<vtkImageExtractComponents> extract1 = vtkSmartPointer<vtkImageExtractComponents>::New();
  extract1->SetComponents(0);
  extract1->SetInputConnection(cost1->GetOutputPort());
  vtkSmartPointer<vtkImageCast> cast1 = vtkSmartPointer<vtkImageCast>::New();
  cast1->SetOutputScalarTypeToFloat();
  cast1->SetInputConnection(extract1->GetOutputPort());
  vtkSmartPointer<vtkImageExtractComponents> extract2 = vtkSmartPointer<vtkImageExtractComponents>::New();
  extract2->SetComponents(0);
  extract2->SetInputConnection(cost2->GetOutputPort());
  vtkSmartPointer<vtkImageCast> cast2 = vtkSmartPointer<vtkImageCast>::New();
  cast2->SetOutputScalarTypeToFloat();
  cast2->SetInputConnection(extract2->GetOutputPort());
  vtkSmartPointer<vtkImageExtractComponents> extract3 = vtkSmartPointer<vtkImageExtractComponents>::New();
  extract3->SetComponents(0);
  extract3->SetInputConnection(cost3->GetOutputPort());
  vtkSmartPointer<vtkImageCast> cast3 = vtkSmartPointer<vtkImageCast>::New();
  cast3->SetOutputScalarTypeToFloat();
  cast3->SetInputConnection(extract3->GetOutputPort());

  vtkSmartPointer<vtkDirectedAcyclicGraphMaxFlowSegmentation> dagmf =
    vtkSmartPointer<vtkDirectedAcyclicGraphMaxFlowSegmentation>::New();
  dagmf->SetStructure(DAG);
  dagmf->SetDataInputConnection(bkg,cast0->GetOutputPort());
  dagmf->SetDataInputConnection(l1,cast1->GetOutputPort());
  dagmf->SetDataInputConnection(l2,cast2->GetOutputPort());
  dagmf->SetDataInputConnection(l3,cast3->GetOutputPort());
  dagmf->AddSmoothnessScalar(bkg,0.01);
  dagmf->AddSmoothnessScalar(l1, 0.01);
  dagmf->AddSmoothnessScalar(l2, 0.01);
  dagmf->AddSmoothnessScalar(l3, 0.01);
  dagmf->AddSmoothnessScalar(c1, 50);
  dagmf->AddSmoothnessScalar(c2, 50);
  dagmf->SetCC(0.01);
  dagmf->SetStepSize(0.1);
  dagmf->SetNumberOfIterations(100);

  vtkSmartPointer<vtkMetaImageWriter> writer = vtkSmartPointer<vtkMetaImageWriter>::New();
  writer->SetInputConnection(dagmf->GetOutputPort(bkg));
  writer->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "\\l0.mhd").c_str());
  writer->SetRAWFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "\\l0.raw").c_str());
  writer->Update();
  writer->Write();
  writer->SetInputConnection(dagmf->GetOutputPort(l1));
  writer->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "\\l1.mhd").c_str());
  writer->SetRAWFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "\\l1.raw").c_str());
  writer->Update();
  writer->Write();
  writer->SetInputConnection(dagmf->GetOutputPort(l2));
  writer->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "\\l2.mhd").c_str());
  writer->SetRAWFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "\\l2.raw").c_str());
  writer->Update();
  writer->Write();
  writer->SetInputConnection(dagmf->GetOutputPort(l3));
  writer->SetFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "\\l3.mhd").c_str());
  writer->SetRAWFileName(std::string(vtksys::SystemTools::GetFilenamePath(outputDirectory) + "\\l3.raw").c_str());
  writer->Update();
  writer->Write();

  return 0;
}
<|endoftext|>


<commit_before>// UjoImro, 2013
// Experimental code for the CARP Project
// Copyright (c) RealEyes, 2013
// This version tests the responseMap calculation with input dumps

/*
  extern int EF_ALIGNMENT = 0;
  extern int EF_PROTECT_BELOW = 0;
  extern int EF_PROTECT_FREE = 0;
  extern int EF_ALLOW_MALLOC_0 = 1;
  extern int EF_FILL = 1922;
*/

#include <iomanip>
#include <boost/smart_ptr.hpp>

#include "opencl.hpp"
#include "memory.hpp"
#include "bench_mlp.hpp"

const int processed_frames = 100;

int main()
{
    conductor_t conductor; // the class for importing the input from the clm
    carp::opencl::device device;
    device.compile( {"mlp_impl.cl"}, {"calculateMaps"} );

    int fail = 0;
    long int elapsed_time = 0;
    int64_t maxnetallocated = 0;
    int64_t maxgrossallocated = 0;

    for ( conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id);
          ((conductor.id != -1) and (conductor.id != processed_frames));
          // conductor.id != -1;
          conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id)
        )
    {
        PRINT(conductor.id);
        conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack);

        int groupsize = conductor.hack.m_visibleLandmarks_size;

        boost::shared_array<char> buffer( new char[groupsize * local_memsize] );

        // std::vector<carp::memory::buddy> pools( groupsize, carp::memory::buddy({local_memsize, uint8_t()}));
        std::vector<carp::memory::dense> pools( groupsize, carp::memory::dense({local_memsize, uint8_t()}));
        carp::memory::local_memory_manager locmm( groupsize * local_memsize, groupsize, local_memsize );

        void * self = buffer.get();
        std::vector<int> segments = locmm.get_segments();

        // here comes the function call
        {
            auto calcpackages = convertHackToMlp( self, pools, segments, conductor.hack );

            for ( auto & pool : pools ) {
//                PRINT(pool.grossallocated());
//                PRINT(pool.netallocated());
                maxgrossallocated = std::max( maxgrossallocated, pool.grossallocated() );
                maxnetallocated = std::max( maxnetallocated, pool.netallocated() );
            }

            // preparing the opencl data
            carp::opencl::array<uint8_t> clSelf( device, groupsize * local_memsize, self );
            carp::opencl::array<int> clSegments( device, segments );
            carp::opencl::array<calcpackage> clCalcpackages( device, calcpackages );

            auto start = std::chrono::high_resolution_clock::now();
            device["calculateMaps"](
                clSelf.cl(),
                clSegments.cl(),
                conductor.hack.m_visibleLandmarks_size,
                conductor.hack.m_mapSize,
                clCalcpackages.cl(),
                carp::opencl::buffer(48 * KiB)
                ).groupsize({32},{32*conductor.hack.m_visibleLandmarks_size});
            auto end = std::chrono::high_resolution_clock::now();
            elapsed_time += microseconds(end - start);

            // copying the data back to the CPU
            auto processed = clSelf.get();
            void * results = reinterpret_cast<void*>(processed.data());

            clMat patch = GetMatFromVector( results + segments[9], calcpackages[9].tmp.patches, 0 );
            patch.rows = patch.rows * patch.cols;
            patch.cols = 1;
            patch.step = 1;

            clMat imagePatch = GetBlockChar( results + segments[9], calcpackages[9].input.alignedImage, 5, 16, 52, 63 );
            clMat xOuts = GetMatFromVector( results + segments[9], calcpackages[9].tmp.xOuts, 0 );
            clMat e = GetMatFromVector( results + segments[9], calcpackages[9].tmp.es, 0 );

            // printMatChar( results + segments[9], imagePatch, "imagePatch" );
            // printMatFloat( results + segments[9], patch, "patch");
            // printMatFloat( results + segments[9], e, "e");
            // printMatFloat( results + segments[9], xOuts, "xOuts");

            // printMatFloat( results + segments[9], calcpackages[9].output.responseMap, "calcpackages[9].output.responseMap");

//            assert(false);

            // converting the outputs
            std::vector< cv::Mat_<double> > calculatedResults;
            for (int q=0; q<conductor.hack.m_visibleLandmarks_size; q++)
            {
                cv::Mat_<double> nextResult;
                nextResult = convertMatFloatToCV( results + segments[q], calcpackages[q].output.responseMap );
                calculatedResults.push_back(nextResult);
            }

            // testing the output
            for (int q=0; q<conductor.hack.m_visibleLandmarks_size; q++)
            {
                // std::cout << "cv::norm( conductor.hack.responseMaps[" << q << "] - calculatedResults[" << q << "] ) = "
                //             << cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) << std::endl;

                // for (int row=0; row<calculatedResults[q].rows; row++ )
                //     for (int col=0; col<calculatedResults[q].cols; col++ )
                //         if ( (conductor.hack.responseMaps[q](row,col) - calculatedResults[q](row,col)) > 0.0001 )
                //         {
                //             PRINT(row);
                //             PRINT(col);
                //             PRINT(conductor.hack.responseMaps[q](row,col));
                //             PRINT(calculatedResults[q](row,col));
                //         }

                PRINT(cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ));
                assert(cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) < 0.08);
            }

        }
    }

    std::cout << "total elapsed time = " << elapsed_time / 1000000. << " s." << std::endl;
    std::cout << std::setprecision(2) << std::fixed;
    std::cout << "processing speed   = " << 1000000. * processed_frames / elapsed_time << "fps" << std::endl;
    //conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack);

    PRINT(maxnetallocated);
    PRINT(maxgrossallocated);

    return EXIT_SUCCESS;
} // int main

// LuM end of file
<commit_msg>the unittest strenghtened after Robi has fixed the initialization<commit_after>// UjoImro, 2013
// Experimental code for the CARP Project
// Copyright (c) RealEyes, 2013
// This version tests the responseMap calculation with input dumps

/*
  extern int EF_ALIGNMENT = 0;
  extern int EF_PROTECT_BELOW = 0;
  extern int EF_PROTECT_FREE = 0;
  extern int EF_ALLOW_MALLOC_0 = 1;
  extern int EF_FILL = 1922;
*/

#include <iomanip>
#include <boost/smart_ptr.hpp>

#include "opencl.hpp"
#include "memory.hpp"
#include "bench_mlp.hpp"

const int processed_frames = 100;

int main()
{
    conductor_t conductor; // the class for importing the input from the clm
    carp::opencl::device device;
    device.compile( {"mlp_impl.cl"}, {"calculateMaps"} );

    int fail = 0;
    long int elapsed_time = 0;
    int64_t maxnetallocated = 0;
    int64_t maxgrossallocated = 0;

    for ( conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id);
          ((conductor.id != -1) and (conductor.id != processed_frames));
          // conductor.id != -1;
          conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.id)
        )
    {
        PRINT(conductor.id);
        conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack);

        int groupsize = conductor.hack.m_visibleLandmarks_size;

        boost::shared_array<char> buffer( new char[groupsize * local_memsize] );

        // std::vector<carp::memory::buddy> pools( groupsize, carp::memory::buddy({local_memsize, uint8_t()}));
        std::vector<carp::memory::dense> pools( groupsize, carp::memory::dense({local_memsize, uint8_t()}));
        carp::memory::local_memory_manager locmm( groupsize * local_memsize, groupsize, local_memsize );

        void * self = buffer.get();
        std::vector<int> segments = locmm.get_segments();

        // here comes the function call
        {
            auto calcpackages = convertHackToMlp( self, pools, segments, conductor.hack );

            for ( auto & pool : pools ) {
//                PRINT(pool.grossallocated());
//                PRINT(pool.netallocated());
                maxgrossallocated = std::max( maxgrossallocated, pool.grossallocated() );
                maxnetallocated = std::max( maxnetallocated, pool.netallocated() );
            }

            // preparing the opencl data
            carp::opencl::array<uint8_t> clSelf( device, groupsize * local_memsize, self );
            carp::opencl::array<int> clSegments( device, segments );
            carp::opencl::array<calcpackage> clCalcpackages( device, calcpackages );

            auto start = std::chrono::high_resolution_clock::now();
            device["calculateMaps"](
                clSelf.cl(),
                clSegments.cl(),
                conductor.hack.m_visibleLandmarks_size,
                conductor.hack.m_mapSize,
                clCalcpackages.cl(),
                carp::opencl::buffer(48 * KiB)
                ).groupsize({32},{32*conductor.hack.m_visibleLandmarks_size});
            auto end = std::chrono::high_resolution_clock::now();
            elapsed_time += microseconds(end - start);

            // copying the data back to the CPU
            auto processed = clSelf.get();
            void * results = reinterpret_cast<void*>(processed.data());

            clMat patch = GetMatFromVector( results + segments[9], calcpackages[9].tmp.patches, 0 );
            patch.rows = patch.rows * patch.cols;
            patch.cols = 1;
            patch.step = 1;

            clMat imagePatch = GetBlockChar( results + segments[9], calcpackages[9].input.alignedImage, 5, 16, 52, 63 );
            clMat xOuts = GetMatFromVector( results + segments[9], calcpackages[9].tmp.xOuts, 0 );
            clMat e = GetMatFromVector( results + segments[9], calcpackages[9].tmp.es, 0 );

            // printMatChar( results + segments[9], imagePatch, "imagePatch" );
            // printMatFloat( results + segments[9], patch, "patch");
            // printMatFloat( results + segments[9], e, "e");
            // printMatFloat( results + segments[9], xOuts, "xOuts");

            // printMatFloat( results + segments[9], calcpackages[9].output.responseMap, "calcpackages[9].output.responseMap");

//            assert(false);

            // converting the outputs
            std::vector< cv::Mat_<double> > calculatedResults;
            for (int q=0; q<conductor.hack.m_visibleLandmarks_size; q++)
            {
                cv::Mat_<double> nextResult;
                nextResult = convertMatFloatToCV( results + segments[q], calcpackages[q].output.responseMap );
                calculatedResults.push_back(nextResult);
            }

            // testing the output
            for (int q=0; q<conductor.hack.m_visibleLandmarks_size; q++)
            {
                // std::cout << "cv::norm( conductor.hack.responseMaps[" << q << "] - calculatedResults[" << q << "] ) = "
                //             << cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) << std::endl;

                // for (int row=0; row<calculatedResults[q].rows; row++ )
                //     for (int col=0; col<calculatedResults[q].cols; col++ )
                //         if ( (conductor.hack.responseMaps[q](row,col) - calculatedResults[q](row,col)) > 0.0001 )
                //         {
                //             PRINT(row);
                //             PRINT(col);
                //             PRINT(conductor.hack.responseMaps[q](row,col));
                //             PRINT(calculatedResults[q](row,col));
                //         }

                assert(cv::norm( conductor.hack.responseMaps[q] - calculatedResults[q] ) < 0.0001);
            }

        }
    }

    std::cout << "total elapsed time = " << elapsed_time / 1000000. << " s." << std::endl;
    std::cout << std::setprecision(2) << std::fixed;
    std::cout << "processing speed   = " << 1000000. * processed_frames / elapsed_time << "fps" << std::endl;
    //conductor.importer >> BOOST_SERIALIZATION_NVP(conductor.hack);

    PRINT(maxnetallocated);
    PRINT(maxgrossallocated);

    return EXIT_SUCCESS;
} // int main

// LuM end of file
<|endoftext|>


<commit_before>#include "kwm.h"
#include "helpers.h"
#include "daemon.h"
#include "display.h"
#include "space.h"
#include "window.h"
#include "keys.h"
#include "interpreter.h"
#include "scratchpad.h"
#include "border.h"
#include "config.h"
#include "command.h"
#include "cursor.h"
#include "axlib/axlib.h"

#define internal static
const std::string KwmCurrentVersion = "Kwm Version 3.0.3";
std::map<const char *, space_info> WindowTree;

ax_state AXState = {};
ax_display *FocusedDisplay = NULL;
ax_application *FocusedApplication = NULL;
ax_window *MarkedWindow = NULL;

kwm_mach KWMMach = {};
kwm_path KWMPath = {};
kwm_settings KWMSettings = {};
kwm_thread KWMThread = {};
kwm_hotkeys KWMHotkeys = {};
kwm_border FocusedBorder = {};
kwm_border MarkedBorder = {};
scratchpad Scratchpad = {};

CGEventRef CGEventCallback(CGEventTapProxy Proxy, CGEventType Type, CGEventRef Event, void *Refcon)
{
    switch(Type)
    {
        case kCGEventTapDisabledByTimeout:
        case kCGEventTapDisabledByUserInput:
        {
            if(!KWMMach.DisableEventTapInternal)
            {
                DEBUG("Restarting Event Tap");
                CGEventTapEnable(KWMMach.EventTap, true);
            }
        } break;
        case kCGEventKeyDown:
        {
            /* TODO(koekeishiya): Is there a better way to decide whether
                                  we should eat the CGEventRef or not (?) */
            if(KWMSettings.UseBuiltinHotkeys)
            {
                hotkey Eventkey = {}, *Hotkey = NULL;
                Hotkey = new hotkey;
                if(Hotkey)
                {
                    CreateHotkeyFromCGEvent(Event, &Eventkey);
                    if(HotkeyExists(Eventkey.Flags, Eventkey.Key, Hotkey, KWMHotkeys.ActiveMode->Name))
                    {
                        AXLibConstructEvent(AXEvent_HotkeyPressed, Hotkey, false);
                        if(!Hotkey->Passthrough)
                            return NULL;
                    }
                    else
                    {
                        delete Hotkey;
                    }
                }
            }
        } break;
        case kCGEventMouseMoved:
        {
            if(KWMSettings.Focus == FocusModeAutoraise)
                AXLibConstructEvent(AXEvent_MouseMoved, NULL, false);
        } break;
        default: {} break;
    }

    return Event;
}

internal bool
CheckPrivileges()
{
    bool Result = false;
    const void * Keys[] = { kAXTrustedCheckOptionPrompt };
    const void * Values[] = { kCFBooleanTrue };

    CFDictionaryRef Options;
    Options = CFDictionaryCreate(kCFAllocatorDefault,
                                 Keys, Values, sizeof(Keys) / sizeof(*Keys),
                                 &kCFCopyStringDictionaryKeyCallBacks,
                                 &kCFTypeDictionaryValueCallBacks);

    Result = AXIsProcessTrustedWithOptions(Options);
    CFRelease(Options);

    return Result;
}

internal bool
CheckArguments(int argc, char **argv)
{
    bool Result = false;

    if(argc == 2)
    {
        std::string Arg = argv[1];
        if(Arg == "--version")
        {
            std::cout << KwmCurrentVersion << std::endl;
            Result = true;
        }
    }

    return Result;
}

internal bool
GetKwmFilePath()
{
    bool Result = false;
    char PathBuf[PROC_PIDPATHINFO_MAXSIZE];
    pid_t Pid = getpid();
    int Ret = proc_pidpath(Pid, PathBuf, sizeof(PathBuf));
    if (Ret > 0)
    {
        KWMPath.FilePath = PathBuf;

        std::size_t Split = KWMPath.FilePath.find_last_of("/\\");
        KWMPath.FilePath = KWMPath.FilePath.substr(0, Split);
        Result = true;
    }

    return Result;
}

internal void
KwmClearSettings()
{
    KWMHotkeys.Modes.clear();
    KWMSettings.WindowRules.clear();
    KWMSettings.SpaceSettings.clear();
    KWMSettings.DisplaySettings.clear();
    KWMHotkeys.ActiveMode = GetBindingMode("default");
}

internal void
KwmExecuteConfig()
{
    char *HomeP = std::getenv("HOME");
    if(!HomeP)
    {
        DEBUG("Failed to get environment variable 'HOME'");
        return;
    }

    KWMPath.EnvHome = HomeP;
    KwmParseConfig(KWMPath.ConfigFile);
}

internal void
KwmExecuteInitScript()
{
    std::string InitFile = KWMPath.EnvHome + "/" + KWMPath.ConfigFolder + "/init";

    struct stat Buffer;
    if(stat(InitFile.c_str(), &Buffer) == 0)
        KwmExecuteThreadedSystemCommand(InitFile);
}

internal void
SignalHandler(int Signum)
{
    ShowAllScratchpadWindows();
    DEBUG("SignalHandler() " << Signum);

    CloseBorder(&FocusedBorder);
    CloseBorder(&MarkedBorder);
    exit(Signum);
}

internal void
Fatal(const std::string &Err)
{
    std::cout << Err << std::endl;
    exit(1);
}

internal void
KwmInit()
{
    if(!CheckPrivileges())
        Fatal("Error: Could not access OSX Accessibility!");

    if(KwmStartDaemon())
        pthread_create(&KWMThread.Daemon, NULL, &KwmDaemonHandleConnectionBG, NULL);
    else
        Fatal("Error: Could not start daemon!");

#ifndef DEBUG_BUILD
    signal(SIGSEGV, SignalHandler);
    signal(SIGABRT, SignalHandler);
    signal(SIGTRAP, SignalHandler);
    signal(SIGTERM, SignalHandler);
    signal(SIGKILL, SignalHandler);
    signal(SIGINT, SignalHandler);
#else
    printf("Kwm: Signal handlers are disabled!\n");
#endif

    KWMSettings.SplitRatio = 0.5;
    KWMSettings.SplitMode = SPLIT_OPTIMAL;
    KWMSettings.DefaultOffset = CreateDefaultScreenOffset();

    KWMSettings.UseBuiltinHotkeys = true;
    KWMSettings.UseMouseFollowsFocus = true;
    KWMSettings.OptimalRatio = 1.618;
    KWMSettings.LockToContainer = true;

    KWMSettings.Space = SpaceModeBSP;
    KWMSettings.Focus = FocusModeAutoraise;
    KWMSettings.Cycle = CycleModeScreen;

    FocusedBorder.Radius = -1;
    MarkedBorder.Radius = -1;

    KWMPath.ConfigFile = "kwmrc";
    KWMPath.ConfigFolder = ".kwm";
    KWMPath.BSPLayouts = "layouts";
    KWMHotkeys.ActiveMode = GetBindingMode("default");

    GetKwmFilePath();
}

void KwmQuit()
{
    ShowAllScratchpadWindows();
    CloseBorder(&FocusedBorder);
    CloseBorder(&MarkedBorder);

    exit(0);
}

void KwmReloadConfig()
{
    KwmClearSettings();
    KwmExecuteConfig();
}

int main(int argc, char **argv)
{
    if(CheckArguments(argc, argv))
        return 0;

    NSApplicationLoad();
    if(!AXLibDisplayHasSeparateSpaces())
        Fatal("Error: 'Displays have separate spaces' must be enabled!");

    /* NOTE(koekeishiya): Initialize AXLIB */
    AXLibInit(&AXState);
    AXLibStartEventLoop();

    ax_display *MainDisplay = AXLibMainDisplay();
    ax_display *Display = MainDisplay;
    do
    {
        ax_space *PrevSpace = Display->Space;
        Display->Space = AXLibGetActiveSpace(Display);
        Display->PrevSpace = PrevSpace;
        Display = AXLibNextDisplay(Display);
    } while(Display != MainDisplay);

    FocusedDisplay = MainDisplay;
    FocusedApplication = AXLibGetFocusedApplication();
    /* ----------------------------------- */

    KwmInit();
    KwmExecuteConfig();
    KwmExecuteInitScript();
    CreateWindowNodeTree(MainDisplay);

    if(CGSIsSecureEventInputSet())
        fprintf(stderr, "Secure Keyboard Entry is enabled, hotkeys will not work!\n");

    KWMMach.EventMask = ((1 << kCGEventKeyDown) |
                         (1 << kCGEventMouseMoved));

    KWMMach.EventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault, KWMMach.EventMask, CGEventCallback, NULL);
    if(!KWMMach.EventTap || !CGEventTapIsEnabled(KWMMach.EventTap))
        Fatal("Error: Could not create event-tap!");

    CFRunLoopAddSource(CFRunLoopGetMain(),
                       CFMachPortCreateRunLoopSource(kCFAllocatorDefault, KWMMach.EventTap, 0),
                       kCFRunLoopCommonModes);
    CGEventTapEnable(KWMMach.EventTap, true);
    CFRunLoopRun();
    return 0;
}
<commit_msg>version 3.0.4<commit_after>#include "kwm.h"
#include "helpers.h"
#include "daemon.h"
#include "display.h"
#include "space.h"
#include "window.h"
#include "keys.h"
#include "interpreter.h"
#include "scratchpad.h"
#include "border.h"
#include "config.h"
#include "command.h"
#include "cursor.h"
#include "axlib/axlib.h"

#define internal static
const std::string KwmCurrentVersion = "Kwm Version 3.0.4";
std::map<const char *, space_info> WindowTree;

ax_state AXState = {};
ax_display *FocusedDisplay = NULL;
ax_application *FocusedApplication = NULL;
ax_window *MarkedWindow = NULL;

kwm_mach KWMMach = {};
kwm_path KWMPath = {};
kwm_settings KWMSettings = {};
kwm_thread KWMThread = {};
kwm_hotkeys KWMHotkeys = {};
kwm_border FocusedBorder = {};
kwm_border MarkedBorder = {};
scratchpad Scratchpad = {};

CGEventRef CGEventCallback(CGEventTapProxy Proxy, CGEventType Type, CGEventRef Event, void *Refcon)
{
    switch(Type)
    {
        case kCGEventTapDisabledByTimeout:
        case kCGEventTapDisabledByUserInput:
        {
            if(!KWMMach.DisableEventTapInternal)
            {
                DEBUG("Restarting Event Tap");
                CGEventTapEnable(KWMMach.EventTap, true);
            }
        } break;
        case kCGEventKeyDown:
        {
            /* TODO(koekeishiya): Is there a better way to decide whether
                                  we should eat the CGEventRef or not (?) */
            if(KWMSettings.UseBuiltinHotkeys)
            {
                hotkey Eventkey = {}, *Hotkey = NULL;
                Hotkey = new hotkey;
                if(Hotkey)
                {
                    CreateHotkeyFromCGEvent(Event, &Eventkey);
                    if(HotkeyExists(Eventkey.Flags, Eventkey.Key, Hotkey, KWMHotkeys.ActiveMode->Name))
                    {
                        AXLibConstructEvent(AXEvent_HotkeyPressed, Hotkey, false);
                        if(!Hotkey->Passthrough)
                            return NULL;
                    }
                    else
                    {
                        delete Hotkey;
                    }
                }
            }
        } break;
        case kCGEventMouseMoved:
        {
            if(KWMSettings.Focus == FocusModeAutoraise)
                AXLibConstructEvent(AXEvent_MouseMoved, NULL, false);
        } break;
        default: {} break;
    }

    return Event;
}

internal bool
CheckPrivileges()
{
    bool Result = false;
    const void * Keys[] = { kAXTrustedCheckOptionPrompt };
    const void * Values[] = { kCFBooleanTrue };

    CFDictionaryRef Options;
    Options = CFDictionaryCreate(kCFAllocatorDefault,
                                 Keys, Values, sizeof(Keys) / sizeof(*Keys),
                                 &kCFCopyStringDictionaryKeyCallBacks,
                                 &kCFTypeDictionaryValueCallBacks);

    Result = AXIsProcessTrustedWithOptions(Options);
    CFRelease(Options);

    return Result;
}

internal bool
CheckArguments(int argc, char **argv)
{
    bool Result = false;

    if(argc == 2)
    {
        std::string Arg = argv[1];
        if(Arg == "--version")
        {
            std::cout << KwmCurrentVersion << std::endl;
            Result = true;
        }
    }

    return Result;
}

internal bool
GetKwmFilePath()
{
    bool Result = false;
    char PathBuf[PROC_PIDPATHINFO_MAXSIZE];
    pid_t Pid = getpid();
    int Ret = proc_pidpath(Pid, PathBuf, sizeof(PathBuf));
    if (Ret > 0)
    {
        KWMPath.FilePath = PathBuf;

        std::size_t Split = KWMPath.FilePath.find_last_of("/\\");
        KWMPath.FilePath = KWMPath.FilePath.substr(0, Split);
        Result = true;
    }

    return Result;
}

internal void
KwmClearSettings()
{
    KWMHotkeys.Modes.clear();
    KWMSettings.WindowRules.clear();
    KWMSettings.SpaceSettings.clear();
    KWMSettings.DisplaySettings.clear();
    KWMHotkeys.ActiveMode = GetBindingMode("default");
}

internal void
KwmExecuteConfig()
{
    char *HomeP = std::getenv("HOME");
    if(!HomeP)
    {
        DEBUG("Failed to get environment variable 'HOME'");
        return;
    }

    KWMPath.EnvHome = HomeP;
    KwmParseConfig(KWMPath.ConfigFile);
}

internal void
KwmExecuteInitScript()
{
    std::string InitFile = KWMPath.EnvHome + "/" + KWMPath.ConfigFolder + "/init";

    struct stat Buffer;
    if(stat(InitFile.c_str(), &Buffer) == 0)
        KwmExecuteThreadedSystemCommand(InitFile);
}

internal void
SignalHandler(int Signum)
{
    ShowAllScratchpadWindows();
    DEBUG("SignalHandler() " << Signum);

    CloseBorder(&FocusedBorder);
    CloseBorder(&MarkedBorder);
    exit(Signum);
}

internal void
Fatal(const std::string &Err)
{
    std::cout << Err << std::endl;
    exit(1);
}

internal void
KwmInit()
{
    if(!CheckPrivileges())
        Fatal("Error: Could not access OSX Accessibility!");

    if(KwmStartDaemon())
        pthread_create(&KWMThread.Daemon, NULL, &KwmDaemonHandleConnectionBG, NULL);
    else
        Fatal("Error: Could not start daemon!");

#ifndef DEBUG_BUILD
    signal(SIGSEGV, SignalHandler);
    signal(SIGABRT, SignalHandler);
    signal(SIGTRAP, SignalHandler);
    signal(SIGTERM, SignalHandler);
    signal(SIGKILL, SignalHandler);
    signal(SIGINT, SignalHandler);
#else
    printf("Kwm: Signal handlers are disabled!\n");
#endif

    KWMSettings.SplitRatio = 0.5;
    KWMSettings.SplitMode = SPLIT_OPTIMAL;
    KWMSettings.DefaultOffset = CreateDefaultScreenOffset();

    KWMSettings.UseBuiltinHotkeys = true;
    KWMSettings.UseMouseFollowsFocus = true;
    KWMSettings.OptimalRatio = 1.618;
    KWMSettings.LockToContainer = true;

    KWMSettings.Space = SpaceModeBSP;
    KWMSettings.Focus = FocusModeAutoraise;
    KWMSettings.Cycle = CycleModeScreen;

    FocusedBorder.Radius = -1;
    MarkedBorder.Radius = -1;

    KWMPath.ConfigFile = "kwmrc";
    KWMPath.ConfigFolder = ".kwm";
    KWMPath.BSPLayouts = "layouts";
    KWMHotkeys.ActiveMode = GetBindingMode("default");

    GetKwmFilePath();
}

void KwmQuit()
{
    ShowAllScratchpadWindows();
    CloseBorder(&FocusedBorder);
    CloseBorder(&MarkedBorder);

    exit(0);
}

void KwmReloadConfig()
{
    KwmClearSettings();
    KwmExecuteConfig();
}

int main(int argc, char **argv)
{
    if(CheckArguments(argc, argv))
        return 0;

    NSApplicationLoad();
    if(!AXLibDisplayHasSeparateSpaces())
        Fatal("Error: 'Displays have separate spaces' must be enabled!");

    /* NOTE(koekeishiya): Initialize AXLIB */
    AXLibInit(&AXState);
    AXLibStartEventLoop();

    ax_display *MainDisplay = AXLibMainDisplay();
    ax_display *Display = MainDisplay;
    do
    {
        ax_space *PrevSpace = Display->Space;
        Display->Space = AXLibGetActiveSpace(Display);
        Display->PrevSpace = PrevSpace;
        Display = AXLibNextDisplay(Display);
    } while(Display != MainDisplay);

    FocusedDisplay = MainDisplay;
    FocusedApplication = AXLibGetFocusedApplication();
    /* ----------------------------------- */

    KwmInit();
    KwmExecuteConfig();
    KwmExecuteInitScript();
    CreateWindowNodeTree(MainDisplay);

    if(CGSIsSecureEventInputSet())
        fprintf(stderr, "Secure Keyboard Entry is enabled, hotkeys will not work!\n");

    KWMMach.EventMask = ((1 << kCGEventKeyDown) |
                         (1 << kCGEventMouseMoved));

    KWMMach.EventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault, KWMMach.EventMask, CGEventCallback, NULL);
    if(!KWMMach.EventTap || !CGEventTapIsEnabled(KWMMach.EventTap))
        Fatal("Error: Could not create event-tap!");

    CFRunLoopAddSource(CFRunLoopGetMain(),
                       CFMachPortCreateRunLoopSource(kCFAllocatorDefault, KWMMach.EventTap, 0),
                       kCFRunLoopCommonModes);
    CGEventTapEnable(KWMMach.EventTap, true);
    CFRunLoopRun();
    return 0;
}
<|endoftext|>


<commit_before>// Time:  O(n^3)
// Space: O(n^2)

class Solution {
public:
    /**
     * @param A an integer array
     * @param k an integer
     * @return an integer
     */
    int postOffice(vector<int>& A, int k) {
        const int n = A.size();
        if (A.empty() || k >= n) {
            return 0;
        }

        sort(A.begin(), A.end());  // Time:  O(nlogn)

        // Precompute cost.
        // Time:  O(n^3)
        // Space: O(n^2)
        vector<vector<int>> cost(A.size() + 1, vector<int>(A.size() + 1, 0));
        computeMinCost(A, &cost);

        // DP of sum.
        // Time:  O(k * n^2)
        // Space: O(n)
        // sum[i][j] denotes the smallest sum of
        // picking i post offices for the first j houses.
        vector<vector<int>> sum(2, vector<int>(A.size() + 1, INT_MAX));
        sum[0][0] = 0;
        for (int i = 1; i <= k; ++i) {
            for (int j = 0; j <= n; ++j) {
                sum[i % 2][j] = INT_MAX;
                for (int r = 1; r <= j; ++r) {
                    if (sum[(i - 1) % 2][j - r] != INT_MAX) {
                        sum[i % 2][j] = min(sum[i % 2][j],
                                            sum[(i - 1) % 2][j - r] +
                                            cost[j - r + 1][j]);
                    }
                }
            }
        }
        return sum[k % 2][n];
    }

    void computeMinCost(const vector<int>& A, vector<vector<int>> *cost) {
        // Min cost of building a post office between house (i, j).
        // This post office must be in median position.
        const int n = A.size();
        for (int i = 0; i < n; ++i) {
            for (int j = i; j < n; ++j) {
                int mid = (i + j) / 2;
                for (int r = i; r <= mid; ++r) {
                    (*cost)[i + 1][j + 1] += A[mid] - A[r];
                }
                for (int r = mid + 1; r <= j; ++r) {
                    (*cost)[i + 1][j + 1] += A[r] - A[mid];
                }
            }
        }
    }
};

// Time:  O(n^3)
// Space: O(n^2)
class Solution2 {
public:
    /**
     * @param A an integer array
     * @param k an integer
     * @return an integer
     */
    int postOffice(vector<int>& A, int k) {
        const int n = A.size();
        if (A.empty() || k >= n) {
            return 0;
        }

        sort(A.begin(), A.end());  // Time:  O(nlogn)

        // Precompute cost.
        // Time:  O(n^3)
        // Space: O(n^2)
        vector<vector<int>> cost(A.size() + 1, vector<int>(A.size() + 1, 0));
        computeMinCost(A, &cost);

        // DP of sum.
        // Time:  O(k * n^2)
        // Space: O(k * n)
        // sum[i][j] denotes the smallest sum of
        // picking i post offices for the first j houses.
        vector<vector<int>> sum(k + 1, vector<int>(A.size() + 1, INT_MAX));
        sum[0][0] = 0;
        for (int i = 1; i <= k; ++i) {
            for (int j = 0; j < n; ++j) {
                if (sum[i - 1][j] != INT_MAX) {
                    for (int r = 1; j + r <= n; ++r) {
                       sum[i][j + r] = min(sum[i][j + r],
                                           sum[i - 1][j] + cost[j + 1][j + r]);
                    }
                }
            }
        }
        return sum[k][n];
    }

    void computeMinCost(const vector<int>& A, vector<vector<int>> *cost) {
        // Min cost of building a post office between house (i, j).
        // This post office must be in median position.
        const int n = A.size();
        for (int i = 0; i < n; ++i) {
            for (int j = i; j < n; ++j) {
                int mid = (i + j) / 2;
                for (int r = i; r <= mid; ++r) {
                    (*cost)[i + 1][j + 1] += A[mid] - A[r];
                }
                for (int r = mid + 1; r <= j; ++r) {
                    (*cost)[i + 1][j + 1] += A[r] - A[mid];
                }
            }
        }
    }
};
<commit_msg>Update post-office-problem.cpp<commit_after>// Time:  O(n^3)
// Space: O(n^2)

class Solution {
public:
    /**
     * @param A an integer array
     * @param k an integer
     * @return an integer
     */
    int postOffice(vector<int>& A, int k) {
        const int n = A.size();
        if (A.empty() || k >= n) {
            return 0;
        }

        sort(A.begin(), A.end());  // Time:  O(nlogn)

        // Precompute cost.
        // Time:  O(n^3)
        // Space: O(n^2)
        vector<vector<int>> cost(A.size() + 1, vector<int>(A.size() + 1, 0));
        computeMinCost(A, &cost);

        // DP of sum.
        // Time:  O(k * n^2)
        // Space: O(n)
        // sum[i][j] denotes the smallest sum of
        // picking i post offices for the first j houses.
        vector<vector<int>> sum(2, vector<int>(A.size() + 1, INT_MAX));
        sum[0][0] = 0;
        for (int i = 1; i <= k; ++i) {
            for (int j = 0; j <= n; ++j) {
                // sum[i % 2][j] = INT_MAX;
                for (int r = 1; r <= j; ++r) {
                    if (sum[(i - 1) % 2][j - r] != INT_MAX) {
                        sum[i % 2][j] = min(sum[i % 2][j],
                                            sum[(i - 1) % 2][j - r] +
                                            cost[j - r + 1][j]);
                    }
                }
            }
        }
        return sum[k % 2][n];
    }

    void computeMinCost(const vector<int>& A, vector<vector<int>> *cost) {
        // Min cost of building a post office between house (i, j).
        // This post office must be in median position.
        const int n = A.size();
        for (int i = 0; i < n; ++i) {
            for (int j = i; j < n; ++j) {
                int mid = (i + j) / 2;
                for (int r = i; r <= mid; ++r) {
                    (*cost)[i + 1][j + 1] += A[mid] - A[r];
                }
                for (int r = mid + 1; r <= j; ++r) {
                    (*cost)[i + 1][j + 1] += A[r] - A[mid];
                }
            }
        }
    }
};

// Time:  O(n^3)
// Space: O(n^2)
class Solution2 {
public:
    /**
     * @param A an integer array
     * @param k an integer
     * @return an integer
     */
    int postOffice(vector<int>& A, int k) {
        const int n = A.size();
        if (A.empty() || k >= n) {
            return 0;
        }

        sort(A.begin(), A.end());  // Time:  O(nlogn)

        // Precompute cost.
        // Time:  O(n^3)
        // Space: O(n^2)
        vector<vector<int>> cost(A.size() + 1, vector<int>(A.size() + 1, 0));
        computeMinCost(A, &cost);

        // DP of sum.
        // Time:  O(k * n^2)
        // Space: O(k * n)
        // sum[i][j] denotes the smallest sum of
        // picking i post offices for the first j houses.
        vector<vector<int>> sum(k + 1, vector<int>(A.size() + 1, INT_MAX));
        sum[0][0] = 0;
        for (int i = 1; i <= k; ++i) {
            for (int j = 0; j < n; ++j) {
                if (sum[i - 1][j] != INT_MAX) {
                    for (int r = 1; j + r <= n; ++r) {
                       sum[i][j + r] = min(sum[i][j + r],
                                           sum[i - 1][j] + cost[j + 1][j + r]);
                    }
                }
            }
        }
        return sum[k][n];
    }

    void computeMinCost(const vector<int>& A, vector<vector<int>> *cost) {
        // Min cost of building a post office between house (i, j).
        // This post office must be in median position.
        const int n = A.size();
        for (int i = 0; i < n; ++i) {
            for (int j = i; j < n; ++j) {
                int mid = (i + j) / 2;
                for (int r = i; r <= mid; ++r) {
                    (*cost)[i + 1][j + 1] += A[mid] - A[r];
                }
                for (int r = mid + 1; r <= j; ++r) {
                    (*cost)[i + 1][j + 1] += A[r] - A[mid];
                }
            }
        }
    }
};
<|endoftext|>


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

  Program:   Visualization Library
  Module:    GeomF.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#include "GeomF.hh"

// Description:
// Construct with all types of clipping turned off.
vlGeometryFilter::vlGeometryFilter()
{
  this->PointMinimum = 0;
  this->PointMaximum = LARGE_INTEGER;

  this->CellMinimum = 0;
  this->CellMaximum = LARGE_INTEGER;

  this->Extent[0] = -LARGE_FLOAT;
  this->Extent[1] = LARGE_FLOAT;
  this->Extent[2] = -LARGE_FLOAT;
  this->Extent[3] = LARGE_FLOAT;
  this->Extent[4] = -LARGE_FLOAT;
  this->Extent[5] = LARGE_FLOAT;

  this->PointClipping = 0;
  this->CellClipping = 0;
  this->ExtentClipping = 0;
}

void vlGeometryFilter::SetExtent(float xMin, float xMax, float yMin,
                                     float yMax, float zMin, float zMax)
{
  float extent[6];

  extent[0] = xMin;
  extent[1] = xMax;
  extent[2] = yMin;
  extent[3] = yMax;
  extent[4] = zMin;
  extent[5] = zMax;

  this->SetExtent(extent);
}

// Description:
// Specify a (xmin,xmax, ymin,ymax, zmin,zmax) bounding box to clip data.
void vlGeometryFilter::SetExtent(float *extent)
{
  int i;

  if ( extent[0] != this->Extent[0] || extent[1] != this->Extent[1] ||
  extent[2] != this->Extent[2] || extent[3] != this->Extent[3] ||
  extent[4] != this->Extent[4] || extent[5] != this->Extent[5] )
    {
    this->Modified();
    for (i=0; i<3; i++)
      {
      if ( extent[2*i] < 0 ) extent[2*i] = 0;
      if ( extent[2*i+1] < extent[2*i] ) extent[2*i+1] = extent[2*i];
      this->Extent[2*i] = extent[2*i];
      this->Extent[2*i+1] = extent[2*i+1];
      }
    }
}

void vlGeometryFilter::Execute()
{
  int cellId, i, j;
  int numPts=this->Input->GetNumberOfPoints();
  int numCells=this->Input->GetNumberOfCells();
  char *cellVis;
  vlCell *cell, *face;
  float *x;
  vlIdList *ptIds;
  static vlIdList cellIds(MAX_CELL_SIZE);
  vlFloatPoints *newPts;
  int ptId;
  int npts, pts[MAX_CELL_SIZE];
  vlPointData *pd = this->Input->GetPointData();
  int allVisible;

  this->Initialize();

  if ( (!this->CellClipping) && (!this->PointClipping) &&
  (!this->ExtentClipping) )
    {
    allVisible = 1;
    cellVis = NULL;
    }
  else
    {
    allVisible = 0;
    cellVis = new char[numCells];
    }
//
// Mark cells as being visible or not
//
  if ( ! allVisible )
    {
    for(cellId=0; cellId < numCells; cellId++)
      {
      if ( this->CellClipping && cellId < this->CellMinimum ||
      cellId > this->CellMaximum )
        {
        cellVis[cellId] = 0;
        }
      else
        {
        cell = this->Input->GetCell(cellId);
        ptIds = cell->GetPointIds();
        for (i=0; i < ptIds->GetNumberOfIds(); i++)
          {
          ptId = ptIds->GetId(i);
          x = this->Input->GetPoint(ptId);

          if ( (this->PointClipping && (ptId < this->PointMinimum ||
          ptId > this->PointMaximum) ) &&
          (this->ExtentClipping &&
          (x[0] < this->Extent[0] || x[0] > this->Extent[1] ||
          x[1] < this->Extent[2] || x[1] > this->Extent[3] ||
          x[2] < this->Extent[4] || x[2] > this->Extent[5] )) )
            {
            cellVis[cellId] = 0;
            break;
            }
          }
        if ( i >= ptIds->GetNumberOfIds() ) cellVis[cellId] = 1;
        }
      }
    }
//
// Allocate
//
  newPts = new vlFloatPoints(numPts,numPts/2);
  this->Allocate(4*numCells,numCells/2);
  this->PointData.CopyAllocate(pd,numPts,numPts/2);
//
// Traverse cells to extract geometry
//
  for(cellId=0; cellId < numCells; cellId++)
    {
    if ( allVisible || cellVis[cellId] )
      {
      cell = this->Input->GetCell(cellId);
      switch (cell->GetCellDimension())
        {
        // create new points and then cell
        case 0: case 1: case 2:

          npts = cell->GetNumberOfPoints();
          for ( i=0; i < npts; i++)
            {
            ptId = cell->GetPointId(i);
            x = this->Input->GetPoint(ptId);
            pts[i] = newPts->InsertNextPoint(x);
            this->PointData.CopyData(pd,ptId,pts[i]);
            }
          this->InsertNextCell(cell->GetCellType(), npts, pts);
          break;

        case 3:
          for (j=0; j < cell->GetNumberOfFaces(); j++)
            {
            face = cell->GetFace(j);
            this->Input->GetCellNeighbors(cellId, face->PointIds, cellIds);
            if ( cellIds.GetNumberOfIds() <= 0 ||
            (!allVisible && !cellVis[cellIds.GetId(0)]) )
              {
              npts = face->GetNumberOfPoints();
              for ( i=0; i < npts; i++)
                {
                ptId = cell->GetPointId(i);
                x = this->Input->GetPoint(ptId);
                pts[i] = newPts->InsertNextPoint(x);
                this->PointData.CopyData(pd,ptId,pts[i]);
                }
              this->InsertNextCell(face->GetCellType(), npts, pts);
              }
            }
          break;

        } //switch
      } //if visible
    } //for all cells
//
// Update ourselves
//
  this->SetPoints(newPts);
  this->Squeeze();

  if ( cellVis ) delete [] cellVis;

}

void vlGeometryFilter::PrintSelf(ostream& os, vlIndent indent)
{
  vlDataSetToPolyFilter::PrintSelf(os,indent);

  os << indent << "Point Minimum : " << this->PointMinimum << "\n";
  os << indent << "Point Maximum : " << this->PointMaximum << "\n";

  os << indent << "Cell Minimum : " << this->CellMinimum << "\n";
  os << indent << "Cell Maximum : " << this->CellMaximum << "\n";

  os << indent << "Extent: ("
     << this->Extent[0] << ", " << this->Extent[1] << ")\n("
     << this->Extent[2] << ", " << this->Extent[3] << ")\n("
     << this->Extent[4] << ", " << this->Extent[5] << ")\n";

  os << indent << "PointClipping: " << (this->PointClipping ? "On\n" : "Off\n");
  os << indent << "CellClipping: " << (this->CellClipping ? "On\n" : "Off\n");
  os << indent << "ExtentClipping: " << (this->ExtentClipping ? "On\n" : "Off\n");

}

<commit_msg>ERR: Fixed print method.<commit_after>/*=========================================================================

  Program:   Visualization Library
  Module:    GeomF.cc
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

This file is part of the Visualization Library. No part of this file
or its contents may be copied, reproduced or altered in any way
without the express written consent of the authors.

Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen 1993, 1994

=========================================================================*/
#include "GeomF.hh"

// Description:
// Construct with all types of clipping turned off.
vlGeometryFilter::vlGeometryFilter()
{
  this->PointMinimum = 0;
  this->PointMaximum = LARGE_INTEGER;

  this->CellMinimum = 0;
  this->CellMaximum = LARGE_INTEGER;

  this->Extent[0] = -LARGE_FLOAT;
  this->Extent[1] = LARGE_FLOAT;
  this->Extent[2] = -LARGE_FLOAT;
  this->Extent[3] = LARGE_FLOAT;
  this->Extent[4] = -LARGE_FLOAT;
  this->Extent[5] = LARGE_FLOAT;

  this->PointClipping = 0;
  this->CellClipping = 0;
  this->ExtentClipping = 0;
}

void vlGeometryFilter::SetExtent(float xMin, float xMax, float yMin,
                                     float yMax, float zMin, float zMax)
{
  float extent[6];

  extent[0] = xMin;
  extent[1] = xMax;
  extent[2] = yMin;
  extent[3] = yMax;
  extent[4] = zMin;
  extent[5] = zMax;

  this->SetExtent(extent);
}

// Description:
// Specify a (xmin,xmax, ymin,ymax, zmin,zmax) bounding box to clip data.
void vlGeometryFilter::SetExtent(float *extent)
{
  int i;

  if ( extent[0] != this->Extent[0] || extent[1] != this->Extent[1] ||
  extent[2] != this->Extent[2] || extent[3] != this->Extent[3] ||
  extent[4] != this->Extent[4] || extent[5] != this->Extent[5] )
    {
    this->Modified();
    for (i=0; i<3; i++)
      {
      if ( extent[2*i] < 0 ) extent[2*i] = 0;
      if ( extent[2*i+1] < extent[2*i] ) extent[2*i+1] = extent[2*i];
      this->Extent[2*i] = extent[2*i];
      this->Extent[2*i+1] = extent[2*i+1];
      }
    }
}

void vlGeometryFilter::Execute()
{
  int cellId, i, j;
  int numPts=this->Input->GetNumberOfPoints();
  int numCells=this->Input->GetNumberOfCells();
  char *cellVis;
  vlCell *cell, *face;
  float *x;
  vlIdList *ptIds;
  static vlIdList cellIds(MAX_CELL_SIZE);
  vlFloatPoints *newPts;
  int ptId;
  int npts, pts[MAX_CELL_SIZE];
  vlPointData *pd = this->Input->GetPointData();
  int allVisible;

  this->Initialize();

  if ( (!this->CellClipping) && (!this->PointClipping) &&
  (!this->ExtentClipping) )
    {
    allVisible = 1;
    cellVis = NULL;
    }
  else
    {
    allVisible = 0;
    cellVis = new char[numCells];
    }
//
// Mark cells as being visible or not
//
  if ( ! allVisible )
    {
    for(cellId=0; cellId < numCells; cellId++)
      {
      if ( this->CellClipping && cellId < this->CellMinimum ||
      cellId > this->CellMaximum )
        {
        cellVis[cellId] = 0;
        }
      else
        {
        cell = this->Input->GetCell(cellId);
        ptIds = cell->GetPointIds();
        for (i=0; i < ptIds->GetNumberOfIds(); i++)
          {
          ptId = ptIds->GetId(i);
          x = this->Input->GetPoint(ptId);

          if ( (this->PointClipping && (ptId < this->PointMinimum ||
          ptId > this->PointMaximum) ) &&
          (this->ExtentClipping &&
          (x[0] < this->Extent[0] || x[0] > this->Extent[1] ||
          x[1] < this->Extent[2] || x[1] > this->Extent[3] ||
          x[2] < this->Extent[4] || x[2] > this->Extent[5] )) )
            {
            cellVis[cellId] = 0;
            break;
            }
          }
        if ( i >= ptIds->GetNumberOfIds() ) cellVis[cellId] = 1;
        }
      }
    }
//
// Allocate
//
  newPts = new vlFloatPoints(numPts,numPts/2);
  this->Allocate(4*numCells,numCells/2);
  this->PointData.CopyAllocate(pd,numPts,numPts/2);
//
// Traverse cells to extract geometry
//
  for(cellId=0; cellId < numCells; cellId++)
    {
    if ( allVisible || cellVis[cellId] )
      {
      cell = this->Input->GetCell(cellId);
      switch (cell->GetCellDimension())
        {
        // create new points and then cell
        case 0: case 1: case 2:

          npts = cell->GetNumberOfPoints();
          for ( i=0; i < npts; i++)
            {
            ptId = cell->GetPointId(i);
            x = this->Input->GetPoint(ptId);
            pts[i] = newPts->InsertNextPoint(x);
            this->PointData.CopyData(pd,ptId,pts[i]);
            }
          this->InsertNextCell(cell->GetCellType(), npts, pts);
          break;

        case 3:
          for (j=0; j < cell->GetNumberOfFaces(); j++)
            {
            face = cell->GetFace(j);
            this->Input->GetCellNeighbors(cellId, face->PointIds, cellIds);
            if ( cellIds.GetNumberOfIds() <= 0 ||
            (!allVisible && !cellVis[cellIds.GetId(0)]) )
              {
              npts = face->GetNumberOfPoints();
              for ( i=0; i < npts; i++)
                {
                ptId = cell->GetPointId(i);
                x = this->Input->GetPoint(ptId);
                pts[i] = newPts->InsertNextPoint(x);
                this->PointData.CopyData(pd,ptId,pts[i]);
                }
              this->InsertNextCell(face->GetCellType(), npts, pts);
              }
            }
          break;

        } //switch
      } //if visible
    } //for all cells
//
// Update ourselves
//
  this->SetPoints(newPts);
  this->Squeeze();

  if ( cellVis ) delete [] cellVis;

}

void vlGeometryFilter::PrintSelf(ostream& os, vlIndent indent)
{
  vlDataSetToPolyFilter::PrintSelf(os,indent);

  os << indent << "Point Minimum : " << this->PointMinimum << "\n";
  os << indent << "Point Maximum : " << this->PointMaximum << "\n";

  os << indent << "Cell Minimum : " << this->CellMinimum << "\n";
  os << indent << "Cell Maximum : " << this->CellMaximum << "\n";

  os << indent << "Extent: \n";
  os << indent << "  Xmin,Xmax: (" << this->Extent[0] << ", " << this->Extent[1] << ")\n";
  os << indent << "  Ymin,Ymax: (" << this->Extent[2] << ", " << this->Extent[3] << ")\n";
  os << indent << "  Zmin,Zmax: (" << this->Extent[4] << ", " << this->Extent[5] << ")\n";

  os << indent << "PointClipping: " << (this->PointClipping ? "On\n" : "Off\n");
  os << indent << "CellClipping: " << (this->CellClipping ? "On\n" : "Off\n");
  os << indent << "ExtentClipping: " << (this->ExtentClipping ? "On\n" : "Off\n");

}

<|endoftext|>


<commit_before>#include "file_data.hpp"

#include "../reader.hpp" // For Reader exceptions.
#include "../writer.hpp" // For Writer exceptions.

#include "../../base/exception.hpp"
#include "../../base/logging.hpp"

#include "../../base/start_mem_debug.hpp"

namespace my {

FileData::FileData(string const & fileName, Op op)
    : m_FileName(fileName), m_Op(op)
{
  char const * const modes [] = {"rb", "wb", "r+b", "ab"};
#ifdef OMIM_OS_BADA
  result error = m_File.Construct(fileName.c_str(), modes[op]);
  if (error == E_SUCCESS)
    return;
#else
  m_File = fopen(fileName.c_str(), modes[op]);
  int error = m_File ? ferror(m_File) : 0;
  if (m_File && !error)
    return;
  if (op == OP_WRITE_EXISTING)
  {
    // Special case, since "r+b" fails if file doesn't exist.
    if (m_File)
      fclose(m_File);
    m_File = fopen(fileName.c_str(), "wb");
    error = m_File ? ferror(m_File) : 0;
  }
  if (m_File && !error)
    return;
#endif
  // if we're here - something bad is happened
  if (m_Op)
    MYTHROW(Writer::OpenException, (fileName, error));
  else
    MYTHROW(Reader::OpenException, (fileName, error));
}

FileData::~FileData()
{
#ifndef OMIM_OS_BADA
  if (int error = fclose(m_File))
  {
    LOG(LWARNING, ("Error closing file", m_FileName, m_Op, error));
  }
#endif
}

uint64_t FileData::Size() const
{
#ifdef OMIM_OS_BADA
  Osp::Io::FileAttributes attr;
  result error = Osp::Io::File::GetAttributes(m_FileName.c_str(), attr);
  if (IsFailed(error))
    MYTHROW(Reader::OpenException, (m_FileName, m_Op, error));
  return attr.GetFileSize();
#else
  uint64_t const pos = Pos();
  fseek64(m_File, 0, SEEK_END);
  if (int error = ferror(m_File))
    MYTHROW(Reader::OpenException, (m_FileName, m_Op, error));
  uint64_t size = ftell64(m_File);
  if (int error = ferror(m_File))
    MYTHROW(Reader::OpenException, (m_FileName, m_Op, error));
  fseek64(m_File, pos, SEEK_SET);
  if (int error = ferror(m_File))
    MYTHROW(Writer::SeekException, (m_FileName, m_Op, error, pos));
  return size;
#endif
}

void FileData::Read(uint64_t pos, void * p, size_t size)
{
#ifdef OMIM_OS_BADA
  result error = m_File.Seek(Osp::Io::FILESEEKPOSITION_BEGIN, pos);
  if (IsFailed(error))
    MYTHROW(Reader::ReadException, (error, pos));
  int bytesRead = m_File.Read(p, size);
  error = GetLastResult();
  if (static_cast<size_t>(bytesRead) != size || IsFailed(error))
    MYTHROW(Reader::ReadException, (m_FileName, m_Op, error, bytesRead, pos, size));
#else
  fseek64(m_File, pos, SEEK_SET);
  if (int error = ferror(m_File))
      MYTHROW(Reader::ReadException, (error, pos));
  size_t bytesRead = fread(p, 1, size, m_File);
  int error = ferror(m_File);
  if (bytesRead != size || error)
    MYTHROW(Reader::ReadException, (m_FileName, m_Op, error, bytesRead, pos, size));
#endif
}

uint64_t FileData::Pos() const
{
#ifdef OMIM_OS_BADA
  int pos = m_File.Tell();
  result error = GetLastResult();
  if (IsFailed(error))
    MYTHROW(Writer::PosException, (m_FileName, m_Op, error, pos));
  return pos;
#else
  uint64_t result = ftell64(m_File);
  if (int error = ferror(m_File))
    MYTHROW(Writer::PosException, (m_FileName, m_Op, error, result));
  return result;
#endif
}

void FileData::Seek(uint64_t pos)
{
  ASSERT_NOT_EQUAL(m_Op, OP_APPEND, (m_FileName, m_Op, pos));
#ifdef OMIM_OS_BADA
  result error = m_File.Seek(Osp::Io::FILESEEKPOSITION_BEGIN, pos);
  if (IsFailed(error))
    MYTHROW(Writer::SeekException, (m_FileName, m_Op, error, pos));
#else
  fseek64(m_File, pos, SEEK_SET);
  if (int error = ferror(m_File))
    MYTHROW(Writer::SeekException, (m_FileName, m_Op, error, pos));
#endif
}

void FileData::Write(void const * p, size_t size)
{
#ifdef OMIM_OS_BADA
  result error = m_File.Write(p, size);
  if (IsFailed(error))
    MYTHROW(Writer::WriteException, (m_FileName, m_Op, error, size));
#else
  size_t bytesWritten = fwrite(p, 1, size, m_File);
  int error = ferror(m_File);
  if (bytesWritten != size || error)
    MYTHROW(Writer::WriteException, (m_FileName, m_Op, error, bytesWritten, size));
#endif
}

void FileData::Flush()
{
#ifdef OMIM_OS_BADA
  result error = m_File.Flush();
  if (IsFailed(error))
    MYTHROW(Writer::WriteException, (m_FileName, m_Op, error));
#else
  fflush(m_File);
  if (int error = ferror(m_File))
    MYTHROW(Writer::WriteException, (m_FileName, m_Op, error));
#endif
}

void FileData::Truncate(uint64_t sz)
{
#ifdef OMIM_OS_WINDOWS
  _chsize(fileno(m_File), sz);
#else
  ftruncate(fileno(m_File), sz);
#endif
}

bool GetFileSize(string const & fName, uint64_t & sz)
{
  try
  {
    typedef my::FileData fdata_t;
    fdata_t f(fName, fdata_t::OP_READ);
    sz = f.Size();
    return true;
  }
  catch (RootException const &)
  {
    // supress all exceptions here
    return false;
  }
}

void DeleteFileX(string const & fName)
{
#ifdef OMIM_OS_BADA
  Osp::Io::File::Remove(fName.c_str());
#else

  // Erase file.
  if (0 != remove(fName.c_str()))
  {
    // additional check if file really was removed correctly
    FILE * f = fopen(fName.c_str(), "r");
    if (f)
    {
      fclose(f);
      LOG(LERROR, ("File exists but can't be deleted. Sharing violation?", fName));
    }
  }
#endif
}

bool RenameFileX(string const & fOld, string const & fNew)
{
#ifdef OMIM_OS_BADA
  return Osp::Io::File::Rename(fOld.c_str(), fNew.c_str());
#else
  return (0 == rename(fOld.c_str(), fNew.c_str()));
#endif
}

}
<commit_msg>[msvc] Compile error.<commit_after>#include "file_data.hpp"

#include "../reader.hpp" // For Reader exceptions.
#include "../writer.hpp" // For Writer exceptions.

#include "../../base/exception.hpp"
#include "../../base/logging.hpp"

#include "../../std/target_os.hpp"

#ifdef OMIM_OS_WINDOWS
#include <io.h>
#endif

#include "../../base/start_mem_debug.hpp"

namespace my {

FileData::FileData(string const & fileName, Op op)
    : m_FileName(fileName), m_Op(op)
{
  char const * const modes [] = {"rb", "wb", "r+b", "ab"};
#ifdef OMIM_OS_BADA
  result error = m_File.Construct(fileName.c_str(), modes[op]);
  if (error == E_SUCCESS)
    return;
#else
  m_File = fopen(fileName.c_str(), modes[op]);
  int error = m_File ? ferror(m_File) : 0;
  if (m_File && !error)
    return;
  if (op == OP_WRITE_EXISTING)
  {
    // Special case, since "r+b" fails if file doesn't exist.
    if (m_File)
      fclose(m_File);
    m_File = fopen(fileName.c_str(), "wb");
    error = m_File ? ferror(m_File) : 0;
  }
  if (m_File && !error)
    return;
#endif
  // if we're here - something bad is happened
  if (m_Op)
    MYTHROW(Writer::OpenException, (fileName, error));
  else
    MYTHROW(Reader::OpenException, (fileName, error));
}

FileData::~FileData()
{
#ifndef OMIM_OS_BADA
  if (int error = fclose(m_File))
  {
    LOG(LWARNING, ("Error closing file", m_FileName, m_Op, error));
  }
#endif
}

uint64_t FileData::Size() const
{
#ifdef OMIM_OS_BADA
  Osp::Io::FileAttributes attr;
  result error = Osp::Io::File::GetAttributes(m_FileName.c_str(), attr);
  if (IsFailed(error))
    MYTHROW(Reader::OpenException, (m_FileName, m_Op, error));
  return attr.GetFileSize();
#else
  uint64_t const pos = Pos();
  fseek64(m_File, 0, SEEK_END);
  if (int error = ferror(m_File))
    MYTHROW(Reader::OpenException, (m_FileName, m_Op, error));
  uint64_t size = ftell64(m_File);
  if (int error = ferror(m_File))
    MYTHROW(Reader::OpenException, (m_FileName, m_Op, error));
  fseek64(m_File, pos, SEEK_SET);
  if (int error = ferror(m_File))
    MYTHROW(Writer::SeekException, (m_FileName, m_Op, error, pos));
  return size;
#endif
}

void FileData::Read(uint64_t pos, void * p, size_t size)
{
#ifdef OMIM_OS_BADA
  result error = m_File.Seek(Osp::Io::FILESEEKPOSITION_BEGIN, pos);
  if (IsFailed(error))
    MYTHROW(Reader::ReadException, (error, pos));
  int bytesRead = m_File.Read(p, size);
  error = GetLastResult();
  if (static_cast<size_t>(bytesRead) != size || IsFailed(error))
    MYTHROW(Reader::ReadException, (m_FileName, m_Op, error, bytesRead, pos, size));
#else
  fseek64(m_File, pos, SEEK_SET);
  if (int error = ferror(m_File))
      MYTHROW(Reader::ReadException, (error, pos));
  size_t bytesRead = fread(p, 1, size, m_File);
  int error = ferror(m_File);
  if (bytesRead != size || error)
    MYTHROW(Reader::ReadException, (m_FileName, m_Op, error, bytesRead, pos, size));
#endif
}

uint64_t FileData::Pos() const
{
#ifdef OMIM_OS_BADA
  int pos = m_File.Tell();
  result error = GetLastResult();
  if (IsFailed(error))
    MYTHROW(Writer::PosException, (m_FileName, m_Op, error, pos));
  return pos;
#else
  uint64_t result = ftell64(m_File);
  if (int error = ferror(m_File))
    MYTHROW(Writer::PosException, (m_FileName, m_Op, error, result));
  return result;
#endif
}

void FileData::Seek(uint64_t pos)
{
  ASSERT_NOT_EQUAL(m_Op, OP_APPEND, (m_FileName, m_Op, pos));
#ifdef OMIM_OS_BADA
  result error = m_File.Seek(Osp::Io::FILESEEKPOSITION_BEGIN, pos);
  if (IsFailed(error))
    MYTHROW(Writer::SeekException, (m_FileName, m_Op, error, pos));
#else
  fseek64(m_File, pos, SEEK_SET);
  if (int error = ferror(m_File))
    MYTHROW(Writer::SeekException, (m_FileName, m_Op, error, pos));
#endif
}

void FileData::Write(void const * p, size_t size)
{
#ifdef OMIM_OS_BADA
  result error = m_File.Write(p, size);
  if (IsFailed(error))
    MYTHROW(Writer::WriteException, (m_FileName, m_Op, error, size));
#else
  size_t bytesWritten = fwrite(p, 1, size, m_File);
  int error = ferror(m_File);
  if (bytesWritten != size || error)
    MYTHROW(Writer::WriteException, (m_FileName, m_Op, error, bytesWritten, size));
#endif
}

void FileData::Flush()
{
#ifdef OMIM_OS_BADA
  result error = m_File.Flush();
  if (IsFailed(error))
    MYTHROW(Writer::WriteException, (m_FileName, m_Op, error));
#else
  fflush(m_File);
  if (int error = ferror(m_File))
    MYTHROW(Writer::WriteException, (m_FileName, m_Op, error));
#endif
}

void FileData::Truncate(uint64_t sz)
{
#ifdef OMIM_OS_WINDOWS
  _chsize(fileno(m_File), sz);
#else
  ftruncate(fileno(m_File), sz);
#endif
}

bool GetFileSize(string const & fName, uint64_t & sz)
{
  try
  {
    typedef my::FileData fdata_t;
    fdata_t f(fName, fdata_t::OP_READ);
    sz = f.Size();
    return true;
  }
  catch (RootException const &)
  {
    // supress all exceptions here
    return false;
  }
}

void DeleteFileX(string const & fName)
{
#ifdef OMIM_OS_BADA
  Osp::Io::File::Remove(fName.c_str());
#else

  // Erase file.
  if (0 != remove(fName.c_str()))
  {
    // additional check if file really was removed correctly
    FILE * f = fopen(fName.c_str(), "r");
    if (f)
    {
      fclose(f);
      LOG(LERROR, ("File exists but can't be deleted. Sharing violation?", fName));
    }
  }
#endif
}

bool RenameFileX(string const & fOld, string const & fNew)
{
#ifdef OMIM_OS_BADA
  return Osp::Io::File::Rename(fOld.c_str(), fNew.c_str());
#else
  return (0 == rename(fOld.c_str(), fNew.c_str()));
#endif
}

}
<|endoftext|>