<commit_before>/* Copyright (c) 2014, Julian Straub <jstraub@csail.mit.edu>
 * Licensed under the MIT license. See the license file LICENSE.
 */
#pragma once

#include <iostream>
#include <stdint.h>
#include <vector>
#include <Eigen/Dense>

#include <cuda_runtime.h>
#include <nvidia/helper_cuda.h>
#include <jsCore/global.hpp>

using namespace Eigen;
using std::cout;
using std::endl;

void copy_gpu( double *d_from, double *d_to , uint32_t N,
    uint32_t step, uint32_t offset, uint32_t D);
void copy_gpu( float *d_from, float *d_to , uint32_t N,
    uint32_t step, uint32_t offset, uint32_t D);
void copy_gpu( uint32_t *d_from, uint32_t *d_to , uint32_t N,
    uint32_t step, uint32_t offset, uint32_t D);

namespace jsc {

template <class T>
struct GpuMatrix
{

  GpuMatrix(uint32_t rows, uint32_t cols=1);
  GpuMatrix(const Matrix<T,Dynamic,Dynamic> & data);
  GpuMatrix(const Matrix<T,Dynamic,1> & data);
  GpuMatrix(const std::vector<T> & data);
  GpuMatrix(const shared_ptr<Matrix<T,Dynamic,Dynamic> >& data);
  GpuMatrix(const shared_ptr<Matrix<T,Dynamic,1> > & data);
  ~GpuMatrix();

  void set(T A);
  void set(const T* A, uint32_t rows, uint32_t cols,
    uint32_t aPitch, uint32_t gpuPitch);
  void set(const T* A, uint32_t rows, uint32_t cols);
  void set(const std::vector<T>& A);
  void set(const Matrix<T,Dynamic,Dynamic>& A);
  void set(const Matrix<T,Dynamic,1>& A);
  void set(const shared_ptr<Matrix<T,Dynamic,Dynamic> >& A);
  void set(const shared_ptr<Matrix<T,Dynamic,1> >& A);
  void setZero();
  void setAsync(const T* A, uint32_t rows, uint32_t cols, cudaStream_t& stream);

  void get(T& a);
  void get(Matrix<T,Dynamic,Dynamic>& A);
  void get(T* A, uint32_t rows, uint32_t cols);
  void get(Matrix<T,Dynamic,1>& A);
  void get(const shared_ptr<Matrix<T,Dynamic,Dynamic> >& A);
  void get(const shared_ptr<Matrix<T,Dynamic,1> >& A);
  Matrix<T,Dynamic,Dynamic> get(void)
  {
    Matrix<T,Dynamic,Dynamic> d(rows_,cols_);
    this->get(d); return d;
  };
  void getAsync(T* A, uint32_t rows, uint32_t cols, cudaStream_t& stream);

  void copyFromGpu(T* d_A, uint32_t N, uint32_t step, uint32_t offset, uint32_t rows);

  void resize(uint32_t rows, uint32_t cols);

  uint32_t rows(){return rows_;};
  uint32_t cols(){return cols_;};
  T* data(){ assert(initialized_); return data_;};
  bool isInit(){return initialized_;};

  void print(){cout<<rows_<<";"<<cols_<<" init="<<(initialized_?'y':'n')<<endl;};

  static cudaStream_t createStream()
  {
    cudaStream_t stream;
    checkCudaErrors(cudaStreamCreate(&stream));
    return stream;
  };
  static void deleteStream(cudaStream_t& stream)
  {
    checkCudaErrors(cudaStreamDestroy(stream));
  };

private:
  uint32_t rows_;
  uint32_t cols_;
  T * data_;
  bool initialized_;
};

// --------------------------------- impl -------------------------------------

template <class T>
GpuMatrix<T>::GpuMatrix(uint32_t rows, uint32_t cols)
  : rows_(rows), cols_(cols), initialized_(false)
{
//  cout<<rows_<<"x"<<cols_<<"="<<rows_*cols_<<endl;
  checkCudaErrors(cudaMalloc((void **)&data_, rows_*cols_*sizeof(T)));
};

template <class T>
GpuMatrix<T>::GpuMatrix(const Matrix<T,Dynamic,Dynamic> & data)
  : rows_(data.rows()), cols_(data.cols()), initialized_(false)
{
//  cout<<rows_<<"x"<<cols_<<"="<<rows_*cols_<<endl;
  checkCudaErrors(cudaMalloc((void **)&data_, rows_*cols_*sizeof(T)));
  set(data);
};

template <class T>
GpuMatrix<T>::GpuMatrix(const Matrix<T,Dynamic,1> & data)
  : rows_(data.rows()), cols_(1), initialized_(false)
{
//  cout<<rows_<<"x"<<cols_<<"="<<rows_*cols_<<endl;
  checkCudaErrors(cudaMalloc((void **)&data_, rows_*cols_*sizeof(T)));
  set(data);
};

template <class T>
GpuMatrix<T>::GpuMatrix(const std::vector<T> & data)
  : rows_(data.size()), cols_(1), initialized_(false)
{
//  cout<<rows_<<"x"<<cols_<<"="<<rows_*cols_<<endl;
  checkCudaErrors(cudaMalloc((void **)&data_, rows_*cols_*sizeof(T)));
  set(data);
};

template <class T>
GpuMatrix<T>::GpuMatrix(const shared_ptr<Matrix<T,Dynamic,Dynamic> > & data)
  : rows_(data->rows()), cols_(data->cols()), initialized_(false)
{
//  cout<<rows_<<"x"<<cols_<<"="<<rows_*cols_<<endl;
  checkCudaErrors(cudaMalloc((void **)&data_, rows_*cols_*sizeof(T)));
  set(data);
};

template <class T>
GpuMatrix<T>::GpuMatrix(const shared_ptr<Matrix<T,Dynamic,1> > & data)
  : rows_(data->rows()), cols_(1), initialized_(false)
{
//  cout<<rows_<<"x"<<cols_<<"="<<rows_*cols_<<endl;
  checkCudaErrors(cudaMalloc((void **)&data_, rows_*cols_*sizeof(T)));
  set(data);
};

template <class T>
GpuMatrix<T>::~GpuMatrix()
{
  checkCudaErrors(cudaFree(data_));
};

template <class T>
void GpuMatrix<T>::resize(uint32_t rows, uint32_t cols)
{
  if((rows != rows_)||(cols != cols_))
  {
    rows_ = rows;
    cols_ = cols;
    checkCudaErrors(cudaFree(data_));
    checkCudaErrors(cudaMalloc((void **)&data_, rows_*cols_*sizeof(T)));
  }
};

//setters
template <class T>
  void GpuMatrix<T>::set(T A)
{
  resize(1,1);
  assert(1 == cols_);
  assert(1 == rows_);
  checkCudaErrors(cudaMemcpy(data_, &A, cols_*rows_* sizeof(T),
        cudaMemcpyHostToDevice));
  initialized_ = true;
};

template <class T>
void GpuMatrix<T>::set(const T* A, uint32_t rows, uint32_t cols,
    uint32_t aPitch, uint32_t gpuPitch)
{
  resize(rows,cols);
  assert(rows == rows_);
  assert(cols == cols_);
  checkCudaErrors(cudaMemcpy2D(data_, gpuPitch*sizeof(T), A,
        aPitch*sizeof(T), cols_* sizeof(T), rows_,
        cudaMemcpyHostToDevice));
  initialized_ = true;
}

template <class T>
  void GpuMatrix<T>::set(const T* A, uint32_t rows, uint32_t cols)
{
  resize(rows,cols);
  assert(rows == rows_);
  assert(cols == cols_);
  checkCudaErrors(cudaMemcpy(data_, A, cols_*rows_* sizeof(T),
        cudaMemcpyHostToDevice));
  initialized_ = true;
}
template <class T>
  void GpuMatrix<T>::set(const std::vector<T>& A)
{
  resize(A.size(),1);
  assert(A.size() == rows_);
  assert(1 == cols_);
  checkCudaErrors(cudaMemcpy(data_, A.data(), cols_*rows_* sizeof(T),
        cudaMemcpyHostToDevice));
  initialized_ = true;
}

template <class T>
void GpuMatrix<T>::set(const Matrix<T,Dynamic,Dynamic>& A)
{
  resize(A.rows(),A.cols());
  assert(A.cols() == cols_);
  assert(A.rows() == rows_);
  checkCudaErrors(cudaMemcpy(data_, A.data(), cols_*rows_* sizeof(T),
        cudaMemcpyHostToDevice));
  initialized_ = true;
};

template <class T>
void GpuMatrix<T>::set(const Matrix<T,Dynamic,1>& A)
{
  resize(A.rows(),A.cols());
  assert(A.cols() == cols_);
  assert(A.rows() == rows_);
  checkCudaErrors(cudaMemcpy(data_, A.data(), cols_*rows_* sizeof(T),
        cudaMemcpyHostToDevice));
  initialized_ = true;
};

template <class T>
void GpuMatrix<T>::set(const shared_ptr<Matrix<T,Dynamic,Dynamic> >& A)
{
  resize(A->rows(),A->cols());
  assert(A->cols() == cols_);
  assert(A->rows() == rows_);
  checkCudaErrors(cudaMemcpy(data_, A->data(), cols_*rows_* sizeof(T),
        cudaMemcpyHostToDevice));
  initialized_ = true;
};

template <class T>
void GpuMatrix<T>::set(const shared_ptr<Matrix<T,Dynamic,1> >& A)
{
  resize(A->rows(),A->cols());
  assert(A->cols() == cols_);
  assert(A->rows() == rows_);
  checkCudaErrors(cudaMemcpy(data_, A->data(), cols_*rows_* sizeof(T),
        cudaMemcpyHostToDevice));
  initialized_ = true;
};

template <class T>
void GpuMatrix<T>::setZero()
{
  Matrix<T,Dynamic,Dynamic> A = Matrix<T,Dynamic,Dynamic>::Zero(rows_,cols_);
  checkCudaErrors(cudaMemcpy(data_, A.data(), cols_*rows_* sizeof(T),
        cudaMemcpyHostToDevice));
  initialized_ = true;
};

 // getters
template <class T>
  void GpuMatrix<T>::get(T& a)
{
  assert(1 == cols_);
  assert(1 == rows_);
  checkCudaErrors(cudaMemcpy(&a,data_, cols_*rows_*sizeof(T),
                cudaMemcpyDeviceToHost));
}

template <class T>
void GpuMatrix<T>::get(T* A, uint32_t rows, uint32_t cols)
{
  assert(cols == cols_);
  assert(rows == rows_);
  checkCudaErrors(cudaMemcpy(A,data_, cols_*rows_*sizeof(T),
                cudaMemcpyDeviceToHost));
};

template <class T>
void GpuMatrix<T>::get(Matrix<T,Dynamic,Dynamic>& A)
{
  A.resize(rows_,cols_);
  assert(A.cols() == cols_);
  assert(A.rows() == rows_);
  checkCudaErrors(cudaMemcpy(A.data(),data_, cols_*rows_*sizeof(T),
                cudaMemcpyDeviceToHost));
};

template <class T>
void GpuMatrix<T>::get(Matrix<T,Dynamic,1>& A)
{
  A.resize(rows_);
  assert(A.cols() == cols_);
  assert(A.rows() == rows_);
  checkCudaErrors(cudaMemcpy(A.data(),data_, cols_*rows_*sizeof(T),
                cudaMemcpyDeviceToHost));
};

template <class T>
void GpuMatrix<T>::get(const shared_ptr<Matrix<T,Dynamic,Dynamic> >& A)
{
  A->resize(rows_,cols_);
  assert(A->cols() == cols_);
  assert(A->rows() == rows_);
  checkCudaErrors(cudaMemcpy(A->data(),data_, cols_*rows_*sizeof(T),
                cudaMemcpyDeviceToHost));
};

template <class T>
void GpuMatrix<T>::get(const shared_ptr<Matrix<T,Dynamic,1> >& A)
{
  A->resize(rows_);
  assert(A->cols() == cols_);
  assert(A->rows() == rows_);
  checkCudaErrors(cudaMemcpy(A->data(),data_, cols_*rows_*sizeof(T),
                cudaMemcpyDeviceToHost));
};

template <class T>
void GpuMatrix<T>::copyFromGpu(T* d_A, uint32_t N, uint32_t step, uint32_t offset, uint32_t rows)
{
  // input d_A is N long and step per element
  // output (this class) is N long and rows per element
  resize(rows,N);
//  checkCudaErrors(cudaMemcpy(A->data(),data_, cols_*rows_*sizeof(T),
//                        cudaMemcpyDeviceToHost));
  if(step != rows || offset!=0)
    copy_gpu(d_A, data_, N, step, offset, rows);
  else{
    // can just do simple mem copy
    checkCudaErrors(cudaMemcpy(data_, d_A, cols_*rows_*sizeof(T),
                cudaMemcpyDeviceToDevice));
  }

  initialized_ = true;
};

template <class T>
void GpuMatrix<T>::setAsync(const T* A, uint32_t rows, uint32_t cols, cudaStream_t& stream)
{
  resize(rows,cols);
  assert(rows == rows_);
  assert(cols == cols_);
  checkCudaErrors(cudaMemcpyAsync(data_, A, cols_*rows_* sizeof(T),
        cudaMemcpyHostToDevice,stream));
  initialized_ = true;
};

template <class T>
void GpuMatrix<T>::getAsync(T* A, uint32_t rows, uint32_t cols, cudaStream_t& stream)
{
  assert(cols == cols_);
  assert(rows == rows_);
  checkCudaErrors(cudaMemcpyAsync(A,data_, cols_*rows_*sizeof(T),
                cudaMemcpyDeviceToHost,stream));
};

}
<commit_msg>setOnes<commit_after>/* Copyright (c) 2014, Julian Straub <jstraub@csail.mit.edu>
 * Licensed under the MIT license. See the license file LICENSE.
 */
#pragma once

#include <iostream>
#include <stdint.h>
#include <vector>
#include <Eigen/Dense>

#include <cuda_runtime.h>
#include <nvidia/helper_cuda.h>
#include <jsCore/global.hpp>

using namespace Eigen;
using std::cout;
using std::endl;

void copy_gpu( double *d_from, double *d_to , uint32_t N,
    uint32_t step, uint32_t offset, uint32_t D);
void copy_gpu( float *d_from, float *d_to , uint32_t N,
    uint32_t step, uint32_t offset, uint32_t D);
void copy_gpu( uint32_t *d_from, uint32_t *d_to , uint32_t N,
    uint32_t step, uint32_t offset, uint32_t D);

namespace jsc {

template <class T>
struct GpuMatrix
{

  GpuMatrix(uint32_t rows, uint32_t cols=1);
  GpuMatrix(const Matrix<T,Dynamic,Dynamic> & data);
  GpuMatrix(const Matrix<T,Dynamic,1> & data);
  GpuMatrix(const std::vector<T> & data);
  GpuMatrix(const shared_ptr<Matrix<T,Dynamic,Dynamic> >& data);
  GpuMatrix(const shared_ptr<Matrix<T,Dynamic,1> > & data);
  ~GpuMatrix();

  void set(T A);
  void set(const T* A, uint32_t rows, uint32_t cols,
    uint32_t aPitch, uint32_t gpuPitch);
  void set(const T* A, uint32_t rows, uint32_t cols);
  void set(const std::vector<T>& A);
  void set(const Matrix<T,Dynamic,Dynamic>& A);
  void set(const Matrix<T,Dynamic,1>& A);
  void set(const shared_ptr<Matrix<T,Dynamic,Dynamic> >& A);
  void set(const shared_ptr<Matrix<T,Dynamic,1> >& A);
  void setZero();
  void setOnes();
  void setAsync(const T* A, uint32_t rows, uint32_t cols, cudaStream_t& stream);

  void get(T& a);
  void get(Matrix<T,Dynamic,Dynamic>& A);
  void get(T* A, uint32_t rows, uint32_t cols);
  void get(Matrix<T,Dynamic,1>& A);
  void get(const shared_ptr<Matrix<T,Dynamic,Dynamic> >& A);
  void get(const shared_ptr<Matrix<T,Dynamic,1> >& A);
  Matrix<T,Dynamic,Dynamic> get(void)
  {
    Matrix<T,Dynamic,Dynamic> d(rows_,cols_);
    this->get(d); return d;
  };
  void getAsync(T* A, uint32_t rows, uint32_t cols, cudaStream_t& stream);

  void copyFromGpu(T* d_A, uint32_t N, uint32_t step, uint32_t offset, uint32_t rows);

  void resize(uint32_t rows, uint32_t cols);

  uint32_t rows(){return rows_;};
  uint32_t cols(){return cols_;};
  T* data(){ assert(initialized_); return data_;};
  bool isInit(){return initialized_;};

  void print(){cout<<rows_<<";"<<cols_<<" init="<<(initialized_?'y':'n')<<endl;};

  static cudaStream_t createStream()
  {
    cudaStream_t stream;
    checkCudaErrors(cudaStreamCreate(&stream));
    return stream;
  };
  static void deleteStream(cudaStream_t& stream)
  {
    checkCudaErrors(cudaStreamDestroy(stream));
  };

private:
  uint32_t rows_;
  uint32_t cols_;
  T * data_;
  bool initialized_;
};

// --------------------------------- impl -------------------------------------

template <class T>
GpuMatrix<T>::GpuMatrix(uint32_t rows, uint32_t cols)
  : rows_(rows), cols_(cols), initialized_(false)
{
//  cout<<rows_<<"x"<<cols_<<"="<<rows_*cols_<<endl;
  checkCudaErrors(cudaMalloc((void **)&data_, rows_*cols_*sizeof(T)));
};

template <class T>
GpuMatrix<T>::GpuMatrix(const Matrix<T,Dynamic,Dynamic> & data)
  : rows_(data.rows()), cols_(data.cols()), initialized_(false)
{
//  cout<<rows_<<"x"<<cols_<<"="<<rows_*cols_<<endl;
  checkCudaErrors(cudaMalloc((void **)&data_, rows_*cols_*sizeof(T)));
  set(data);
};

template <class T>
GpuMatrix<T>::GpuMatrix(const Matrix<T,Dynamic,1> & data)
  : rows_(data.rows()), cols_(1), initialized_(false)
{
//  cout<<rows_<<"x"<<cols_<<"="<<rows_*cols_<<endl;
  checkCudaErrors(cudaMalloc((void **)&data_, rows_*cols_*sizeof(T)));
  set(data);
};

template <class T>
GpuMatrix<T>::GpuMatrix(const std::vector<T> & data)
  : rows_(data.size()), cols_(1), initialized_(false)
{
//  cout<<rows_<<"x"<<cols_<<"="<<rows_*cols_<<endl;
  checkCudaErrors(cudaMalloc((void **)&data_, rows_*cols_*sizeof(T)));
  set(data);
};

template <class T>
GpuMatrix<T>::GpuMatrix(const shared_ptr<Matrix<T,Dynamic,Dynamic> > & data)
  : rows_(data->rows()), cols_(data->cols()), initialized_(false)
{
//  cout<<rows_<<"x"<<cols_<<"="<<rows_*cols_<<endl;
  checkCudaErrors(cudaMalloc((void **)&data_, rows_*cols_*sizeof(T)));
  set(data);
};

template <class T>
GpuMatrix<T>::GpuMatrix(const shared_ptr<Matrix<T,Dynamic,1> > & data)
  : rows_(data->rows()), cols_(1), initialized_(false)
{
//  cout<<rows_<<"x"<<cols_<<"="<<rows_*cols_<<endl;
  checkCudaErrors(cudaMalloc((void **)&data_, rows_*cols_*sizeof(T)));
  set(data);
};

template <class T>
GpuMatrix<T>::~GpuMatrix()
{
  checkCudaErrors(cudaFree(data_));
};

template <class T>
void GpuMatrix<T>::resize(uint32_t rows, uint32_t cols)
{
  if((rows != rows_)||(cols != cols_))
  {
    rows_ = rows;
    cols_ = cols;
    checkCudaErrors(cudaFree(data_));
    checkCudaErrors(cudaMalloc((void **)&data_, rows_*cols_*sizeof(T)));
  }
};

//setters
template <class T>
  void GpuMatrix<T>::set(T A)
{
  resize(1,1);
  assert(1 == cols_);
  assert(1 == rows_);
  checkCudaErrors(cudaMemcpy(data_, &A, cols_*rows_* sizeof(T),
        cudaMemcpyHostToDevice));
  initialized_ = true;
};

template <class T>
void GpuMatrix<T>::set(const T* A, uint32_t rows, uint32_t cols,
    uint32_t aPitch, uint32_t gpuPitch)
{
  resize(rows,cols);
  assert(rows == rows_);
  assert(cols == cols_);
  checkCudaErrors(cudaMemcpy2D(data_, gpuPitch*sizeof(T), A,
        aPitch*sizeof(T), cols_* sizeof(T), rows_,
        cudaMemcpyHostToDevice));
  initialized_ = true;
}

template <class T>
  void GpuMatrix<T>::set(const T* A, uint32_t rows, uint32_t cols)
{
  resize(rows,cols);
  assert(rows == rows_);
  assert(cols == cols_);
  checkCudaErrors(cudaMemcpy(data_, A, cols_*rows_* sizeof(T),
        cudaMemcpyHostToDevice));
  initialized_ = true;
}
template <class T>
  void GpuMatrix<T>::set(const std::vector<T>& A)
{
  resize(A.size(),1);
  assert(A.size() == rows_);
  assert(1 == cols_);
  checkCudaErrors(cudaMemcpy(data_, A.data(), cols_*rows_* sizeof(T),
        cudaMemcpyHostToDevice));
  initialized_ = true;
}

template <class T>
void GpuMatrix<T>::set(const Matrix<T,Dynamic,Dynamic>& A)
{
  resize(A.rows(),A.cols());
  assert(A.cols() == cols_);
  assert(A.rows() == rows_);
  checkCudaErrors(cudaMemcpy(data_, A.data(), cols_*rows_* sizeof(T),
        cudaMemcpyHostToDevice));
  initialized_ = true;
};

template <class T>
void GpuMatrix<T>::set(const Matrix<T,Dynamic,1>& A)
{
  resize(A.rows(),A.cols());
  assert(A.cols() == cols_);
  assert(A.rows() == rows_);
  checkCudaErrors(cudaMemcpy(data_, A.data(), cols_*rows_* sizeof(T),
        cudaMemcpyHostToDevice));
  initialized_ = true;
};

template <class T>
void GpuMatrix<T>::set(const shared_ptr<Matrix<T,Dynamic,Dynamic> >& A)
{
  resize(A->rows(),A->cols());
  assert(A->cols() == cols_);
  assert(A->rows() == rows_);
  checkCudaErrors(cudaMemcpy(data_, A->data(), cols_*rows_* sizeof(T),
        cudaMemcpyHostToDevice));
  initialized_ = true;
};

template <class T>
void GpuMatrix<T>::set(const shared_ptr<Matrix<T,Dynamic,1> >& A)
{
  resize(A->rows(),A->cols());
  assert(A->cols() == cols_);
  assert(A->rows() == rows_);
  checkCudaErrors(cudaMemcpy(data_, A->data(), cols_*rows_* sizeof(T),
        cudaMemcpyHostToDevice));
  initialized_ = true;
};

template <class T>
void GpuMatrix<T>::setZero()
{
  Matrix<T,Dynamic,Dynamic> A = Matrix<T,Dynamic,Dynamic>::Zero(rows_,cols_);
  checkCudaErrors(cudaMemcpy(data_, A.data(), cols_*rows_* sizeof(T),
        cudaMemcpyHostToDevice));
  initialized_ = true;
};

template <class T>
void GpuMatrix<T>::setOnes()
{
  Matrix<T,Dynamic,Dynamic> A = Matrix<T,Dynamic,Dynamic>::Ones(rows_,cols_);
  checkCudaErrors(cudaMemcpy(data_, A.data(), cols_*rows_* sizeof(T),
        cudaMemcpyHostToDevice));
  initialized_ = true;
};

 // getters
template <class T>
  void GpuMatrix<T>::get(T& a)
{
  assert(1 == cols_);
  assert(1 == rows_);
  checkCudaErrors(cudaMemcpy(&a,data_, cols_*rows_*sizeof(T),
                cudaMemcpyDeviceToHost));
}

template <class T>
void GpuMatrix<T>::get(T* A, uint32_t rows, uint32_t cols)
{
  assert(cols == cols_);
  assert(rows == rows_);
  checkCudaErrors(cudaMemcpy(A,data_, cols_*rows_*sizeof(T),
                cudaMemcpyDeviceToHost));
};

template <class T>
void GpuMatrix<T>::get(Matrix<T,Dynamic,Dynamic>& A)
{
  A.resize(rows_,cols_);
  assert(A.cols() == cols_);
  assert(A.rows() == rows_);
  checkCudaErrors(cudaMemcpy(A.data(),data_, cols_*rows_*sizeof(T),
                cudaMemcpyDeviceToHost));
};

template <class T>
void GpuMatrix<T>::get(Matrix<T,Dynamic,1>& A)
{
  A.resize(rows_);
  assert(A.cols() == cols_);
  assert(A.rows() == rows_);
  checkCudaErrors(cudaMemcpy(A.data(),data_, cols_*rows_*sizeof(T),
                cudaMemcpyDeviceToHost));
};

template <class T>
void GpuMatrix<T>::get(const shared_ptr<Matrix<T,Dynamic,Dynamic> >& A)
{
  A->resize(rows_,cols_);
  assert(A->cols() == cols_);
  assert(A->rows() == rows_);
  checkCudaErrors(cudaMemcpy(A->data(),data_, cols_*rows_*sizeof(T),
                cudaMemcpyDeviceToHost));
};

template <class T>
void GpuMatrix<T>::get(const shared_ptr<Matrix<T,Dynamic,1> >& A)
{
  A->resize(rows_);
  assert(A->cols() == cols_);
  assert(A->rows() == rows_);
  checkCudaErrors(cudaMemcpy(A->data(),data_, cols_*rows_*sizeof(T),
                cudaMemcpyDeviceToHost));
};

template <class T>
void GpuMatrix<T>::copyFromGpu(T* d_A, uint32_t N, uint32_t step, uint32_t offset, uint32_t rows)
{
  // input d_A is N long and step per element
  // output (this class) is N long and rows per element
  resize(rows,N);
//  checkCudaErrors(cudaMemcpy(A->data(),data_, cols_*rows_*sizeof(T),
//                        cudaMemcpyDeviceToHost));
  if(step != rows || offset!=0)
    copy_gpu(d_A, data_, N, step, offset, rows);
  else{
    // can just do simple mem copy
    checkCudaErrors(cudaMemcpy(data_, d_A, cols_*rows_*sizeof(T),
                cudaMemcpyDeviceToDevice));
  }

  initialized_ = true;
};

template <class T>
void GpuMatrix<T>::setAsync(const T* A, uint32_t rows, uint32_t cols, cudaStream_t& stream)
{
  resize(rows,cols);
  assert(rows == rows_);
  assert(cols == cols_);
  checkCudaErrors(cudaMemcpyAsync(data_, A, cols_*rows_* sizeof(T),
        cudaMemcpyHostToDevice,stream));
  initialized_ = true;
};

template <class T>
void GpuMatrix<T>::getAsync(T* A, uint32_t rows, uint32_t cols, cudaStream_t& stream)
{
  assert(cols == cols_);
  assert(rows == rows_);
  checkCudaErrors(cudaMemcpyAsync(A,data_, cols_*rows_*sizeof(T),
                cudaMemcpyDeviceToHost,stream));
};

}
<|endoftext|>


<commit_before>//
// Copyright (C) Zbigniew Zagorski <z.zagorski@gmail.com>,
// licensed to the public under the terms of the GNU GPL (>= 2)
// see the file COPYING for details
// I.e., do what you like, but keep copyright and there's NO WARRANTY.
//

#include "tinfra/test.h"

#include "tinfra/fs.h"
#include "tinfra/path.h"
#include "tinfra/fmt.h"

#include <iostream>

#include <unittest++/UnitTest++.h>
#include <unittest++/TestReporter.h>
#include <unittest++/TestDetails.h>
#include <unittest++/TestResults.h>
#include <unittest++/TestReporter.h>

#include <stdio.h> // screw cxxx headers because they are incompatible
#include <stdarg.h>

#ifdef _WIN32
#include <windows.h>
#endif

namespace tinfra {
namespace test {

using std::string;
using std::cout;
using std::cin;
using std::endl;

#ifdef SRCDIR
static std::string top_srcdir = SRCDIR;
#else
static std::string top_srcdir = ".";
#endif

TempTestLocation::TempTestLocation(std::string const& name)
    : name_(name), orig_pwd_(""), tmp_path_("")
{
    init();
}

void TempTestLocation::init()
{
    tmp_path_ = path::tmppath();
    fs::mkdir(tmp_path_.c_str());
    if( name_.size() > 0 ) {
        string real_path = path::join(top_srcdir, name_);
        if( !path::exists(real_path) ) {
            throw tinfra::generic_exception(fmt("unable to find test resource %s (%s)") % name_ % real_path);
        }
        string name_in_tmp_ = path::join(tmp_path_, name_);
        fs::recursive_copy(real_path, name_in_tmp_);
    }
    orig_pwd_ = fs::pwd();
    fs::cd(tmp_path_.c_str());
}
TempTestLocation::~TempTestLocation()
{
    fs::cd(orig_pwd_.c_str());
    if( path::exists(tmp_path_) ) {
        fs::recursive_rm(tmp_path_.c_str());
    }
}

std::string TempTestLocation::getPath() const {
    if( name_.size() > 0 )
        return name_;
    else
        return ".";
}

void TempTestLocation::setTestResourcesDir(std::string const& x)
{
    top_srcdir = x;
}

void user_wait(const char* prompt)
{
    if( prompt ) {
        cout << prompt << " ";
    }
    cout << "(waiting for enter)";
    cout.flush();
    std::string s;
    std::getline(cin, s);
}

static void out(const char* message, ...)
{
    va_list ap;
    va_start(ap, message);
#ifdef _WIN32
    char buf[2048];
    vsprintf(buf,message, ap);
    printf("%s",buf);
    OutputDebugString(buf);
#else
    vprintf(message, ap);
#endif
    va_end(ap);
}

class TinfraTestReporter: public UnitTest::TestReporter {
public:
    void ReportFailure(UnitTest::TestDetails const& details, char const* failure)
    {

#ifdef _MSC_VER
        char const* const errorFormat = "%s(%d): error: FAILURE in %s: %s\n";
#else   // only MSC has weird message format, rest use name:line: message (AFAIK)
        char const* const errorFormat = "%s:%d: error: FAILURE in %s: %s\n";
#endif
        out(errorFormat, details.filename, details.lineNumber, details.testName, failure);
    }

    void ReportTestStart(UnitTest::TestDetails const& test)
    {
        if( strcmp("DefaultSuite",test.suiteName) != 0 ) {
            out("TEST %s::%s\n", test.suiteName, test.testName);
        } else {
            out("TEST %s\n", test.testName);
        }
    }

    void ReportTestFinish(UnitTest::TestDetails const& /*test*/, float)
    {
    }

    void ReportSummary(int totalTestCount, int failedTestCount,
                       int failureCount, float secondsElapsed)
    {
        if (failureCount > 0)
            out("FAILURE: %d out of %d tests failed (%d failures).\n", failedTestCount, totalTestCount, failureCount);
        else
            out("Success: %d tests passed.\n", totalTestCount);
        out("Test time: %.2f seconds.\n", secondsElapsed);
    }
};

typedef std::vector<std::string> test_name_list;

class test_name_matcher {
    test_name_list& names_;
public:
    test_name_matcher(test_name_list& n): names_(n) {}

    bool operator()(const UnitTest::Test* const test) const
    {
        std::string test_name = test->m_details.testName;
        return find(names_.begin(), names_.end(), test_name) != names_.end();
    }
};

int test_main(int argc, char** argv)
{
    TinfraTestReporter reporter;
    UnitTest::TestRunner runner(reporter);
    if( argc > 1 ) {
        test_name_list test_names(argv+1, argv+argc);
        test_name_matcher predicate(test_names);

        return runner.RunTestsIf(UnitTest::Test::GetTestList(), 0, predicate, 0);
    } else {
        return runner.RunTestsIf(UnitTest::Test::GetTestList(), 0, UnitTest::True(), 0);
    }
}

} } // end namespace tinfra::test

// jedit: :tabSize=8:indentSize=4:noTabs=true:mode=c++

<commit_msg> * test.cpp (test_main): don't treat args starting with - as test names<commit_after>//
// Copyright (C) Zbigniew Zagorski <z.zagorski@gmail.com>,
// licensed to the public under the terms of the GNU GPL (>= 2)
// see the file COPYING for details
// I.e., do what you like, but keep copyright and there's NO WARRANTY.
//

#include "tinfra/test.h"

#include "tinfra/fs.h"
#include "tinfra/path.h"
#include "tinfra/fmt.h"

#include <iostream>

#include <unittest++/UnitTest++.h>
#include <unittest++/TestReporter.h>
#include <unittest++/TestDetails.h>
#include <unittest++/TestResults.h>
#include <unittest++/TestReporter.h>

#include <stdio.h> // screw cxxx headers because they are incompatible
#include <stdarg.h>

#ifdef _WIN32
#include <windows.h>
#endif

namespace tinfra {
namespace test {

using std::string;
using std::cout;
using std::cin;
using std::endl;

#ifdef SRCDIR
static std::string top_srcdir = SRCDIR;
#else
static std::string top_srcdir = ".";
#endif

TempTestLocation::TempTestLocation(std::string const& name)
    : name_(name), orig_pwd_(""), tmp_path_("")
{
    init();
}

void TempTestLocation::init()
{
    tmp_path_ = path::tmppath();
    fs::mkdir(tmp_path_.c_str());
    if( name_.size() > 0 ) {
        string real_path = path::join(top_srcdir, name_);
        if( !path::exists(real_path) ) {
            throw tinfra::generic_exception(fmt("unable to find test resource %s (%s)") % name_ % real_path);
        }
        string name_in_tmp_ = path::join(tmp_path_, name_);
        fs::recursive_copy(real_path, name_in_tmp_);
    }
    orig_pwd_ = fs::pwd();
    fs::cd(tmp_path_.c_str());
}
TempTestLocation::~TempTestLocation()
{
    fs::cd(orig_pwd_.c_str());
    if( path::exists(tmp_path_) ) {
        fs::recursive_rm(tmp_path_.c_str());
    }
}

std::string TempTestLocation::getPath() const {
    if( name_.size() > 0 )
        return name_;
    else
        return ".";
}

void TempTestLocation::setTestResourcesDir(std::string const& x)
{
    top_srcdir = x;
}

void user_wait(const char* prompt)
{
    if( prompt ) {
        cout << prompt << " ";
    }
    cout << "(waiting for enter)";
    cout.flush();
    std::string s;
    std::getline(cin, s);
}

static void out(const char* message, ...)
{
    va_list ap;
    va_start(ap, message);
#ifdef _WIN32
    char buf[2048];
    vsprintf(buf,message, ap);
    printf("%s",buf);
    OutputDebugString(buf);
#else
    vprintf(message, ap);
#endif
    va_end(ap);
}

class TinfraTestReporter: public UnitTest::TestReporter {
public:
    void ReportFailure(UnitTest::TestDetails const& details, char const* failure)
    {

#ifdef _MSC_VER
        char const* const errorFormat = "%s(%d): error: FAILURE in %s: %s\n";
#else   // only MSC has weird message format, rest use name:line: message (AFAIK)
        char const* const errorFormat = "%s:%d: error: FAILURE in %s: %s\n";
#endif
        out(errorFormat, details.filename, details.lineNumber, details.testName, failure);
    }

    void ReportTestStart(UnitTest::TestDetails const& test)
    {
        if( strcmp("DefaultSuite",test.suiteName) != 0 ) {
            out("TEST %s::%s\n", test.suiteName, test.testName);
        } else {
            out("TEST %s\n", test.testName);
        }
    }

    void ReportTestFinish(UnitTest::TestDetails const& /*test*/, float)
    {
    }

    void ReportSummary(int totalTestCount, int failedTestCount,
                       int failureCount, float secondsElapsed)
    {
        if (failureCount > 0)
            out("FAILURE: %d out of %d tests failed (%d failures).\n", failedTestCount, totalTestCount, failureCount);
        else
            out("Success: %d tests passed.\n", totalTestCount);
        out("Test time: %.2f seconds.\n", secondsElapsed);
    }
};

typedef std::vector<std::string> test_name_list;

class test_name_matcher {
    test_name_list& names_;
public:
    test_name_matcher(test_name_list& n): names_(n) {}

    bool operator()(const UnitTest::Test* const test) const
    {
        std::string test_name = test->m_details.testName;
        return find(names_.begin(), names_.end(), test_name) != names_.end();
    }
};

int test_main(int argc, char** argv)
{
    TinfraTestReporter reporter;
    UnitTest::TestRunner runner(reporter);
    test_name_list test_names;
    for(int i = 1; i < argc; ++i ) {
        if( strncmp(argv[i],"-",1) != 0 )
            test_names.push_back(argv[i]);
    }
    if( ! test_names.empty() ) {
        test_name_matcher predicate(test_names);
        return runner.RunTestsIf(UnitTest::Test::GetTestList(), 0, predicate, 0);
    } else {
        return runner.RunTestsIf(UnitTest::Test::GetTestList(), 0, UnitTest::True(), 0);
    }
}

} } // end namespace tinfra::test

// jedit: :tabSize=8:indentSize=4:noTabs=true:mode=c++

<|endoftext|>


<commit_before>#pragma once

#include "container.hpp"

namespace kgr {
namespace detail {

template<typename CRTP, template<typename> class Map>
struct InvokerBase {
	template<typename F, typename... Args>
	detail::function_result_t<typename std::decay<F>::type> operator()(F&& f, Args&&... args) {
		return static_cast<CRTP*>(this)->_container.template invoke<Map>(std::forward<F>(f), std::forward<Args>(args)...);
	}
};

template<typename CRTP, typename T>
struct GeneratorBase {
	template<typename... Args>
	ServiceType<T> operator()(Args&& ...args) {
		return static_cast<CRTP*>(this)->_container.template service<T>(std::forward<Args>(args)...);
	}
};

template<typename T>
struct LazyHelper {
protected:
	using type = T;
	using ref = T&;
	using ptr = T*;

	T&& assign(T&& service) {
		return std::move(service);
	}

	T& value(T& service) {
		return service;
	}
};

template<typename T>
struct LazyHelper<T&> {
protected:
	using type = T*;
	using ref = T&;
	using ptr = T*;

	T* assign(T& service) {
		return &service;
	}

	T& value(T* service) {
		return *service;
	}
};

template<typename CRTP, typename T>
struct LazyBase : LazyHelper<ServiceType<T>> {
private:
	using typename detail::LazyHelper<ServiceType<T>>::type;
	using typename detail::LazyHelper<ServiceType<T>>::ref;
	using typename detail::LazyHelper<ServiceType<T>>::ptr;

public:
	LazyBase() = default;
	LazyBase(LazyBase&& other) {
		if (other._initialized) {
			emplace(std::move(other.data()));
		}
	}

	LazyBase& operator=(LazyBase&& other) {
		if (other._initialized) {
			emplace(std::move(other.data()));
		}
		return *this;
	}

	LazyBase(const LazyBase& other) {
		if (other._initialized) {
			emplace(other.data());
		}
	}

	LazyBase& operator=(const LazyBase& other) {
		if (other._initialized) {
			emplace(other.data());
		}
		return *this;
	}

	~LazyBase() {
		if (_initialized) {
			reinterpret_cast<type*>(&_service)->~type();
		}
	}

	ref operator*() {
		return get();
	}

	ptr operator->() {
		return &get();
	}

	ref get() {
		if (!_initialized) {
			emplace(this->assign(static_cast<CRTP*>(this)->_container.template service<T>()));
		}

		return this->value(*reinterpret_cast<type*>(&_service));
	}

private:
	type data() {
		return *reinterpret_cast<type*>(&_service);
	}

	template<typename... Args>
	void emplace(Args&&... args) {
		if (_initialized) {
			reinterpret_cast<type*>(&_service)->~type();
		}

		_initialized = true;
		new (&_service) type(std::forward<Args>(args)...);
	}

	bool _initialized = false;
	typename std::aligned_storage<sizeof(type), alignof(type)>::type _service;
};

} // namespace detail

template<template<typename> class Map>
struct Invoker : detail::InvokerBase<Invoker<Map>, Map> {
	explicit Invoker(Container& container) : _container{container} {}

private:
	friend struct detail::InvokerBase<Invoker<Map>, Map>;
	kgr::Container& _container;
};

template<template<typename> class Map>
struct ForkedInvoker : detail::InvokerBase<ForkedInvoker<Map>, Map> {
	explicit ForkedInvoker(Container container) : _container{std::move(container)} {}

private:
	friend struct detail::InvokerBase<ForkedInvoker<Map>, Map>;
	kgr::Container _container;
};

template<typename T>
struct Generator : detail::GeneratorBase<Generator<T>, T> {
	explicit Generator(Container& container) : _container{container} {}

private:
	friend struct detail::GeneratorBase<Generator<T>, T>;
	kgr::Container& _container;
};

template<typename T>
struct ForkedGenerator : detail::GeneratorBase<ForkedGenerator<T>, T> {
	explicit ForkedGenerator(Container container) : _container{std::move(container)} {}

private:
	friend struct detail::GeneratorBase<ForkedGenerator<T>, T>;
	kgr::Container _container;
};

template<typename T>
struct Lazy : detail::LazyBase<Lazy<T>, T> {
	explicit Lazy(kgr::Container& container) : _container{container} {}

private:
	friend struct detail::LazyBase<Lazy<T>, T>;
	kgr::Container& _container;
};

template<typename T>
struct ForkedLazy : detail::LazyBase<ForkedLazy<T>, T> {
	explicit ForkedLazy(kgr::Container container) : _container{std::move(container)} {}

private:
	friend struct detail::LazyBase<ForkedLazy<T>, T>;
	kgr::Container _container;
};

} // namespace kgr
<commit_msg>small cleanups in Lazy<commit_after>#pragma once

#include "container.hpp"

namespace kgr {
namespace detail {

template<typename CRTP, template<typename> class Map>
struct InvokerBase {
	template<typename F, typename... Args>
	detail::function_result_t<typename std::decay<F>::type> operator()(F&& f, Args&&... args) {
		return static_cast<CRTP*>(this)->_container.template invoke<Map>(std::forward<F>(f), std::forward<Args>(args)...);
	}
};

template<typename CRTP, typename T>
struct GeneratorBase {
	template<typename... Args>
	ServiceType<T> operator()(Args&& ...args) {
		return static_cast<CRTP*>(this)->_container.template service<T>(std::forward<Args>(args)...);
	}
};

template<typename T>
struct LazyHelper {
protected:
	using type = T;
	using ref = T&;
	using ptr = T*;

	T&& assign(T&& service) {
		return std::move(service);
	}

	T& value(T& service) {
		return service;
	}
};

template<typename T>
struct LazyHelper<T&> {
protected:
	using type = T*;
	using ref = T&;
	using ptr = T*;

	T* assign(T& service) {
		return &service;
	}

	T& value(T* service) {
		return *service;
	}
};

template<typename CRTP, typename T>
struct LazyBase : LazyHelper<ServiceType<T>> {
private:
	using typename detail::LazyHelper<ServiceType<T>>::type;
	using typename detail::LazyHelper<ServiceType<T>>::ref;
	using typename detail::LazyHelper<ServiceType<T>>::ptr;

public:
	LazyBase() = default;
	LazyBase(LazyBase&& other) {
		if (other._initialized) {
			emplace(std::move(other.data()));
		}
	}

	LazyBase& operator=(LazyBase&& other) {
		if (other._initialized) {
			emplace(std::move(other.data()));
		}
		return *this;
	}

	LazyBase(const LazyBase& other) {
		if (other._initialized) {
			emplace(other.data());
		}
	}

	LazyBase& operator=(const LazyBase& other) {
		if (other._initialized) {
			emplace(other.data());
		}
		return *this;
	}

	~LazyBase() {
		if (_initialized) {
			data().~type();
		}
	}

	ref operator*() {
		return get();
	}

	ptr operator->() {
		return &get();
	}

	ref get() {
		if (!_initialized) {
			emplace(this->assign(static_cast<CRTP*>(this)->_container.template service<T>()));
		}

		return this->value(data());
	}

private:
	type& data() {
		return *reinterpret_cast<type*>(&_service);
	}

	template<typename... Args>
	void emplace(Args&&... args) {
		if (_initialized) {
			data().~type();
		}

		_initialized = true;
		new (&_service) type(std::forward<Args>(args)...);
	}

	bool _initialized = false;
	typename std::aligned_storage<sizeof(type), alignof(type)>::type _service;
};

} // namespace detail

template<template<typename> class Map>
struct Invoker : detail::InvokerBase<Invoker<Map>, Map> {
	explicit Invoker(Container& container) : _container{container} {}

private:
	friend struct detail::InvokerBase<Invoker<Map>, Map>;
	kgr::Container& _container;
};

template<template<typename> class Map>
struct ForkedInvoker : detail::InvokerBase<ForkedInvoker<Map>, Map> {
	explicit ForkedInvoker(Container container) : _container{std::move(container)} {}

private:
	friend struct detail::InvokerBase<ForkedInvoker<Map>, Map>;
	kgr::Container _container;
};

template<typename T>
struct Generator : detail::GeneratorBase<Generator<T>, T> {
	explicit Generator(Container& container) : _container{container} {}

private:
	friend struct detail::GeneratorBase<Generator<T>, T>;
	kgr::Container& _container;
};

template<typename T>
struct ForkedGenerator : detail::GeneratorBase<ForkedGenerator<T>, T> {
	explicit ForkedGenerator(Container container) : _container{std::move(container)} {}

private:
	friend struct detail::GeneratorBase<ForkedGenerator<T>, T>;
	kgr::Container _container;
};

template<typename T>
struct Lazy : detail::LazyBase<Lazy<T>, T> {
	explicit Lazy(kgr::Container& container) : _container{container} {}

private:
	friend struct detail::LazyBase<Lazy<T>, T>;
	kgr::Container& _container;
};

template<typename T>
struct ForkedLazy : detail::LazyBase<ForkedLazy<T>, T> {
	explicit ForkedLazy(kgr::Container container) : _container{std::move(container)} {}

private:
	friend struct detail::LazyBase<ForkedLazy<T>, T>;
	kgr::Container _container;
};

} // namespace kgr
<|endoftext|>


<commit_before>/*

Copyright (c) 2003-2014, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 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 TORRENT_DEBUG_HPP_INCLUDED
#define TORRENT_DEBUG_HPP_INCLUDED

#include "libtorrent/config.hpp"

#if TORRENT_USE_ASSERTS && defined BOOST_HAS_PTHREADS
#include <pthread.h>
#endif

#if defined TORRENT_ASIO_DEBUGGING

#include "libtorrent/assert.hpp"
#include "libtorrent/thread.hpp"
#include "libtorrent/time.hpp"

#include <map>
#include <cstring>
#include <deque>

#ifdef __MACH__
#include <mach/task_info.h>
#include <mach/task.h>
#include <mach/mach_init.h>
#endif

std::string demangle(char const* name);

namespace libtorrent
{
	struct async_t
	{
		async_t() : refs(0) {}
		std::string stack;
		int refs;
	};

	// defined in session_impl.cpp
	extern std::map<std::string, async_t> _async_ops;
	extern int _async_ops_nthreads;
	extern mutex _async_ops_mutex;

	// timestamp -> operation
	struct wakeup_t
	{
		ptime timestamp;
		boost::uint64_t context_switches;
		char const* operation;
	};
	extern std::deque<wakeup_t> _wakeups;

	inline bool has_outstanding_async(char const* name)
	{
		mutex::scoped_lock l(_async_ops_mutex);
		std::map<std::string, async_t>::iterator i = _async_ops.find(name);
		return i != _async_ops.end();
	}

	inline void add_outstanding_async(char const* name)
	{
		mutex::scoped_lock l(_async_ops_mutex);
		async_t& a = _async_ops[name];
		if (a.stack.empty())
		{
			char stack_text[10000];
			print_backtrace(stack_text, sizeof(stack_text), 9);

			// skip the stack frame of 'add_outstanding_async'
			char* ptr = strchr(stack_text, '\n');
			if (ptr != NULL) ++ptr;
			else ptr = stack_text;
			a.stack = ptr;
		}
		++a.refs;
	}

	inline void complete_async(char const* name)
	{
		mutex::scoped_lock l(_async_ops_mutex);
		async_t& a = _async_ops[name];
		TORRENT_ASSERT(a.refs > 0);
		--a.refs;
		_wakeups.push_back(wakeup_t());
		wakeup_t& w = _wakeups.back();
		w.timestamp = time_now_hires();
#ifdef __MACH__
		task_events_info teinfo;
		mach_msg_type_number_t t_info_count = TASK_EVENTS_INFO_COUNT;
		task_info(mach_task_self(), TASK_EVENTS_INFO, (task_info_t)&teinfo
			, &t_info_count);
		w.context_switches = teinfo.csw;
#else
		w.context_switches = 0;
#endif
		w.operation = name;
	}

	inline void async_inc_threads()
	{
		mutex::scoped_lock l(_async_ops_mutex);
		++_async_ops_nthreads;
	}

	inline void async_dec_threads()
	{
		mutex::scoped_lock l(_async_ops_mutex);
		--_async_ops_nthreads;
	}

	inline int log_async()
	{
		mutex::scoped_lock l(_async_ops_mutex);
		int ret = 0;
		for (std::map<std::string, async_t>::iterator i = _async_ops.begin()
			, end(_async_ops.end()); i != end; ++i)
		{
			if (i->second.refs <= _async_ops_nthreads - 1) continue;
			ret += i->second.refs;
			printf("%s: (%d)\n%s\n", i->first.c_str(), i->second.refs, i->second.stack.c_str());
		}
		return ret;
	}
}

#endif // TORRENT_ASIO_DEBUGGING

namespace libtorrent
{
#if TORRENT_USE_ASSERTS && defined BOOST_HAS_PTHREADS
	struct single_threaded
	{
		single_threaded(): m_single_thread(0) {}
		~single_threaded() { m_single_thread = 0; }
		bool is_single_thread() const
		{
			if (m_single_thread == 0)
			{
				m_single_thread = pthread_self();
				return true;
			}
			return m_single_thread == pthread_self();
		}
		bool is_not_thread() const
		{
			if (m_single_thread == 0) return true;
			return m_single_thread != pthread_self();
		}

		void thread_started()
		{ m_single_thread = pthread_self(); }

		void transfer_ownership()
		{ m_single_thread = 0; }

	private:
		mutable pthread_t m_single_thread;
	};
#else
	struct single_threaded {
		bool is_single_thread() const { return true; }
		void thread_started() {}
		bool is_not_thread() const {return true; }
	};
#endif
}

#endif // TORRENT_DEBUG_HPP_INCLUDED

<commit_msg>fix wakeup profiling to not grow memory usage indefinitely<commit_after>/*

Copyright (c) 2003-2014, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 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 TORRENT_DEBUG_HPP_INCLUDED
#define TORRENT_DEBUG_HPP_INCLUDED

#include "libtorrent/config.hpp"

#if TORRENT_USE_ASSERTS && defined BOOST_HAS_PTHREADS
#include <pthread.h>
#endif

#if defined TORRENT_ASIO_DEBUGGING

#include "libtorrent/assert.hpp"
#include "libtorrent/thread.hpp"
#include "libtorrent/time.hpp"

#include <map>
#include <cstring>
#include <deque>

#ifdef __MACH__
#include <mach/task_info.h>
#include <mach/task.h>
#include <mach/mach_init.h>
#endif

std::string demangle(char const* name);

namespace libtorrent
{
	struct async_t
	{
		async_t() : refs(0) {}
		std::string stack;
		int refs;
	};

	// defined in session_impl.cpp
	extern std::map<std::string, async_t> _async_ops;
	extern int _async_ops_nthreads;
	extern mutex _async_ops_mutex;

	// timestamp -> operation
	struct wakeup_t
	{
		ptime timestamp;
		boost::uint64_t context_switches;
		char const* operation;
	};
	extern std::deque<wakeup_t> _wakeups;

	inline bool has_outstanding_async(char const* name)
	{
		mutex::scoped_lock l(_async_ops_mutex);
		std::map<std::string, async_t>::iterator i = _async_ops.find(name);
		return i != _async_ops.end();
	}

	inline void add_outstanding_async(char const* name)
	{
		mutex::scoped_lock l(_async_ops_mutex);
		async_t& a = _async_ops[name];
		if (a.stack.empty())
		{
			char stack_text[10000];
			print_backtrace(stack_text, sizeof(stack_text), 9);

			// skip the stack frame of 'add_outstanding_async'
			char* ptr = strchr(stack_text, '\n');
			if (ptr != NULL) ++ptr;
			else ptr = stack_text;
			a.stack = ptr;
		}
		++a.refs;
	}

	inline void complete_async(char const* name)
	{
		mutex::scoped_lock l(_async_ops_mutex);
		async_t& a = _async_ops[name];
		TORRENT_ASSERT(a.refs > 0);
		--a.refs;

		// don't let this grow indefinitely
		if (_wakeups.size() < 100000)
		{
			_wakeups.push_back(wakeup_t());
			wakeup_t& w = _wakeups.back();
			w.timestamp = time_now_hires();
		}
#ifdef __MACH__
		task_events_info teinfo;
		mach_msg_type_number_t t_info_count = TASK_EVENTS_INFO_COUNT;
		task_info(mach_task_self(), TASK_EVENTS_INFO, (task_info_t)&teinfo
			, &t_info_count);
		w.context_switches = teinfo.csw;
#else
		w.context_switches = 0;
#endif
		w.operation = name;
	}

	inline void async_inc_threads()
	{
		mutex::scoped_lock l(_async_ops_mutex);
		++_async_ops_nthreads;
	}

	inline void async_dec_threads()
	{
		mutex::scoped_lock l(_async_ops_mutex);
		--_async_ops_nthreads;
	}

	inline int log_async()
	{
		mutex::scoped_lock l(_async_ops_mutex);
		int ret = 0;
		for (std::map<std::string, async_t>::iterator i = _async_ops.begin()
			, end(_async_ops.end()); i != end; ++i)
		{
			if (i->second.refs <= _async_ops_nthreads - 1) continue;
			ret += i->second.refs;
			printf("%s: (%d)\n%s\n", i->first.c_str(), i->second.refs, i->second.stack.c_str());
		}
		return ret;
	}
}

#endif // TORRENT_ASIO_DEBUGGING

namespace libtorrent
{
#if TORRENT_USE_ASSERTS && defined BOOST_HAS_PTHREADS
	struct single_threaded
	{
		single_threaded(): m_single_thread(0) {}
		~single_threaded() { m_single_thread = 0; }
		bool is_single_thread() const
		{
			if (m_single_thread == 0)
			{
				m_single_thread = pthread_self();
				return true;
			}
			return m_single_thread == pthread_self();
		}
		bool is_not_thread() const
		{
			if (m_single_thread == 0) return true;
			return m_single_thread != pthread_self();
		}

		void thread_started()
		{ m_single_thread = pthread_self(); }

		void transfer_ownership()
		{ m_single_thread = 0; }

	private:
		mutable pthread_t m_single_thread;
	};
#else
	struct single_threaded {
		bool is_single_thread() const { return true; }
		void thread_started() {}
		bool is_not_thread() const {return true; }
	};
#endif
}

#endif // TORRENT_DEBUG_HPP_INCLUDED

<|endoftext|>


<commit_before>// Copyright (c) 2021 ASMlover. All rights reserved.
//
//  ______             __                  ___           ____    ____
// /\__  _\           /\ \                /\_ \         /\  _`\ /\  _`\
// \/_/\ \/    __     \_\ \  _____     ___\//\ \      __\ \ \L\_\ \ \/\_\
//    \ \ \  /'__`\   /'_` \/\ '__`\  / __`\\ \ \   /'__`\ \ \L_L\ \ \/_/_
//     \ \ \/\ \L\.\_/\ \L\ \ \ \L\ \/\ \L\ \\_\ \_/\  __/\ \ \/, \ \ \L\ \
//      \ \_\ \__/.\_\ \___,_\ \ ,__/\ \____//\____\ \____\\ \____/\ \____/
//       \/_/\/__/\/_/\/__,_ /\ \ \/  \/___/ \/____/\/____/ \/___/  \/___/
//                             \ \_\
//                              \/_/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//  * Redistributions of source code must retain the above copyright
//    notice, this list ofconditions and the following disclaimer.
//
//  * Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in
//    the documentation and/or other materialsprovided with the
//    distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, 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.
#pragma once

#include <tadpole/common/common.hh>

namespace tadpole::gc {

enum class MemoryTag : u8_t {
  MEMORY,
  OBJECT,
};

class MemoryHeader : private UnCopyable {
  MemoryTag tag_{MemoryTag::MEMORY};
public:
  MemoryHeader(MemoryTag tag) noexcept : tag_(tag) {}

  inline MemoryTag tag() const noexcept { return tag_; }
};

}
<commit_msg>:fire: remove(mem): remove memory header<commit_after><|endoftext|>


<commit_before>#pragma once

#include <random>
#include <memory>
#include <random>

#include "Moe.hpp"
#include "Mutations.hpp"
#include "Crossovers.hpp"

namespace moe
{
    namespace Crossover
    {
        enum : const unsigned int
        {
            OnePoint = 0,
            TwoPoint,
            Uniform
        };
    }
}

template <typename MoeType>
class Moether
{
    public:
        Moether ();
        ~Moether();

        void                init   ( unsigned int _moesPerGen, unsigned int _eliteCopies, float _mutationRate = 0.1f, float _crossoverRate = 0.5f );
        void                run    ( unsigned int _generations );

        void                setFitnessFunction  ( std::function<double( const MoeType& )> _fitnessFunction );
        void                setFitnessMode      ( bool _mode);
        void                setInitGenotypeSize ( unsigned int _size );

        void                setCrossover        ( unsigned int _crossoverID );
        void                setCrossoverEnabled ( bool _crossoverEnabled );
        void                setMutationEnabled  ( bool _mutationEnabled );

        const bool&         isFitnessMode       () const;
        const bool&         isCrossoverEnabled  () const;
        const bool&         isMutationEnabled   () const;

        void                registerCrossover   ( std::unique_ptr<Crossover>);
        void                registerMutation    ( std::unique_ptr<Mutation> );

        void                setAsciiRange       ( unsigned int _a, unsigned int _b );
        void                setCharset          ( const std::string& _charset );
        const std::string&  getCharset          () const;

        const MoeType&      getBestMoe          () const;

    private:
        /* private member functions */
        std::string         randomizeGenotype   ();
        void                crossover           ( const MoeType& _parent1, const MoeType& _parent2, MoeType& _offspring1, MoeType& _offspring2 );
        void                mutate              ( MoeType& _moe );

        std::function< double( const MoeType& ) > m_fitnessFunction;
        // ---

        /* standard types */
        unsigned int    m_generations,
                        m_moesPerGen,
                        m_eliteCopies;
        unsigned int    m_initGenotypeSize = 8;
        unsigned int    m_crossover = moe::Crossover::OnePoint;

        float           m_mutationRate  = 0.1f,
                        m_crossoverRate = 0.5f;

        bool            m_mode = true,
                        m_isCrossoverEnabled = true,
                        m_isMutationsEnabled = true;
        // ---

        std::vector< std::unique_ptr<Mutation> > m_mutations;
        std::vector< std::unique_ptr<Crossover>> m_crossovers;

        MoeType         m_bestMoe;
        std::string     m_charset;

        std::uniform_int_distribution<unsigned int> distrib_charset;
        std::default_random_engine gen;
};

#include "Moether_defs.hpp"<commit_msg>Removed redundant header<commit_after>#pragma once

#include <random>
#include <memory>

#include "Moe.hpp"
#include "Mutations.hpp"
#include "Crossovers.hpp"

namespace moe
{
    namespace Crossover
    {
        enum : const unsigned int
        {
            OnePoint = 0,
            TwoPoint,
            Uniform
        };
    }
}

template <typename MoeType>
class Moether
{
    public:
        Moether ();
        ~Moether();

        void                init   ( unsigned int _moesPerGen, unsigned int _eliteCopies, float _mutationRate = 0.1f, float _crossoverRate = 0.5f );
        void                run    ( unsigned int _generations );

        void                setFitnessFunction  ( std::function<double( const MoeType& )> _fitnessFunction );
        void                setFitnessMode      ( bool _mode);
        void                setInitGenotypeSize ( unsigned int _size );

        void                setCrossover        ( unsigned int _crossoverID );
        void                setCrossoverEnabled ( bool _crossoverEnabled );
        void                setMutationEnabled  ( bool _mutationEnabled );

        const bool&         isFitnessMode       () const;
        const bool&         isCrossoverEnabled  () const;
        const bool&         isMutationEnabled   () const;

        void                registerCrossover   ( std::unique_ptr<Crossover>);
        void                registerMutation    ( std::unique_ptr<Mutation> );

        void                setAsciiRange       ( unsigned int _a, unsigned int _b );
        void                setCharset          ( const std::string& _charset );
        const std::string&  getCharset          () const;

        const MoeType&      getBestMoe          () const;

    private:
        /* private member functions */
        std::string         randomizeGenotype   ();
        void                crossover           ( const MoeType& _parent1, const MoeType& _parent2, MoeType& _offspring1, MoeType& _offspring2 );
        void                mutate              ( MoeType& _moe );

        std::function< double( const MoeType& ) > m_fitnessFunction;
        // ---

        /* standard types */
        unsigned int    m_generations,
                        m_moesPerGen,
                        m_eliteCopies;
        unsigned int    m_initGenotypeSize = 8;
        unsigned int    m_crossover = moe::Crossover::OnePoint;

        float           m_mutationRate  = 0.1f,
                        m_crossoverRate = 0.5f;

        bool            m_mode = true,
                        m_isCrossoverEnabled = true,
                        m_isMutationsEnabled = true;
        // ---

        std::vector< std::unique_ptr<Mutation> > m_mutations;
        std::vector< std::unique_ptr<Crossover>> m_crossovers;

        MoeType         m_bestMoe;
        std::string     m_charset;

        std::uniform_int_distribution<unsigned int> distrib_charset;
        std::default_random_engine gen;
};

#include "Moether_defs.hpp"<|endoftext|>


<commit_before>/////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2019, OpenROAD
// All rights reserved.
//
// BSD 3-Clause License
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 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.
//
///////////////////////////////////////////////////////////////////////////////

#pragma once

#include <string>
#include <set>
#include <vector>

extern "C" {
struct Tcl_Interp;
}

namespace odb {
class dbDatabase;
class dbBlock;
class dbTech;
class dbLib;
class Point;
class Rect;
}

namespace sta {
class dbSta;
class dbNetwork;
class Resizer;
class LibertyCell;
}

namespace ioPlacer {
class IOPlacer;
}

namespace TritonCTS {
class TritonCTSKernel;
}

namespace FastRoute {
class GlobalRouter;
}

namespace tapcell {
    class Tapcell;
}

namespace opendp {
class Opendp;
}

namespace MacroPlace {
class TritonMacroPlace;
}

namespace replace {
class Replace;
}

namespace OpenRCX {
class Ext;
}

namespace psn {
class Psn;
}

namespace pdnsim {
class PDNSim;
}

namespace antenna_checker {
class AntennaChecker;
}

namespace ord {

using std::string;

class dbVerilogNetwork;

// Only pointers to components so the header has no dependents.
class OpenRoad
{
public:
  // Singleton accessor used by tcl command interpreter.
  static OpenRoad *openRoad();
  void init(Tcl_Interp *tcl_interp);

  Tcl_Interp *tclInterp() { return tcl_interp_; }
  odb::dbDatabase *getDb() { return db_; }
  sta::dbSta *getSta() { return sta_; }
  sta::dbNetwork *getDbNetwork();
  sta::Resizer *getResizer() { return resizer_; }
  TritonCTS::TritonCTSKernel *getTritonCts() { return tritonCts_; }
  dbVerilogNetwork *getVerilogNetwork() { return verilog_network_; }
  opendp::Opendp *getOpendp() { return opendp_; }
  tapcell::Tapcell *getTapcell() { return tapcell_; }
  MacroPlace::TritonMacroPlace *getTritonMp() { return tritonMp_; }
  OpenRCX::Ext *getOpenRCX() { return extractor_; }
  replace::Replace* getReplace() { return replace_; }
  pdnsim::PDNSim* getPDNSim() { return pdnsim_; }
  FastRoute::GlobalRouter* getFastRoute() { return fastRoute_; }
  antenna_checker::AntennaChecker *getAntennaChecker(){ return antennaChecker_; }
  ioPlacer::IOPlacer *getIOPlacer() { return ioPlacer_; }
  // Return the bounding box of the db rows.
  odb::Rect getCore();
  // Return true if the command units have been initialized.
  bool unitsInitialized();

  void readLef(const char *filename,
	       const char *lib_name,
	       bool make_tech,
	       bool make_library);

  void readDef(const char *filename,
               bool order_wires,
               bool continue_on_errors);
  void writeDef(const char *filename,
		// major.minor (avoid including defout.h)
		string version);

  void readVerilog(const char *filename);
  // Write a flat verilog netlist for the database.
  void writeVerilog(const char *filename,
		    bool sort,
		    std::vector<sta::LibertyCell*> *remove_cells);
  void linkDesign(const char *top_cell_name);

  void readDb(const char *filename);
  void writeDb(const char *filename);

  // Observer interface
  class Observer
  {
  public:
    virtual ~Observer();

    // Either pointer could be null
    virtual void postReadLef(odb::dbTech* tech, odb::dbLib* library) = 0;
    virtual void postReadDef(odb::dbBlock* block) = 0;
    virtual void postReadDb(odb::dbDatabase* db) = 0;

  private:
    OpenRoad* owner_ = nullptr;
    friend class OpenRoad;
  };

  void addObserver(Observer *observer);
  void removeObserver(Observer *observer);

protected:
  ~OpenRoad();
  friend void deleteAllMemory();

private:
  OpenRoad();

  Tcl_Interp *tcl_interp_;
  odb::dbDatabase *db_;
  dbVerilogNetwork *verilog_network_;
  sta::dbSta *sta_;
  sta::Resizer *resizer_;
  ioPlacer::IOPlacer *ioPlacer_;
  opendp::Opendp *opendp_;
  MacroPlace::TritonMacroPlace *tritonMp_;
  FastRoute::GlobalRouter *fastRoute_;
  TritonCTS::TritonCTSKernel *tritonCts_;
  tapcell::Tapcell *tapcell_;
  OpenRCX::Ext *extractor_;
  antenna_checker::AntennaChecker *antennaChecker_;
#ifdef BUILD_OPENPHYSYN
  psn::Psn *psn_;
#endif
  replace::Replace *replace_;
  pdnsim::PDNSim *pdnsim_;

  std::set<Observer *> observers_;

  // Singleton used by tcl command interpreter.
  static OpenRoad *openroad_;
};

// Return the bounding box of the db rows.
odb::Rect
getCore(odb::dbBlock *block);

// Return the point inside rect that is closest to pt.
odb::Point
closestPtInRect(odb::Rect rect,
		odb::Point pt);
odb::Point
closestPtInRect(odb::Rect rect,
		int x,
		int y);

int
tclAppInit(Tcl_Interp *interp);

void
deleteAllMemory();

} // namespace ord
<commit_msg>more openphysyn fallout<commit_after>/////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2019, OpenROAD
// All rights reserved.
//
// BSD 3-Clause License
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
//   contributors may be used to endorse or promote products derived from
//   this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 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.
//
///////////////////////////////////////////////////////////////////////////////

#pragma once

#include <string>
#include <set>
#include <vector>

extern "C" {
struct Tcl_Interp;
}

namespace odb {
class dbDatabase;
class dbBlock;
class dbTech;
class dbLib;
class Point;
class Rect;
}

namespace sta {
class dbSta;
class dbNetwork;
class Resizer;
class LibertyCell;
}

namespace ioPlacer {
class IOPlacer;
}

namespace TritonCTS {
class TritonCTSKernel;
}

namespace FastRoute {
class GlobalRouter;
}

namespace tapcell {
    class Tapcell;
}

namespace opendp {
class Opendp;
}

namespace MacroPlace {
class TritonMacroPlace;
}

namespace replace {
class Replace;
}

namespace OpenRCX {
class Ext;
}

namespace psn {
class Psn;
}

namespace pdnsim {
class PDNSim;
}

namespace antenna_checker {
class AntennaChecker;
}

namespace ord {

using std::string;

class dbVerilogNetwork;

// Only pointers to components so the header has no dependents.
class OpenRoad
{
public:
  // Singleton accessor used by tcl command interpreter.
  static OpenRoad *openRoad();
  void init(Tcl_Interp *tcl_interp);

  Tcl_Interp *tclInterp() { return tcl_interp_; }
  odb::dbDatabase *getDb() { return db_; }
  sta::dbSta *getSta() { return sta_; }
  sta::dbNetwork *getDbNetwork();
  sta::Resizer *getResizer() { return resizer_; }
  TritonCTS::TritonCTSKernel *getTritonCts() { return tritonCts_; }
  dbVerilogNetwork *getVerilogNetwork() { return verilog_network_; }
  opendp::Opendp *getOpendp() { return opendp_; }
  tapcell::Tapcell *getTapcell() { return tapcell_; }
  MacroPlace::TritonMacroPlace *getTritonMp() { return tritonMp_; }
  OpenRCX::Ext *getOpenRCX() { return extractor_; }
  replace::Replace* getReplace() { return replace_; }
  pdnsim::PDNSim* getPDNSim() { return pdnsim_; }
  FastRoute::GlobalRouter* getFastRoute() { return fastRoute_; }
  antenna_checker::AntennaChecker *getAntennaChecker(){ return antennaChecker_; }
  ioPlacer::IOPlacer *getIOPlacer() { return ioPlacer_; }
  // Return the bounding box of the db rows.
  odb::Rect getCore();
  // Return true if the command units have been initialized.
  bool unitsInitialized();

  void readLef(const char *filename,
	       const char *lib_name,
	       bool make_tech,
	       bool make_library);

  void readDef(const char *filename,
               bool order_wires,
               bool continue_on_errors);
  void writeDef(const char *filename,
		// major.minor (avoid including defout.h)
		string version);

  void readVerilog(const char *filename);
  // Write a flat verilog netlist for the database.
  void writeVerilog(const char *filename,
		    bool sort,
		    std::vector<sta::LibertyCell*> *remove_cells);
  void linkDesign(const char *top_cell_name);

  void readDb(const char *filename);
  void writeDb(const char *filename);

  // Observer interface
  class Observer
  {
  public:
    virtual ~Observer();

    // Either pointer could be null
    virtual void postReadLef(odb::dbTech* tech, odb::dbLib* library) = 0;
    virtual void postReadDef(odb::dbBlock* block) = 0;
    virtual void postReadDb(odb::dbDatabase* db) = 0;

  private:
    OpenRoad* owner_ = nullptr;
    friend class OpenRoad;
  };

  void addObserver(Observer *observer);
  void removeObserver(Observer *observer);

protected:
  ~OpenRoad();
  friend void deleteAllMemory();

private:
  OpenRoad();

  Tcl_Interp *tcl_interp_;
  odb::dbDatabase *db_;
  dbVerilogNetwork *verilog_network_;
  sta::dbSta *sta_;
  sta::Resizer *resizer_;
  ioPlacer::IOPlacer *ioPlacer_;
  opendp::Opendp *opendp_;
  MacroPlace::TritonMacroPlace *tritonMp_;
  FastRoute::GlobalRouter *fastRoute_;
  TritonCTS::TritonCTSKernel *tritonCts_;
  tapcell::Tapcell *tapcell_;
  OpenRCX::Ext *extractor_;
  antenna_checker::AntennaChecker *antennaChecker_;
  psn::Psn *psn_;
  replace::Replace *replace_;
  pdnsim::PDNSim *pdnsim_;

  std::set<Observer *> observers_;

  // Singleton used by tcl command interpreter.
  static OpenRoad *openroad_;
};

// Return the bounding box of the db rows.
odb::Rect
getCore(odb::dbBlock *block);

// Return the point inside rect that is closest to pt.
odb::Point
closestPtInRect(odb::Rect rect,
		odb::Point pt);
odb::Point
closestPtInRect(odb::Rect rect,
		int x,
		int y);

int
tclAppInit(Tcl_Interp *interp);

void
deleteAllMemory();

} // namespace ord
<|endoftext|>


<commit_before>// Images.cpp

#include "stdafx.h"

#include "Images.h"
#include "../interface/HeeksObj.h"

Images::Images(){
	m_image_list = NULL;
}

int Images::GetImage(HeeksObj *object)
{
	int image_index = -1;

	if(m_image_list && object->GetType() != UnknownType)
	{
		std::map<int, int>::iterator FindIt;
		if (image_map.size()>0) FindIt = image_map.find(object->GetType());
		if (image_map.size() == 0 || FindIt == image_map.end())
		{
#ifdef HEEKSCAD
			wxString folder = wxGetApp().GetExeFolder();
#else
			wxString folder = theApp.GetDllFolder();
#endif
			image_index = m_image_list->Add(wxIcon(folder + _T("/icons/") + object->GetIcon() + _T(".png"), wxBITMAP_TYPE_PNG));
			FindIt = image_map.insert(std::pair<int, int>(object->GetType(), image_index)).first;
			image_index = FindIt->second;
		}
		else image_index = FindIt->second;
	}
	return image_index;
}

bool Images::InitializeImageList(int width, int height){
	if(m_image_list == NULL){
		m_image_list = new wxImageList(width, height);
		return true;
	}
	return false;
}
<commit_msg>tidying up icons, some more<commit_after>// Images.cpp

#include "stdafx.h"

#include "Images.h"
#include "../interface/HeeksObj.h"

Images::Images(){
	m_image_list = NULL;
}

int Images::GetImage(HeeksObj *object)
{
	int image_index = -1;

	if(m_image_list && object->GetType() != UnknownType)
	{
		std::map<int, int>::iterator FindIt;
		if (image_map.size()>0) FindIt = image_map.find(object->GetType());
		if (image_map.size() == 0 || FindIt == image_map.end())
		{
			image_index = m_image_list->Add(wxIcon(wxGetApp().GetExeFolder() + _T("/icons/") + object->GetIcon() + _T(".png"), wxBITMAP_TYPE_PNG));
			FindIt = image_map.insert(std::pair<int, int>(object->GetType(), image_index)).first;
			image_index = FindIt->second;
		}
		else image_index = FindIt->second;
	}
	return image_index;
}

bool Images::InitializeImageList(int width, int height){
	if(m_image_list == NULL){
		m_image_list = new wxImageList(width, height);
		return true;
	}
	return false;
}
<|endoftext|>


<commit_before>/***************************************************************************
* Copyright (c) 2017, Sylvain Corlay and Johan Mabille                     *
*                                                                          *
* Distributed under the terms of the BSD 3-Clause License.                 *
*                                                                          *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/

#ifndef XOBJECT_HPP
#define XOBJECT_HPP

#include <string>
#include <unordered_map>

#include "xtl/xoptional.hpp"

#include "xproperty/xobserved.hpp"

#include "xmaterialize.hpp"
#include "xtransport.hpp"

namespace xtl
{
    /***********************************************************
     * to_json and from_json specialization for xtl::xoptional *
     ***********************************************************/

    template <class D>
    void to_json(xeus::xjson& j, const xoptional<D>& o)
    {
        if (!o.has_value())
        {
            j = nullptr;
        }
        else
        {
            j = o.value();
        }
    }

    template <class D>
    void from_json(const xeus::xjson& j, xoptional<D>& o)
    {
        if (j.is_null())
        {
            o = missing<D>();
        }
        else
        {
            o = j.get<D>();
        }
    }
}

namespace xw
{

    /****************************
     * base xobject declaration *
     ****************************/

    template <class D>
    class xobject : public xp::xobserved<D>, public xtransport<D>
    {
    public:

        using base_type = xtransport<D>;
        using derived_type = D;

        using base_type::derived_cast;

        xeus::xjson get_state() const;
        void apply_patch(const xeus::xjson&);

        XPROPERTY(xtl::xoptional<std::string>, derived_type, _model_module, "jupyter-js-widgets");
        XPROPERTY(xtl::xoptional<std::string>, derived_type, _model_module_version, "~2.1.4");
        XPROPERTY(xtl::xoptional<std::string>, derived_type, _model_name, "WidgetModel");
        XPROPERTY(xtl::xoptional<std::string>, derived_type, _view_module, "jupyter-js-widgets");
        XPROPERTY(xtl::xoptional<std::string>, derived_type, _view_module_version, "~2.1.4");
        XPROPERTY(xtl::xoptional<std::string>, derived_type, _view_name, "WidgetView");

        using base_type::notify;

    protected:

        using base_type::base_type;
        using concrete_type = xconcrete_type_t<D>;

        concrete_type* self();
        const concrete_type* self() const;
    };

    /*******************************
     * base xobject implementation *
     *******************************/

    #define XOBJECT_SET_PROPERTY_FROM_PATCH(name, patch)                   \
    if (patch.find(#name) != patch.end())                                  \
    {                                                                      \
        name = patch.at(#name).get<typename decltype(name)::value_type>(); \
    }

    #define XOBJECT_SET_PATCH_FROM_PROPERTY(name, patch) \
    patch[#name] = this->name();

    template <class D>
    inline xeus::xjson xobject<D>::get_state() const
    {
        xeus::xjson state;

        XOBJECT_SET_PATCH_FROM_PROPERTY(_model_module, state);
        XOBJECT_SET_PATCH_FROM_PROPERTY(_model_module_version, state);
        XOBJECT_SET_PATCH_FROM_PROPERTY(_model_name, state);
        XOBJECT_SET_PATCH_FROM_PROPERTY(_view_module, state);
        XOBJECT_SET_PATCH_FROM_PROPERTY(_view_module_version, state);
        XOBJECT_SET_PATCH_FROM_PROPERTY(_view_name, state);

        return state;
    }

    template <class D>
    inline void xobject<D>::apply_patch(const xeus::xjson& patch)
    {
        XOBJECT_SET_PROPERTY_FROM_PATCH(_model_module, patch);
        XOBJECT_SET_PROPERTY_FROM_PATCH(_model_module_version, patch);
        XOBJECT_SET_PROPERTY_FROM_PATCH(_model_name, patch);
        XOBJECT_SET_PROPERTY_FROM_PATCH(_view_module, patch);
        XOBJECT_SET_PROPERTY_FROM_PATCH(_view_module_version, patch);
        XOBJECT_SET_PROPERTY_FROM_PATCH(_view_name, patch);
    }

    template <class D>
    inline auto xobject<D>::self() -> concrete_type*
    {
        return reinterpret_cast<concrete_type*>(this);
    }

    template <class D>
    inline auto xobject<D>::self() const -> const concrete_type*
    {
        return reinterpret_cast<const concrete_type*>(this);
    }
}

#endif
<commit_msg>Fixup versions for usage in jupyterlab<commit_after>/***************************************************************************
* Copyright (c) 2017, Sylvain Corlay and Johan Mabille                     *
*                                                                          *
* Distributed under the terms of the BSD 3-Clause License.                 *
*                                                                          *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/

#ifndef XOBJECT_HPP
#define XOBJECT_HPP

#include <string>
#include <unordered_map>

#include "xtl/xoptional.hpp"

#include "xproperty/xobserved.hpp"

#include "xmaterialize.hpp"
#include "xtransport.hpp"

namespace xtl
{
    /***********************************************************
     * to_json and from_json specialization for xtl::xoptional *
     ***********************************************************/

    template <class D>
    void to_json(xeus::xjson& j, const xoptional<D>& o)
    {
        if (!o.has_value())
        {
            j = nullptr;
        }
        else
        {
            j = o.value();
        }
    }

    template <class D>
    void from_json(const xeus::xjson& j, xoptional<D>& o)
    {
        if (j.is_null())
        {
            o = missing<D>();
        }
        else
        {
            o = j.get<D>();
        }
    }
}

namespace xw
{

    /****************************
     * base xobject declaration *
     ****************************/

    template <class D>
    class xobject : public xp::xobserved<D>, public xtransport<D>
    {
    public:

        using base_type = xtransport<D>;
        using derived_type = D;

        using base_type::derived_cast;

        xeus::xjson get_state() const;
        void apply_patch(const xeus::xjson&);

        XPROPERTY(xtl::xoptional<std::string>, derived_type, _model_module, "@jupyter-widgets/base");
        XPROPERTY(xtl::xoptional<std::string>, derived_type, _model_module_version, "^1.0.0");
        XPROPERTY(xtl::xoptional<std::string>, derived_type, _model_name, "WidgetModel");
        XPROPERTY(xtl::xoptional<std::string>, derived_type, _view_module, "@jupyter-widgets/base");
        XPROPERTY(xtl::xoptional<std::string>, derived_type, _view_module_version, "^1.0.0");
        XPROPERTY(xtl::xoptional<std::string>, derived_type, _view_name, "WidgetView");

        using base_type::notify;

    protected:

        using base_type::base_type;
        using concrete_type = xconcrete_type_t<D>;

        concrete_type* self();
        const concrete_type* self() const;
    };

    /*******************************
     * base xobject implementation *
     *******************************/

    #define XOBJECT_SET_PROPERTY_FROM_PATCH(name, patch)                   \
    if (patch.find(#name) != patch.end())                                  \
    {                                                                      \
        name = patch.at(#name).get<typename decltype(name)::value_type>(); \
    }

    #define XOBJECT_SET_PATCH_FROM_PROPERTY(name, patch) \
    patch[#name] = this->name();

    template <class D>
    inline xeus::xjson xobject<D>::get_state() const
    {
        xeus::xjson state;

        XOBJECT_SET_PATCH_FROM_PROPERTY(_model_module, state);
        XOBJECT_SET_PATCH_FROM_PROPERTY(_model_module_version, state);
        XOBJECT_SET_PATCH_FROM_PROPERTY(_model_name, state);
        XOBJECT_SET_PATCH_FROM_PROPERTY(_view_module, state);
        XOBJECT_SET_PATCH_FROM_PROPERTY(_view_module_version, state);
        XOBJECT_SET_PATCH_FROM_PROPERTY(_view_name, state);

        return state;
    }

    template <class D>
    inline void xobject<D>::apply_patch(const xeus::xjson& patch)
    {
        XOBJECT_SET_PROPERTY_FROM_PATCH(_model_module, patch);
        XOBJECT_SET_PROPERTY_FROM_PATCH(_model_module_version, patch);
        XOBJECT_SET_PROPERTY_FROM_PATCH(_model_name, patch);
        XOBJECT_SET_PROPERTY_FROM_PATCH(_view_module, patch);
        XOBJECT_SET_PROPERTY_FROM_PATCH(_view_module_version, patch);
        XOBJECT_SET_PROPERTY_FROM_PATCH(_view_name, patch);
    }

    template <class D>
    inline auto xobject<D>::self() -> concrete_type*
    {
        return reinterpret_cast<concrete_type*>(this);
    }

    template <class D>
    inline auto xobject<D>::self() const -> const concrete_type*
    {
        return reinterpret_cast<const concrete_type*>(this);
    }
}

#endif
<|endoftext|>


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

#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif

#ifndef INCLUDED_SFX2_DLLAPI_H
#include "sfx2/dllapi.h"
#endif

#ifndef _SAL_TYPES_H_
#include "sal/types.h"
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif

#include <com/sun/star/uno/Any.hxx>

#include <com/sun/star/document/XDocumentInfo.hpp>

#ifndef _ERRCODE_HXX //autogen wg. ErrCode
#include <tools/errcode.hxx>
#endif
#ifndef _DATETIME_HXX //autogen
#include <tools/datetime.hxx>
#endif
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _SFXHINT_HXX //autogen
#include <svtools/hint.hxx>
#endif

#include <hash_map>
#include <svtools/itemprop.hxx>

class SfxObjectShell;
class GDIMetaFile;
class SotStorage;
class SfxDocumentInfo_Impl;

const BYTE MAXDOCUSERKEYS  = 4;

class SFX2_DLLPUBLIC SfxDocumentInfo
{
    SfxDocumentInfo_Impl* pImp;

    SAL_DLLPRIVATE DateTime DATETIME_PROP(sal_Int32 nHandle) const;
    SAL_DLLPRIVATE BOOL BOOL_PROP(sal_Int32 nHandle) const;
    SAL_DLLPRIVATE sal_Int32 INT_PROP(sal_Int32 nHandle) const;
    SAL_DLLPRIVATE String STRING_PROP(sal_Int32 nHandle) const;
    SAL_DLLPRIVATE void SET_PROP(sal_Int32 nHandle, const com::sun::star::uno::Any& aValue );

public:

    SfxDocumentInfo( SfxObjectShell* pDoc=0);

    // deep copy
    SfxDocumentInfo( const SfxDocumentInfo& );

    // shallow copy
    SfxDocumentInfo( const com::sun::star::uno::Reference < com::sun::star::document::XDocumentInfo >& );

    ~SfxDocumentInfo();

    const SfxDocumentInfo& operator=( const SfxDocumentInfo& );
    int operator==( const SfxDocumentInfo& ) const;

    com::sun::star::uno::Reference < com::sun::star::document::XDocumentInfo > GetInfo() const;

    sal_uInt32 LoadPropertySet( SotStorage* pStor );
    sal_Bool SavePropertySet( SotStorage* pStor, GDIMetaFile* pThumb ) const;

    BOOL IsReloadEnabled() const;
    sal_Int16 GetDocumentNumber() const;
    sal_Int32 GetReloadDelay() const;
    sal_Int32 GetTime() const;
    String GetDefaultTarget() const;
    String GetReloadURL() const;
    String GetTemplateName() const;
    String GetTemplateFileName() const;
    String GetTitle()   const;
    String GetTheme()   const;
    String GetComment() const;
    String GetKeywords()const;
    String GetMimeType() const;
    String GetAuthor() const;
    DateTime GetCreationDate() const;
    String GetModificationAuthor() const;
    DateTime GetModificationDate() const;
    String GetPrintedBy() const;
    DateTime GetPrintDate() const;
    DateTime GetTemplateDate() const;

    void EnableReload( BOOL bEnable );
    void SetDocumentNumber(sal_Int16 nNo);
    void SetReloadDelay( sal_Int32 nDelay );
    void SetTime(sal_Int32 l);
    void SetDefaultTarget( const String& rString );
    void SetReloadURL( const String& rString );
    void SetTemplateName( const String& rName );
    void SetTemplateFileName( const String& rFileName );
    void SetTitle( const String& rVal );
    void SetTheme( const String& rVal );
    void SetComment( const String& rVal );
    void SetKeywords( const String& rVal );
    void SetMimeType( const String& rVal );
    void SetAuthor( const String& rAuthor );
    void SetModificationAuthor( const String& rChangedBy );
    void SetPrintedBy( const String& rPrintedBy );
    void SetCreationDate(const DateTime& rDate);
    void SetModificationDate(const DateTime& rDate);
    void SetPrintDate(const DateTime& rDate);
    void SetTemplateDate(const DateTime& rDate);
    void IncDocumentNumber();
    void SetCreated( const String& rAuthor );
    void SetChanged( const String& rName );
    void SetPrinted( const String& rName );

    USHORT GetUserKeyCount() const;
    String GetUserKeyTitle(USHORT n) const;
    String GetUserKeyWord(USHORT n) const;
    void   SetUserKey( const String& rName, const String& rValue, USHORT n );
    void   SetUserKeyWord( const String& rValue, USHORT n );
    void   SetUserKeyTitle( const String& rValue, USHORT n );

    void ClearTemplateInformation();
    void DeleteUserData( const String* pAuthor=0 );
    void ResetUserData( const String& rAuthor );
    void Clear();
    void ResetFromTemplate( const String& rTemplateName, const String& rFileName );

    // --> PB 2004-08-23 #i33095#
    sal_Bool        IsLoadReadonly() const;
    void            SetLoadReadonly( sal_Bool _bReadonly );

    BOOL LoadFromBinaryFormat( SvStream& rStream );
    BOOL SaveToBinaryFormat( SvStream& rStream ) const;
    BOOL LoadFromBinaryFormat( SotStorage* rStream );
    BOOL SaveToBinaryFormat( SotStorage* rStream ) const;

    BOOL SetCustomProperty(const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue);

};

DECL_PTRHINT(SFX2_DLLPUBLIC, SfxDocumentInfoHint, SfxDocumentInfo);

#endif

<commit_msg>INTEGRATION: CWS customfields (1.5.80); FILE MERGED 2007/10/25 09:50:49 mba 1.5.80.1: #i5092#: support custom property fields<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: docinf.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: ihi $ $Date: 2007-11-26 15:34:21 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _SFXDOCINF_HXX
#define _SFXDOCINF_HXX

#ifndef _SAL_CONFIG_H_
#include "sal/config.h"
#endif

#ifndef INCLUDED_SFX2_DLLAPI_H
#include "sfx2/dllapi.h"
#endif

#ifndef _SAL_TYPES_H_
#include "sal/types.h"
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif

#include <com/sun/star/uno/Any.hxx>

#include <com/sun/star/document/XDocumentInfo.hpp>

#ifndef _ERRCODE_HXX //autogen wg. ErrCode
#include <tools/errcode.hxx>
#endif
#ifndef _DATETIME_HXX //autogen
#include <tools/datetime.hxx>
#endif
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _SFXHINT_HXX //autogen
#include <svtools/hint.hxx>
#endif

#include <hash_map>
#include <svtools/itemprop.hxx>

class SfxObjectShell;
class GDIMetaFile;
class SotStorage;
class SfxDocumentInfo_Impl;

const BYTE MAXDOCUSERKEYS  = 4;

class SFX2_DLLPUBLIC SfxDocumentInfo
{
    SfxDocumentInfo_Impl* pImp;

    SAL_DLLPRIVATE DateTime DATETIME_PROP(sal_Int32 nHandle) const;
    SAL_DLLPRIVATE BOOL BOOL_PROP(sal_Int32 nHandle) const;
    SAL_DLLPRIVATE sal_Int32 INT_PROP(sal_Int32 nHandle) const;
    SAL_DLLPRIVATE String STRING_PROP(sal_Int32 nHandle) const;
    SAL_DLLPRIVATE void SET_PROP(sal_Int32 nHandle, const com::sun::star::uno::Any& aValue );

public:

    SfxDocumentInfo( SfxObjectShell* pDoc=0);

    // deep copy
    SfxDocumentInfo( const SfxDocumentInfo& );

    // shallow copy
    SfxDocumentInfo( const com::sun::star::uno::Reference < com::sun::star::document::XDocumentInfo >& );

    ~SfxDocumentInfo();

    const SfxDocumentInfo& operator=( const SfxDocumentInfo& );
    int operator==( const SfxDocumentInfo& ) const;

    com::sun::star::uno::Reference < com::sun::star::document::XDocumentInfo > GetInfo() const;

    sal_uInt32 LoadPropertySet( SotStorage* pStor );
    sal_Bool SavePropertySet( SotStorage* pStor, GDIMetaFile* pThumb ) const;

    BOOL IsReloadEnabled() const;
    sal_Int16 GetDocumentNumber() const;
    sal_Int32 GetReloadDelay() const;
    sal_Int32 GetTime() const;
    String GetDefaultTarget() const;
    String GetReloadURL() const;
    String GetTemplateName() const;
    String GetTemplateFileName() const;
    String GetTitle()   const;
    String GetTheme()   const;
    String GetComment() const;
    String GetKeywords()const;
    String GetMimeType() const;
    String GetAuthor() const;
    DateTime GetCreationDate() const;
    String GetModificationAuthor() const;
    DateTime GetModificationDate() const;
    String GetPrintedBy() const;
    DateTime GetPrintDate() const;
    DateTime GetTemplateDate() const;

    void EnableReload( BOOL bEnable );
    void SetDocumentNumber(sal_Int16 nNo);
    void SetReloadDelay( sal_Int32 nDelay );
    void SetTime(sal_Int32 l);
    void SetDefaultTarget( const String& rString );
    void SetReloadURL( const String& rString );
    void SetTemplateName( const String& rName );
    void SetTemplateFileName( const String& rFileName );
    void SetTitle( const String& rVal );
    void SetTheme( const String& rVal );
    void SetComment( const String& rVal );
    void SetKeywords( const String& rVal );
    void SetMimeType( const String& rVal );
    void SetAuthor( const String& rAuthor );
    void SetModificationAuthor( const String& rChangedBy );
    void SetPrintedBy( const String& rPrintedBy );
    void SetCreationDate(const DateTime& rDate);
    void SetModificationDate(const DateTime& rDate);
    void SetPrintDate(const DateTime& rDate);
    void SetTemplateDate(const DateTime& rDate);
    void IncDocumentNumber();
    void SetCreated( const String& rAuthor );
    void SetChanged( const String& rName );
    void SetPrinted( const String& rName );

    USHORT GetUserKeyCount() const;
    String GetUserKeyTitle(USHORT n) const;
    String GetUserKeyWord(USHORT n) const;
    void   SetUserKey( const String& rName, const String& rValue, USHORT n );
    void   SetUserKeyWord( const String& rValue, USHORT n );
    void   SetUserKeyTitle( const String& rValue, USHORT n );

    void ClearTemplateInformation();
    void DeleteUserData( const String* pAuthor=0 );
    void ResetUserData( const String& rAuthor );
    void Clear();
    void ResetFromTemplate( const String& rTemplateName, const String& rFileName );

    // --> PB 2004-08-23 #i33095#
    sal_Bool        IsLoadReadonly() const;
    void            SetLoadReadonly( sal_Bool _bReadonly );

    BOOL LoadFromBinaryFormat( SvStream& rStream );
    BOOL SaveToBinaryFormat( SvStream& rStream ) const;
    BOOL LoadFromBinaryFormat( SotStorage* rStream );
    BOOL SaveToBinaryFormat( SotStorage* rStream ) const;

    BOOL InsertCustomProperty(const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue);
    com::sun::star::uno::Sequence < ::rtl::OUString > GetCustomPropertyNames() const;
};

DECL_PTRHINT(SFX2_DLLPUBLIC, SfxDocumentInfoHint, SfxDocumentInfo);

#endif

<|endoftext|>