<commit_before>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2013 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include "xenia/kernel/xmodule.h"

#include "xenia/base/byte_stream.h"
#include "xenia/base/string.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/user_module.h"

namespace xe {
namespace kernel {

XModule::XModule(KernelState* kernel_state, ModuleType module_type,
                 const std::string& path)
    : XObject(kernel_state, kTypeModule),
      module_type_(module_type),
      path_(path),
      processor_module_(nullptr),
      hmodule_ptr_(0) {
  name_ = NameFromPath(path);

  // Loader data (HMODULE)
  hmodule_ptr_ = memory()->SystemHeapAlloc(sizeof(X_LDR_DATA_TABLE_ENTRY));

  // Hijack the checksum field to store our kernel object handle.
  auto ldr_data =
      memory()->TranslateVirtual<X_LDR_DATA_TABLE_ENTRY*>(hmodule_ptr_);
  ldr_data->checksum = handle();
}

XModule::~XModule() {
  kernel_state_->UnregisterModule(this);

  // Destroy the loader data.
  memory()->SystemHeapFree(hmodule_ptr_);
}

bool XModule::Matches(const std::string& name) const {
  if (strcasecmp(xe::find_name_from_path(path_).c_str(), name.c_str()) == 0) {
    return true;
  }
  if (strcasecmp(name_.c_str(), name.c_str()) == 0) {
    return true;
  }
  if (strcasecmp(path_.c_str(), name.c_str()) == 0) {
    return true;
  }
  return false;
}

void XModule::OnLoad() { kernel_state_->RegisterModule(this); }

void XModule::OnUnload() { kernel_state_->UnregisterModule(this); }

X_STATUS XModule::GetSection(const char* name, uint32_t* out_section_data,
                             uint32_t* out_section_size) {
  return X_STATUS_UNSUCCESSFUL;
}

object_ref<XModule> XModule::GetFromHModule(KernelState* kernel_state,
                                            void* hmodule) {
  // Grab the object from our stashed kernel handle
  return kernel_state->object_table()->LookupObject<XModule>(
      GetHandleFromHModule(hmodule));
}

uint32_t XModule::GetHandleFromHModule(void* hmodule) {
  auto ldr_data = reinterpret_cast<X_LDR_DATA_TABLE_ENTRY*>(hmodule);
  return ldr_data->checksum;
}

std::string XModule::NameFromPath(std::string path) {
  std::string name;
  auto last_slash = path.find_last_of('/');
  if (last_slash == path.npos) {
    last_slash = path.find_last_of('\\');
  }
  if (last_slash == path.npos) {
    name = path;
  } else {
    name = path.substr(last_slash + 1);
  }
  auto dot = name.find_last_of('.');
  if (dot != name.npos) {
    name = name.substr(0, dot);
  }

  return name;
}

bool XModule::Save(ByteStream* stream) {
  stream->Write('XMOD');

  stream->Write(path_);
  stream->Write(hmodule_ptr_);

  if (!SaveObject(stream)) {
    return false;
  }

  return true;
}

object_ref<XModule> XModule::Restore(KernelState* kernel_state,
                                     ByteStream* stream) {
  if (stream->Read<uint32_t>() != 'XMOD') {
    return false;
  }

  auto path = stream->Read<std::string>();
  auto hmodule_ptr = stream->Read<uint32_t>();

  // Can only save user modules at the moment, so just redirect.
  // TODO: Find a way to call RestoreObject here before UserModule::Restore.
  auto module = UserModule::Restore(kernel_state, stream, path);

  module->hmodule_ptr_ = hmodule_ptr;
  return module;
}

}  // namespace kernel
}  // namespace xe
<commit_msg>XModule log on save/restore<commit_after>/**
 ******************************************************************************
 * Xenia : Xbox 360 Emulator Research Project                                 *
 ******************************************************************************
 * Copyright 2013 Ben Vanik. All rights reserved.                             *
 * Released under the BSD license - see LICENSE in the root for more details. *
 ******************************************************************************
 */

#include "xenia/kernel/xmodule.h"

#include "xenia/base/byte_stream.h"
#include "xenia/base/logging.h"
#include "xenia/base/string.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/user_module.h"

namespace xe {
namespace kernel {

XModule::XModule(KernelState* kernel_state, ModuleType module_type,
                 const std::string& path)
    : XObject(kernel_state, kTypeModule),
      module_type_(module_type),
      path_(path),
      processor_module_(nullptr),
      hmodule_ptr_(0) {
  name_ = NameFromPath(path);

  // Loader data (HMODULE)
  hmodule_ptr_ = memory()->SystemHeapAlloc(sizeof(X_LDR_DATA_TABLE_ENTRY));

  // Hijack the checksum field to store our kernel object handle.
  auto ldr_data =
      memory()->TranslateVirtual<X_LDR_DATA_TABLE_ENTRY*>(hmodule_ptr_);
  ldr_data->checksum = handle();
}

XModule::~XModule() {
  kernel_state_->UnregisterModule(this);

  // Destroy the loader data.
  memory()->SystemHeapFree(hmodule_ptr_);
}

bool XModule::Matches(const std::string& name) const {
  if (strcasecmp(xe::find_name_from_path(path_).c_str(), name.c_str()) == 0) {
    return true;
  }
  if (strcasecmp(name_.c_str(), name.c_str()) == 0) {
    return true;
  }
  if (strcasecmp(path_.c_str(), name.c_str()) == 0) {
    return true;
  }
  return false;
}

void XModule::OnLoad() { kernel_state_->RegisterModule(this); }

void XModule::OnUnload() { kernel_state_->UnregisterModule(this); }

X_STATUS XModule::GetSection(const char* name, uint32_t* out_section_data,
                             uint32_t* out_section_size) {
  return X_STATUS_UNSUCCESSFUL;
}

object_ref<XModule> XModule::GetFromHModule(KernelState* kernel_state,
                                            void* hmodule) {
  // Grab the object from our stashed kernel handle
  return kernel_state->object_table()->LookupObject<XModule>(
      GetHandleFromHModule(hmodule));
}

uint32_t XModule::GetHandleFromHModule(void* hmodule) {
  auto ldr_data = reinterpret_cast<X_LDR_DATA_TABLE_ENTRY*>(hmodule);
  return ldr_data->checksum;
}

std::string XModule::NameFromPath(std::string path) {
  std::string name;
  auto last_slash = path.find_last_of('/');
  if (last_slash == path.npos) {
    last_slash = path.find_last_of('\\');
  }
  if (last_slash == path.npos) {
    name = path;
  } else {
    name = path.substr(last_slash + 1);
  }
  auto dot = name.find_last_of('.');
  if (dot != name.npos) {
    name = name.substr(0, dot);
  }

  return name;
}

bool XModule::Save(ByteStream* stream) {
  XELOGD("XModule %.8X (%s)", handle(), path_.c_str());

  stream->Write('XMOD');

  stream->Write(path_);
  stream->Write(hmodule_ptr_);

  if (!SaveObject(stream)) {
    return false;
  }

  return true;
}

object_ref<XModule> XModule::Restore(KernelState* kernel_state,
                                     ByteStream* stream) {
  if (stream->Read<uint32_t>() != 'XMOD') {
    return false;
  }

  auto path = stream->Read<std::string>();
  auto hmodule_ptr = stream->Read<uint32_t>();

  // Can only save user modules at the moment, so just redirect.
  // TODO: Find a way to call RestoreObject here before UserModule::Restore.
  auto module = UserModule::Restore(kernel_state, stream, path);
  XELOGD("XModule %.8X (%s)", module->handle(), module->path_.c_str());

  module->hmodule_ptr_ = hmodule_ptr;
  return module;
}

}  // namespace kernel
}  // namespace xe
<|endoftext|>


<commit_before>#include <xzero/MonotonicClock.h>
#include <xzero/Duration.h>
#include <xzero/RuntimeError.h>
#include <xzero/defines.h>
#include <xzero/sysconfig.h>

#if defined(XZERO_OS_DARWIN)
#include <mach/mach.h>
#include <mach/mach_time.h>
#endif

namespace xzero {

#if defined(XZERO_OS_DARWIN)
mach_timebase_info_data_t timebaseInfo;

XZERO_INIT static void tbi_initialize() {
  mach_timebase_info(&timebaseInfo);
}
#endif

MonotonicTime MonotonicClock::now() {
#if defined(HAVE_CLOCK_GETTIME) // POSIX realtime API
  timespec ts;
  int rv = clock_gettime(CLOCK_MONOTONIC, &ts);

  if (rv < 0)
    RAISE_ERRNO(errno);

  uint64_t nanos =
      Duration::fromSeconds(ts.tv_sec).microseconds() * 1000 +
      ts.tv_nsec;

  return MonotonicTime(nanos);
#elif defined(XZERO_OS_DARWIN)
  uint64_t machTimeUnits = mach_absolute_time();
  uint64_t nanos = machTimeUnits * timebaseInfo.numer / timebaseInfo.denom;

  return MonotonicTime(nanos);
#else
  // TODO
  #error "MonotonicClock: Your platform is not implemented."
#endif
}

} // namespace xzero
<commit_msg>[xzero] MonotonicClock: make me compile under ubuntu:12.04 (docker)<commit_after>#include <xzero/MonotonicClock.h>
#include <xzero/Duration.h>
#include <xzero/RuntimeError.h>
#include <xzero/defines.h>
#include <xzero/sysconfig.h>

#if defined(XZERO_OS_DARWIN)
#include <mach/mach.h>
#include <mach/mach_time.h>
#endif

namespace xzero {

#if defined(XZERO_OS_DARWIN)
mach_timebase_info_data_t timebaseInfo;

XZERO_INIT static void tbi_initialize() {
  mach_timebase_info(&timebaseInfo);
}
#endif

MonotonicTime MonotonicClock::now() {
#if defined(XZERO_OS_DARWIN)
  uint64_t machTimeUnits = mach_absolute_time();
  uint64_t nanos = machTimeUnits * timebaseInfo.numer / timebaseInfo.denom;

  return MonotonicTime(nanos);
#else
  // FIXME: doesn't work inside docker ubuntu:12.04
  // => defined(HAVE_CLOCK_GETTIME) // POSIX realtime API

  timespec ts;
  int rv = clock_gettime(CLOCK_MONOTONIC, &ts);

  if (rv < 0)
    RAISE_ERRNO(errno);

  uint64_t nanos =
      Duration::fromSeconds(ts.tv_sec).microseconds() * 1000 +
      ts.tv_nsec;

  return MonotonicTime(nanos);
#endif
}

} // namespace xzero
<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_FUN_MEAN_HPP
#define STAN_MATH_PRIM_FUN_MEAN_HPP

#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <vector>

namespace stan {
namespace math {

/**
 * Returns the sample mean (i.e., average) of the coefficients
 * in the specified standard vector.
 *
 * @tparam T type of elements in the vector
 * @param v Specified vector.
 * @return Sample mean of vector coefficients.
 * @throws std::domain_error if the size of the vector is less
 * than 1.
 */
template <typename StdVec, require_std_vector_t<StdVec>* = nullptr,
          require_not_vt_var<StdVec>* = nullptr>
inline value_type_t<StdVec> mean(StdVec&& v) {
  using vec_value = value_type_t<StdVec>;
  check_nonzero_size("mean", "v", v);
  Eigen::Map<const Eigen::Matrix<vec_value, Eigen::Dynamic, 1>> m(&v[0],
                                                                  v.size());
  return m.mean();
}

/**
 * Returns the sample mean (i.e., average) of the coefficients
 * in the specified vector, row vector, or matrix.
 *
 * @tparam T type of elements in the matrix
 * @tparam R number of rows, can be Eigen::Dynamic
 * @tparam C number of columns, can be Eigen::Dynamic
 *
 * @param m Specified vector, row vector, or matrix.
 * @return Sample mean of vector coefficients.
 */
template <typename EigMat, require_eigen_t<EigMat>* = nullptr,
          require_not_vt_var<EigMat>* = nullptr>
inline value_type_t<EigMat> mean(EigMat&& m) {
  check_nonzero_size("mean", "m", m);
  return m.mean();
}

}  // namespace math
}  // namespace stan

#endif
<commit_msg>Fix sfinae for prim mean to accept var<commit_after>#ifndef STAN_MATH_PRIM_FUN_MEAN_HPP
#define STAN_MATH_PRIM_FUN_MEAN_HPP

#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/Eigen.hpp>
#include <vector>

namespace stan {
namespace math {

/**
 * Returns the sample mean (i.e., average) of the coefficients
 * in the specified standard vector.
 *
 * @tparam T type of elements in the vector
 * @param v Specified vector.
 * @return Sample mean of vector coefficients.
 * @throws std::domain_error if the size of the vector is less
 * than 1.
 */
template <typename StdVec, require_std_vector_t<StdVec>* = nullptr>
inline value_type_t<StdVec> mean(StdVec&& v) {
  using vec_value = value_type_t<StdVec>;
  check_nonzero_size("mean", "v", v);
  Eigen::Map<const Eigen::Matrix<vec_value, Eigen::Dynamic, 1>> m(&v[0],
                                                                  v.size());
  return m.mean();
}

/**
 * Returns the sample mean (i.e., average) of the coefficients
 * in the specified vector, row vector, or matrix.
 *
 * @tparam T type of elements in the matrix
 * @tparam R number of rows, can be Eigen::Dynamic
 * @tparam C number of columns, can be Eigen::Dynamic
 *
 * @param m Specified vector, row vector, or matrix.
 * @return Sample mean of vector coefficients.
 */
template <typename EigMat, require_eigen_t<EigMat>* = nullptr>
inline value_type_t<EigMat> mean(EigMat&& m) {
  check_nonzero_size("mean", "m", m);
  return m.mean();
}

}  // namespace math
}  // namespace stan

#endif
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/**
  \file    AbstrRenderer.cpp
  \author    Jens Krueger
        SCI Institute
        University of Utah
  \date    August 2008
*/

#include "AbstrRenderer.h"
#include "../Controller/MasterController.h"

using namespace std;

AbstrRenderer::AbstrRenderer(MasterController* pMasterController) :
  m_pMasterController(pMasterController),
  m_bRedraw(true),
  m_bCompleteRedraw(true),
  m_eRenderMode(RM_1DTRANS),
  m_eViewMode(VM_ONEBYTREE),
  m_bUseLigthing(true),
  m_pDataset(NULL),
  m_p1DTrans(NULL),
  m_p2DTrans(NULL),
  m_fSampleRateModifier(1.0f),
  m_fIsovalue(0.5f),
  m_vTextColor(1,1,1,1),
  m_fZoom(0.0f)
{
  m_vBackgroundColors[0] = FLOATVECTOR3(0,0,0);
  m_vBackgroundColors[1] = FLOATVECTOR3(0,0,0);

  m_eWindowMode[0] = WM_3D;
  m_eWindowMode[1] = WM_CORONAL;
  m_eWindowMode[2] = WM_AXIAL;
  m_eWindowMode[3] = WM_SAGITTAL;

  m_fSliceIndex[0] = 0.5f;
  m_fSliceIndex[1] = 0.5f;
  m_fSliceIndex[2] = 0.5f;
  m_fSliceIndex[3] = 0.5f;
}

bool AbstrRenderer::LoadDataset(const string& strFilename) {
  if (m_pMasterController == NULL) return false;

  if (m_pMasterController->IOMan() == NULL) {
    m_pMasterController->DebugOut()->Error("AbstrRenderer::LoadDataset","Cannont load dataset because m_pMasterController->IOMan() == NULL");
    return false;
  }

  m_pDataset = m_pMasterController->IOMan()->LoadDataset(strFilename,this);

  if (m_pDataset == NULL) {
    m_pMasterController->DebugOut()->Error("AbstrRenderer::LoadDataset","IOMan call to load dataset failed");
    return false;
  }

  m_pMasterController->DebugOut()->Message("AbstrRenderer::LoadDataset","Load successful, initializing renderer!");

  return true;
}

AbstrRenderer::~AbstrRenderer() {
  m_pMasterController->MemMan()->FreeDataset(m_pDataset, this);
  m_pMasterController->MemMan()->Free1DTrans(m_p1DTrans, this);
  m_pMasterController->MemMan()->Free2DTrans(m_p2DTrans, this);

}

void AbstrRenderer::SetRendermode(ERenderMode eRenderMode)
{
  if (m_eRenderMode != eRenderMode) {
    m_eRenderMode = eRenderMode;
    m_bRedraw = true;
    m_bCompleteRedraw = true;
  }
}

void AbstrRenderer::SetViewmode(EViewMode eViewMode)
{
  if (m_eViewMode != eViewMode) {
    m_eViewMode = eViewMode;
    m_bRedraw = true;
    m_bCompleteRedraw = true;
  }
}

void AbstrRenderer::SetWindowmode(unsigned int iWindowIndex, EWindowMode eWindowMode)
{
  if (m_eWindowMode[iWindowIndex] != eWindowMode) {
    m_eWindowMode[iWindowIndex] = eWindowMode;
    m_bRedraw = true;
    m_bCompleteRedraw = true;
    /// \todo only redraw the windows dependent on this change
  }
}

void AbstrRenderer::SetUseLigthing(bool bUseLigthing) {
  if (m_bUseLigthing != bUseLigthing) {
    m_bUseLigthing = bUseLigthing;
    m_bRedraw = true;
    m_bCompleteRedraw = true;
    /// \todo only redraw the windows dependent on this change
  }
}

void AbstrRenderer::Changed1DTrans() {
  if (m_eRenderMode != RM_1DTRANS) {
    m_pMasterController->DebugOut()->Message("AbstrRenderer::Changed1DTrans","not using the 1D transferfunction at the moment, ignoring message");
  } else {
    m_pMasterController->DebugOut()->Message("AbstrRenderer::Changed1DTrans","complete redraw scheduled");
    m_bRedraw = true;
    m_bCompleteRedraw = true;
  }
}

void AbstrRenderer::Changed2DTrans() {
  if (m_eRenderMode != RM_2DTRANS) {
    m_pMasterController->DebugOut()->Message("AbstrRenderer::Changed2DTrans","not using the 2D transferfunction at the moment, ignoring message");
  } else {
    m_pMasterController->DebugOut()->Message("AbstrRenderer::Changed2DTrans","complete redraw scheduled");
    m_bRedraw = true;
    m_bCompleteRedraw = true;
  }
}

void AbstrRenderer::SetSampleRateModifier(float fSampleRateModifier) {
  if(m_fSampleRateModifier != fSampleRateModifier) {
    m_fSampleRateModifier = fSampleRateModifier;
    m_bRedraw = true;
    m_bCompleteRedraw = true;
  }
}

void AbstrRenderer::SetIsoValue(float fIsovalue) {
  if(m_fIsovalue != fIsovalue) {
    m_fIsovalue = fIsovalue;
    m_bRedraw = true;
    m_bCompleteRedraw = true;
  }
}

void AbstrRenderer::Resize(const UINTVECTOR2& vWinSize) {
  m_ArcBall.SetWindowSize(vWinSize.x, vWinSize.y);
}

void AbstrRenderer::Click(UINTVECTOR2 vPosition) {
  m_ArcBall.Click(vPosition);
}

void AbstrRenderer::Release(UINTVECTOR2) {
  m_RestRot = m_Rot;
}

void AbstrRenderer::Drag(UINTVECTOR2 vPosition) {
  m_Rot = m_ArcBall.Drag(vPosition).ComputeRotation() * m_RestRot;
  m_bRedraw = true;
  m_bCompleteRedraw = true;
}

void AbstrRenderer::Zoom(int iZoom) {
  m_fZoom += float(iZoom)/1000.0f;
  m_bRedraw = true;
  m_bCompleteRedraw = true;
}<commit_msg><commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2008 Scientific Computing and Imaging Institute,
   University of Utah.

   Permission is hereby granted, free of charge, to any person obtaining a
   copy of this software and associated documentation files (the "Software"),
   to deal in the Software without restriction, including without limitation
   the rights to use, copy, modify, merge, publish, distribute, sublicense,
   and/or sell copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included
   in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
   OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
   THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
   DEALINGS IN THE SOFTWARE.
*/

/**
  \file    AbstrRenderer.cpp
  \author    Jens Krueger
        SCI Institute
        University of Utah
  \date    August 2008
*/

#include "AbstrRenderer.h"
#include "../Controller/MasterController.h"

using namespace std;

AbstrRenderer::AbstrRenderer(MasterController* pMasterController) :
  m_pMasterController(pMasterController),
  m_bRedraw(true),
  m_bCompleteRedraw(true),
  m_eRenderMode(RM_1DTRANS),
  m_eViewMode(VM_SINGLE),
  m_bUseLigthing(true),
  m_pDataset(NULL),
  m_p1DTrans(NULL),
  m_p2DTrans(NULL),
  m_fSampleRateModifier(1.0f),
  m_fIsovalue(0.5f),
  m_vTextColor(1,1,1,1),
  m_fZoom(0.0f)
{
  m_vBackgroundColors[0] = FLOATVECTOR3(0,0,0);
  m_vBackgroundColors[1] = FLOATVECTOR3(0,0,0);

  m_eWindowMode[0] = WM_3D;
  m_eWindowMode[1] = WM_CORONAL;
  m_eWindowMode[2] = WM_AXIAL;
  m_eWindowMode[3] = WM_SAGITTAL;

  m_fSliceIndex[0] = 0.5f;
  m_fSliceIndex[1] = 0.5f;
  m_fSliceIndex[2] = 0.5f;
  m_fSliceIndex[3] = 0.5f;
}

bool AbstrRenderer::LoadDataset(const string& strFilename) {
  if (m_pMasterController == NULL) return false;

  if (m_pMasterController->IOMan() == NULL) {
    m_pMasterController->DebugOut()->Error("AbstrRenderer::LoadDataset","Cannont load dataset because m_pMasterController->IOMan() == NULL");
    return false;
  }

  m_pDataset = m_pMasterController->IOMan()->LoadDataset(strFilename,this);

  if (m_pDataset == NULL) {
    m_pMasterController->DebugOut()->Error("AbstrRenderer::LoadDataset","IOMan call to load dataset failed");
    return false;
  }

  m_pMasterController->DebugOut()->Message("AbstrRenderer::LoadDataset","Load successful, initializing renderer!");

  return true;
}

AbstrRenderer::~AbstrRenderer() {
  m_pMasterController->MemMan()->FreeDataset(m_pDataset, this);
  m_pMasterController->MemMan()->Free1DTrans(m_p1DTrans, this);
  m_pMasterController->MemMan()->Free2DTrans(m_p2DTrans, this);

}

void AbstrRenderer::SetRendermode(ERenderMode eRenderMode)
{
  if (m_eRenderMode != eRenderMode) {
    m_eRenderMode = eRenderMode;
    m_bRedraw = true;
    m_bCompleteRedraw = true;
  }
}

void AbstrRenderer::SetViewmode(EViewMode eViewMode)
{
  if (m_eViewMode != eViewMode) {
    m_eViewMode = eViewMode;
    m_bRedraw = true;
    m_bCompleteRedraw = true;
  }
}

void AbstrRenderer::SetWindowmode(unsigned int iWindowIndex, EWindowMode eWindowMode)
{
  if (m_eWindowMode[iWindowIndex] != eWindowMode) {
    m_eWindowMode[iWindowIndex] = eWindowMode;
    m_bRedraw = true;
    m_bCompleteRedraw = true;
    /// \todo only redraw the windows dependent on this change
  }
}

void AbstrRenderer::SetUseLigthing(bool bUseLigthing) {
  if (m_bUseLigthing != bUseLigthing) {
    m_bUseLigthing = bUseLigthing;
    m_bRedraw = true;
    m_bCompleteRedraw = true;
    /// \todo only redraw the windows dependent on this change
  }
}

void AbstrRenderer::Changed1DTrans() {
  if (m_eRenderMode != RM_1DTRANS) {
    m_pMasterController->DebugOut()->Message("AbstrRenderer::Changed1DTrans","not using the 1D transferfunction at the moment, ignoring message");
  } else {
    m_pMasterController->DebugOut()->Message("AbstrRenderer::Changed1DTrans","complete redraw scheduled");
    m_bRedraw = true;
    m_bCompleteRedraw = true;
  }
}

void AbstrRenderer::Changed2DTrans() {
  if (m_eRenderMode != RM_2DTRANS) {
    m_pMasterController->DebugOut()->Message("AbstrRenderer::Changed2DTrans","not using the 2D transferfunction at the moment, ignoring message");
  } else {
    m_pMasterController->DebugOut()->Message("AbstrRenderer::Changed2DTrans","complete redraw scheduled");
    m_bRedraw = true;
    m_bCompleteRedraw = true;
  }
}

void AbstrRenderer::SetSampleRateModifier(float fSampleRateModifier) {
  if(m_fSampleRateModifier != fSampleRateModifier) {
    m_fSampleRateModifier = fSampleRateModifier;
    m_bRedraw = true;
    m_bCompleteRedraw = true;
  }
}

void AbstrRenderer::SetIsoValue(float fIsovalue) {
  if(m_fIsovalue != fIsovalue) {
    m_fIsovalue = fIsovalue;
    m_bRedraw = true;
    m_bCompleteRedraw = true;
  }
}

void AbstrRenderer::Resize(const UINTVECTOR2& vWinSize) {
  m_ArcBall.SetWindowSize(vWinSize.x, vWinSize.y);
}

void AbstrRenderer::Click(UINTVECTOR2 vPosition) {
  m_ArcBall.Click(vPosition);
}

void AbstrRenderer::Release(UINTVECTOR2) {
  m_RestRot = m_Rot;
}

void AbstrRenderer::Drag(UINTVECTOR2 vPosition) {
  m_Rot = m_ArcBall.Drag(vPosition).ComputeRotation() * m_RestRot;
  m_bRedraw = true;
  m_bCompleteRedraw = true;
}

void AbstrRenderer::Zoom(int iZoom) {
  m_fZoom += float(iZoom)/1000.0f;
  m_bRedraw = true;
  m_bCompleteRedraw = true;
}<|endoftext|>


<commit_before>/**
 * Madhav Datt - 14CS30015
 *
 * Software Engineering Lab - Assignment 3
 * Contains implementation of the Date Computations Functions
 *
 */

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdint>
#include <exception>

#include "date_comp.h"
#include "date.h"

/**
 * Check validity of (d, m, y) as a triplet
 */
bool is_valid_Date (uint32_t date, uint32_t month, uint32_t year)
{
    // Check validity of passed d and m values
    if (is_valid_Arg (date, month) == false)
        return false;

    // Check if date in month
    if (date > month_length (month, year))
        return false;

    return true;
}

/**
 * Check if d or m take invalid values
 */
bool is_valid_Arg (uint32_t date, uint32_t month)
{
    // date or month are out of bounds/take invalid values
    if (date > 32 || month > 12)
        return false;

    return true;
}

 /**
  * Check if y is a leap year
  */
bool is_leap_Year (uint32_t year)
{
    bool flag = false;

    // Leap year - divisible by 4 & if divisible by 100, then also by 400
    if (year % 100 == 0 && year % 400 == 0)
        flag = true;
    else if (year % 100 != 0 && year % 4 == 0)
        flag = true;

    return flag;
}

/**
 * Give length of month for given year
 * Consider leap years and February
 */
uint32_t month_length (uint32_t month, uint32_t year)
{
    // month_days[i] = number of days in ith month
    static const uint32_t month_days[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    uint32_t month_length = month_days[month];

    // Leap year and month is February then length = 29
    if (is_leap_Year (year) && month == 2)
        month_length = 29;

    return month_length;
}

/**
 * Give three letter name of month
 */
char* month_name (uint32_t month)
{
    // month_days[i] = three letter name of ith month
    static const char month_name[][4] = {"", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
    return month[i];
}

/**
 * Give number of weeks in year y
 * A week starts on Monday and ends on Sunday. Weeks are numbered in a year from 1 to 52/53.
 * Week 1 (W01) of a year starts contains the first Thursday of the year.
 */
int number_of_weeks (uint32_t year)
{
    // Last day of year (falls in last week)
    Date year_end (31, 12, year);

    // Find first Thursday of year
    Date year_start (1, 1, year);
    while ((WeekDay)year_start != 4)
        ++year_start;

    // Find start of Week 1 of year
    year_start = year_start + (-3);

    // Number of days between first week and end of year
    int num_days = year_end - year_start;

    // Return week number in which end of year falls
    return static_cast<int> (num_days / 7) + 1;
}

/**
 * Date formatter function
 * Accept date in specified format
 *
 * dateFormat:
 * 0: No date. This is valid for output only.
 * "d": single digit date in one digit, double digit date in two digits (7, 23)
 * "dd": all dates in two digits with single digit dates with leading 0 (07, 23)
 */
void formatter_date (const char* dateString, char* dateFormat) throw (format_error)
{
    if (strcmp (dateString, "d") == 0)
        dateFormat = new char[2];

    else if (strcmp (dateString, "dd") == 0)
        dateFormat = new char[3];

    else if (strcmp (dateString, "0") == 0)
        dateFormat = new char[2];

    else
        throw format_error ();

    strcpy (dateFormat, dateString);
}

/**
 * Month formatter function
 * Accept month in specified format
 *
 * monthFormat:
 * 0: each month in its full name (February, November). This is valid for output only.
 * "m": single digit month in one digit, double digit month in two digits (2, 11)
 * "mm": all months in two digits with single digit months with leading 0 (02, 11)
 * "mmm": each month with first three letters of its name (Feb, Nov). This is valid for output only.
 */
void formatter_month (const char* dateString, char* monthFormat) throw (format_error)
{

}

/**
 * Year formatter function
 * Accept year in specified format
 *
 * yearFormat:
 * 0: No year. This is valid for output only.
 * "yy": year in last two digits (1961 as 61, 2016 as 16)
 * "yyyy": year in four digits (1961 as 1961, 2016 as 2016)
 */
void formatter_year (const char* dateString, char* yearFormat) throw (format_error)
{

}
<commit_msg>add formatter functions<commit_after>/**
 * Madhav Datt - 14CS30015
 *
 * Software Engineering Lab - Assignment 3
 * Contains implementation of the Date Computations Functions
 *
 */

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdint>
#include <exception>

#include "date_comp.h"
#include "date.h"

/**
 * Check validity of (d, m, y) as a triplet
 */
bool is_valid_Date (uint32_t date, uint32_t month, uint32_t year)
{
    // Check validity of passed d and m values
    if (is_valid_Arg (date, month) == false)
        return false;

    // Check if date in month
    if (date > month_length (month, year))
        return false;

    return true;
}

/**
 * Check if d or m take invalid values
 */
bool is_valid_Arg (uint32_t date, uint32_t month)
{
    // date or month are out of bounds/take invalid values
    if (date > 32 || month > 12)
        return false;

    return true;
}

 /**
  * Check if y is a leap year
  */
bool is_leap_Year (uint32_t year)
{
    bool flag = false;

    // Leap year - divisible by 4 & if divisible by 100, then also by 400
    if (year % 100 == 0 && year % 400 == 0)
        flag = true;
    else if (year % 100 != 0 && year % 4 == 0)
        flag = true;

    return flag;
}

/**
 * Give length of month for given year
 * Consider leap years and February
 */
uint32_t month_length (uint32_t month, uint32_t year)
{
    // month_days[i] = number of days in ith month
    static const uint32_t month_days[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    uint32_t month_length = month_days[month];

    // Leap year and month is February then length = 29
    if (is_leap_Year (year) && month == 2)
        month_length = 29;

    return month_length;
}

/**
 * Give three letter name of month
 */
char* month_name (uint32_t month)
{
    // month_days[i] = three letter name of ith month
    static const char month_name[][4] = {"", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
    return month[i];
}

/**
 * Give number of weeks in year y
 * A week starts on Monday and ends on Sunday. Weeks are numbered in a year from 1 to 52/53.
 * Week 1 (W01) of a year starts contains the first Thursday of the year.
 */
int number_of_weeks (uint32_t year)
{
    // Last day of year (falls in last week)
    Date year_end (31, 12, year);

    // Find first Thursday of year
    Date year_start (1, 1, year);
    while ((WeekDay)year_start != 4)
        ++year_start;

    // Find start of Week 1 of year
    year_start = year_start + (-3);

    // Number of days between first week and end of year
    int num_days = year_end - year_start;

    // Return week number in which end of year falls
    return static_cast<int> (num_days / 7) + 1;
}

/**
 * Date formatter function
 * Accept date in specified format
 *
 * dateFormat:
 * 0: No date. This is valid for output only.
 * "d": single digit date in one digit, double digit date in two digits (7, 23)
 * "dd": all dates in two digits with single digit dates with leading 0 (07, 23)
 */
void formatter_date (const char* dateString, char* dateFormat) throw (format_error)
{
    // "d": single digit date in one digit, double digit date in two digits
    if (strcmp (dateString, "d") == 0)
        dateFormat = new char[2];

    // "dd": all dates in two digits with single digit dates with leading 0
    else if (strcmp (dateString, "dd") == 0)
        dateFormat = new char[3];

    // 0: No date
    else if (strcmp (dateString, "0") == 0)
        dateFormat = new char[2];

    // Incorrect format entered
    else
        throw format_error ();

    strcpy (dateFormat, dateString);
}

/**
 * Month formatter function
 * Accept month in specified format
 *
 * monthFormat:
 * 0: each month in its full name (February, November). This is valid for output only.
 * "m": single digit month in one digit, double digit month in two digits (2, 11)
 * "mm": all months in two digits with single digit months with leading 0 (02, 11)
 * "mmm": each month with first three letters of its name (Feb, Nov). This is valid for output only.
 */
void formatter_month (const char* dateString, char* monthFormat) throw (format_error)
{
    // "m": single digit month in one digit, double digit month in two digits
    if (strcmp (dateString, "m") == 0)
        monthFormat = new char[2];

    // "mm": all months in two digits with single digit months with leading 0
    else if (strcmp (dateString, "mm") == 0)
        monthFormat = new char[3];

    // "mmm": each month with first three letters of its name
    else if (strcmp (dateString, "mmm") == 0)
        monthFormat = new char[4];

    // 0: each month in its full name
    else if (strcmp (dateString, "0") == 0)
        monthFormat = new char[2];

    // Incorrect format entered
    else
        throw format_error ();

    strcpy (monthFormat, dateString);
}

/**
 * Year formatter function
 * Accept year in specified format
 *
 * yearFormat:
 * 0: No year. This is valid for output only.
 * "yy": year in last two digits (1961 as 61, 2016 as 16)
 * "yyyy": year in four digits (1961 as 1961, 2016 as 2016)
 */
void formatter_year (const char* dateString, char* yearFormat) throw (format_error)
{
    // "yy": year in last two digits
    if (strcmp (dateString, "yy") == 0)
        yearFormat = new char[3];

    // "yyyy": year in four digits
    else if (strcmp (dateString, "yyyy") == 0)
        yearFormat = new char[5];

    // 0: No year
    else if (strcmp (dateString, "0") == 0)
        yearFormat = new char[2];

    // Incorrect format entered
    else
        throw format_error ();

    strcpy (yearFormat, dateString);
}
<|endoftext|>


<commit_before>// Copyright (c) 2011, Christian Rorvik
// Distributed under the Simplified BSD License (See accompanying file LICENSE.txt)

#ifndef CRUNCH_BASE_DURATION_HPP
#define CRUNCH_BASE_DURATION_HPP

#include "crunch/base/stdint.hpp"

namespace Crunch {

/// Duration of time
/// Range: +/- 292 years
/// Resolution: 1 nanosecond
class Duration
{
public:
    static Duration Nanoseconds(int64 nanoseconds);
    static Duration Microseconds(int64 microseconds);
    static Duration Milliseconds(int64 milliseconds);
    static Duration Seconds(int64 seconds);
    static Duration Minutes(int32 minutes);
    static Duration Hours(int32 hours);
    static Duration Days(int32 days);

    static Duration const Zero;
    static Duration const PositiveInfinity;
    static Duration const NegativeInfinity;

    int64 GetTotalNanoseconds() const;
    int64 GetTotalMicroseconds() const;
    int64 GetTotalMilliseconds() const;
    int64 GetTotalSeconds() const;
    int32 GetTotalMinutes() const;
    int32 GetTotalHours() const;
    int32 GetTotalDays() const;

    bool IsNegative() const;

    bool operator == (Duration rhs) const;

    Duration& operator += (Duration rhs);
    Duration& operator -= (Duration rhs);

private:
    static int64 const NanosecondsPerMicrosecond = 1000ll;
    static int64 const NanosecondsPerMillisecond = 1000000ll;
    static int64 const NanosecondsPerSecond = 1000000000ll;
    static int64 const NanosecondsPerMinute = 60ll * NanosecondsPerSecond;
    static int64 const NanosecondsPerHour = 60ll * NanosecondsPerMinute;
    static int64 const NanosecondsPerDay = 24 * NanosecondsPerHour;

    Duration(int64 nanoseconds);

    int64 mNanoseconds;
};

inline Duration Duration::Nanoseconds(int64 nanoseconds)
{
    return Duration(nanoseconds);
}

inline Duration Duration::Microseconds(int64 microseconds)
{
    return Duration(microseconds * NanosecondsPerMicrosecond);
}

inline Duration Duration::Milliseconds(int64 milliseconds)
{
    return Duration(milliseconds * NanosecondsPerMillisecond);
}

inline Duration Duration::Seconds(int64 seconds)
{
    return Duration(seconds * NanosecondsPerSecond);
}

inline Duration Duration::Minutes(int32 minutes)
{
    return Duration(minutes * NanosecondsPerMinute);
}

inline Duration Duration::Hours(int32 hours)
{
    return Duration(hours * NanosecondsPerHour);
}

inline Duration Duration::Days(int32 days)
{
    return Duration(days * NanosecondsPerDay);
}

inline int64 Duration::GetTotalNanoseconds() const
{
    return mNanoseconds;
}

inline int64 Duration::GetTotalMicroseconds() const
{
    return mNanoseconds / NanosecondsPerMicrosecond;
}

inline int64 Duration::GetTotalMilliseconds() const
{
    return mNanoseconds / NanosecondsPerMillisecond;
}

inline int64 Duration::GetTotalSeconds() const
{
    return mNanoseconds / NanosecondsPerSecond;
}

inline int32 Duration::GetTotalMinutes() const
{
    return static_cast<int32>(mNanoseconds / NanosecondsPerMinute);
}

inline int32 Duration::GetTotalHours() const
{
    return static_cast<int32>(mNanoseconds / NanosecondsPerHour);
}

inline int32 Duration::GetTotalDays() const
{
    return static_cast<int32>(mNanoseconds / NanosecondsPerDay);
}

inline bool Duration::IsNegative() const
{
    return mNanoseconds < 0;
}

inline bool Duration::operator == (Duration rhs) const
{
    return mNanoseconds == rhs.mNanoseconds;
}

inline Duration& Duration::operator += (Duration rhs)
{
    mNanoseconds += rhs.mNanoseconds;
    return *this;
}

inline Duration& Duration::operator -= (Duration rhs)
{
    mNanoseconds -= rhs.mNanoseconds;
    return *this;
}

inline Duration operator + (Duration lhs, Duration rhs)
{
    return lhs += rhs;
}

inline Duration operator - (Duration lhs, Duration rhs)
{
    return lhs -= rhs;
}

}

#endif
<commit_msg>Added missing implementation of Duration::Duration()<commit_after>// Copyright (c) 2011, Christian Rorvik
// Distributed under the Simplified BSD License (See accompanying file LICENSE.txt)

#ifndef CRUNCH_BASE_DURATION_HPP
#define CRUNCH_BASE_DURATION_HPP

#include "crunch/base/stdint.hpp"

namespace Crunch {

/// Duration of time
/// Range: +/- 292 years
/// Resolution: 1 nanosecond
class Duration
{
public:
    static Duration Nanoseconds(int64 nanoseconds);
    static Duration Microseconds(int64 microseconds);
    static Duration Milliseconds(int64 milliseconds);
    static Duration Seconds(int64 seconds);
    static Duration Minutes(int32 minutes);
    static Duration Hours(int32 hours);
    static Duration Days(int32 days);

    static Duration const Zero;
    static Duration const PositiveInfinity;
    static Duration const NegativeInfinity;

    int64 GetTotalNanoseconds() const;
    int64 GetTotalMicroseconds() const;
    int64 GetTotalMilliseconds() const;
    int64 GetTotalSeconds() const;
    int32 GetTotalMinutes() const;
    int32 GetTotalHours() const;
    int32 GetTotalDays() const;

    bool IsNegative() const;

    bool operator == (Duration rhs) const;

    Duration& operator += (Duration rhs);
    Duration& operator -= (Duration rhs);

private:
    static int64 const NanosecondsPerMicrosecond = 1000ll;
    static int64 const NanosecondsPerMillisecond = 1000000ll;
    static int64 const NanosecondsPerSecond = 1000000000ll;
    static int64 const NanosecondsPerMinute = 60ll * NanosecondsPerSecond;
    static int64 const NanosecondsPerHour = 60ll * NanosecondsPerMinute;
    static int64 const NanosecondsPerDay = 24 * NanosecondsPerHour;

    Duration(int64 nanoseconds);

    int64 mNanoseconds;
};

inline Duration Duration::Nanoseconds(int64 nanoseconds)
{
    return Duration(nanoseconds);
}

inline Duration Duration::Microseconds(int64 microseconds)
{
    return Duration(microseconds * NanosecondsPerMicrosecond);
}

inline Duration Duration::Milliseconds(int64 milliseconds)
{
    return Duration(milliseconds * NanosecondsPerMillisecond);
}

inline Duration Duration::Seconds(int64 seconds)
{
    return Duration(seconds * NanosecondsPerSecond);
}

inline Duration Duration::Minutes(int32 minutes)
{
    return Duration(minutes * NanosecondsPerMinute);
}

inline Duration Duration::Hours(int32 hours)
{
    return Duration(hours * NanosecondsPerHour);
}

inline Duration Duration::Days(int32 days)
{
    return Duration(days * NanosecondsPerDay);
}

inline int64 Duration::GetTotalNanoseconds() const
{
    return mNanoseconds;
}

inline int64 Duration::GetTotalMicroseconds() const
{
    return mNanoseconds / NanosecondsPerMicrosecond;
}

inline int64 Duration::GetTotalMilliseconds() const
{
    return mNanoseconds / NanosecondsPerMillisecond;
}

inline int64 Duration::GetTotalSeconds() const
{
    return mNanoseconds / NanosecondsPerSecond;
}

inline int32 Duration::GetTotalMinutes() const
{
    return static_cast<int32>(mNanoseconds / NanosecondsPerMinute);
}

inline int32 Duration::GetTotalHours() const
{
    return static_cast<int32>(mNanoseconds / NanosecondsPerHour);
}

inline int32 Duration::GetTotalDays() const
{
    return static_cast<int32>(mNanoseconds / NanosecondsPerDay);
}

inline bool Duration::IsNegative() const
{
    return mNanoseconds < 0;
}

inline bool Duration::operator == (Duration rhs) const
{
    return mNanoseconds == rhs.mNanoseconds;
}

inline Duration& Duration::operator += (Duration rhs)
{
    mNanoseconds += rhs.mNanoseconds;
    return *this;
}

inline Duration& Duration::operator -= (Duration rhs)
{
    mNanoseconds -= rhs.mNanoseconds;
    return *this;
}

inline Duration operator + (Duration lhs, Duration rhs)
{
    return lhs += rhs;
}

inline Duration operator - (Duration lhs, Duration rhs)
{
    return lhs -= rhs;
}

inline Duration::Duration(int64 nanoseconds)
    : mNanoseconds(nanoseconds)
{}

}

#endif
<|endoftext|>


<commit_before>/*      _______   __   __   __   ______   __   __   _______   __   __
 *     / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___  /\ /  |\/ /\
 *    / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
 *   / / /__   / / // / // / // / /    / ___  / // ___  / // /| ' / /
 *  / /_// /\ / /_// / // / // /_/_   / / // / // /\_/ / // / |  / /
 * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
 * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
 *
 * Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson
 *
 *                                                         Js_./
 * Per Larsson a.k.a finalman                          _RqZ{a<^_aa
 * Olof Naessn a.k.a jansem/yakslem                _asww7!uY`>  )\a//
 *                                                 _Qhm`] _f "'c  1!5m
 * Visit: http://guichan.darkbits.org             )Qk<P ` _: :+' .'  "{[
 *                                               .)j(] .d_/ '-(  P .   S
 * License: (BSD)                                <Td/Z <fP"5(\"??"\a.  .L
 * Redistribution and use in source and          _dV>ws?a-?'      ._/L  #'
 * binary forms, with or without                 )4d[#7r, .   '     )d`)[
 * modification, are permitted provided         _Q-5'5W..j/?'   -?!\)cam'
 * that the following conditions are met:       j<<WP+k/);.        _W=j f
 * 1. Redistributions of source code must       .$%w\/]Q  . ."'  .  mj$
 *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\
 *    this list of conditions and the           j(]1u<sE"L,. .   ./^ ]{a
 *    following disclaimer.                     4'_uomm\.  )L);-4     (3=
 * 2. Redistributions in binary form must        )_]X{Z('a_"a7'<a"a,  ]"[
 *    reproduce the above copyright notice,       #}<]m7`Za??4,P-"'7. ).m
 *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ/
 *    following disclaimer in the                <B!</]C)d_, '(<' .f. =C+m
 *    documentation and/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'
 *    provided with the distribution.          .w[5]' _[ /.)_-"+?   _/ <W"
 * 3. Neither the name of Guichan nor the      :$we` _! + _/ .        j?
 *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    "
 *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..
 *    from this software without specific        (js, \[QQW$QWW#?!V"".
 *    prior written permission.                    ]y:.<\..          .
 *                                                 -]n w/ '         [.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )/ )/           !
 * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY         <  (; sac    ,    '
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P"_(\?d'.,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f/<[]/  ?"
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%"'  " -'.a_ _,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION)                     ^
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef GCN_FOCUSHANDLER_HPP
#define GCN_FOCUSHANDLER_HPP

#include <vector>

#include "guichan/event.hpp"
#include "guichan/platform.hpp"

namespace gcn
{
    class Widget;

    /**
     * Used to keep track of widget focus. You will probably not have
     * to use the FocusHandler directly to handle focus. Widget has
     * functions for handling focus which uses a FocusHandler. Use them
     * instead.
     *
     * @see Widget::isFocused
     * @see Widget::requestFocus
     * @see Widget::setFocusable
     * @see Widget::isFocusable
     * @see FocusListener
     */
    class GCN_CORE_DECLSPEC FocusHandler
    {
    public:

        /**
         * Constructor.
         */
        FocusHandler();

        /**
         * Destructor.
         */
        virtual ~FocusHandler() { };

        /**
         * Sets focus to a widget. When a widget receives focus will
         * the focus listener's of the widget be notified with a
         * a focus event.
         *
         * @param widget the widget to focus.
         */
        virtual void requestFocus(Widget* widget);

        /**
         * Sets modal focus to a widget.
         *
         * @param widget the Widget to focus modal.
         * @throws Exception when another widget already has modal focus.
         */
        virtual void requestModalFocus(Widget* widget);

        /**
         * Releases modal focus if the widget has modal focus.
         * Otherwise nothing will be done.
         *
         * @param widget the Widget to release modal focus for.
         */
        virtual void releaseModalFocus(Widget* widget);

        /**
         * Sets modal mouse input focus to a widget. Modal mouse input focus means
         * no other widget then the widget with modal mouse input focus will
         * receive mouse input..
         * The widget with modal mouse input focus will also receive mouse input no
         * matter what the mouse input is or where the mouse input occurs.
         *
         * @param widget the widget to focus for modal mouse input focus.
         * @throws Exception when another widget already has modal mouse input focus.
         */
        virtual void requestModalMouseInputFocus(Widget* widget);

        /**
         * Releases modal mouse input focus if the widget has modal mouse input
         * focus. Otherwise nothing will be done.
         *
         * @param widget the widget to release modal mouse input focus for.
         */
        virtual void releaseModalMouseInputFocus(Widget* widget);

        /**
         * Gets the widget with focus.
         *
         * @return the Widget with focus. NULL will be returned if
         *         no Widget has focus.
         */
        virtual Widget* getFocused() const;

        /**
         * Gets the widget with modal focus.
         *
         * @return the Widget with modal focus. NULL will be returned
         *         if no Widget has modal focus.
         */
        virtual Widget* getModalFocused() const;

        /**
         * Gets the widget with modal mouse input focus.
         *
         * @return the widget with modal mouse input focus. NULL will be returned
         *         if no widget has modal mouse input focus.
         */
        virtual Widget* getModalMouseInputFocused() const;

        /**
         * Focuses the next Widget. If no Widget has focus the first
         * Widget gets focus. The order in which the Widgets are focused
         * depends on the order you add them to the GUI.
         */
        virtual void focusNext();

        /**
         * Focuses the previous Widget. If no Widget has focus the first
         * Widget gets focus. The order in which the widgets are focused
         * depends on the order you add them to the GUI.
         */
        virtual void focusPrevious();

        /**
         * Checks if a Widget is focused.
         *
         * @param widget widget to check if it is focused.
         * @return true if the widget is focused.
         */
        virtual bool isFocused(const Widget* widget) const;

        /**
         * Adds a widget to the FocusHandler.
         *
         * @param widget the widget to add.
         */
        virtual void add(Widget* widget);

        /**
         * Removes a widget from the FocusHandler.
         *
         * @param widget the widget to remove.
         */
        virtual void remove(Widget* widget);

        /**
         * Focuses nothing. When a widget loses focus will
         * the focus listener's of the widget be notified with a
         * a focus event.
         */
        virtual void focusNone();

        /**
         * Focuses the next Widget which allows tab in unless current focused
         * Widget disallows tab out.
         */
        virtual void tabNext();

        /**
         * Focuses the previous Widget which allows tab in unless current focused
         * Widget disallows tab out.
         */
        virtual void tabPrevious();

    protected:
        /**
         * Distributes a focus lost event.
         *
         * @param focusEvent the event to distribute.
         * @author Olof Naessn
         * @since 0.7.0
         */
        virtual void distributeFocusLostEvent(const Event& focusEvent);

        /**
         * Distributes a focus gained event.
         *
         * @param focusEvent the event to distribute.
         * @author Olof Naessn
         * @since 0.7.0
         */
        virtual void distributeFocusGainedEvent(const Event& focusEvent);

        typedef std::vector<Widget*> WidgetVector;
        typedef WidgetVector::iterator WidgetIterator;
        WidgetVector mWidgets;

        Widget* mFocusedWidget;
        Widget* mModalFocusedWidget;
        Widget* mModalMouseInputFocusedWidget;
    };
}

#endif // end GCN_FOCUSHANDLER_HPP
<commit_msg>Comments have been updated.<commit_after>/*      _______   __   __   __   ______   __   __   _______   __   __
 *     / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___  /\ /  |\/ /\
 *    / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
 *   / / /__   / / // / // / // / /    / ___  / // ___  / // /| ' / /
 *  / /_// /\ / /_// / // / // /_/_   / / // / // /\_/ / // / |  / /
 * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
 * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
 *
 * Copyright (c) 2004, 2005, 2006, 2007 Olof Naessn and Per Larsson
 *
 *                                                         Js_./
 * Per Larsson a.k.a finalman                          _RqZ{a<^_aa
 * Olof Naessn a.k.a jansem/yakslem                _asww7!uY`>  )\a//
 *                                                 _Qhm`] _f "'c  1!5m
 * Visit: http://guichan.darkbits.org             )Qk<P ` _: :+' .'  "{[
 *                                               .)j(] .d_/ '-(  P .   S
 * License: (BSD)                                <Td/Z <fP"5(\"??"\a.  .L
 * Redistribution and use in source and          _dV>ws?a-?'      ._/L  #'
 * binary forms, with or without                 )4d[#7r, .   '     )d`)[
 * modification, are permitted provided         _Q-5'5W..j/?'   -?!\)cam'
 * that the following conditions are met:       j<<WP+k/);.        _W=j f
 * 1. Redistributions of source code must       .$%w\/]Q  . ."'  .  mj$
 *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\
 *    this list of conditions and the           j(]1u<sE"L,. .   ./^ ]{a
 *    following disclaimer.                     4'_uomm\.  )L);-4     (3=
 * 2. Redistributions in binary form must        )_]X{Z('a_"a7'<a"a,  ]"[
 *    reproduce the above copyright notice,       #}<]m7`Za??4,P-"'7. ).m
 *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ/
 *    following disclaimer in the                <B!</]C)d_, '(<' .f. =C+m
 *    documentation and/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'
 *    provided with the distribution.          .w[5]' _[ /.)_-"+?   _/ <W"
 * 3. Neither the name of Guichan nor the      :$we` _! + _/ .        j?
 *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    "
 *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..
 *    from this software without specific        (js, \[QQW$QWW#?!V"".
 *    prior written permission.                    ]y:.<\..          .
 *                                                 -]n w/ '         [.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )/ )/           !
 * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY         <  (; sac    ,    '
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P"_(\?d'.,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f/<[]/  ?"
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%"'  " -'.a_ _,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION)                     ^
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef GCN_FOCUSHANDLER_HPP
#define GCN_FOCUSHANDLER_HPP

#include <vector>

#include "guichan/event.hpp"
#include "guichan/platform.hpp"

namespace gcn
{
    class Widget;

    /**
     * Used to keep track of widget focus. You will probably not have
     * to use the FocusHandler directly to handle focus. Widget has
     * functions for handling focus which uses a FocusHandler. Use them
     * instead.
     *
     * @see Widget::isFocused
     * @see Widget::requestFocus
     * @see Widget::setFocusable
     * @see Widget::isFocusable
     * @see FocusListener
     */
    class GCN_CORE_DECLSPEC FocusHandler
    {
    public:

        /**
         * Constructor.
         */
        FocusHandler();

        /**
         * Destructor.
         */
        virtual ~FocusHandler() { };

        /**
         * Sets focus to a widget. A focus event will also be sent to the widget's
         * focus listeners.
         *
         * @param widget the widget to focus.
         */
        virtual void requestFocus(Widget* widget);

        /**
         * Sets modal focus to a widget.
         *
         * @param widget the Widget to focus modal.
         * @throws Exception when another widget already has modal focus.
         */
        virtual void requestModalFocus(Widget* widget);

        /**
         * Releases modal focus if the widget has modal focus.
         * Otherwise nothing will be done.
         *
         * @param widget the Widget to release modal focus for.
         */
        virtual void releaseModalFocus(Widget* widget);

        /**
         * Sets modal mouse input focus to a widget. Modal mouse input focus means
         * no other widget then the widget with modal mouse input focus will
         * receive mouse input..
         * The widget with modal mouse input focus will also receive mouse input no
         * matter what the mouse input is or where the mouse input occurs.
         *
         * @param widget the widget to focus for modal mouse input focus.
         * @throws Exception when another widget already has modal mouse input focus.
         */
        virtual void requestModalMouseInputFocus(Widget* widget);

        /**
         * Releases modal mouse input focus if the widget has modal mouse input
         * focus. Otherwise nothing will be done.
         *
         * @param widget the widget to release modal mouse input focus for.
         */
        virtual void releaseModalMouseInputFocus(Widget* widget);

        /**
         * Gets the widget with focus.
         *
         * @return the Widget with focus. NULL will be returned if
         *         no Widget has focus.
         */
        virtual Widget* getFocused() const;

        /**
         * Gets the widget with modal focus.
         *
         * @return the Widget with modal focus. NULL will be returned
         *         if no Widget has modal focus.
         */
        virtual Widget* getModalFocused() const;

        /**
         * Gets the widget with modal mouse input focus.
         *
         * @return the widget with modal mouse input focus. NULL will be returned
         *         if no widget has modal mouse input focus.
         */
        virtual Widget* getModalMouseInputFocused() const;

        /**
         * Focuses the next Widget. If no Widget has focus the first
         * Widget gets focus. The order in which the Widgets are focused
         * depends on the order you add them to the GUI.
         */
        virtual void focusNext();

        /**
         * Focuses the previous Widget. If no Widget has focus the first
         * Widget gets focus. The order in which the widgets are focused
         * depends on the order you add them to the GUI.
         */
        virtual void focusPrevious();

        /**
         * Checks if a Widget is focused.
         *
         * @param widget widget to check if it is focused.
         * @return true if the widget is focused.
         */
        virtual bool isFocused(const Widget* widget) const;

        /**
         * Adds a widget to the FocusHandler.
         *
         * @param widget the widget to add.
         */
        virtual void add(Widget* widget);

        /**
         * Removes a widget from the FocusHandler.
         *
         * @param widget the widget to remove.
         */
        virtual void remove(Widget* widget);

        /**
         * Focuses nothing. A focus event will also be sent to the focused widget's
         * focus listeners if a widget has focus.
         */
        virtual void focusNone();

        /**
         * Focuses the next Widget which allows tab in unless current focused
         * Widget disallows tab out.
         */
        virtual void tabNext();

        /**
         * Focuses the previous Widget which allows tab in unless current focused
         * Widget disallows tab out.
         */
        virtual void tabPrevious();

    protected:
        /**
         * Distributes a focus lost event.
         *
         * @param focusEvent the event to distribute.
         * @author Olof Naessn
         * @since 0.7.0
         */
        virtual void distributeFocusLostEvent(const Event& focusEvent);

        /**
         * Distributes a focus gained event.
         *
         * @param focusEvent the event to distribute.
         * @author Olof Naessn
         * @since 0.7.0
         */
        virtual void distributeFocusGainedEvent(const Event& focusEvent);

        typedef std::vector<Widget*> WidgetVector;
        typedef WidgetVector::iterator WidgetIterator;
        WidgetVector mWidgets;

        Widget* mFocusedWidget;
        Widget* mModalFocusedWidget;
        Widget* mModalMouseInputFocusedWidget;
    };
}

#endif // end GCN_FOCUSHANDLER_HPP
<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "EventDispatcher.h"

#include <react/core/StateUpdate.h>

#include "BatchedEventQueue.h"
#include "RawEvent.h"
#include "UnbatchedEventQueue.h"

#define REACT_FABRIC_SYNC_EVENT_DISPATCHING_DISABLED

namespace facebook {
namespace react {

EventDispatcher::EventDispatcher(
    const EventPipe &eventPipe,
    const StatePipe &statePipe,
    const EventBeatFactory &synchonousEventBeatFactory,
    const EventBeatFactory &asynchonousEventBeatFactory) {
  // Synchronous/Unbatched
  eventQueues_[(int)EventPriority::SynchronousUnbatched] =
      std::make_unique<UnbatchedEventQueue>(
          eventPipe, statePipe, synchonousEventBeatFactory());

  // Synchronous/Batched
  eventQueues_[(int)EventPriority::SynchronousBatched] =
      std::make_unique<BatchedEventQueue>(
          eventPipe, statePipe, synchonousEventBeatFactory());

  // Asynchronous/Unbatched
  eventQueues_[(int)EventPriority::AsynchronousUnbatched] =
      std::make_unique<UnbatchedEventQueue>(
          eventPipe, statePipe, asynchonousEventBeatFactory());

  // Asynchronous/Batched
  eventQueues_[(int)EventPriority::AsynchronousBatched] =
      std::make_unique<BatchedEventQueue>(
          eventPipe, statePipe, asynchonousEventBeatFactory());
}

void EventDispatcher::dispatchEvent(
    const RawEvent &rawEvent,
    EventPriority priority) const {
  getEventQueue(priority).enqueueEvent(std::move(rawEvent));
}

void EventDispatcher::dispatchStateUpdate(
    StateUpdate &&stateUpdate,
    EventPriority priority) const {
  getEventQueue(priority).enqueueStateUpdate(std::move(stateUpdate));
}

const EventQueue &EventDispatcher::getEventQueue(EventPriority priority) const {
#ifdef REACT_FABRIC_SYNC_EVENT_DISPATCHING_DISABLED
  // Synchronous dispatch works, but JavaScript interop layer does not have
  // proper synchonization yet and it crashes.
  if (priority == EventPriority::SynchronousUnbatched) {
    priority = EventPriority::AsynchronousUnbatched;
  }

  if (priority == EventPriority::SynchronousBatched) {
    priority = EventPriority::AsynchronousBatched;
  }
#endif

  return *eventQueues_[(int)priority];
}

} // namespace react
} // namespace facebook
<commit_msg>Fabric: Disabling sync and unbatched event queues<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "EventDispatcher.h"

#include <react/core/StateUpdate.h>

#include "BatchedEventQueue.h"
#include "RawEvent.h"
#include "UnbatchedEventQueue.h"

#define REACT_FABRIC_SYNC_EVENT_DISPATCHING_DISABLED

namespace facebook {
namespace react {

EventDispatcher::EventDispatcher(
    const EventPipe &eventPipe,
    const StatePipe &statePipe,
    const EventBeatFactory &synchonousEventBeatFactory,
    const EventBeatFactory &asynchonousEventBeatFactory) {
  // Synchronous/Unbatched
  eventQueues_[(int)EventPriority::SynchronousUnbatched] =
      std::make_unique<UnbatchedEventQueue>(
          eventPipe, statePipe, synchonousEventBeatFactory());

  // Synchronous/Batched
  eventQueues_[(int)EventPriority::SynchronousBatched] =
      std::make_unique<BatchedEventQueue>(
          eventPipe, statePipe, synchonousEventBeatFactory());

  // Asynchronous/Unbatched
  eventQueues_[(int)EventPriority::AsynchronousUnbatched] =
      std::make_unique<UnbatchedEventQueue>(
          eventPipe, statePipe, asynchonousEventBeatFactory());

  // Asynchronous/Batched
  eventQueues_[(int)EventPriority::AsynchronousBatched] =
      std::make_unique<BatchedEventQueue>(
          eventPipe, statePipe, asynchonousEventBeatFactory());
}

void EventDispatcher::dispatchEvent(
    const RawEvent &rawEvent,
    EventPriority priority) const {
  getEventQueue(priority).enqueueEvent(std::move(rawEvent));
}

void EventDispatcher::dispatchStateUpdate(
    StateUpdate &&stateUpdate,
    EventPriority priority) const {
  getEventQueue(priority).enqueueStateUpdate(std::move(stateUpdate));
}

const EventQueue &EventDispatcher::getEventQueue(EventPriority priority) const {
#ifdef REACT_FABRIC_SYNC_EVENT_DISPATCHING_DISABLED
  priority = EventPriority::AsynchronousBatched;
#endif

  return *eventQueues_[(int)priority];
}

} // namespace react
} // namespace facebook
<|endoftext|>


<commit_before>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

#include "db/builder.h"

#include "db/filename.h"
#include "db/dbformat.h"
#include "db/table_cache.h"
#include "db/version_edit.h"
#include "leveldb/db.h"
#include "leveldb/env.h"
#include "leveldb/iterator.h"

namespace leveldb {

Status BuildTable(const std::string& dbname,
                  Env* env,
                  const Options& options,
                  const Comparator * user_comparator,
                  TableCache* table_cache,
                  Iterator* iter,
                  FileMetaData* meta,
                  SequenceNumber smallest_snapshot) {
  Status s;
  size_t keys_seen, keys_retired;

  keys_seen=0;
  keys_retired=0;

  meta->file_size = 0;
  iter->SeekToFirst();

  KeyRetirement retire(user_comparator, smallest_snapshot);

  std::string fname = TableFileName(options, meta->number, meta->level);
  if (iter->Valid()) {
    WritableFile* file;
    size_t map_size;

    // large buffers, try for a little bit bigger than half hoping
    //  for two writes ... not three
    if (10*1024*1024 < options.write_buffer_size)
        map_size=(options.write_buffer_size/6)*4;
    else
        map_size=(options.write_buffer_size*12)/10;  // integer multiply 1.2

    s = env->NewWritableFile(fname, &file, map_size);
    if (!s.ok()) {
      return s;
    }

    // tune fadvise to keep all of this lower level file in page cache
    //  (compaction of unsorted files causes severe cache misses)
    file->SetMetadataOffset(1);

    TableBuilder* builder = new TableBuilder(options, file);
    meta->smallest.DecodeFrom(iter->key());
    for (; iter->Valid(); iter->Next()) {
      ++keys_seen;
      Slice key = iter->key();
      if (!retire(key))
      {
          meta->largest.DecodeFrom(key);
          builder->Add(key, iter->value());
          ++meta->num_entries;
      }   // if
      else
      {
          ++keys_retired;
      }   // else
    }

    // Finish and check for builder errors
    if (s.ok()) {
      s = builder->Finish();
      if (s.ok()) {
        meta->file_size = builder->FileSize();
        assert(meta->file_size > 0);
      }
    } else {
      builder->Abandon();
    }
    delete builder;

    // Finish and check for file errors
    if (s.ok()) {
      s = file->Sync();
    }
    if (s.ok()) {
      s = file->Close();
    }
    delete file;
    file = NULL;

    if (s.ok()) {
      // Verify that the table is usable
      Iterator* it = table_cache->NewIterator(ReadOptions(),
                                              meta->number,
                                              meta->file_size,
                                              meta->level);
      s = it->status();
      delete it;
    }
  }

  // Check for input iterator errors
  if (!iter->status().ok()) {
    s = iter->status();
  }

  if (s.ok() && meta->file_size > 0) {
    // Keep it
      if (0!=keys_retired)
      {
          Log(options.info_log, "Level-0 table #%" PRIu64 ": %zd keys seen, %zd keys retired",
              meta->number, keys_seen, keys_retired);
      }   // if
  } else {
    env->DeleteFile(fname);
  }
  return s;
}

}  // namespace leveldb
<commit_msg>oops, forgot on place that needed RecoveryMmapSize() added.  Nice to have a good code reviewer.  Thank you ajs.<commit_after>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

#include "db/builder.h"

#include "db/filename.h"
#include "db/dbformat.h"
#include "db/table_cache.h"
#include "db/version_edit.h"
#include "leveldb/db.h"
#include "leveldb/env.h"
#include "leveldb/iterator.h"

namespace leveldb {

Status BuildTable(const std::string& dbname,
                  Env* env,
                  const Options& options,
                  const Comparator * user_comparator,
                  TableCache* table_cache,
                  Iterator* iter,
                  FileMetaData* meta,
                  SequenceNumber smallest_snapshot) {
  Status s;
  size_t keys_seen, keys_retired;

  keys_seen=0;
  keys_retired=0;

  meta->file_size = 0;
  iter->SeekToFirst();

  KeyRetirement retire(user_comparator, smallest_snapshot);

  std::string fname = TableFileName(options, meta->number, meta->level);
  if (iter->Valid()) {
    WritableFile* file;

    s = env->NewWritableFile(fname, &file,
                                 env->RecoveryMmapSize(&options));
    if (!s.ok()) {
      return s;
    }

    // tune fadvise to keep all of this lower level file in page cache
    //  (compaction of unsorted files causes severe cache misses)
    file->SetMetadataOffset(1);

    TableBuilder* builder = new TableBuilder(options, file);
    meta->smallest.DecodeFrom(iter->key());
    for (; iter->Valid(); iter->Next()) {
      ++keys_seen;
      Slice key = iter->key();
      if (!retire(key))
      {
          meta->largest.DecodeFrom(key);
          builder->Add(key, iter->value());
          ++meta->num_entries;
      }   // if
      else
      {
          ++keys_retired;
      }   // else
    }

    // Finish and check for builder errors
    if (s.ok()) {
      s = builder->Finish();
      if (s.ok()) {
        meta->file_size = builder->FileSize();
        assert(meta->file_size > 0);
      }
    } else {
      builder->Abandon();
    }
    delete builder;

    // Finish and check for file errors
    if (s.ok()) {
      s = file->Sync();
    }
    if (s.ok()) {
      s = file->Close();
    }
    delete file;
    file = NULL;

    if (s.ok()) {
      // Verify that the table is usable
      Iterator* it = table_cache->NewIterator(ReadOptions(),
                                              meta->number,
                                              meta->file_size,
                                              meta->level);
      s = it->status();
      delete it;
    }
  }

  // Check for input iterator errors
  if (!iter->status().ok()) {
    s = iter->status();
  }

  if (s.ok() && meta->file_size > 0) {
    // Keep it
      if (0!=keys_retired)
      {
          Log(options.info_log, "Level-0 table #%" PRIu64 ": %zd keys seen, %zd keys retired",
              meta->number, keys_seen, keys_retired);
      }   // if
  } else {
    env->DeleteFile(fname);
  }
  return s;
}

}  // namespace leveldb
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_TEXT_ITEMIZER_HPP
#define MAPNIK_TEXT_ITEMIZER_HPP

//mapnik
#include <mapnik/text/evaluated_format_properties_ptr.hpp>
#include <mapnik/value_types.hpp>
#include <mapnik/util/noncopyable.hpp>
#include <mapnik/config.hpp>

// stl
#include <string>
#include <list>
#include <vector>

// ICU
#include <unicode/unistr.h>
#include <unicode/uscript.h>
#include <unicode/ubidi.h>

namespace mapnik
{

struct MAPNIK_DECL text_item : util::noncopyable
{
    text_item(unsigned s,
              unsigned e,
              UScriptCode sc,
              UBiDiDirection d,
              evaluated_format_properties_ptr const& f)
      : start(s),
        end(e),
        script(sc),
        dir(d),
        format_(f) {}
    text_item( text_item && rhs)
      : start(std::move(rhs.start)),
        end(std::move(rhs.end)),
        script(std::move(rhs.script)),
        dir(std::move(rhs.dir)),
        format_(rhs.format_) {}
    unsigned start; // First char (UTF16 offset)
    unsigned end; // Char _after_ the last char (UTF16 offset)
    UScriptCode script;
    UBiDiDirection dir;
    evaluated_format_properties_ptr const& format_;
};

// This class splits text into parts which all have the same
// - direction (LTR, RTL)
// - format
// - script (http://en.wikipedia.org/wiki/Scripts_in_Unicode)

class MAPNIK_DECL text_itemizer
{
public:
    text_itemizer();
    void add_text(value_unicode_string const& str, evaluated_format_properties_ptr const& format);
    std::list<text_item> const& itemize(unsigned start=0, unsigned end=0);
    void clear();
    value_unicode_string const& text() const { return text_; }
    // Returns the start and end position of a certain line.
    // Only forced line breaks with \n characters are handled here.
    std::pair<unsigned, unsigned> line(unsigned i) const;
    unsigned num_lines() const;
private:
    template<typename T> struct run : util::noncopyable
    {
        run(T const& _data, unsigned _start, unsigned _end)
            :  start(_start), end(_end), data(_data) {}
        unsigned start;
        unsigned end;
        T data;
    };
    using format_run_t = run<evaluated_format_properties_ptr const&>;
    using direction_run_t = run<UBiDiDirection>;
    using script_run_t = run<UScriptCode>;
    using format_run_list = std::list<format_run_t>;
    using script_run_list = std::list<script_run_t>;
    using direction_run_list = std::list<direction_run_t>;
    value_unicode_string text_;
    /// Format runs are always sorted by char index
    format_run_list format_runs_;
    /// Directions runs are always in visual order! This is different from
    /// format and script runs!
    direction_run_list direction_runs_;
    /// Script runs are always sorted by char index
    script_run_list script_runs_;
    void itemize_direction(unsigned start, unsigned end);
    void itemize_script();
    void create_item_list();
    std::list<text_item> output_;
    template <typename T> typename T::const_iterator find_run(T const& list, unsigned position);
    std::vector<unsigned> forced_line_breaks_; //Positions of \n characters
};
} //ns mapnik

#endif // TEXT_ITEMIZER_HPP
<commit_msg>make text_itemizer noncopyable<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2015 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

#ifndef MAPNIK_TEXT_ITEMIZER_HPP
#define MAPNIK_TEXT_ITEMIZER_HPP

//mapnik
#include <mapnik/text/evaluated_format_properties_ptr.hpp>
#include <mapnik/value_types.hpp>
#include <mapnik/util/noncopyable.hpp>
#include <mapnik/config.hpp>

// stl
#include <string>
#include <list>
#include <vector>

// ICU
#include <unicode/unistr.h>
#include <unicode/uscript.h>
#include <unicode/ubidi.h>

namespace mapnik
{

struct MAPNIK_DECL text_item : util::noncopyable
{
    text_item(unsigned s,
              unsigned e,
              UScriptCode sc,
              UBiDiDirection d,
              evaluated_format_properties_ptr const& f)
      : start(s),
        end(e),
        script(sc),
        dir(d),
        format_(f) {}
    text_item( text_item && rhs)
      : start(std::move(rhs.start)),
        end(std::move(rhs.end)),
        script(std::move(rhs.script)),
        dir(std::move(rhs.dir)),
        format_(rhs.format_) {}
    unsigned start; // First char (UTF16 offset)
    unsigned end; // Char _after_ the last char (UTF16 offset)
    UScriptCode script;
    UBiDiDirection dir;
    evaluated_format_properties_ptr const& format_;
};

// This class splits text into parts which all have the same
// - direction (LTR, RTL)
// - format
// - script (http://en.wikipedia.org/wiki/Scripts_in_Unicode)

class MAPNIK_DECL text_itemizer : util::noncopyable
{
public:
    text_itemizer();
    void add_text(value_unicode_string const& str, evaluated_format_properties_ptr const& format);
    std::list<text_item> const& itemize(unsigned start=0, unsigned end=0);
    void clear();
    value_unicode_string const& text() const { return text_; }
    // Returns the start and end position of a certain line.
    // Only forced line breaks with \n characters are handled here.
    std::pair<unsigned, unsigned> line(unsigned i) const;
    unsigned num_lines() const;
private:
    template<typename T> struct run : util::noncopyable
    {
        run(T const& _data, unsigned _start, unsigned _end)
            :  start(_start), end(_end), data(_data) {}
        unsigned start;
        unsigned end;
        T data;
    };
    using format_run_t = run<evaluated_format_properties_ptr const&>;
    using direction_run_t = run<UBiDiDirection>;
    using script_run_t = run<UScriptCode>;
    using format_run_list = std::list<format_run_t>;
    using script_run_list = std::list<script_run_t>;
    using direction_run_list = std::list<direction_run_t>;
    value_unicode_string text_;
    /// Format runs are always sorted by char index
    format_run_list format_runs_;
    /// Directions runs are always in visual order! This is different from
    /// format and script runs!
    direction_run_list direction_runs_;
    /// Script runs are always sorted by char index
    script_run_list script_runs_;
    void itemize_direction(unsigned start, unsigned end);
    void itemize_script();
    void create_item_list();
    std::list<text_item> output_;
    template <typename T> typename T::const_iterator find_run(T const& list, unsigned position);
    std::vector<unsigned> forced_line_breaks_; //Positions of \n characters
};
} //ns mapnik

#endif // TEXT_ITEMIZER_HPP
<|endoftext|>


<commit_before>/*
 * FakeObject.hpp
 * Copyright (c) 2014 Eran Pe'er.
 *
 * This program is made available under the terms of the MIT License.
 *
 * Created on Jun 8, 2014
 */
#pragma once

#include <new>
#include "mockutils/VirtualTable.hpp"

namespace fakeit {
// silent GCC compiler warning: iso c++ forbids zero-size array [-Wpedantic]
#ifdef __GNUG__
#ifndef __clang__
#pragma GCC diagnostic ignored "-Wpedantic"
#endif
#endif

// silent MSC++ compiler warning: C4200: nonstandard extension used : zero-sized array in struct/union.
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable : 4200 )
#endif

    template<typename C, typename ... baseclasses>
    class FakeObject {

        VirtualTable<C, baseclasses...> vtable;

        static const size_t SIZE = sizeof(C) - sizeof(VirtualTable<C, baseclasses...>);
        char instanceArea[SIZE ? SIZE : 0];

        FakeObject(FakeObject const &) = delete;            // undefined
        FakeObject &operator=(FakeObject const &) = delete; // undefined

    public:

        FakeObject() : vtable() {
            initializeDataMembersArea();
        }

        ~FakeObject() {
            vtable.dispose();
        }

        void initializeDataMembersArea() {
            for (size_t i = 0; i < SIZE; ++i) instanceArea[i] = (char) 0;
        }

        void setMethod(unsigned int index, void *method) {
            vtable.setMethod(index, method);
        }

        VirtualTable<C, baseclasses...> &getVirtualTable() {
            return vtable;
        }

        void setVirtualTable(VirtualTable<C, baseclasses...> &t) {
            vtable = t;
        }

        void setDtor(void *dtor) {
            vtable.setDtor(dtor);
        }
    };

#ifdef _MSC_VER
#pragma warning( pop )
#endif

#ifdef __GNUG__
#ifndef __clang__
#pragma GCC diagnostic pop
#endif
#endif

}
<commit_msg>160 Add pragma GCC diagnostic push.<commit_after>/*
 * FakeObject.hpp
 * Copyright (c) 2014 Eran Pe'er.
 *
 * This program is made available under the terms of the MIT License.
 *
 * Created on Jun 8, 2014
 */
#pragma once

#include <new>
#include "mockutils/VirtualTable.hpp"

namespace fakeit {
// silent GCC compiler warning: iso c++ forbids zero-size array [-Wpedantic]
#ifdef __GNUG__
#ifndef __clang__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
#endif
#endif

// silent MSC++ compiler warning: C4200: nonstandard extension used : zero-sized array in struct/union.
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable : 4200 )
#endif

    template<typename C, typename ... baseclasses>
    class FakeObject {

        VirtualTable<C, baseclasses...> vtable;

        static const size_t SIZE = sizeof(C) - sizeof(VirtualTable<C, baseclasses...>);
        char instanceArea[SIZE ? SIZE : 0];

        FakeObject(FakeObject const &) = delete;            // undefined
        FakeObject &operator=(FakeObject const &) = delete; // undefined

    public:

        FakeObject() : vtable() {
            initializeDataMembersArea();
        }

        ~FakeObject() {
            vtable.dispose();
        }

        void initializeDataMembersArea() {
            for (size_t i = 0; i < SIZE; ++i) instanceArea[i] = (char) 0;
        }

        void setMethod(unsigned int index, void *method) {
            vtable.setMethod(index, method);
        }

        VirtualTable<C, baseclasses...> &getVirtualTable() {
            return vtable;
        }

        void setVirtualTable(VirtualTable<C, baseclasses...> &t) {
            vtable = t;
        }

        void setDtor(void *dtor) {
            vtable.setDtor(dtor);
        }
    };

#ifdef _MSC_VER
#pragma warning( pop )
#endif

#ifdef __GNUG__
#ifndef __clang__
#pragma GCC diagnostic pop
#endif
#endif

}
<|endoftext|>


<commit_before>/// (c) Koheron

#include "tests.hpp"

#include <cmath>
#include <random>
#include <thread>

Tests::Tests(Klib::DevMem& dvm_unused_)
: data(0)
{
    waveform_size = 0;
    mean = 0;
    std_dev = 0;
    status = CLOSED;
}

Tests::~Tests()
{
    Close();
}

int Tests::Open(uint32_t waveform_size_)
{
    // Reopening
    if (status == OPENED && waveform_size_ != waveform_size)
        Close();

    if (status == CLOSED) {
        waveform_size = waveform_size_;
        data = Klib::KVector<float>(waveform_size, 0);
        status = OPENED;
    }

    return 0;
}

void Tests::Close()
{
    if (status == OPENED)
        status = CLOSED;
}

Klib::KVector<float>& Tests::read()
{
    std::default_random_engine generator(std::random_device{}());
    std::normal_distribution<float> distribution(mean, std_dev);

    for (unsigned int i=0; i<data.size(); i++)
        data[i] = distribution(generator);

    return data;
}

void Tests::set_mean(float mean_)
{
    mean = mean_;
}

void Tests::set_std_dev(float std_dev_)
{
    std_dev = std_dev_;
}

std::array<uint32_t, 10>& Tests::send_std_array()
{
    for (uint32_t i=0; i<data_std_array.size(); i++)
        data_std_array[i] = i*i;

    return data_std_array;
}

uint64_t Tests::read64()
{
    return (1UL << 63);
}

<commit_msg>Fix to unsigned long long<commit_after>/// (c) Koheron

#include "tests.hpp"

#include <cmath>
#include <random>
#include <thread>

Tests::Tests(Klib::DevMem& dvm_unused_)
: data(0)
{
    waveform_size = 0;
    mean = 0;
    std_dev = 0;
    status = CLOSED;
}

Tests::~Tests()
{
    Close();
}

int Tests::Open(uint32_t waveform_size_)
{
    // Reopening
    if (status == OPENED && waveform_size_ != waveform_size)
        Close();

    if (status == CLOSED) {
        waveform_size = waveform_size_;
        data = Klib::KVector<float>(waveform_size, 0);
        status = OPENED;
    }

    return 0;
}

void Tests::Close()
{
    if (status == OPENED)
        status = CLOSED;
}

Klib::KVector<float>& Tests::read()
{
    std::default_random_engine generator(std::random_device{}());
    std::normal_distribution<float> distribution(mean, std_dev);

    for (unsigned int i=0; i<data.size(); i++)
        data[i] = distribution(generator);

    return data;
}

void Tests::set_mean(float mean_)
{
    mean = mean_;
}

void Tests::set_std_dev(float std_dev_)
{
    std_dev = std_dev_;
}

std::array<uint32_t, 10>& Tests::send_std_array()
{
    for (uint32_t i=0; i<data_std_array.size(); i++)
        data_std_array[i] = i*i;

    return data_std_array;
}

uint64_t Tests::read64()
{
    return (1ULL << 63);
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: autoregisterhelper.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 02:27:37 $
 *
 *  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 <stdio.h>
#include <stdlib.h>
#include "autoregisterhelper.hxx"

#include <rtl/ustring.hxx>

#include <cppunit/autoregister/registerfunc.h>
#include <cppunit/autoregister/callbackstructure.h>
#include <cppunit/result/callbackfunc.h>
#include <cppunit/autoregister/testfunc.h>
#include "filehelper.hxx"

FunctionList m_Functions;
// osl::Mutex   m_Mutex;

extern "C" void SAL_CALL registerFunc(FktPtr _pFunc, const char*)
{
    m_Functions.push_back(_pFunc);
}

// -----------------------------------------------------------------------------
AutomaticRegisterHelper::AutomaticRegisterHelper(rtl::OUString const& _sDLLName, GetOpt & _aOptions /*, JobList * _pJobList*/)
        :DynamicLibraryHelper(_sDLLName, _aOptions),
         m_bLoadLibraryOK(false)
{
    // try to get the entry pointer
    FktRegAllPtr pFunc = (FktRegAllPtr) m_pModule->getFunctionSymbol(
        rtl::OUString::createFromAscii( "registerAllTestFunction" ) );

    if (pFunc)
    {
        m_bLoadLibraryOK = true;
        // FktRegFuncPtr pRegisterFunc = &DynamicLibraryHelper::registerFunc;
        // pFunc(pRegisterFunc);
        // osl::Guard aGuard(m_Mutex);
        FktRegFuncPtr pRegisterFunc = &registerFunc;

        CallbackStructure aCallback;
        aCallback.aRegisterFunction = pRegisterFunc;

        aCallback.aCallbackDispatch  = &CallbackDispatch;

        // special parameter for API testing
        if (_aOptions.hasOpt("-forward"))
        {
            aCallback.psForward = _aOptions.getOpt("-forward").getStr();
        }

        // aCallback.pJobList = _pJobList;

        //# aCallback.aStartTest  = &TestResult_startTest;
        //# aCallback.aAddFailure = &TestResult_addFailure;
        //# aCallback.aAddError   = &TestResult_addError;
        //# aCallback.aEndTest    = &TestResult_endTest;
        //# aCallback.aShouldStop = &TestResult_shouldStop;
        //# aCallback.aAddInfo    = &TestResult_addInfo;
        //# aCallback.aEnterNode  = &TestResult_enterNode;
        //# aCallback.aLeaveNode  = &TestResult_leaveNode;

        aCallback.nBits       = FileHelper::createFlags(_aOptions);

        pFunc(&aCallback);

        if (aCallback.nMagic == aCallback.nMagic2)
        {
            // ok internal simple test done.
            m_aFunctionList = m_Functions;
        }
        else
        {
            // ERROR, the function seams not to be what we thing it's to be.
            fprintf(stderr, "error: Internal check failed. Structure inconsistent, Value Magic2 != Magic.\nPlease recompile your test libraries.");
            exit(-1);
        }
    }
    else
    {
        fprintf(stderr, "warning: Function 'registerAllTestFunction' not found.\n");
        fprintf(stderr, "If you think, you are right, build testshl2 completly new.\n");
    }
}

void AutomaticRegisterHelper::CallAll(hTestResult _hResult) const
{
    // can't load the module, break the tests.
    if (m_bLoadLibraryOK == false)
    {
        return;
    }

    for (FunctionList::const_iterator it = m_aFunctionList.begin();
         it != m_aFunctionList.end();
         ++it)
    {
        FktPtr pFunc = *it;
        if (pFunc)
        {
            (pFunc)(_hResult);
        }
    }
}

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

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

#include <stdio.h>
#include <stdlib.h>
#include "autoregisterhelper.hxx"

#include <rtl/ustring.hxx>

#include <cppunit/autoregister/registerfunc.h>
#include <cppunit/autoregister/callbackstructure.h>
#include <cppunit/result/callbackfunc.h>
#include <cppunit/autoregister/testfunc.h>
#include "filehelper.hxx"

FunctionList m_Functions;
// osl::Mutex   m_Mutex;

extern "C" void SAL_CALL registerFunc(FktPtr _pFunc, const char*)
{
    m_Functions.push_back(_pFunc);
}

// -----------------------------------------------------------------------------
AutomaticRegisterHelper::AutomaticRegisterHelper(rtl::OUString const& _sDLLName, GetOpt & _aOptions /*, JobList * _pJobList*/)
        :DynamicLibraryHelper(_sDLLName, _aOptions),
         m_bLoadLibraryOK(false)
{
    // try to get the entry pointer
    FktRegAllPtr pFunc = (FktRegAllPtr) m_pModule->getFunctionSymbol(
        rtl::OUString::createFromAscii( "registerAllTestFunction" ) );

    if (pFunc)
    {
        m_bLoadLibraryOK = true;
        // FktRegFuncPtr pRegisterFunc = &DynamicLibraryHelper::registerFunc;
        // pFunc(pRegisterFunc);
        // osl::Guard aGuard(m_Mutex);
        FktRegFuncPtr pRegisterFunc = &registerFunc;

        CallbackStructure aCallback;
        aCallback.aRegisterFunction = pRegisterFunc;

        aCallback.aCallbackDispatch  = &CallbackDispatch;

        // special parameter for API testing
        if (_aOptions.hasOpt("-forward"))
        {
            aCallback.psForward = _aOptions.getOpt("-forward").getStr();
        }

        // aCallback.pJobList = _pJobList;

        //# aCallback.aStartTest  = &TestResult_startTest;
        //# aCallback.aAddFailure = &TestResult_addFailure;
        //# aCallback.aAddError   = &TestResult_addError;
        //# aCallback.aEndTest    = &TestResult_endTest;
        //# aCallback.aShouldStop = &TestResult_shouldStop;
        //# aCallback.aAddInfo    = &TestResult_addInfo;
        //# aCallback.aEnterNode  = &TestResult_enterNode;
        //# aCallback.aLeaveNode  = &TestResult_leaveNode;

        aCallback.nBits       = FileHelper::createFlags(_aOptions);

        pFunc(&aCallback);

        if (aCallback.nMagic == aCallback.nMagic2)
        {
            // ok internal simple test done.
            m_aFunctionList = m_Functions;
        }
        else
        {
            // ERROR, the function seams not to be what we thing it's to be.
            fprintf(stderr, "error: Internal check failed. Structure inconsistent, Value Magic2 != Magic.\nPlease recompile your test libraries.");
            exit(-1);
        }
    }
    else
    {
        fprintf(stderr, "warning: Function 'registerAllTestFunction' not found.\n");
        fprintf(stderr, "If you think, you are right, build testshl2 completly new.\n");
    }
}

void AutomaticRegisterHelper::CallAll(hTestResult _hResult) const
{
    // can't load the module, break the tests.
    if (m_bLoadLibraryOK == false)
    {
        return;
    }

    for (FunctionList::const_iterator it = m_aFunctionList.begin();
         it != m_aFunctionList.end();
         ++it)
    {
        FktPtr pFunc = *it;
        if (pFunc)
        {
            (pFunc)(_hResult);
        }
    }
}

<|endoftext|>