<commit_before>#include <math.h>
#include <iostream>

#include <cuda.h>
#include <cusparse.h>

#include <iucore.h>
#include <iusparse.h>
#include <iuio.h>
#include <iutransform.h>

#include "print_helpers.h"

#define NSIZES 3
#define NALG   6

//cusparseHandle_t handle = 0;

// Forward declarations
void rof_primal_dual(iu::ImageGpu_32f_C1* device_f, iu::ImageGpu_32f_C1* device_u,
                     iu::ImageGpu_32f_C1* device_u_, iu::ImageGpu_32f_C2* device_p,
                     float lambda, int max_iter);

void rof_primal_dual_sparse(iu::SparseMatrixGpu_32f* G,
                            iu::ImageGpu_32f_C1* device_f, iu::ImageGpu_32f_C1* device_u,
                            iu::ImageGpu_32f_C1* device_u_, iu::ImageGpu_32f_C2* device_p,
                            float lambda, int max_iter);

void rof_primal_dual_notex(iu::ImageGpu_32f_C1* device_f, iu::ImageGpu_32f_C1* device_u,
                           iu::ImageGpu_32f_C1* device_u_, iu::ImageGpu_32f_C2* device_p,
                           float lambda, int max_iter);

void rof_primal_dual_shared(iu::ImageGpu_32f_C1* device_f, iu::ImageGpu_32f_C1* device_u,
                            iu::ImageGpu_32f_C1* device_u_, iu::ImageGpu_32f_C2* device_p,
                            float lambda, int max_iter);

void rof_primal_dual_shared_single(iu::ImageGpu_32f_C1* device_f, iu::ImageGpu_32f_C1* device_u,
                            iu::ImageGpu_32f_C2* device_p, float lambda, int max_iter);

void rof_primal_dual_shared_single2(iu::ImageGpu_32f_C1* device_f, iu::ImageGpu_32f_C1* device_u,
                                    iu::ImageGpu_32f_C2* device_p, float lambda, int max_iter);

// Calls
void calcROF(iu::ImageGpu_32f_C1* f, iu::ImageGpu_32f_C1* u,
             float lambda, int max_iter, double* init, double* alg, double* complete,
             bool notex=false)
{
  cudaThreadSynchronize();
  double start = iu::getTime();

  iu::ImageGpu_32f_C1 u_(u->size());
  iu::copy(u, &u_);
  iu::ImageGpu_32f_C2 p(u->size());
  iu::setValue(make_float2(0.0f, 0.0f), &p, p.roi());

  cudaThreadSynchronize();
  double interm = iu::getTime();
  *init = interm - start;

  if (notex)
    rof_primal_dual_notex(f, u, &u_, &p, lambda, max_iter);
  else
    rof_primal_dual(f, u, &u_, &p, lambda, max_iter);

  cudaThreadSynchronize();
  *alg = iu::getTime() - interm;
  *complete = iu::getTime() - start;

  return;
}

void calcROFshared(iu::ImageGpu_32f_C1* f, iu::ImageGpu_32f_C1* u,
                   float lambda, int max_iter, double* init, double* alg, double* complete,
                   bool single=false, int internal=2)
{
  cudaThreadSynchronize();
  double start = iu::getTime();

  iu::ImageGpu_32f_C1 u_(u->size());
  iu::copy(u, &u_);
  iu::ImageGpu_32f_C2 p(u->size());
  iu::setValue(make_float2(0.0f, 0.0f), &p, p.roi());

  cudaThreadSynchronize();
  double interm = iu::getTime();
  *init = interm - start;

  if (single)
  {
    if (internal == 1)
      rof_primal_dual_shared_single(f, u, &p, lambda, max_iter);
    else if (internal == 2)
      rof_primal_dual_shared_single2(f, u, &p, lambda, max_iter);
  }
  else
    rof_primal_dual_shared(f, u, &u_, &p, lambda, max_iter);

  cudaThreadSynchronize();
  *alg = iu::getTime() - interm;
  *complete = iu::getTime() - start;

  return;
}

void calcROFSparse(iu::ImageGpu_32f_C1* f, iu::ImageGpu_32f_C1* u,
                   float lambda, int max_iter, double* init, double* alg, double* complete)
{
  // Sparse matrix
  cusparseHandle_t handle = 0;
  cusparseCreate(&handle);

  cudaThreadSynchronize();
  double start = iu::getTime();

  iu::ImageGpu_32f_C1 u_(u->size());
  iu::copy(u, &u_);
  iu::ImageGpu_32f_C2 p(u->size());
  iu::setValue(make_float2(0.0f, 0.0f), &p, p.roi());

  // Generate Matrix G
  iu::LinearHostMemory<int> rowG(u->stride()*u->height()*4);
  iu::LinearHostMemory<int> colG(u->stride()*u->height()*4);
  iu::LinearHostMemory<float> valG(u->stride()*u->height()*4);

  int cind = 0;
  for (int y=0; y<u->height(); y++)
  {
    for (int x=0; x<u->width(); x++)
    {
      if (x<u->width()-1)
      {
        *rowG.data(cind) = y*p.stride()*2 + x*2;
        *colG.data(cind) = y*u->stride() + x;
        *valG.data(cind) = -1.0f;
        cind++;

        *rowG.data(cind) = y*p.stride()*2 + x*2;
        *colG.data(cind) = y*u->stride() + x+1;
        *valG.data(cind) = 1.0f;
        cind++;
      }
      if (y<u->height()-1)
      {
        *rowG.data(cind) = y*p.stride()*2 + x*2+1;
        *colG.data(cind) = y*u->stride() + x;
        *valG.data(cind) = -1.0f;
        cind++;

        *rowG.data(cind) = y*p.stride()*2 + x*2+1;
        *colG.data(cind) = (y+1)*u->stride() + x;
        *valG.data(cind) = 1.0f;
        cind++;
      }
    }
  }
  iu::LinearDeviceMemory<int> rowG_d(cind);
  iu::copy(&rowG, &rowG_d);
  iu::LinearDeviceMemory<int> colG_d(cind);
  iu::copy(&colG, &colG_d);
  iu::LinearDeviceMemory<float> valG_d(cind);
  iu::copy(&valG, &valG_d);
  iu::SparseMatrixGpu_32f G_d(&handle, &valG_d, &rowG_d, p.stride()*2*p.height(), &colG_d, u->stride()*u->height());

  G_d.changeSparseFormat(CSR);

  cudaThreadSynchronize();
  double interm = iu::getTime();
  *init = interm - start;

  rof_primal_dual_sparse(&G_d, f, u, &u_, &p, lambda, max_iter);

  cudaThreadSynchronize();
  *alg = iu::getTime() - interm;
  *complete = iu::getTime() - start;

  cusparseDestroy(handle);

  return;
}

//////////////////////////////////////////////////////////////////
int main(int argc, char *argv[])
{
  //  // Sparse matrix
  //  cusparseCreate(&handle);

  char* name[] = {"Standard: ", "No Tex:   ", "Shared:   ", "Single:   ", "Single2:  ", "Sparse:   "};
  int sizes[] = {256, 1024, 2048};

  float lambda    = 5.0f;
  int   max_iter  = 100;

  double init[NSIZES][NALG];
  double alg[NSIZES][NALG];
  double complete[NSIZES][NALG];
  for (int a=0; a<NALG; a++)
  {
    for(int sz=0; sz<NSIZES; sz++)
    {
      init[sz][a] = -1.0;
      alg[sz][a] = -1.0;
      complete[sz][a] = -1.0;
    }
  }

  // Read input
//  iu::ImageGpu_32f_C1* input_full = iu::imread_cu32f_C1("../../Data/test/cat.pgm");
  iu::ImageGpu_32f_C1* input_full = iu::imread_cu32f_C1("/home/markus/Downloads/lena_bw_2048.pgm");

  for (int s=0; s<NSIZES; s++)
  {
    // Downsample and create images
    iu::ImageGpu_32f_C1 input_resized(sizes[s], sizes[s]*input_full->height()/input_full->width());
    iu::reduce(input_full, &input_resized);

    iu::ImageGpu_32f_C1 output(input_resized.size());
    iu::ImageGpu_32f_C1 output_notex(input_resized.size());
    iu::ImageGpu_32f_C1 output_shared(input_resized.size());
    iu::ImageGpu_32f_C1 output_shared_single(input_resized.size());
    iu::ImageGpu_32f_C1 output_shared_single2(input_resized.size());
    iu::ImageGpu_32f_C1 output_sparse(input_resized.size());
    iu::copy(&input_resized, &output);
    iu::copy(&input_resized, &output_notex);
    iu::copy(&input_resized, &output_shared);
    iu::copy(&input_resized, &output_shared_single);
    iu::copy(&input_resized, &output_shared_single2);
    iu::copy(&input_resized, &output_sparse);

    int calg = 0;
    // Co calculations of standard ROF model
    calcROF(&input_resized, &output,  lambda, max_iter, &init[s][calg], &alg[s][calg], &complete[s][calg]);
    calg++;

    // Co calculations of standard ROF with no texture model
    calcROF(&input_resized, &output_notex,  lambda, max_iter, &init[s][calg], &alg[s][calg], &complete[s][calg], true);
    calg++;

    // Co calculations of standard ROF with shared memory
    calcROFshared(&input_resized, &output_shared,  lambda, max_iter, &init[s][calg], &alg[s][calg], &complete[s][calg]);
    calg++;

    // Co calculations of standard ROF with shared memory in single kernel
    calcROFshared(&input_resized, &output_shared_single,  lambda, max_iter, &init[s][calg], &alg[s][calg], &complete[s][calg], true, 1);
    calg++;

    // Co calculations of standard ROF with shared memory in single kernel with two iterations
    calcROFshared(&input_resized, &output_shared_single2,  lambda, max_iter, &init[s][calg], &alg[s][calg], &complete[s][calg], true, 2);
    calg++;

  //    // Co calculations of sparse ROF model
  //    calcROFSparse(&input_resized, &output_sparse,  lambda, max_iter, &init[s][calg], &alg[s][calg], &complete[s][calg]);
  //    calg++;

    // Save Output
    char buffer [50];
    sprintf(buffer, "%d_input.png", sizes[s]);
    iu::imsave(&input_resized, buffer);
    sprintf(buffer, "%d_std_output.png", sizes[s]);
    iu::imsave(&output, buffer);
    sprintf(buffer, "%d_notex_output.png", sizes[s]);
    iu::imsave(&output_notex, buffer);
    sprintf(buffer, "%d_shared_output.png", sizes[s]);
    iu::imsave(&output_shared, buffer);
    sprintf(buffer, "%d_shared_single_output.png", sizes[s]);
    iu::imsave(&output_shared_single, buffer);
    sprintf(buffer, "%d_shared_single2_output.png", sizes[s]);
    iu::imsave(&output_shared_single2, buffer);
//    sprintf(buffer, "%d_sparse_output.png", sizes[s]);
//    iu::imsave(&output_sparse, buffer);
}

  std::cout << "\t\t";
  for(int sz=0; sz<NSIZES; sz++)
  {
    char buffer [50];
    sprintf(buffer, "%d", sizes[sz]);
    std::cout.width(8);
    std::cout << buffer << "\t\t";
  }
  std::cout << std::endl;
  for (int a=0; a<NALG; a++)
  {
    std::cout << name[a]<< "\t";
    for(int sz=0; sz<NSIZES; sz++)
    {
      std::cout.width(7);
      std::cout << complete[sz][a] << " (";
      std::cout.width(7);
      std::cout << alg[sz][a] << ") \t";
    }
    std::cout << std::endl;
  }
  std::cout << std::endl;

  // Clean up
  //  cusparseDestroy(handle);
  delete input_full;

  return 0;
}
<commit_msg><commit_after>#include <math.h>
#include <iostream>

#include <cuda.h>
#include <cusparse.h>

#include <iucore.h>
#include <iusparse.h>
#include <iuio.h>
#include <iutransform.h>

#include "print_helpers.h"

#define NSIZES 3
#define NALG   6

//cusparseHandle_t handle = 0;

// Forward declarations
void rof_primal_dual(iu::ImageGpu_32f_C1* device_f, iu::ImageGpu_32f_C1* device_u,
                     iu::ImageGpu_32f_C1* device_u_, iu::ImageGpu_32f_C2* device_p,
                     float lambda, int max_iter);

void rof_primal_dual_sparse(iu::SparseMatrixGpu_32f* G,
                            iu::ImageGpu_32f_C1* device_f, iu::ImageGpu_32f_C1* device_u,
                            iu::ImageGpu_32f_C1* device_u_, iu::ImageGpu_32f_C2* device_p,
                            float lambda, int max_iter);

void rof_primal_dual_notex(iu::ImageGpu_32f_C1* device_f, iu::ImageGpu_32f_C1* device_u,
                           iu::ImageGpu_32f_C1* device_u_, iu::ImageGpu_32f_C2* device_p,
                           float lambda, int max_iter);

void rof_primal_dual_shared(iu::ImageGpu_32f_C1* device_f, iu::ImageGpu_32f_C1* device_u,
                            iu::ImageGpu_32f_C1* device_u_, iu::ImageGpu_32f_C2* device_p,
                            float lambda, int max_iter);

void rof_primal_dual_shared_single(iu::ImageGpu_32f_C1* device_f, iu::ImageGpu_32f_C1* device_u,
                            iu::ImageGpu_32f_C2* device_p, float lambda, int max_iter);

void rof_primal_dual_shared_single2(iu::ImageGpu_32f_C1* device_f, iu::ImageGpu_32f_C1* device_u,
                                    iu::ImageGpu_32f_C2* device_p, float lambda, int max_iter);

// Calls
void calcROF(iu::ImageGpu_32f_C1* f, iu::ImageGpu_32f_C1* u,
             float lambda, int max_iter, double* init, double* alg, double* complete,
             bool notex=false)
{
  cudaThreadSynchronize();
  double start = iu::getTime();

  iu::ImageGpu_32f_C1 u_(u->size());
  iu::copy(u, &u_);
  iu::ImageGpu_32f_C2 p(u->size());
  iu::setValue(make_float2(0.0f, 0.0f), &p, p.roi());

  cudaThreadSynchronize();
  double interm = iu::getTime();
  *init = interm - start;

  if (notex)
    rof_primal_dual_notex(f, u, &u_, &p, lambda, max_iter);
  else
    rof_primal_dual(f, u, &u_, &p, lambda, max_iter);

  cudaThreadSynchronize();
  *alg = iu::getTime() - interm;
  *complete = iu::getTime() - start;

  return;
}

void calcROFshared(iu::ImageGpu_32f_C1* f, iu::ImageGpu_32f_C1* u,
                   float lambda, int max_iter, double* init, double* alg, double* complete,
                   bool single=false, int internal=2)
{
  cudaThreadSynchronize();
  double start = iu::getTime();

  iu::ImageGpu_32f_C1 u_(u->size());
  iu::copy(u, &u_);
  iu::ImageGpu_32f_C2 p(u->size());
  iu::setValue(make_float2(0.0f, 0.0f), &p, p.roi());

  cudaThreadSynchronize();
  double interm = iu::getTime();
  *init = interm - start;

  if (single)
  {
    if (internal == 1)
      rof_primal_dual_shared_single(f, u, &p, lambda, max_iter);
    else if (internal == 2)
      rof_primal_dual_shared_single2(f, u, &p, lambda, max_iter);
  }
  else
    rof_primal_dual_shared(f, u, &u_, &p, lambda, max_iter);

  cudaThreadSynchronize();
  *alg = iu::getTime() - interm;
  *complete = iu::getTime() - start;

  return;
}

void calcROFSparse(iu::ImageGpu_32f_C1* f, iu::ImageGpu_32f_C1* u,
                   float lambda, int max_iter, double* init, double* alg, double* complete)
{
  // Sparse matrix
  cusparseHandle_t handle = 0;
  cusparseCreate(&handle);

  cudaThreadSynchronize();
  double start = iu::getTime();

  iu::ImageGpu_32f_C1 u_(u->size());
  iu::copy(u, &u_);
  iu::ImageGpu_32f_C2 p(u->size());
  iu::setValue(make_float2(0.0f, 0.0f), &p, p.roi());

  // Generate Matrix G
  iu::LinearHostMemory<int> rowG(u->stride()*u->height()*4);
  iu::LinearHostMemory<int> colG(u->stride()*u->height()*4);
  iu::LinearHostMemory<float> valG(u->stride()*u->height()*4);

  int cind = 0;
  for (int y=0; y<u->height(); y++)
  {
    for (int x=0; x<u->width(); x++)
    {
      if (x<u->width()-1)
      {
        *rowG.data(cind) = y*p.stride()*2 + x*2;
        *colG.data(cind) = y*u->stride() + x;
        *valG.data(cind) = -1.0f;
        cind++;

        *rowG.data(cind) = y*p.stride()*2 + x*2;
        *colG.data(cind) = y*u->stride() + x+1;
        *valG.data(cind) = 1.0f;
        cind++;
      }
      if (y<u->height()-1)
      {
        *rowG.data(cind) = y*p.stride()*2 + x*2+1;
        *colG.data(cind) = y*u->stride() + x;
        *valG.data(cind) = -1.0f;
        cind++;

        *rowG.data(cind) = y*p.stride()*2 + x*2+1;
        *colG.data(cind) = (y+1)*u->stride() + x;
        *valG.data(cind) = 1.0f;
        cind++;
      }
    }
  }
  iu::LinearDeviceMemory<int> rowG_d(cind);
  iu::copy(&rowG, &rowG_d);
  iu::LinearDeviceMemory<int> colG_d(cind);
  iu::copy(&colG, &colG_d);
  iu::LinearDeviceMemory<float> valG_d(cind);
  iu::copy(&valG, &valG_d);
  iu::SparseMatrixGpu_32f G_d(&handle, &valG_d, &rowG_d, p.stride()*2*p.height(), &colG_d, u->stride()*u->height());

  G_d.changeSparseFormat(CSR);

  cudaThreadSynchronize();
  double interm = iu::getTime();
  *init = interm - start;

  rof_primal_dual_sparse(&G_d, f, u, &u_, &p, lambda, max_iter);

  cudaThreadSynchronize();
  *alg = iu::getTime() - interm;
  *complete = iu::getTime() - start;

  cusparseDestroy(handle);

  return;
}

//////////////////////////////////////////////////////////////////
int main(int argc, char *argv[])
{
  //  // Sparse matrix
  //  cusparseCreate(&handle);

  char* name[] = {"Standard: ", "No Tex:   ", "Shared:   ", "Single:   ", "Single2:  ", "Sparse:   "};
  int sizes[] = {256, 1024, 2048};

  float lambda    = 5.0f;
  int   max_iter  = 100;

  double init[NSIZES][NALG];
  double alg[NSIZES][NALG];
  double complete[NSIZES][NALG];
  for (int a=0; a<NALG; a++)
  {
    for(int sz=0; sz<NSIZES; sz++)
    {
      init[sz][a] = -1.0;
      alg[sz][a] = -1.0;
      complete[sz][a] = -1.0;
    }
  }

  // Read input
  iu::ImageGpu_32f_C1* input_full = iu::imread_cu32f_C1("../../Data/test/cat.pgm");
//  iu::ImageGpu_32f_C1* input_full = iu::imread_cu32f_C1("/home/markus/Downloads/lena_bw_2048.pgm");

  for (int s=0; s<NSIZES; s++)
  {
    // Downsample and create images
    iu::ImageGpu_32f_C1 input_resized(sizes[s], sizes[s]*input_full->height()/input_full->width());
    iu::reduce(input_full, &input_resized);

    iu::ImageGpu_32f_C1 output(input_resized.size());
    iu::ImageGpu_32f_C1 output_notex(input_resized.size());
    iu::ImageGpu_32f_C1 output_shared(input_resized.size());
    iu::ImageGpu_32f_C1 output_shared_single(input_resized.size());
    iu::ImageGpu_32f_C1 output_shared_single2(input_resized.size());
    iu::ImageGpu_32f_C1 output_sparse(input_resized.size());
    iu::copy(&input_resized, &output);
    iu::copy(&input_resized, &output_notex);
    iu::copy(&input_resized, &output_shared);
    iu::copy(&input_resized, &output_shared_single);
    iu::copy(&input_resized, &output_shared_single2);
    iu::copy(&input_resized, &output_sparse);

    int calg = 0;
    // Co calculations of standard ROF model
    calcROF(&input_resized, &output,  lambda, max_iter, &init[s][calg], &alg[s][calg], &complete[s][calg]);
    calg++;

    // Co calculations of standard ROF with no texture model
    calcROF(&input_resized, &output_notex,  lambda, max_iter, &init[s][calg], &alg[s][calg], &complete[s][calg], true);
    calg++;

    // Co calculations of standard ROF with shared memory
    calcROFshared(&input_resized, &output_shared,  lambda, max_iter, &init[s][calg], &alg[s][calg], &complete[s][calg]);
    calg++;

    // Co calculations of standard ROF with shared memory in single kernel
    calcROFshared(&input_resized, &output_shared_single,  lambda, max_iter, &init[s][calg], &alg[s][calg], &complete[s][calg], true, 1);
    calg++;

    // Co calculations of standard ROF with shared memory in single kernel with two iterations
    calcROFshared(&input_resized, &output_shared_single2,  lambda, max_iter, &init[s][calg], &alg[s][calg], &complete[s][calg], true, 2);
    calg++;

  //    // Co calculations of sparse ROF model
  //    calcROFSparse(&input_resized, &output_sparse,  lambda, max_iter, &init[s][calg], &alg[s][calg], &complete[s][calg]);
  //    calg++;

    // Save Output
    char buffer [50];
    sprintf(buffer, "%d_input.png", sizes[s]);
    iu::imsave(&input_resized, buffer);
    sprintf(buffer, "%d_std_output.png", sizes[s]);
    iu::imsave(&output, buffer);
    sprintf(buffer, "%d_notex_output.png", sizes[s]);
    iu::imsave(&output_notex, buffer);
    sprintf(buffer, "%d_shared_output.png", sizes[s]);
    iu::imsave(&output_shared, buffer);
    sprintf(buffer, "%d_shared_single_output.png", sizes[s]);
    iu::imsave(&output_shared_single, buffer);
    sprintf(buffer, "%d_shared_single2_output.png", sizes[s]);
    iu::imsave(&output_shared_single2, buffer);
//    sprintf(buffer, "%d_sparse_output.png", sizes[s]);
//    iu::imsave(&output_sparse, buffer);
}

  std::cout << "\t\t";
  for(int sz=0; sz<NSIZES; sz++)
  {
    char buffer [50];
    sprintf(buffer, "%d", sizes[sz]);
    std::cout.width(8);
    std::cout << buffer << "\t\t";
  }
  std::cout << std::endl;
  for (int a=0; a<NALG; a++)
  {
    std::cout << name[a]<< "\t";
    for(int sz=0; sz<NSIZES; sz++)
    {
      std::cout.width(7);
      std::cout << complete[sz][a] << " (";
      std::cout.width(7);
      std::cout << alg[sz][a] << ") \t";
    }
    std::cout << std::endl;
  }
  std::cout << std::endl;

  // Clean up
  //  cusparseDestroy(handle);
  delete input_full;

  return 0;
}
<|endoftext|>


<commit_before>// ***************************************************************************
//
//   Generated automatically by genwrapper.
//   Please DO NOT EDIT this file!
//
// ***************************************************************************

#include <osgIntrospection/ReflectionMacros>
#include <osgIntrospection/TypedMethodInfo>
#include <osgIntrospection/StaticMethodInfo>
#include <osgIntrospection/Attributes>

#include <osg/Camera>
#include <osg/FrameStamp>
#include <osg/GraphicsThread>
#include <osg/Node>
#include <osg/Timer>
#include <osgViewer/Viewer>

// Must undefine IN and OUT macros defined in Windows headers
#ifdef IN
#undef IN
#endif
#ifdef OUT
#undef OUT
#endif

TYPE_NAME_ALIAS(std::vector< osg::GraphicsContext * >, osgViewer::Viewer::Contexts);

TYPE_NAME_ALIAS(std::vector< osgViewer::GraphicsWindow * >, osgViewer::Viewer::Windows);

TYPE_NAME_ALIAS(std::vector< osg::Camera * >, osgViewer::Viewer::Cameras);

BEGIN_ENUM_REFLECTOR(osgViewer::Viewer::ThreadingModel)
	I_EnumLabel(osgViewer::Viewer::SingleThreaded);
	I_EnumLabel(osgViewer::Viewer::ThreadPerContext);
	I_EnumLabel(osgViewer::Viewer::ThreadPerCamera);
END_REFLECTOR

BEGIN_ENUM_REFLECTOR(osgViewer::Viewer::BarrierPosition)
	I_EnumLabel(osgViewer::Viewer::BeforeSwapBuffers);
	I_EnumLabel(osgViewer::Viewer::AfterSwapBuffers);
END_REFLECTOR

BEGIN_OBJECT_REFLECTOR(osgViewer::Viewer)
	I_BaseType(osgViewer::View);
	I_Constructor0(____Viewer,
	               "",
	               "");
	I_Method0(bool, isRealized,
	          __bool__isRealized,
	          "Get whether at least of one of this viewers windows are realized. ",
	          "");
	I_Method0(void, realize,
	          __void__realize,
	          "set up windows and associated threads. ",
	          "");
	I_Method1(void, setDone, IN, bool, done,
	          __void__setDone__bool,
	          "",
	          "");
	I_Method0(bool, done,
	          __bool__done,
	          "",
	          "");
	I_Method1(void, setStartTick, IN, osg::Timer_t, tick,
	          __void__setStartTick__osg_Timer_t,
	          "",
	          "");
	I_Method0(osg::Timer_t, getStartTick,
	          __osg_Timer_t__getStartTick,
	          "",
	          "");
	I_MethodWithDefaults1(void, setReferenceTime, IN, double, time, 0.0,
	                      __void__setReferenceTime__double,
	                      "",
	                      "");
	I_Method1(void, setFrameStamp, IN, osg::FrameStamp *, frameStamp,
	          __void__setFrameStamp__osg_FrameStamp_P1,
	          "",
	          "");
	I_Method0(osg::FrameStamp *, getFrameStamp,
	          __osg_FrameStamp_P1__getFrameStamp,
	          "",
	          "");
	I_Method0(const osg::FrameStamp *, getFrameStamp,
	          __C5_osg_FrameStamp_P1__getFrameStamp,
	          "",
	          "");
	I_Method1(void, setSceneData, IN, osg::Node *, node,
	          __void__setSceneData__osg_Node_P1,
	          "",
	          "");
	I_Method1(void, setThreadingModel, IN, osgViewer::Viewer::ThreadingModel, threadingModel,
	          __void__setThreadingModel__ThreadingModel,
	          "Set the threading model the rendering traversals will use. ",
	          "");
	I_Method0(osgViewer::Viewer::ThreadingModel, getThreadingModel,
	          __ThreadingModel__getThreadingModel,
	          "Get the threading model the rendering traversals will use. ",
	          "");
	I_Method1(void, setUseMainThreadForRenderingTraversals, IN, bool, flag,
	          __void__setUseMainThreadForRenderingTraversals__bool,
	          "Set whether the main thread, calling frame(), should be used for the rendering traversals. ",
	          "");
	I_Method0(bool, getUseMainThreadForRenderingTraversals,
	          __bool__getUseMainThreadForRenderingTraversals,
	          "Get whether the main thread, calling frame(), should be used for the rendering traversals. ",
	          "");
	I_Method1(void, setEndBarrierPosition, IN, osgViewer::Viewer::BarrierPosition, bp,
	          __void__setEndBarrierPosition__BarrierPosition,
	          "Set the position of the end barrier. ",
	          "AfterSwapBuffers will may result is slightly higher framerates, by may lead to inconcistent swapping between different windows. BeforeSwapBuffers may lead to slightly lower framerate, but improve consistency in timing of swap buffers, especially important if you are likely to consistently break frame. ");
	I_Method0(osgViewer::Viewer::BarrierPosition, getEndBarrierPosition,
	          __BarrierPosition__getEndBarrierPosition,
	          "Get the end barrier position. ",
	          "");
	I_Method1(void, setKeyEventSetsDone, IN, int, key,
	          __void__setKeyEventSetsDone__int,
	          "Set the key event that the viewer checks on each frame to see if the viewer's done flag should be set to signal end of viewers main loop. ",
	          "Default value is Escape (osgGA::GUIEVentAdapter::KEY_Escape). Setting to 0 switches off the feature. ");
	I_Method0(int, getKeyEventSetsDone,
	          __int__getKeyEventSetsDone,
	          "get the key event that the viewer checks on each frame to see if the viewer's done flag. ",
	          "");
	I_Method1(void, setQuitEventSetsDone, IN, bool, flag,
	          __void__setQuitEventSetsDone__bool,
	          "if the flag is true, the viewer set its done flag when a QUIT_APPLICATION is received, false disables this feature ",
	          "");
	I_Method0(bool, getQuitEventSetsDone,
	          __bool__getQuitEventSetsDone,
	          "",
	          "true if the viewer respond to the QUIT_APPLICATION-event  ");
	I_Method0(int, run,
	          __int__run,
	          "Execute a main frame loop. ",
	          "Equivialant to while (!viewer.done()) viewer.frame(); Also calls realize() if the viewer is not already realized, and installs trackball manipulator if one is not already assigned.");
	I_MethodWithDefaults1(void, frame, IN, double, simulationTime, USE_REFERENCE_TIME,
	                      __void__frame__double,
	                      "Render a complete new frame. ",
	                      "Calls advance(), eventTraversal(), updateTraversal(), renderingTraversals(). ");
	I_MethodWithDefaults1(void, advance, IN, double, simulationTime, USE_REFERENCE_TIME,
	                      __void__advance__double,
	                      "",
	                      "");
	I_Method0(void, eventTraversal,
	          __void__eventTraversal,
	          "",
	          "");
	I_Method0(void, updateTraversal,
	          __void__updateTraversal,
	          "",
	          "");
	I_Method0(void, renderingTraversals,
	          __void__renderingTraversals,
	          "",
	          "");
	I_Method1(void, setCameraWithFocus, IN, osg::Camera *, camera,
	          __void__setCameraWithFocus__osg_Camera_P1,
	          "",
	          "");
	I_Method0(osg::Camera *, getCameraWithFocus,
	          __osg_Camera_P1__getCameraWithFocus,
	          "",
	          "");
	I_Method0(const osg::Camera *, getCameraWithFocus,
	          __C5_osg_Camera_P1__getCameraWithFocus,
	          "",
	          "");
	I_MethodWithDefaults2(void, getContexts, IN, osgViewer::Viewer::Contexts &, contexts, , IN, bool, onlyValid, true,
	                      __void__getContexts__Contexts_R1__bool,
	                      "",
	                      "");
	I_MethodWithDefaults2(void, getWindows, IN, osgViewer::Viewer::Windows &, windows, , IN, bool, onlyValid, true,
	                      __void__getWindows__Windows_R1__bool,
	                      "",
	                      "");
	I_MethodWithDefaults2(void, getCameras, IN, osgViewer::Viewer::Cameras &, cameras, , IN, bool, onlyActive, true,
	                      __void__getCameras__Cameras_R1__bool,
	                      "",
	                      "");
	I_Method1(void, setRealizeOperation, IN, osg::Operation *, op,
	          __void__setRealizeOperation__osg_Operation_P1,
	          "Set the graphics operation to call on realization of the viewers graphics windows. ",
	          "");
	I_Method0(osg::Operation *, getRealizeOperation,
	          __osg_Operation_P1__getRealizeOperation,
	          "Get the graphics operation to call on realization of the viewers graphics windows. ",
	          "");
	I_Method0(void, stopThreading,
	          __void__stopThreading,
	          "Stop any threads begin run by viewer. ",
	          "");
	I_Method0(void, startThreading,
	          __void__startThreading,
	          "Start any threads required by the viewer, as per viewers ThreadingModel. ",
	          "");
	I_Method0(void, setUpRenderingSupport,
	          __void__setUpRenderingSupport,
	          "Set up the Operations to render the various viewer cameras on the viewers graphics windows. ",
	          "");
	I_SimpleProperty(osg::Camera *, CameraWithFocus,
	                 __osg_Camera_P1__getCameraWithFocus,
	                 __void__setCameraWithFocus__osg_Camera_P1);
	I_SimpleProperty(bool, Done,
	                 0,
	                 __void__setDone__bool);
	I_SimpleProperty(osgViewer::Viewer::BarrierPosition, EndBarrierPosition,
	                 __BarrierPosition__getEndBarrierPosition,
	                 __void__setEndBarrierPosition__BarrierPosition);
	I_SimpleProperty(osg::FrameStamp *, FrameStamp,
	                 __osg_FrameStamp_P1__getFrameStamp,
	                 __void__setFrameStamp__osg_FrameStamp_P1);
	I_SimpleProperty(int, KeyEventSetsDone,
	                 __int__getKeyEventSetsDone,
	                 __void__setKeyEventSetsDone__int);
	I_SimpleProperty(bool, QuitEventSetsDone,
	                 __bool__getQuitEventSetsDone,
	                 __void__setQuitEventSetsDone__bool);
	I_SimpleProperty(osg::Operation *, RealizeOperation,
	                 __osg_Operation_P1__getRealizeOperation,
	                 __void__setRealizeOperation__osg_Operation_P1);
	I_SimpleProperty(double, ReferenceTime,
	                 0,
	                 __void__setReferenceTime__double);
	I_SimpleProperty(osg::Node *, SceneData,
	                 0,
	                 __void__setSceneData__osg_Node_P1);
	I_SimpleProperty(osg::Timer_t, StartTick,
	                 __osg_Timer_t__getStartTick,
	                 __void__setStartTick__osg_Timer_t);
	I_SimpleProperty(osgViewer::Viewer::ThreadingModel, ThreadingModel,
	                 __ThreadingModel__getThreadingModel,
	                 __void__setThreadingModel__ThreadingModel);
	I_SimpleProperty(bool, UseMainThreadForRenderingTraversals,
	                 __bool__getUseMainThreadForRenderingTraversals,
	                 __void__setUseMainThreadForRenderingTraversals__bool);
END_REFLECTOR

STD_VECTOR_REFLECTOR(std::vector< osg::Camera * >);

<commit_msg>Updated wrappers<commit_after>// ***************************************************************************
//
//   Generated automatically by genwrapper.
//   Please DO NOT EDIT this file!
//
// ***************************************************************************

#include <osgIntrospection/ReflectionMacros>
#include <osgIntrospection/TypedMethodInfo>
#include <osgIntrospection/StaticMethodInfo>
#include <osgIntrospection/Attributes>

#include <osg/Camera>
#include <osg/FrameStamp>
#include <osg/GraphicsThread>
#include <osg/Node>
#include <osg/Timer>
#include <osgViewer/Viewer>

// Must undefine IN and OUT macros defined in Windows headers
#ifdef IN
#undef IN
#endif
#ifdef OUT
#undef OUT
#endif

TYPE_NAME_ALIAS(std::vector< osg::GraphicsContext * >, osgViewer::Viewer::Contexts);

TYPE_NAME_ALIAS(std::vector< osgViewer::GraphicsWindow * >, osgViewer::Viewer::Windows);

TYPE_NAME_ALIAS(std::vector< osg::Camera * >, osgViewer::Viewer::Cameras);

TYPE_NAME_ALIAS(std::vector< OpenThreads::Thread * >, osgViewer::Viewer::Threads);

TYPE_NAME_ALIAS(std::vector< osg::OperationsThread * >, osgViewer::Viewer::OperationsThreads);

BEGIN_ENUM_REFLECTOR(osgViewer::Viewer::ThreadingModel)
	I_EnumLabel(osgViewer::Viewer::SingleThreaded);
	I_EnumLabel(osgViewer::Viewer::CullDrawThreadPerContext);
	I_EnumLabel(osgViewer::Viewer::DrawThreadPerContext);
	I_EnumLabel(osgViewer::Viewer::CullThreadPerCameraDrawThreadPerContext);
	I_EnumLabel(osgViewer::Viewer::AutomaticSelection);
END_REFLECTOR

BEGIN_ENUM_REFLECTOR(osgViewer::Viewer::BarrierPosition)
	I_EnumLabel(osgViewer::Viewer::BeforeSwapBuffers);
	I_EnumLabel(osgViewer::Viewer::AfterSwapBuffers);
END_REFLECTOR

BEGIN_OBJECT_REFLECTOR(osgViewer::Viewer)
	I_BaseType(osgViewer::View);
	I_Constructor0(____Viewer,
	               "",
	               "");
	I_Method0(bool, isRealized,
	          __bool__isRealized,
	          "Get whether at least of one of this viewers windows are realized. ",
	          "");
	I_Method0(void, realize,
	          __void__realize,
	          "set up windows and associated threads. ",
	          "");
	I_Method1(void, setDone, IN, bool, done,
	          __void__setDone__bool,
	          "",
	          "");
	I_Method0(bool, done,
	          __bool__done,
	          "",
	          "");
	I_Method1(void, setStartTick, IN, osg::Timer_t, tick,
	          __void__setStartTick__osg_Timer_t,
	          "",
	          "");
	I_Method0(osg::Timer_t, getStartTick,
	          __osg_Timer_t__getStartTick,
	          "",
	          "");
	I_MethodWithDefaults1(void, setReferenceTime, IN, double, time, 0.0,
	                      __void__setReferenceTime__double,
	                      "",
	                      "");
	I_Method1(void, setFrameStamp, IN, osg::FrameStamp *, frameStamp,
	          __void__setFrameStamp__osg_FrameStamp_P1,
	          "",
	          "");
	I_Method0(osg::FrameStamp *, getFrameStamp,
	          __osg_FrameStamp_P1__getFrameStamp,
	          "",
	          "");
	I_Method0(const osg::FrameStamp *, getFrameStamp,
	          __C5_osg_FrameStamp_P1__getFrameStamp,
	          "",
	          "");
	I_Method1(void, setSceneData, IN, osg::Node *, node,
	          __void__setSceneData__osg_Node_P1,
	          "",
	          "");
	I_Method1(void, setThreadingModel, IN, osgViewer::Viewer::ThreadingModel, threadingModel,
	          __void__setThreadingModel__ThreadingModel,
	          "Set the threading model the rendering traversals will use. ",
	          "");
	I_Method0(osgViewer::Viewer::ThreadingModel, getThreadingModel,
	          __ThreadingModel__getThreadingModel,
	          "Get the threading model the rendering traversals will use. ",
	          "");
	I_Method1(void, setUseMainThreadForRenderingTraversals, IN, bool, flag,
	          __void__setUseMainThreadForRenderingTraversals__bool,
	          "Set whether the main thread, calling frame(), should be used for the rendering traversals. ",
	          "");
	I_Method0(bool, getUseMainThreadForRenderingTraversals,
	          __bool__getUseMainThreadForRenderingTraversals,
	          "Get whether the main thread, calling frame(), should be used for the rendering traversals. ",
	          "");
	I_Method0(osgViewer::Viewer::ThreadingModel, suggestBestThreadingModel,
	          __ThreadingModel__suggestBestThreadingModel,
	          "Let the viewer suggest the best threading model for the viewers camera/window setup and the hardware available. ",
	          "");
	I_Method1(void, setEndBarrierPosition, IN, osgViewer::Viewer::BarrierPosition, bp,
	          __void__setEndBarrierPosition__BarrierPosition,
	          "Set the position of the end barrier. ",
	          "AfterSwapBuffers will may result is slightly higher framerates, by may lead to inconcistent swapping between different windows. BeforeSwapBuffers may lead to slightly lower framerate, but improve consistency in timing of swap buffers, especially important if you are likely to consistently break frame. ");
	I_Method0(osgViewer::Viewer::BarrierPosition, getEndBarrierPosition,
	          __BarrierPosition__getEndBarrierPosition,
	          "Get the end barrier position. ",
	          "");
	I_Method1(void, setKeyEventSetsDone, IN, int, key,
	          __void__setKeyEventSetsDone__int,
	          "Set the key event that the viewer checks on each frame to see if the viewer's done flag should be set to signal end of viewers main loop. ",
	          "Default value is Escape (osgGA::GUIEVentAdapter::KEY_Escape). Setting to 0 switches off the feature. ");
	I_Method0(int, getKeyEventSetsDone,
	          __int__getKeyEventSetsDone,
	          "get the key event that the viewer checks on each frame to see if the viewer's done flag. ",
	          "");
	I_Method1(void, setQuitEventSetsDone, IN, bool, flag,
	          __void__setQuitEventSetsDone__bool,
	          "if the flag is true, the viewer set its done flag when a QUIT_APPLICATION is received, false disables this feature ",
	          "");
	I_Method0(bool, getQuitEventSetsDone,
	          __bool__getQuitEventSetsDone,
	          "",
	          "true if the viewer respond to the QUIT_APPLICATION-event  ");
	I_Method0(int, run,
	          __int__run,
	          "Execute a main frame loop. ",
	          "Equivialant to while (!viewer.done()) viewer.frame(); Also calls realize() if the viewer is not already realized, and installs trackball manipulator if one is not already assigned.");
	I_MethodWithDefaults1(void, frame, IN, double, simulationTime, USE_REFERENCE_TIME,
	                      __void__frame__double,
	                      "Render a complete new frame. ",
	                      "Calls advance(), eventTraversal(), updateTraversal(), renderingTraversals(). ");
	I_MethodWithDefaults1(void, advance, IN, double, simulationTime, USE_REFERENCE_TIME,
	                      __void__advance__double,
	                      "",
	                      "");
	I_Method0(void, eventTraversal,
	          __void__eventTraversal,
	          "",
	          "");
	I_Method0(void, updateTraversal,
	          __void__updateTraversal,
	          "",
	          "");
	I_Method0(void, renderingTraversals,
	          __void__renderingTraversals,
	          "",
	          "");
	I_Method1(void, setCameraWithFocus, IN, osg::Camera *, camera,
	          __void__setCameraWithFocus__osg_Camera_P1,
	          "",
	          "");
	I_Method0(osg::Camera *, getCameraWithFocus,
	          __osg_Camera_P1__getCameraWithFocus,
	          "",
	          "");
	I_Method0(const osg::Camera *, getCameraWithFocus,
	          __C5_osg_Camera_P1__getCameraWithFocus,
	          "",
	          "");
	I_MethodWithDefaults2(void, getContexts, IN, osgViewer::Viewer::Contexts &, contexts, , IN, bool, onlyValid, true,
	                      __void__getContexts__Contexts_R1__bool,
	                      "",
	                      "");
	I_MethodWithDefaults2(void, getWindows, IN, osgViewer::Viewer::Windows &, windows, , IN, bool, onlyValid, true,
	                      __void__getWindows__Windows_R1__bool,
	                      "",
	                      "");
	I_MethodWithDefaults2(void, getCameras, IN, osgViewer::Viewer::Cameras &, cameras, , IN, bool, onlyActive, true,
	                      __void__getCameras__Cameras_R1__bool,
	                      "",
	                      "");
	I_MethodWithDefaults2(void, getAllThreads, IN, osgViewer::Viewer::Threads &, threads, , IN, bool, onlyActive, true,
	                      __void__getAllThreads__Threads_R1__bool,
	                      "",
	                      "");
	I_MethodWithDefaults2(void, getOperationsThreads, IN, osgViewer::Viewer::OperationsThreads &, threads, , IN, bool, onlyActive, true,
	                      __void__getOperationsThreads__OperationsThreads_R1__bool,
	                      "",
	                      "");
	I_Method1(void, setRealizeOperation, IN, osg::Operation *, op,
	          __void__setRealizeOperation__osg_Operation_P1,
	          "Set the graphics operation to call on realization of the viewers graphics windows. ",
	          "");
	I_Method0(osg::Operation *, getRealizeOperation,
	          __osg_Operation_P1__getRealizeOperation,
	          "Get the graphics operation to call on realization of the viewers graphics windows. ",
	          "");
	I_Method0(void, stopThreading,
	          __void__stopThreading,
	          "Stop any threads begin run by viewer. ",
	          "");
	I_Method0(void, startThreading,
	          __void__startThreading,
	          "Start any threads required by the viewer, as per viewers ThreadingModel. ",
	          "");
	I_Method0(void, setUpRenderingSupport,
	          __void__setUpRenderingSupport,
	          "Set up the Operations to render the various viewer cameras on the viewers graphics windows. ",
	          "");
	I_SimpleProperty(osg::Camera *, CameraWithFocus,
	                 __osg_Camera_P1__getCameraWithFocus,
	                 __void__setCameraWithFocus__osg_Camera_P1);
	I_SimpleProperty(bool, Done,
	                 0,
	                 __void__setDone__bool);
	I_SimpleProperty(osgViewer::Viewer::BarrierPosition, EndBarrierPosition,
	                 __BarrierPosition__getEndBarrierPosition,
	                 __void__setEndBarrierPosition__BarrierPosition);
	I_SimpleProperty(osg::FrameStamp *, FrameStamp,
	                 __osg_FrameStamp_P1__getFrameStamp,
	                 __void__setFrameStamp__osg_FrameStamp_P1);
	I_SimpleProperty(int, KeyEventSetsDone,
	                 __int__getKeyEventSetsDone,
	                 __void__setKeyEventSetsDone__int);
	I_SimpleProperty(bool, QuitEventSetsDone,
	                 __bool__getQuitEventSetsDone,
	                 __void__setQuitEventSetsDone__bool);
	I_SimpleProperty(osg::Operation *, RealizeOperation,
	                 __osg_Operation_P1__getRealizeOperation,
	                 __void__setRealizeOperation__osg_Operation_P1);
	I_SimpleProperty(double, ReferenceTime,
	                 0,
	                 __void__setReferenceTime__double);
	I_SimpleProperty(osg::Node *, SceneData,
	                 0,
	                 __void__setSceneData__osg_Node_P1);
	I_SimpleProperty(osg::Timer_t, StartTick,
	                 __osg_Timer_t__getStartTick,
	                 __void__setStartTick__osg_Timer_t);
	I_SimpleProperty(osgViewer::Viewer::ThreadingModel, ThreadingModel,
	                 __ThreadingModel__getThreadingModel,
	                 __void__setThreadingModel__ThreadingModel);
	I_SimpleProperty(bool, UseMainThreadForRenderingTraversals,
	                 __bool__getUseMainThreadForRenderingTraversals,
	                 __void__setUseMainThreadForRenderingTraversals__bool);
END_REFLECTOR

STD_VECTOR_REFLECTOR(std::vector< OpenThreads::Thread * >);

STD_VECTOR_REFLECTOR(std::vector< osg::Camera * >);

STD_VECTOR_REFLECTOR(std::vector< osg::OperationsThread * >);

<|endoftext|>


<commit_before>#include <assert.h>
#include <stdlib.h>

extern "C"
void __cxa_pure_virtual(void) {
        /* Pure C++ virtual call; abort! */
    assert("Pure C++ virtual call");
}

void* __attribute__ ((weak)) operator new(size_t size) {
    return malloc(size);
}

void* __attribute__ ((weak)) operator new[](size_t size) {
    return malloc(size);
}

void __attribute__ ((weak)) operator delete(void *ptr) {
    free(ptr);
}

void __attribute__ ((weak)) operator delete[](void *ptr) {
    free(ptr);
}
<commit_msg>Fix non-failing assertion<commit_after>#include <assert.h>
#include <stdlib.h>

extern "C"
void __cxa_pure_virtual(void) {
    /* Pure C++ virtual call; abort! */
    assert(false);
}

void* __attribute__ ((weak)) operator new(size_t size) {
    return malloc(size);
}

void* __attribute__ ((weak)) operator new[](size_t size) {
    return malloc(size);
}

void __attribute__ ((weak)) operator delete(void *ptr) {
    free(ptr);
}

void __attribute__ ((weak)) operator delete[](void *ptr) {
    free(ptr);
}
<|endoftext|>


<commit_before><commit_msg>Update doosabin/doosabin_test.cpp<commit_after><|endoftext|>


<commit_before>#include "BackgroundWorker.h"

#include <LuminaXDG.h>
#include <QMediaServiceSupportedFormatsInterface>
#include <QImageReader>
#include <QDir>
#include <QFileInfo>

BackgroundWorker::BackgroundWorker() : QObject(){

}

BackgroundWorker::~BackgroundWorker(){

}

void BackgroundWorker::startDirChecks(QString path){
  QDir dir(path);
  //Make sure to remove any symlinks or redundency in the path
  if(dir.canonicalPath()!=path){ path = dir.canonicalPath(); dir.cd(path); }
  qDebug() << "Starting Dir Checks:" << path;
  //First check for image files
  if(imgFilter.isEmpty()){
    //Initial Run - load supported image extensions
    QList<QByteArray> fmt = QImageReader::supportedImageFormats();
    for(int i=0; i<fmt.length(); i++){ imgFilter << "*."+QString(fmt[i]).toLower(); }
    qDebug() << "Supported Image Formats:" << imgFilter;
  }
  QStringList pics = dir.entryList(imgFilter, QDir::Files | QDir::NoDotAndDotDot, QDir::Name | QDir::IgnoreCase);
  if(!pics.isEmpty() && !imgFilter.isEmpty()){ emit ImagesAvailable(pics); }

  //Now check for multimedia files
  if(multiFilter.isEmpty()){
    //Initial Run - load supported multimedia extensions
    // (Auto-detection of supported types broken in Qt5 - just use everythings for now)
    multiFilter = LXDG::findAVFileExtensions();
    multiFilter.removeDuplicates();
    qDebug() << "Supported Multimedia Formats:" << multiFilter;
  }
  QStringList files = dir.entryList(multiFilter, QDir::Files | QDir::NoDotAndDotDot, QDir::Name | QDir::IgnoreCase);
  if(!files.isEmpty() && !multiFilter.isEmpty()){ emit MultimediaAvailable(files); }
  qDebug() << " - done with audio/multimedia checks";
  //Now check for ZFS snapshots of the directory
  if(!QFileInfo(path).isWritable() ){ return; } //skip ZFS checks if can't restore to this dir
  cdir = path;
  QStringList snapDirs;
  QString baseSnapDir;
  bool found = false;
  qDebug() << " - start searching for base snapshot directory";
  if(cdir == path && QFile::exists(csnapdir) ){
     //no need to re-search for it - just found it recently
    baseSnapDir= csnapdir; found=true;
  }else{
    while(dir.canonicalPath()!="/" && !found){
      if(dir.exists(".zfs/snapshot")){
        baseSnapDir = dir.canonicalPath()+"/.zfs/snapshot";
	found = true;
      }else{ dir.cdUp(); }
    }
  }
  qDebug() << " - done with base snapshot directory";
  cdir = path; csnapdir = baseSnapDir;
  //Now find the snapshots that contain this directory and save them
  if(found){
    qDebug() << " - start fetching snapshots";
    QString reldir = path;
	  reldir.remove(baseSnapDir.section("/.zfs/snapshot",0,0)); //convert to a relative path
    dir.cd(baseSnapDir);
    snapDirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Time);
    //Check that the current directory exists in each snapshot
    for(int i=0; i<snapDirs.length(); i++){
      if( !dir.exists(snapDirs[i]+"/"+reldir) ){
        snapDirs.removeAt(i);
	i--;
      }else{
	snapDirs[i] = QFileInfo(dir, snapDirs[i]+"/"+reldir).created().toString("yyyyMMddhhmmsszzz")+"::::"+snapDirs[i];
      }
    }
    qDebug() << " - done fetching snapshots";
    snapDirs.sort();
    //Sort the snapshots by time (newest last) and format them
    for(int i=0; i<snapDirs.length(); i++){
      snapDirs[i] = dir.absolutePath()+"/"+snapDirs[i].section("::::",1,50)+"/"+reldir;
    }
    if(!snapDirs.isEmpty()){ emit SnapshotsAvailable(baseSnapDir, snapDirs); }
    qDebug() << "Found snapshots";
  }
}

void BackgroundWorker::createStatusBarMsg(QFileInfoList fileList, QString path, QString messageFolders, QString messageFiles){

  //collect some statistics of dir and display them in statusbar
  //Get the total size of the items
  double totalSizes = 0;
  int numberFolders = 0;
  int numberFiles = 0;
  for(int i=0; i<fileList.length(); i++){
    if(!fileList[i].isDir()){
      numberFiles += 1;
      totalSizes += fileList[i].size(); //in Bytes
    }
    else { numberFolders += 1; }
  }
  //Convert the size into display units
  static QStringList units = QStringList() << tr("B") << tr("KB") << tr("MB") << tr("GB") << tr("TB");
  int cunit = 0;
  while(cunit < units.length() && totalSizes > 1024){
    cunit++;
    totalSizes = totalSizes/1024;
  }
  //Assemble the message
  QString msgStatusBar = QString(tr("%1: %2 / %3: %4")).arg(messageFolders).arg(numberFolders).arg(messageFiles).arg(numberFiles);

  if(totalSizes > 0){
    totalSizes = qRound(totalSizes*100)/100.0; //round to 2 decimel places
    msgStatusBar += "    "+QString(tr("Total size: %1 %2")).arg(QString::number(totalSizes), units[cunit]);
  }
  //If a path given, get the total capacity of it (percantage)
  if (!path.isEmpty()) { //path could be empty when fileList is based on user's selection
	  QString capacity = LOS::FileSystemCapacity(path) ;
      if (msgStatusBar.isEmpty()) msgStatusBar += QString(tr("Capacity: %1")).arg(capacity);
      else msgStatusBar += "   "+QString(tr("Capacity: %1")).arg(capacity);
  }
  //Emit the signal to show this on the UI
  if (!msgStatusBar.isEmpty()){
    emit Si_DisplayStatusBar(msgStatusBar);
  }
}
<commit_msg>use ++ in createStatusBarMgs over += 1<commit_after>#include "BackgroundWorker.h"

#include <LuminaXDG.h>
#include <QMediaServiceSupportedFormatsInterface>
#include <QImageReader>
#include <QDir>
#include <QFileInfo>

BackgroundWorker::BackgroundWorker() : QObject(){

}

BackgroundWorker::~BackgroundWorker(){

}

void BackgroundWorker::startDirChecks(QString path){
  QDir dir(path);
  //Make sure to remove any symlinks or redundency in the path
  if(dir.canonicalPath()!=path){ path = dir.canonicalPath(); dir.cd(path); }
  qDebug() << "Starting Dir Checks:" << path;
  //First check for image files
  if(imgFilter.isEmpty()){
    //Initial Run - load supported image extensions
    QList<QByteArray> fmt = QImageReader::supportedImageFormats();
    for(int i=0; i<fmt.length(); i++){ imgFilter << "*."+QString(fmt[i]).toLower(); }
    qDebug() << "Supported Image Formats:" << imgFilter;
  }
  QStringList pics = dir.entryList(imgFilter, QDir::Files | QDir::NoDotAndDotDot, QDir::Name | QDir::IgnoreCase);
  if(!pics.isEmpty() && !imgFilter.isEmpty()){ emit ImagesAvailable(pics); }

  //Now check for multimedia files
  if(multiFilter.isEmpty()){
    //Initial Run - load supported multimedia extensions
    // (Auto-detection of supported types broken in Qt5 - just use everythings for now)
    multiFilter = LXDG::findAVFileExtensions();
    multiFilter.removeDuplicates();
    qDebug() << "Supported Multimedia Formats:" << multiFilter;
  }
  QStringList files = dir.entryList(multiFilter, QDir::Files | QDir::NoDotAndDotDot, QDir::Name | QDir::IgnoreCase);
  if(!files.isEmpty() && !multiFilter.isEmpty()){ emit MultimediaAvailable(files); }
  qDebug() << " - done with audio/multimedia checks";
  //Now check for ZFS snapshots of the directory
  if(!QFileInfo(path).isWritable() ){ return; } //skip ZFS checks if can't restore to this dir
  cdir = path;
  QStringList snapDirs;
  QString baseSnapDir;
  bool found = false;
  qDebug() << " - start searching for base snapshot directory";
  if(cdir == path && QFile::exists(csnapdir) ){
     //no need to re-search for it - just found it recently
    baseSnapDir= csnapdir; found=true;
  }else{
    while(dir.canonicalPath()!="/" && !found){
      if(dir.exists(".zfs/snapshot")){
        baseSnapDir = dir.canonicalPath()+"/.zfs/snapshot";
	found = true;
      }else{ dir.cdUp(); }
    }
  }
  qDebug() << " - done with base snapshot directory";
  cdir = path; csnapdir = baseSnapDir;
  //Now find the snapshots that contain this directory and save them
  if(found){
    qDebug() << " - start fetching snapshots";
    QString reldir = path;
	  reldir.remove(baseSnapDir.section("/.zfs/snapshot",0,0)); //convert to a relative path
    dir.cd(baseSnapDir);
    snapDirs = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot, QDir::Time);
    //Check that the current directory exists in each snapshot
    for(int i=0; i<snapDirs.length(); i++){
      if( !dir.exists(snapDirs[i]+"/"+reldir) ){
        snapDirs.removeAt(i);
	i--;
      }else{
	snapDirs[i] = QFileInfo(dir, snapDirs[i]+"/"+reldir).created().toString("yyyyMMddhhmmsszzz")+"::::"+snapDirs[i];
      }
    }
    qDebug() << " - done fetching snapshots";
    snapDirs.sort();
    //Sort the snapshots by time (newest last) and format them
    for(int i=0; i<snapDirs.length(); i++){
      snapDirs[i] = dir.absolutePath()+"/"+snapDirs[i].section("::::",1,50)+"/"+reldir;
    }
    if(!snapDirs.isEmpty()){ emit SnapshotsAvailable(baseSnapDir, snapDirs); }
    qDebug() << "Found snapshots";
  }
}

void BackgroundWorker::createStatusBarMsg(QFileInfoList fileList, QString path, QString messageFolders, QString messageFiles){

  //collect some statistics of dir and display them in statusbar
  //Get the total size of the items
  double totalSizes = 0;
  int numberFolders = 0;
  int numberFiles = 0;
  for(int i=0; i<fileList.length(); i++){
    if(!fileList[i].isDir()){
      numberFiles++;
      totalSizes += fileList[i].size(); //in Bytes
    }
    else { numberFolders++; }
  }
  //Convert the size into display units
  static QStringList units = QStringList() << tr("B") << tr("KB") << tr("MB") << tr("GB") << tr("TB");
  int cunit = 0;
  while(cunit < units.length() && totalSizes > 1024){
    cunit++;
    totalSizes = totalSizes/1024;
  }
  //Assemble the message
  QString msgStatusBar = QString(tr("%1: %2 / %3: %4")).arg(messageFolders).arg(numberFolders).arg(messageFiles).arg(numberFiles);

  if(totalSizes > 0){
    totalSizes = qRound(totalSizes*100)/100.0; //round to 2 decimel places
    msgStatusBar += "    "+QString(tr("Total size: %1 %2")).arg(QString::number(totalSizes), units[cunit]);
  }
  //If a path given, get the total capacity of it (percantage)
  if (!path.isEmpty()) { //path could be empty when fileList is based on user's selection
	  QString capacity = LOS::FileSystemCapacity(path) ;
      if (msgStatusBar.isEmpty()) msgStatusBar += QString(tr("Capacity: %1")).arg(capacity);
      else msgStatusBar += "   "+QString(tr("Capacity: %1")).arg(capacity);
  }
  //Emit the signal to show this on the UI
  if (!msgStatusBar.isEmpty()){
    emit Si_DisplayStatusBar(msgStatusBar);
  }
}
<|endoftext|>


<commit_before>#include <bacs/system/process.hpp>

#include <yandex/contest/invoker/All.hpp>

#include <bunsan/config/cast.hpp>

#include <boost/property_tree/json_parser.hpp>

#include <sstream>

namespace bacs {
namespace system {
namespace process {

using namespace yandex::contest::invoker;

#define RLIM_UPDATE(SRC, DST, TR) \
  if (resource_limits.has_##SRC()) rlimit.DST = TR(resource_limits.SRC())

void setup(const yandex::contest::invoker::ProcessGroupPointer &process_group,
           const yandex::contest::invoker::ProcessPointer &process,
           const bacs::process::ResourceLimits &resource_limits) {
  ProcessGroup::ResourceLimits rlimit = process_group->resourceLimits();
  RLIM_UPDATE(real_time_limit_millis, realTimeLimit, std::chrono::milliseconds);
  process_group->setResourceLimits(rlimit);

  setup(process, resource_limits);
}

void setup(const yandex::contest::invoker::ProcessPointer &process,
           const bacs::process::ResourceLimits &resource_limits) {
  Process::ResourceLimits rlimit = process->resourceLimits();
  RLIM_UPDATE(time_limit_millis, timeLimit, std::chrono::milliseconds);
  RLIM_UPDATE(memory_limit_bytes, memoryLimitBytes, );
  RLIM_UPDATE(output_limit_bytes, outputLimitBytes, );
  RLIM_UPDATE(number_of_processes, numberOfProcesses, );
  process->setResourceLimits(rlimit);
}

#undef RLIM_UPDATE

bool parse_result(const ProcessGroup::Result &process_group_result,
                  const Process::Result &process_result,
                  bacs::process::ExecutionResult &result) {
  switch (process_group_result.completionStatus) {
    case ProcessGroup::Result::CompletionStatus::OK:
    case ProcessGroup::Result::CompletionStatus::ABNORMAL_EXIT:
      // it may happen if Process::terminateGroupOnCrash is not set
      switch (process_result.completionStatus) {
        case Process::Result::CompletionStatus::OK:
          result.set_status(bacs::process::ExecutionResult::OK);
          break;
        case Process::Result::CompletionStatus::ABNORMAL_EXIT:
          result.set_status(bacs::process::ExecutionResult::ABNORMAL_EXIT);
          break;
        case Process::Result::CompletionStatus::MEMORY_LIMIT_EXCEEDED:
          result.set_status(
              bacs::process::ExecutionResult::MEMORY_LIMIT_EXCEEDED);
          break;
        case Process::Result::CompletionStatus::TIME_LIMIT_EXCEEDED:
          result.set_status(
              bacs::process::ExecutionResult::TIME_LIMIT_EXCEEDED);
          break;
        case Process::Result::CompletionStatus::OUTPUT_LIMIT_EXCEEDED:
          result.set_status(
              bacs::process::ExecutionResult::OUTPUT_LIMIT_EXCEEDED);
          break;
        case Process::Result::CompletionStatus::USER_TIME_LIMIT_EXCEEDED:
        case Process::Result::CompletionStatus::SYSTEM_TIME_LIMIT_EXCEEDED:
        case Process::Result::CompletionStatus::TERMINATED_BY_SYSTEM:
          result.set_status(
              bacs::process::ExecutionResult::TERMINATED_BY_SYSTEM);
          break;
        case Process::Result::CompletionStatus::START_FAILED:
        case Process::Result::CompletionStatus::STOPPED:
          result.set_status(bacs::process::ExecutionResult::FAILED);
          break;
      }
      break;
    case ProcessGroup::Result::CompletionStatus::REAL_TIME_LIMIT_EXCEEDED:
      result.set_status(
          bacs::process::ExecutionResult::REAL_TIME_LIMIT_EXCEEDED);
      break;
    case ProcessGroup::Result::CompletionStatus::STOPPED:
      result.set_status(bacs::process::ExecutionResult::FAILED);
      break;
  }
  if (process_result.exitStatus)
    result.set_exit_status(process_result.exitStatus.get());
  if (process_result.termSig) result.set_term_sig(process_result.termSig.get());
  {
    bacs::process::ResourceUsage &resource_usage =
        *result.mutable_resource_usage();
    resource_usage.set_time_usage_millis(
        std::chrono::duration_cast<std::chrono::milliseconds>(
            process_result.resourceUsage.timeUsage).count());
    resource_usage.set_memory_usage_bytes(
        process_result.resourceUsage.memoryUsageBytes);
  }
  // full: dump all results here
  {
    boost::property_tree::ptree ptree;
    ptree.put_child("processGroupResult",
                    bunsan::config::save<boost::property_tree::ptree>(
                        process_group_result));
    ptree.put_child(
        "processResult",
        bunsan::config::save<boost::property_tree::ptree>(process_result));
    std::ostringstream buf;
    boost::property_tree::write_json(buf, ptree);
    result.set_full(buf.str());
  }
  return result.status() == bacs::process::ExecutionResult::OK;
}

}  // namespace process
}  // namespace system
}  // namespace bacs
<commit_msg>Accept zero resource limits in process::setup().<commit_after>#include <bacs/system/process.hpp>

#include <yandex/contest/invoker/All.hpp>

#include <bunsan/config/cast.hpp>

#include <boost/property_tree/json_parser.hpp>

#include <sstream>

namespace bacs {
namespace system {
namespace process {

using namespace yandex::contest::invoker;

#define RLIM_UPDATE(SRC, DST, TR) \
  if (resource_limits.SRC()) rlimit.DST = TR(resource_limits.SRC())

void setup(const yandex::contest::invoker::ProcessGroupPointer &process_group,
           const yandex::contest::invoker::ProcessPointer &process,
           const bacs::process::ResourceLimits &resource_limits) {
  ProcessGroup::ResourceLimits rlimit = process_group->resourceLimits();
  RLIM_UPDATE(real_time_limit_millis, realTimeLimit, std::chrono::milliseconds);
  process_group->setResourceLimits(rlimit);

  setup(process, resource_limits);
}

void setup(const yandex::contest::invoker::ProcessPointer &process,
           const bacs::process::ResourceLimits &resource_limits) {
  Process::ResourceLimits rlimit = process->resourceLimits();
  RLIM_UPDATE(time_limit_millis, timeLimit, std::chrono::milliseconds);
  RLIM_UPDATE(memory_limit_bytes, memoryLimitBytes, );
  RLIM_UPDATE(output_limit_bytes, outputLimitBytes, );
  RLIM_UPDATE(number_of_processes, numberOfProcesses, );
  process->setResourceLimits(rlimit);
}

#undef RLIM_UPDATE

bool parse_result(const ProcessGroup::Result &process_group_result,
                  const Process::Result &process_result,
                  bacs::process::ExecutionResult &result) {
  switch (process_group_result.completionStatus) {
    case ProcessGroup::Result::CompletionStatus::OK:
    case ProcessGroup::Result::CompletionStatus::ABNORMAL_EXIT:
      // it may happen if Process::terminateGroupOnCrash is not set
      switch (process_result.completionStatus) {
        case Process::Result::CompletionStatus::OK:
          result.set_status(bacs::process::ExecutionResult::OK);
          break;
        case Process::Result::CompletionStatus::ABNORMAL_EXIT:
          result.set_status(bacs::process::ExecutionResult::ABNORMAL_EXIT);
          break;
        case Process::Result::CompletionStatus::MEMORY_LIMIT_EXCEEDED:
          result.set_status(
              bacs::process::ExecutionResult::MEMORY_LIMIT_EXCEEDED);
          break;
        case Process::Result::CompletionStatus::TIME_LIMIT_EXCEEDED:
          result.set_status(
              bacs::process::ExecutionResult::TIME_LIMIT_EXCEEDED);
          break;
        case Process::Result::CompletionStatus::OUTPUT_LIMIT_EXCEEDED:
          result.set_status(
              bacs::process::ExecutionResult::OUTPUT_LIMIT_EXCEEDED);
          break;
        case Process::Result::CompletionStatus::USER_TIME_LIMIT_EXCEEDED:
        case Process::Result::CompletionStatus::SYSTEM_TIME_LIMIT_EXCEEDED:
        case Process::Result::CompletionStatus::TERMINATED_BY_SYSTEM:
          result.set_status(
              bacs::process::ExecutionResult::TERMINATED_BY_SYSTEM);
          break;
        case Process::Result::CompletionStatus::START_FAILED:
        case Process::Result::CompletionStatus::STOPPED:
          result.set_status(bacs::process::ExecutionResult::FAILED);
          break;
      }
      break;
    case ProcessGroup::Result::CompletionStatus::REAL_TIME_LIMIT_EXCEEDED:
      result.set_status(
          bacs::process::ExecutionResult::REAL_TIME_LIMIT_EXCEEDED);
      break;
    case ProcessGroup::Result::CompletionStatus::STOPPED:
      result.set_status(bacs::process::ExecutionResult::FAILED);
      break;
  }
  if (process_result.exitStatus)
    result.set_exit_status(process_result.exitStatus.get());
  if (process_result.termSig) result.set_term_sig(process_result.termSig.get());
  {
    bacs::process::ResourceUsage &resource_usage =
        *result.mutable_resource_usage();
    resource_usage.set_time_usage_millis(
        std::chrono::duration_cast<std::chrono::milliseconds>(
            process_result.resourceUsage.timeUsage).count());
    resource_usage.set_memory_usage_bytes(
        process_result.resourceUsage.memoryUsageBytes);
  }
  // full: dump all results here
  {
    boost::property_tree::ptree ptree;
    ptree.put_child("processGroupResult",
                    bunsan::config::save<boost::property_tree::ptree>(
                        process_group_result));
    ptree.put_child(
        "processResult",
        bunsan::config::save<boost::property_tree::ptree>(process_result));
    std::ostringstream buf;
    boost::property_tree::write_json(buf, ptree);
    result.set_full(buf.str());
  }
  return result.status() == bacs::process::ExecutionResult::OK;
}

}  // namespace process
}  // namespace system
}  // namespace bacs
<|endoftext|>


<commit_before>#ifndef MJOLNIR_INTERACTION_EXTERNAL_POSITION_RESTRAINT_INTERACTION_HPP
#define MJOLNIR_INTERACTION_EXTERNAL_POSITION_RESTRAINT_INTERACTION_HPP
#include <mjolnir/core/ExternalForceInteractionBase.hpp>
#include <mjolnir/math/math.hpp>
#include <mjolnir/util/string.hpp>

namespace mjolnir
{

//! @brief Interaction between particles and points.
template<typename traitsT, typename potentialT>
class PositionRestraintInteraction final
    : public ExternalForceInteractionBase<traitsT>
{
  public:
    using traits_type     = traitsT;
    using potential_type  = potentialT;
    using base_type       = ExternalForceInteractionBase<traitsT>;
    using real_type       = typename base_type::real_type;
    using coordinate_type = typename base_type::coordinate_type;
    using system_type     = typename base_type::system_type;
    using boundary_type   = typename base_type::boundary_type;

    // list of {pair of a particle-id and a position at which
    //          the particle would be restrained}
    using shape_type = std::vector<std::pair<std::size_t, coordinate_type>>;

  public:

    PositionRestraintInteraction(
        shape_type shape, potential_type pot)
        : shape_(std::move(shape)), potential_(std::move(pot))
    {}
    ~PositionRestraintInteraction() override = default;

    void      calc_force (system_type&)       const noexcept override;
    real_type calc_energy(system_type const&) const noexcept override;

    /*! @brief initialize spatial partition (e.g. CellList)                   *
     *  @details before calling `calc_(force|energy)`, this should be called. */
    void initialize(const system_type& sys) override
    {
        // update system parameters such as temperature, ionic-strength, etc.,
        this->potential_.update(sys);
        return;
    }

    void update(const system_type& sys) override
    {
        // update system parameters such as temperature, ionic-strength, etc.
        this->potential_.update(sys);
        return;
    }

    // no margin to be updated exists.
    void update_margin(const real_type, const system_type&) override {return;}

    std::string name() const override
    {return "PositionRestraint:"_s + potential_.name();}

  private:

    shape_type     shape_;
    potential_type potential_;
};

template<typename traitsT, typename potT>
void PositionRestraintInteraction<traitsT, potT>::calc_force(
        system_type& sys) const noexcept
{
    for(const auto& pidpos : this->shape_)
    {
        const auto  pid = pidpos.first;  // particle index
        const auto& pos = pidpos.second; // restrained position

        const auto& r_i = sys.position(pid);
        const auto  dr  = sys.adjust_direction(pos - r_i);

        const auto dist = math::length(dr);
        const auto dV   = this->potential_.derivative(pid, dist);
        if(dV == 0.0){continue;}

        sys.force(pid) += dV * dr;
    }
    return ;
}

template<typename traitsT, typename potT>
typename PositionRestraintInteraction<traitsT, potT>::real_type
PositionRestraintInteraction<traitsT, potT>::calc_energy(
        const system_type& sys) const noexcept
{
    real_type E = 0.0;
    for(const auto& pidpos : this->shape_)
    {
        const auto  pid = pidpos.first;  // particle index
        const auto& pos = pidpos.second; // restrained position

        const auto& r_i = sys.position(pid);
        const auto  dr  = sys.adjust_direction(pos - r_i);

        const auto dist = math::length(dr);
        E += this->potential_.potential(pid, dist);
    }
    return E;
}

} // mjolnir
#endif//MJOLNIR_BOX_INTEARACTION_BASE
<commit_msg>fix: force strength in PositionRestraint<commit_after>#ifndef MJOLNIR_INTERACTION_EXTERNAL_POSITION_RESTRAINT_INTERACTION_HPP
#define MJOLNIR_INTERACTION_EXTERNAL_POSITION_RESTRAINT_INTERACTION_HPP
#include <mjolnir/core/ExternalForceInteractionBase.hpp>
#include <mjolnir/math/math.hpp>
#include <mjolnir/util/string.hpp>

namespace mjolnir
{

//! @brief Interaction between particles and points.
template<typename traitsT, typename potentialT>
class PositionRestraintInteraction final
    : public ExternalForceInteractionBase<traitsT>
{
  public:
    using traits_type     = traitsT;
    using potential_type  = potentialT;
    using base_type       = ExternalForceInteractionBase<traitsT>;
    using real_type       = typename base_type::real_type;
    using coordinate_type = typename base_type::coordinate_type;
    using system_type     = typename base_type::system_type;
    using boundary_type   = typename base_type::boundary_type;

    // list of {pair of a particle-id and a position at which
    //          the particle would be restrained}
    using shape_type = std::vector<std::pair<std::size_t, coordinate_type>>;

  public:

    PositionRestraintInteraction(
        shape_type shape, potential_type pot)
        : shape_(std::move(shape)), potential_(std::move(pot))
    {}
    ~PositionRestraintInteraction() override = default;

    void      calc_force (system_type&)       const noexcept override;
    real_type calc_energy(system_type const&) const noexcept override;

    /*! @brief initialize spatial partition (e.g. CellList)                   *
     *  @details before calling `calc_(force|energy)`, this should be called. */
    void initialize(const system_type& sys) override
    {
        // update system parameters such as temperature, ionic-strength, etc.,
        this->potential_.update(sys);
        return;
    }

    void update(const system_type& sys) override
    {
        // update system parameters such as temperature, ionic-strength, etc.
        this->potential_.update(sys);
        return;
    }

    // no margin to be updated exists.
    void update_margin(const real_type, const system_type&) override {return;}

    std::string name() const override
    {return "PositionRestraint:"_s + potential_.name();}

  private:

    shape_type     shape_;
    potential_type potential_;
};

template<typename traitsT, typename potT>
void PositionRestraintInteraction<traitsT, potT>::calc_force(
        system_type& sys) const noexcept
{
    for(const auto& pidpos : this->shape_)
    {
        const auto  pid = pidpos.first;  // particle index
        const auto& pos = pidpos.second; // restrained position

        const auto& r_i = sys.position(pid);
        const auto  dr  = sys.adjust_direction(pos - r_i);

        const auto rlen = math::rlength(dr); // 1 / |dr|
        const auto dist = math::length_sq(dr) * rlen;
        const auto dV   = this->potential_.derivative(pid, dist);
        if(dV == 0.0){continue;}

        sys.force(pid) += (dV * rlen) * dr;
    }
    return ;
}

template<typename traitsT, typename potT>
typename PositionRestraintInteraction<traitsT, potT>::real_type
PositionRestraintInteraction<traitsT, potT>::calc_energy(
        const system_type& sys) const noexcept
{
    real_type E = 0.0;
    for(const auto& pidpos : this->shape_)
    {
        const auto  pid = pidpos.first;  // particle index
        const auto& pos = pidpos.second; // restrained position

        const auto& r_i = sys.position(pid);
        const auto  dr  = sys.adjust_direction(pos - r_i);

        const auto dist = math::length(dr);
        E += this->potential_.potential(pid, dist);
    }
    return E;
}

} // mjolnir
#endif//MJOLNIR_BOX_INTEARACTION_BASE
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: dockingareadefaultacceptor.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: kz $ $Date: 2004-02-25 17:46:44 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_HELPER_DOCKINGAREADEFAULTACCEPTOR_HXX_
#include <helper/dockingareadefaultacceptor.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_AWT_XDEVICE_HPP_
#include <com/sun/star/awt/XDevice.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_
#include <com/sun/star/awt/PosSize.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_XLAYOUTCONSTRAINS_HPP_
#include <com/sun/star/awt/XLayoutConstrains.hpp>
#endif

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

using namespace ::com::sun::star::container     ;
using namespace ::com::sun::star::frame         ;
using namespace ::com::sun::star::lang          ;
using namespace ::com::sun::star::uno           ;
using namespace ::cppu                          ;
using namespace ::osl                           ;
using namespace ::rtl                           ;

//_________________________________________________________________________________________________________________
//  non exported const
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  non exported definitions
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  declarations
//_________________________________________________________________________________________________________________

//*****************************************************************************************************************
//  constructor
//*****************************************************************************************************************
DockingAreaDefaultAcceptor::DockingAreaDefaultAcceptor( const   Reference< XFrame >&        xOwner  )
        //  Init baseclasses first
        :   OWeakObject     (           )
        // Init member
        ,   m_xOwner        ( xOwner    )
{
}

//*****************************************************************************************************************
//  destructor
//*****************************************************************************************************************
DockingAreaDefaultAcceptor::~DockingAreaDefaultAcceptor()
{
}

//*****************************************************************************************************************
//  XInterface, XTypeProvider
//*****************************************************************************************************************
DEFINE_XINTERFACE_2(    DockingAreaDefaultAcceptor                                              ,
                        OWeakObject                                                             ,
                        DIRECT_INTERFACE(XTypeProvider                                      )   ,
                        DIRECT_INTERFACE(::drafts::com::sun::star::ui::XDockingAreaAcceptor )   )

DEFINE_XTYPEPROVIDER_2( DockingAreaDefaultAcceptor                          ,
                        XTypeProvider                                       ,
                        ::drafts::com::sun::star::ui::XDockingAreaAcceptor  )

//*****************************************************************************************************************
//  XDockingAreaAcceptor
//*****************************************************************************************************************
css::uno::Reference< css::awt::XWindow > SAL_CALL DockingAreaDefaultAcceptor::getContainerWindow() throw (css::uno::RuntimeException)
{
    // Ready for multithreading
    ResetableGuard aGuard( m_aLock );

    // Try to "lock" the frame for access to taskscontainer.
    Reference< XFrame > xFrame( m_xOwner.get(), UNO_QUERY );
    Reference< css::awt::XWindow > xContainerWindow( xFrame->getContainerWindow() );

    return xContainerWindow;
}

sal_Bool SAL_CALL DockingAreaDefaultAcceptor::requestDockingAreaSpace( const css::awt::Rectangle& RequestedSpace ) throw (css::uno::RuntimeException)
{
    // Ready for multithreading
    ResetableGuard aGuard( m_aLock );

    // Try to "lock" the frame for access to taskscontainer.
    Reference< XFrame > xFrame( m_xOwner.get(), UNO_QUERY );
    if ( xFrame.is() == sal_True )
    {
        Reference< css::awt::XWindow > xContainerWindow( xFrame->getContainerWindow() );
        Reference< css::awt::XWindow > xComponentWindow( xFrame->getComponentWindow() );

        if (( xContainerWindow.is() == sal_True ) &&
            ( xComponentWindow.is() == sal_True )       )
        {
            css::uno::Reference< css::awt::XDevice > xDevice( xContainerWindow, css::uno::UNO_QUERY );
            // Convert relativ size to output size.
            css::awt::Rectangle  aRectangle  = xContainerWindow->getPosSize();
            css::awt::DeviceInfo aInfo       = xDevice->getInfo();
            css::awt::Size       aSize       (  aRectangle.Width  - aInfo.LeftInset - aInfo.RightInset  ,
                                                aRectangle.Height - aInfo.TopInset  - aInfo.BottomInset );

            // client size of container window
//            css::uno::Reference< css::awt::XLayoutConstrains > xLayoutContrains( xComponentWindow, css::uno::UNO_QUERY );
            css::awt::Size aMinSize( 0, 0 ); // = xLayoutContrains->getMinimumSize();

            // Check if request border space would decrease component window size below minimum size
            if ((( aSize.Width - RequestedSpace.X - RequestedSpace.Width ) < aMinSize.Width ) ||
                (( aSize.Height - RequestedSpace.Y - RequestedSpace.Height ) < aMinSize.Height  )       )
                return sal_False;

            return sal_True;
        }
    }

    return sal_False;
}

void SAL_CALL DockingAreaDefaultAcceptor::setDockingAreaSpace( const css::awt::Rectangle& BorderSpace ) throw (css::uno::RuntimeException)
{
    // Ready for multithreading
    ResetableGuard aGuard( m_aLock );

    // Try to "lock" the frame for access to taskscontainer.
    Reference< XFrame > xFrame( m_xOwner.get(), UNO_QUERY );
    if ( xFrame.is() == sal_True )
    {
        Reference< css::awt::XWindow > xContainerWindow( xFrame->getContainerWindow() );
        Reference< css::awt::XWindow > xComponentWindow( xFrame->getComponentWindow() );

        if (( xContainerWindow.is() == sal_True ) &&
            ( xComponentWindow.is() == sal_True )       )
        {
            css::uno::Reference< css::awt::XDevice > xDevice( xContainerWindow, css::uno::UNO_QUERY );
            // Convert relativ size to output size.
            css::awt::Rectangle  aRectangle  = xContainerWindow->getPosSize();
            css::awt::DeviceInfo aInfo       = xDevice->getInfo();
            css::awt::Size       aSize       (  aRectangle.Width  - aInfo.LeftInset - aInfo.RightInset  ,
                                                aRectangle.Height - aInfo.TopInset  - aInfo.BottomInset );
            // client size of container window
//            css::uno::Reference< css::awt::XLayoutConstrains > xLayoutContrains( xComponentWindow, css::uno::UNO_QUERY );
            css::awt::Size aMinSize( 0, 0 );// = xLayoutContrains->getMinimumSize();

            // Check if request border space would decrease component window size below minimum size
            sal_Int32 nWidth     = aSize.Width - BorderSpace.X - BorderSpace.Width;
            sal_Int32 nHeight    = aSize.Height - BorderSpace.Y - BorderSpace.Height;

            if (( nWidth > aMinSize.Width ) && ( nHeight > aMinSize.Height ))
            {
                // Resize our component window.
                xComponentWindow->setPosSize( BorderSpace.X, BorderSpace.Y, nWidth, nHeight, css::awt::PosSize::POSSIZE );
            }
        }
    }
}

} // namespace framework
<commit_msg>INTEGRATION: CWS removedrafts (1.2.204); FILE MERGED 2005/02/17 12:47:39 cd 1.2.204.1: #i42557# move UNOIDL types from drafts to com<commit_after>/*************************************************************************
 *
 *  $RCSfile: dockingareadefaultacceptor.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2005-03-01 19:35:29 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_HELPER_DOCKINGAREADEFAULTACCEPTOR_HXX_
#include <helper/dockingareadefaultacceptor.hxx>
#endif

#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_AWT_XDEVICE_HPP_
#include <com/sun/star/awt/XDevice.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_
#include <com/sun/star/awt/PosSize.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_XLAYOUTCONSTRAINS_HPP_
#include <com/sun/star/awt/XLayoutConstrains.hpp>
#endif

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

using namespace ::com::sun::star::container     ;
using namespace ::com::sun::star::frame         ;
using namespace ::com::sun::star::lang          ;
using namespace ::com::sun::star::uno           ;
using namespace ::cppu                          ;
using namespace ::osl                           ;
using namespace ::rtl                           ;

//_________________________________________________________________________________________________________________
//  non exported const
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  non exported definitions
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  declarations
//_________________________________________________________________________________________________________________

//*****************************************************************************************************************
//  constructor
//*****************************************************************************************************************
DockingAreaDefaultAcceptor::DockingAreaDefaultAcceptor( const   Reference< XFrame >&        xOwner  )
        //  Init baseclasses first
        :   OWeakObject     (           )
        // Init member
        ,   m_xOwner        ( xOwner    )
{
}

//*****************************************************************************************************************
//  destructor
//*****************************************************************************************************************
DockingAreaDefaultAcceptor::~DockingAreaDefaultAcceptor()
{
}

//*****************************************************************************************************************
//  XInterface, XTypeProvider
//*****************************************************************************************************************
DEFINE_XINTERFACE_2(    DockingAreaDefaultAcceptor                                              ,
                        OWeakObject                                                             ,
                        DIRECT_INTERFACE(XTypeProvider                                      )   ,
                        DIRECT_INTERFACE(::com::sun::star::ui::XDockingAreaAcceptor )   )

DEFINE_XTYPEPROVIDER_2( DockingAreaDefaultAcceptor                          ,
                        XTypeProvider                                       ,
                        ::com::sun::star::ui::XDockingAreaAcceptor  )

//*****************************************************************************************************************
//  XDockingAreaAcceptor
//*****************************************************************************************************************
css::uno::Reference< css::awt::XWindow > SAL_CALL DockingAreaDefaultAcceptor::getContainerWindow() throw (css::uno::RuntimeException)
{
    // Ready for multithreading
    ResetableGuard aGuard( m_aLock );

    // Try to "lock" the frame for access to taskscontainer.
    Reference< XFrame > xFrame( m_xOwner.get(), UNO_QUERY );
    Reference< css::awt::XWindow > xContainerWindow( xFrame->getContainerWindow() );

    return xContainerWindow;
}

sal_Bool SAL_CALL DockingAreaDefaultAcceptor::requestDockingAreaSpace( const css::awt::Rectangle& RequestedSpace ) throw (css::uno::RuntimeException)
{
    // Ready for multithreading
    ResetableGuard aGuard( m_aLock );

    // Try to "lock" the frame for access to taskscontainer.
    Reference< XFrame > xFrame( m_xOwner.get(), UNO_QUERY );
    if ( xFrame.is() == sal_True )
    {
        Reference< css::awt::XWindow > xContainerWindow( xFrame->getContainerWindow() );
        Reference< css::awt::XWindow > xComponentWindow( xFrame->getComponentWindow() );

        if (( xContainerWindow.is() == sal_True ) &&
            ( xComponentWindow.is() == sal_True )       )
        {
            css::uno::Reference< css::awt::XDevice > xDevice( xContainerWindow, css::uno::UNO_QUERY );
            // Convert relativ size to output size.
            css::awt::Rectangle  aRectangle  = xContainerWindow->getPosSize();
            css::awt::DeviceInfo aInfo       = xDevice->getInfo();
            css::awt::Size       aSize       (  aRectangle.Width  - aInfo.LeftInset - aInfo.RightInset  ,
                                                aRectangle.Height - aInfo.TopInset  - aInfo.BottomInset );

            // client size of container window
//            css::uno::Reference< css::awt::XLayoutConstrains > xLayoutContrains( xComponentWindow, css::uno::UNO_QUERY );
            css::awt::Size aMinSize( 0, 0 ); // = xLayoutContrains->getMinimumSize();

            // Check if request border space would decrease component window size below minimum size
            if ((( aSize.Width - RequestedSpace.X - RequestedSpace.Width ) < aMinSize.Width ) ||
                (( aSize.Height - RequestedSpace.Y - RequestedSpace.Height ) < aMinSize.Height  )       )
                return sal_False;

            return sal_True;
        }
    }

    return sal_False;
}

void SAL_CALL DockingAreaDefaultAcceptor::setDockingAreaSpace( const css::awt::Rectangle& BorderSpace ) throw (css::uno::RuntimeException)
{
    // Ready for multithreading
    ResetableGuard aGuard( m_aLock );

    // Try to "lock" the frame for access to taskscontainer.
    Reference< XFrame > xFrame( m_xOwner.get(), UNO_QUERY );
    if ( xFrame.is() == sal_True )
    {
        Reference< css::awt::XWindow > xContainerWindow( xFrame->getContainerWindow() );
        Reference< css::awt::XWindow > xComponentWindow( xFrame->getComponentWindow() );

        if (( xContainerWindow.is() == sal_True ) &&
            ( xComponentWindow.is() == sal_True )       )
        {
            css::uno::Reference< css::awt::XDevice > xDevice( xContainerWindow, css::uno::UNO_QUERY );
            // Convert relativ size to output size.
            css::awt::Rectangle  aRectangle  = xContainerWindow->getPosSize();
            css::awt::DeviceInfo aInfo       = xDevice->getInfo();
            css::awt::Size       aSize       (  aRectangle.Width  - aInfo.LeftInset - aInfo.RightInset  ,
                                                aRectangle.Height - aInfo.TopInset  - aInfo.BottomInset );
            // client size of container window
//            css::uno::Reference< css::awt::XLayoutConstrains > xLayoutContrains( xComponentWindow, css::uno::UNO_QUERY );
            css::awt::Size aMinSize( 0, 0 );// = xLayoutContrains->getMinimumSize();

            // Check if request border space would decrease component window size below minimum size
            sal_Int32 nWidth     = aSize.Width - BorderSpace.X - BorderSpace.Width;
            sal_Int32 nHeight    = aSize.Height - BorderSpace.Y - BorderSpace.Height;

            if (( nWidth > aMinSize.Width ) && ( nHeight > aMinSize.Height ))
            {
                // Resize our component window.
                xComponentWindow->setPosSize( BorderSpace.X, BorderSpace.Y, nWidth, nHeight, css::awt::PosSize::POSSIZE );
            }
        }
    }
}

} // namespace framework
<|endoftext|>