<commit_before>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * 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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbDEMConvertAdapter.h"

#include "itkImageIOFactory.h"

namespace otb
{
namespace Wrapper
{

class DEMConvert : public Application
{
public:
  /** Standard class typedefs. */
  typedef DEMConvert                    Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(DEMConvert, otb::Application);

private:
  void DoInit() override
  {
    SetName("DEMConvert");
    SetDescription("Converts a geo-referenced DEM image into a general raster file compatible with OTB DEM handling.");

    SetDocName("DEM Conversion");
    SetDocLongDescription("In order to be understood by the Orfeo ToolBox and the underlying OSSIM library, a geo-referenced Digital Elevation Model image can be converted into a general raster image, which consists in 3 files with the following extensions: .ras, .geom and .omd. Once converted, you have to place these files in a separate directory, and you can then use this directory to set the \"DEM Directory\" parameter of a DEM based OTB application or filter.");
    SetDocLimitations("None");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(" ");

    AddDocTag(Tags::Manip);

    AddParameter(ParameterType_InputImage,  "in",  "Input geo-referenced DEM");
    SetParameterDescription("in", "Input geo-referenced DEM to convert to general raster format.");

    AddParameter(ParameterType_OutputFilename,    "out", "Prefix of the output files");
    std::ostringstream oss;
    oss << "will be used to get the prefix (name withtout extensions) of the files to write. ";
    oss << "Three files - prefix.geom, prefix.omd and prefix.ras - will be generated.";
    SetParameterDescription("out", oss.str());
    //MandatoryOn("out");

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "QB_Toulouse_Ortho_Elev.tif");
    SetDocExampleParameterValue("out", "outputDEM");

    SetOfficialDocLink();
}

void DoUpdateParameters() override
{
  // nothing to update
}

/* The main is simple : read image using OTB and write it as a tif.
*  Read this tif using OSSIM and convert it as a general raster file
*  (.ras, .geom and . omd)
*/

void DoExecute() override
{
  // Load input image
  FloatVectorImageType::Pointer inImage = GetParameterImage("in");

  // Set temporary tif filename (for ossim)
  std::string ofname = GetParameterString("out");
  std::string path   = itksys::SystemTools::GetFilenamePath(ofname);
  std::string fname  = itksys::SystemTools::GetFilenameWithoutExtension(ofname);
  std::string tempFilename = path+"/"+fname+"_DEMConvert.tif";
  std::string tempFilenameGeom = path+"/"+fname+"_DEMConvert.geom";

  // Generate the tif image using OTB while keeping the same  pixel
  // type then the input image
  // Initialize an outputParameter and set its output pixeltype
  OutputImageParameter::Pointer paramOut = OutputImageParameter::New();
  std::ostringstream osswriter;
  osswriter<< "writing temporary tif file";

  // Set the filename of the current output image
  paramOut->SetFileName(tempFilename);
  paramOut->SetValue(inImage);

  // Set the output pixel type
  ImageIOBase::Pointer  imageIO = ImageIOFactory::CreateImageIO( GetParameterString("in").c_str(),
                                                                      ImageIOFactory::ReadMode);
  std::string componentTypeInfo(imageIO->GetComponentTypeInfo().name());
  if( componentTypeInfo == typeid(unsigned char).name())
    {
    paramOut->SetPixelType(ImagePixelType_uint8);
    }
  else if( componentTypeInfo == typeid(unsigned short).name())
    {
    paramOut->SetPixelType(ImagePixelType_uint16);
    }
  else if( componentTypeInfo == typeid(short).name())
    {
    paramOut->SetPixelType(ImagePixelType_int16);
    }
  else if( componentTypeInfo == typeid(unsigned int).name())
    {
    paramOut->SetPixelType(ImagePixelType_uint32);
    }
  else if( componentTypeInfo == typeid(int).name())
    {
    paramOut->SetPixelType(ImagePixelType_int32);
    }
  else if( componentTypeInfo == typeid(float).name())
    {
    paramOut->SetPixelType(ImagePixelType_float);
    }
  else if( componentTypeInfo == typeid(double).name())
    {
    paramOut->SetPixelType(ImagePixelType_double);
    }
  else
    {
    itkExceptionMacro("This application doesn't support image pixel type " << componentTypeInfo);
    }

  // Add the tempfilename to be written
  paramOut->InitializeWriters();
  AddProcess(paramOut->GetWriter(), osswriter.str());
  paramOut->Write();

  // Set the output ras file
  std::string output = path+"/"+fname+".ras";

  DEMConvertAdapter::Pointer DEMConverter = DEMConvertAdapter::New();
  DEMConverter->Convert(tempFilename, output);

  // remove the temprorary tif file
  if( !itksys::SystemTools::RemoveFile(tempFilename) )
    {
    itkExceptionMacro("Problem while removing the file " << tempFilename);
    }

  // remove the geom file if any
  if( itksys::SystemTools::FileExists(tempFilenameGeom)
      && !itksys::SystemTools::RemoveFile(tempFilenameGeom))
    {
    itkExceptionMacro("Problem while removing the Geom file " << tempFilenameGeom);
    }
  }

};

} // namespace otb
}
OTB_APPLICATION_EXPORT(otb::Wrapper::DEMConvert)

<commit_msg>BUG: allow DEMConvert to work with extended filename<commit_after>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * 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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbDEMConvertAdapter.h"

#include "itkImageIOFactory.h"

namespace otb
{
namespace Wrapper
{

class DEMConvert : public Application
{
public:
  /** Standard class typedefs. */
  typedef DEMConvert                    Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(DEMConvert, otb::Application);

private:
  void DoInit() override
  {
    SetName("DEMConvert");
    SetDescription("Converts a geo-referenced DEM image into a general raster file compatible with OTB DEM handling.");

    SetDocName("DEM Conversion");
    SetDocLongDescription("In order to be understood by the Orfeo ToolBox and the underlying OSSIM library, a geo-referenced Digital Elevation Model image can be converted into a general raster image, which consists in 3 files with the following extensions: .ras, .geom and .omd. Once converted, you have to place these files in a separate directory, and you can then use this directory to set the \"DEM Directory\" parameter of a DEM based OTB application or filter.");
    SetDocLimitations("None");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(" ");

    AddDocTag(Tags::Manip);

    AddParameter(ParameterType_InputImage,  "in",  "Input geo-referenced DEM");
    SetParameterDescription("in", "Input geo-referenced DEM to convert to general raster format.");

    AddParameter(ParameterType_OutputFilename,    "out", "Prefix of the output files");
    std::ostringstream oss;
    oss << "will be used to get the prefix (name withtout extensions) of the files to write. ";
    oss << "Three files - prefix.geom, prefix.omd and prefix.ras - will be generated.";
    SetParameterDescription("out", oss.str());
    //MandatoryOn("out");

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "QB_Toulouse_Ortho_Elev.tif");
    SetDocExampleParameterValue("out", "outputDEM");

    SetOfficialDocLink();
}

void DoUpdateParameters() override
{
  // nothing to update
}

/* The main is simple : read image using OTB and write it as a tif.
*  Read this tif using OSSIM and convert it as a general raster file
*  (.ras, .geom and . omd)
*/

void DoExecute() override
{
  // Load input image
  FloatVectorImageType::Pointer inImage = GetParameterImage("in");

  // Set temporary tif filename (for ossim)
  std::string ofname = GetParameterString("out");
  std::string path   = itksys::SystemTools::GetFilenamePath(ofname);
  std::string fname  = itksys::SystemTools::GetFilenameWithoutExtension(ofname);
  std::string tempFilename = path+"/"+fname+"_DEMConvert.tif";
  std::string tempFilenameGeom = path+"/"+fname+"_DEMConvert.geom";

  // Generate the tif image using OTB while keeping the same  pixel
  // type then the input image
  // Initialize an outputParameter and set its output pixeltype
  OutputImageParameter::Pointer paramOut = OutputImageParameter::New();
  std::ostringstream osswriter;
  osswriter<< "writing temporary tif file";

  // Set the filename of the current output image
  paramOut->SetFileName(tempFilename);
  paramOut->SetValue(inImage);

  // Set the output pixel type
  std::string typeInfo;
  itk::ExposeMetaData< std::string >( inImage->GetMetaDataDictionary(),
          MetaDataKey::OriginalPixelType , typeInfo) ;
  if( typeInfo == "unsigned char" )
    {
    paramOut->SetPixelType(ImagePixelType_uint8);
    }
  else if( typeInfo == "unsigned short" )
    {
    paramOut->SetPixelType(ImagePixelType_uint16);
    }
  else if( typeInfo == "short" )
    {
    paramOut->SetPixelType(ImagePixelType_int16);
    }
  else if( typeInfo == "unsigned int" )
    {
    paramOut->SetPixelType(ImagePixelType_uint32);
    }
  else if( typeInfo == "int" )
    {
    paramOut->SetPixelType(ImagePixelType_int32);
    }
  else if( typeInfo == "float" )
    {
    paramOut->SetPixelType(ImagePixelType_float);
    }
  else if( typeInfo == "double" )
    {
    paramOut->SetPixelType(ImagePixelType_double);
    }
  else
    {
    itkExceptionMacro("This application doesn't support image pixel type " << typeInfo);
    }

  // Add the tempfilename to be written
  paramOut->InitializeWriters();
  AddProcess(paramOut->GetWriter(), osswriter.str());
  paramOut->Write();

  // Set the output ras file
  std::string output = path+"/"+fname+".ras";

  DEMConvertAdapter::Pointer DEMConverter = DEMConvertAdapter::New();
  DEMConverter->Convert(tempFilename, output);

  // remove the temprorary tif file
  if( !itksys::SystemTools::RemoveFile(tempFilename) )
    {
    itkExceptionMacro("Problem while removing the file " << tempFilename);
    }

  // remove the geom file if any
  if( itksys::SystemTools::FileExists(tempFilenameGeom)
      && !itksys::SystemTools::RemoveFile(tempFilenameGeom))
    {
    itkExceptionMacro("Problem while removing the Geom file " << tempFilenameGeom);
    }
  }

};

} // namespace otb
}
OTB_APPLICATION_EXPORT(otb::Wrapper::DEMConvert)

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
 */

#include "base/os.h"
#include <cmn/agent_cmn.h>
#include <pkt/pkt_handler.h>
#include <oper/route_common.h>
#include <services/icmpv6_proto.h>

Icmpv6Proto::Icmpv6Proto(Agent *agent, boost::asio::io_service &io) :
    Proto(agent, "Agent::Services", PktHandler::ICMPV6, io) {
    vn_table_listener_id_ = agent->vn_table()->Register(
                             boost::bind(&Icmpv6Proto::VnNotify, this, _2));
    vrf_table_listener_id_ = agent->vrf_table()->Register(
                             boost::bind(&Icmpv6Proto::VrfNotify, this, _2));
    interface_listener_id_ = agent->interface_table()->Register(
                             boost::bind(&Icmpv6Proto::InterfaceNotify,
                                         this, _2));

    boost::shared_ptr<PktInfo> pkt_info(new PktInfo(NULL));
    routing_advert_handler_.reset(new Icmpv6Handler(agent, pkt_info, io));

    timer_ = TimerManager::CreateTimer(io, "Icmpv6Timer",
             TaskScheduler::GetInstance()->GetTaskId("Agent::Services"),
             PktHandler::ICMPV6);
    timer_->Start(kRouterAdvertTimeout,
                  boost::bind(&Icmpv6Handler::RouterAdvertisement,
                              routing_advert_handler_.get(), this));
}

Icmpv6Proto::~Icmpv6Proto() {
}

void Icmpv6Proto::Shutdown() {
    agent_->vn_table()->Unregister(vn_table_listener_id_);
    agent_->vrf_table()->Unregister(vrf_table_listener_id_);
    agent_->interface_table()->Unregister(interface_listener_id_);
    timer_->Cancel();
    TimerManager::DeleteTimer(timer_);
}

ProtoHandler *Icmpv6Proto::AllocProtoHandler(boost::shared_ptr<PktInfo> info,
                                             boost::asio::io_service &io) {
    return new Icmpv6Handler(agent(), info, io);
}

void Icmpv6Proto::VnNotify(DBEntryBase *entry) {
    if (entry->IsDeleted()) return;

    VnEntry *vn = static_cast<VnEntry *>(entry);
    VrfEntry *vrf = vn->GetVrf();
    if (!vrf) return;

    if (vrf->GetName() == agent_->fabric_vrf_name())
        return;

    if (vn->layer3_forwarding()) {
        boost::system::error_code ec;
        Ip6Address addr = Ip6Address::from_string(IPV6_ALL_ROUTERS_ADDRESS, ec);
        static_cast<InetUnicastAgentRouteTable *>
            (vrf->GetInet6UnicastRouteTable())->AddHostRoute(vrf->GetName(),
                                                             addr, 128,
                                                             vn->GetName());
        /* We need route for PKT0_LINKLOCAL_ADDRESS so that vrouter can respond
         * to NDP requests for PKT0_LINKLOCAL_ADDRESS. Even though the nexthop
         * for this route is pkt0, vrouter never sends pkts pointing to this
         * route on pkt0.
         */
        addr = Ip6Address::from_string(PKT0_LINKLOCAL_ADDRESS, ec);
        static_cast<InetUnicastAgentRouteTable *>
            (vrf->GetInet6UnicastRouteTable())->AddHostRoute(vrf->GetName(),
                                                             addr, 128,
                                                             vn->GetName());
    }
}

void Icmpv6Proto::VrfNotify(DBEntryBase *entry) {
    VrfEntry *vrf = static_cast<VrfEntry *>(entry);
    if (vrf->GetName() == agent_->fabric_vrf_name())
        return;

    if (entry->IsDeleted()) {
        boost::system::error_code ec;
        Ip6Address addr = Ip6Address::from_string(IPV6_ALL_ROUTERS_ADDRESS, ec);
        // enqueue delete request on fabric VRF
        agent_->fabric_inet4_unicast_table()->DeleteReq(agent_->local_peer(),
                                                        vrf->GetName(),
                                                        addr, 128, NULL);
        addr = Ip6Address::from_string(PKT0_LINKLOCAL_ADDRESS, ec);
        agent_->fabric_inet4_unicast_table()->DeleteReq(agent_->local_peer(),
                                                        vrf->GetName(),
                                                        addr, 128, NULL);
    }
}

void Icmpv6Proto::InterfaceNotify(DBEntryBase *entry) {
    Interface *interface = static_cast<Interface *>(entry);
    if (interface->type() != Interface::VM_INTERFACE)
        return;

    VmInterface *vm_interface = static_cast<VmInterface *>(entry);
    if (interface->IsDeleted())
        vm_interfaces_.erase(vm_interface);
    else
        vm_interfaces_.insert(vm_interface);
}
<commit_msg>Add client state to VRF when all routers route entry is added.<commit_after>/*
 * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.
 */

#include "base/os.h"
#include <cmn/agent_cmn.h>
#include <pkt/pkt_handler.h>
#include <oper/route_common.h>
#include <services/icmpv6_proto.h>

Icmpv6Proto::Icmpv6Proto(Agent *agent, boost::asio::io_service &io) :
    Proto(agent, "Agent::Services", PktHandler::ICMPV6, io) {
    vn_table_listener_id_ = agent->vn_table()->Register(
                             boost::bind(&Icmpv6Proto::VnNotify, this, _2));
    vrf_table_listener_id_ = agent->vrf_table()->Register(
                             boost::bind(&Icmpv6Proto::VrfNotify, this, _2));
    interface_listener_id_ = agent->interface_table()->Register(
                             boost::bind(&Icmpv6Proto::InterfaceNotify,
                                         this, _2));

    boost::shared_ptr<PktInfo> pkt_info(new PktInfo(NULL));
    routing_advert_handler_.reset(new Icmpv6Handler(agent, pkt_info, io));

    timer_ = TimerManager::CreateTimer(io, "Icmpv6Timer",
             TaskScheduler::GetInstance()->GetTaskId("Agent::Services"),
             PktHandler::ICMPV6);
    timer_->Start(kRouterAdvertTimeout,
                  boost::bind(&Icmpv6Handler::RouterAdvertisement,
                              routing_advert_handler_.get(), this));
}

Icmpv6Proto::~Icmpv6Proto() {
}

void Icmpv6Proto::Shutdown() {
    agent_->vn_table()->Unregister(vn_table_listener_id_);
    agent_->vrf_table()->Unregister(vrf_table_listener_id_);
    agent_->interface_table()->Unregister(interface_listener_id_);
    timer_->Cancel();
    TimerManager::DeleteTimer(timer_);
}

ProtoHandler *Icmpv6Proto::AllocProtoHandler(boost::shared_ptr<PktInfo> info,
                                             boost::asio::io_service &io) {
    return new Icmpv6Handler(agent(), info, io);
}

void Icmpv6Proto::VnNotify(DBEntryBase *entry) {
    if (entry->IsDeleted()) return;

    VnEntry *vn = static_cast<VnEntry *>(entry);
    VrfEntry *vrf = vn->GetVrf();
    if (!vrf) return;

    if (vrf->GetName() == agent_->fabric_vrf_name())
        return;

    if (vn->layer3_forwarding()) {
        if (vrf->GetState(vrf->get_table_partition()->parent(),
                          vrf_table_listener_id_))
            return;

        DBState *state = new DBState();
        vrf->SetState(vrf->get_table_partition()->parent(),
                      vrf_table_listener_id_, state);

        boost::system::error_code ec;
        Ip6Address addr = Ip6Address::from_string(IPV6_ALL_ROUTERS_ADDRESS, ec);
        static_cast<InetUnicastAgentRouteTable *>
            (vrf->GetInet6UnicastRouteTable())->AddHostRoute(vrf->GetName(),
                                                             addr, 128,
                                                             vn->GetName());
        /* We need route for PKT0_LINKLOCAL_ADDRESS so that vrouter can respond
         * to NDP requests for PKT0_LINKLOCAL_ADDRESS. Even though the nexthop
         * for this route is pkt0, vrouter never sends pkts pointing to this
         * route on pkt0.
         */
        addr = Ip6Address::from_string(PKT0_LINKLOCAL_ADDRESS, ec);
        static_cast<InetUnicastAgentRouteTable *>
            (vrf->GetInet6UnicastRouteTable())->AddHostRoute(vrf->GetName(),
                                                             addr, 128,
                                                             vn->GetName());
    }
}

void Icmpv6Proto::VrfNotify(DBEntryBase *entry) {
    VrfEntry *vrf = static_cast<VrfEntry *>(entry);
    if (vrf->GetName() == agent_->fabric_vrf_name())
        return;

    if (entry->IsDeleted()) {
        DBState *state = vrf->GetState(vrf->get_table_partition()->parent(),
                                       vrf_table_listener_id_);
        if (!state)
            return;
        vrf->ClearState(vrf->get_table_partition()->parent(),
                        vrf_table_listener_id_);
        delete state;

        boost::system::error_code ec;
        Ip6Address addr = Ip6Address::from_string(IPV6_ALL_ROUTERS_ADDRESS, ec);
        // enqueue delete request on fabric VRF
        agent_->fabric_inet4_unicast_table()->DeleteReq(agent_->local_peer(),
                                                        vrf->GetName(),
                                                        addr, 128, NULL);
        addr = Ip6Address::from_string(PKT0_LINKLOCAL_ADDRESS, ec);
        agent_->fabric_inet4_unicast_table()->DeleteReq(agent_->local_peer(),
                                                        vrf->GetName(),
                                                        addr, 128, NULL);
    }
}

void Icmpv6Proto::InterfaceNotify(DBEntryBase *entry) {
    Interface *interface = static_cast<Interface *>(entry);
    if (interface->type() != Interface::VM_INTERFACE)
        return;

    VmInterface *vm_interface = static_cast<VmInterface *>(entry);
    if (interface->IsDeleted())
        vm_interfaces_.erase(vm_interface);
    else
        vm_interfaces_.insert(vm_interface);
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * 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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbMultiChannelExtractROI.h"
#include "otbGenericRSTransform.h"

namespace otb
{
namespace Wrapper
{

class PixelValue : public Application
{
public:
  /** Standard class typedefs. */
  typedef PixelValue                    Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  typedef otb::MultiChannelExtractROI<FloatVectorImageType::InternalPixelType,
              FloatVectorImageType::InternalPixelType> ExtractROIFilterType;

  typedef otb::GenericRSTransform<>  RSTransformType;
  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(PixelValue, otb::Application);

private:
  void DoInit() ITK_OVERRIDE
  {
    SetName("PixelValue");
    SetDescription("Get the value of a pixel.");

    // Documentation
    SetDocName("Pixel Value");
    SetDocLongDescription("This application gives the value of a selected "
      "pixel. There are three ways of designate a pixel, with its index, "
      "its physical coordinate (in the physical space attached to the image), "
      "and with geographical coordinate system. Coordinates will be "
      "interpreted differently depending on which mode is chosen.");
    SetDocLimitations("None");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(" ");

    AddDocTag("Miscellaneous");
    AddDocTag("Utilities");
    AddDocTag("Coordinates");
    AddDocTag("Raster");

    AddParameter(ParameterType_InputImage , "in", "Input Image");
    SetParameterDescription("in" , "Input image");

    AddParameter(ParameterType_Float , "coordx" , "X coordinate" );
    SetParameterDescription("coordx" ,
          "This will be the X coordinate interpreted depending on the "
          "chosen mode");
    AddParameter(ParameterType_Float , "coordy" , "Y coordinate" );
    SetParameterDescription("coordy" ,
          "This will be the Y coordinate interpreted depending on the "
          "chosen mode");

    AddParameter(ParameterType_Choice , "mode" ,
          "Coordinate system used to designate the pixel");
    SetParameterDescription( "mode" ,
          "Different mode can be selected, default mode is Index.");
    AddChoice( "mode.index" , "Index");
    SetParameterDescription( "mode.index" ,
          "This mode use the given coordinates as index to locate the pixel.");
    AddChoice( "mode.physical" , "Image physical space");
    SetParameterDescription( "mode.physical" ,
          "This mode interpret the given coordinates in the image "
          "physical space.");
    AddChoice( "mode.epsg" , "EPSG coordinates");
    SetParameterDescription( "mode.epsg" ,
          "This mode interpret the given coordinates in the specified "
          "geographical coordinate system by the EPSG code.");

    AddParameter(ParameterType_Int , "epsg" , "EPSG code");
    SetParameterDescription("epsg" ,
          "This code is used to define a geographical coordinate system. "
          "If no system is specified, WGS84 (EPSG : 4326) is used by default.");
    MandatoryOff("epsg");

    AddParameter(ParameterType_ListView,"cl","Channels");
    SetParameterDescription("cl","Displayed channels");
    MandatoryOff("cl");

    AddParameter(ParameterType_String,"value","Pixel Value");
    SetParameterDescription("value", "Pixel radiometric value");
    SetParameterRole("value", Role_Output);

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "QB_Toulouse_Ortho_XS.tif");
    SetDocExampleParameterValue("coordx", "50");
    SetDocExampleParameterValue("coordy", "100");
    SetDocExampleParameterValue("cl", "Channel1");

    SetOfficialDocLink();
  }

  void DoUpdateParameters() ITK_OVERRIDE
  {
    if ( HasValue("in") )
      {
      ExtractROIFilterType::InputImageType * inImage = GetParameterImage("in");

      // Update the values of the channels to be selected
      unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel();
      ClearChoices("cl");
      for (unsigned int idx = 0; idx < nbComponents; ++idx)
        {
        std::ostringstream key, item;
        key<<"cl.channel"<<idx+1;
        item<<"Channel"<<idx+1;
        AddChoice(key.str(), item.str());
        }
      }
  }

  std::string CreateBoundaryBox( const std::string & mode )
  {
    FloatVectorImageType::Pointer inImage = GetParameterImage("in");
    FloatVectorImageType::IndexType min , max;
    min.Fill(0);
    max[0] = inImage->GetLargestPossibleRegion().GetSize()[0] - 1;
    max[1] = inImage->GetLargestPossibleRegion().GetSize()[1] - 1;
    std::string boundaries[4]("");
    if (mode == "index")
      {
      boundaries[0] = std::to_string(max[0]);
      boundaries[1] = std::to_string(max[1]);
      boundaries[2] = std::to_string(min[0]);
      boundaries[3] = std::to_string(min[1]);
      }
    else if (mode == "physical")
      {
      itk::Point< float, 2 > minP(0) , maxP(0);
      inImage->TransformIndexToPhysicalPoint(min,minP);
      inImage->TransformIndexToPhysicalPoint(max,maxP);
      boundaries[0] = std::to_string(std::max(minP[0],maxP[0]));
      boundaries[1] = std::to_string(std::max(minP[1],maxP[1]));
      boundaries[2] = std::to_string(std::min(minP[0],maxP[0]));
      boundaries[3] = std::to_string(std::min(minP[1],maxP[1]));
      }
    else if (mode == "epsg")
      {
      RSTransformType::Pointer inverse = RSTransformType::New();
      if ( HasUserValue("epsg") )
        {
        std::string wktFromEpsg =
          otb::GeoInformationConversion::ToWKT(GetParameterInt( "epsg" ));
        inverse->SetOutputProjectionRef(wktFromEpsg);
        }
      inverse->SetInputKeywordList( inImage->GetImageKeywordlist() );
      inverse->SetInputProjectionRef( inImage->GetProjectionRef() );
      inverse->InstantiateTransform();
      itk::Point< float, 2 > minPOut(0) , maxPOut(0) , minP(0) , maxP(0);
      inImage->TransformIndexToPhysicalPoint(min,minP);
      inImage->TransformIndexToPhysicalPoint(max,maxP);
      minPOut = inverse->TransformPoint( minP );
      maxPOut = inverse->TransformPoint( maxP );
      boundaries[0] = std::to_string(std::max(minPOut[0],maxPOut[0]));
      boundaries[1] = std::to_string(std::max(minPOut[1],maxPOut[1]));
      boundaries[2] = std::to_string(std::min(minPOut[0],maxPOut[0]));
      boundaries[3] = std::to_string(std::min(minPOut[1],maxPOut[1]));
      }

    for (int i = 0 ; i<4 ; i++)
      {
      std::size_t coma = boundaries[i].find(".");
      if ( coma != std::string::npos )
        {
        std::size_t zero = boundaries[i].find_last_not_of("0");
        if ( zero != std::string::npos )
          boundaries[i].erase(zero + 1);
        else
          boundaries[i] = "0";
        }
      }

    std::string box = "";
    box += "["+boundaries[2]+" , "+boundaries[0]+"] x ";
    box += "["+boundaries[3]+" , "+boundaries[1]+"]";
    return box;
  }

  void DoExecute() ITK_OVERRIDE
  {
    std::string mode = GetParameterString( "mode" );
    FloatVectorImageType::Pointer inImage = GetParameterImage("in");
    FloatVectorImageType::IndexType id ;
    id.Fill(0);
    bool isPixelIn( false );
    if ( mode == "index" )
      {
      id[0] = static_cast< int >( GetParameterFloat( "coordx" ) );
      id[1] = static_cast< int >( GetParameterFloat( "coordy" ) );
      if (static_cast< unsigned int >( id[0] ) >=
                    inImage->GetLargestPossibleRegion().GetSize()[0]
       || static_cast< unsigned int >( id[1] ) >=
                    inImage->GetLargestPossibleRegion().GetSize()[1]
       || id[0] < 0 || id[1] < 0 )
        {
        id.Fill(0);
        isPixelIn = false;
        }
      else
        {
        isPixelIn = true;
        }
      }

    else if ( mode == "physical" )
      {
      itk::Point<float, 2> pixel(0);
      pixel[ 0 ] = GetParameterFloat( "coordx" );
      pixel[ 1 ] = GetParameterFloat( "coordy" );
      isPixelIn = inImage->TransformPhysicalPointToIndex(pixel,id);
      }

    else if ( mode == "epsg" )
      {
      RSTransformType::Pointer rsTransform = RSTransformType::New();
      if ( HasUserValue("epsg") )
        {
        std::string wktFromEpsg =
          otb::GeoInformationConversion::ToWKT( GetParameterInt( "epsg" ) );
        rsTransform->SetInputProjectionRef(wktFromEpsg);
        }
      rsTransform->SetOutputKeywordList( inImage->GetImageKeywordlist() );
      rsTransform->SetOutputProjectionRef( inImage->GetProjectionRef() );
      rsTransform->InstantiateTransform();
      itk::Point<float, 2> pixelIn(0) , pixelOut(0);
      pixelIn[ 0 ] = GetParameterFloat( "coordx" );
      pixelIn[ 1 ] = GetParameterFloat( "coordy" );
      rsTransform->InstantiateTransform();
      pixelOut = rsTransform->TransformPoint(pixelIn);
      isPixelIn = inImage->TransformPhysicalPointToIndex(pixelOut,id);
      }

    if ( !isPixelIn )
      {
      std::string why = "Accessible pixels are in ";
      why += CreateBoundaryBox( GetParameterString( "mode" ) );
      why += " for the selected mode.";
      otbAppLogFATAL(<<"Specified position out of bound.\n" + why);
      }

    ExtractROIFilterType::Pointer extractor = ExtractROIFilterType::New();
    extractor->SetInput(inImage);

    // Extract the channels if needed
    if ( GetParameterByKey("cl")->GetActive() )
      {
      for (unsigned int idx = 0; idx < GetSelectedItems("cl").size(); ++idx)
        {
        extractor->SetChannel(GetSelectedItems("cl")[idx] + 1 );
        }
      }
    FloatVectorImageType::SizeType size;
    size.Fill(1);
    FloatVectorImageType::RegionType region;
    region.SetSize(size);
    region.SetIndex(id);

    extractor->SetExtractionRegion(region);
    extractor->Update();

    // Display the pixel value
    id.Fill(0);
    std::ostringstream oss;
    oss << extractor->GetOutput()->GetPixel(id);
    SetParameterString("value", oss.str(), false);
    //Display image information in the dedicated logger
    otbAppLogINFO( << oss.str() );
  }

};

}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::PixelValue)
<commit_msg>COMP : correct list's initialization<commit_after>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * 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 "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbMultiChannelExtractROI.h"
#include "otbGenericRSTransform.h"

namespace otb
{
namespace Wrapper
{

class PixelValue : public Application
{
public:
  /** Standard class typedefs. */
  typedef PixelValue                    Self;
  typedef Application                   Superclass;
  typedef itk::SmartPointer<Self>       Pointer;
  typedef itk::SmartPointer<const Self> ConstPointer;

  typedef otb::MultiChannelExtractROI<FloatVectorImageType::InternalPixelType,
              FloatVectorImageType::InternalPixelType> ExtractROIFilterType;

  typedef otb::GenericRSTransform<>  RSTransformType;
  /** Standard macro */
  itkNewMacro(Self);

  itkTypeMacro(PixelValue, otb::Application);

private:
  void DoInit() ITK_OVERRIDE
  {
    SetName("PixelValue");
    SetDescription("Get the value of a pixel.");

    // Documentation
    SetDocName("Pixel Value");
    SetDocLongDescription("This application gives the value of a selected "
      "pixel. There are three ways of designate a pixel, with its index, "
      "its physical coordinate (in the physical space attached to the image), "
      "and with geographical coordinate system. Coordinates will be "
      "interpreted differently depending on which mode is chosen.");
    SetDocLimitations("None");
    SetDocAuthors("OTB-Team");
    SetDocSeeAlso(" ");

    AddDocTag("Miscellaneous");
    AddDocTag("Utilities");
    AddDocTag("Coordinates");
    AddDocTag("Raster");

    AddParameter(ParameterType_InputImage , "in", "Input Image");
    SetParameterDescription("in" , "Input image");

    AddParameter(ParameterType_Float , "coordx" , "X coordinate" );
    SetParameterDescription("coordx" ,
          "This will be the X coordinate interpreted depending on the "
          "chosen mode");
    AddParameter(ParameterType_Float , "coordy" , "Y coordinate" );
    SetParameterDescription("coordy" ,
          "This will be the Y coordinate interpreted depending on the "
          "chosen mode");

    AddParameter(ParameterType_Choice , "mode" ,
          "Coordinate system used to designate the pixel");
    SetParameterDescription( "mode" ,
          "Different mode can be selected, default mode is Index.");
    AddChoice( "mode.index" , "Index");
    SetParameterDescription( "mode.index" ,
          "This mode use the given coordinates as index to locate the pixel.");
    AddChoice( "mode.physical" , "Image physical space");
    SetParameterDescription( "mode.physical" ,
          "This mode interpret the given coordinates in the image "
          "physical space.");
    AddChoice( "mode.epsg" , "EPSG coordinates");
    SetParameterDescription( "mode.epsg" ,
          "This mode interpret the given coordinates in the specified "
          "geographical coordinate system by the EPSG code.");

    AddParameter(ParameterType_Int , "epsg" , "EPSG code");
    SetParameterDescription("epsg" ,
          "This code is used to define a geographical coordinate system. "
          "If no system is specified, WGS84 (EPSG : 4326) is used by default.");
    MandatoryOff("epsg");

    AddParameter(ParameterType_ListView,"cl","Channels");
    SetParameterDescription("cl","Displayed channels");
    MandatoryOff("cl");

    AddParameter(ParameterType_String,"value","Pixel Value");
    SetParameterDescription("value", "Pixel radiometric value");
    SetParameterRole("value", Role_Output);

    // Doc example parameter settings
    SetDocExampleParameterValue("in", "QB_Toulouse_Ortho_XS.tif");
    SetDocExampleParameterValue("coordx", "50");
    SetDocExampleParameterValue("coordy", "100");
    SetDocExampleParameterValue("cl", "Channel1");

    SetOfficialDocLink();
  }

  void DoUpdateParameters() ITK_OVERRIDE
  {
    if ( HasValue("in") )
      {
      ExtractROIFilterType::InputImageType * inImage = GetParameterImage("in");

      // Update the values of the channels to be selected
      unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel();
      ClearChoices("cl");
      for (unsigned int idx = 0; idx < nbComponents; ++idx)
        {
        std::ostringstream key, item;
        key<<"cl.channel"<<idx+1;
        item<<"Channel"<<idx+1;
        AddChoice(key.str(), item.str());
        }
      }
  }

  std::string CreateBoundaryBox( const std::string & mode )
  {
    FloatVectorImageType::Pointer inImage = GetParameterImage("in");
    FloatVectorImageType::IndexType min , max;
    min.Fill(0);
    max[0] = inImage->GetLargestPossibleRegion().GetSize()[0] - 1;
    max[1] = inImage->GetLargestPossibleRegion().GetSize()[1] - 1;
    std::string boundaries[4];
    if (mode == "index")
      {
      boundaries[0] = std::to_string(max[0]);
      boundaries[1] = std::to_string(max[1]);
      boundaries[2] = std::to_string(min[0]);
      boundaries[3] = std::to_string(min[1]);
      }
    else if (mode == "physical")
      {
      itk::Point< float, 2 > minP(0) , maxP(0);
      inImage->TransformIndexToPhysicalPoint(min,minP);
      inImage->TransformIndexToPhysicalPoint(max,maxP);
      boundaries[0] = std::to_string(std::max(minP[0],maxP[0]));
      boundaries[1] = std::to_string(std::max(minP[1],maxP[1]));
      boundaries[2] = std::to_string(std::min(minP[0],maxP[0]));
      boundaries[3] = std::to_string(std::min(minP[1],maxP[1]));
      }
    else if (mode == "epsg")
      {
      RSTransformType::Pointer inverse = RSTransformType::New();
      if ( HasUserValue("epsg") )
        {
        std::string wktFromEpsg =
          otb::GeoInformationConversion::ToWKT(GetParameterInt( "epsg" ));
        inverse->SetOutputProjectionRef(wktFromEpsg);
        }
      inverse->SetInputKeywordList( inImage->GetImageKeywordlist() );
      inverse->SetInputProjectionRef( inImage->GetProjectionRef() );
      inverse->InstantiateTransform();
      itk::Point< float, 2 > minPOut(0) , maxPOut(0) , minP(0) , maxP(0);
      inImage->TransformIndexToPhysicalPoint(min,minP);
      inImage->TransformIndexToPhysicalPoint(max,maxP);
      minPOut = inverse->TransformPoint( minP );
      maxPOut = inverse->TransformPoint( maxP );
      boundaries[0] = std::to_string(std::max(minPOut[0],maxPOut[0]));
      boundaries[1] = std::to_string(std::max(minPOut[1],maxPOut[1]));
      boundaries[2] = std::to_string(std::min(minPOut[0],maxPOut[0]));
      boundaries[3] = std::to_string(std::min(minPOut[1],maxPOut[1]));
      }

    for (int i = 0 ; i<4 ; i++)
      {
      std::size_t coma = boundaries[i].find(".");
      if ( coma != std::string::npos )
        {
        std::size_t zero = boundaries[i].find_last_not_of("0");
        if ( zero != std::string::npos )
          boundaries[i].erase(zero + 1);
        else
          boundaries[i] = "0";
        }
      }

    std::string box = "";
    box += "["+boundaries[2]+" , "+boundaries[0]+"] x ";
    box += "["+boundaries[3]+" , "+boundaries[1]+"]";
    return box;
  }

  void DoExecute() ITK_OVERRIDE
  {
    std::string mode = GetParameterString( "mode" );
    FloatVectorImageType::Pointer inImage = GetParameterImage("in");
    FloatVectorImageType::IndexType id ;
    id.Fill(0);
    bool isPixelIn( false );
    if ( mode == "index" )
      {
      id[0] = static_cast< int >( GetParameterFloat( "coordx" ) );
      id[1] = static_cast< int >( GetParameterFloat( "coordy" ) );
      if (static_cast< unsigned int >( id[0] ) >=
                    inImage->GetLargestPossibleRegion().GetSize()[0]
       || static_cast< unsigned int >( id[1] ) >=
                    inImage->GetLargestPossibleRegion().GetSize()[1]
       || id[0] < 0 || id[1] < 0 )
        {
        id.Fill(0);
        isPixelIn = false;
        }
      else
        {
        isPixelIn = true;
        }
      }

    else if ( mode == "physical" )
      {
      itk::Point<float, 2> pixel(0);
      pixel[ 0 ] = GetParameterFloat( "coordx" );
      pixel[ 1 ] = GetParameterFloat( "coordy" );
      isPixelIn = inImage->TransformPhysicalPointToIndex(pixel,id);
      }

    else if ( mode == "epsg" )
      {
      RSTransformType::Pointer rsTransform = RSTransformType::New();
      if ( HasUserValue("epsg") )
        {
        std::string wktFromEpsg =
          otb::GeoInformationConversion::ToWKT( GetParameterInt( "epsg" ) );
        rsTransform->SetInputProjectionRef(wktFromEpsg);
        }
      rsTransform->SetOutputKeywordList( inImage->GetImageKeywordlist() );
      rsTransform->SetOutputProjectionRef( inImage->GetProjectionRef() );
      rsTransform->InstantiateTransform();
      itk::Point<float, 2> pixelIn(0) , pixelOut(0);
      pixelIn[ 0 ] = GetParameterFloat( "coordx" );
      pixelIn[ 1 ] = GetParameterFloat( "coordy" );
      rsTransform->InstantiateTransform();
      pixelOut = rsTransform->TransformPoint(pixelIn);
      isPixelIn = inImage->TransformPhysicalPointToIndex(pixelOut,id);
      }

    if ( !isPixelIn )
      {
      std::string why = "Accessible pixels are in ";
      why += CreateBoundaryBox( GetParameterString( "mode" ) );
      why += " for the selected mode.";
      otbAppLogFATAL(<<"Specified position out of bound.\n" + why);
      }

    ExtractROIFilterType::Pointer extractor = ExtractROIFilterType::New();
    extractor->SetInput(inImage);

    // Extract the channels if needed
    if ( GetParameterByKey("cl")->GetActive() )
      {
      for (unsigned int idx = 0; idx < GetSelectedItems("cl").size(); ++idx)
        {
        extractor->SetChannel(GetSelectedItems("cl")[idx] + 1 );
        }
      }
    FloatVectorImageType::SizeType size;
    size.Fill(1);
    FloatVectorImageType::RegionType region;
    region.SetSize(size);
    region.SetIndex(id);

    extractor->SetExtractionRegion(region);
    extractor->Update();

    // Display the pixel value
    id.Fill(0);
    std::ostringstream oss;
    oss << extractor->GetOutput()->GetPixel(id);
    SetParameterString("value", oss.str(), false);
    //Display image information in the dedicated logger
    otbAppLogINFO( << oss.str() );
  }

};

}
}

OTB_APPLICATION_EXPORT(otb::Wrapper::PixelValue)
<|endoftext|>


<commit_before>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */
/* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */

#include "wallpaperwidget.h"
#include "wallpaperlist.h"

#include <QGraphicsLinearLayout>
#include <MLayout>
#include <MLinearLayoutPolicy>
#include <MContainer>
#include <QTimer>
#include <MContentItem>
#include <SelectSingleContentItemPage.h>
#include <QDebug>
#include <QtTracker/Tracker>

#define DEBUG
#include "../debug.h"

static const int MaxColumns = 2;

static const char *oviCommand = "webwidgetrunner /usr/share/webwidgets/applications/d34177b1c241ea44cb132005b63ee6527c9f6040-wrt-widget.desktop -widgetparameter graphics &";

WallpaperWidget::WallpaperWidget (
        WallpaperBusinessLogic *wallpaperBusinessLogic,
        QGraphicsWidget        *parent) :
    DcpWidget (parent),
    m_WallpaperBusinessLogic (wallpaperBusinessLogic)
{
    /*
     * Unfortunatelly the content has to be created late, otherwise the list
     * only shows one row.
     * FIXME: I'm n ot sure how late should this be done, I thing we should use
     * the void MApplicationPage::createContent(), but I don't know how to do
     * that.
     */
    //createContent ();
    QTimer::singleShot(100, this, SLOT(createContent()));
}

WallpaperWidget::~WallpaperWidget ()
{
}

void
WallpaperWidget::createContent ()
{
    QGraphicsLinearLayout *mainLayout;

    SYS_DEBUG ("--- Start ------------");
    mainLayout = new QGraphicsLinearLayout (Qt::Vertical);
    setLayout (mainLayout);
 SYS_DEBUG ("1");
    /*
     * The gallery item.
     */
    m_GalleryItem = new MContentItem (MContentItem::IconAndSingleTextLabel);
    m_GalleryItem->setObjectName ("GalleryItem");
    m_GalleryItem->setItemMode (MContentItem::Single);

    connect (m_GalleryItem, SIGNAL(clicked()),
            this, SLOT(galleryActivated()));
 SYS_DEBUG ("2");
    /*
     * The OVI item.
     */
    m_OviItem = new MContentItem(MContentItem::IconAndSingleTextLabel);
    m_OviItem->setImageID ("icon-m-common-ovi");
    m_OviItem->setObjectName ("OviItem");
    m_OviItem->setItemMode (MContentItem::Single);

    connect (m_OviItem, SIGNAL(clicked()),
            this, SLOT(oviActivated()));

 SYS_DEBUG ("3");
    /*
     * The list of the available images.
     */
    m_ImageList = new WallpaperList (m_WallpaperBusinessLogic, this);
    m_ImageList->setObjectName("WallpaperImageList");
    connect (m_ImageList, SIGNAL(imageActivated(WallpaperDescriptor *)),
            this, SLOT(slotImageActivated(WallpaperDescriptor *)));
 SYS_DEBUG ("3/a");
    m_ImageList->setDataSourceType (WallpaperList::DataSourceLocal);

 SYS_DEBUG ("4");
    /*
     * Adding all widgets into the layout.
     */
    mainLayout->addItem (m_GalleryItem);
    mainLayout->addItem (m_OviItem);
    mainLayout->addItem (m_ImageList);
    mainLayout->setStretchFactor (m_ImageList, 1);

 SYS_DEBUG ("5");
    retranslateUi ();

 SYS_DEBUG ("6");
    connect (m_WallpaperBusinessLogic, SIGNAL(imageEditRequested()),
            this, SLOT(slotImageActivated()));
    SYS_DEBUG ("--- End   ------------");
}

/*
 * This slot is called when the user activates an image in the list. The
 * WallpaperList has a signal for that.
 */
void
WallpaperWidget::slotImageActivated (
        WallpaperDescriptor *desc)
{
    SYS_DEBUG ("*** desc = %s", SYS_STR(desc->basename()));

    m_WallpaperBusinessLogic->setEditedImage (desc);
    m_WallpaperBusinessLogic->startEdit ();

}

/*
 * When this slot is activated the image has to be already loaded, so that the
 * editor widget can be shown without delay.
 */
void
WallpaperWidget::slotImageActivated ()
{
    SYS_DEBUG ("");

    emit changeWidget (1);
}

void
WallpaperWidget::retranslateUi ()
{
    //% "Get more from Ovi Store"
    m_OviItem->setTitle(qtTrId("qtn_wall_get_more_from_ovi"));

    //% "Pick from My Gallery"
    m_GalleryItem->setTitle(qtTrId("qtn_wall_pick_from_gallery"));
}

void
WallpaperWidget::oviActivated ()
{
    SYS_DEBUG ("Executing %s", oviCommand);
    system (oviCommand);
}

void
WallpaperWidget::galleryActivated ()
{
    SYS_DEBUG ("");
    if (m_noImageBrowser) {
            SelectSingleContentItemPage *imageBrowser = new SelectSingleContentItemPage(QString(), QStringList() << "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#Image", QString());
            imageBrowser->setObjectName("SelectSingleContentItemPage_imageBrowser");
            QObject::connect(imageBrowser, SIGNAL(backButtonClicked()), imageBrowser, SLOT(dismiss()));
            QObject::connect(imageBrowser, SIGNAL(backButtonClicked()), this, SLOT(imageBrowserDismissed()));
            QObject::connect(imageBrowser, SIGNAL(selectingContentItem(const QString &)), this, SLOT(galleryImageSelected(const QString &)));
            imageBrowser->appear(MSceneWindow::DestroyWhenDismissed);
            m_noImageBrowser = false;
    }
}

void WallpaperWidget::galleryImageSelected(const QString &uri)
{
    m_WallpaperBusinessLogic->addImageFromGallery(uri);
}

void WallpaperWidget::imageBrowserDismissed()
{
    m_noImageBrowser = true;
}
<commit_msg>Bug NB#187284 fix<commit_after>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */
/* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */

#include "wallpaperwidget.h"
#include "wallpaperlist.h"

#include <QGraphicsLinearLayout>
#include <MLayout>
#include <MLinearLayoutPolicy>
#include <MContainer>
#include <QTimer>
#include <MContentItem>
#include <SelectSingleContentItemPage.h>
#include <QDebug>
#include <QtTracker/Tracker>

#define DEBUG
#include "../debug.h"

static const int MaxColumns = 2;

static const char *oviCommand = "webwidgetrunner /usr/share/webwidgets/applications/d34177b1c241ea44cb132005b63ee6527c9f6040-wrt-widget.desktop -widgetparameter graphics &";

WallpaperWidget::WallpaperWidget (
        WallpaperBusinessLogic *wallpaperBusinessLogic,
        QGraphicsWidget        *parent) :
    DcpWidget (parent),
    m_WallpaperBusinessLogic (wallpaperBusinessLogic)
{
    /*
     * Unfortunatelly the content has to be created late, otherwise the list
     * only shows one row.
     * FIXME: I'm n ot sure how late should this be done, I thing we should use
     * the void MApplicationPage::createContent(), but I don't know how to do
     * that.
     */
    //createContent ();
    QTimer::singleShot(100, this, SLOT(createContent()));
}

WallpaperWidget::~WallpaperWidget ()
{
}

void
WallpaperWidget::createContent ()
{
    QGraphicsLinearLayout *mainLayout;

    SYS_DEBUG ("--- Start ------------");
    mainLayout = new QGraphicsLinearLayout (Qt::Vertical);
    setLayout (mainLayout);

    MLayout *buttonsLayout = new MLayout;

    MLinearLayoutPolicy *wallpaperLandscape =
        new MLinearLayoutPolicy (buttonsLayout, Qt::Horizontal);

    MLinearLayoutPolicy *wallpaperPortrait =
        new MLinearLayoutPolicy (buttonsLayout, Qt::Vertical);

 SYS_DEBUG ("1");
    /*
     * The gallery item.
     */
    m_GalleryItem = new MContentItem (MContentItem::IconAndSingleTextLabel);
    m_GalleryItem->setObjectName ("GalleryItem");
    m_GalleryItem->setItemMode (MContentItem::Single);
    m_GalleryItem->setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Fixed);
    wallpaperLandscape->addItem (m_GalleryItem);
    wallpaperPortrait->addItem (m_GalleryItem);

    connect (m_GalleryItem, SIGNAL(clicked()),
            this, SLOT(galleryActivated()));
 SYS_DEBUG ("2");
    /*
     * The OVI item.
     */
    m_OviItem = new MContentItem(MContentItem::IconAndSingleTextLabel);
    m_OviItem->setImageID ("icon-m-common-ovi");
    m_OviItem->setObjectName ("OviItem");
    m_OviItem->setItemMode (MContentItem::Single);
    m_OviItem->setSizePolicy (QSizePolicy::Expanding, QSizePolicy::Fixed);
    wallpaperLandscape->addItem (m_OviItem);
    wallpaperPortrait->addItem (m_OviItem);

    connect (m_OviItem, SIGNAL(clicked()),
            this, SLOT(oviActivated()));

 SYS_DEBUG ("3");
    /*
     * The list of the available images.
     */
    m_ImageList = new WallpaperList (m_WallpaperBusinessLogic, this);
    m_ImageList->setObjectName("WallpaperImageList");
    connect (m_ImageList, SIGNAL(imageActivated(WallpaperDescriptor *)),
            this, SLOT(slotImageActivated(WallpaperDescriptor *)));
 SYS_DEBUG ("3/a");
    m_ImageList->setDataSourceType (WallpaperList::DataSourceLocal);

 SYS_DEBUG ("4");
    /*
     * Adding all widgets into the layout.
     */
    buttonsLayout->setLandscapePolicy (wallpaperLandscape);
    buttonsLayout->setPortraitPolicy (wallpaperPortrait);
    mainLayout->addItem (buttonsLayout);
    mainLayout->addItem (m_ImageList);
    mainLayout->setStretchFactor (m_ImageList, 1);

 SYS_DEBUG ("5");
    retranslateUi ();

 SYS_DEBUG ("6");
    connect (m_WallpaperBusinessLogic, SIGNAL(imageEditRequested()),
            this, SLOT(slotImageActivated()));
    SYS_DEBUG ("--- End   ------------");
}

/*
 * This slot is called when the user activates an image in the list. The
 * WallpaperList has a signal for that.
 */
void
WallpaperWidget::slotImageActivated (
        WallpaperDescriptor *desc)
{
    SYS_DEBUG ("*** desc = %s", SYS_STR(desc->basename()));

    m_WallpaperBusinessLogic->setEditedImage (desc);
    m_WallpaperBusinessLogic->startEdit ();

}

/*
 * When this slot is activated the image has to be already loaded, so that the
 * editor widget can be shown without delay.
 */
void
WallpaperWidget::slotImageActivated ()
{
    SYS_DEBUG ("");

    emit changeWidget (1);
}

void
WallpaperWidget::retranslateUi ()
{
    //% "Get more from Ovi Store"
    m_OviItem->setTitle(qtTrId("qtn_wall_get_more_from_ovi"));

    //% "Pick from My Gallery"
    m_GalleryItem->setTitle(qtTrId("qtn_wall_pick_from_gallery"));
}

void
WallpaperWidget::oviActivated ()
{
    SYS_DEBUG ("Executing %s", oviCommand);
    system (oviCommand);
}

void
WallpaperWidget::galleryActivated ()
{
    SYS_DEBUG ("");
    if (m_noImageBrowser) {
            SelectSingleContentItemPage *imageBrowser = new SelectSingleContentItemPage(QString(), QStringList() << "http://www.semanticdesktop.org/ontologies/2007/03/22/nfo#Image", QString());
            imageBrowser->setObjectName("SelectSingleContentItemPage_imageBrowser");
            QObject::connect(imageBrowser, SIGNAL(backButtonClicked()), imageBrowser, SLOT(dismiss()));
            QObject::connect(imageBrowser, SIGNAL(backButtonClicked()), this, SLOT(imageBrowserDismissed()));
            QObject::connect(imageBrowser, SIGNAL(selectingContentItem(const QString &)), this, SLOT(galleryImageSelected(const QString &)));
            imageBrowser->appear(MSceneWindow::DestroyWhenDismissed);
            m_noImageBrowser = false;
    }
}

void WallpaperWidget::galleryImageSelected(const QString &uri)
{
    m_WallpaperBusinessLogic->addImageFromGallery(uri);
}

void WallpaperWidget::imageBrowserDismissed()
{
    m_noImageBrowser = true;
}
<|endoftext|>


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

#include "itkAnnulusOperator.h"
#include "itkBackwardDifferenceOperator.h"
#include "itkDerivativeOperator.h"
#include "itkForwardDifferenceOperator.h"
#include "itkGaussianDerivativeOperator.h"
#include "itkGaussianOperator.h"
#include "itkImageKernelOperator.h"
#include "itkLaplacianOperator.h"
#include "itkNeighborhoodOperator.h"
#include "itkSobelOperator.h"
#include "itkTestingMacros.h"

#include <type_traits> // For is_default_constructible, is_copy_constructible, etc.

namespace
{
template <typename T>
constexpr bool
IsDefaultConstructibleCopyableNoThrowMovableAndDestructible()
{
  return std::is_default_constructible<T>::value && std::is_copy_constructible<T>::value &&
         std::is_copy_assignable<T>::value && std::is_nothrow_move_constructible<T>::value &&
         std::is_nothrow_move_assignable<T>::value && std::is_nothrow_destructible<T>::value;
}

static_assert(std::is_copy_assignable<itk::NeighborhoodOperator<int, 3>>::value,
              "NeighborhoodOperator should be copy-assignable.");
static_assert(std::is_nothrow_move_assignable<itk::NeighborhoodOperator<int, 3>>::value,
              "NeighborhoodOperator should be noexcept move-assignable.");

static_assert(IsDefaultConstructibleCopyableNoThrowMovableAndDestructible<itk::AnnulusOperator<int>>(),
              "AnnulusOperator should be default-constructible, copyable, noexcept movable, and destructible.");
static_assert(
  IsDefaultConstructibleCopyableNoThrowMovableAndDestructible<itk::BackwardDifferenceOperator<int>>(),
  "BackwardDifferenceOperator should be default-constructible, copyable, noexcept movable, and destructible.");
static_assert(IsDefaultConstructibleCopyableNoThrowMovableAndDestructible<itk::DerivativeOperator<int>>(),
              "DerivativeOperator should be default-constructible, copyable, noexcept movable, and destructible.");
static_assert(
  IsDefaultConstructibleCopyableNoThrowMovableAndDestructible<itk::ForwardDifferenceOperator<int>>(),
  "ForwardDifferenceOperator should be default-constructible, copyable, noexcept movable, and destructible.");
static_assert(
  IsDefaultConstructibleCopyableNoThrowMovableAndDestructible<itk::GaussianDerivativeOperator<int>>(),
  "GaussianDerivativeOperator should be default-constructible, copyable, noexcept movable, and destructible.");
static_assert(IsDefaultConstructibleCopyableNoThrowMovableAndDestructible<itk::GaussianOperator<int>>(),
              "GaussianOperator should be default-constructible, copyable, noexcept movable, and destructible.");
static_assert(IsDefaultConstructibleCopyableNoThrowMovableAndDestructible<itk::ImageKernelOperator<int>>(),
              "ImageKernelOperator should be default-constructible, copyable, noexcept movable, and destructible.");
static_assert(IsDefaultConstructibleCopyableNoThrowMovableAndDestructible<itk::LaplacianOperator<int>>(),
              "LaplacianOperator should be default-constructible, copyable, noexcept movable, and destructible.");
static_assert(IsDefaultConstructibleCopyableNoThrowMovableAndDestructible<itk::SobelOperator<int>>(),
              "SobelOperator should be default-constructible, copyable, noexcept movable, and destructible.");
} // namespace

int
itkNeighborhoodOperatorTest(int, char *[])
{
  using PixelType = float;
  constexpr unsigned int Dimension1D = 1;
  constexpr unsigned int Dimension2D = 2;
  constexpr unsigned int Dimension3D = 3;
  constexpr unsigned int Dimension4D = 4;

  std::cout << "Testing derivative operator" << std::endl;
  itk::DerivativeOperator<PixelType, Dimension3D, vnl_vector<PixelType>> d;

  ITK_EXERCISE_BASIC_OBJECT_METHODS((&d), DerivativeOperator, NeighborhoodOperator);

  const unsigned int order = 2;
  d.SetOrder(order);
  ITK_TEST_SET_GET_VALUE(order, d.GetOrder());

  unsigned long direction = 1;
  d.SetDirection(direction);
  ITK_TEST_SET_GET_VALUE(direction, d.GetDirection());

  d.CreateDirectional();

  std::cout << "Testing Gaussian operator" << std::endl;
  itk::GaussianOperator<PixelType, Dimension2D, vnl_vector<PixelType>> g;

  ITK_EXERCISE_BASIC_OBJECT_METHODS((&g), GaussianOperator, NeighborhoodOperator);

  const double variance = 2.3;
  g.SetVariance(variance);
  ITK_TEST_SET_GET_VALUE(variance, g.GetVariance());

  const double maximumError = .01;
  g.SetMaximumError(maximumError);
  ITK_TEST_SET_GET_VALUE(maximumError, g.GetMaximumError());

  g.CreateDirectional();

  std::cout << "Testing ForwardDifferenceOperator" << std::endl;
  itk::ForwardDifferenceOperator<PixelType, Dimension4D, vnl_vector<PixelType>> f;

  ITK_EXERCISE_BASIC_OBJECT_METHODS((&f), ForwardDifferenceOperator, NeighborhoodOperator);

  direction = 2;
  f.SetDirection(direction);
  ITK_TEST_SET_GET_VALUE(direction, f.GetDirection());

  itk::Size<4> sz;
  sz[0] = sz[1] = sz[2] = sz[3] = 2;
  f.CreateToRadius(sz);

  std::cout << "Testing BackwardDifferenceOperator" << std::endl;
  itk::BackwardDifferenceOperator<PixelType, Dimension2D, vnl_vector<PixelType>> b;

  ITK_EXERCISE_BASIC_OBJECT_METHODS((&b), BackwardDifferenceOperator, NeighborhoodOperator);

  direction = 0;
  b.SetDirection(direction);
  ITK_TEST_SET_GET_VALUE(direction, b.GetDirection());

  b.CreateDirectional();

  std::cout << "Testing 1D LaplacianOperator" << std::endl;
  itk::LaplacianOperator<PixelType, Dimension1D, vnl_vector<PixelType>> a1;

  ITK_EXERCISE_BASIC_OBJECT_METHODS((&a1), LaplacianOperator, NeighborhoodOperator);

  const double scales_1d[] = { 1.0 / 2.0 };
  a1.SetDerivativeScalings(scales_1d);
  ITK_TEST_SET_GET_VALUE(*scales_1d, *(a1.GetDerivativeScalings()));

  a1.CreateOperator();

  std::cout << "    Operator = [ ";
  for (unsigned int i = 0; i < a1.Size(); ++i)
  {
    std::cout << a1[i];
    if (i < a1.Size() - 1)
    {
      std::cout << ", ";
    }
  }
  std::cout << "]" << std::endl << std::endl;

  std::cout << "Testing 2D LaplacianOperator" << std::endl;
  itk::LaplacianOperator<PixelType, Dimension2D, vnl_vector<PixelType>> a2;

  const double scales_2d[Dimension2D] = { 1.0 / 2.0, 1.0 / 4.0 };
  a2.SetDerivativeScalings(scales_2d);
  ITK_TEST_SET_GET_VALUE(*scales_2d, *(a2.GetDerivativeScalings()));

  a2.CreateOperator();

  std::cout << "    Operator = [ ";
  for (unsigned int i = 0; i < a2.Size(); ++i)
  {
    std::cout << a2[i];
    if (i < a2.Size() - 1)
    {
      std::cout << ", ";
    }
  }
  std::cout << "]" << std::endl << std::endl;

  std::cout << "Testing 3D LaplacianOperator" << std::endl;
  itk::LaplacianOperator<PixelType, Dimension3D, vnl_vector<PixelType>> a3;

  const double scales_3d[Dimension3D] = { 1.0 / 2.0, 1.0 / 4.0, 1.0 / 5.0 };
  a3.SetDerivativeScalings(scales_3d);
  ITK_TEST_SET_GET_VALUE(*scales_3d, *(a3.GetDerivativeScalings()));

  a3.CreateOperator();

  std::cout << "    Operator = [ ";
  for (unsigned int i = 0; i < a3.Size(); ++i)
  {
    std::cout << a3[i];
    if (i < a3.Size() - 1)
    {
      std::cout << ", ";
    }
  }
  std::cout << "]" << std::endl << std::endl;

  std::cout << "Testing SobelOperator2D" << std::endl;
  itk::SobelOperator<PixelType, Dimension2D, vnl_vector<PixelType>> c;

  ITK_EXERCISE_BASIC_OBJECT_METHODS((&c), SobelOperator, NeighborhoodOperator);

  direction = 0;
  c.SetDirection(direction);
  ITK_TEST_SET_GET_VALUE(direction, c.GetDirection());

  c.CreateDirectional();

  std::cout << "    Operator = [ ";
  for (unsigned int i = 0; i < c.Size(); ++i)
  {
    std::cout << c[i];
    if (i < c.Size() - 1)
    {
      std::cout << ", ";
    }
  }
  std::cout << "]" << std::endl << std::endl;

  direction = 1;
  c.SetDirection(direction);
  ITK_TEST_SET_GET_VALUE(direction, c.GetDirection());

  c.CreateDirectional();

  std::cout << "    Operator = [ ";
  for (unsigned int i = 0; i < c.Size(); ++i)
  {
    std::cout << c[i];
    if (i < c.Size() - 1)
    {
      std::cout << ", ";
    }
  }
  std::cout << "]" << std::endl << std::endl;

  std::cout << "Testing SobelOperator3D" << std::endl;
  itk::SobelOperator<PixelType, Dimension3D, vnl_vector<PixelType>> c2;

  direction = 0;
  c2.SetDirection(direction);
  ITK_TEST_SET_GET_VALUE(direction, c2.GetDirection());

  c2.CreateDirectional();

  std::cout << "    Operator = [ ";
  for (unsigned int i = 0; i < c2.Size(); ++i)
  {
    std::cout << c2[i];
    if (i < c2.Size() - 1)
    {
      std::cout << ", ";
    }
  }
  std::cout << "]" << std::endl << std::endl;

  direction = 1;
  c2.SetDirection(direction);
  ITK_TEST_SET_GET_VALUE(direction, c2.GetDirection());

  c2.CreateDirectional();

  std::cout << "    Operator = [ ";
  for (unsigned int i = 0; i < c2.Size(); ++i)
  {
    std::cout << c2[i];
    if (i < c2.Size() - 1)
    {
      std::cout << ", ";
    }
  }
  std::cout << "]" << std::endl << std::endl;

  direction = 2;
  c2.SetDirection(direction);
  ITK_TEST_SET_GET_VALUE(direction, c2.GetDirection());

  c2.CreateDirectional();

  std::cout << "    Operator = [ ";
  for (unsigned int i = 0; i < c2.Size(); ++i)
  {
    std::cout << c2[i];
    if (i < c2.Size() - 1)
    {
      std::cout << ", ";
    }
  }
  std::cout << "]" << std::endl << std::endl;

  std::cout << "Test finished." << std::endl;
  return EXIT_SUCCESS;
}
<commit_msg>STYLE: Prefer implicitly deriving array size in test<commit_after>/*=========================================================================
 *
 *  Copyright NumFOCUS
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "itkAnnulusOperator.h"
#include "itkBackwardDifferenceOperator.h"
#include "itkDerivativeOperator.h"
#include "itkForwardDifferenceOperator.h"
#include "itkGaussianDerivativeOperator.h"
#include "itkGaussianOperator.h"
#include "itkImageKernelOperator.h"
#include "itkLaplacianOperator.h"
#include "itkNeighborhoodOperator.h"
#include "itkSobelOperator.h"
#include "itkTestingMacros.h"

#include <type_traits> // For is_default_constructible, is_copy_constructible, etc.

namespace
{
template <typename T>
constexpr bool
IsDefaultConstructibleCopyableNoThrowMovableAndDestructible()
{
  return std::is_default_constructible<T>::value && std::is_copy_constructible<T>::value &&
         std::is_copy_assignable<T>::value && std::is_nothrow_move_constructible<T>::value &&
         std::is_nothrow_move_assignable<T>::value && std::is_nothrow_destructible<T>::value;
}

static_assert(std::is_copy_assignable<itk::NeighborhoodOperator<int, 3>>::value,
              "NeighborhoodOperator should be copy-assignable.");
static_assert(std::is_nothrow_move_assignable<itk::NeighborhoodOperator<int, 3>>::value,
              "NeighborhoodOperator should be noexcept move-assignable.");

static_assert(IsDefaultConstructibleCopyableNoThrowMovableAndDestructible<itk::AnnulusOperator<int>>(),
              "AnnulusOperator should be default-constructible, copyable, noexcept movable, and destructible.");
static_assert(
  IsDefaultConstructibleCopyableNoThrowMovableAndDestructible<itk::BackwardDifferenceOperator<int>>(),
  "BackwardDifferenceOperator should be default-constructible, copyable, noexcept movable, and destructible.");
static_assert(IsDefaultConstructibleCopyableNoThrowMovableAndDestructible<itk::DerivativeOperator<int>>(),
              "DerivativeOperator should be default-constructible, copyable, noexcept movable, and destructible.");
static_assert(
  IsDefaultConstructibleCopyableNoThrowMovableAndDestructible<itk::ForwardDifferenceOperator<int>>(),
  "ForwardDifferenceOperator should be default-constructible, copyable, noexcept movable, and destructible.");
static_assert(
  IsDefaultConstructibleCopyableNoThrowMovableAndDestructible<itk::GaussianDerivativeOperator<int>>(),
  "GaussianDerivativeOperator should be default-constructible, copyable, noexcept movable, and destructible.");
static_assert(IsDefaultConstructibleCopyableNoThrowMovableAndDestructible<itk::GaussianOperator<int>>(),
              "GaussianOperator should be default-constructible, copyable, noexcept movable, and destructible.");
static_assert(IsDefaultConstructibleCopyableNoThrowMovableAndDestructible<itk::ImageKernelOperator<int>>(),
              "ImageKernelOperator should be default-constructible, copyable, noexcept movable, and destructible.");
static_assert(IsDefaultConstructibleCopyableNoThrowMovableAndDestructible<itk::LaplacianOperator<int>>(),
              "LaplacianOperator should be default-constructible, copyable, noexcept movable, and destructible.");
static_assert(IsDefaultConstructibleCopyableNoThrowMovableAndDestructible<itk::SobelOperator<int>>(),
              "SobelOperator should be default-constructible, copyable, noexcept movable, and destructible.");
} // namespace

int
itkNeighborhoodOperatorTest(int, char *[])
{
  using PixelType = float;
  constexpr unsigned int Dimension1D = 1;
  constexpr unsigned int Dimension2D = 2;
  constexpr unsigned int Dimension3D = 3;
  constexpr unsigned int Dimension4D = 4;

  std::cout << "Testing derivative operator" << std::endl;
  itk::DerivativeOperator<PixelType, Dimension3D, vnl_vector<PixelType>> d;

  ITK_EXERCISE_BASIC_OBJECT_METHODS((&d), DerivativeOperator, NeighborhoodOperator);

  const unsigned int order = 2;
  d.SetOrder(order);
  ITK_TEST_SET_GET_VALUE(order, d.GetOrder());

  unsigned long direction = 1;
  d.SetDirection(direction);
  ITK_TEST_SET_GET_VALUE(direction, d.GetDirection());

  d.CreateDirectional();

  std::cout << "Testing Gaussian operator" << std::endl;
  itk::GaussianOperator<PixelType, Dimension2D, vnl_vector<PixelType>> g;

  ITK_EXERCISE_BASIC_OBJECT_METHODS((&g), GaussianOperator, NeighborhoodOperator);

  const double variance = 2.3;
  g.SetVariance(variance);
  ITK_TEST_SET_GET_VALUE(variance, g.GetVariance());

  const double maximumError = .01;
  g.SetMaximumError(maximumError);
  ITK_TEST_SET_GET_VALUE(maximumError, g.GetMaximumError());

  g.CreateDirectional();

  std::cout << "Testing ForwardDifferenceOperator" << std::endl;
  itk::ForwardDifferenceOperator<PixelType, Dimension4D, vnl_vector<PixelType>> f;

  ITK_EXERCISE_BASIC_OBJECT_METHODS((&f), ForwardDifferenceOperator, NeighborhoodOperator);

  direction = 2;
  f.SetDirection(direction);
  ITK_TEST_SET_GET_VALUE(direction, f.GetDirection());

  itk::Size<4> sz;
  sz[0] = sz[1] = sz[2] = sz[3] = 2;
  f.CreateToRadius(sz);

  std::cout << "Testing BackwardDifferenceOperator" << std::endl;
  itk::BackwardDifferenceOperator<PixelType, Dimension2D, vnl_vector<PixelType>> b;

  ITK_EXERCISE_BASIC_OBJECT_METHODS((&b), BackwardDifferenceOperator, NeighborhoodOperator);

  direction = 0;
  b.SetDirection(direction);
  ITK_TEST_SET_GET_VALUE(direction, b.GetDirection());

  b.CreateDirectional();

  std::cout << "Testing 1D LaplacianOperator" << std::endl;
  itk::LaplacianOperator<PixelType, Dimension1D, vnl_vector<PixelType>> a1;

  ITK_EXERCISE_BASIC_OBJECT_METHODS((&a1), LaplacianOperator, NeighborhoodOperator);

  const double scales_1d[] = { 1.0 / 2.0 };
  a1.SetDerivativeScalings(scales_1d);
  ITK_TEST_SET_GET_VALUE(*scales_1d, *(a1.GetDerivativeScalings()));

  a1.CreateOperator();

  std::cout << "    Operator = [ ";
  for (unsigned int i = 0; i < a1.Size(); ++i)
  {
    std::cout << a1[i];
    if (i < a1.Size() - 1)
    {
      std::cout << ", ";
    }
  }
  std::cout << "]" << std::endl << std::endl;

  std::cout << "Testing 2D LaplacianOperator" << std::endl;
  itk::LaplacianOperator<PixelType, Dimension2D, vnl_vector<PixelType>> a2;

  const double scales_2d[] = { 1.0 / 2.0, 1.0 / 4.0 };
  a2.SetDerivativeScalings(scales_2d);
  ITK_TEST_SET_GET_VALUE(*scales_2d, *(a2.GetDerivativeScalings()));

  a2.CreateOperator();

  std::cout << "    Operator = [ ";
  for (unsigned int i = 0; i < a2.Size(); ++i)
  {
    std::cout << a2[i];
    if (i < a2.Size() - 1)
    {
      std::cout << ", ";
    }
  }
  std::cout << "]" << std::endl << std::endl;

  std::cout << "Testing 3D LaplacianOperator" << std::endl;
  itk::LaplacianOperator<PixelType, Dimension3D, vnl_vector<PixelType>> a3;

  const double scales_3d[] = { 1.0 / 2.0, 1.0 / 4.0, 1.0 / 5.0 };
  a3.SetDerivativeScalings(scales_3d);
  ITK_TEST_SET_GET_VALUE(*scales_3d, *(a3.GetDerivativeScalings()));

  a3.CreateOperator();

  std::cout << "    Operator = [ ";
  for (unsigned int i = 0; i < a3.Size(); ++i)
  {
    std::cout << a3[i];
    if (i < a3.Size() - 1)
    {
      std::cout << ", ";
    }
  }
  std::cout << "]" << std::endl << std::endl;

  std::cout << "Testing SobelOperator2D" << std::endl;
  itk::SobelOperator<PixelType, Dimension2D, vnl_vector<PixelType>> c;

  ITK_EXERCISE_BASIC_OBJECT_METHODS((&c), SobelOperator, NeighborhoodOperator);

  direction = 0;
  c.SetDirection(direction);
  ITK_TEST_SET_GET_VALUE(direction, c.GetDirection());

  c.CreateDirectional();

  std::cout << "    Operator = [ ";
  for (unsigned int i = 0; i < c.Size(); ++i)
  {
    std::cout << c[i];
    if (i < c.Size() - 1)
    {
      std::cout << ", ";
    }
  }
  std::cout << "]" << std::endl << std::endl;

  direction = 1;
  c.SetDirection(direction);
  ITK_TEST_SET_GET_VALUE(direction, c.GetDirection());

  c.CreateDirectional();

  std::cout << "    Operator = [ ";
  for (unsigned int i = 0; i < c.Size(); ++i)
  {
    std::cout << c[i];
    if (i < c.Size() - 1)
    {
      std::cout << ", ";
    }
  }
  std::cout << "]" << std::endl << std::endl;

  std::cout << "Testing SobelOperator3D" << std::endl;
  itk::SobelOperator<PixelType, Dimension3D, vnl_vector<PixelType>> c2;

  direction = 0;
  c2.SetDirection(direction);
  ITK_TEST_SET_GET_VALUE(direction, c2.GetDirection());

  c2.CreateDirectional();

  std::cout << "    Operator = [ ";
  for (unsigned int i = 0; i < c2.Size(); ++i)
  {
    std::cout << c2[i];
    if (i < c2.Size() - 1)
    {
      std::cout << ", ";
    }
  }
  std::cout << "]" << std::endl << std::endl;

  direction = 1;
  c2.SetDirection(direction);
  ITK_TEST_SET_GET_VALUE(direction, c2.GetDirection());

  c2.CreateDirectional();

  std::cout << "    Operator = [ ";
  for (unsigned int i = 0; i < c2.Size(); ++i)
  {
    std::cout << c2[i];
    if (i < c2.Size() - 1)
    {
      std::cout << ", ";
    }
  }
  std::cout << "]" << std::endl << std::endl;

  direction = 2;
  c2.SetDirection(direction);
  ITK_TEST_SET_GET_VALUE(direction, c2.GetDirection());

  c2.CreateDirectional();

  std::cout << "    Operator = [ ";
  for (unsigned int i = 0; i < c2.Size(); ++i)
  {
    std::cout << c2[i];
    if (i < c2.Size() - 1)
    {
      std::cout << ", ";
    }
  }
  std::cout << "]" << std::endl << std::endl;

  std::cout << "Test finished." << std::endl;
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * 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.
 */

#ifndef otbGenericRSTransform_hxx
#define otbGenericRSTransform_hxx

#include "otbGenericRSTransform.h"
#include "otbMacro.h"
#include "otbMetaDataKey.h"
#include "itkMetaDataObject.h"

#include "otbSpatialReference.h"

#include "ogr_spatialref.h"

namespace otb
{

template<class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions>
GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>
::GenericRSTransform() : Superclass(0)
{
  m_InputProjectionRef.clear();
  m_OutputProjectionRef.clear();
  m_InputKeywordList.Clear();
  m_OutputKeywordList.Clear();
  m_InputSpacing.Fill(1);
  m_InputOrigin.Fill(0);
  m_OutputSpacing.Fill(1);
  m_OutputOrigin.Fill(0);

  m_Transform = nullptr;
  m_InputTransform = nullptr;
  m_OutputTransform = nullptr;
  m_TransformUpToDate = false;
  m_TransformAccuracy = Projection::UNKNOWN;
}

template<class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions>
const typename GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::TransformType*
GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>
::GetTransform() const
{
  itkDebugMacro("returning MapProjection address " << this->m_Transform);
  if ((!m_TransformUpToDate) || (m_Transform.IsNull()))
    {
    itkExceptionMacro(<< "m_Transform not up-to-date, call InstantiateTransform() first");
    }

  return this->m_Transform;
}

/**
 * Instantiate the transformation according to information
 */
template<class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions>
void
GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>
::InstantiateTransform(void)
{
  m_Transform = TransformType::New();

  if (m_InputKeywordList.GetSize()  == 0)
    {
    itk::ExposeMetaData<ImageKeywordlist>(m_InputDictionary, MetaDataKey::OSSIMKeywordlistKey, m_InputKeywordList);
    }
  if (m_InputProjectionRef.empty())
    {
    itk::ExposeMetaData<std::string>(m_InputDictionary, MetaDataKey::ProjectionRefKey, m_InputProjectionRef);
    }

  otbMsgDevMacro(<< "Information to instantiate transform: ");
  otbMsgDevMacro(<< " * Input Origin: " << m_InputOrigin);
  otbMsgDevMacro(<< " * Input Spacing: " << m_InputSpacing);
  otbMsgDevMacro(<< " * Input keyword list: "
                 << ((m_InputKeywordList.GetSize() == 0) ? "Empty" : "Full"));
  otbMsgDevMacro(<< " * Input projection: " << m_InputProjectionRef);
  otbMsgDevMacro(<< " * Output keyword list: "
                 << ((m_OutputKeywordList.GetSize() == 0) ? "Empty" : "Full"));
  otbMsgDevMacro(<< " * Output projection: " << m_OutputProjectionRef);
  otbMsgDevMacro(<< " * Output Origin: " << m_OutputOrigin);
  otbMsgDevMacro(<< " * Output Spacing: " << m_OutputSpacing);

  //Make sure that the state is clean:
  m_InputTransform = nullptr;
  m_OutputTransform = nullptr;

  bool inputTransformIsSensor = false;
  bool inputTransformIsMap = false;
  bool outputTransformIsSensor = false;
  bool outputTransformIsMap = false;

  //*****************************
  //Set the input transformation
  //*****************************

    // First, try to make a geo transform
  if (!m_InputProjectionRef.empty()) //map projection
    {
    typedef otb::GenericMapProjection<TransformDirection::INVERSE, ScalarType, InputSpaceDimension, InputSpaceDimension>
        InverseMapProjectionType;
    typename InverseMapProjectionType::Pointer mapTransform = InverseMapProjectionType::New();

    mapTransform->SetWkt(m_InputProjectionRef);
    if (mapTransform->IsProjectionDefined())
      {
      m_InputTransform = mapTransform.GetPointer();
      inputTransformIsMap = true;
      otbMsgDevMacro(<< "Input projection set to map transform: " << m_InputTransform);
      }
    }

  // If not, try to make a sensor model
  if ((m_InputTransform.IsNull()) && (m_InputKeywordList.GetSize() > 0))
    {
    typedef otb::ForwardSensorModel<double, InputSpaceDimension, InputSpaceDimension> ForwardSensorModelType;
    typename ForwardSensorModelType::Pointer sensorModel = ForwardSensorModelType::New();

    sensorModel->SetImageGeometry(m_InputKeywordList);

    if (sensorModel->IsValidSensorModel())
      {
      m_InputTransform = sensorModel.GetPointer();
      inputTransformIsSensor = true;
      otbMsgDevMacro(<< "Input projection set to sensor model.");
      }
    }

  if (m_InputTransform.IsNull()) //default if we didn't manage to instantiate it before
    {
    m_InputTransform = itk::IdentityTransform<double, NInputDimensions>::New();
    }

  //*****************************
  //Set the output transformation
  //*****************************
  if (!m_OutputProjectionRef.empty()) //map projection
    {
    typedef otb::GenericMapProjection<TransformDirection::FORWARD, ScalarType, InputSpaceDimension,
    OutputSpaceDimension> ForwardMapProjectionType;
    typename ForwardMapProjectionType::Pointer mapTransform = ForwardMapProjectionType::New();
    mapTransform->SetWkt(m_OutputProjectionRef);
    if (mapTransform->IsProjectionDefined())
      {
      m_OutputTransform = mapTransform.GetPointer();
      outputTransformIsMap = true;
      otbMsgDevMacro(<< "Output projection set to map transform: " << m_OutputTransform);
      }
    }

  // If not, try to make a sensor model
  if ((m_OutputTransform.IsNull()) && (m_OutputKeywordList.GetSize() > 0))
    {
    typedef otb::InverseSensorModel<double, InputSpaceDimension, OutputSpaceDimension> InverseSensorModelType;
    typename InverseSensorModelType::Pointer sensorModel = InverseSensorModelType::New();

    sensorModel->SetImageGeometry(m_OutputKeywordList);

    if (sensorModel->IsValidSensorModel())
      {
      m_OutputTransform = sensorModel.GetPointer();
      outputTransformIsSensor = true;
      otbMsgDevMacro(<< "Output projection set to sensor model");
      }
    }

  if (m_OutputTransform.IsNull()) //default if we didn't manage to instantiate it before
    {
    // In this case, if input transform is set, we set
    // outputProjectionRef to wgs84 to ensure consistency
    if(inputTransformIsSensor || inputTransformIsMap)
      {
      m_OutputProjectionRef = SpatialReference::FromWGS84().ToWkt();
      }

    m_OutputTransform = itk::IdentityTransform<double, NOutputDimensions>::New();
    otbMsgDevMacro(<< "Output projection set to identity");
    }

  m_Transform->SetFirstTransform(m_InputTransform);
  m_Transform->SetSecondTransform(m_OutputTransform);
  m_TransformUpToDate = true;

  //The accuracy information is a simplistic model for now and should be refined
  if ((inputTransformIsSensor || outputTransformIsSensor))
    {
    //Sensor model
    m_TransformAccuracy = Projection::ESTIMATE;
    }
  else if (!outputTransformIsSensor && !outputTransformIsMap)
    {
    //The original image was in lon/lat and we did not change anything
    m_TransformAccuracy = Projection::PRECISE;
    }
  else if (!inputTransformIsSensor && !outputTransformIsSensor && !inputTransformIsMap && !outputTransformIsMap)
    {
    //no transform
    m_TransformAccuracy = Projection::UNKNOWN;
    }
  else
    {
    m_TransformAccuracy = Projection::PRECISE;
    }

}

template<class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions>
typename GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::OutputPointType
GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>
::TransformPoint(const InputPointType& point) const
{
  InputPointType inputPoint = point;

  // Apply input origin/spacing
  inputPoint[0] = inputPoint[0] * m_InputSpacing[0] + m_InputOrigin[0];
  inputPoint[1] = inputPoint[1] * m_InputSpacing[1] + m_InputOrigin[1];

  // Transform point
  OutputPointType outputPoint;
  outputPoint = this->GetTransform()->TransformPoint(inputPoint);

  // Apply output origin/spacing
  outputPoint[0] = (outputPoint[0] - m_OutputOrigin[0]) / m_OutputSpacing[0];
  outputPoint[1] = (outputPoint[1] - m_OutputOrigin[1]) / m_OutputSpacing[1];

//  otbMsgDevMacro("GenericRSTransform: " << point << " -> " << outputPoint);

  return outputPoint;
}

template<class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions>
bool
GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>
::GetInverse(Self * inverseTransform) const
{
  // Test the inverseTransform pointer
  if (inverseTransform == nullptr)
    {
    return false;
    }

  // Swich projection refs
  inverseTransform->SetInputProjectionRef(m_OutputProjectionRef);
  inverseTransform->SetOutputProjectionRef(m_InputProjectionRef);

  // Switch keywordlists
  inverseTransform->SetInputKeywordList(m_OutputKeywordList);
  inverseTransform->SetOutputKeywordList(m_InputKeywordList);

  // Switch dictionnaries
  inverseTransform->SetInputDictionary(m_OutputDictionary);
  inverseTransform->SetOutputDictionary(m_InputDictionary);

  // Switch spacings
  inverseTransform->SetInputSpacing(m_OutputSpacing);
  inverseTransform->SetOutputSpacing(m_InputSpacing);

  // Switch origins
  inverseTransform->SetInputOrigin(m_OutputOrigin);
  inverseTransform->SetOutputOrigin(m_InputOrigin);

  // Instantiate transform
  inverseTransform->InstantiateTransform();

  return true;
}

template<class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions>
typename GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>
::InverseTransformBasePointer
GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>
::GetInverseTransform() const
{
  Self * inverseTransform = Self::New();

  bool success = this->GetInverse(inverseTransform);

  if (!success)
    {
    itkExceptionMacro(<< "Failed to create inverse transform");
    }

  return inverseTransform;
}

template<class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions>
void
GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>
::PrintSelf(std::ostream& os, itk::Indent indent) const
{
  Superclass::PrintSelf(os, indent);
  os << indent << "Up to date: " << m_TransformUpToDate << std::endl;
  if (m_TransformUpToDate)
    {
    os << indent << "Input transform: "<< std::endl;
    m_InputTransform->Print(os, indent.GetNextIndent());
    os << indent << "Output transform: " << std::endl;
    m_OutputTransform->Print(os, indent.GetNextIndent());
    }
  else
    {
    os << indent << "Input transform: NULL" << std::endl;
    os << indent << "Output transform: NULL" << std::endl;
    }
  os << indent << "Accuracy: "
      << (m_TransformAccuracy == Projection::PRECISE ?
                "PRECISE" : (m_TransformAccuracy == Projection::ESTIMATE ?
                                  "ESTIMATE" : "UNKNOWN")) << std::endl;
}

} // namespace otb

#endif
<commit_msg>ENH: Symmetric computation of default wkt<commit_after>/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * 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.
 */

#ifndef otbGenericRSTransform_hxx
#define otbGenericRSTransform_hxx

#include "otbGenericRSTransform.h"
#include "otbMacro.h"
#include "otbMetaDataKey.h"
#include "itkMetaDataObject.h"

#include "otbSpatialReference.h"

#include "ogr_spatialref.h"

namespace otb
{

template<class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions>
GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>
::GenericRSTransform() : Superclass(0)
{
  m_InputProjectionRef.clear();
  m_OutputProjectionRef.clear();
  m_InputKeywordList.Clear();
  m_OutputKeywordList.Clear();
  m_InputSpacing.Fill(1);
  m_InputOrigin.Fill(0);
  m_OutputSpacing.Fill(1);
  m_OutputOrigin.Fill(0);

  m_Transform = nullptr;
  m_InputTransform = nullptr;
  m_OutputTransform = nullptr;
  m_TransformUpToDate = false;
  m_TransformAccuracy = Projection::UNKNOWN;
}

template<class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions>
const typename GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::TransformType*
GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>
::GetTransform() const
{
  itkDebugMacro("returning MapProjection address " << this->m_Transform);
  if ((!m_TransformUpToDate) || (m_Transform.IsNull()))
    {
    itkExceptionMacro(<< "m_Transform not up-to-date, call InstantiateTransform() first");
    }

  return this->m_Transform;
}

/**
 * Instantiate the transformation according to information
 */
template<class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions>
void
GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>
::InstantiateTransform(void)
{
  m_Transform = TransformType::New();

  if (m_InputKeywordList.GetSize()  == 0)
    {
    itk::ExposeMetaData<ImageKeywordlist>(m_InputDictionary, MetaDataKey::OSSIMKeywordlistKey, m_InputKeywordList);
    }
  if (m_InputProjectionRef.empty())
    {
    itk::ExposeMetaData<std::string>(m_InputDictionary, MetaDataKey::ProjectionRefKey, m_InputProjectionRef);
    }

  otbMsgDevMacro(<< "Information to instantiate transform: ");
  otbMsgDevMacro(<< " * Input Origin: " << m_InputOrigin);
  otbMsgDevMacro(<< " * Input Spacing: " << m_InputSpacing);
  otbMsgDevMacro(<< " * Input keyword list: "
                 << ((m_InputKeywordList.GetSize() == 0) ? "Empty" : "Full"));
  otbMsgDevMacro(<< " * Input projection: " << m_InputProjectionRef);
  otbMsgDevMacro(<< " * Output keyword list: "
                 << ((m_OutputKeywordList.GetSize() == 0) ? "Empty" : "Full"));
  otbMsgDevMacro(<< " * Output projection: " << m_OutputProjectionRef);
  otbMsgDevMacro(<< " * Output Origin: " << m_OutputOrigin);
  otbMsgDevMacro(<< " * Output Spacing: " << m_OutputSpacing);

  //Make sure that the state is clean:
  m_InputTransform = nullptr;
  m_OutputTransform = nullptr;

  bool inputTransformIsSensor = false;
  bool inputTransformIsMap = false;
  bool outputTransformIsSensor = false;
  bool outputTransformIsMap = false;

  //*****************************
  //Set the input transformation
  //*****************************

  // First, try to make a geo transform
  if (!m_InputProjectionRef.empty()) //map projection
    {
    typedef otb::GenericMapProjection<TransformDirection::INVERSE, ScalarType, InputSpaceDimension, InputSpaceDimension>
        InverseMapProjectionType;
    typename InverseMapProjectionType::Pointer mapTransform = InverseMapProjectionType::New();

    mapTransform->SetWkt(m_InputProjectionRef);
    if (mapTransform->IsProjectionDefined())
      {
      m_InputTransform = mapTransform.GetPointer();
      inputTransformIsMap = true;
      otbMsgDevMacro(<< "Input projection set to map transform: " << m_InputTransform);
      }
    }

  // If not, try to make a sensor model
  if ((m_InputTransform.IsNull()) && (m_InputKeywordList.GetSize() > 0))
    {
    typedef otb::ForwardSensorModel<double, InputSpaceDimension, InputSpaceDimension> ForwardSensorModelType;
    typename ForwardSensorModelType::Pointer sensorModel = ForwardSensorModelType::New();

    sensorModel->SetImageGeometry(m_InputKeywordList);

    if (sensorModel->IsValidSensorModel())
      {
      m_InputTransform = sensorModel.GetPointer();
      inputTransformIsSensor = true;
      otbMsgDevMacro(<< "Input projection set to sensor model.");
      }
    }

  //*****************************
  //Set the output transformation
  //*****************************
  if (!m_OutputProjectionRef.empty()) //map projection
    {
    typedef otb::GenericMapProjection<TransformDirection::FORWARD, ScalarType, InputSpaceDimension,
    OutputSpaceDimension> ForwardMapProjectionType;
    typename ForwardMapProjectionType::Pointer mapTransform = ForwardMapProjectionType::New();
    mapTransform->SetWkt(m_OutputProjectionRef);
    if (mapTransform->IsProjectionDefined())
      {
      m_OutputTransform = mapTransform.GetPointer();
      outputTransformIsMap = true;
      otbMsgDevMacro(<< "Output projection set to map transform: " << m_OutputTransform);
      }
    }

  // If not, try to make a sensor model
  if ((m_OutputTransform.IsNull()) && (m_OutputKeywordList.GetSize() > 0))
    {
    typedef otb::InverseSensorModel<double, InputSpaceDimension, OutputSpaceDimension> InverseSensorModelType;
    typename InverseSensorModelType::Pointer sensorModel = InverseSensorModelType::New();

    sensorModel->SetImageGeometry(m_OutputKeywordList);

    if (sensorModel->IsValidSensorModel())
      {
      m_OutputTransform = sensorModel.GetPointer();
      outputTransformIsSensor = true;
      otbMsgDevMacro(<< "Output projection set to sensor model");
      }
    }

  if (m_InputTransform.IsNull()) //default if we didn't manage to instantiate it before
    {
    // In this case, if output transform is set, we set
    // inputProjectionRef to wgs84 to ensure consistency
    if(outputTransformIsSensor || outputTransformIsMap)
      {
      m_InputProjectionRef = SpatialReference::FromWGS84().ToWkt();
      }

    m_InputTransform = itk::IdentityTransform<double, NInputDimensions>::New();
    }

  if (m_OutputTransform.IsNull()) //default if we didn't manage to instantiate it before
    {
    // In this case, if input transform is set, we set
    // outputProjectionRef to wgs84 to ensure consistency
    if(inputTransformIsSensor || inputTransformIsMap)
      {
      m_OutputProjectionRef = SpatialReference::FromWGS84().ToWkt();
      }

    m_OutputTransform = itk::IdentityTransform<double, NOutputDimensions>::New();
    otbMsgDevMacro(<< "Output projection set to identity");
    }

  m_Transform->SetFirstTransform(m_InputTransform);
  m_Transform->SetSecondTransform(m_OutputTransform);
  m_TransformUpToDate = true;

  //The accuracy information is a simplistic model for now and should be refined
  if ((inputTransformIsSensor || outputTransformIsSensor))
    {
    //Sensor model
    m_TransformAccuracy = Projection::ESTIMATE;
    }
  else if (!outputTransformIsSensor && !outputTransformIsMap)
    {
    //The original image was in lon/lat and we did not change anything
    m_TransformAccuracy = Projection::PRECISE;
    }
  else if (!inputTransformIsSensor && !outputTransformIsSensor && !inputTransformIsMap && !outputTransformIsMap)
    {
    //no transform
    m_TransformAccuracy = Projection::UNKNOWN;
    }
  else
    {
    m_TransformAccuracy = Projection::PRECISE;
    }

}

template<class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions>
typename GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>::OutputPointType
GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>
::TransformPoint(const InputPointType& point) const
{
  InputPointType inputPoint = point;

  // Apply input origin/spacing
  inputPoint[0] = inputPoint[0] * m_InputSpacing[0] + m_InputOrigin[0];
  inputPoint[1] = inputPoint[1] * m_InputSpacing[1] + m_InputOrigin[1];

  // Transform point
  OutputPointType outputPoint;
  outputPoint = this->GetTransform()->TransformPoint(inputPoint);

  // Apply output origin/spacing
  outputPoint[0] = (outputPoint[0] - m_OutputOrigin[0]) / m_OutputSpacing[0];
  outputPoint[1] = (outputPoint[1] - m_OutputOrigin[1]) / m_OutputSpacing[1];

//  otbMsgDevMacro("GenericRSTransform: " << point << " -> " << outputPoint);

  return outputPoint;
}

template<class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions>
bool
GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>
::GetInverse(Self * inverseTransform) const
{
  // Test the inverseTransform pointer
  if (inverseTransform == nullptr)
    {
    return false;
    }

  // Swich projection refs
  inverseTransform->SetInputProjectionRef(m_OutputProjectionRef);
  inverseTransform->SetOutputProjectionRef(m_InputProjectionRef);

  // Switch keywordlists
  inverseTransform->SetInputKeywordList(m_OutputKeywordList);
  inverseTransform->SetOutputKeywordList(m_InputKeywordList);

  // Switch dictionnaries
  inverseTransform->SetInputDictionary(m_OutputDictionary);
  inverseTransform->SetOutputDictionary(m_InputDictionary);

  // Switch spacings
  inverseTransform->SetInputSpacing(m_OutputSpacing);
  inverseTransform->SetOutputSpacing(m_InputSpacing);

  // Switch origins
  inverseTransform->SetInputOrigin(m_OutputOrigin);
  inverseTransform->SetOutputOrigin(m_InputOrigin);

  // Instantiate transform
  inverseTransform->InstantiateTransform();

  return true;
}

template<class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions>
typename GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>
::InverseTransformBasePointer
GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>
::GetInverseTransform() const
{
  Self * inverseTransform = Self::New();

  bool success = this->GetInverse(inverseTransform);

  if (!success)
    {
    itkExceptionMacro(<< "Failed to create inverse transform");
    }

  return inverseTransform;
}

template<class TScalarType, unsigned int NInputDimensions, unsigned int NOutputDimensions>
void
GenericRSTransform<TScalarType, NInputDimensions, NOutputDimensions>
::PrintSelf(std::ostream& os, itk::Indent indent) const
{
  Superclass::PrintSelf(os, indent);
  os << indent << "Up to date: " << m_TransformUpToDate << std::endl;
  if (m_TransformUpToDate)
    {
    os << indent << "Input transform: "<< std::endl;
    m_InputTransform->Print(os, indent.GetNextIndent());
    os << indent << "Output transform: " << std::endl;
    m_OutputTransform->Print(os, indent.GetNextIndent());
    }
  else
    {
    os << indent << "Input transform: NULL" << std::endl;
    os << indent << "Output transform: NULL" << std::endl;
    }
  os << indent << "Accuracy: "
      << (m_TransformAccuracy == Projection::PRECISE ?
                "PRECISE" : (m_TransformAccuracy == Projection::ESTIMATE ?
                                  "ESTIMATE" : "UNKNOWN")) << std::endl;
}

} // namespace otb

#endif
<|endoftext|>