<commit_before>/// HEADER
#include "dynamic_transform.h"

/// COMPONENT
#include <csapex_transform/transform_message.h>
#include <csapex_transform/time_stamp_message.h>
#include "listener.h"

/// PROJECT
#include <csapex/msg/output.h>
#include <csapex/msg/input.h>
#include <utils_param/parameter_factory.h>
#include <csapex/model/node_modifier.h>
#include <csapex/utility/register_apex_plugin.h>

/// SYSTEM
#include <tf/transform_datatypes.h>

CSAPEX_REGISTER_CLASS(csapex::DynamicTransform, csapex::Node)

using namespace csapex;

DynamicTransform::DynamicTransform()
    : init_(false)
{
}

void DynamicTransform::setupParameters()
{
    std::vector<std::string> topics;
    addParameter(param::ParameterFactory::declareParameterStringSet("from", topics), boost::bind(&DynamicTransform::update, this));
    addParameter(param::ParameterFactory::declareParameterStringSet("to", topics), boost::bind(&DynamicTransform::update, this));

    addParameter(param::ParameterFactory::declareTrigger("refresh"), boost::bind(&DynamicTransform::refresh, this));
    addParameter(param::ParameterFactory::declareTrigger("reset tf"), boost::bind(&DynamicTransform::resetTf, this));

    from_p = boost::dynamic_pointer_cast<param::SetParameter>(getParameter("from"));
    to_p = boost::dynamic_pointer_cast<param::SetParameter>(getParameter("to"));
}

void DynamicTransform::process()
{
    if(!init_) {
        refresh();
    }

    setError(false);
    bool update = false;

    bool use_in_frame = frame_in_from_->hasMessage();
    from_p->setEnabled(!use_in_frame);
    if(use_in_frame) {
        std::string from = frame_in_from_->getMessage<connection_types::GenericValueMessage<std::string> >()->value;

        if(readParameter<std::string>("from") != from) {
            setParameter("from", from);
            update = true;
        }
    }

    bool use_to_frame = frame_in_to_->hasMessage();
    to_p->setEnabled(!use_to_frame);
    if(use_to_frame) {
        std::string to = frame_in_to_->getMessage<connection_types::GenericValueMessage<std::string> >()->value;

        if(readParameter<std::string>("to") != to) {
            setParameter("to", to);
            update = true;
        }
    }

    if(update) {
        refresh();
    }

    if(time_in_->hasMessage()) {
        connection_types::TimeStampMessage::Ptr time_msg = time_in_->getMessage<connection_types::TimeStampMessage>();
        publishTransform(time_msg->value);
    } else {
        publishTransform(ros::Time(0));
    }
}

void DynamicTransform::publishTransform(const ros::Time& time)
{
    if(!init_) {
        refresh();
    }

    tf::StampedTransform t;

    if(getParameter("from")->is<void>()) {
        throw std::runtime_error("from is not a string");
    }
    if(getParameter("to")->is<void>()) {
        throw std::runtime_error("to is not a string");
    }

    std::string to = readParameter<std::string>("to");
    std::string from = readParameter<std::string>("from");

    try {
        LockedListener l = Listener::getLocked();

        if(l.l) {
            l.l->tfl->lookupTransform(to, from, time, t);
            setError(false);
        } else {
            return;
        }
    } catch(const tf2::TransformException& e) {
        setError(true, e.what(), EL_WARNING);
        return;
    }

    connection_types::TransformMessage::Ptr msg(new connection_types::TransformMessage);
    msg->value = t;
    msg->frame_id = from;
    msg->child_frame = to;
    output_->publish(msg);

    connection_types::GenericValueMessage<std::string>::Ptr frame(new connection_types::GenericValueMessage<std::string>);
    frame->value = readParameter<std::string>("to");
    output_frame_->publish(frame);
}

void DynamicTransform::setup()
{
    time_in_ = modifier_->addOptionalInput<connection_types::TimeStampMessage>("Time");
    frame_in_from_ = modifier_->addOptionalInput<connection_types::GenericValueMessage<std::string> >("Origin Frame");
    frame_in_to_ = modifier_->addOptionalInput<connection_types::GenericValueMessage<std::string> >("Target Frame");

    output_ = modifier_->addOutput<connection_types::TransformMessage>("Transform");
    output_frame_ = modifier_->addOutput<connection_types::GenericValueMessage<std::string> >("Target Frame");
}

void DynamicTransform::resetTf()
{
    LockedListener l = Listener::getLocked();
    if(l.l) {
        l.l->reset();
    }
}

void DynamicTransform::refresh()
{
    std::vector<std::string> frames;

    std::string to, from;

    if(getParameter("from")->is<std::string>()) {
        to = to_p->as<std::string>();
    }
    if(getParameter("to")->is<std::string>()) {
        from = from_p->as<std::string>();
    }

    LockedListener l = Listener::getLocked();
    l.l->tfl->waitForTransform(from, to, ros::Time(0), ros::Duration(1.0));
    if(l.l) {
        std::vector<std::string> f;
        l.l->tfl->getFrameStrings(f);

        for(std::size_t i = 0; i < f.size(); ++i) {
            frames.push_back(std::string("/") + f[i]);
        }

    } else {
        return;
    }

    if(std::find(frames.begin(), frames.end(), from) == frames.end()) {
        frames.push_back(from);
    }
    if(std::find(frames.begin(), frames.end(), to) == frames.end()) {
        frames.push_back(to);
    }

    from_p->setSet(frames);
    to_p->setSet(frames);

    init_ = true;
}

void DynamicTransform::update()
{
}
<commit_msg>segfault fixed when no ros connection<commit_after>/// HEADER
#include "dynamic_transform.h"

/// COMPONENT
#include <csapex_transform/transform_message.h>
#include <csapex_transform/time_stamp_message.h>
#include "listener.h"

/// PROJECT
#include <csapex/msg/output.h>
#include <csapex/msg/input.h>
#include <utils_param/parameter_factory.h>
#include <csapex/model/node_modifier.h>
#include <csapex/utility/register_apex_plugin.h>

/// SYSTEM
#include <tf/transform_datatypes.h>

CSAPEX_REGISTER_CLASS(csapex::DynamicTransform, csapex::Node)

using namespace csapex;

DynamicTransform::DynamicTransform()
    : init_(false)
{
}

void DynamicTransform::setupParameters()
{
    std::vector<std::string> topics;
    addParameter(param::ParameterFactory::declareParameterStringSet("from", topics), boost::bind(&DynamicTransform::update, this));
    addParameter(param::ParameterFactory::declareParameterStringSet("to", topics), boost::bind(&DynamicTransform::update, this));

    addParameter(param::ParameterFactory::declareTrigger("refresh"), boost::bind(&DynamicTransform::refresh, this));
    addParameter(param::ParameterFactory::declareTrigger("reset tf"), boost::bind(&DynamicTransform::resetTf, this));

    from_p = boost::dynamic_pointer_cast<param::SetParameter>(getParameter("from"));
    to_p = boost::dynamic_pointer_cast<param::SetParameter>(getParameter("to"));
}

void DynamicTransform::process()
{
    if(!init_) {
        refresh();
    }

    setError(false);
    bool update = false;

    bool use_in_frame = frame_in_from_->hasMessage();
    from_p->setEnabled(!use_in_frame);
    if(use_in_frame) {
        std::string from = frame_in_from_->getMessage<connection_types::GenericValueMessage<std::string> >()->value;

        if(readParameter<std::string>("from") != from) {
            setParameter("from", from);
            update = true;
        }
    }

    bool use_to_frame = frame_in_to_->hasMessage();
    to_p->setEnabled(!use_to_frame);
    if(use_to_frame) {
        std::string to = frame_in_to_->getMessage<connection_types::GenericValueMessage<std::string> >()->value;

        if(readParameter<std::string>("to") != to) {
            setParameter("to", to);
            update = true;
        }
    }

    if(update) {
        refresh();
    }

    if(time_in_->hasMessage()) {
        connection_types::TimeStampMessage::Ptr time_msg = time_in_->getMessage<connection_types::TimeStampMessage>();
        publishTransform(time_msg->value);
    } else {
        publishTransform(ros::Time(0));
    }
}

void DynamicTransform::publishTransform(const ros::Time& time)
{
    if(!init_) {
        refresh();
    }

    tf::StampedTransform t;

    if(getParameter("from")->is<void>()) {
        throw std::runtime_error("from is not a string");
    }
    if(getParameter("to")->is<void>()) {
        throw std::runtime_error("to is not a string");
    }

    std::string to = readParameter<std::string>("to");
    std::string from = readParameter<std::string>("from");

    try {
        LockedListener l = Listener::getLocked();

        if(l.l) {
            l.l->tfl->lookupTransform(to, from, time, t);
            setError(false);
        } else {
            return;
        }
    } catch(const tf2::TransformException& e) {
        setError(true, e.what(), EL_WARNING);
        return;
    }

    connection_types::TransformMessage::Ptr msg(new connection_types::TransformMessage);
    msg->value = t;
    msg->frame_id = from;
    msg->child_frame = to;
    output_->publish(msg);

    connection_types::GenericValueMessage<std::string>::Ptr frame(new connection_types::GenericValueMessage<std::string>);
    frame->value = readParameter<std::string>("to");
    output_frame_->publish(frame);
}

void DynamicTransform::setup()
{
    time_in_ = modifier_->addOptionalInput<connection_types::TimeStampMessage>("Time");
    frame_in_from_ = modifier_->addOptionalInput<connection_types::GenericValueMessage<std::string> >("Origin Frame");
    frame_in_to_ = modifier_->addOptionalInput<connection_types::GenericValueMessage<std::string> >("Target Frame");

    output_ = modifier_->addOutput<connection_types::TransformMessage>("Transform");
    output_frame_ = modifier_->addOutput<connection_types::GenericValueMessage<std::string> >("Target Frame");
}

void DynamicTransform::resetTf()
{
    LockedListener l = Listener::getLocked();
    if(l.l) {
        l.l->reset();
    }
}

void DynamicTransform::refresh()
{
    std::vector<std::string> frames;

    std::string to, from;

    if(getParameter("from")->is<std::string>()) {
        to = to_p->as<std::string>();
    }
    if(getParameter("to")->is<std::string>()) {
        from = from_p->as<std::string>();
    }

    LockedListener l = Listener::getLocked();
    if(!l.l) {
        return;
    }
    l.l->tfl->waitForTransform(from, to, ros::Time(0), ros::Duration(1.0));
    if(l.l) {
        std::vector<std::string> f;
        l.l->tfl->getFrameStrings(f);

        for(std::size_t i = 0; i < f.size(); ++i) {
            frames.push_back(std::string("/") + f[i]);
        }

    } else {
        return;
    }

    if(std::find(frames.begin(), frames.end(), from) == frames.end()) {
        frames.push_back(from);
    }
    if(std::find(frames.begin(), frames.end(), to) == frames.end()) {
        frames.push_back(to);
    }

    from_p->setSet(frames);
    to_p->setSet(frames);

    init_ = true;
}

void DynamicTransform::update()
{
}
<|endoftext|>


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

/* $Id$ */

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//  Base Class for Detector specific Trigger                                 //                                                                           //
//                                                                           //
//                                                                           //
//                                                                           //
//                                                                           //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

#include <Riostream.h>
#include <TNamed.h>
#include <TString.h>
#include <TObjArray.h>
#include <TRandom.h>

#include "AliLog.h"
#include "AliRun.h"
#include "AliRunLoader.h"

#include "AliTriggerInput.h"
#include "AliTriggerDetector.h"

ClassImp( AliTriggerDetector )

//_____________________________________________________________________________
AliTriggerDetector::AliTriggerDetector() :
  TNamed(),
  fMask(0),
  fInputs()
{
   // Default constructor
}

//_____________________________________________________________________________
AliTriggerDetector::AliTriggerDetector(const AliTriggerDetector & de ):
  TNamed(de),
  fMask(de.fMask),
  fInputs(de.fInputs)
{
  // Copy constructor

}

//_____________________________________________________________________________
AliTriggerDetector::~AliTriggerDetector()
{
  // Destructor
  // Delete only inputs that are not
  // associated to the CTP
  Int_t ninputs = fInputs.GetEntriesFast();
  for(Int_t i = 0; i < ninputs; i++) {
    AliTriggerInput *inp = (AliTriggerInput *)fInputs.At(i);
    if (inp->GetSignature() == -1 &&
	inp->GetMask() == 0)
      delete fInputs.RemoveAt(i);
  }
}

//_____________________________________________________________________________
void AliTriggerDetector::CreateInputs(const TObjArray &inputs)
{
   // Define the inputs to the Central Trigger Processor
   // This is a dummy version

   // Check if we have to create the inputs first
   if( fInputs.GetEntriesFast() == 0 ) {
     // Create the inputs that the detector can provide
     CreateInputs();
   }

   TString name = GetName();

   // Pointer to the available inputs provided by the detector
   TObjArray* availInputs = &fInputs;

   Int_t ninputs = inputs.GetEntriesFast();
   for( Int_t j=0; j<ninputs; j++ ) {
     AliTriggerInput *inp = (AliTriggerInput*)inputs.At(j);
     if ( name.CompareTo(inp->GetModule().Data()) ) continue;

     TObject *tempObj = availInputs->FindObject(inp->GetInputName().Data());
     if ( tempObj ) {
       Int_t tempIndex = availInputs->IndexOf(tempObj);
       delete availInputs->Remove(tempObj);
       fInputs.AddAt( inp, tempIndex );
       inp->Enable();
       AliInfo(Form("Trigger input (%s) is found in the CTP configuration. Therefore it is enabled for trigger detector (%s)",
		    inp->GetInputName().Data(),name.Data()));
     }
     else {
       AliWarning(Form("Trigger Input (%s) is not implemented for the trigger detector (%s) ! It will be disabled !",
		       inp->GetInputName().Data(),name.Data()));
     }
   }

   for( Int_t j=0; j<fInputs.GetEntriesFast(); j++ ) {
     AliTriggerInput *inp = (AliTriggerInput *)fInputs.At(j);
     if (inp->GetSignature() == -1 &&
	 inp->GetMask() == 0)
       inp->Enable();
       AliInfo(Form("Trigger input (%s) was not found in the CTP configuration. Therefore it will be run in a stand-alone mode",
		    inp->GetInputName().Data()));
   }

   fInputs.SetOwner(kFALSE);
}

//_____________________________________________________________________________
void AliTriggerDetector::CreateInputs()
{
   // Define the inputs to the Central Trigger Processor
   // This is a dummy version

   // Do not create inputs again!!
   if( fInputs.GetEntriesFast() > 0 ) return;

   fInputs.AddLast( new AliTriggerInput( "TEST1_L0", "TEST", 0 ) );
   fInputs.AddLast( new AliTriggerInput( "TEST2_L0", "TEST", 0 ) );
   fInputs.AddLast( new AliTriggerInput( "TEST3_L0", "TEST", 0 ) );
}

//_____________________________________________________________________________
void AliTriggerDetector::Trigger()
{
   // This is a dummy version set all inputs in a random way

   AliWarning( Form( "Triggering dummy detector %s", GetName() ) );

   //  ********** Get Digits for the current event **********
   AliRunLoader* runLoader = gAlice->GetRunLoader();
   AliInfo( Form( "Event %d", runLoader->GetEventNumber() ) );

   TString loadername = GetName();
   loadername.Append( "Loader" );
   AliLoader * loader = runLoader->GetLoader( loadername.Data() );
   if( loader ) {
      loader->LoadDigits( "READ" );
      TTree* digits = loader->TreeD();
      // Do something with the digits !!!
      if( digits ) {
//         digits->Print();
      }
      loader->UnloadDigits();
   }
   //  ******************************************************

   // set all inputs in a random way
   Int_t nInputs = fInputs.GetEntriesFast();
   for( Int_t j=0; j<nInputs; j++ ) {
      AliTriggerInput* in = (AliTriggerInput*)fInputs.At( j );
      if( gRandom->Rndm() > 0.5 ) {
         in->Set();
         fMask |= in->GetValue();
      }
   }
}

//_____________________________________________________________________________
void AliTriggerDetector::SetInput( TString& name )
{
   // Set Input by name
   SetInput( name.Data() );
}

//_____________________________________________________________________________
void AliTriggerDetector::SetInput( const char * name )
{
   // Set Input by name
   AliTriggerInput* in = ((AliTriggerInput*)fInputs.FindObject( name ));
   if( in ) {
      in->Set();
      fMask |= in->GetValue();
   } else
      AliError( Form( "There is not input named %s", name ) );
}

//_____________________________________________________________________________
void AliTriggerDetector::Print( const Option_t* opt ) const
{
   // Print
   cout << "Trigger Detector : " << GetName() << endl;
   cout << "  Trigger Class Mask: 0x" << hex << GetMask() << dec << endl;
   Int_t nInputs = fInputs.GetEntriesFast();
   for( Int_t j=0; j<nInputs; j++ ) {
      AliTriggerInput* in = (AliTriggerInput*)fInputs.At( j );
      in->Print( opt );
   }
}
<commit_msg>Bug fix. Missing {} that was causing a false information message that the trigger input will be running in a stand-alone mode. Thanks to Philippe for noticing the problem<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/* $Id$ */

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//  Base Class for Detector specific Trigger                                 //                                                                           //
//                                                                           //
//                                                                           //
//                                                                           //
//                                                                           //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

#include <Riostream.h>
#include <TNamed.h>
#include <TString.h>
#include <TObjArray.h>
#include <TRandom.h>

#include "AliLog.h"
#include "AliRun.h"
#include "AliRunLoader.h"

#include "AliTriggerInput.h"
#include "AliTriggerDetector.h"

ClassImp( AliTriggerDetector )

//_____________________________________________________________________________
AliTriggerDetector::AliTriggerDetector() :
  TNamed(),
  fMask(0),
  fInputs()
{
   // Default constructor
}

//_____________________________________________________________________________
AliTriggerDetector::AliTriggerDetector(const AliTriggerDetector & de ):
  TNamed(de),
  fMask(de.fMask),
  fInputs(de.fInputs)
{
  // Copy constructor

}

//_____________________________________________________________________________
AliTriggerDetector::~AliTriggerDetector()
{
  // Destructor
  // Delete only inputs that are not
  // associated to the CTP
  Int_t ninputs = fInputs.GetEntriesFast();
  for(Int_t i = 0; i < ninputs; i++) {
    AliTriggerInput *inp = (AliTriggerInput *)fInputs.At(i);
    if (inp->GetSignature() == -1 &&
	inp->GetMask() == 0)
      delete fInputs.RemoveAt(i);
  }
}

//_____________________________________________________________________________
void AliTriggerDetector::CreateInputs(const TObjArray &inputs)
{
   // Define the inputs to the Central Trigger Processor
   // This is a dummy version

   // Check if we have to create the inputs first
   if( fInputs.GetEntriesFast() == 0 ) {
     // Create the inputs that the detector can provide
     CreateInputs();
   }

   TString name = GetName();

   // Pointer to the available inputs provided by the detector
   TObjArray* availInputs = &fInputs;

   Int_t ninputs = inputs.GetEntriesFast();
   for( Int_t j=0; j<ninputs; j++ ) {
     AliTriggerInput *inp = (AliTriggerInput*)inputs.At(j);
     if ( name.CompareTo(inp->GetModule().Data()) ) continue;

     TObject *tempObj = availInputs->FindObject(inp->GetInputName().Data());
     if ( tempObj ) {
       Int_t tempIndex = availInputs->IndexOf(tempObj);
       delete availInputs->Remove(tempObj);
       fInputs.AddAt( inp, tempIndex );
       inp->Enable();
       AliInfo(Form("Trigger input (%s) is found in the CTP configuration. Therefore it is enabled for trigger detector (%s)",
		    inp->GetInputName().Data(),name.Data()));
     }
     else {
       AliWarning(Form("Trigger Input (%s) is not implemented for the trigger detector (%s) ! It will be disabled !",
		       inp->GetInputName().Data(),name.Data()));
     }
   }

   for( Int_t j=0; j<fInputs.GetEntriesFast(); j++ ) {
     AliTriggerInput *inp = (AliTriggerInput *)fInputs.At(j);
     if (inp->GetSignature() == -1 &&
	 inp->GetMask() == 0) {
       inp->Enable();
       AliInfo(Form("Trigger input (%s) was not found in the CTP configuration. Therefore it will be run in a stand-alone mode",
		    inp->GetInputName().Data()));
     }
   }

   fInputs.SetOwner(kFALSE);
}

//_____________________________________________________________________________
void AliTriggerDetector::CreateInputs()
{
   // Define the inputs to the Central Trigger Processor
   // This is a dummy version

   // Do not create inputs again!!
   if( fInputs.GetEntriesFast() > 0 ) return;

   fInputs.AddLast( new AliTriggerInput( "TEST1_L0", "TEST", 0 ) );
   fInputs.AddLast( new AliTriggerInput( "TEST2_L0", "TEST", 0 ) );
   fInputs.AddLast( new AliTriggerInput( "TEST3_L0", "TEST", 0 ) );
}

//_____________________________________________________________________________
void AliTriggerDetector::Trigger()
{
   // This is a dummy version set all inputs in a random way

   AliWarning( Form( "Triggering dummy detector %s", GetName() ) );

   //  ********** Get Digits for the current event **********
   AliRunLoader* runLoader = gAlice->GetRunLoader();
   AliInfo( Form( "Event %d", runLoader->GetEventNumber() ) );

   TString loadername = GetName();
   loadername.Append( "Loader" );
   AliLoader * loader = runLoader->GetLoader( loadername.Data() );
   if( loader ) {
      loader->LoadDigits( "READ" );
      TTree* digits = loader->TreeD();
      // Do something with the digits !!!
      if( digits ) {
//         digits->Print();
      }
      loader->UnloadDigits();
   }
   //  ******************************************************

   // set all inputs in a random way
   Int_t nInputs = fInputs.GetEntriesFast();
   for( Int_t j=0; j<nInputs; j++ ) {
      AliTriggerInput* in = (AliTriggerInput*)fInputs.At( j );
      if( gRandom->Rndm() > 0.5 ) {
         in->Set();
         fMask |= in->GetValue();
      }
   }
}

//_____________________________________________________________________________
void AliTriggerDetector::SetInput( TString& name )
{
   // Set Input by name
   SetInput( name.Data() );
}

//_____________________________________________________________________________
void AliTriggerDetector::SetInput( const char * name )
{
   // Set Input by name
   AliTriggerInput* in = ((AliTriggerInput*)fInputs.FindObject( name ));
   if( in ) {
      in->Set();
      fMask |= in->GetValue();
   } else
      AliError( Form( "There is not input named %s", name ) );
}

//_____________________________________________________________________________
void AliTriggerDetector::Print( const Option_t* opt ) const
{
   // Print
   cout << "Trigger Detector : " << GetName() << endl;
   cout << "  Trigger Class Mask: 0x" << hex << GetMask() << dec << endl;
   Int_t nInputs = fInputs.GetEntriesFast();
   for( Int_t j=0; j<nInputs; j++ ) {
      AliTriggerInput* in = (AliTriggerInput*)fInputs.At( j );
      in->Print( opt );
   }
}
<|endoftext|>


<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "paddle/fluid/framework/data_layout_transform.h"
#include "paddle/fluid/framework/feed_fetch_type.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/platform/device_context.h"
#include "paddle/fluid/platform/profiler.h"

namespace paddle {
namespace operators {

// FIXME(yuyang18): Should we assume the fetch operator always generate
// CPU outputs?
static void DataCopy(const framework::LoDTensor &src_item,
                     const std::string &fetch_var_name,
                     framework::LoDTensor *dst_item) {
  if (src_item.IsInitialized() && src_item.numel() > 0) {
#ifdef PADDLE_WITH_MKLDNN
    // Conversion from MKL-DNN to Paddle
    if (src_item.layout() == framework::DataLayout::kMKLDNN) {
      framework::Tensor out;
      // Convert to desired Paddle layout, apart from grads of filter
      // as params are not a subject to paddle's data_format
      framework::innerTransDataLayoutFromMKLDNN(
          src_item.layout(), fetch_var_name == framework::GradVarName("Filter")
                                 ? framework::DataLayout::kNCHW
                                 : paddle::platform::MKLDNNDeviceContext::tls()
                                       .get_cur_paddle_data_layout(),
          src_item, &out, platform::CPUPlace());
      TensorCopySync(out, platform::CPUPlace(), dst_item);
    } else {
      TensorCopySync(src_item, platform::CPUPlace(), dst_item);
    }
#else
#ifdef PADDLE_WITH_ASCEND_CL
    if (platform::is_npu_place(src_item.place())) {
      platform::DeviceContextPool::Instance().Get(src_item.place())->Wait();
    }
#endif
    TensorCopySync(src_item, platform::CPUPlace(), dst_item);
#endif
  } else {
    // Not copy, if the src tensor is empty.
    dst_item->clear();
    dst_item->Resize({0});
  }
  dst_item->set_lod(src_item.lod());
}

class FetchOp : public framework::OperatorBase {
 public:
  FetchOp(const std::string &type, const framework::VariableNameMap &inputs,
          const framework::VariableNameMap &outputs,
          const framework::AttributeMap &attrs)
      : OperatorBase(type, inputs, outputs, attrs) {}

 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &place) const override {
    OP_INOUT_CHECK(HasInputs("X"), "Input", "X", "Fetch");
    OP_INOUT_CHECK(HasOutputs("Out"), "Output", "Out", "Fetch");

    auto fetch_var_name = Input("X");
    auto *fetch_var = scope.FindVar(fetch_var_name);
    PADDLE_ENFORCE_NOT_NULL(
        fetch_var,
        platform::errors::NotFound(
            "Input variable(%s) cannot be found in scope for operator 'Fetch'."
            "Confirm that you have used the fetch `Variable` format "
            "instead of the string literal('%s') in `fetch_list` "
            "parameter when using `executor.run` method. In other "
            "words, the format of "
            "`executor.run(fetch_list=[fetch_var])`(fetch_var is a "
            "Variable) is recommended.",
            fetch_var_name, fetch_var_name));

    auto out_name = Output("Out");
    auto *out_var = scope.FindVar(out_name);
    PADDLE_ENFORCE_NOT_NULL(out_var, platform::errors::NotFound(
                                         "Output variable(%s) cannot be found "
                                         "in scope for operator 'Fetch'.",
                                         out_name));

    int col = Attr<int>("col");
    PADDLE_ENFORCE_GE(
        col, 0, platform::errors::InvalidArgument(
                    "Expected the column index (the attribute 'col' of "
                    "operator 'Fetch') of current fetching variable to be "
                    "no less than 0. But received column index = %d.",
                    col));

    VLOG(3) << "Fetch variable " << fetch_var_name << " to variable "
            << out_name << "'s " << col << " column.";

    auto *fetch_list = out_var->GetMutable<framework::FetchList>();

    if (static_cast<size_t>(col) >= fetch_list->size()) {
      fetch_list->resize(col + 1);
    }

    if (fetch_var->IsType<framework::LoDTensor>()) {
      auto &src_item = fetch_var->Get<framework::LoDTensor>();
      auto *dst_item = &(BOOST_GET(framework::LoDTensor, fetch_list->at(col)));
      DataCopy(src_item, fetch_var_name, dst_item);
    } else {
      auto &src_item = fetch_var->Get<framework::LoDTensorArray>();
      framework::LoDTensorArray tmp(src_item.size());
      fetch_list->at(col) = tmp;
      auto &dst_item =
          BOOST_GET(framework::LoDTensorArray, fetch_list->at(col));
      for (size_t i = 0; i < src_item.size(); ++i) {
        DataCopy(src_item[i], fetch_var_name, &dst_item[i]);
      }
    }
  }
};

class FetchOpInfoMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
             "(LoDTensor) The resulted LoDTensor which is expected to return "
             "to users.");
    AddOutput("Out",
              "(vector<LoDTensor>) A fetching list of LoDTensor which may have "
              "different dimension, shape and data type.");
    AddAttr<int>("col", "(int) The column index of fetching object.");
    AddComment(R"DOC(
Fetch Operator.

It should not be configured by users directly.

)DOC");
  }
};
}  // namespace operators
}  // namespace paddle

REGISTER_OPERATOR(
    fetch, paddle::operators::FetchOp,
    paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
    paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>,
    paddle::operators::FetchOpInfoMaker);
<commit_msg>[NPU] remove duplicated stream sync in fetch op (#33819)<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#include "paddle/fluid/framework/data_layout_transform.h"
#include "paddle/fluid/framework/feed_fetch_type.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/platform/device_context.h"
#include "paddle/fluid/platform/profiler.h"

namespace paddle {
namespace operators {

// FIXME(yuyang18): Should we assume the fetch operator always generate
// CPU outputs?
static void DataCopy(const framework::LoDTensor &src_item,
                     const std::string &fetch_var_name,
                     framework::LoDTensor *dst_item) {
  if (src_item.IsInitialized() && src_item.numel() > 0) {
#ifdef PADDLE_WITH_MKLDNN
    // Conversion from MKL-DNN to Paddle
    if (src_item.layout() == framework::DataLayout::kMKLDNN) {
      framework::Tensor out;
      // Convert to desired Paddle layout, apart from grads of filter
      // as params are not a subject to paddle's data_format
      framework::innerTransDataLayoutFromMKLDNN(
          src_item.layout(), fetch_var_name == framework::GradVarName("Filter")
                                 ? framework::DataLayout::kNCHW
                                 : paddle::platform::MKLDNNDeviceContext::tls()
                                       .get_cur_paddle_data_layout(),
          src_item, &out, platform::CPUPlace());
      TensorCopySync(out, platform::CPUPlace(), dst_item);
    } else {
      TensorCopySync(src_item, platform::CPUPlace(), dst_item);
    }
#else
    TensorCopySync(src_item, platform::CPUPlace(), dst_item);
#endif
  } else {
    // Not copy, if the src tensor is empty.
    dst_item->clear();
    dst_item->Resize({0});
  }
  dst_item->set_lod(src_item.lod());
}

class FetchOp : public framework::OperatorBase {
 public:
  FetchOp(const std::string &type, const framework::VariableNameMap &inputs,
          const framework::VariableNameMap &outputs,
          const framework::AttributeMap &attrs)
      : OperatorBase(type, inputs, outputs, attrs) {}

 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &place) const override {
    OP_INOUT_CHECK(HasInputs("X"), "Input", "X", "Fetch");
    OP_INOUT_CHECK(HasOutputs("Out"), "Output", "Out", "Fetch");

    auto fetch_var_name = Input("X");
    auto *fetch_var = scope.FindVar(fetch_var_name);
    PADDLE_ENFORCE_NOT_NULL(
        fetch_var,
        platform::errors::NotFound(
            "Input variable(%s) cannot be found in scope for operator 'Fetch'."
            "Confirm that you have used the fetch `Variable` format "
            "instead of the string literal('%s') in `fetch_list` "
            "parameter when using `executor.run` method. In other "
            "words, the format of "
            "`executor.run(fetch_list=[fetch_var])`(fetch_var is a "
            "Variable) is recommended.",
            fetch_var_name, fetch_var_name));

    auto out_name = Output("Out");
    auto *out_var = scope.FindVar(out_name);
    PADDLE_ENFORCE_NOT_NULL(out_var, platform::errors::NotFound(
                                         "Output variable(%s) cannot be found "
                                         "in scope for operator 'Fetch'.",
                                         out_name));

    int col = Attr<int>("col");
    PADDLE_ENFORCE_GE(
        col, 0, platform::errors::InvalidArgument(
                    "Expected the column index (the attribute 'col' of "
                    "operator 'Fetch') of current fetching variable to be "
                    "no less than 0. But received column index = %d.",
                    col));

    VLOG(3) << "Fetch variable " << fetch_var_name << " to variable "
            << out_name << "'s " << col << " column.";

    auto *fetch_list = out_var->GetMutable<framework::FetchList>();

    if (static_cast<size_t>(col) >= fetch_list->size()) {
      fetch_list->resize(col + 1);
    }

    if (fetch_var->IsType<framework::LoDTensor>()) {
      auto &src_item = fetch_var->Get<framework::LoDTensor>();
      auto *dst_item = &(BOOST_GET(framework::LoDTensor, fetch_list->at(col)));
      DataCopy(src_item, fetch_var_name, dst_item);
    } else {
      auto &src_item = fetch_var->Get<framework::LoDTensorArray>();
      framework::LoDTensorArray tmp(src_item.size());
      fetch_list->at(col) = tmp;
      auto &dst_item =
          BOOST_GET(framework::LoDTensorArray, fetch_list->at(col));
      for (size_t i = 0; i < src_item.size(); ++i) {
        DataCopy(src_item[i], fetch_var_name, &dst_item[i]);
      }
    }
  }
};

class FetchOpInfoMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput("X",
             "(LoDTensor) The resulted LoDTensor which is expected to return "
             "to users.");
    AddOutput("Out",
              "(vector<LoDTensor>) A fetching list of LoDTensor which may have "
              "different dimension, shape and data type.");
    AddAttr<int>("col", "(int) The column index of fetching object.");
    AddComment(R"DOC(
Fetch Operator.

It should not be configured by users directly.

)DOC");
  }
};
}  // namespace operators
}  // namespace paddle

REGISTER_OPERATOR(
    fetch, paddle::operators::FetchOp,
    paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>,
    paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>,
    paddle::operators::FetchOpInfoMaker);
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: htmlfile.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-23 09:05:00 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <precomp.h>
#include <toolkit/htmlfile.hxx>

// NOT FULLY DECLARED SERVICES
#include <cosv/file.hxx>
#include <udm/html/htmlitem.hxx>

using namespace csi;
using csi::xml::AnAttribute;

DocuFile_Html::DocuFile_Html()
    :   sFilePath(),
        sTitle(),
        sLocation(),
        sStyle(),
        sCssFile(),
        sCopyright(),
        aBodyData()
{
}

void
DocuFile_Html::SetLocation( const csv::ploc::Path & i_rFilePath )
{
    StreamLock sPath(1000);
    i_rFilePath.Get( sPath() );

    sFilePath = sPath().c_str();
}

void
DocuFile_Html::SetTitle( const char * i_sTitle )
{
    sTitle = i_sTitle;
}

void
DocuFile_Html::SetInlineStyle( const char * i_sStyle )
{
    sStyle = i_sStyle;
}

void
DocuFile_Html::SetRelativeCssPath( const char * i_sCssFile_relativePath )
{
    sCssFile = i_sCssFile_relativePath;
}

void
DocuFile_Html::SetCopyright( const char * i_sCopyright )
{
    sCopyright = i_sCopyright;
}

void
DocuFile_Html::EmptyBody()
{
    aBodyData.SetContent(0);
    aBodyData
        >> *new html::Label( "_top_" )
        << " ";
}

bool
DocuFile_Html::CreateFile()
{
    csv::File aFile(sFilePath, csv::CFM_CREATE);
    if (NOT aFile.open())
    {
        Cerr() << "Can't create file " << sFilePath << "." << Endl();
        return false;
    }

    WriteHeader(aFile);
    WriteBody(aFile);

    // Write end
    static const char sCompletion[] = "\n\n";
    aFile.write( sCompletion );

    aFile.close();
    Cout() << '.' << Flush();
    return true;
}

void
DocuFile_Html::WriteHeader( csv::File & io_aFile )
{
    static const char s1[] =
        "\n\n<title>";
    static const char s2[] =
        "</title>\n"
        "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n";

    io_aFile.write( s1 );
    io_aFile.write( sTitle );
    io_aFile.write( s2 );

    if (NOT sCssFile.empty())
    {
        static const char s3[] =
            "<link rel=\"stylesheet\" type=\"text/css\" href=\"";
        static const char s4[] =
            "\">\n";

        io_aFile.write(s3);
        io_aFile.write(sCssFile);
        io_aFile.write(s4);
    }

    if (NOT sStyle.empty())
    {
        static const char s5[] =
            "\n";

        io_aFile.write(s5);
        io_aFile.write(sStyle);
        io_aFile.write(s6);
    }

    static const char s7[] =
        "\n";
    io_aFile.write(s7);
}

void
DocuFile_Html::WriteBody( csv::File & io_aFile )
{
    aBodyData
        >> *new html::Link( "#_top_" )
                << "Top of Page";

    if ( sCopyright.length() > 0 )
    {
        aBodyData
            << new xml::XmlCode("
");

        aBodyData
            >> *new html::Paragraph
                    << new html::ClassAttr( "copyright" )
                    << new xml::AnAttribute( "align", "center" )
                    << new xml::XmlCode(sCopyright);
    }
    aBodyData.WriteOut(io_aFile);
}

<commit_msg>INTEGRATION: CWS adc12p (1.3.6); FILE MERGED 2005/07/27 11:21:25 np 1.3.6.1: #i52495#<commit_after>/*************************************************************************
 *
 *  $RCSfile: htmlfile.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2005-08-05 14:26:23 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <precomp.h>
#include <toolkit/htmlfile.hxx>

// NOT FULLY DECLARED SERVICES
#include <cosv/file.hxx>
#include <udm/html/htmlitem.hxx>

using namespace csi;
using csi::xml::AnAttribute;

DocuFile_Html::DocuFile_Html()
    :   sFilePath(),
        sTitle(),
        sLocation(),
        sStyle(),
        sCssFile(),
        sCopyright(),
        aBodyData(),
        aBuffer(60000) // Grows dynamically, when necessary.
{
}

void
DocuFile_Html::SetLocation( const csv::ploc::Path & i_rFilePath )
{
    StreamLock sPath(1000);
    i_rFilePath.Get( sPath() );

    sFilePath = sPath().c_str();
}

void
DocuFile_Html::SetTitle( const char * i_sTitle )
{
    sTitle = i_sTitle;
}

void
DocuFile_Html::SetInlineStyle( const char * i_sStyle )
{
    sStyle = i_sStyle;
}

void
DocuFile_Html::SetRelativeCssPath( const char * i_sCssFile_relativePath )
{
    sCssFile = i_sCssFile_relativePath;
}

void
DocuFile_Html::SetCopyright( const char * i_sCopyright )
{
    sCopyright = i_sCopyright;
}

void
DocuFile_Html::EmptyBody()
{
    aBodyData.SetContent(0);
    aBodyData
        >> *new html::Label( "_top_" )
        << " ";
}

bool
DocuFile_Html::CreateFile()
{
    csv::File aFile(sFilePath, csv::CFM_CREATE);
    if (NOT aFile.open())
    {
        Cerr() << "Can't create file " << sFilePath << "." << Endl();
        return false;
    }

    WriteHeader(aFile);
    WriteBody(aFile);

    // Write end
    static const char sCompletion[] = "\n\n";
    aFile.write( sCompletion );

    aFile.close();
    Cout() << '.' << Flush();
    return true;
}

void
DocuFile_Html::WriteHeader( csv::File & io_aFile )
{
    aBuffer.reset();

    static const char s1[] =
        "\n\n<title>";
    static const char s2[] =
        "</title>\n"
        "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n";

    aBuffer.write( s1 );
    aBuffer.write( sTitle );
    aBuffer.write( s2 );

    if (NOT sCssFile.empty())
    {
        static const char s3[] =
            "<link rel=\"stylesheet\" type=\"text/css\" href=\"";
        static const char s4[] =
            "\">\n";

        aBuffer.write(s3);
        aBuffer.write(sCssFile);
        aBuffer.write(s4);
    }

    if (NOT sStyle.empty())
    {
        static const char s5[] =
            "\n";

        aBuffer.write(s5);
        aBuffer.write(sStyle);
        aBuffer.write(s6);
    }

    static const char s7[] =
        "\n";
    aBuffer.write(s7);

    io_aFile.write(aBuffer.c_str(), aBuffer.size());
}

void
DocuFile_Html::WriteBody( csv::File & io_aFile )
{
    aBuffer.reset();

    aBodyData
        >> *new html::Link( "#_top_" )
                << "Top of Page";

    if ( sCopyright.length() > 0 )
    {
        aBodyData
            << new xml::XmlCode("
");

        aBodyData
            >> *new html::Paragraph
                    << new html::ClassAttr( "copyright" )
                    << new xml::AnAttribute( "align", "center" )
                    << new xml::XmlCode(sCopyright);
    }
    aBodyData.WriteOut(aBuffer);

    io_aFile.write(aBuffer.c_str(), aBuffer.size());
}

<|endoftext|>


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

#define _WIN32_WINDOWS 0x0410
#ifdef _MSC_VER
#pragma warning(push, 1) /* disable warnings within system headers */
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msiquery.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include <malloc.h>

#ifdef UNICODE
#define _UNICODE
#define _tstring    wstring
#else
#define _tstring    string
#endif
#include <tchar.h>
#include <string>

#include <io.h>

static std::_tstring GetMsiProperty( MSIHANDLE handle, const std::_tstring& sProperty )
{
    std::_tstring   result;
    TCHAR   szDummy[1] = TEXT("");
    DWORD   nChars = 0;

    if ( MsiGetProperty( handle, sProperty.c_str(), szDummy, &nChars ) == ERROR_MORE_DATA )
    {
        DWORD nBytes = ++nChars * sizeof(TCHAR);
        LPTSTR buffer = reinterpret_cast<LPTSTR>(_alloca(nBytes));
        ZeroMemory( buffer, nBytes );
        MsiGetProperty(handle, sProperty.c_str(), buffer, &nChars);
        result = buffer;
    }

    return  result;
}

static BOOL ExecuteCommand( LPCTSTR lpCommand, BOOL bSync )
{
    BOOL                fSuccess = FALSE;
    STARTUPINFO         si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);

    fSuccess = CreateProcess(
        NULL,
        (LPTSTR)lpCommand,
        NULL,
        NULL,
        FALSE,
        0,
        NULL,
        NULL,
        &si,
        &pi
        );

    if ( fSuccess )
    {
        if ( bSync )
            WaitForSingleObject( pi.hProcess, INFINITE );

        CloseHandle( pi.hProcess );
        CloseHandle( pi.hThread );
    }

    return fSuccess;
}

extern "C" UINT __stdcall ExecutePostUninstallScript( MSIHANDLE handle )
{
    TCHAR   szValue[8192];
    DWORD   nValueSize = sizeof(szValue);
    HKEY    hKey;
    std::_tstring   sInstDir;

    std::_tstring   sProductKey = GetMsiProperty( handle, TEXT("FINDPRODUCT") );

    // MessageBox( NULL, sProductKey.c_str(), "Titel", MB_OK );

    if ( ERROR_SUCCESS == RegOpenKey( HKEY_CURRENT_USER,  sProductKey.c_str(), &hKey ) )
    {
        if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("OFFICEINSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
        {
            sInstDir = szValue;
        }
        RegCloseKey( hKey );
    }
    else if ( ERROR_SUCCESS == RegOpenKey( HKEY_LOCAL_MACHINE,  sProductKey.c_str(), &hKey ) )
    {
        if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("OFFICEINSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
        {
            sInstDir = szValue;
        }
        RegCloseKey( hKey );
    }
    else
        return ERROR_SUCCESS;

    std::_tstring   sInfFile = sInstDir + TEXT("program\\postuninstall.inf");
    std::_tstring   sCommand = _T("RUNDLL32.EXE ");

    // MessageBox( NULL, sInfFile.c_str(), "Titel", MB_OK );

    if ( (LONG)GetVersion() < 0 )
        sCommand += _T("setupx.dll");
    else
        sCommand += _T("setupapi.dll");

    sCommand += _T(",InstallHinfSection PostUninstall 132 ");
    sCommand += sInfFile;

    if ( 0 == _taccess( sInfFile.c_str(), 2 ) )
        ExecuteCommand( sCommand.c_str(), TRUE );

    DeleteFile( sInfFile.c_str() );

    return ERROR_SUCCESS;
}

<commit_msg>INTEGRATION: CWS changefileheader (1.8.4); FILE MERGED 2008/03/31 16:08:01 rt 1.8.4.1: #i87441# Change license header to LPGL v3.<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: postuninstall.cxx,v $
 * $Revision: 1.9 $
 *
 * 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.
 *
 ************************************************************************/

#define _WIN32_WINDOWS 0x0410
#ifdef _MSC_VER
#pragma warning(push, 1) /* disable warnings within system headers */
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <msiquery.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif

#include <malloc.h>

#ifdef UNICODE
#define _UNICODE
#define _tstring    wstring
#else
#define _tstring    string
#endif
#include <tchar.h>
#include <string>

#include <io.h>

static std::_tstring GetMsiProperty( MSIHANDLE handle, const std::_tstring& sProperty )
{
    std::_tstring   result;
    TCHAR   szDummy[1] = TEXT("");
    DWORD   nChars = 0;

    if ( MsiGetProperty( handle, sProperty.c_str(), szDummy, &nChars ) == ERROR_MORE_DATA )
    {
        DWORD nBytes = ++nChars * sizeof(TCHAR);
        LPTSTR buffer = reinterpret_cast<LPTSTR>(_alloca(nBytes));
        ZeroMemory( buffer, nBytes );
        MsiGetProperty(handle, sProperty.c_str(), buffer, &nChars);
        result = buffer;
    }

    return  result;
}

static BOOL ExecuteCommand( LPCTSTR lpCommand, BOOL bSync )
{
    BOOL                fSuccess = FALSE;
    STARTUPINFO         si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);

    fSuccess = CreateProcess(
        NULL,
        (LPTSTR)lpCommand,
        NULL,
        NULL,
        FALSE,
        0,
        NULL,
        NULL,
        &si,
        &pi
        );

    if ( fSuccess )
    {
        if ( bSync )
            WaitForSingleObject( pi.hProcess, INFINITE );

        CloseHandle( pi.hProcess );
        CloseHandle( pi.hThread );
    }

    return fSuccess;
}

extern "C" UINT __stdcall ExecutePostUninstallScript( MSIHANDLE handle )
{
    TCHAR   szValue[8192];
    DWORD   nValueSize = sizeof(szValue);
    HKEY    hKey;
    std::_tstring   sInstDir;

    std::_tstring   sProductKey = GetMsiProperty( handle, TEXT("FINDPRODUCT") );

    // MessageBox( NULL, sProductKey.c_str(), "Titel", MB_OK );

    if ( ERROR_SUCCESS == RegOpenKey( HKEY_CURRENT_USER,  sProductKey.c_str(), &hKey ) )
    {
        if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("OFFICEINSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
        {
            sInstDir = szValue;
        }
        RegCloseKey( hKey );
    }
    else if ( ERROR_SUCCESS == RegOpenKey( HKEY_LOCAL_MACHINE,  sProductKey.c_str(), &hKey ) )
    {
        if ( ERROR_SUCCESS == RegQueryValueEx( hKey, TEXT("OFFICEINSTALLLOCATION"), NULL, NULL, (LPBYTE)szValue, &nValueSize ) )
        {
            sInstDir = szValue;
        }
        RegCloseKey( hKey );
    }
    else
        return ERROR_SUCCESS;

    std::_tstring   sInfFile = sInstDir + TEXT("program\\postuninstall.inf");
    std::_tstring   sCommand = _T("RUNDLL32.EXE ");

    // MessageBox( NULL, sInfFile.c_str(), "Titel", MB_OK );

    if ( (LONG)GetVersion() < 0 )
        sCommand += _T("setupx.dll");
    else
        sCommand += _T("setupapi.dll");

    sCommand += _T(",InstallHinfSection PostUninstall 132 ");
    sCommand += sInfFile;

    if ( 0 == _taccess( sInfFile.c_str(), 2 ) )
        ExecuteCommand( sCommand.c_str(), TRUE );

    DeleteFile( sInfFile.c_str() );

    return ERROR_SUCCESS;
}

<|endoftext|>


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

#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <mapnik/raster_colorizer.hpp>

using mapnik::raster_colorizer;
using mapnik::raster_colorizer_ptr;
using mapnik::color_band;
using mapnik::color_bands;

namespace {
   void append_band1(raster_colorizer_ptr & rc, color_band b)
   {
      rc->append_band(b);
   }
   void append_band2(raster_colorizer_ptr & rc, color_band b, unsigned m)
   {
      rc->append_band(b, m);
   }
   void append_band3(raster_colorizer_ptr & rc, float v, color c)
   {
      rc->append_band(v, c);
   }
   void append_band4(raster_colorizer_ptr & rc, float v, color c, unsigned m)
   {
      rc->append_band(v, c, m);
   }
   color_bands const& get_color_bands(raster_colorizer_ptr & rc)
   {
      return rc->get_color_bands();
   }
}

void export_raster_colorizer()
{
    using namespace boost::python;

    class_<raster_colorizer,raster_colorizer_ptr>("RasterColorizer", init<>("Deafult ctor."))

    .add_property("bands",make_function
                  (get_color_bands,
                  return_value_policy<reference_existing_object>()))
    .def("append_band", append_band1, "TODO: Write docs")
    .def("append_band", append_band2, "TODO: Write docs")
    .def("append_band", append_band3, "TODO: Write docs")
    .def("append_band", append_band4, "TODO: Write docs")
    .def("get_color", &raster_colorizer::get_color, "TODO: Write docs")
	;

    class_<color_bands>("ColorBands",init<>("Default ctor."))
    	.def(vector_indexing_suite<color_bands>())
    	;

    class_<color_band>("ColorBand",
                       init<float,color const&>("Deafult ctor."))
    .add_property("color", make_function
                  (&color_band::get_color,
                   return_value_policy<reference_existing_object>()))
    .add_property("value", &color_band::get_value)
    .def(self == self)
    .def("__str__",&color_band::to_string)
    ;
}
<commit_msg>+ add using mapnik::color<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2010 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id$

#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <mapnik/raster_colorizer.hpp>

using mapnik::raster_colorizer;
using mapnik::raster_colorizer_ptr;
using mapnik::color_band;
using mapnik::color_bands;
using mapnik::color;

namespace {
   void append_band1(raster_colorizer_ptr & rc, color_band b)
   {
      rc->append_band(b);
   }
   void append_band2(raster_colorizer_ptr & rc, color_band b, unsigned m)
   {
      rc->append_band(b, m);
   }
   void append_band3(raster_colorizer_ptr & rc, float v, color c)
   {
      rc->append_band(v, c);
   }
   void append_band4(raster_colorizer_ptr & rc, float v, color c, unsigned m)
   {
      rc->append_band(v, c, m);
   }
   color_bands const& get_color_bands(raster_colorizer_ptr & rc)
   {
      return rc->get_color_bands();
   }
}

void export_raster_colorizer()
{
    using namespace boost::python;

    class_<raster_colorizer,raster_colorizer_ptr>("RasterColorizer", init<>("Deafult ctor."))

    .add_property("bands",make_function
                  (get_color_bands,
                  return_value_policy<reference_existing_object>()))
    .def("append_band", append_band1, "TODO: Write docs")
    .def("append_band", append_band2, "TODO: Write docs")
    .def("append_band", append_band3, "TODO: Write docs")
    .def("append_band", append_band4, "TODO: Write docs")
    .def("get_color", &raster_colorizer::get_color, "TODO: Write docs")
	;

    class_<color_bands>("ColorBands",init<>("Default ctor."))
    	.def(vector_indexing_suite<color_bands>())
    	;

    class_<color_band>("ColorBand",
                       init<float,color const&>("Deafult ctor."))
    .add_property("color", make_function
                  (&color_band::get_color,
                   return_value_policy<reference_existing_object>()))
    .add_property("value", &color_band::get_value)
    .def(self == self)
    .def("__str__",&color_band::to_string)
    ;
}
<|endoftext|>


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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#ifndef _CONNECTIVITY_JAVA_LANG_CLASS_HXX_
#include "java/lang/Class.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

using namespace connectivity;
//**************************************************************
//************ Class: java.lang.Class
//**************************************************************

jclass java_lang_Class::theClass = 0;

java_lang_Class::~java_lang_Class()
{}

jclass java_lang_Class::getMyClass()
{
    // die Klasse muss nur einmal geholt werden, daher statisch
    if( !theClass ){
        SDBThreadAttach t;
        if( !t.pEnv ) return (jclass)NULL;
        jclass tempClass = t.pEnv->FindClass("java/lang/Class"); OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!");
        jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
        t.pEnv->DeleteLocalRef( tempClass );
        saveClassRef( globClass );
    }
    return theClass;
}

void java_lang_Class::saveClassRef( jclass pClass )
{
    if( pClass==NULL  )
        return;
    // der uebergebe Klassen-Handle ist schon global, daher einfach speichern
    theClass = pClass;
}

java_lang_Class * java_lang_Class::forName( const ::rtl::OUString& _par0 )
{
    jobject out(NULL);
    SDBThreadAttach t;
    if( t.pEnv )
    {
        ::rtl::OString sClassName = ::rtl::OUStringToOString(_par0, RTL_TEXTENCODING_JAVA_UTF8);
        sClassName = sClassName.replace('.','/');
        out = t.pEnv->FindClass(sClassName);
        ThrowSQLException(t.pEnv,0);
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    return out==0 ? NULL : new java_lang_Class( t.pEnv, out );
}

sal_Bool java_lang_Class::isAssignableFrom( java_lang_Class * _par0 )
{
    jboolean out(0);
    SDBThreadAttach t;
    if( t.pEnv ){

        // temporaere Variable initialisieren
        static const char * cSignature = "(Ljava/lang/Class;)Z";
        static const char * cMethodName = "isAssignableFrom";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID ){
            jvalue args[1];
            // Parameter konvertieren
            args[0].l = _par0 != NULL ? ((java_lang_Object *)_par0)->getJavaObject() : NULL;
            out = t.pEnv->CallBooleanMethod( object, mID, args[0].l );
            ThrowSQLException(t.pEnv,0);
            // und aufraeumen
        } //mID
    } //t.pEnv
    return out;
}

java_lang_Object * java_lang_Class::newInstance()
{
    jobject out(NULL);
    SDBThreadAttach t;
    if( t.pEnv ){
        // temporaere Variable initialisieren
        static const char * cSignature = "()Ljava/lang/Object;";
        static const char * cMethodName = "newInstance";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID ){
            out = t.pEnv->CallObjectMethod( object, mID);
            ThrowSQLException(t.pEnv,0);
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    return out==0 ? NULL : new java_lang_Object( t.pEnv, out );
}

jobject java_lang_Class::newInstanceObject()
{
    jobject out(NULL);
    SDBThreadAttach t;
    if( t.pEnv )
    {
        // temporaere Variable initialisieren
        static const char * cSignature = "()Ljava/lang/Object;";
        static const char * cMethodName = "newInstance";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID ){
            out = t.pEnv->CallObjectMethod( object, mID);
            ThrowSQLException(t.pEnv,0);
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    return out;
}

::rtl::OUString java_lang_Class::getName()
{
    SDBThreadAttach t;
    ::rtl::OUString aStr;
    if( t.pEnv ){
        // temporaere Variable initialisieren
        static const char * cSignature = "()Ljava/lang/String;";
        static const char * cMethodName = "getName";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID ){
            jstring out = (jstring)t.pEnv->CallObjectMethod( object, mID);
            ThrowSQLException(t.pEnv,0);
            aStr = JavaString2String(t.pEnv, (jstring)out );
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    return aStr;
}

<commit_msg>INTEGRATION: CWS changefileheader (1.13.216); FILE MERGED 2008/04/01 15:08:50 thb 1.13.216.3: #i85898# Stripping all external header guards 2008/04/01 10:53:04 thb 1.13.216.2: #i85898# Stripping all external header guards 2008/03/28 15:23:41 rt 1.13.216.1: #i87441# Change license header to LPGL v3.<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: Class.cxx,v $
 * $Revision: 1.14 $
 *
 * 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.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_connectivity.hxx"
#include "java/lang/Class.hxx"
#include "java/tools.hxx"
#include <rtl/ustring.hxx>

using namespace connectivity;
//**************************************************************
//************ Class: java.lang.Class
//**************************************************************

jclass java_lang_Class::theClass = 0;

java_lang_Class::~java_lang_Class()
{}

jclass java_lang_Class::getMyClass()
{
    // die Klasse muss nur einmal geholt werden, daher statisch
    if( !theClass ){
        SDBThreadAttach t;
        if( !t.pEnv ) return (jclass)NULL;
        jclass tempClass = t.pEnv->FindClass("java/lang/Class"); OSL_ENSURE(tempClass,"Java : FindClass nicht erfolgreich!");
        jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
        t.pEnv->DeleteLocalRef( tempClass );
        saveClassRef( globClass );
    }
    return theClass;
}

void java_lang_Class::saveClassRef( jclass pClass )
{
    if( pClass==NULL  )
        return;
    // der uebergebe Klassen-Handle ist schon global, daher einfach speichern
    theClass = pClass;
}

java_lang_Class * java_lang_Class::forName( const ::rtl::OUString& _par0 )
{
    jobject out(NULL);
    SDBThreadAttach t;
    if( t.pEnv )
    {
        ::rtl::OString sClassName = ::rtl::OUStringToOString(_par0, RTL_TEXTENCODING_JAVA_UTF8);
        sClassName = sClassName.replace('.','/');
        out = t.pEnv->FindClass(sClassName);
        ThrowSQLException(t.pEnv,0);
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    return out==0 ? NULL : new java_lang_Class( t.pEnv, out );
}

sal_Bool java_lang_Class::isAssignableFrom( java_lang_Class * _par0 )
{
    jboolean out(0);
    SDBThreadAttach t;
    if( t.pEnv ){

        // temporaere Variable initialisieren
        static const char * cSignature = "(Ljava/lang/Class;)Z";
        static const char * cMethodName = "isAssignableFrom";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID ){
            jvalue args[1];
            // Parameter konvertieren
            args[0].l = _par0 != NULL ? ((java_lang_Object *)_par0)->getJavaObject() : NULL;
            out = t.pEnv->CallBooleanMethod( object, mID, args[0].l );
            ThrowSQLException(t.pEnv,0);
            // und aufraeumen
        } //mID
    } //t.pEnv
    return out;
}

java_lang_Object * java_lang_Class::newInstance()
{
    jobject out(NULL);
    SDBThreadAttach t;
    if( t.pEnv ){
        // temporaere Variable initialisieren
        static const char * cSignature = "()Ljava/lang/Object;";
        static const char * cMethodName = "newInstance";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID ){
            out = t.pEnv->CallObjectMethod( object, mID);
            ThrowSQLException(t.pEnv,0);
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    return out==0 ? NULL : new java_lang_Object( t.pEnv, out );
}

jobject java_lang_Class::newInstanceObject()
{
    jobject out(NULL);
    SDBThreadAttach t;
    if( t.pEnv )
    {
        // temporaere Variable initialisieren
        static const char * cSignature = "()Ljava/lang/Object;";
        static const char * cMethodName = "newInstance";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID ){
            out = t.pEnv->CallObjectMethod( object, mID);
            ThrowSQLException(t.pEnv,0);
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    return out;
}

::rtl::OUString java_lang_Class::getName()
{
    SDBThreadAttach t;
    ::rtl::OUString aStr;
    if( t.pEnv ){
        // temporaere Variable initialisieren
        static const char * cSignature = "()Ljava/lang/String;";
        static const char * cMethodName = "getName";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );OSL_ENSURE(mID,"Unknown method id!");
        if( mID ){
            jstring out = (jstring)t.pEnv->CallObjectMethod( object, mID);
            ThrowSQLException(t.pEnv,0);
            aStr = JavaString2String(t.pEnv, (jstring)out );
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    return aStr;
}

<|endoftext|>


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

#include <cassert>

#include "boost/format.hpp"

#include "IECoreGL/ToGLMeshConverter.h"
#include "IECoreGL/MeshPrimitive.h"

#include "IECore/MeshPrimitive.h"
#include "IECore/TriangulateOp.h"
#include "IECore/MeshNormalsOp.h"
#include "IECore/DespatchTypedData.h"
#include "IECore/MessageHandler.h"

using namespace IECoreGL;

class ToGLMeshConverter::ToFaceVaryingConverter
{
	public:

		typedef IECore::DataPtr ReturnType;

		ToFaceVaryingConverter( IECore::ConstIntVectorDataPtr vertIds ) : m_vertIds( vertIds )
		{
			assert( m_vertIds );
		}

		template<typename T>
		IECore::DataPtr operator()( typename T::Ptr inData )
		{
			assert( inData );

			const typename T::Ptr outData = new T();
			outData->writable().resize( m_vertIds->readable().size() );

			typename T::ValueType::iterator outIt = outData->writable().begin();

			for ( typename T::ValueType::size_type i = 0; i <  m_vertIds->readable().size(); i++ )
			{
				*outIt++ = inData->readable()[ m_vertIds->readable()[ i ] ];
			}

			return outData;
		}

		IECore::ConstIntVectorDataPtr m_vertIds;
};

ToGLMeshConverter::ToGLMeshConverter( IECore::ConstMeshPrimitivePtr toConvert )
	:	ToGLConverter( staticTypeName(), "Converts IECore::MeshPrimitive objects to IECoreGL::MeshPrimitive objects.", IECore::MeshPrimitiveTypeId )
{
	srcParameter()->setValue( boost::const_pointer_cast<IECore::MeshPrimitive>( toConvert ) );
}

ToGLMeshConverter::~ToGLMeshConverter()
{
}

IECore::RunTimeTypedPtr ToGLMeshConverter::doConversion( IECore::ConstObjectPtr src, IECore::ConstCompoundObjectPtr operands ) const
{
	IECore::MeshPrimitivePtr mesh = boost::static_pointer_cast<IECore::MeshPrimitive>( src->copy() ); // safe because the parameter validated it for us

	IECore::TriangulateOpPtr op = new IECore::TriangulateOp();
	op->inputParameter()->setValue( mesh );
	op->throwExceptionsParameter()->setTypedValue( false ); // it's better to see something than nothing

	mesh = IECore::runTimeCast< IECore::MeshPrimitive > ( op->operate() );
	assert( mesh );

	IECore::ConstV3fVectorDataPtr p = 0;
	IECore::PrimitiveVariableMap::const_iterator pIt = mesh->variables.find( "P" );
	if( pIt!=mesh->variables.end() )
	{
		if( pIt->second.interpolation==IECore::PrimitiveVariable::Vertex )
		{
			p = IECore::runTimeCast<const IECore::V3fVectorData>( pIt->second.data );
		}
	}
	if( !p )
	{
		throw IECore::Exception( "Must specify primitive variable \"P\", of type V3fVectorData and interpolation type Vertex." );
	}

	IECore::ConstV3fVectorDataPtr n = 0;
	IECore::PrimitiveVariableMap::const_iterator nIt = mesh->variables.find( "N" );
	if( nIt != mesh->variables.end() )
	{
		if( nIt->second.interpolation==IECore::PrimitiveVariable::Vertex || nIt->second.interpolation==IECore::PrimitiveVariable::Varying || nIt->second.interpolation==IECore::PrimitiveVariable::FaceVarying )
		{
			n = IECore::runTimeCast<const IECore::V3fVectorData>( nIt->second.data );
		}
		if( !n )
		{
			throw IECore::Exception( "Must specify primitive variable \"N\", of type V3fVectorData" );
		}
	}
	else
	{
		IECore::MeshNormalsOpPtr normOp = new IECore::MeshNormalsOp();
		normOp->inputParameter()->setValue( mesh );

		mesh = IECore::runTimeCast< IECore::MeshPrimitive > ( normOp->operate() );
		assert( mesh );

		nIt = mesh->variables.find( "N" );
		assert( nIt != mesh->variables.end() );
		n = IECore::runTimeCast<const IECore::V3fVectorData>( nIt->second.data );
	}
	assert( n );

	MeshPrimitivePtr glMesh = new MeshPrimitive( mesh->vertexIds(), p );

	ToFaceVaryingConverter primVarConverter( mesh->vertexIds() );

	for ( IECore::PrimitiveVariableMap::iterator pIt = mesh->variables.begin(); pIt != mesh->variables.end(); ++pIt )
	{
		if ( pIt->second.data )
		{
			if ( pIt->second.interpolation==IECore::PrimitiveVariable::Vertex || pIt->second.interpolation==IECore::PrimitiveVariable::Varying )
			{
				IECore::DataPtr newData = IECore::despatchTypedData< ToFaceVaryingConverter, IECore::TypeTraits::IsVectorTypedData >( pIt->second.data, primVarConverter );
				pIt->second.interpolation = IECore::PrimitiveVariable::FaceVarying;
				glMesh->addVertexAttribute( pIt->first, newData );
			}
			else if ( pIt->second.interpolation==IECore::PrimitiveVariable::FaceVarying )
			{
				glMesh->addVertexAttribute( pIt->first, pIt->second.data );
			}
		}
		else
		{
			IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", boost::format( "No data given for primvar \"%s\"" ) % pIt->first );
		}
	}

	IECore::PrimitiveVariableMap::const_iterator sIt = mesh->variables.find( "s" );
	IECore::PrimitiveVariableMap::const_iterator tIt = mesh->variables.find( "t" );
	if ( sIt != mesh->variables.end() && tIt != mesh->variables.end() )
	{
		if ( sIt->second.interpolation == IECore::PrimitiveVariable::FaceVarying
			&&  tIt->second.interpolation == IECore::PrimitiveVariable::FaceVarying )
		{
			IECore::ConstFloatVectorDataPtr s = IECore::runTimeCast< const IECore::FloatVectorData >( sIt->second.data );
			IECore::ConstFloatVectorDataPtr t = IECore::runTimeCast< const IECore::FloatVectorData >( tIt->second.data );

			if ( s && t )
			{
				/// Should hold true if primvarsAreValid
				assert( s->readable().size() == t->readable().size() );

				IECore::V2fVectorDataPtr stData = new IECore::V2fVectorData();
				stData->writable().resize( s->readable().size() );

				for ( unsigned i = 0; i < s->readable().size(); i++ )
				{
					stData->writable()[i] = Imath::V2f( s->readable()[i], t->readable()[i] );
				}

				glMesh->addVertexAttribute( "st", stData );
			}
			else
			{
				IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", "If specified, primitive variables \"s\" and \"t\" must be of type FloatVectorData and interpolation type FaceVarying." );
			}
		}
		else
		{
			IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", "If specified, primitive variables \"s\" and \"t\" must be of type FloatVectorData and interpolation type FaceVarying." );
		}
	}
	else if ( sIt != mesh->variables.end() || tIt != mesh->variables.end() )
	{
		IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", "Primitive variable \"s\" or \"t\" found, but not both." );
	}

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

#include <cassert>

#include "boost/format.hpp"

#include "IECoreGL/ToGLMeshConverter.h"
#include "IECoreGL/MeshPrimitive.h"

#include "IECore/MeshPrimitive.h"
#include "IECore/TriangulateOp.h"
#include "IECore/MeshNormalsOp.h"
#include "IECore/DespatchTypedData.h"
#include "IECore/MessageHandler.h"

using namespace IECoreGL;

/// \todo This should be in a standalone Op, and should cope with more than just Vertex interpolated input.
class ToGLMeshConverter::ToFaceVaryingConverter
{
	public:

		typedef IECore::DataPtr ReturnType;

		ToFaceVaryingConverter( IECore::ConstIntVectorDataPtr vertIds ) : m_vertIds( vertIds )
		{
			assert( m_vertIds );
		}

		template<typename T>
		IECore::DataPtr operator()( typename T::Ptr inData )
		{
			assert( inData );

			const typename T::Ptr outData = new T();
			outData->writable().resize( m_vertIds->readable().size() );

			typename T::ValueType::iterator outIt = outData->writable().begin();

			for ( typename T::ValueType::size_type i = 0; i <  m_vertIds->readable().size(); i++ )
			{
				*outIt++ = inData->readable()[ m_vertIds->readable()[ i ] ];
			}

			return outData;
		}

		IECore::ConstIntVectorDataPtr m_vertIds;
};

ToGLMeshConverter::ToGLMeshConverter( IECore::ConstMeshPrimitivePtr toConvert )
	:	ToGLConverter( staticTypeName(), "Converts IECore::MeshPrimitive objects to IECoreGL::MeshPrimitive objects.", IECore::MeshPrimitiveTypeId )
{
	srcParameter()->setValue( boost::const_pointer_cast<IECore::MeshPrimitive>( toConvert ) );
}

ToGLMeshConverter::~ToGLMeshConverter()
{
}

IECore::RunTimeTypedPtr ToGLMeshConverter::doConversion( IECore::ConstObjectPtr src, IECore::ConstCompoundObjectPtr operands ) const
{
	IECore::MeshPrimitivePtr mesh = boost::static_pointer_cast<IECore::MeshPrimitive>( src->copy() ); // safe because the parameter validated it for us

	IECore::TriangulateOpPtr op = new IECore::TriangulateOp();
	op->inputParameter()->setValue( mesh );
	op->throwExceptionsParameter()->setTypedValue( false ); // it's better to see something than nothing

	mesh = IECore::runTimeCast< IECore::MeshPrimitive > ( op->operate() );
	assert( mesh );

	IECore::ConstV3fVectorDataPtr p = 0;
	IECore::PrimitiveVariableMap::const_iterator pIt = mesh->variables.find( "P" );
	if( pIt!=mesh->variables.end() )
	{
		if( pIt->second.interpolation==IECore::PrimitiveVariable::Vertex )
		{
			p = IECore::runTimeCast<const IECore::V3fVectorData>( pIt->second.data );
		}
	}
	if( !p )
	{
		throw IECore::Exception( "Must specify primitive variable \"P\", of type V3fVectorData and interpolation type Vertex." );
	}

	IECore::ConstV3fVectorDataPtr n = 0;
	IECore::PrimitiveVariableMap::const_iterator nIt = mesh->variables.find( "N" );
	if( nIt != mesh->variables.end() )
	{
		if( nIt->second.interpolation==IECore::PrimitiveVariable::Vertex || nIt->second.interpolation==IECore::PrimitiveVariable::Varying || nIt->second.interpolation==IECore::PrimitiveVariable::FaceVarying )
		{
			n = IECore::runTimeCast<const IECore::V3fVectorData>( nIt->second.data );
		}
		if( !n )
		{
			throw IECore::Exception( "Must specify primitive variable \"N\", of type V3fVectorData" );
		}
	}
	else
	{
		IECore::MeshNormalsOpPtr normOp = new IECore::MeshNormalsOp();
		normOp->inputParameter()->setValue( mesh );

		mesh = IECore::runTimeCast< IECore::MeshPrimitive > ( normOp->operate() );
		assert( mesh );

		nIt = mesh->variables.find( "N" );
		assert( nIt != mesh->variables.end() );
		n = IECore::runTimeCast<const IECore::V3fVectorData>( nIt->second.data );
	}
	assert( n );

	MeshPrimitivePtr glMesh = new MeshPrimitive( mesh->vertexIds(), p );

	ToFaceVaryingConverter primVarConverter( mesh->vertexIds() );

	for ( IECore::PrimitiveVariableMap::iterator pIt = mesh->variables.begin(); pIt != mesh->variables.end(); ++pIt )
	{
		if ( pIt->second.data )
		{
			if ( pIt->second.interpolation==IECore::PrimitiveVariable::Vertex || pIt->second.interpolation==IECore::PrimitiveVariable::Varying )
			{
				// convert to facevarying
				IECore::DataPtr newData = IECore::despatchTypedData< ToFaceVaryingConverter, IECore::TypeTraits::IsVectorTypedData >( pIt->second.data, primVarConverter );
				glMesh->addVertexAttribute( pIt->first, newData );
				// modify the primvar we converted in case it is "s" or "t", then we don't have to do another conversion below.
				pIt->second.interpolation = IECore::PrimitiveVariable::FaceVarying;
				pIt->second.data = newData;
			}
			else if ( pIt->second.interpolation==IECore::PrimitiveVariable::FaceVarying )
			{
				glMesh->addVertexAttribute( pIt->first, pIt->second.data );
			}
		}
		else
		{
			IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", boost::format( "No data given for primvar \"%s\"" ) % pIt->first );
		}
	}

	IECore::PrimitiveVariableMap::const_iterator sIt = mesh->variables.find( "s" );
	IECore::PrimitiveVariableMap::const_iterator tIt = mesh->variables.find( "t" );
	if ( sIt != mesh->variables.end() && tIt != mesh->variables.end() )
	{
		if ( sIt->second.interpolation == IECore::PrimitiveVariable::FaceVarying
			&&  tIt->second.interpolation == IECore::PrimitiveVariable::FaceVarying )
		{
			IECore::ConstFloatVectorDataPtr s = IECore::runTimeCast< const IECore::FloatVectorData >( sIt->second.data );
			IECore::ConstFloatVectorDataPtr t = IECore::runTimeCast< const IECore::FloatVectorData >( tIt->second.data );

			if ( s && t )
			{
				/// Should hold true if primvarsAreValid
				assert( s->readable().size() == t->readable().size() );

				IECore::V2fVectorDataPtr stData = new IECore::V2fVectorData();
				stData->writable().resize( s->readable().size() );

				for ( unsigned i = 0; i < s->readable().size(); i++ )
				{
					stData->writable()[i] = Imath::V2f( s->readable()[i], t->readable()[i] );
				}

				glMesh->addVertexAttribute( "st", stData );
			}
			else
			{
				IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", "If specified, primitive variables \"s\" and \"t\" must be of type FloatVectorData and interpolation type FaceVarying." );
			}
		}
		else
		{
			IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", "If specified, primitive variables \"s\" and \"t\" must be of type FloatVectorData and interpolation type FaceVarying." );
		}
	}
	else if ( sIt != mesh->variables.end() || tIt != mesh->variables.end() )
	{
		IECore::msg( IECore::Msg::Warning, "ToGLMeshConverter", "Primitive variable \"s\" or \"t\" found, but not both." );
	}

	return glMesh;
}
<|endoftext|>