<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <decaf/internal/util/concurrent/Atomics.h>

#ifndef HAVE_ATOMIC_BUILTINS
#if defined(SOLARIS2) && SOLARIS2 >= 10
#include <atomic.h>
#endif
#endif

using namespace decaf::internal;
using namespace decaf::internal::util;
using namespace decaf::internal::util::concurrent;

////////////////////////////////////////////////////////////////////////////////
#ifndef HAVE_ATOMIC_BUILTINS

#include <decaf/internal/util/concurrent/PlatformThread.h>

namespace {
    decaf_mutex_t atomicMutex;
}

#endif

////////////////////////////////////////////////////////////////////////////////
void Atomics::initialize() {
#ifndef HAVE_ATOMIC_BUILTINS
    PlatformThread::createMutex(&atomicMutex);
#endif
}

////////////////////////////////////////////////////////////////////////////////
void Atomics::shutdown() {
#ifndef HAVE_ATOMIC_BUILTINS
    PlatformThread::destroyMutex(atomicMutex);
#endif
}

////////////////////////////////////////////////////////////////////////////////
bool Atomics::compareAndSet32(volatile int* target, int expect, int update ) {

#ifdef HAVE_ATOMIC_BUILTINS
    return __sync_val_compare_and_swap(target, expect, update)  == (unsigned int)expect;
#elif defined(SOLARIS2) && SOLARIS2 >= 10
    return atomic_cas_32((volatile unsigned int*)target, expect, update);
#else
    bool result = false;
    PlatformThread::lockMutex(atomicMutex);

    if (*target == expect) {
        *target = update;
        result = true;
    }

    PlatformThread::unlockMutex(atomicMutex);

    return result;
#endif
}

////////////////////////////////////////////////////////////////////////////////
bool Atomics::compareAndSet(volatile void** target, void* expect, void* update) {
#ifdef HAVE_ATOMIC_BUILTINS
    return __sync_val_compare_and_swap(target, (void*)expect, (void*)update) == (void*)expect;
#elif defined(SOLARIS2) && SOLARIS2 >= 10
    return atomic_cas_ptr(target, expect, update);
#else
    bool result = false;
    PlatformThread::lockMutex(atomicMutex);

    if (*target == expect) {
        *target = update;
        result = true;
    }

    PlatformThread::unlockMutex(atomicMutex);

    return result;
#endif
}

////////////////////////////////////////////////////////////////////////////////
int Atomics::getAndSet(volatile int* target, int newValue) {
#ifdef HAVE_ATOMIC_BUILTINS
    __sync_synchronize();
    return __sync_lock_test_and_set(target, newValue);
#elif defined(SOLARIS2) && SOLARIS2 >= 10
    return atomic_swap_32(target, newValue);
#else
    int oldValue;
    PlatformThread::lockMutex(atomicMutex);

    oldValue = *target;
    *target = newValue;

    PlatformThread::unlockMutex(atomicMutex);

    return oldValue;
#endif
}

////////////////////////////////////////////////////////////////////////////////
void* Atomics::getAndSet(volatile void** target, void* newValue) {
#ifdef HAVE_ATOMIC_BUILTINS
    __sync_synchronize();
    return (void*) __sync_lock_test_and_set(target, newValue);
#elif defined(SOLARIS2) && SOLARIS2 >= 10
    return atomic_swap_ptr(target, newValue);
#elif defined(__APPLE__)
    return atomic_swap_32(target, newValue);
#else
    void* oldValue;
    PlatformThread::lockMutex(atomicMutex);

    oldValue = *(void **)target;
    *target = newValue;

    PlatformThread::unlockMutex(atomicMutex);

    return oldValue;
#endif
}

////////////////////////////////////////////////////////////////////////////////
int Atomics::getAndIncrement(volatile int* target) {
#ifdef HAVE_ATOMIC_BUILTINS
    return __sync_fetch_and_add(target, 1);
#elif defined(SOLARIS2) && SOLARIS2 >= 10
    return atomic_add_32_nv(mem, 1) - 1;
#else
    int oldValue;
    PlatformThread::lockMutex(atomicMutex);

    oldValue = *target;
    (*target)++;

    PlatformThread::unlockMutex(atomicMutex);

    return oldValue;
#endif
}

////////////////////////////////////////////////////////////////////////////////
int Atomics::getAndDecrement(volatile int* target) {
#ifdef HAVE_ATOMIC_BUILTINS
    return __sync_fetch_and_add(target, 0xFFFFFFFF);
#elif defined(SOLARIS2) && SOLARIS2 >= 10
    return atomic_add_32_nv(target, 0xFFFFFFFF) + 1;
#else
    int oldValue;
    PlatformThread::lockMutex(atomicMutex);

    oldValue = *target;
    (*target)--;

    PlatformThread::unlockMutex(atomicMutex);

    return oldValue;
#endif
}

////////////////////////////////////////////////////////////////////////////////
int Atomics::getAndAdd(volatile int* target, int delta) {
#ifdef HAVE_ATOMIC_BUILTINS
    return __sync_fetch_and_add(target, delta);
#elif defined(SOLARIS2) && SOLARIS2 >= 10
    return atomic_add_32_nv(target, delta) - delta;
#else
    int oldValue;
    PlatformThread::lockMutex(atomicMutex);

    oldValue = *target;
    *target += delta;

    PlatformThread::unlockMutex(atomicMutex);

    return oldValue;
#endif
}

////////////////////////////////////////////////////////////////////////////////
int Atomics::addAndGet(volatile int* target, int delta) {
#ifdef HAVE_ATOMIC_BUILTINS
    return __sync_fetch_and_add(target, delta) + delta;
#elif defined(SOLARIS2) && SOLARIS2 >= 10
    return atomic_add_32_nv(target, delta);
#else
    int newValue;
    PlatformThread::lockMutex(atomicMutex);

    *target += delta;
    newValue = *target;

    PlatformThread::unlockMutex(atomicMutex);

    return newValue;
#endif
}

////////////////////////////////////////////////////////////////////////////////
int Atomics::incrementAndGet(volatile int* target) {
#ifdef HAVE_ATOMIC_BUILTINS
    return __sync_fetch_and_add(target, 1) + 1;
#elif defined(SOLARIS2) && SOLARIS2 >= 10
    return atomic_add_32_nv(target, 1);
#else
    int newValue;
    PlatformThread::lockMutex(atomicMutex);

    (*target)++;
    newValue = *target;

    PlatformThread::unlockMutex(atomicMutex);

    return newValue;
#endif
}

////////////////////////////////////////////////////////////////////////////////
int Atomics::decrementAndGet(volatile int* target) {
#ifdef HAVE_ATOMIC_BUILTINS
    return __sync_fetch_and_add(target, 0xFFFFFFFF) - 1;
#elif defined(SOLARIS2) && SOLARIS2 >= 10
    return atomic_add_32_nv(target, 0xFFFFFFFF);
#else
    int newValue;
    PlatformThread::lockMutex(atomicMutex);

    (*target)--;
    newValue = *target;

    PlatformThread::unlockMutex(atomicMutex);

    return newValue;
#endif
}

<commit_msg>fix for: https://issues.apache.org/jira/browse/AMQCPP-475<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <decaf/internal/util/concurrent/Atomics.h>

#ifndef HAVE_ATOMIC_BUILTINS
#if defined(SOLARIS2) && SOLARIS2 >= 10
#include <atomic.h>
#endif
#endif

using namespace decaf::internal;
using namespace decaf::internal::util;
using namespace decaf::internal::util::concurrent;

////////////////////////////////////////////////////////////////////////////////
#ifndef HAVE_ATOMIC_BUILTINS

#include <decaf/internal/util/concurrent/PlatformThread.h>

namespace {
    decaf_mutex_t atomicMutex;
}

#endif

////////////////////////////////////////////////////////////////////////////////
void Atomics::initialize() {
#ifndef HAVE_ATOMIC_BUILTINS
    PlatformThread::createMutex(&atomicMutex);
#endif
}

////////////////////////////////////////////////////////////////////////////////
void Atomics::shutdown() {
#ifndef HAVE_ATOMIC_BUILTINS
    PlatformThread::destroyMutex(atomicMutex);
#endif
}

////////////////////////////////////////////////////////////////////////////////
bool Atomics::compareAndSet32(volatile int* target, int expect, int update ) {

#ifdef HAVE_ATOMIC_BUILTINS
    return __sync_val_compare_and_swap(target, expect, update)  == expect;
#elif defined(SOLARIS2) && SOLARIS2 >= 10
    return atomic_cas_32((volatile unsigned int*)target, expect, update) == expect;
#else
    bool result = false;
    PlatformThread::lockMutex(atomicMutex);

    if (*target == expect) {
        *target = update;
        result = true;
    }

    PlatformThread::unlockMutex(atomicMutex);

    return result;
#endif
}

////////////////////////////////////////////////////////////////////////////////
bool Atomics::compareAndSet(volatile void** target, void* expect, void* update) {
#ifdef HAVE_ATOMIC_BUILTINS
    return __sync_val_compare_and_swap(target, (void*)expect, (void*)update) == (void*)expect;
#elif defined(SOLARIS2) && SOLARIS2 >= 10
    return atomic_cas_ptr(target, expect, update) == expect;
#else
    bool result = false;
    PlatformThread::lockMutex(atomicMutex);

    if (*target == expect) {
        *target = update;
        result = true;
    }

    PlatformThread::unlockMutex(atomicMutex);

    return result;
#endif
}

////////////////////////////////////////////////////////////////////////////////
int Atomics::getAndSet(volatile int* target, int newValue) {
#ifdef HAVE_ATOMIC_BUILTINS
    __sync_synchronize();
    return __sync_lock_test_and_set(target, newValue);
#elif defined(SOLARIS2) && SOLARIS2 >= 10
    return atomic_swap_32((volatile unsigned int*)target, newValue);
#else
    int oldValue;
    PlatformThread::lockMutex(atomicMutex);

    oldValue = *target;
    *target = newValue;

    PlatformThread::unlockMutex(atomicMutex);

    return oldValue;
#endif
}

////////////////////////////////////////////////////////////////////////////////
void* Atomics::getAndSet(volatile void** target, void* newValue) {
#ifdef HAVE_ATOMIC_BUILTINS
    __sync_synchronize();
    return (void*) __sync_lock_test_and_set(target, newValue);
#elif defined(SOLARIS2) && SOLARIS2 >= 10
    return atomic_swap_ptr(target, newValue);
#elif defined(__APPLE__)
    return atomic_swap_32(target, newValue);
#else
    void* oldValue;
    PlatformThread::lockMutex(atomicMutex);

    oldValue = *(void **)target;
    *target = newValue;

    PlatformThread::unlockMutex(atomicMutex);

    return oldValue;
#endif
}

////////////////////////////////////////////////////////////////////////////////
int Atomics::getAndIncrement(volatile int* target) {
#ifdef HAVE_ATOMIC_BUILTINS
    return __sync_fetch_and_add(target, 1);
#elif defined(SOLARIS2) && SOLARIS2 >= 10
    return atomic_add_32_nv((volatile unsigned int*)target, 1) - 1;
#else
    int oldValue;
    PlatformThread::lockMutex(atomicMutex);

    oldValue = *target;
    (*target)++;

    PlatformThread::unlockMutex(atomicMutex);

    return oldValue;
#endif
}

////////////////////////////////////////////////////////////////////////////////
int Atomics::getAndDecrement(volatile int* target) {
#ifdef HAVE_ATOMIC_BUILTINS
    return __sync_fetch_and_add(target, 0xFFFFFFFF);
#elif defined(SOLARIS2) && SOLARIS2 >= 10
    return atomic_add_32_nv((volatile unsigned int*)target, 0xFFFFFFFF) + 1;
#else
    int oldValue;
    PlatformThread::lockMutex(atomicMutex);

    oldValue = *target;
    (*target)--;

    PlatformThread::unlockMutex(atomicMutex);

    return oldValue;
#endif
}

////////////////////////////////////////////////////////////////////////////////
int Atomics::getAndAdd(volatile int* target, int delta) {
#ifdef HAVE_ATOMIC_BUILTINS
    return __sync_fetch_and_add(target, delta);
#elif defined(SOLARIS2) && SOLARIS2 >= 10
    return atomic_add_32_nv((volatile unsigned int*)target, delta) - delta;
#else
    int oldValue;
    PlatformThread::lockMutex(atomicMutex);

    oldValue = *target;
    *target += delta;

    PlatformThread::unlockMutex(atomicMutex);

    return oldValue;
#endif
}

////////////////////////////////////////////////////////////////////////////////
int Atomics::addAndGet(volatile int* target, int delta) {
#ifdef HAVE_ATOMIC_BUILTINS
    return __sync_fetch_and_add(target, delta) + delta;
#elif defined(SOLARIS2) && SOLARIS2 >= 10
    return atomic_add_32_nv((volatile unsigned int*)target, delta);
#else
    int newValue;
    PlatformThread::lockMutex(atomicMutex);

    *target += delta;
    newValue = *target;

    PlatformThread::unlockMutex(atomicMutex);

    return newValue;
#endif
}

////////////////////////////////////////////////////////////////////////////////
int Atomics::incrementAndGet(volatile int* target) {
#ifdef HAVE_ATOMIC_BUILTINS
    return __sync_fetch_and_add(target, 1) + 1;
#elif defined(SOLARIS2) && SOLARIS2 >= 10
    return atomic_add_32_nv((volatile unsigned int*)target, 1);
#else
    int newValue;
    PlatformThread::lockMutex(atomicMutex);

    (*target)++;
    newValue = *target;

    PlatformThread::unlockMutex(atomicMutex);

    return newValue;
#endif
}

////////////////////////////////////////////////////////////////////////////////
int Atomics::decrementAndGet(volatile int* target) {
#ifdef HAVE_ATOMIC_BUILTINS
    return __sync_fetch_and_add(target, 0xFFFFFFFF) - 1;
#elif defined(SOLARIS2) && SOLARIS2 >= 10
    return atomic_add_32_nv((volatile unsigned int*)target, 0xFFFFFFFF);
#else
    int newValue;
    PlatformThread::lockMutex(atomicMutex);

    (*target)--;
    newValue = *target;

    PlatformThread::unlockMutex(atomicMutex);

    return newValue;
#endif
}

<|endoftext|>


<commit_before>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "ui_SimpleViewUI.h"
#include "SimpleViewUI.h"

#include <QFileDialog>
#include <vtkCamera.h>

#include "vtkKWImage.h"
#include "vtkKWImageIO.h"

// Constructor
SimpleView::SimpleView()
{
  this->ui = new Ui_SimpleView;
  this->ui->setupUi(this);

  renderer = vtkSmartPointer<vtkRenderer>::New();

  this->ui->qvtkWidget->GetRenderWindow()->AddRenderer(renderer);

  vtkRenderWindowInteractor * renderInteractor = this->ui->qvtkWidget->GetInteractor();

  planeWidget1 = vtkSmartPointer<vtkImagePlaneWidget>::New();
  planeWidget2 = vtkSmartPointer<vtkImagePlaneWidget>::New();

  planeWidget1->SetInteractor( renderInteractor );
  planeWidget2->SetInteractor( renderInteractor );

  double origin[3] = {0,1,0};

  planeWidget1->SetOrigin(origin);
  planeWidget1->UpdatePlacement();

  planeWidget2->SetOrigin(origin);
  planeWidget2->UpdatePlacement();

  picker1 = vtkSmartPointer< vtkCellPicker >::New();
  picker2 = vtkSmartPointer< vtkCellPicker >::New();

  picker1->SetTolerance(0.005);
  picker2->SetTolerance(0.005);

  property1 = vtkSmartPointer< vtkProperty >::New();
  property2 = vtkSmartPointer< vtkProperty >::New();

  renderer->SetBackground(0.329,0.349,0.427);
  renderer->SetBackground2(0.658,0.698,0.855);
  renderer->GradientBackgroundOn();

  vtkCamera * camera = renderer->GetActiveCamera();

  camera->SetPosition ( 0.5, 0.5, -1 );
  camera->SetViewUp( 0, -1, 0 );

  renderer->ResetCamera();

  // Set up action signals and slots
  connect(this->ui->actionExit, SIGNAL(triggered()), this, SLOT(slotExit()));
  connect(this->ui->pushButton1, SIGNAL(pressed()), this, SLOT(slotLoadImage1()));
  connect(this->ui->pushButton2, SIGNAL(pressed()), this, SLOT(slotLoadImage2()));
};

void SimpleView::slotExit()
{
  qApp->exit();
}

std::string SimpleView::GetFileName()
{
  QFileDialog fileDialog(this);

  fileDialog.setViewMode( QFileDialog::Detail );

  QStringList filters;
  filters << "Image files (*.*)";

  fileDialog.setFilters( filters );
  fileDialog.setLabelText( QFileDialog::LookIn,"Select Input");

  fileDialog.exec();

  QStringList listOfFiles = fileDialog.selectedFiles();

  std::string inputFilename = listOfFiles[0].toStdString();

  return inputFilename;
}

void SimpleView::slotLoadImage1()
{
  std::string inputFilename = this->GetFileName();

  vtkSmartPointer< vtkKWImageIO > kwreader = vtkSmartPointer< vtkKWImageIO >::New();

  kwreader->SetFileName( inputFilename );
  kwreader->ReadImage();

  vtkSmartPointer< vtkKWImage > kwimage = kwreader->HarvestReadImage();

  vtkImageData * vtkimage1 = kwimage->GetVTKImage();

  planeWidget1->SetInput( vtkimage1 );

  int x0, x1, y0, y1, z0, z1;

  vtkimage1->GetExtent( x0, x1, y0, y1, z0, z1 );

  int middleSliceNumber = ( z1 + z0 ) / 2;

  planeWidget1->SetPlaneOrientationToZAxes();
  planeWidget1->SetSlicePosition( middleSliceNumber );
  planeWidget1->SetPicker(picker1);
  planeWidget1->RestrictPlaneToVolumeOn();
  planeWidget1->SetKeyPressActivationValue('z');
  planeWidget1->SetTexturePlaneProperty(property1);
  planeWidget1->On();

  planeWidget2->SetPlaneOrientationToZAxes();
  planeWidget2->SetSlicePosition( middleSliceNumber );
  planeWidget2->SetPicker(picker2);
  planeWidget2->RestrictPlaneToVolumeOn();
  planeWidget2->SetKeyPressActivationValue('z');
  planeWidget2->SetTexturePlaneProperty(property2);
  planeWidget2->On();

  vtkCamera * camera = renderer->GetActiveCamera();

  camera->SetPosition ( 0.5, 0.5, -1 );
  camera->SetViewUp( 0, -1, 0 );

  renderer->ResetCamera();
}

void SimpleView::slotLoadImage2()
{
  std::string inputFilename = this->GetFileName();

  vtkSmartPointer< vtkKWImageIO > kwreader = vtkSmartPointer< vtkKWImageIO >::New();

  kwreader->SetFileName( inputFilename );
  kwreader->ReadImage();

  vtkSmartPointer< vtkKWImage > kwimage = kwreader->HarvestReadImage();

  vtkImageData * vtkimage1 = kwimage->GetVTKImage();

  planeWidget1->SetInput( vtkimage1 );

  int x0, x1, y0, y1, z0, z1;

  vtkimage1->GetExtent( x0, x1, y0, y1, z0, z1 );

  int middleSliceNumber = ( z1 + z0 ) / 2;

  planeWidget1->SetPlaneOrientationToZAxes();
  planeWidget1->SetSlicePosition( middleSliceNumber );
  planeWidget1->SetPicker(picker1);
  planeWidget1->RestrictPlaneToVolumeOn();
  planeWidget1->SetKeyPressActivationValue('z');
  planeWidget1->SetTexturePlaneProperty(property1);
  planeWidget1->On();

  planeWidget2->SetPlaneOrientationToZAxes();
  planeWidget2->SetSlicePosition( middleSliceNumber );
  planeWidget2->SetPicker(picker2);
  planeWidget2->RestrictPlaneToVolumeOn();
  planeWidget2->SetKeyPressActivationValue('z');
  planeWidget2->SetTexturePlaneProperty(property2);
  planeWidget2->On();

  vtkCamera * camera = renderer->GetActiveCamera();

  camera->SetPosition ( 0.5, 0.5, -1 );
  camera->SetViewUp( 0, -1, 0 );

  renderer->ResetCamera();
}
<commit_msg>ENH: Connected two image planes.<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "ui_SimpleViewUI.h"
#include "SimpleViewUI.h"

#include <QFileDialog>
#include <vtkCamera.h>

#include "vtkKWImage.h"
#include "vtkKWImageIO.h"

// Constructor
SimpleView::SimpleView()
{
  this->ui = new Ui_SimpleView;
  this->ui->setupUi(this);

  renderer = vtkSmartPointer<vtkRenderer>::New();

  this->ui->qvtkWidget->GetRenderWindow()->AddRenderer(renderer);

  vtkRenderWindowInteractor * renderInteractor = this->ui->qvtkWidget->GetInteractor();

  planeWidget1 = vtkSmartPointer<vtkImagePlaneWidget>::New();
  planeWidget2 = vtkSmartPointer<vtkImagePlaneWidget>::New();

  planeWidget1->SetInteractor( renderInteractor );
  planeWidget2->SetInteractor( renderInteractor );

  double origin[3] = {0,1,0};

  planeWidget1->SetOrigin(origin);
  planeWidget1->UpdatePlacement();

  planeWidget2->SetOrigin(origin);
  planeWidget2->UpdatePlacement();

  picker1 = vtkSmartPointer< vtkCellPicker >::New();
  picker2 = vtkSmartPointer< vtkCellPicker >::New();

  picker1->SetTolerance(0.005);
  picker2->SetTolerance(0.005);

  property1 = vtkSmartPointer< vtkProperty >::New();
  property2 = vtkSmartPointer< vtkProperty >::New();

  renderer->SetBackground(0.329,0.349,0.427);
  renderer->SetBackground2(0.658,0.698,0.855);
  renderer->GradientBackgroundOn();

  vtkCamera * camera = renderer->GetActiveCamera();

  camera->SetPosition ( 0.5, 0.5, -1 );
  camera->SetViewUp( 0, -1, 0 );

  renderer->ResetCamera();

  // Set up action signals and slots
  connect(this->ui->actionExit, SIGNAL(triggered()), this, SLOT(slotExit()));
  connect(this->ui->pushButton1, SIGNAL(pressed()), this, SLOT(slotLoadImage1()));
  connect(this->ui->pushButton2, SIGNAL(pressed()), this, SLOT(slotLoadImage2()));
};

void SimpleView::slotExit()
{
  qApp->exit();
}

std::string SimpleView::GetFileName()
{
  QFileDialog fileDialog(this);

  fileDialog.setViewMode( QFileDialog::Detail );

  QStringList filters;
  filters << "Image files (*.*)";

  fileDialog.setFilters( filters );
  fileDialog.setLabelText( QFileDialog::LookIn,"Select Input");

  fileDialog.exec();

  QStringList listOfFiles = fileDialog.selectedFiles();

  std::string inputFilename = listOfFiles[0].toStdString();

  return inputFilename;
}

void SimpleView::slotLoadImage1()
{
  std::string inputFilename = this->GetFileName();

  vtkSmartPointer< vtkKWImageIO > kwreader = vtkSmartPointer< vtkKWImageIO >::New();

  kwreader->SetFileName( inputFilename );
  kwreader->ReadImage();

  vtkSmartPointer< vtkKWImage > kwimage = kwreader->HarvestReadImage();

  vtkImageData * vtkimage1 = kwimage->GetVTKImage();

  planeWidget1->SetInput( vtkimage1 );

  int x0, x1, y0, y1, z0, z1;

  vtkimage1->GetExtent( x0, x1, y0, y1, z0, z1 );

  int middleSliceNumber = ( z1 + z0 ) / 2;

  planeWidget1->SetPlaneOrientationToZAxes();
  planeWidget1->SetSlicePosition( middleSliceNumber );
  planeWidget1->SetPicker(picker1);
  planeWidget1->RestrictPlaneToVolumeOn();
  planeWidget1->SetKeyPressActivationValue('z');
  planeWidget1->SetTexturePlaneProperty(property1);
  planeWidget1->On();

  vtkCamera * camera = renderer->GetActiveCamera();

  camera->SetPosition ( 0.5, 0.5, -1 );
  camera->SetViewUp( 0, -1, 0 );

  renderer->ResetCamera();
}

void SimpleView::slotLoadImage2()
{
  std::string inputFilename = this->GetFileName();

  vtkSmartPointer< vtkKWImageIO > kwreader = vtkSmartPointer< vtkKWImageIO >::New();

  kwreader->SetFileName( inputFilename );
  kwreader->ReadImage();

  vtkSmartPointer< vtkKWImage > kwimage = kwreader->HarvestReadImage();

  vtkImageData * vtkimage2 = kwimage->GetVTKImage();

  planeWidget2->SetInput( vtkimage2 );

  int x0, x1, y0, y1, z0, z1;

  vtkimage2->GetExtent( x0, x1, y0, y1, z0, z1 );

  int middleSliceNumber = ( z1 + z0 ) / 2;

  planeWidget2->SetPlaneOrientationToZAxes();
  planeWidget2->SetSlicePosition( middleSliceNumber );
  planeWidget2->SetPicker(picker2);
  planeWidget2->RestrictPlaneToVolumeOn();
  planeWidget2->SetKeyPressActivationValue('z');
  planeWidget2->SetTexturePlaneProperty(property2);
  planeWidget2->On();

  vtkCamera * camera = renderer->GetActiveCamera();

  camera->SetPosition ( 0.5, 0.5, -1 );
  camera->SetViewUp( 0, -1, 0 );

  renderer->ResetCamera();
}
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

///////////////////////////////////////////////////////////////////////////
//                                                                       //
//  T0 Tender supply    //
//  //
//                                                                       //
///////////////////////////////////////////////////////////////////////////

#include <AliESDEvent.h>
#include <AliESDtrack.h>

#include <AliTender.h>
#include <AliT0TenderSupply.h>
#include <AliCDBManager.h>
#include <AliCDBEntry.h>
#include <AliT0CalibSeasonTimeShift.h>

ClassImp(AliT0TenderSupply)

//________________________________________________________________________
AliT0TenderSupply::AliT0TenderSupply():
  AliTenderSupply(),
  fCorrectMeanTime(kFALSE),
  fCorrectStartTimeOnAmplSatur(kFALSE),
  fAmplitudeThreshold(100),
  fPass4LHC11aCorrection(kFALSE)
{
  //
  // default constructor
  //
  for(int i=0; i<4; i++) fTimeOffset[i]=0;
}

//________________________________________________________________________
AliT0TenderSupply::AliT0TenderSupply(const char *name, const AliTender *tender):
  AliTenderSupply(name,tender),
  fCorrectMeanTime(kFALSE),
  fCorrectStartTimeOnAmplSatur(kFALSE),
  fAmplitudeThreshold(100),
  fPass4LHC11aCorrection(kFALSE)
{
  //
  // constructor
  //
  for(int i=0; i<3; i++) fTimeOffset[i]=0;
}

//________________________________________________________________________
AliT0TenderSupply::~AliT0TenderSupply(){
  //
  // destructor
  //

}

//________________________________________________________________________
void AliT0TenderSupply::Init(){
  //
  // Init
  //
  Int_t run = fTender->GetRun();
  if (run == 0) return;                // to skip first init, when we don't have yet a run number

  fCorrectMeanTime = kFALSE; //reset
  for(int i=0; i<4; i++) fTimeOffset[i]=0;

  fCorrectStartTimeOnAmplSatur = kFALSE;
  fAmplitudeThreshold = 100; //in mips

  if(167693<= run && run<=170593){  // LHC11h
    fCorrectStartTimeOnAmplSatur = kTRUE;
    fAmplitudeThreshold = 50; //in mips
  }

}

//________________________________________________________________________
void AliT0TenderSupply::ProcessEvent(){
    //
    // loop over all online T0 candidates and flag
    // selected daughter tracks using the status bis of the TObject
    //

    AliESDEvent *event=fTender->GetEvent();
    if (!event) return;

    //Do something when the run number changed, like loading OCDB entries etc.
    if(fTender->RunChanged()){
        Init();
    }

    if(fPass4LHC11aCorrection) {
      const Double32_t* mean = event->GetT0TOF();
      event->SetT0TOF(0, (mean[1]+mean[2])/2.);

    }
    if(fCorrectStartTimeOnAmplSatur){
        //correct A side ORA on amplitude saturation
        const Double32_t* time = event->GetT0time();
        const Double32_t* amplitude = event->GetT0amplitude();

        Int_t idxOfFirstPmtA = -1;
        Double32_t timeOrA   = 99999;
        for(int ipmt=12; ipmt<24; ipmt++){ //loop over A side
            if( amplitude[ipmt] < fAmplitudeThreshold){
                if( time[ipmt] > -200 && time[ipmt]!=0 && time[ipmt] < timeOrA ){
                    timeOrA        = time[ipmt];
                    idxOfFirstPmtA = ipmt;
                }
            }
        }

        if(idxOfFirstPmtA>-1){ //a hit in aside with less than 40 mips
            const Double32_t* mean = event->GetT0TOF();
            Double32_t timeOrC = mean[2];
            Double32_t timeOrAplusOrC = (timeOrA+timeOrC)/2;

            event->SetT0TOF(0, timeOrAplusOrC);
            event->SetT0TOF(1, timeOrA);
        }
    }

    //...........................................
    Float_t *t0means=0x0;
     if(fCorrectMeanTime){
      AliCDBManager* ocdbMan = AliCDBManager::Instance();
      ocdbMan->SetRun(fTender->GetRun());
      AliCDBEntry *entry = ocdbMan->Get("T0/Calib/TimeAdjust/");
      if(entry) {
	AliT0CalibSeasonTimeShift *clb = (AliT0CalibSeasonTimeShift*) entry->GetObject();
	t0means= clb->GetT0Means();
     } else {
	for (Int_t i=0;i<4;i++) t0means[i]=0;
	AliWarning("T0Tender no T0 entry found T0shift set to 0");
      }
    } else {
      for (Int_t i=0;i<4;i++) t0means=0;
    }
       // correct mean time offsets
     const Double32_t* mean = event->GetT0TOF();
     for(int it0=0; it0<3; it0++){
       if(-2000 < mean[it0]){
	 event->SetT0TOF(it0, mean[it0] - t0means[it0]);
       }
     }
}

<commit_msg>o automatic detection of 11a pass4 (Alla)<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

///////////////////////////////////////////////////////////////////////////
//                                                                       //
//  T0 Tender supply    //
//  //
//                                                                       //
///////////////////////////////////////////////////////////////////////////

#include <AliESDEvent.h>
#include <AliESDtrack.h>

#include <AliTender.h>
#include <AliT0TenderSupply.h>
#include <AliCDBManager.h>
#include <AliCDBEntry.h>
#include <AliT0CalibSeasonTimeShift.h>
#include <AliESDInputHandler.h>

ClassImp(AliT0TenderSupply)

//________________________________________________________________________
AliT0TenderSupply::AliT0TenderSupply():
  AliTenderSupply(),
  fCorrectMeanTime(kFALSE),
  fCorrectStartTimeOnAmplSatur(kFALSE),
  fAmplitudeThreshold(100),
  fPass4LHC11aCorrection(kFALSE)
{
  //
  // default constructor
  //
  for(int i=0; i<4; i++) fTimeOffset[i]=0;
}

//________________________________________________________________________
AliT0TenderSupply::AliT0TenderSupply(const char *name, const AliTender *tender):
  AliTenderSupply(name,tender),
  fCorrectMeanTime(kFALSE),
  fCorrectStartTimeOnAmplSatur(kFALSE),
  fAmplitudeThreshold(100),
  fPass4LHC11aCorrection(kFALSE)
{
  //
  // constructor
  //
  for(int i=0; i<3; i++) fTimeOffset[i]=0;
}

//________________________________________________________________________
AliT0TenderSupply::~AliT0TenderSupply(){
  //
  // destructor
  //

}

//________________________________________________________________________
void AliT0TenderSupply::Init(){
  // Init
  //
  Int_t run = fTender->GetRun();
  if (run == 0) return;    // to skip first init, when we don't have yet a run number
  fPass4LHC11aCorrection=kFALSE;

  fCorrectMeanTime = kFALSE; //reset
  for(int i=0; i<4; i++) fTimeOffset[i]=0;

  fCorrectStartTimeOnAmplSatur = kFALSE;
  fAmplitudeThreshold = 100; //in mips

  if(167693<= run && run<=170593){  // LHC11h
    fCorrectStartTimeOnAmplSatur = kTRUE;
    fAmplitudeThreshold = 50; //in mips
  }

}

//________________________________________________________________________
void AliT0TenderSupply::ProcessEvent(){
    //
    // loop over all online T0 candidates and flag
    // selected daughter tracks using the status bis of the TObject
    //

    AliESDEvent *event=fTender->GetEvent();
    if (!event) return;

    //Do something when the run number changed, like loading OCDB entries etc.
    fPass4LHC11aCorrection=kFALSE;
    if(fTender->RunChanged()){
      Init();
      if (fTender->GetRun()>=139699&&  fTender->GetRun()<=146860){
        AliESDInputHandler *esdIH = dynamic_cast<AliESDInputHandler*>  (fTender->GetESDhandler());
        if (esdIH) {
          TTree *tree= (TTree*)esdIH->GetTree();
          TFile *file= (TFile*)tree->GetCurrentFile();
          if (file){
            TString fileName(file->GetName());
            if (fileName.Contains("pass4") ) fPass4LHC11aCorrection=kTRUE;
	  }
	}
      }
    }

    if(fPass4LHC11aCorrection) {
      const Double32_t* mean = event->GetT0TOF();
      event->SetT0TOF(0, (mean[1]+mean[2])/2.);

    }
    if(fCorrectStartTimeOnAmplSatur){
        //correct A side ORA on amplitude saturation
        const Double32_t* time = event->GetT0time();
        const Double32_t* amplitude = event->GetT0amplitude();

        Int_t idxOfFirstPmtA = -1;
        Double32_t timeOrA   = 99999;
        for(int ipmt=12; ipmt<24; ipmt++){ //loop over A side
            if( amplitude[ipmt] < fAmplitudeThreshold){
                if( time[ipmt] > -200 && time[ipmt]!=0 && time[ipmt] < timeOrA ){
                    timeOrA        = time[ipmt];
                    idxOfFirstPmtA = ipmt;
                }
            }
        }

        if(idxOfFirstPmtA>-1){ //a hit in aside with less than 40 mips
            const Double32_t* mean = event->GetT0TOF();
            Double32_t timeOrC = mean[2];
            Double32_t timeOrAplusOrC = (timeOrA+timeOrC)/2;

            event->SetT0TOF(0, timeOrAplusOrC);
            event->SetT0TOF(1, timeOrA);
        }
    }

    //...........................................
    Float_t *t0means=0x0;
     if(fCorrectMeanTime){
      AliCDBManager* ocdbMan = AliCDBManager::Instance();
      ocdbMan->SetRun(fTender->GetRun());
      AliCDBEntry *entry = ocdbMan->Get("T0/Calib/TimeAdjust/");
      if(entry) {
	AliT0CalibSeasonTimeShift *clb = (AliT0CalibSeasonTimeShift*) entry->GetObject();
	t0means= clb->GetT0Means();
     } else {
	for (Int_t i=0;i<4;i++) t0means[i]=0;
	AliWarning("T0Tender no T0 entry found T0shift set to 0");
      }
    } else {
      for (Int_t i=0;i<4;i++) t0means=0;
    }
       // correct mean time offsets
     const Double32_t* mean = event->GetT0TOF();
     for(int it0=0; it0<3; it0++){
       if(-2000 < mean[it0]){
	 event->SetT0TOF(it0, mean[it0] - t0means[it0]);
       }
     }
}

<|endoftext|>


<commit_before>
#include <Hord/Rule/Defs.hpp>
#include <Hord/Error.hpp>
#include <Hord/System/Driver.hpp>

#include <type_traits>
#include <algorithm>
#include <utility>
#include <chrono>

namespace Hord {
namespace System {

// class Driver implementation

#define HORD_SCOPE_CLASS_IDENT__ System::Driver

Driver::Driver(
	System::IDGenerator& id_generator
) noexcept
	: m_id_generator(id_generator)
{
	static_assert(
		std::is_same<
			int64_t,
			std::chrono::steady_clock::rep
		>::value,
		"steady_clock representation is not 64 bits!"
	);

	// Initialize generator
	m_id_generator.seed(
		std::chrono::steady_clock::now().time_since_epoch().count()
	);
	// TODO: Register standard rule types.
}

Driver::Driver(Driver&&) = default;
Driver::~Driver() noexcept = default;

#define HORD_SCOPE_FUNC_IDENT__ register_rule_type
void
Driver::register_rule_type(
	Rule::type_info const& type_info
) {
	if (
		static_cast<Rule::Type>(Rule::StandardTypes::ReservedLast)
		>= type_info.type
	) {
		HORD_THROW_ERROR_SCOPED_FQN(
			ErrorCode::driver_rule_type_reserved,
			"type is within range reserved for standard rules"
		);
	} else if (0u == type_info.permitted_types) {
		HORD_THROW_ERROR_SCOPED_FQN(
			ErrorCode::driver_rule_type_zero_permitted_types,
			"permitted_types property must be a nonzero combination"
			" of FieldTypes"
		);
	} else if (m_rule_types.cend() != m_rule_types.find(type_info.type)) {
		HORD_THROW_ERROR_SCOPED_FQN(
			ErrorCode::driver_rule_type_shared,
			"type has already been registered"
		);
	}
	m_rule_types.insert(std::move(std::make_pair(
		type_info.type,
		type_info
	)));
}
#undef HORD_SCOPE_FUNC_IDENT__

#define HORD_SCOPE_FUNC_IDENT__ placehold_hive
Hive::Unit const&
Driver::placehold_hive(
	IO::Datastore::type_info const& type_info,
	String root_path
) {
	if (root_path.empty()) {
		HORD_THROW_ERROR_SCOPED_FQN(
			ErrorCode::driver_hive_root_empty,
			"cannot placehold hive with empty root path"
		);
	} else if (
		// FIXME: This is rank.
		m_datastores.cend()
		!= std::find_if(m_datastores.cbegin(), m_datastores.cend(),
			[&root_path](datastore_map_type::value_type const& pair) -> bool {
				return 0 == root_path.compare(pair.second->get_root_path());
			}
		)
	) {
		HORD_THROW_ERROR_SCOPED_FQN(
			ErrorCode::driver_hive_root_shared,
			"cannot placehold hive with non-unique root path"
		);
	}

	// Phew. Now let's try to construct and insert this guy
	Object::ID const
		id = m_id_generator.generate_unique(m_datastores);
	IO::Datastore* const
		datastore_ptr = type_info.construct(std::move(root_path), id);
	if (nullptr == datastore_ptr) {
		HORD_THROW_ERROR_SCOPED_FQN(
			ErrorCode::driver_datastore_construct_failed,
			"failed to construct datastore for root path"
		);
	}
	auto result_pair = m_datastores.emplace(
		id,
		std::move(std::unique_ptr<IO::Datastore>{
			datastore_ptr
		})
	);
	m_hive_order.emplace_back(id);
	return result_pair.first->second->get_hive();
}
#undef HORD_SCOPE_FUNC_IDENT__

#undef HORD_SCOPE_CLASS_IDENT__

} // namespace System
} // namespace Hord
<commit_msg>System::Driver: report root path with non-unique error message.<commit_after>
#include <Hord/Rule/Defs.hpp>
#include <Hord/Error.hpp>
#include <Hord/System/Driver.hpp>

#include <ceformat/print.hpp>

#include <type_traits>
#include <algorithm>
#include <utility>
#include <chrono>

namespace Hord {
namespace System {

// class Driver implementation

#define HORD_SCOPE_CLASS_IDENT__ System::Driver

Driver::Driver(
	System::IDGenerator& id_generator
) noexcept
	: m_id_generator(id_generator)
{
	static_assert(
		std::is_same<
			int64_t,
			std::chrono::steady_clock::rep
		>::value,
		"steady_clock representation is not 64 bits!"
	);

	// Initialize generator
	m_id_generator.seed(
		std::chrono::steady_clock::now().time_since_epoch().count()
	);
	// TODO: Register standard rule types.
}

Driver::Driver(Driver&&) = default;
Driver::~Driver() noexcept = default;

#define HORD_SCOPE_FUNC_IDENT__ register_rule_type
void
Driver::register_rule_type(
	Rule::type_info const& type_info
) {
	if (
		static_cast<Rule::Type>(Rule::StandardTypes::ReservedLast)
		>= type_info.type
	) {
		HORD_THROW_ERROR_SCOPED_FQN(
			ErrorCode::driver_rule_type_reserved,
			"type is within range reserved for standard rules"
		);
	} else if (0u == type_info.permitted_types) {
		HORD_THROW_ERROR_SCOPED_FQN(
			ErrorCode::driver_rule_type_zero_permitted_types,
			"permitted_types property must be a nonzero combination"
			" of FieldTypes"
		);
	} else if (m_rule_types.cend() != m_rule_types.find(type_info.type)) {
		HORD_THROW_ERROR_SCOPED_FQN(
			ErrorCode::driver_rule_type_shared,
			"type has already been registered"
		);
	}
	m_rule_types.insert(std::move(std::make_pair(
		type_info.type,
		type_info
	)));
}
#undef HORD_SCOPE_FUNC_IDENT__

#define HORD_SCOPE_FUNC_IDENT__ placehold_hive

HORD_FMT_SCOPED_FQN(
	s_err_root_shared,
	"cannot placehold hive with non-unique root path `%s`"
);

Hive::Unit const&
Driver::placehold_hive(
	IO::Datastore::type_info const& type_info,
	String root_path
) {
	if (root_path.empty()) {
		HORD_THROW_ERROR_SCOPED_FQN(
			ErrorCode::driver_hive_root_empty,
			"cannot placehold hive with empty root path"
		);
	} else if (
		// FIXME: This is rank.
		m_datastores.cend()
		!= std::find_if(m_datastores.cbegin(), m_datastores.cend(),
			[&root_path](datastore_map_type::value_type const& pair) -> bool {
				return 0 == root_path.compare(pair.second->get_root_path());
			}
		)
	) {
		HORD_THROW_ERROR_F(
			ErrorCode::driver_hive_root_shared,
			s_err_root_shared,
			root_path
		);
	}

	// Phew. Now let's try to construct and insert this guy
	Object::ID const
		id = m_id_generator.generate_unique(m_datastores);
	IO::Datastore* const
		datastore_ptr = type_info.construct(std::move(root_path), id);
	if (nullptr == datastore_ptr) {
		HORD_THROW_ERROR_SCOPED_FQN(
			ErrorCode::driver_datastore_construct_failed,
			"failed to construct datastore for root path"
		);
	}
	auto result_pair = m_datastores.emplace(
		id,
		std::move(std::unique_ptr<IO::Datastore>{
			datastore_ptr
		})
	);
	m_hive_order.emplace_back(id);
	return result_pair.first->second->get_hive();
}
#undef HORD_SCOPE_FUNC_IDENT__

#undef HORD_SCOPE_CLASS_IDENT__

} // namespace System
} // namespace Hord
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "IECoreRI/SLOReader.h"

#include "IECore/Shader.h"
#include "IECore/MessageHandler.h"
#include "IECore/SimpleTypedData.h"
#include "IECore/FileNameParameter.h"
#include "IECore/ObjectParameter.h"
#include "IECore/NullObject.h"
#include "IECore/CompoundObject.h"

#include "slo.h"

using namespace IECore;
using namespace IECoreRI;
using namespace boost;
using namespace std;
using namespace Imath;

const Reader::ReaderDescription<SLOReader> SLOReader::m_readerDescription( "sdl" );

SLOReader::SLOReader()
	:	Reader( "SLOReader", "Reads compiled renderman shaders.", new ObjectParameter( "result", "The loaded shader", new NullObject, Shader::staticTypeId() ) )
{
}

SLOReader::SLOReader( const std::string &fileName )
	:	Reader( "SLOReader", "Reads compiled renderman shaders.", new ObjectParameter( "result", "The loaded shader", new NullObject, Shader::staticTypeId() ) )
{
	m_fileNameParameter->setTypedValue( fileName );
}

SLOReader::~SLOReader()
{
}

bool SLOReader::canRead( const std::string &fileName )
{
	if( Slo_SetShader( fileName.c_str() ) )
	{
		return false;
	}
	Slo_EndShader();
	return true;
}

ObjectPtr SLOReader::doOperation( ConstCompoundObjectPtr operands )
{
	if( Slo_SetShader( fileName().c_str() ) )
	{
		return 0;
	}

	string name = Slo_GetName();
	string type = Slo_TypetoStr( Slo_GetType() );
	ShaderPtr result = new Shader( name, type );

	CompoundDataPtr typeHints = new CompoundData;
	result->blindData()->writable().insert( pair<string, DataPtr>( "ri:parameterTypeHints", typeHints ) );

	int numArgs = Slo_GetNArgs();
	for( int i=1; i<=numArgs; i++ )
	{
		DataPtr data = 0;

		SLO_VISSYMDEF *arg = Slo_GetArgById( i );
		switch( arg->svd_type )
		{
			case SLO_TYPE_POINT :
			case SLO_TYPE_VECTOR :
			case SLO_TYPE_NORMAL :
				{
					if( arg->svd_arraylen==0 )
					{
						const SLO_POINT *p = arg->svd_default.pointval;
						data = new V3fData( V3f( p->xval, p->yval, p->zval ) );
					}
					else
					{
						V3fVectorDataPtr vData = new V3fVectorData();
						data = vData;
						for( int j=0; j<arg->svd_arraylen; j++ )
						{
							SLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );
							const SLO_POINT *p = a->svd_default.pointval;
							vData->writable().push_back( V3f( p->xval, p->yval, p->zval ) );
						}
					}
					typeHints->writable().insert( pair<string, DataPtr>( arg->svd_name, new StringData( Slo_TypetoStr( arg->svd_type ) ) ) );
					break;
				}

			case SLO_TYPE_COLOR :
				{
					if( arg->svd_arraylen==0 )
					{
						const SLO_POINT *p = arg->svd_default.pointval;
						data = new Color3fData( Color3f( p->xval, p->yval, p->zval ) );
					}
					else
					{
						Color3fVectorDataPtr vData = new Color3fVectorData();
						data = vData;
						for( int j=0; j<arg->svd_arraylen; j++ )
						{
							SLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );
							const SLO_POINT *p = a->svd_default.pointval;
							vData->writable().push_back( Color3f( p->xval, p->yval, p->zval ) );
						}
					}
				}
				break;

			case SLO_TYPE_SCALAR :
				{
					if( arg->svd_arraylen==0 )
					{
						data = new FloatData( *(arg->svd_default.scalarval) );
					}
					else
					{
						FloatVectorDataPtr vData = new FloatVectorData();
						data = vData;
						for( int j=0; j<arg->svd_arraylen; j++ )
						{
							SLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );
							vData->writable().push_back( *(a->svd_default.scalarval) );
						}
					}
				}
				break;

			case SLO_TYPE_STRING :
				{
					if( arg->svd_arraylen==0 )
					{
						data = new StringData( arg->svd_default.stringval );
					}
					else
					{
						StringVectorDataPtr vData = new StringVectorData();
						data = vData;
						for( int j=0; j<arg->svd_arraylen; j++ )
						{
							SLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );
							vData->writable().push_back( a->svd_default.stringval );
						}
					}
				}
				break;

			case SLO_TYPE_MATRIX :
				{
					if( arg->svd_arraylen==0 )
					{
						const float *m = arg->svd_default.matrixval;
						M44f mm(	m[0], m[1], m[2], m[3],
									m[4], m[5], m[6], m[7],
									m[8], m[9], m[10], m[11],
									m[12], m[13], m[14], m[15] 	);
						data = new M44fData( mm );
					}
					else
					{
						M44fVectorDataPtr vData = new M44fVectorData();
						data = vData;
						for( int j=0; j<arg->svd_arraylen; j++ )
						{
							SLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );
							const float *m = a->svd_default.matrixval;
							M44f mm(	m[0], m[1], m[2], m[3],
										m[4], m[5], m[6], m[7],
										m[8], m[9], m[10], m[11],
										m[12], m[13], m[14], m[15] 	);
							vData->writable().push_back( mm );
						}
					}
				}
				break;

			default :

				msg( Msg::Warning, "SLOReader::read", format( "Parameter \"%s\" has unsupported type." ) % arg->svd_name );
		}

		if( data )
		{
			result->parameters().insert( CompoundDataMap::value_type( arg->svd_name, data ) );
		}

	}

	return result;
}

<commit_msg>Can now handle null default values in string arrays.<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2007, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

#include "IECoreRI/SLOReader.h"

#include "IECore/Shader.h"
#include "IECore/MessageHandler.h"
#include "IECore/SimpleTypedData.h"
#include "IECore/FileNameParameter.h"
#include "IECore/ObjectParameter.h"
#include "IECore/NullObject.h"
#include "IECore/CompoundObject.h"

#include "slo.h"

using namespace IECore;
using namespace IECoreRI;
using namespace boost;
using namespace std;
using namespace Imath;

const Reader::ReaderDescription<SLOReader> SLOReader::m_readerDescription( "sdl" );

SLOReader::SLOReader()
	:	Reader( "SLOReader", "Reads compiled renderman shaders.", new ObjectParameter( "result", "The loaded shader", new NullObject, Shader::staticTypeId() ) )
{
}

SLOReader::SLOReader( const std::string &fileName )
	:	Reader( "SLOReader", "Reads compiled renderman shaders.", new ObjectParameter( "result", "The loaded shader", new NullObject, Shader::staticTypeId() ) )
{
	m_fileNameParameter->setTypedValue( fileName );
}

SLOReader::~SLOReader()
{
}

bool SLOReader::canRead( const std::string &fileName )
{
	if( Slo_SetShader( fileName.c_str() ) )
	{
		return false;
	}
	Slo_EndShader();
	return true;
}

ObjectPtr SLOReader::doOperation( ConstCompoundObjectPtr operands )
{
	if( Slo_SetShader( fileName().c_str() ) )
	{
		return 0;
	}

	string name = Slo_GetName();
	string type = Slo_TypetoStr( Slo_GetType() );
	ShaderPtr result = new Shader( name, type );

	CompoundDataPtr typeHints = new CompoundData;
	result->blindData()->writable().insert( pair<string, DataPtr>( "ri:parameterTypeHints", typeHints ) );

	int numArgs = Slo_GetNArgs();
	for( int i=1; i<=numArgs; i++ )
	{
		DataPtr data = 0;

		SLO_VISSYMDEF *arg = Slo_GetArgById( i );
		switch( arg->svd_type )
		{
			case SLO_TYPE_POINT :
			case SLO_TYPE_VECTOR :
			case SLO_TYPE_NORMAL :
				{
					if( arg->svd_arraylen==0 )
					{
						const SLO_POINT *p = arg->svd_default.pointval;
						data = new V3fData( V3f( p->xval, p->yval, p->zval ) );
					}
					else
					{
						V3fVectorDataPtr vData = new V3fVectorData();
						data = vData;
						for( int j=0; j<arg->svd_arraylen; j++ )
						{
							SLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );
							const SLO_POINT *p = a->svd_default.pointval;
							vData->writable().push_back( V3f( p->xval, p->yval, p->zval ) );
						}
					}
					typeHints->writable().insert( pair<string, DataPtr>( arg->svd_name, new StringData( Slo_TypetoStr( arg->svd_type ) ) ) );
					break;
				}

			case SLO_TYPE_COLOR :
				{
					if( arg->svd_arraylen==0 )
					{
						const SLO_POINT *p = arg->svd_default.pointval;
						data = new Color3fData( Color3f( p->xval, p->yval, p->zval ) );
					}
					else
					{
						Color3fVectorDataPtr vData = new Color3fVectorData();
						data = vData;
						for( int j=0; j<arg->svd_arraylen; j++ )
						{
							SLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );
							const SLO_POINT *p = a->svd_default.pointval;
							vData->writable().push_back( Color3f( p->xval, p->yval, p->zval ) );
						}
					}
				}
				break;

			case SLO_TYPE_SCALAR :
				{
					if( arg->svd_arraylen==0 )
					{
						data = new FloatData( *(arg->svd_default.scalarval) );
					}
					else
					{
						FloatVectorDataPtr vData = new FloatVectorData();
						data = vData;
						for( int j=0; j<arg->svd_arraylen; j++ )
						{
							SLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );
							vData->writable().push_back( *(a->svd_default.scalarval) );
						}
					}
				}
				break;

			case SLO_TYPE_STRING :
				{
					if( arg->svd_arraylen==0 )
					{
						data = new StringData( arg->svd_default.stringval );
					}
					else
					{
						StringVectorDataPtr vData = new StringVectorData();
						data = vData;
						for( int j=0; j<arg->svd_arraylen; j++ )
						{
							SLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );
							// sometimes the default value for an element of a string array can be a null pointer.
							// i'm not sure what the meaning of this is. the 3delight shaderinfo utility reports such values
							// as "(null)", so that's what we do too.
							const char *defaultValue = a->svd_default.stringval;
							vData->writable().push_back( defaultValue ? defaultValue : "(null)" );
						}
					}
				}
				break;

			case SLO_TYPE_MATRIX :
				{
					if( arg->svd_arraylen==0 )
					{
						const float *m = arg->svd_default.matrixval;
						M44f mm(	m[0], m[1], m[2], m[3],
									m[4], m[5], m[6], m[7],
									m[8], m[9], m[10], m[11],
									m[12], m[13], m[14], m[15] 	);
						data = new M44fData( mm );
					}
					else
					{
						M44fVectorDataPtr vData = new M44fVectorData();
						data = vData;
						for( int j=0; j<arg->svd_arraylen; j++ )
						{
							SLO_VISSYMDEF *a = Slo_GetArrayArgElement( arg, j );
							const float *m = a->svd_default.matrixval;
							M44f mm(	m[0], m[1], m[2], m[3],
										m[4], m[5], m[6], m[7],
										m[8], m[9], m[10], m[11],
										m[12], m[13], m[14], m[15] 	);
							vData->writable().push_back( mm );
						}
					}
				}
				break;

			default :

				msg( Msg::Warning, "SLOReader::read", format( "Parameter \"%s\" has unsupported type." ) % arg->svd_name );
		}

		if( data )
		{
			result->parameters().insert( CompoundDataMap::value_type( arg->svd_name, data ) );
		}

	}

	return result;
}

<|endoftext|>


<commit_before>// Created on: 2012-07-18
// Created by: Kirill GAVRILOV
// Copyright (c) 2012 OPEN CASCADE SAS
//
// The content of this file is subject to the Open CASCADE Technology Public
// License Version 6.5 (the "License"). You may not use the content of this file
// except in compliance with the License. Please obtain a copy of the License
// at http://www.opencascade.org and read it completely before using this file.
//
// The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
// main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
//
// The Original Code and all software distributed under the License is
// distributed on an "AS IS" basis, without warranty of any kind, and the
// Initial Developer hereby disclaims all such warranties, including without
// limitation, any warranties of merchantability, fitness for a particular
// purpose or non-infringement. Please see the License for the specific terms
// and conditions governing the rights and limitations under the License.

#include <Image_PixMap.hxx>

#ifdef _MSC_VER
  #include <malloc.h>
#elif (defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 1)
  #include <mm_malloc.h>
#else
  extern "C" int posix_memalign (void** thePtr, size_t theAlign, size_t theBytesCount);
#endif

template<typename TypePtr>
inline TypePtr MemAllocAligned (const Standard_Size& theBytesCount,
                                const Standard_Size& theAlign = 16)
{
#if defined(_MSC_VER)
  return (TypePtr )_aligned_malloc (theBytesCount, theAlign);
#elif (defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 1)
  return (TypePtr )     _mm_malloc (theBytesCount, theAlign);
#else
  void* aPtr;
  if (posix_memalign (&aPtr, theAlign, theBytesCount))
  {
    aPtr = NULL;
  }
  return (TypePtr )aPtr;
#endif
}

inline void MemFreeAligned (void* thePtrAligned)
{
#if defined(_MSC_VER)
  _aligned_free (thePtrAligned);
#elif (defined(__GNUC__) && __GNUC__ >= 4 && __GNUC_MINOR__ >= 1)
  _mm_free (thePtrAligned);
#else
  free (thePtrAligned);
#endif
}

IMPLEMENT_STANDARD_HANDLE (Image_PixMap, Standard_Transient)
IMPLEMENT_STANDARD_RTTIEXT(Image_PixMap, Standard_Transient)

// =======================================================================
// function : Image_PixMap
// purpose  :
// =======================================================================
Image_PixMap::Image_PixMap()
: myImgFormat (Image_PixMap::ImgGray),
  myIsOwnPointer (true)
{
  memset (&myData, 0, sizeof(myData));
  myData.mySizeBPP   = 1;
  myData.myTopToDown = 1;
  setFormat (Image_PixMap::ImgGray);
}

// =======================================================================
// function : ~Image_PixMap
// purpose  :
// =======================================================================
Image_PixMap::~Image_PixMap()
{
  Clear();
}

Standard_Size Image_PixMap::SizePixelBytes (const Image_PixMap::ImgFormat thePixelFormat)
{
  switch (thePixelFormat)
  {
    case ImgGrayF:
      return sizeof(float);
    case ImgRGBAF:
    case ImgBGRAF:
      return sizeof(float) * 4;
    case ImgRGBF:
    case ImgBGRF:
      return sizeof(float) * 3;
    case ImgRGBA:
    case ImgBGRA:
      return 4;
    case ImgRGB32:
    case ImgBGR32:
      return 4;
    case ImgRGB:
    case ImgBGR:
      return 3;
    case ImgGray:
    default:
      return 1;
  }
}

// =======================================================================
// function : setFormat
// purpose  :
// =======================================================================
void Image_PixMap::setFormat (Image_PixMap::ImgFormat thePixelFormat)
{
  myImgFormat      = thePixelFormat;
  myData.mySizeBPP = SizePixelBytes (myImgFormat);
}

// =======================================================================
// function : setTopDown
// purpose  :
// =======================================================================
void Image_PixMap::setTopDown()
{
  myData.myTopRowPtr = ((myData.myTopToDown == 1 || myData.myDataPtr == NULL)
                     ? myData.myDataPtr : (myData.myDataPtr + myData.mySizeRowBytes * (myData.mySizeY - 1)));
}

// =======================================================================
// function : InitWrapper
// purpose  :
// =======================================================================
bool Image_PixMap::InitWrapper (Image_PixMap::ImgFormat thePixelFormat,
                                Standard_Byte*          theDataPtr,
                                const Standard_Size     theSizeX,
                                const Standard_Size     theSizeY,
                                const Standard_Size     theSizeRowBytes)
{
  Clear (thePixelFormat);
  if ((theSizeX == 0) || (theSizeY == 0) || (theDataPtr == NULL))
  {
    return false;
  }
  myData.mySizeX        = theSizeX;
  myData.mySizeY        = theSizeY;
  myData.mySizeRowBytes = (theSizeRowBytes != 0) ? theSizeRowBytes : (theSizeX * myData.mySizeBPP);
  myData.myDataPtr      = theDataPtr;
  myIsOwnPointer = false;
  setTopDown();
  return true;
}

// =======================================================================
// function : InitTrash
// purpose  :
// =======================================================================
bool Image_PixMap::InitTrash (Image_PixMap::ImgFormat thePixelFormat,
                              const Standard_Size     theSizeX,
                              const Standard_Size     theSizeY,
                              const Standard_Size     theSizeRowBytes)
{
  Clear (thePixelFormat);
  if ((theSizeX == 0) || (theSizeY == 0))
  {
    return false;
  }
  myData.mySizeX        = theSizeX;
  myData.mySizeY        = theSizeY;
  myData.mySizeRowBytes = myData.mySizeX * myData.mySizeBPP;
  if (theSizeRowBytes > myData.mySizeRowBytes)
  {
    // use argument only if it greater
    myData.mySizeRowBytes = theSizeRowBytes;
  }
  myData.myDataPtr = MemAllocAligned<Standard_Byte*> (SizeBytes());
  myIsOwnPointer   = true;
  setTopDown();
  return myData.myDataPtr != NULL;
}

// =======================================================================
// function : InitZero
// purpose  :
// =======================================================================
bool Image_PixMap::InitZero (Image_PixMap::ImgFormat thePixelFormat,
                             const Standard_Size     theSizeX,
                             const Standard_Size     theSizeY,
                             const Standard_Size     theSizeRowBytes,
                             const Standard_Byte     theValue)
{
  if (!InitTrash (thePixelFormat, theSizeX, theSizeY, theSizeRowBytes))
  {
    return false;
  }
  memset (myData.myDataPtr, (int )theValue, SizeBytes());
  return true;
}

// =======================================================================
// function : InitCopy
// purpose  :
// =======================================================================
bool Image_PixMap::InitCopy (const Image_PixMap& theCopy)
{
  if (&theCopy == this)
  {
    // self-copying disallowed
    return false;
  }
  if (InitTrash (theCopy.myImgFormat, theCopy.myData.mySizeX, theCopy.myData.mySizeY, theCopy.myData.mySizeRowBytes))
  {
    memcpy (myData.myDataPtr, theCopy.myData.myDataPtr, theCopy.SizeBytes());
    return true;
  }
  return false;
}

// =======================================================================
// function : Clear
// purpose  :
// =======================================================================
void Image_PixMap::Clear (Image_PixMap::ImgFormat thePixelFormat)
{
  if (myIsOwnPointer && (myData.myDataPtr != NULL))
  {
    MemFreeAligned (myData.myDataPtr);
  }
  myData.myDataPtr = myData.myTopRowPtr = NULL;
  myIsOwnPointer = true;
  myData.mySizeX = myData.mySizeY = myData.mySizeRowBytes = 0;
  setFormat (thePixelFormat);
  myData.myTopToDown = 1;
}

// =======================================================================
// function : PixelColor
// purpose  :
// =======================================================================
Quantity_Color Image_PixMap::PixelColor (const Standard_Integer theX,
                                         const Standard_Integer theY,
                                         Quantity_Parameter&    theAlpha) const
{
  if (IsEmpty() ||
      theX < 0 || (Standard_Size )theX >= myData.mySizeX ||
      theY < 0 || (Standard_Size )theY >= myData.mySizeY)
  {
    theAlpha = 0.0; // transparent
    return Quantity_Color (0.0, 0.0, 0.0, Quantity_TOC_RGB);
  }

  switch (myImgFormat)
  {
    case ImgGrayF:
    {
      const Standard_ShortReal& aPixel = Value<Standard_ShortReal> (theY, theX);
      theAlpha = 1.0; // opaque
      return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel)),
                             Quantity_Parameter (Standard_Real (aPixel)),
                             Quantity_Parameter (Standard_Real (aPixel)),
                             Quantity_TOC_RGB);
      break;
    }
    case ImgRGBAF:
    {
      const Image_ColorRGBAF& aPixel = Value<Image_ColorRGBAF> (theY, theX);
      theAlpha = aPixel.a();
      return Quantity_Color (Quantity_Parameter (aPixel.r()),
                             Quantity_Parameter (aPixel.g()),
                             Quantity_Parameter (aPixel.b()),
                             Quantity_TOC_RGB);
    }
    case ImgBGRAF:
    {
      const Image_ColorBGRAF& aPixel = Value<Image_ColorBGRAF> (theY, theX);
      theAlpha = aPixel.a();
      return Quantity_Color (Quantity_Parameter (aPixel.r()),
                             Quantity_Parameter (aPixel.g()),
                             Quantity_Parameter (aPixel.b()),
                             Quantity_TOC_RGB);
    }
    case ImgRGBF:
    {
      const Image_ColorRGBF& aPixel = Value<Image_ColorRGBF> (theY, theX);
      theAlpha =  1.0; // opaque
      return Quantity_Color (Quantity_Parameter (aPixel.r()),
                             Quantity_Parameter (aPixel.g()),
                             Quantity_Parameter (aPixel.b()),
                             Quantity_TOC_RGB);
    }
    case ImgBGRF:
    {
      const Image_ColorBGRF& aPixel = Value<Image_ColorBGRF> (theY, theX);
      theAlpha =  1.0; // opaque
      return Quantity_Color (Quantity_Parameter (aPixel.r()),
                             Quantity_Parameter (aPixel.g()),
                             Quantity_Parameter (aPixel.b()),
                             Quantity_TOC_RGB);
    }
    case ImgRGBA:
    {
      const Image_ColorRGBA& aPixel = Value<Image_ColorRGBA> (theY, theX);
      theAlpha = Standard_Real (aPixel.a()) / 255.0;
      return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
                             Quantity_TOC_RGB);
    }
    case ImgBGRA:
    {
      const Image_ColorBGRA& aPixel = Value<Image_ColorBGRA> (theY, theX);
      theAlpha = Standard_Real (aPixel.a()) / 255.0;
      return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
                             Quantity_TOC_RGB);
    }
    case ImgRGB32:
    {
      const Image_ColorRGB32& aPixel = Value<Image_ColorRGB32> (theY, theX);
      theAlpha = 1.0; // opaque
      return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
                             Quantity_TOC_RGB);
    }
    case ImgBGR32:
    {
      const Image_ColorBGR32& aPixel = Value<Image_ColorBGR32> (theY, theX);
      theAlpha = 1.0; // opaque
      return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
                             Quantity_TOC_RGB);
    }
    case ImgRGB:
    {
      const Image_ColorRGB& aPixel = Value<Image_ColorRGB> (theY, theX);
      theAlpha = 1.0; // opaque
      return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
                             Quantity_TOC_RGB);
    }
    case ImgBGR:
    {
      const Image_ColorBGR& aPixel = Value<Image_ColorBGR> (theY, theX);
      theAlpha = 1.0; // opaque
      return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
                             Quantity_TOC_RGB);
    }
    case ImgGray:
    {
      const Standard_Byte& aPixel = Value<Standard_Byte> (theY, theX);
      theAlpha = 1.0; // opaque
      return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel) / 255.0),
                             Quantity_TOC_RGB);
    }
    default:
    {
      // not supported image type
      theAlpha = 0.0; // transparent
      return Quantity_Color (0.0, 0.0, 0.0, Quantity_TOC_RGB);
    }
  }
}
<commit_msg>Fix build failure on Mac OSX 10.5, posix_memalign was introduced in 10.6<commit_after>// Created on: 2012-07-18
// Created by: Kirill GAVRILOV
// Copyright (c) 2012 OPEN CASCADE SAS
//
// The content of this file is subject to the Open CASCADE Technology Public
// License Version 6.5 (the "License"). You may not use the content of this file
// except in compliance with the License. Please obtain a copy of the License
// at http://www.opencascade.org and read it completely before using this file.
//
// The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
// main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
//
// The Original Code and all software distributed under the License is
// distributed on an "AS IS" basis, without warranty of any kind, and the
// Initial Developer hereby disclaims all such warranties, including without
// limitation, any warranties of merchantability, fitness for a particular
// purpose or non-infringement. Please see the License for the specific terms
// and conditions governing the rights and limitations under the License.

#include <Image_PixMap.hxx>

#ifdef _MSC_VER
  #include <malloc.h>
#elif defined(HAVE_MM_MALLOC_H)
  #include <mm_malloc.h>
#else
  #include <stdlib.h>
#endif

template<typename TypePtr>
inline TypePtr MemAllocAligned (const Standard_Size& theBytesCount,
                                const Standard_Size& theAlign = 16)
{
#if defined(_MSC_VER)
  return (TypePtr )_aligned_malloc (theBytesCount, theAlign);
#elif defined(HAVE_MM_MALLOC_H)
  return (TypePtr )     _mm_malloc (theBytesCount, theAlign);
#elif defined(HAVE_POSIX_MEMALIGN)
  void* aPtr;
  if (posix_memalign (&aPtr, theAlign, theBytesCount))
  {
    aPtr = NULL;
  }
  return (TypePtr )aPtr;
#else
  return (TypePtr ) malloc (theBytesCount);
#endif
}

inline void MemFreeAligned (void* thePtrAligned)
{
#if defined(_MSC_VER)
  _aligned_free (thePtrAligned);
#elif defined(HAVE_MM_MALLOC_H)
  _mm_free (thePtrAligned);
#else
  free (thePtrAligned);
#endif
}

IMPLEMENT_STANDARD_HANDLE (Image_PixMap, Standard_Transient)
IMPLEMENT_STANDARD_RTTIEXT(Image_PixMap, Standard_Transient)

// =======================================================================
// function : Image_PixMap
// purpose  :
// =======================================================================
Image_PixMap::Image_PixMap()
: myImgFormat (Image_PixMap::ImgGray),
  myIsOwnPointer (true)
{
  memset (&myData, 0, sizeof(myData));
  myData.mySizeBPP   = 1;
  myData.myTopToDown = 1;
  setFormat (Image_PixMap::ImgGray);
}

// =======================================================================
// function : ~Image_PixMap
// purpose  :
// =======================================================================
Image_PixMap::~Image_PixMap()
{
  Clear();
}

Standard_Size Image_PixMap::SizePixelBytes (const Image_PixMap::ImgFormat thePixelFormat)
{
  switch (thePixelFormat)
  {
    case ImgGrayF:
      return sizeof(float);
    case ImgRGBAF:
    case ImgBGRAF:
      return sizeof(float) * 4;
    case ImgRGBF:
    case ImgBGRF:
      return sizeof(float) * 3;
    case ImgRGBA:
    case ImgBGRA:
      return 4;
    case ImgRGB32:
    case ImgBGR32:
      return 4;
    case ImgRGB:
    case ImgBGR:
      return 3;
    case ImgGray:
    default:
      return 1;
  }
}

// =======================================================================
// function : setFormat
// purpose  :
// =======================================================================
void Image_PixMap::setFormat (Image_PixMap::ImgFormat thePixelFormat)
{
  myImgFormat      = thePixelFormat;
  myData.mySizeBPP = SizePixelBytes (myImgFormat);
}

// =======================================================================
// function : setTopDown
// purpose  :
// =======================================================================
void Image_PixMap::setTopDown()
{
  myData.myTopRowPtr = ((myData.myTopToDown == 1 || myData.myDataPtr == NULL)
                     ? myData.myDataPtr : (myData.myDataPtr + myData.mySizeRowBytes * (myData.mySizeY - 1)));
}

// =======================================================================
// function : InitWrapper
// purpose  :
// =======================================================================
bool Image_PixMap::InitWrapper (Image_PixMap::ImgFormat thePixelFormat,
                                Standard_Byte*          theDataPtr,
                                const Standard_Size     theSizeX,
                                const Standard_Size     theSizeY,
                                const Standard_Size     theSizeRowBytes)
{
  Clear (thePixelFormat);
  if ((theSizeX == 0) || (theSizeY == 0) || (theDataPtr == NULL))
  {
    return false;
  }
  myData.mySizeX        = theSizeX;
  myData.mySizeY        = theSizeY;
  myData.mySizeRowBytes = (theSizeRowBytes != 0) ? theSizeRowBytes : (theSizeX * myData.mySizeBPP);
  myData.myDataPtr      = theDataPtr;
  myIsOwnPointer = false;
  setTopDown();
  return true;
}

// =======================================================================
// function : InitTrash
// purpose  :
// =======================================================================
bool Image_PixMap::InitTrash (Image_PixMap::ImgFormat thePixelFormat,
                              const Standard_Size     theSizeX,
                              const Standard_Size     theSizeY,
                              const Standard_Size     theSizeRowBytes)
{
  Clear (thePixelFormat);
  if ((theSizeX == 0) || (theSizeY == 0))
  {
    return false;
  }
  myData.mySizeX        = theSizeX;
  myData.mySizeY        = theSizeY;
  myData.mySizeRowBytes = myData.mySizeX * myData.mySizeBPP;
  if (theSizeRowBytes > myData.mySizeRowBytes)
  {
    // use argument only if it greater
    myData.mySizeRowBytes = theSizeRowBytes;
  }
  myData.myDataPtr = MemAllocAligned<Standard_Byte*> (SizeBytes());
  myIsOwnPointer   = true;
  setTopDown();
  return myData.myDataPtr != NULL;
}

// =======================================================================
// function : InitZero
// purpose  :
// =======================================================================
bool Image_PixMap::InitZero (Image_PixMap::ImgFormat thePixelFormat,
                             const Standard_Size     theSizeX,
                             const Standard_Size     theSizeY,
                             const Standard_Size     theSizeRowBytes,
                             const Standard_Byte     theValue)
{
  if (!InitTrash (thePixelFormat, theSizeX, theSizeY, theSizeRowBytes))
  {
    return false;
  }
  memset (myData.myDataPtr, (int )theValue, SizeBytes());
  return true;
}

// =======================================================================
// function : InitCopy
// purpose  :
// =======================================================================
bool Image_PixMap::InitCopy (const Image_PixMap& theCopy)
{
  if (&theCopy == this)
  {
    // self-copying disallowed
    return false;
  }
  if (InitTrash (theCopy.myImgFormat, theCopy.myData.mySizeX, theCopy.myData.mySizeY, theCopy.myData.mySizeRowBytes))
  {
    memcpy (myData.myDataPtr, theCopy.myData.myDataPtr, theCopy.SizeBytes());
    return true;
  }
  return false;
}

// =======================================================================
// function : Clear
// purpose  :
// =======================================================================
void Image_PixMap::Clear (Image_PixMap::ImgFormat thePixelFormat)
{
  if (myIsOwnPointer && (myData.myDataPtr != NULL))
  {
    MemFreeAligned (myData.myDataPtr);
  }
  myData.myDataPtr = myData.myTopRowPtr = NULL;
  myIsOwnPointer = true;
  myData.mySizeX = myData.mySizeY = myData.mySizeRowBytes = 0;
  setFormat (thePixelFormat);
  myData.myTopToDown = 1;
}

// =======================================================================
// function : PixelColor
// purpose  :
// =======================================================================
Quantity_Color Image_PixMap::PixelColor (const Standard_Integer theX,
                                         const Standard_Integer theY,
                                         Quantity_Parameter&    theAlpha) const
{
  if (IsEmpty() ||
      theX < 0 || (Standard_Size )theX >= myData.mySizeX ||
      theY < 0 || (Standard_Size )theY >= myData.mySizeY)
  {
    theAlpha = 0.0; // transparent
    return Quantity_Color (0.0, 0.0, 0.0, Quantity_TOC_RGB);
  }

  switch (myImgFormat)
  {
    case ImgGrayF:
    {
      const Standard_ShortReal& aPixel = Value<Standard_ShortReal> (theY, theX);
      theAlpha = 1.0; // opaque
      return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel)),
                             Quantity_Parameter (Standard_Real (aPixel)),
                             Quantity_Parameter (Standard_Real (aPixel)),
                             Quantity_TOC_RGB);
      break;
    }
    case ImgRGBAF:
    {
      const Image_ColorRGBAF& aPixel = Value<Image_ColorRGBAF> (theY, theX);
      theAlpha = aPixel.a();
      return Quantity_Color (Quantity_Parameter (aPixel.r()),
                             Quantity_Parameter (aPixel.g()),
                             Quantity_Parameter (aPixel.b()),
                             Quantity_TOC_RGB);
    }
    case ImgBGRAF:
    {
      const Image_ColorBGRAF& aPixel = Value<Image_ColorBGRAF> (theY, theX);
      theAlpha = aPixel.a();
      return Quantity_Color (Quantity_Parameter (aPixel.r()),
                             Quantity_Parameter (aPixel.g()),
                             Quantity_Parameter (aPixel.b()),
                             Quantity_TOC_RGB);
    }
    case ImgRGBF:
    {
      const Image_ColorRGBF& aPixel = Value<Image_ColorRGBF> (theY, theX);
      theAlpha =  1.0; // opaque
      return Quantity_Color (Quantity_Parameter (aPixel.r()),
                             Quantity_Parameter (aPixel.g()),
                             Quantity_Parameter (aPixel.b()),
                             Quantity_TOC_RGB);
    }
    case ImgBGRF:
    {
      const Image_ColorBGRF& aPixel = Value<Image_ColorBGRF> (theY, theX);
      theAlpha =  1.0; // opaque
      return Quantity_Color (Quantity_Parameter (aPixel.r()),
                             Quantity_Parameter (aPixel.g()),
                             Quantity_Parameter (aPixel.b()),
                             Quantity_TOC_RGB);
    }
    case ImgRGBA:
    {
      const Image_ColorRGBA& aPixel = Value<Image_ColorRGBA> (theY, theX);
      theAlpha = Standard_Real (aPixel.a()) / 255.0;
      return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
                             Quantity_TOC_RGB);
    }
    case ImgBGRA:
    {
      const Image_ColorBGRA& aPixel = Value<Image_ColorBGRA> (theY, theX);
      theAlpha = Standard_Real (aPixel.a()) / 255.0;
      return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
                             Quantity_TOC_RGB);
    }
    case ImgRGB32:
    {
      const Image_ColorRGB32& aPixel = Value<Image_ColorRGB32> (theY, theX);
      theAlpha = 1.0; // opaque
      return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
                             Quantity_TOC_RGB);
    }
    case ImgBGR32:
    {
      const Image_ColorBGR32& aPixel = Value<Image_ColorBGR32> (theY, theX);
      theAlpha = 1.0; // opaque
      return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
                             Quantity_TOC_RGB);
    }
    case ImgRGB:
    {
      const Image_ColorRGB& aPixel = Value<Image_ColorRGB> (theY, theX);
      theAlpha = 1.0; // opaque
      return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
                             Quantity_TOC_RGB);
    }
    case ImgBGR:
    {
      const Image_ColorBGR& aPixel = Value<Image_ColorBGR> (theY, theX);
      theAlpha = 1.0; // opaque
      return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel.r()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.g()) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel.b()) / 255.0),
                             Quantity_TOC_RGB);
    }
    case ImgGray:
    {
      const Standard_Byte& aPixel = Value<Standard_Byte> (theY, theX);
      theAlpha = 1.0; // opaque
      return Quantity_Color (Quantity_Parameter (Standard_Real (aPixel) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel) / 255.0),
                             Quantity_Parameter (Standard_Real (aPixel) / 255.0),
                             Quantity_TOC_RGB);
    }
    default:
    {
      // not supported image type
      theAlpha = 0.0; // transparent
      return Quantity_Color (0.0, 0.0, 0.0, Quantity_TOC_RGB);
    }
  }
}
<|endoftext|>


<commit_before><commit_msg>PartDesign: Mild code cleanup of Helix<commit_after><|endoftext|>


<commit_before>
//   Copyright 2016 otris software AG
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//
//   This project is hosted at https://github.com/otris

#pragma once

#include <string>

#ifdef EWS_HAS_NOEXCEPT_SPECIFIER
#define EWS_NOEXCEPT noexcept
#else
#define EWS_NOEXCEPT
#endif

// Forward declarations
namespace ews
{
class and_;
class attachment;
class attachment_id;
class attendee;
class basic_credentials;
class body;
class calendar_item;
class connecting_sid;
class contact;
class contains;
class date_time;
class delegate_user;
class directory_id;
class distinguished_folder_id;
class duration;
class exception;
class exchange_error;
class folder_id;
class http_error;
class indexed_property_path;
class internet_message_header;
class is_equal_to;
class is_greater_than;
class is_greater_than_or_equal_to;
class is_less_than;
class is_less_than_or_equal_to;
class is_not_equal_to;
class item;
class item_id;
class mailbox;
class message;
class mime_content;
class not_;
class ntlm_credentials;
class or_;
class paging_view;
class parse_error;
class property;
class property_path;
class schema_validation_error;
class search_expression;
class soap_fault;
class task;
class update;
class user_id;
struct autodiscover_result;
struct autodiscover_hints;
struct resolution;
struct resolution_set;
template <typename T> class basic_service;
bool operator==(const date_time&, const date_time&);
bool operator==(const property_path&, const property_path&);
void set_up() EWS_NOEXCEPT;
void tear_down() EWS_NOEXCEPT;
std::string version();
template <typename T>
autodiscover_result get_exchange_web_services_url(const std::string&,
                                                  const basic_credentials&);
template <typename T>
autodiscover_result get_exchange_web_services_url(const std::string&,
                                                  const basic_credentials&,
                                                  const autodiscover_hints&);
}

// vim:et ts=4 sw=4
<commit_msg>Fix wrong forward declaration<commit_after>
//   Copyright 2016 otris software AG
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//
//   This project is hosted at https://github.com/otris

#pragma once

#include <string>

#ifdef EWS_HAS_NOEXCEPT_SPECIFIER
#define EWS_NOEXCEPT noexcept
#else
#define EWS_NOEXCEPT
#endif

// Forward declarations
namespace ews
{
class and_;
class attachment;
class attachment_id;
class attendee;
class basic_credentials;
class body;
class calendar_item;
class connecting_sid;
class contact;
class contains;
class date_time;
class delegate_user;
class directory_id;
class distinguished_folder_id;
class duration;
class exception;
class exchange_error;
class folder_id;
class http_error;
class indexed_property_path;
class internet_message_header;
class is_equal_to;
class is_greater_than;
class is_greater_than_or_equal_to;
class is_less_than;
class is_less_than_or_equal_to;
class is_not_equal_to;
class item;
class item_id;
class mailbox;
class message;
class mime_content;
class not_;
class ntlm_credentials;
class or_;
class paging_view;
class property;
class property_path;
class schema_validation_error;
class search_expression;
class soap_fault;
class task;
class update;
class user_id;
class xml_parse_error;
struct autodiscover_hints;
struct autodiscover_result;
struct resolution;
struct resolution_set;
template <typename T> class basic_service;
bool operator==(const date_time&, const date_time&);
bool operator==(const property_path&, const property_path&);
void set_up() EWS_NOEXCEPT;
void tear_down() EWS_NOEXCEPT;
std::string version();
template <typename T>
autodiscover_result get_exchange_web_services_url(const std::string&,
                                                  const basic_credentials&);
template <typename T>
autodiscover_result get_exchange_web_services_url(const std::string&,
                                                  const basic_credentials&,
                                                  const autodiscover_hints&);
}

// vim:et ts=4 sw=4
<|endoftext|>


<commit_before>
#include "python_plugin.hh"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define CHK(bad, fmt, ...)					       \
    do {							       \
	if (bad) {						       \
	    fprintf(stderr,fmt, ## __VA_ARGS__);		       \
	    exit(1);						       \
	}							       \
    } while(0)

void gdb_in_window(int sig) {}

void analyze(const char *what,bp::object retval)
{
    PyObject *res_str = PyObject_Str(retval.ptr());
    Py_XDECREF(res_str);
    printf("analyze: %s returned '%s' - '%s'\n",what,
	   PyString_AsString(res_str),
	   retval.ptr()->ob_type->tp_name);
}

void exercise(PythonPlugin *pp,const char *mod, const char*func,  bp::tuple tupleargs,   bp::dict kwargs)
{

    bp::object r;

    bool callable = pp->is_callable(mod,func);
    printf("callable(%s.%s) = %s\n",mod,func,callable ? "TRUE": "FALSE");

    int status = pp->call(mod,func, tupleargs,kwargs,r);
    switch (status) {
    case PLUGIN_EXCEPTION:
	printf("call(%s.%s): exception='%s' status = %d\n",
	       mod,func,pp->last_exception().c_str(), status);
	break;
    case PLUGIN_OK:
	printf("call(%s.%s): OK\n", mod,func);
	analyze( func,r);
	break;
    default:
	printf("call(%s.%s): status = %d\n", mod,func,status);
    }
}

void run(PythonPlugin *pp,const char *cmd, bool as_file)
{
    bp::object r;
    int status = pp->run_string(cmd,r, as_file);
    printf("run_string(%s): status = %d\n", cmd,status);
    analyze(cmd,r);
}

void foo_init()
{
    printf("foo init\n");
}
void bar_init()
{
    printf("bar init\n");
}

const char *inifile = "test.ini";
const char *section = "PYTHON";
struct _inittab builtin_modules[] = {
    { (char *) "foo", foo_init },
    { (char *) "bar", bar_init },
    // any others...
    { NULL, NULL }
};

int builtins;
bool as_file = false;
int
main (int argc, char **argv)
{

    int index;
    int c;
    bp::object retval;
    char *callablefunc = NULL;
    char *callablemod = NULL;
    char *xcallable = NULL;

    opterr = 0;

    while ((c = getopt (argc, argv, "fbi:C:c:x:")) != -1) {
	switch (c)  {
	case 'f':
	    as_file = true;
	    break;
	case 'b':
	    builtins++;
	    break;
	case 'i':
	    inifile = optarg;
	    break;
	case 'C':
	    callablemod = optarg;
	    break;
	case 'c':
	    callablefunc = optarg;
	    break;
	case 'x':
	    xcallable = optarg;
	    break;
	case '?':
	    if (optopt == 'c')
		fprintf (stderr, "Option -%c requires an argument.\n", optopt);
	    else if (isprint (optopt))
		fprintf (stderr, "Unknown option `-%c'.\n", optopt);
	    else
		fprintf (stderr,
			 "Unknown option character `\\x%x'.\n",
			 optopt);
	    return 1;
	default:
	    abort ();
	}
    }
    // creates the singleton instance
    PythonPlugin *pp = PythonPlugin::configure(inifile,
						 section,
						 builtins ? builtin_modules : NULL);
    // PythonPlugin two = pp; // this fails since copy constructor is private.
    // PythonPlugin &second = PythonPlugin::getInstance();  // returns the singleton instance

    printf("status = %d\n", pp->plugin_status());
    bp::tuple tupleargs,nulltupleargs;
    bp::dict kwargs,nullkwargs;
    kwargs['x'] = 10;
    kwargs['y'] = 20;
    tupleargs = bp::make_tuple(3,2,1,"foo");

    exercise(pp,NULL,"func",nulltupleargs, nullkwargs);

    system("/usr/bin/touch testmod.py");

    exercise(pp,NULL,"badfunc",tupleargs,kwargs);
    exercise(pp,NULL,"retstring",tupleargs,kwargs);
    exercise(pp,NULL,"retdouble",tupleargs,kwargs);
    // exercise(pp,"submod","subfunc");

    for (index = optind; index < argc; index++) {
	run(pp, argv[index], as_file);
    }
    return 0;
}
<commit_msg>testpp: use strdup for strstore<commit_after>
#include "python_plugin.hh"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define CHK(bad, fmt, ...)					       \
    do {							       \
	if (bad) {						       \
	    fprintf(stderr,fmt, ## __VA_ARGS__);		       \
	    exit(1);						       \
	}							       \
    } while(0)

const char *strstore(const char *s) { return strdup(s); }

void analyze(const char *what,bp::object retval)
{
    PyObject *res_str = PyObject_Str(retval.ptr());
    Py_XDECREF(res_str);
    printf("analyze: %s returned '%s' - '%s'\n",what,
	   PyString_AsString(res_str),
	   retval.ptr()->ob_type->tp_name);
}

void exercise(PythonPlugin *pp,const char *mod, const char*func,  bp::tuple tupleargs,   bp::dict kwargs)
{

    bp::object r;

    bool callable = pp->is_callable(mod,func);
    printf("callable(%s.%s) = %s\n",mod,func,callable ? "TRUE": "FALSE");

    int status = pp->call(mod,func, tupleargs,kwargs,r);
    switch (status) {
    case PLUGIN_EXCEPTION:
	printf("call(%s.%s): exception='%s' status = %d\n",
	       mod,func,pp->last_exception().c_str(), status);
	break;
    case PLUGIN_OK:
	printf("call(%s.%s): OK\n", mod,func);
	analyze( func,r);
	break;
    default:
	printf("call(%s.%s): status = %d\n", mod,func,status);
    }
}

void run(PythonPlugin *pp,const char *cmd, bool as_file)
{
    bp::object r;
    int status = pp->run_string(cmd,r, as_file);
    printf("run_string(%s): status = %d\n", cmd,status);
    analyze(cmd,r);
}

void foo_init()
{
    printf("foo init\n");
}
void bar_init()
{
    printf("bar init\n");
}

const char *inifile = "test.ini";
const char *section = "PYTHON";
struct _inittab builtin_modules[] = {
    { (char *) "foo", foo_init },
    { (char *) "bar", bar_init },
    // any others...
    { NULL, NULL }
};

int builtins;
bool as_file = false;
int
main (int argc, char **argv)
{

    int index;
    int c;
    bp::object retval;
    char *callablefunc = NULL;
    char *callablemod = NULL;
    char *xcallable = NULL;

    opterr = 0;

    while ((c = getopt (argc, argv, "fbi:C:c:x:")) != -1) {
	switch (c)  {
	case 'f':
	    as_file = true;
	    break;
	case 'b':
	    builtins++;
	    break;
	case 'i':
	    inifile = optarg;
	    break;
	case 'C':
	    callablemod = optarg;
	    break;
	case 'c':
	    callablefunc = optarg;
	    break;
	case 'x':
	    xcallable = optarg;
	    break;
	case '?':
	    if (optopt == 'c')
		fprintf (stderr, "Option -%c requires an argument.\n", optopt);
	    else if (isprint (optopt))
		fprintf (stderr, "Unknown option `-%c'.\n", optopt);
	    else
		fprintf (stderr,
			 "Unknown option character `\\x%x'.\n",
			 optopt);
	    return 1;
	default:
	    abort ();
	}
    }
    // creates the singleton instance
    PythonPlugin *pp = PythonPlugin::configure(inifile,
						 section,
						 builtins ? builtin_modules : NULL);
    // PythonPlugin two = pp; // this fails since copy constructor is private.
    // PythonPlugin &second = PythonPlugin::getInstance();  // returns the singleton instance

    printf("status = %d\n", pp->plugin_status());
    bp::tuple tupleargs,nulltupleargs;
    bp::dict kwargs,nullkwargs;
    kwargs['x'] = 10;
    kwargs['y'] = 20;
    tupleargs = bp::make_tuple(3,2,1,"foo");

    exercise(pp,NULL,"func",nulltupleargs, nullkwargs);

    system("/usr/bin/touch testmod.py");

    exercise(pp,NULL,"badfunc",tupleargs,kwargs);
    exercise(pp,NULL,"retstring",tupleargs,kwargs);
    exercise(pp,NULL,"retdouble",tupleargs,kwargs);
    // exercise(pp,"submod","subfunc");

    for (index = optind; index < argc; index++) {
	run(pp, argv[index], as_file);
    }
    return 0;
}
<|endoftext|>