<commit_before>// Copyright (c) 2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "scheduler.h"

#include <assert.h>
#include <boost/bind.hpp>
#include <utility>

CScheduler::CScheduler() : nThreadsServicingQueue(0), stopRequested(false), stopWhenEmpty(false)
{
}

CScheduler::~CScheduler()
{
    assert(nThreadsServicingQueue == 0);
}

#if BOOST_VERSION < 105000
static boost::system_time toPosixTime(const boost::chrono::system_clock::time_point& t)
{
    return boost::posix_time::from_time_t(boost::chrono::system_clock::to_time_t(t));
}
#endif

void CScheduler::serviceQueue()
{
    boost::unique_lock<boost::mutex> lock(newTaskMutex);
    ++nThreadsServicingQueue;

    // newTaskMutex is locked throughout this loop EXCEPT
    // when the thread is waiting or when the user's function
    // is called.
    while (!shouldStop()) {
        try {
            while (!shouldStop() && taskQueue.empty()) {
                // Wait until there is something to do.
                newTaskScheduled.wait(lock);
            }

            // Wait until either there is a new task, or until
            // the time of the first item on the queue:

// wait_until needs boost 1.50 or later; older versions have timed_wait:
#if BOOST_VERSION < 105000
            while (!shouldStop() && !taskQueue.empty() &&
                   newTaskScheduled.timed_wait(lock, toPosixTime(taskQueue.begin()->first))) {
                // Keep waiting until timeout
            }
#else
            // Some boost versions have a conflicting overload of wait_until that returns void.
            // Explicitly use a template here to avoid hitting that overload.
            while (!shouldStop() && !taskQueue.empty() &&
                   newTaskScheduled.wait_until<>(lock, taskQueue.begin()->first) != boost::cv_status::timeout) {
                // Keep waiting until timeout
            }
#endif
            // If there are multiple threads, the queue can empty while we're waiting (another
            // thread may service the task we were waiting on).
            if (shouldStop() || taskQueue.empty())
                continue;

            Function f = taskQueue.begin()->second;
            taskQueue.erase(taskQueue.begin());

            // Unlock before calling f, so it can reschedule itself or another task
            // without deadlocking:
            lock.unlock();
            f();
            lock.lock();
        } catch (...) {
            --nThreadsServicingQueue;
            throw;
        }
    }
    --nThreadsServicingQueue;
}

void CScheduler::stop(bool drain)
{
    {
        boost::unique_lock<boost::mutex> lock(newTaskMutex);
        if (drain)
            stopWhenEmpty = true;
        else
            stopRequested = true;
    }
    newTaskScheduled.notify_all();
}

void CScheduler::schedule(CScheduler::Function f, boost::chrono::system_clock::time_point t)
{
    {
        boost::unique_lock<boost::mutex> lock(newTaskMutex);
        taskQueue.insert(std::make_pair(t, f));
    }
    newTaskScheduled.notify_one();
}

void CScheduler::scheduleFromNow(CScheduler::Function f, int64_t deltaSeconds)
{
    schedule(f, boost::chrono::system_clock::now() + boost::chrono::seconds(deltaSeconds));
}

static void Repeat(CScheduler* s, CScheduler::Function f, int64_t deltaSeconds)
{
    f();
    s->scheduleFromNow(boost::bind(&Repeat, s, f, deltaSeconds), deltaSeconds);
}

void CScheduler::scheduleEvery(CScheduler::Function f, int64_t deltaSeconds)
{
    scheduleFromNow(boost::bind(&Repeat, this, f, deltaSeconds), deltaSeconds);
}

size_t CScheduler::getQueueInfo(boost::chrono::system_clock::time_point &first,
                             boost::chrono::system_clock::time_point &last) const
{
    boost::unique_lock<boost::mutex> lock(newTaskMutex);
    size_t result = taskQueue.size();
    if (!taskQueue.empty()) {
        first = taskQueue.begin()->first;
        last = taskQueue.rbegin()->first;
    }
    return result;
}
<commit_msg>Make sure we re-acquire lock if a task throws<commit_after>// Copyright (c) 2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "scheduler.h"

#include <assert.h>
#include <boost/bind.hpp>
#include <boost/thread/reverse_lock.hpp>
#include <utility>

CScheduler::CScheduler() : nThreadsServicingQueue(0), stopRequested(false), stopWhenEmpty(false)
{
}

CScheduler::~CScheduler()
{
    assert(nThreadsServicingQueue == 0);
}

#if BOOST_VERSION < 105000
static boost::system_time toPosixTime(const boost::chrono::system_clock::time_point& t)
{
    return boost::posix_time::from_time_t(boost::chrono::system_clock::to_time_t(t));
}
#endif

void CScheduler::serviceQueue()
{
    boost::unique_lock<boost::mutex> lock(newTaskMutex);
    ++nThreadsServicingQueue;

    // newTaskMutex is locked throughout this loop EXCEPT
    // when the thread is waiting or when the user's function
    // is called.
    while (!shouldStop()) {
        try {
            while (!shouldStop() && taskQueue.empty()) {
                // Wait until there is something to do.
                newTaskScheduled.wait(lock);
            }

            // Wait until either there is a new task, or until
            // the time of the first item on the queue:

// wait_until needs boost 1.50 or later; older versions have timed_wait:
#if BOOST_VERSION < 105000
            while (!shouldStop() && !taskQueue.empty() &&
                   newTaskScheduled.timed_wait(lock, toPosixTime(taskQueue.begin()->first))) {
                // Keep waiting until timeout
            }
#else
            // Some boost versions have a conflicting overload of wait_until that returns void.
            // Explicitly use a template here to avoid hitting that overload.
            while (!shouldStop() && !taskQueue.empty() &&
                   newTaskScheduled.wait_until<>(lock, taskQueue.begin()->first) != boost::cv_status::timeout) {
                // Keep waiting until timeout
            }
#endif
            // If there are multiple threads, the queue can empty while we're waiting (another
            // thread may service the task we were waiting on).
            if (shouldStop() || taskQueue.empty())
                continue;

            Function f = taskQueue.begin()->second;
            taskQueue.erase(taskQueue.begin());

            {
                // Unlock before calling f, so it can reschedule itself or another task
                // without deadlocking:
                boost::reverse_lock<boost::unique_lock<boost::mutex> > rlock(lock);
                f();
            }
        } catch (...) {
            --nThreadsServicingQueue;
            throw;
        }
    }
    --nThreadsServicingQueue;
}

void CScheduler::stop(bool drain)
{
    {
        boost::unique_lock<boost::mutex> lock(newTaskMutex);
        if (drain)
            stopWhenEmpty = true;
        else
            stopRequested = true;
    }
    newTaskScheduled.notify_all();
}

void CScheduler::schedule(CScheduler::Function f, boost::chrono::system_clock::time_point t)
{
    {
        boost::unique_lock<boost::mutex> lock(newTaskMutex);
        taskQueue.insert(std::make_pair(t, f));
    }
    newTaskScheduled.notify_one();
}

void CScheduler::scheduleFromNow(CScheduler::Function f, int64_t deltaSeconds)
{
    schedule(f, boost::chrono::system_clock::now() + boost::chrono::seconds(deltaSeconds));
}

static void Repeat(CScheduler* s, CScheduler::Function f, int64_t deltaSeconds)
{
    f();
    s->scheduleFromNow(boost::bind(&Repeat, s, f, deltaSeconds), deltaSeconds);
}

void CScheduler::scheduleEvery(CScheduler::Function f, int64_t deltaSeconds)
{
    scheduleFromNow(boost::bind(&Repeat, this, f, deltaSeconds), deltaSeconds);
}

size_t CScheduler::getQueueInfo(boost::chrono::system_clock::time_point &first,
                             boost::chrono::system_clock::time_point &last) const
{
    boost::unique_lock<boost::mutex> lock(newTaskMutex);
    size_t result = taskQueue.size();
    if (!taskQueue.empty()) {
        first = taskQueue.begin()->first;
        last = taskQueue.rbegin()->first;
    }
    return result;
}
<|endoftext|>


<commit_before>#include "selectors.hpp"

#include "json_spirit/json_spirit_reader_template.h"
#include "json_spirit/json_spirit_writer_template.h"

#include <boost/foreach.hpp>

using namespace json_spirit;

Interval get_chunk_coordinate(int chunk_coord){
	return Interval(chunk_coord * 16, (chunk_coord + 1) * 16 - 1);
}

in_circle_predicate::in_circle_predicate(point_surface & ps, int _size):
	size(_size),center(ps){

}

bool in_circle_predicate::operator()(const mc::utils::level_coord & coord) {
	Interval x_chunk(get_chunk_coordinate(coord.get_x()));
	Interval z_chunk(get_chunk_coordinate(coord.get_z()));

	point_surface  ps=center;
	int distance_sqr;

	int dist_x = x_chunk.distance(ps.x);
	int dist_y = z_chunk.distance(ps.z);

	// std::cout <<" in circle ?" <<std::endl;
	distance_sqr = dist_x * dist_x + dist_y * dist_y ;

	// std::cout <<" d sqr :"<< distance_sqr << ", size" << size * size<<std::endl;
	return distance_sqr <= size * size ;
	// distance of the chunk from the circle
}

template<typename Y>
Y sqr(Y val)
{ return val*val; }

bool in_circle_predicate::operator()(const point & pt){
	// std::cout << "in circle ?" << std::endl;
	int distance_sqr = sqr(pt.x - center.x) + sqr ( pt.z - center.z);
	// std::cout << pt.x << " " << pt.y << " "<< pt.z <<" " << distance_sqr << " " << sqr(size) << std::endl;
	// std::cout << pt.x << " " << pt.z <<" " << distance_sqr << " " << sqr(size) << std::endl;
	return distance_sqr <= sqr(size);
}

std::ostream & operator<<(std::ostream & out, Interval & i){
	out << "[" << i.getmin() << "," << i.getmax() << "]" <<endl;
	return out;
}

std::ostream & operator<<(std::ostream & out,point_surface  & p){
	out << "[ x:" << p.x << ", z: " << p.z << "]" << endl;
	return out;
}

pchunksel analyse_json_unknown(wmValue & v, bool & error);
point analyse_point(wmValue & v, bool & error){
	wmObject obj = v.get_obj();

	std::cout << "analysing point" <<std::endl;
	int X,Y,Z ;
	X=Y=Z=0;
	std::wstring str_x(L"X") ;
	X = obj[std::wstring(str_x)].get_int(); // .get("X").get_int();
	std::wstring str_y(L"Y") ;
	Y = obj[std::wstring(str_y)].get_int();
	std::wstring str_z(L"Z") ;
	Z = obj[std::wstring(str_z)].get_int();

	return point(X,Y,Z);
}

pchunksel analyse_json_circle(wmValue & v, bool & error){
	// pallchunksel sel(new all_criterium_chunk_selector());
	std::cout << "analysing circle" << std::endl;

	point p = analyse_point(v.get_obj()[L"center"],error);
	point_surface p_s(p.x,p.z);
	int size = v.get_obj()[L"diameter"].get_int();
	in_circle_predicate in_c(p_s,size);

	return pchunksel(new in_circle_criterium(in_c)) ;
}

pchunksel analyse_json_not(wmValue & v, bool & error){
	pchunksel inverse( analyse_json_unknown(v,error));
	pchunksel sel(new not_in_criterium_chunk_selector(inverse));
	return sel;
}

pchunksel analyse_json_and (wmValue & v,bool & error){
	std::cout << "analysing and" << std::endl ;
	pallchunksel andsel( new all_criterium_chunk_selector());
	switch (v.type()) {
		case array_type:
			BOOST_FOREACH(wmValue val, v.get_array() ){
				andsel->add_criterium(analyse_json_unknown(val, error));
			}
		break;
		default:
		error=true;
	}
	return andsel;
}

pchunksel analyse_json_or (wmValue & v,bool & error){
	panychunksel anysel( new any_criterium_chunk_selector());
	switch (v.type()) {
		case array_type:
			BOOST_FOREACH(wmValue val, v.get_array() ){
				anysel->add_criterium(analyse_json_unknown(val, error));
			}

		break;
		default:
		error=true;
	}
	return anysel;
}

pchunksel analyse_json_unknown(wmValue & v, bool & error){
	pchunksel sel;
	wmObject obj;
	std::cout << "analysing unknown" << std::endl;
	switch (v.type()){
		case obj_type:
		obj=v.get_obj();
		// write_stream(v,std::cout,raw_utf8);
		BOOST_FOREACH(wmConfig::Pair_type obj_,obj ){
			wstring first = obj_.first ;
			std::cout << "plop";
			std::wcout << first << std::endl;
		}
		std::cout << "is an obj" <<std::endl;
		if (obj.count( L"circle") > 0 ){
			sel = analyse_json_circle(obj[L"circle"],error);
		}else if (obj.count( L"and") > 0 ){
			sel = analyse_json_and(obj[L"and"],error);
		}else if(obj.count( L"or") > 0 ){
			sel = analyse_json_or(obj[L"or"],error);
		}else if(obj.count( L"not") > 0 ){
			sel = analyse_json_not(obj[L"not"],error);
		}else {
			error=true;
		}
		break;
		default:
			error=true;
	}
	return sel;
}

pchunksel selector_factory::from_json_spec(std::string & filename){
	std::wifstream json_file(filename.c_str());
	bool error = false;
	if (! json_file.good()){
		std::cout << "bad json spec selector file : "<< filename <<" exiting" << std::endl;
		exit(0);
	}
	wmValue value;

	read_stream(json_file,value);
	pchunksel p(analyse_json_and(value,error));
	if(error){
		std::cout << "erreur de parsing" << std::endl;
		exit(0);
	}

	return p;
}

<commit_msg>Changed command line switch, added parsing state informations<commit_after>#include "selectors.hpp"

#include "json_spirit/json_spirit_reader_template.h"
#include "json_spirit/json_spirit_writer_template.h"

#include <boost/foreach.hpp>

using namespace json_spirit;

Interval get_chunk_coordinate(int chunk_coord){
	return Interval(chunk_coord * 16, (chunk_coord + 1) * 16 - 1);
}

in_circle_predicate::in_circle_predicate(point_surface & ps, int _size):
	size(_size),center(ps){

}

bool in_circle_predicate::operator()(const mc::utils::level_coord & coord) {
	Interval x_chunk(get_chunk_coordinate(coord.get_x()));
	Interval z_chunk(get_chunk_coordinate(coord.get_z()));

	point_surface  ps=center;
	int distance_sqr;

	int dist_x = x_chunk.distance(ps.x);
	int dist_y = z_chunk.distance(ps.z);

	// std::cout <<" in circle ?" <<std::endl;
	distance_sqr = dist_x * dist_x + dist_y * dist_y ;

	// std::cout <<" d sqr :"<< distance_sqr << ", size" << size * size<<std::endl;
	return distance_sqr <= size * size ;
	// distance of the chunk from the circle
}

template<typename Y>
Y sqr(Y val)
{ return val*val; }

bool in_circle_predicate::operator()(const point & pt){
	// std::cout << "in circle ?" << std::endl;
	int distance_sqr = sqr(pt.x - center.x) + sqr ( pt.z - center.z);
	// std::cout << pt.x << " " << pt.y << " "<< pt.z <<" " << distance_sqr << " " << sqr(size) << std::endl;
	// std::cout << pt.x << " " << pt.z <<" " << distance_sqr << " " << sqr(size) << std::endl;
	return distance_sqr <= sqr(size);
}

std::ostream & operator<<(std::ostream & out, Interval & i){
	out << "[" << i.getmin() << "," << i.getmax() << "]" <<endl;
	return out;
}

std::ostream & operator<<(std::ostream & out,point_surface  & p){
	out << "[ x:" << p.x << ", z: " << p.z << "]" << endl;
	return out;
}

pchunksel analyse_json_unknown(wmValue & v, bool & error);
point analyse_point(wmValue & v, bool & error){
	wmObject obj = v.get_obj();

	std::cout << "analysing point" <<std::endl;
	int X,Y,Z ;
	X=Y=Z=0;
	std::wstring str_x(L"X") ;
	X = obj[std::wstring(str_x)].get_int(); // .get("X").get_int();
	std::wstring str_y(L"Y") ;
	Y = obj[std::wstring(str_y)].get_int();
	std::wstring str_z(L"Z") ;
	Z = obj[std::wstring(str_z)].get_int();

	return point(X,Y,Z);
}

pchunksel analyse_json_circle(wmValue & v, bool & error){
	// pallchunksel sel(new all_criterium_chunk_selector());
	std::cout << "analysing circle" << std::endl;

	point p = analyse_point(v.get_obj()[L"center"],error);
	point_surface p_s(p.x,p.z);
	int size = v.get_obj()[L"diameter"].get_int();
	in_circle_predicate in_c(p_s,size);

	return pchunksel(new in_circle_criterium(in_c)) ;
}

pchunksel analyse_json_not(wmValue & v, bool & error){
	pchunksel inverse( analyse_json_unknown(v,error));
	pchunksel sel(new not_in_criterium_chunk_selector(inverse));
	return sel;
}

pchunksel analyse_json_and (wmValue & v,bool & error){
	std::cout << "analysing and" << std::endl ;
	pallchunksel andsel( new all_criterium_chunk_selector());
	switch (v.type()) {
		case array_type:
			BOOST_FOREACH(wmValue val, v.get_array() ){
				andsel->add_criterium(analyse_json_unknown(val, error));
			}
		break;
		default:
			cout << "erreur de parsing dans le \"and\" : attendu un tableau";
		error=true;
	}
	return andsel;
}

pchunksel analyse_json_or (wmValue & v,bool & error){
	std::cout << "analysing unknown" << std::endl;
	panychunksel anysel( new any_criterium_chunk_selector());
	switch (v.type()) {
		case array_type:
			BOOST_FOREACH(wmValue val, v.get_array() ){
				anysel->add_criterium(analyse_json_unknown(val, error));
			}

		break;
		default:
		cout << "or error parsing" << std::endl;
		error=true;
	}
	return anysel;
}

pchunksel analyse_json_unknown(wmValue & v, bool & error){
	pchunksel sel;
	wmObject obj;
	std::cout << "analysing unknown" << std::endl;
	switch (v.type()){
		case obj_type:
		obj=v.get_obj();
		BOOST_FOREACH(wmConfig::Pair_type obj_,obj ){
			wstring first = obj_.first ;
			std::cout << "plop";
			std::wcout << first << std::endl;
		}
		std::cout << "is an obj" <<std::endl;
		if (obj.count( L"circle") > 0 ){
			sel = analyse_json_circle(obj[L"circle"],error);
		}else if (obj.count( L"and") > 0 ){
			sel = analyse_json_and(obj[L"and"],error);
		}else if(obj.count( L"or") > 0 ){
			sel = analyse_json_or(obj[L"or"],error);
		}else if(obj.count( L"not") > 0 ){
			sel = analyse_json_not(obj[L"not"],error);
		}else {

			cout << "JSon SPec Error : not niether a and, not or circle" << std::endl;
			error=true;
		}
		break;
		default:
			cout << "Json Spec Error : Object waited";
			error=true;
	}
	return sel;
}

pchunksel selector_factory::from_json_spec(std::string & filename){
	std::wifstream json_file(filename.c_str());
	bool error = false;
	if (! json_file.good()){
		std::cout << "bad json spec selector file : "<< filename <<" exiting" << std::endl;
		exit(0);
	}
	wmValue value;

	read_stream(json_file,value);
	pchunksel p(analyse_json_and(value,error));
	if(error){
		std::cout << "erreur de parsing" << std::endl;
		exit(0);
	}

	return p;
}

<|endoftext|>


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

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

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

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

#include "mitkImageToSurfaceFilter.h"
#include <vtkImageData.h>
#include <vtkDecimate.h>
#include <vtkDecimatePro.h>
#include <vtkImageChangeInformation.h>
#include <vtkLinearTransform.h>
#include <vtkMath.h>
#include <vtkMatrix4x4.h>

mitk::ImageToSurfaceFilter::ImageToSurfaceFilter()
{
  m_Smooth = false;
  m_Decimate = NoDecimation;
  m_Threshold = 1;
  m_TargetReduction = 0.95f;
};

mitk::ImageToSurfaceFilter::~ImageToSurfaceFilter()
{
};

template <class T1, class T2, class T3>
inline void mitkVtkLinearTransformPoint(T1 matrix[4][4],
                                           T2 in[3], T3 out[3])
{
  T3 x = matrix[0][0]*in[0]+matrix[0][1]*in[1]+matrix[0][2]*in[2]+matrix[0][3];
  T3 y = matrix[1][0]*in[0]+matrix[1][1]*in[1]+matrix[1][2]*in[2]+matrix[1][3];
  T3 z = matrix[2][0]*in[0]+matrix[2][1]*in[1]+matrix[2][2]*in[2]+matrix[2][3];

  out[0] = x;
  out[1] = y;
  out[2] = z;
}

void mitk::ImageToSurfaceFilter::CreateSurface(int time, vtkImageData *vtkimage, mitk::Surface * surface, const ScalarType threshold)
{
  vtkImageChangeInformation *indexCoordinatesImageFilter = vtkImageChangeInformation::New();
  indexCoordinatesImageFilter->SetInput(vtkimage);
  indexCoordinatesImageFilter->SetOutputOrigin(0.0,0.0,0.0);

  //MarchingCube -->create Surface
  vtkMarchingCubes *skinExtractor = vtkMarchingCubes::New();
  skinExtractor->SetInput(indexCoordinatesImageFilter->GetOutput());//RC++
  indexCoordinatesImageFilter->Delete();
  skinExtractor->SetValue(0, threshold);

  vtkPolyData *polydata;
  polydata = skinExtractor->GetOutput();
  polydata->Register(NULL);//RC++
  skinExtractor->Delete();

  if (m_Smooth)
  {
    int spIterations =50;
    float spRelaxation =0.1;

    vtkSmoothPolyDataFilter *smoother = vtkSmoothPolyDataFilter::New();
    //read poly1 (poly1 can be the original polygon, or the decimated polygon)
    smoother->SetInput(polydata);//RC++
    smoother->SetNumberOfIterations( spIterations );
    smoother->SetRelaxationFactor( spRelaxation );
    smoother->SetFeatureAngle( 60 );
    smoother->FeatureEdgeSmoothingOff();
    smoother->BoundarySmoothingOff();
    smoother->SetConvergence( 0 );

    polydata->Delete();//RC--
    polydata = smoother->GetOutput();
    polydata->Register(NULL);//RC++
    smoother->Delete();
  }

  //decimate = to reduce number of polygons
  if(m_Decimate==DecimatePro)
  {
    vtkDecimatePro *decimate = vtkDecimatePro::New();
    decimate->SplittingOff();
    decimate->SetErrorIsAbsolute(5);
    decimate->SetFeatureAngle(30);
    decimate->PreserveTopologyOn();
    decimate->BoundaryVertexDeletionOff();
    decimate->SetDegree(10); //std-value is 25!

    decimate->SetInput(polydata);//RC++
    decimate->SetTargetReduction(m_TargetReduction);
    decimate->SetMaximumError(0.002);

    polydata->Delete();//RC--
    polydata = decimate->GetOutput();
    polydata->Register(NULL);//RC++
    decimate->Delete();
  }
  else if (m_Decimate==Decimate)
  {
    vtkDecimate *decimate = vtkDecimate::New();
    decimate->SetInput( polydata );
    decimate->PreserveTopologyOn();
    decimate->BoundaryVertexDeletionOff();
    decimate->SetTargetReduction( m_TargetReduction );
    polydata->Delete();//RC--
    polydata = decimate->GetOutput();
    polydata->Register(NULL);//RC++
    decimate->Delete();
  }

  polydata->Update();

  polydata->SetSource(NULL);

  vtkFloatingPointType* spacing;
  spacing = vtkimage->GetSpacing();

  vtkPoints * points = polydata->GetPoints();
  vtkMatrix4x4 *vtkmatrix = vtkMatrix4x4::New();
  GetInput()->GetGeometry(time)->GetVtkTransform()->GetMatrix(vtkmatrix);
  double (*matrix)[4] = vtkmatrix->Element;

  unsigned int i,j;
  for(i=0;i<3;++i)
    for(j=0;j<3;++j)
      matrix[i][j]/=spacing[j];

  unsigned int n = points->GetNumberOfPoints();
  vtkFloatingPointType point[3];

  for (i = 0; i < n; i++)
  {
    points->GetPoint(i, point);
    mitkVtkLinearTransformPoint(matrix,point,point);
    points->SetPoint(i, point);
  }
  vtkmatrix->Delete();

  surface->SetVtkPolyData(polydata, time);
  polydata->UnRegister(NULL);
}

void mitk::ImageToSurfaceFilter::GenerateData()
{
  mitk::Surface *surface = this->GetOutput();
  mitk::Image * image        =  (mitk::Image*)GetInput();
  mitk::Image::RegionType outputRegion = image->GetRequestedRegion();

  int tstart=outputRegion.GetIndex(3);
  int tmax=tstart+outputRegion.GetSize(3); //GetSize()==1 - will aber 0 haben, wenn nicht zeitaufgelst

  int t;
  for( t=tstart; t < tmax; ++t)
  {
    vtkImageData *vtkimagedata =  image->GetVtkImageData(t);
    CreateSurface(t,vtkimagedata,surface,m_Threshold);
  }
}

void mitk::ImageToSurfaceFilter::SetInput(const mitk::Image *image)
{
  // Process object is not const-correct so the const_cast is required here
  this->ProcessObject::SetNthInput(0, const_cast< mitk::Image * >( image ) );
}

const mitk::Image *mitk::ImageToSurfaceFilter::GetInput(void)
{
  if (this->GetNumberOfInputs() < 1)
  {
    return 0;
  }

  return static_cast<const mitk::Image * >
    ( this->ProcessObject::GetInput(0) );
}

void mitk::ImageToSurfaceFilter::GenerateOutputInformation()
{
  mitk::Image::ConstPointer inputImage  =(mitk::Image*) this->GetInput();

  //mitk::Image *inputImage = (mitk::Image*)this->GetImage();
  mitk::Surface::Pointer output = this->GetOutput();

  itkDebugMacro(<<"GenerateOutputInformation()");

  if(inputImage.IsNull()) return;

  //Set Data
}
<commit_msg>FIX: do not crash when no surface has been generated<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

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

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

#include "mitkImageToSurfaceFilter.h"
#include <vtkImageData.h>
#include <vtkDecimate.h>
#include <vtkDecimatePro.h>
#include <vtkImageChangeInformation.h>
#include <vtkLinearTransform.h>
#include <vtkMath.h>
#include <vtkMatrix4x4.h>

mitk::ImageToSurfaceFilter::ImageToSurfaceFilter()
{
  m_Smooth = false;
  m_Decimate = NoDecimation;
  m_Threshold = 1;
  m_TargetReduction = 0.95f;
};

mitk::ImageToSurfaceFilter::~ImageToSurfaceFilter()
{
};

template <class T1, class T2, class T3>
inline void mitkVtkLinearTransformPoint(T1 matrix[4][4],
                                           T2 in[3], T3 out[3])
{
  T3 x = matrix[0][0]*in[0]+matrix[0][1]*in[1]+matrix[0][2]*in[2]+matrix[0][3];
  T3 y = matrix[1][0]*in[0]+matrix[1][1]*in[1]+matrix[1][2]*in[2]+matrix[1][3];
  T3 z = matrix[2][0]*in[0]+matrix[2][1]*in[1]+matrix[2][2]*in[2]+matrix[2][3];

  out[0] = x;
  out[1] = y;
  out[2] = z;
}

void mitk::ImageToSurfaceFilter::CreateSurface(int time, vtkImageData *vtkimage, mitk::Surface * surface, const ScalarType threshold)
{
  vtkImageChangeInformation *indexCoordinatesImageFilter = vtkImageChangeInformation::New();
  indexCoordinatesImageFilter->SetInput(vtkimage);
  indexCoordinatesImageFilter->SetOutputOrigin(0.0,0.0,0.0);

  //MarchingCube -->create Surface
  vtkMarchingCubes *skinExtractor = vtkMarchingCubes::New();
  skinExtractor->SetInput(indexCoordinatesImageFilter->GetOutput());//RC++
  indexCoordinatesImageFilter->Delete();
  skinExtractor->SetValue(0, threshold);

  vtkPolyData *polydata;
  polydata = skinExtractor->GetOutput();
  polydata->Register(NULL);//RC++
  skinExtractor->Delete();

  if (m_Smooth)
  {
    int spIterations =50;
    float spRelaxation =0.1;

    vtkSmoothPolyDataFilter *smoother = vtkSmoothPolyDataFilter::New();
    //read poly1 (poly1 can be the original polygon, or the decimated polygon)
    smoother->SetInput(polydata);//RC++
    smoother->SetNumberOfIterations( spIterations );
    smoother->SetRelaxationFactor( spRelaxation );
    smoother->SetFeatureAngle( 60 );
    smoother->FeatureEdgeSmoothingOff();
    smoother->BoundarySmoothingOff();
    smoother->SetConvergence( 0 );

    polydata->Delete();//RC--
    polydata = smoother->GetOutput();
    polydata->Register(NULL);//RC++
    smoother->Delete();
  }

  //decimate = to reduce number of polygons
  if(m_Decimate==DecimatePro)
  {
    vtkDecimatePro *decimate = vtkDecimatePro::New();
    decimate->SplittingOff();
    decimate->SetErrorIsAbsolute(5);
    decimate->SetFeatureAngle(30);
    decimate->PreserveTopologyOn();
    decimate->BoundaryVertexDeletionOff();
    decimate->SetDegree(10); //std-value is 25!

    decimate->SetInput(polydata);//RC++
    decimate->SetTargetReduction(m_TargetReduction);
    decimate->SetMaximumError(0.002);

    polydata->Delete();//RC--
    polydata = decimate->GetOutput();
    polydata->Register(NULL);//RC++
    decimate->Delete();
  }
  else if (m_Decimate==Decimate)
  {
    vtkDecimate *decimate = vtkDecimate::New();
    decimate->SetInput( polydata );
    decimate->PreserveTopologyOn();
    decimate->BoundaryVertexDeletionOff();
    decimate->SetTargetReduction( m_TargetReduction );
    polydata->Delete();//RC--
    polydata = decimate->GetOutput();
    polydata->Register(NULL);//RC++
    decimate->Delete();
  }

  polydata->Update();

  polydata->SetSource(NULL);

  if(polydata->GetNumberOfPoints() > 0)
  {
    vtkFloatingPointType* spacing;
    spacing = vtkimage->GetSpacing();

    vtkPoints * points = polydata->GetPoints();
    vtkMatrix4x4 *vtkmatrix = vtkMatrix4x4::New();
    GetInput()->GetGeometry(time)->GetVtkTransform()->GetMatrix(vtkmatrix);
    double (*matrix)[4] = vtkmatrix->Element;

    unsigned int i,j;
    for(i=0;i<3;++i)
      for(j=0;j<3;++j)
        matrix[i][j]/=spacing[j];

    unsigned int n = points->GetNumberOfPoints();
    vtkFloatingPointType point[3];

    for (i = 0; i < n; i++)
    {
      points->GetPoint(i, point);
      mitkVtkLinearTransformPoint(matrix,point,point);
      points->SetPoint(i, point);
    }
    vtkmatrix->Delete();
  }

  surface->SetVtkPolyData(polydata, time);
  polydata->UnRegister(NULL);
}

void mitk::ImageToSurfaceFilter::GenerateData()
{
  mitk::Surface *surface = this->GetOutput();
  mitk::Image * image        =  (mitk::Image*)GetInput();
  mitk::Image::RegionType outputRegion = image->GetRequestedRegion();

  int tstart=outputRegion.GetIndex(3);
  int tmax=tstart+outputRegion.GetSize(3); //GetSize()==1 - will aber 0 haben, wenn nicht zeitaufgelst

  int t;
  for( t=tstart; t < tmax; ++t)
  {
    vtkImageData *vtkimagedata =  image->GetVtkImageData(t);
    CreateSurface(t,vtkimagedata,surface,m_Threshold);
  }
}

void mitk::ImageToSurfaceFilter::SetInput(const mitk::Image *image)
{
  // Process object is not const-correct so the const_cast is required here
  this->ProcessObject::SetNthInput(0, const_cast< mitk::Image * >( image ) );
}

const mitk::Image *mitk::ImageToSurfaceFilter::GetInput(void)
{
  if (this->GetNumberOfInputs() < 1)
  {
    return 0;
  }

  return static_cast<const mitk::Image * >
    ( this->ProcessObject::GetInput(0) );
}

void mitk::ImageToSurfaceFilter::GenerateOutputInformation()
{
  mitk::Image::ConstPointer inputImage  =(mitk::Image*) this->GetInput();

  //mitk::Image *inputImage = (mitk::Image*)this->GetImage();
  mitk::Surface::Pointer output = this->GetOutput();

  itkDebugMacro(<<"GenerateOutputInformation()");

  if(inputImage.IsNull()) return;

  //Set Data
}
<|endoftext|>


<commit_before>#include "StateMachine.h"
#include "StateTransitionOperation.h"
#include "OperationEvent.h"
#include "UndoController.h"

//##ModelId=3E5B2DB301FD
mitk::StateMachine::StateMachine(std::string type)
: m_Type(type), m_CurrentState(0)
{}

//##ModelId=3E5B2E660087
std::string mitk::StateMachine::GetType() const
{
	return m_Type;
}

//##ModelId=3E5B2DE30378
bool mitk::StateMachine::HandleEvent(StateEvent const* stateEvent)
{
	if (m_CurrentState == NULL)
		return false;//m_CurrentState needs to be set first!

	const Transition *tempTransition = m_CurrentState->GetTransition(stateEvent->GetId());
	State *tempState = tempTransition->GetNextState();
	if (tempState == NULL)
		return false;
	int tempSideEffectId = tempTransition->GetSideEffectId();

	//UNDO StateTransitionOperation
	StateTransitionOperation* undoSTO = new StateTransitionOperation(mitk::STATETRANSITION, m_CurrentState);
	StateTransitionOperation* redoSTO = new StateTransitionOperation(mitk::STATETRANSITION, tempState);//tempStateZeiger? mgl. Fehlerquelle

	//Dummy
	//OperationActor *destination = new OperationActor;//hier StateMachine, also "this"???
	//Dummy

	OperationEvent *tempOE = new OperationEvent();//to get Object- and GroupEventId
	OperationEvent *operationEvent = new OperationEvent(((mitk::OperationActor*)(this)), undoSTO, redoSTO,
						tempOE->GenerateObjectEventId(), tempOE->GenerateGroupEventId());
	UndoController *undoController = new UndoController(mitk::LIMITEDLINEARUNDO);//switch to LLU or add LLU
	undoController->SetOperationEvent(operationEvent);

	//first following StateChange, then operation(SideEffect)
	m_CurrentState = tempState;

	bool ok = ExecuteSideEffect(tempSideEffectId);//Undo in ExecuteSideEffect(...)
	return ok;
}

<commit_msg>error notification test<commit_after>#include "StateMachine.h"
#include "StateTransitionOperation.h"
#include "OperationEvent.h"
#include "UndoController.h"

#include "StupidErrorNotification.h"

//##ModelId=3E5B2DB301FD
mitk::StateMachine::StateMachine(std::string type)
: m_Type(type), m_CurrentState(0)
{}

//##ModelId=3E5B2E660087
std::string mitk::StateMachine::GetType() const
{
	return m_Type;
}

//##ModelId=3E5B2DE30378
bool mitk::StateMachine::HandleEvent(StateEvent const* stateEvent)
{
	if (m_CurrentState == NULL)
		return false;//m_CurrentState needs to be set first!

	const Transition *tempTransition = m_CurrentState->GetTransition(stateEvent->GetId());
	State *tempState = tempTransition->GetNextState();
	if (tempState == NULL)
		return false;
	int tempSideEffectId = tempTransition->GetSideEffectId();

	//UNDO StateTransitionOperation
	StateTransitionOperation* undoSTO = new StateTransitionOperation(mitk::STATETRANSITION, m_CurrentState);
	StateTransitionOperation* redoSTO = new StateTransitionOperation(mitk::STATETRANSITION, tempState);//tempStateZeiger? mgl. Fehlerquelle

	//Dummy
	//OperationActor *destination = new OperationActor;//hier StateMachine, also "this"???
	//Dummy

	OperationEvent *tempOE = new OperationEvent();//to get Object- and GroupEventId
	OperationEvent *operationEvent = new OperationEvent(((mitk::OperationActor*)(this)), undoSTO, redoSTO,
						tempOE->GenerateObjectEventId(), tempOE->GenerateGroupEventId());
	UndoController *undoController = new UndoController(mitk::LIMITEDLINEARUNDO);//switch to LLU or add LLU
	undoController->SetOperationEvent(operationEvent);

	//first following StateChange, then operation(SideEffect)
	m_CurrentState = tempState;

	bool ok = ExecuteSideEffect(tempSideEffectId);//Undo in ExecuteSideEffect(...)
	return ok;
}

<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

=========================================================================*/
#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbMultiToMonoChannelExtractROI.h"
#include "itkRescaleIntensityImageFilter.h"
#include "otbVectorRescaleIntensityImageFilter.h"

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {ROI_QB_MUL_1.png}
//    OUTPUTS: {PCAOutput.tif}, {InversePCAOutput.tif},{InversePCAOutput1.png}, {PCAOutput1.png}, {PCAOutput2.png}, {PCAOutput3.png}
//    3
//  Software Guide : EndCommandLineArgs

// Software Guide : BeginLatex
//
// This example illustrates the use of the
// \doxygen{otb}{PCAImageFilter}.
// This filter computes a Principal Component Analysis using an
// efficient method based on the inner product in order to compute the
// covariance matrix.
//
// The first step required to use this filter is to include its header file.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "otbPCAImageFilter.h"
// Software Guide : EndCodeSnippet

int main(int argc, char* argv[])
{
  typedef double PixelType;
  const unsigned int Dimension = 2;
  const char *       inputFileName = argv[1];
  const char *       outputFilename = argv[2];
  const char *       outputInverseFilename = argv[3];
  const unsigned int numberOfPrincipalComponentsRequired(atoi(argv[8]));

  // Software Guide : BeginLatex
  //
  // We start by defining the types for the images and the reader and
  // the writer. We choose to work with a \doxygen{otb}{VectorImage},
  // since we will produce a multi-channel image (the principal
  // components) from a multi-channel input image.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef otb::VectorImage<PixelType, Dimension> ImageType;
  typedef otb::ImageFileReader<ImageType>        ReaderType;
  typedef otb::ImageFileWriter<ImageType>        WriterType;
  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // We instantiate now the image reader and we set the image file name.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  ReaderType::Pointer reader     = ReaderType::New();
  reader->SetFileName(inputFileName);
  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // We define the type for the filter. It is templated over the input
  // and the output image types and also the transformation direction. The
  // internal structure of this filter is a filter-to-filter like structure.
  // We can now the instantiate the filter.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef otb::PCAImageFilter<ImageType, ImageType,
                              otb::Transform::FORWARD> PCAFilterType;
  PCAFilterType::Pointer pcafilter     = PCAFilterType::New();
  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // The only parameter needed for the PCA is the number of principal
  // components required as output. We can choose to get less PCs than
  // the number of input bands.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  pcafilter->SetNumberOfPrincipalComponentsRequired(
    numberOfPrincipalComponentsRequired);
  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // We now instantiate the writer and set the file name for the
  // output image.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  WriterType::Pointer writer     = WriterType::New();
  writer->SetFileName(outputFilename);
  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // We finally plug the pipeline and trigger the PCA computation with
  // the method \code{Update()} of the writer.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  pcafilter->SetInput(reader->GetOutput());
  writer->SetInput(pcafilter->GetOutput());

  writer->Update();
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // \doxygen{otb}{PCAImageFilter} allows also to compute inverse
  // transformation from PCA coefficients. In REVERSE mode, the
  // covariance matrix or the transformation matrix
  // (which may not be square) has to be given.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef otb::PCAImageFilter< ImageType, ImageType, otb::Transform::INVERSE > InvPCAFilterType;
  InvPCAFilterType::Pointer invFilter = InvPCAFilterType::New();
  invFilter->SetInput(pcafilter->GetOutput());
  invFilter->SetTransformationMatrix(pcafilter->GetTransformationMatrix());

  WriterType::Pointer invWriter = WriterType::New();
  invWriter->SetFileName(outputInverseFilename );
  invWriter->SetInput(invFilter->GetOutput() );

  invWriter->Update();

  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  // Figure~\ref{fig:PCA_FILTER} shows the result of applying
  // the PCA to a 3 band RGB image.
  // \begin{figure}
  // \center
  // \includegraphics[width=0.25\textwidth]{ROI_QB_MUL_1.eps}
  // \includegraphics[width=0.25\textwidth]{PCAOutput1.eps}
  // \includegraphics[width=0.25\textwidth]{PCAOutput2.eps}
  // \includegraphics[width=0.25\textwidth]{PCAOutput3.eps}
  // \includegraphics[width=0.25\textwidth]{InversePCAOutput1.eps}
  // \itkcaption[PCA Filter (forward trasnformation)]{Result of applying the
  // \doxygen{otb}{PCAImageFilter} to an image. From left
  // to right and top to bottom:
  // original image, first PC, second PC, third PC and inverse mode output.}
  // \label{fig:PCA_FILTER}
  // \end{figure}
  //
  //  Software Guide : EndLatex

  typedef otb::Image<PixelType, Dimension> MonoImageType;

  typedef otb::MultiToMonoChannelExtractROI<PixelType, PixelType>
  ExtractROIFilterType;

  typedef otb::Image<unsigned char, 2>                OutputImageType;
  typedef otb::VectorImage<unsigned char, 2>          OutputPrettyImageType;
  typedef otb::ImageFileWriter<OutputImageType>       WriterType2;
  typedef otb::ImageFileWriter<OutputPrettyImageType> WriterType3;

  typedef itk::RescaleIntensityImageFilter<MonoImageType,
                                           OutputImageType> RescalerType;

  typedef otb::VectorRescaleIntensityImageFilter<ImageType,
						 OutputPrettyImageType> RescalerType2;
  typedef ImageType::PixelType                  VectorPixelType;

  for (unsigned int cpt = 0; cpt < numberOfPrincipalComponentsRequired; cpt++)
    {
    ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New();
    RescalerType::Pointer         rescaler = RescalerType::New();
    WriterType2::Pointer          writer2 = WriterType2::New();

    extractROIFilter->SetInput(pcafilter->GetOutput());
    extractROIFilter->SetChannel(cpt + 1);

    rescaler->SetInput(extractROIFilter->GetOutput());
    rescaler->SetOutputMinimum(0);
    rescaler->SetOutputMaximum(255);

    writer2->SetInput(rescaler->GetOutput());
    writer2->SetFileName(argv[cpt + 5]);
    writer2->Update();
    }

  WriterType3::Pointer          writerInverse = WriterType3::New();
  RescalerType2::Pointer        rescalerInverse = RescalerType2::New();
  rescalerInverse->SetInput(invFilter->GetOutput());

  VectorPixelType minimum, maximum;
  minimum.SetSize(3);
  maximum.SetSize(3);
  minimum.Fill(0);
  maximum.Fill(255);
  rescalerInverse->SetOutputMinimum(minimum);
  rescalerInverse->SetOutputMaximum(maximum);

  writerInverse->SetInput(rescalerInverse->GetOutput());
  writerInverse->SetFileName(argv[4]);
  writerInverse->Update();

  return EXIT_SUCCESS;
}
<commit_msg>STYLE:kwstyle<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

=========================================================================*/
#include "otbImage.h"
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbMultiToMonoChannelExtractROI.h"
#include "itkRescaleIntensityImageFilter.h"
#include "otbVectorRescaleIntensityImageFilter.h"

//  Software Guide : BeginCommandLineArgs
//    INPUTS: {ROI_QB_MUL_1.png}
//    OUTPUTS: {PCAOutput.tif}, {InversePCAOutput.tif},{InversePCAOutput1.png}, {PCAOutput1.png}, {PCAOutput2.png}, {PCAOutput3.png}
//    3
//  Software Guide : EndCommandLineArgs

// Software Guide : BeginLatex
//
// This example illustrates the use of the
// \doxygen{otb}{PCAImageFilter}.
// This filter computes a Principal Component Analysis using an
// efficient method based on the inner product in order to compute the
// covariance matrix.
//
// The first step required to use this filter is to include its header file.
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "otbPCAImageFilter.h"
// Software Guide : EndCodeSnippet

int main(int argc, char* argv[])
{
  typedef double PixelType;
  const unsigned int Dimension = 2;
  const char *       inputFileName = argv[1];
  const char *       outputFilename = argv[2];
  const char *       outputInverseFilename = argv[3];
  const unsigned int numberOfPrincipalComponentsRequired(atoi(argv[8]));

  // Software Guide : BeginLatex
  //
  // We start by defining the types for the images and the reader and
  // the writer. We choose to work with a \doxygen{otb}{VectorImage},
  // since we will produce a multi-channel image (the principal
  // components) from a multi-channel input image.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef otb::VectorImage<PixelType, Dimension> ImageType;
  typedef otb::ImageFileReader<ImageType>        ReaderType;
  typedef otb::ImageFileWriter<ImageType>        WriterType;
  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // We instantiate now the image reader and we set the image file name.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  ReaderType::Pointer reader     = ReaderType::New();
  reader->SetFileName(inputFileName);
  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // We define the type for the filter. It is templated over the input
  // and the output image types and also the transformation direction. The
  // internal structure of this filter is a filter-to-filter like structure.
  // We can now the instantiate the filter.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef otb::PCAImageFilter<ImageType, ImageType,
                              otb::Transform::FORWARD> PCAFilterType;
  PCAFilterType::Pointer pcafilter     = PCAFilterType::New();
  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // The only parameter needed for the PCA is the number of principal
  // components required as output. We can choose to get less PCs than
  // the number of input bands.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  pcafilter->SetNumberOfPrincipalComponentsRequired(
    numberOfPrincipalComponentsRequired);
  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // We now instantiate the writer and set the file name for the
  // output image.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  WriterType::Pointer writer     = WriterType::New();
  writer->SetFileName(outputFilename);
  // Software Guide : EndCodeSnippet
  // Software Guide : BeginLatex
  //
  // We finally plug the pipeline and trigger the PCA computation with
  // the method \code{Update()} of the writer.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  pcafilter->SetInput(reader->GetOutput());
  writer->SetInput(pcafilter->GetOutput());

  writer->Update();
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // \doxygen{otb}{PCAImageFilter} allows also to compute inverse
  // transformation from PCA coefficients. In REVERSE mode, the
  // covariance matrix or the transformation matrix
  // (which may not be square) has to be given.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef otb::PCAImageFilter< ImageType, ImageType, otb::Transform::INVERSE > InvPCAFilterType;
  InvPCAFilterType::Pointer invFilter = InvPCAFilterType::New();
  invFilter->SetInput(pcafilter->GetOutput());
  invFilter->SetTransformationMatrix(pcafilter->GetTransformationMatrix());

  WriterType::Pointer invWriter = WriterType::New();
  invWriter->SetFileName(outputInverseFilename );
  invWriter->SetInput(invFilter->GetOutput() );

  invWriter->Update();

  // Software Guide : EndCodeSnippet

  //  Software Guide : BeginLatex
  // Figure~\ref{fig:PCA_FILTER} shows the result of applying
  // the PCA to a 3 band RGB image.
  // \begin{figure}
  // \center
  // \includegraphics[width=0.25\textwidth]{ROI_QB_MUL_1.eps}
  // \includegraphics[width=0.25\textwidth]{PCAOutput1.eps}
  // \includegraphics[width=0.25\textwidth]{PCAOutput2.eps}
  // \includegraphics[width=0.25\textwidth]{PCAOutput3.eps}
  // \includegraphics[width=0.25\textwidth]{InversePCAOutput1.eps}
  // \itkcaption[PCA Filter (forward trasnformation)]{Result of applying the
  // \doxygen{otb}{PCAImageFilter} to an image. From left
  // to right and top to bottom:
  // original image, first PC, second PC, third PC and inverse mode output.}
  // \label{fig:PCA_FILTER}
  // \end{figure}
  //
  //  Software Guide : EndLatex

  typedef otb::Image<PixelType, Dimension> MonoImageType;

  typedef otb::MultiToMonoChannelExtractROI<PixelType, PixelType>
  ExtractROIFilterType;

  typedef otb::Image<unsigned char, 2>                OutputImageType;
  typedef otb::VectorImage<unsigned char, 2>          OutputPrettyImageType;
  typedef otb::ImageFileWriter<OutputImageType>       WriterType2;
  typedef otb::ImageFileWriter<OutputPrettyImageType> WriterType3;

  typedef itk::RescaleIntensityImageFilter<MonoImageType,
                                           OutputImageType> RescalerType;

  typedef otb::VectorRescaleIntensityImageFilter<ImageType,
                                                 OutputPrettyImageType> RescalerType2;

  typedef ImageType::PixelType                  VectorPixelType;

  for (unsigned int cpt = 0; cpt < numberOfPrincipalComponentsRequired; cpt++)
    {
    ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New();
    RescalerType::Pointer         rescaler = RescalerType::New();
    WriterType2::Pointer          writer2 = WriterType2::New();

    extractROIFilter->SetInput(pcafilter->GetOutput());
    extractROIFilter->SetChannel(cpt + 1);

    rescaler->SetInput(extractROIFilter->GetOutput());
    rescaler->SetOutputMinimum(0);
    rescaler->SetOutputMaximum(255);

    writer2->SetInput(rescaler->GetOutput());
    writer2->SetFileName(argv[cpt + 5]);
    writer2->Update();
    }

  WriterType3::Pointer          writerInverse = WriterType3::New();
  RescalerType2::Pointer        rescalerInverse = RescalerType2::New();
  rescalerInverse->SetInput(invFilter->GetOutput());

  VectorPixelType minimum, maximum;
  minimum.SetSize(3);
  maximum.SetSize(3);
  minimum.Fill(0);
  maximum.Fill(255);
  rescalerInverse->SetOutputMinimum(minimum);
  rescalerInverse->SetOutputMaximum(maximum);

  writerInverse->SetInput(rescalerInverse->GetOutput());
  writerInverse->SetFileName(argv[4]);
  writerInverse->Update();

  return EXIT_SUCCESS;
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkSimpleImageToImageFilter.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/
#include "vtkSimpleImageToImageFilter.h"

#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"

vtkCxxRevisionMacro(vtkSimpleImageToImageFilter, "1.14");

//----------------------------------------------------------------------------
vtkSimpleImageToImageFilter::vtkSimpleImageToImageFilter()
{
}

//----------------------------------------------------------------------------
vtkSimpleImageToImageFilter::~vtkSimpleImageToImageFilter()
{
}

int vtkSimpleImageToImageFilter::RequestUpdateExtent (
  vtkInformation * vtkNotUsed(request),
  vtkInformationVector **inputVector,
  vtkInformationVector *vtkNotUsed( outputVector ))
{
  vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);

  // always request the whole extent
  inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(),
              inInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()),6);

  return 1;
}

int vtkSimpleImageToImageFilter::RequestData(
  vtkInformation* vtkNotUsed( request ),
  vtkInformationVector** inputVector,
  vtkInformationVector* outputVector)
{
  // get the data object
  vtkInformation *outInfo = outputVector->GetInformationObject(0);
  vtkImageData *output = vtkImageData::SafeDownCast(
    outInfo->Get(vtkDataObject::DATA_OBJECT()));

  vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
  vtkImageData *input = vtkImageData::SafeDownCast(
    inInfo->Get(vtkDataObject::DATA_OBJECT()));

  // Set the extent of the output and allocate memory.
  output->SetExtent(
    outInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()));
  output->AllocateScalars();

  this->SimpleExecute(input, output);

  return 1;
}

//----------------------------------------------------------------------------
void vtkSimpleImageToImageFilter::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
}
<commit_msg>BUG: better handking of empty input<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkSimpleImageToImageFilter.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/
#include "vtkSimpleImageToImageFilter.h"

#include "vtkImageData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkStreamingDemandDrivenPipeline.h"

vtkCxxRevisionMacro(vtkSimpleImageToImageFilter, "1.15");

//----------------------------------------------------------------------------
vtkSimpleImageToImageFilter::vtkSimpleImageToImageFilter()
{
}

//----------------------------------------------------------------------------
vtkSimpleImageToImageFilter::~vtkSimpleImageToImageFilter()
{
}

int vtkSimpleImageToImageFilter::RequestUpdateExtent (
  vtkInformation * vtkNotUsed(request),
  vtkInformationVector **inputVector,
  vtkInformationVector *vtkNotUsed( outputVector ))
{
  vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);

  // always request the whole extent
  inInfo->Set(vtkStreamingDemandDrivenPipeline::UPDATE_EXTENT(),
              inInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()),6);

  return 1;
}

int vtkSimpleImageToImageFilter::RequestData(
  vtkInformation* vtkNotUsed( request ),
  vtkInformationVector** inputVector,
  vtkInformationVector* outputVector)
{
  // get the data object
  vtkInformation *outInfo = outputVector->GetInformationObject(0);
  vtkImageData *output = vtkImageData::SafeDownCast(
    outInfo->Get(vtkDataObject::DATA_OBJECT()));

  vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
  vtkImageData *input = vtkImageData::SafeDownCast(
    inInfo->Get(vtkDataObject::DATA_OBJECT()));

  int inExt[6];
  input->GetExtent(inExt);
  // if the input extent is empty then exit
  if (inExt[1] < inExt[0] ||
      inExt[3] < inExt[2] ||
      inExt[5] < inExt[4])
    {
    return 1;
    }

  // Set the extent of the output and allocate memory.
  output->SetExtent(
    outInfo->Get(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT()));
  output->AllocateScalars();

  this->SimpleExecute(input, output);

  return 1;
}

//----------------------------------------------------------------------------
void vtkSimpleImageToImageFilter::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);
}
<|endoftext|>


<commit_before>#include "SyncThread.h"
#include "common/RhoTime.h"
#include "common/RhoConf.h"
#include "common/RhoFilePath.h"

#include "ruby/ext/rho/rhoruby.h"
#include "sync/ClientRegister.h"

namespace rho {
namespace sync {

using namespace rho::common;
using namespace rho::db;

IMPLEMENT_LOGCLASS(CSyncThread,"Sync");
CSyncThread* CSyncThread::m_pInstance = 0;

/*static*/ CSyncThread* CSyncThread::Create(common::IRhoClassFactory* factory)
{
    if ( m_pInstance )
        return m_pInstance;

    m_pInstance = new CSyncThread(factory);
    return m_pInstance;
}

/*static*/void CSyncThread::Destroy()
{
    if ( m_pInstance )
        delete m_pInstance;

    m_pInstance = 0;
}

CSyncThread::CSyncThread(common::IRhoClassFactory* factory) : CThreadQueue(factory)
{
    CThreadQueue::setLogCategory(getLogCategory());

    if( RHOCONF().isExist("sync_poll_interval") )
        setPollInterval(RHOCONF().getInt("sync_poll_interval"));

    m_oSyncEngine.setFactory(factory);

    if ( RHOCONF().getString("syncserver").length() > 0 )
        start(epLow);
}

CSyncThread::~CSyncThread(void)
{
    m_oSyncEngine.exitSync();
    stop(SYNC_WAIT_BEFOREKILL_SECONDS);

    db::CDBAdapter::closeAll();
}

#ifndef RHO_NO_RUBY
unsigned long CSyncThread::getRetValue()
{
    unsigned long ret = rho_ruby_get_NIL();
    if ( isNoThreadedMode()  )
    {
        ret = rho_ruby_create_string( getSyncEngine().getNotify().getNotifyBody().c_str() );
        getSyncEngine().getNotify().cleanNotifyBody();
    }

    return ret;
}
#else
unsigned long CSyncThread::getRetValue()
{
    unsigned long ret = 0;
    if ( isNoThreadedMode()  )
    {
        ret = (unsigned long)rho_sync_create_string( getSyncEngine().getNotify().getNotifyBody().c_str() );
        getSyncEngine().getNotify().cleanNotifyBody();
    }

    return ret;
}
#endif

int CSyncThread::getLastPollInterval()
{
    uint64 nowTime = CLocalTime().toULong();

    DBResult( res, CDBAdapter::getUserDB().executeSQL("SELECT last_updated from sources") );
    uint64 latestTimeUpdated = 0;
    for ( ; !res.isEnd(); res.next() )
    {
        uint64 timeUpdated = res.getUInt64ByIdx(0);
        if ( latestTimeUpdated < timeUpdated )
        	latestTimeUpdated = timeUpdated;
    }

	return latestTimeUpdated > 0 ? (int)(nowTime-latestTimeUpdated) : 0;
}

void CSyncThread::processCommands()//throws Exception
{
    if ( isNoCommands() )
        addQueueCommand(new CSyncCommand(scNone,false));

    CThreadQueue::processCommands();
}

void CSyncThread::checkShowStatus(CSyncCommand& oSyncCmd)
{
	boolean bShowStatus = oSyncCmd.m_bShowStatus;
	m_oSyncEngine.getNotify().enableReporting(bShowStatus);
	//if (bShowStatus)
		//m_statusListener.createStatusPopup(RhoRuby.getMessageText("syncronizing_data"));
}

void CSyncThread::processCommand(IQueueCommand* pCmd)
{
    CSyncCommand& oSyncCmd = *((CSyncCommand*)pCmd);
    switch(oSyncCmd.m_nCmdCode)
    {
    case scNone:
        if ( getPollInterval() )
        {
            checkShowStatus(oSyncCmd);
            m_oSyncEngine.doSyncAllSources();
        }
        break;
    case scSyncAll:
        checkShowStatus(oSyncCmd);
        m_oSyncEngine.doSyncAllSources();
        break;
    case scSyncOne:
        {
			checkShowStatus(oSyncCmd);
            m_oSyncEngine.doSyncSource(CSyncEngine::CSourceID(oSyncCmd.m_nCmdParam,oSyncCmd.m_strCmdParam));
        }
        break;
    case scSearchOne:
        {
			checkShowStatus(oSyncCmd);
            m_oSyncEngine.doSearch( ((CSyncSearchCommand&)oSyncCmd).m_arSources, oSyncCmd.m_strCmdParam,
                ((CSyncSearchCommand&)oSyncCmd).m_strFrom, ((CSyncSearchCommand&)oSyncCmd).m_bSyncChanges,
                oSyncCmd.m_nCmdParam);
        }
        break;
    case scLogin:
    	{
    		CSyncLoginCommand& oLoginCmd = (CSyncLoginCommand&)oSyncCmd;

            checkShowStatus(oSyncCmd);
    		m_oSyncEngine.login(oLoginCmd.m_strName, oLoginCmd.m_strPassword, oLoginCmd.m_strCmdParam );
    	}
        break;
    }
}

void CSyncThread::setPollInterval(int nInterval)
{
    if ( nInterval == 0 )
        m_oSyncEngine.stopSync();

    CThreadQueue::setPollInterval(nInterval);
}

String CSyncThread::CSyncCommand::toString()
{
    switch(m_nCmdCode)
    {
    case scSyncAll:
        return "SyncAll";
    case scSyncOne:
        return "SyncOne";
    case scLogin:
        return "Login";
    case scSearchOne:
        return "Search";
    }

    return "Unknown; Code : " + convertToStringA(m_nCmdCode);
}

};
};

extern "C" {

using namespace rho::sync;
using namespace rho::db;

unsigned long rho_sync_doSyncAllSources(int show_status_popup)
{
    CSyncThread::getInstance()->addQueueCommand(new CSyncThread::CSyncCommand(CSyncThread::scSyncAll,show_status_popup!=0));

    return CSyncThread::getInstance()->getRetValue();
}

unsigned long rho_sync_doSyncSourceByID(int nSrcID)
{
    CSyncThread::getInstance()->addQueueCommand(new CSyncThread::CSyncCommand(CSyncThread::scSyncOne, "", nSrcID, false ) );
    return CSyncThread::getInstance()->getRetValue();
}

unsigned long rho_sync_doSyncSourceByName(const char* szSrcName)
{
    CSyncThread::getInstance()->addQueueCommand(new CSyncThread::CSyncCommand(CSyncThread::scSyncOne, szSrcName, 0, false ) );
    return CSyncThread::getInstance()->getRetValue();
}

#ifndef RHO_NO_RUBY
unsigned long rho_sync_doSyncSource(unsigned long nSrcID,int show_status_popup)
{
    CRhoRubyStringOrInt oSrcID = rho_ruby_getstringorint(nSrcID);
    CSyncThread::getInstance()->addQueueCommand(new CSyncThread::CSyncCommand(CSyncThread::scSyncOne, oSrcID.m_szStr, (int)oSrcID.m_nInt, show_status_popup!=0 ) );

    return CSyncThread::getInstance()->getRetValue();
}
#endif //RHO_NO_RUBY

void rho_sync_stop()
{
	if (CSyncThread::getSyncEngine().isSyncing() )
	{
		CSyncThread::getSyncEngine().stopSyncByUser();
        CSyncThread::getInstance()->stopWait();

        while( CDBAdapter::isAnyInsideTransaction() )
			CSyncThread::getInstance()->sleep(100);
	}
}

extern "C" void
source_iter(const char* szName, void* parSources)
{
    rho::Vector<rho::String>& arSources = *((rho::Vector<rho::String>*)(parSources));
    arSources.addElement(szName);
}

#ifndef RHO_NO_RUBY
unsigned long rho_sync_doSearch(unsigned long ar_sources, const char *from, const char *params, bool sync_changes, int nProgressStep,
    const char* callback, const char* callback_params)
{
    rho_sync_stop();
    if ( callback && *callback )
        CSyncThread::getSyncEngine().getNotify().setSearchNotification( callback, callback_params ? callback_params : "");

    rho::Vector<rho::String> arSources;
    rho_ruby_enum_strary(ar_sources, source_iter, &arSources);

    CSyncThread::getInstance()->addQueueCommand(new CSyncThread::CSyncSearchCommand(from,params,arSources,sync_changes,nProgressStep) );

    return CSyncThread::getInstance()->getRetValue();
}
#endif //RHO_NO_RUBY

void rho_sync_doSyncSourceByUrl(const char* szSrcUrl)
{
    const char* szLastSlash = strrchr(szSrcUrl, '\\');
    if ( !szLastSlash )
        szLastSlash = strrchr(szSrcUrl, '/');

    const char* szQuest = strrchr(szSrcUrl, '?');

    rho::String strName = "";
    if (szQuest && szLastSlash)
        strName = rho::String(szLastSlash+1, szQuest-szLastSlash-1);
    else
        strName = szLastSlash ? szLastSlash + 1 : szSrcUrl;

    //TODO: save query params
    CSyncThread::getInstance()->addQueueCommand(new CSyncThread::CSyncCommand(CSyncThread::scSyncOne, strName, (int)0, false ) );
}

void rho_sync_set_pollinterval(int nInterval)
{
    CSyncThread::getInstance()->setPollInterval(nInterval);
}

void rho_sync_set_syncserver(char* syncserver)
{
    rho_sync_stop();

	CSyncThread::getSyncEngine().setSyncServer(syncserver);

    if ( syncserver && *syncserver )
    {
        CSyncThread::getInstance()->start(CSyncThread::epLow);
        if ( CClientRegister::getInstance() != null )
            CClientRegister::getInstance()->startUp();
    }
    else
    {
        CSyncThread::getInstance()->stop(CSyncThread::SYNC_WAIT_BEFOREKILL_SECONDS);
        if ( CClientRegister::getInstance() != null )
            CClientRegister::getInstance()->stop(CSyncThread::SYNC_WAIT_BEFOREKILL_SECONDS);
    }
}

unsigned long rho_sync_login(const char *name, const char *password, const char* callback)
{
    rho_sync_stop();
    CSyncThread::getInstance()->addQueueCommand(new CSyncThread::CSyncLoginCommand(name, password, callback) );

    return CSyncThread::getInstance()->getRetValue();
}

int rho_sync_logged_in()
{
	CDBAdapter& db = CDBAdapter::getUserDB();
    return CSyncThread::getSyncEngine().isLoggedIn() ? 1 : 0;
}

void rho_sync_logout()
{
    rho_sync_stop();

	CDBAdapter& db = CDBAdapter::getUserDB();
    CSyncThread::getSyncEngine().logout();
}

void rho_sync_set_notification(int source_id, const char *url, char* params)
{
    return CSyncThread::getSyncEngine().getNotify().setSyncNotification(source_id, url, params ? params : "");
}

void rho_sync_clear_notification(int source_id)
{
    return CSyncThread::getSyncEngine().getNotify().clearSyncNotification(source_id);
}

void rho_sync_set_bulk_notification(const char *url, char* params)
{
    return CSyncThread::getSyncEngine().getNotify().setBulkSyncNotification(url, params ? params : "");
}

void rho_sync_clear_bulk_notification()
{
    return CSyncThread::getSyncEngine().getNotify().clearBulkSyncNotification();
}

#ifndef RHO_NO_RUBY
unsigned long rho_sync_get_attrs(const char* szPartition, int nSrcID)
{
    return (VALUE)CDBAdapter::getDB(szPartition).getAttrMgr().getAttrsBySrc(nSrcID);
}

unsigned long rho_sync_is_blob_attr(const char* szPartition, int nSrcID, const char* szAttrName)
{
    return rho_ruby_create_boolean( CDBAdapter::getDB(szPartition).getAttrMgr().isBlobAttr(nSrcID, szAttrName) );
}
#endif //RHO_NO_RUBY

void rho_sync_setobjectnotify_url(const char* szUrl)
{
    CSyncNotify::setObjectNotifyUrl(szUrl);
}

void rho_sync_addobjectnotify(int nSrcID, const char* szObject)
{
    CSyncThread::getSyncEngine().getNotify().addObjectNotify(nSrcID, szObject);
}

void rho_sync_addobjectnotify_bysrcname(const char* szSrcName, const char* szObject)
{
    CSyncThread::getSyncEngine().getNotify().addObjectNotify(szSrcName, szObject);
}

void rho_sync_cleanobjectnotify()
{
    CSyncThread::getSyncEngine().getNotify().cleanObjectNotifications();
}

int rho_sync_get_lastsync_objectcount(int nSrcID)
{
    return CSyncThread::getSyncEngine().getNotify().getLastSyncObjectCount(nSrcID);
}

int rho_sync_get_pagesize()
{
    return CSyncThread::getSyncEngine().getSyncPageSize();
}

void rho_sync_set_pagesize(int nPageSize)
{
    CSyncThread::getSyncEngine().setSyncPageSize(nPageSize);
}

void rho_sync_set_threaded_mode(int b)
{
    CSyncThread::getInstance()->setNonThreadedMode(b==0);
    CSyncThread::getSyncEngine().setNonThreadedMode(b==0);
}

char* rho_sync_create_string(const char* szStr)
{
    return strdup(szStr);
}

void rho_sync_free_string(char* szStr)
{
    return free(szStr);
}

}
<commit_msg>add pollinterval description<commit_after>#include "SyncThread.h"
#include "common/RhoTime.h"
#include "common/RhoConf.h"
#include "common/RhoFilePath.h"

#include "ruby/ext/rho/rhoruby.h"
#include "sync/ClientRegister.h"

namespace rho {
namespace sync {

using namespace rho::common;
using namespace rho::db;

IMPLEMENT_LOGCLASS(CSyncThread,"Sync");
CSyncThread* CSyncThread::m_pInstance = 0;

/*static*/ CSyncThread* CSyncThread::Create(common::IRhoClassFactory* factory)
{
    if ( m_pInstance )
        return m_pInstance;

    m_pInstance = new CSyncThread(factory);
    return m_pInstance;
}

/*static*/void CSyncThread::Destroy()
{
    if ( m_pInstance )
        delete m_pInstance;

    m_pInstance = 0;
}

CSyncThread::CSyncThread(common::IRhoClassFactory* factory) : CThreadQueue(factory)
{
    CThreadQueue::setLogCategory(getLogCategory());

    if( RHOCONF().isExist("sync_poll_interval") )
        setPollInterval(RHOCONF().getInt("sync_poll_interval"));

    m_oSyncEngine.setFactory(factory);

    if ( RHOCONF().getString("syncserver").length() > 0 )
        start(epLow);
}

CSyncThread::~CSyncThread(void)
{
    m_oSyncEngine.exitSync();
    stop(SYNC_WAIT_BEFOREKILL_SECONDS);

    db::CDBAdapter::closeAll();
}

#ifndef RHO_NO_RUBY
unsigned long CSyncThread::getRetValue()
{
    unsigned long ret = rho_ruby_get_NIL();
    if ( isNoThreadedMode()  )
    {
        ret = rho_ruby_create_string( getSyncEngine().getNotify().getNotifyBody().c_str() );
        getSyncEngine().getNotify().cleanNotifyBody();
    }

    return ret;
}
#else
unsigned long CSyncThread::getRetValue()
{
    unsigned long ret = 0;
    if ( isNoThreadedMode()  )
    {
        ret = (unsigned long)rho_sync_create_string( getSyncEngine().getNotify().getNotifyBody().c_str() );
        getSyncEngine().getNotify().cleanNotifyBody();
    }

    return ret;
}
#endif

int CSyncThread::getLastPollInterval()
{
    uint64 nowTime = CLocalTime().toULong();

    DBResult( res, CDBAdapter::getUserDB().executeSQL("SELECT last_updated from sources") );
    uint64 latestTimeUpdated = 0;
    for ( ; !res.isEnd(); res.next() )
    {
        uint64 timeUpdated = res.getUInt64ByIdx(0);
        if ( latestTimeUpdated < timeUpdated )
        	latestTimeUpdated = timeUpdated;
    }

	return latestTimeUpdated > 0 ? (int)(nowTime-latestTimeUpdated) : 0;
}

void CSyncThread::processCommands()//throws Exception
{
    if ( isNoCommands() )
        addQueueCommand(new CSyncCommand(scNone,false));

    CThreadQueue::processCommands();
}

void CSyncThread::checkShowStatus(CSyncCommand& oSyncCmd)
{
	boolean bShowStatus = oSyncCmd.m_bShowStatus;
	m_oSyncEngine.getNotify().enableReporting(bShowStatus);
	//if (bShowStatus)
		//m_statusListener.createStatusPopup(RhoRuby.getMessageText("syncronizing_data"));
}

void CSyncThread::processCommand(IQueueCommand* pCmd)
{
    CSyncCommand& oSyncCmd = *((CSyncCommand*)pCmd);
    switch(oSyncCmd.m_nCmdCode)
    {
    case scNone:
        if ( getPollInterval() )
        {
            checkShowStatus(oSyncCmd);
            m_oSyncEngine.doSyncAllSources();
        }
        break;
    case scSyncAll:
        checkShowStatus(oSyncCmd);
        m_oSyncEngine.doSyncAllSources();
        break;
    case scSyncOne:
        {
			checkShowStatus(oSyncCmd);
            m_oSyncEngine.doSyncSource(CSyncEngine::CSourceID(oSyncCmd.m_nCmdParam,oSyncCmd.m_strCmdParam));
        }
        break;
    case scSearchOne:
        {
			checkShowStatus(oSyncCmd);
            m_oSyncEngine.doSearch( ((CSyncSearchCommand&)oSyncCmd).m_arSources, oSyncCmd.m_strCmdParam,
                ((CSyncSearchCommand&)oSyncCmd).m_strFrom, ((CSyncSearchCommand&)oSyncCmd).m_bSyncChanges,
                oSyncCmd.m_nCmdParam);
        }
        break;
    case scLogin:
    	{
    		CSyncLoginCommand& oLoginCmd = (CSyncLoginCommand&)oSyncCmd;

            checkShowStatus(oSyncCmd);
    		m_oSyncEngine.login(oLoginCmd.m_strName, oLoginCmd.m_strPassword, oLoginCmd.m_strCmdParam );
    	}
        break;
    }
}

void CSyncThread::setPollInterval(int nInterval)
{
    if ( nInterval == 0 )
        m_oSyncEngine.stopSync();

    CThreadQueue::setPollInterval(nInterval);
}

String CSyncThread::CSyncCommand::toString()
{
    switch(m_nCmdCode)
    {
    case scNone:
        return "CheckPollInterval";

    case scSyncAll:
        return "SyncAll";
    case scSyncOne:
        return "SyncOne";
    case scLogin:
        return "Login";
    case scSearchOne:
        return "Search";
    }

    return "Unknown; Code : " + convertToStringA(m_nCmdCode);
}

};
};

extern "C" {

using namespace rho::sync;
using namespace rho::db;

unsigned long rho_sync_doSyncAllSources(int show_status_popup)
{
    CSyncThread::getInstance()->addQueueCommand(new CSyncThread::CSyncCommand(CSyncThread::scSyncAll,show_status_popup!=0));

    return CSyncThread::getInstance()->getRetValue();
}

unsigned long rho_sync_doSyncSourceByID(int nSrcID)
{
    CSyncThread::getInstance()->addQueueCommand(new CSyncThread::CSyncCommand(CSyncThread::scSyncOne, "", nSrcID, false ) );
    return CSyncThread::getInstance()->getRetValue();
}

unsigned long rho_sync_doSyncSourceByName(const char* szSrcName)
{
    CSyncThread::getInstance()->addQueueCommand(new CSyncThread::CSyncCommand(CSyncThread::scSyncOne, szSrcName, 0, false ) );
    return CSyncThread::getInstance()->getRetValue();
}

#ifndef RHO_NO_RUBY
unsigned long rho_sync_doSyncSource(unsigned long nSrcID,int show_status_popup)
{
    CRhoRubyStringOrInt oSrcID = rho_ruby_getstringorint(nSrcID);
    CSyncThread::getInstance()->addQueueCommand(new CSyncThread::CSyncCommand(CSyncThread::scSyncOne, oSrcID.m_szStr, (int)oSrcID.m_nInt, show_status_popup!=0 ) );

    return CSyncThread::getInstance()->getRetValue();
}
#endif //RHO_NO_RUBY

void rho_sync_stop()
{
	if (CSyncThread::getSyncEngine().isSyncing() )
	{
		CSyncThread::getSyncEngine().stopSyncByUser();
        CSyncThread::getInstance()->stopWait();

        while( CDBAdapter::isAnyInsideTransaction() )
			CSyncThread::getInstance()->sleep(100);
	}
}

extern "C" void
source_iter(const char* szName, void* parSources)
{
    rho::Vector<rho::String>& arSources = *((rho::Vector<rho::String>*)(parSources));
    arSources.addElement(szName);
}

#ifndef RHO_NO_RUBY
unsigned long rho_sync_doSearch(unsigned long ar_sources, const char *from, const char *params, bool sync_changes, int nProgressStep,
    const char* callback, const char* callback_params)
{
    rho_sync_stop();
    if ( callback && *callback )
        CSyncThread::getSyncEngine().getNotify().setSearchNotification( callback, callback_params ? callback_params : "");

    rho::Vector<rho::String> arSources;
    rho_ruby_enum_strary(ar_sources, source_iter, &arSources);

    CSyncThread::getInstance()->addQueueCommand(new CSyncThread::CSyncSearchCommand(from,params,arSources,sync_changes,nProgressStep) );

    return CSyncThread::getInstance()->getRetValue();
}
#endif //RHO_NO_RUBY

void rho_sync_doSyncSourceByUrl(const char* szSrcUrl)
{
    const char* szLastSlash = strrchr(szSrcUrl, '\\');
    if ( !szLastSlash )
        szLastSlash = strrchr(szSrcUrl, '/');

    const char* szQuest = strrchr(szSrcUrl, '?');

    rho::String strName = "";
    if (szQuest && szLastSlash)
        strName = rho::String(szLastSlash+1, szQuest-szLastSlash-1);
    else
        strName = szLastSlash ? szLastSlash + 1 : szSrcUrl;

    //TODO: save query params
    CSyncThread::getInstance()->addQueueCommand(new CSyncThread::CSyncCommand(CSyncThread::scSyncOne, strName, (int)0, false ) );
}

void rho_sync_set_pollinterval(int nInterval)
{
    CSyncThread::getInstance()->setPollInterval(nInterval);
}

void rho_sync_set_syncserver(char* syncserver)
{
    rho_sync_stop();

	CSyncThread::getSyncEngine().setSyncServer(syncserver);

    if ( syncserver && *syncserver )
    {
        CSyncThread::getInstance()->start(CSyncThread::epLow);
        if ( CClientRegister::getInstance() != null )
            CClientRegister::getInstance()->startUp();
    }
    else
    {
        CSyncThread::getInstance()->stop(CSyncThread::SYNC_WAIT_BEFOREKILL_SECONDS);
        if ( CClientRegister::getInstance() != null )
            CClientRegister::getInstance()->stop(CSyncThread::SYNC_WAIT_BEFOREKILL_SECONDS);
    }
}

unsigned long rho_sync_login(const char *name, const char *password, const char* callback)
{
    rho_sync_stop();
    CSyncThread::getInstance()->addQueueCommand(new CSyncThread::CSyncLoginCommand(name, password, callback) );

    return CSyncThread::getInstance()->getRetValue();
}

int rho_sync_logged_in()
{
	CDBAdapter& db = CDBAdapter::getUserDB();
    return CSyncThread::getSyncEngine().isLoggedIn() ? 1 : 0;
}

void rho_sync_logout()
{
    rho_sync_stop();

	CDBAdapter& db = CDBAdapter::getUserDB();
    CSyncThread::getSyncEngine().logout();
}

void rho_sync_set_notification(int source_id, const char *url, char* params)
{
    return CSyncThread::getSyncEngine().getNotify().setSyncNotification(source_id, url, params ? params : "");
}

void rho_sync_clear_notification(int source_id)
{
    return CSyncThread::getSyncEngine().getNotify().clearSyncNotification(source_id);
}

void rho_sync_set_bulk_notification(const char *url, char* params)
{
    return CSyncThread::getSyncEngine().getNotify().setBulkSyncNotification(url, params ? params : "");
}

void rho_sync_clear_bulk_notification()
{
    return CSyncThread::getSyncEngine().getNotify().clearBulkSyncNotification();
}

#ifndef RHO_NO_RUBY
unsigned long rho_sync_get_attrs(const char* szPartition, int nSrcID)
{
    return (VALUE)CDBAdapter::getDB(szPartition).getAttrMgr().getAttrsBySrc(nSrcID);
}

unsigned long rho_sync_is_blob_attr(const char* szPartition, int nSrcID, const char* szAttrName)
{
    return rho_ruby_create_boolean( CDBAdapter::getDB(szPartition).getAttrMgr().isBlobAttr(nSrcID, szAttrName) );
}
#endif //RHO_NO_RUBY

void rho_sync_setobjectnotify_url(const char* szUrl)
{
    CSyncNotify::setObjectNotifyUrl(szUrl);
}

void rho_sync_addobjectnotify(int nSrcID, const char* szObject)
{
    CSyncThread::getSyncEngine().getNotify().addObjectNotify(nSrcID, szObject);
}

void rho_sync_addobjectnotify_bysrcname(const char* szSrcName, const char* szObject)
{
    CSyncThread::getSyncEngine().getNotify().addObjectNotify(szSrcName, szObject);
}

void rho_sync_cleanobjectnotify()
{
    CSyncThread::getSyncEngine().getNotify().cleanObjectNotifications();
}

int rho_sync_get_lastsync_objectcount(int nSrcID)
{
    return CSyncThread::getSyncEngine().getNotify().getLastSyncObjectCount(nSrcID);
}

int rho_sync_get_pagesize()
{
    return CSyncThread::getSyncEngine().getSyncPageSize();
}

void rho_sync_set_pagesize(int nPageSize)
{
    CSyncThread::getSyncEngine().setSyncPageSize(nPageSize);
}

void rho_sync_set_threaded_mode(int b)
{
    CSyncThread::getInstance()->setNonThreadedMode(b==0);
    CSyncThread::getSyncEngine().setNonThreadedMode(b==0);
}

char* rho_sync_create_string(const char* szStr)
{
    return strdup(szStr);
}

void rho_sync_free_string(char* szStr)
{
    return free(szStr);
}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: propertyset.hxx,v $
 * $Revision: 1.3 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef OOX_HELPER_PROPERTYSET_HXX
#define OOX_HELPER_PROPERTYSET_HXX

#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/XMultiPropertySet.hpp>

namespace oox {

// ============================================================================

/** A wrapper for a UNO property set.

    This class provides functions to silently get and set properties (without
    exceptions, without the need to check validity of the UNO property set).

    An instance is constructed with the reference to a UNO property set or any
    other interface (the constructor will query for the
    com.sun.star.beans.XPropertySet interface then). The reference to the
    property set will be kept as long as the instance of this class is alive.

    The functions getProperties() and setProperties() try to handle all passed
    values at once, using the com.sun.star.beans.XMultiPropertySet interface.
    If the implementation does not support the XMultiPropertySet interface, all
    properties are handled separately in a loop.
 */
class PropertySet
{
public:
    inline explicit     PropertySet() {}

    /** Constructs a property set wrapper with the passed UNO property set. */
    inline explicit     PropertySet(
                            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& rxPropSet )
                                { set( rxPropSet ); }

    /** Constructs a property set wrapper after querying the XPropertySet interface. */
    template< typename Type >
    inline explicit     PropertySet( const Type& rObject ) { set( rObject ); }

    /** Sets the passed UNO property set and releases the old UNO property set. */
    void                set( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& rxPropSet );

    /** Queries the passed object (interface or any) for an XPropertySet and releases the old UNO property set. */
    template< typename Type >
    inline void         set( const Type& rObject )
                            { set( ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >( rObject, ::com::sun::star::uno::UNO_QUERY ) ); }

    /** Returns true, if the contained XPropertySet interface is valid. */
    inline bool         is() const { return mxPropSet.is(); }

    /** Returns the contained XPropertySet interface. */
    inline ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
                        getXPropertySet() const { return mxPropSet; }

    // Get properties ---------------------------------------------------------

    /** Gets the specified property from the property set.
        @return  true, if the any could be filled with the property value. */
    bool                getAnyProperty(
                            ::com::sun::star::uno::Any& orValue,
                            const ::rtl::OUString& rPropName ) const;

    /** Gets the specified property from the property set.
        @return  true, if the passed variable could be filled with the property value. */
    template< typename Type >
    inline bool         getProperty(
                            Type& orValue,
                            const ::rtl::OUString& rPropName ) const;

    /** Gets the specified boolean property from the property set.
        @return  true = property contains true; false = property contains false or error occured. */
    bool                getBoolProperty( const ::rtl::OUString& rPropName ) const;

    /** Gets the specified properties from the property set. Tries to use the XMultiPropertySet interface.
        @param orValues  (out-parameter) The related property values.
        @param rPropNames  The property names. MUST be ordered alphabetically. */
    void                getProperties(
                            ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& orValues,
                            const ::com::sun::star::uno::Sequence< ::rtl::OUString >& rPropNames ) const;

    // Set properties ---------------------------------------------------------

    /** Puts the passed any into the property set. */
    void                setAnyProperty(
                            const ::rtl::OUString& rPropName,
                            const ::com::sun::star::uno::Any& rValue );

    /** Puts the passed value into the property set. */
    template< typename Type >
    inline void         setProperty(
                            const ::rtl::OUString& rPropName,
                            const Type& rValue );

    /** Puts the passed properties into the property set. Tries to use the XMultiPropertySet interface.
        @param rPropNames  The property names. MUST be ordered alphabetically.
        @param rValues  The related property values. */
    void                setProperties(
                            const ::com::sun::star::uno::Sequence< ::rtl::OUString >& rPropNames,
                            const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& rValues );

    // ------------------------------------------------------------------------
private:
    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
                        mxPropSet;          /// The mandatory property set interface.
    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XMultiPropertySet >
                        mxMultiPropSet;     /// The optional multi property set interface.
};

// ----------------------------------------------------------------------------

template< typename Type >
inline bool PropertySet::getProperty( Type& orValue, const ::rtl::OUString& rPropName ) const
{
    ::com::sun::star::uno::Any aAny;
    return getAnyProperty( aAny, rPropName ) && (aAny >>= orValue);
}

template< typename Type >
inline void PropertySet::setProperty( const ::rtl::OUString& rPropName, const Type& rValue )
{
    setAnyProperty( rPropName, ::com::sun::star::uno::Any( rValue ) );
}

// ============================================================================

} // namespace oox

#endif

<commit_msg>INTEGRATION: CWS xmlfilter04 (1.2.12); FILE MERGED 2008/02/27 14:39:39 dr 1.2.12.1: add setters to Color class, add gamma to a:scrgbClr<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: propertyset.hxx,v $
 * $Revision: 1.4 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef OOX_HELPER_PROPERTYSET_HXX
#define OOX_HELPER_PROPERTYSET_HXX

#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/beans/XMultiPropertySet.hpp>

namespace oox {

class PropertyMap;

// ============================================================================

/** A wrapper for a UNO property set.

    This class provides functions to silently get and set properties (without
    exceptions, without the need to check validity of the UNO property set).

    An instance is constructed with the reference to a UNO property set or any
    other interface (the constructor will query for the
    com.sun.star.beans.XPropertySet interface then). The reference to the
    property set will be kept as long as the instance of this class is alive.

    The functions getProperties() and setProperties() try to handle all passed
    values at once, using the com.sun.star.beans.XMultiPropertySet interface.
    If the implementation does not support the XMultiPropertySet interface, all
    properties are handled separately in a loop.
 */
class PropertySet
{
public:
    inline explicit     PropertySet() {}

    /** Constructs a property set wrapper with the passed UNO property set. */
    inline explicit     PropertySet(
                            const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& rxPropSet )
                                { set( rxPropSet ); }

    /** Constructs a property set wrapper after querying the XPropertySet interface. */
    template< typename Type >
    inline explicit     PropertySet( const Type& rObject ) { set( rObject ); }

    /** Sets the passed UNO property set and releases the old UNO property set. */
    void                set( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& rxPropSet );

    /** Queries the passed object (interface or any) for an XPropertySet and releases the old UNO property set. */
    template< typename Type >
    inline void         set( const Type& rObject )
                            { set( ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >( rObject, ::com::sun::star::uno::UNO_QUERY ) ); }

    /** Returns true, if the contained XPropertySet interface is valid. */
    inline bool         is() const { return mxPropSet.is(); }

    /** Returns the contained XPropertySet interface. */
    inline ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
                        getXPropertySet() const { return mxPropSet; }

    // Get properties ---------------------------------------------------------

    /** Gets the specified property from the property set.
        @return  true, if the any could be filled with the property value. */
    bool                getAnyProperty(
                            ::com::sun::star::uno::Any& orValue,
                            const ::rtl::OUString& rPropName ) const;

    /** Gets the specified property from the property set.
        @return  true, if the passed variable could be filled with the property value. */
    template< typename Type >
    inline bool         getProperty(
                            Type& orValue,
                            const ::rtl::OUString& rPropName ) const;

    /** Gets the specified boolean property from the property set.
        @return  true = property contains true; false = property contains false or error occured. */
    bool                getBoolProperty( const ::rtl::OUString& rPropName ) const;

    /** Gets the specified properties from the property set. Tries to use the XMultiPropertySet interface.
        @param orValues  (out-parameter) The related property values.
        @param rPropNames  The property names. MUST be ordered alphabetically. */
    void                getProperties(
                            ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& orValues,
                            const ::com::sun::star::uno::Sequence< ::rtl::OUString >& rPropNames ) const;

    // Set properties ---------------------------------------------------------

    /** Puts the passed any into the property set. */
    void                setAnyProperty(
                            const ::rtl::OUString& rPropName,
                            const ::com::sun::star::uno::Any& rValue );

    /** Puts the passed value into the property set. */
    template< typename Type >
    inline void         setProperty(
                            const ::rtl::OUString& rPropName,
                            const Type& rValue );

    /** Puts the passed properties into the property set. Tries to use the XMultiPropertySet interface.
        @param rPropNames  The property names. MUST be ordered alphabetically.
        @param rValues  The related property values. */
    void                setProperties(
                            const ::com::sun::star::uno::Sequence< ::rtl::OUString >& rPropNames,
                            const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& rValues );

    /** Puts the passed property map into the property set. Tries to use the XMultiPropertySet interface.
        @param rPropertyMap  The property map. */
    void                setProperties( const PropertyMap& rPropertyMap );

    // ------------------------------------------------------------------------
private:
    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >
                        mxPropSet;          /// The mandatory property set interface.
    ::com::sun::star::uno::Reference< ::com::sun::star::beans::XMultiPropertySet >
                        mxMultiPropSet;     /// The optional multi property set interface.
};

// ----------------------------------------------------------------------------

template< typename Type >
inline bool PropertySet::getProperty( Type& orValue, const ::rtl::OUString& rPropName ) const
{
    ::com::sun::star::uno::Any aAny;
    return getAnyProperty( aAny, rPropName ) && (aAny >>= orValue);
}

template< typename Type >
inline void PropertySet::setProperty( const ::rtl::OUString& rPropName, const Type& rValue )
{
    setAnyProperty( rPropName, ::com::sun::star::uno::Any( rValue ) );
}

// ============================================================================

} // namespace oox

#endif

<|endoftext|>