<commit_before>#include "GeometryBuilderGeant4Module.hpp"

#include <cassert>
#include <memory>
#include <string>
#include <utility>

#include <G4RunManager.hh>
#include <G4UImanager.hh>
#include <G4UIterminal.hh>
#include <G4VisExecutive.hh>
#include <G4VisManager.hh>

#include <Math/EulerAngles.h>
#include <Math/Vector3D.h>

#include "GeometryConstructionG4.hpp"

#include "tools/ROOT.h"
#include "tools/geant4.h"

#include "core/config/ConfigReader.hpp"
#include "core/config/exceptions.h"
#include "core/geometry/GeometryManager.hpp"
#include "core/utils/log.h"

// temporary common includes
#include "modules/common/DetectorModelG4.hpp"
#include "modules/common/ReadGeoDescription.hpp"

using namespace allpix;
using namespace ROOT;

// constructor and destructor
GeometryBuilderGeant4Module::GeometryBuilderGeant4Module(Configuration config, Messenger*, GeometryManager* geo_manager)
    : config_(std::move(config)), geo_manager_(geo_manager), run_manager_g4_(nullptr) {
    // construct the internal geometry
    // WARNING: we need to do this here to allow for proper instantiation (initialization is only run after loading)
    // FIXME: move this to a separate module or the core?

    LOG(INFO) << "Constructing internal geometry";
    // read the models
    std::vector<std::string> model_paths;
    if(config_.has("model_paths")) {
        model_paths = config_.getPathArray("model_paths", true);
    }
    auto geo_descriptions = ReadGeoDescription(model_paths);

    // construct the detectors from the config file
    std::string detector_file_name = config_.getPath("detectors_file", true);
    std::ifstream file(detector_file_name);
    ConfigReader detector_config(file, detector_file_name);

    // add the configurations to the detectors
    for(auto& detector_section : detector_config.getConfigurations()) {
        std::shared_ptr<DetectorModel> detector_model =
            geo_descriptions.getDetectorModel(detector_section.get<std::string>("type"));

        // check if detector model is defined
        if(detector_model == nullptr) {
            throw InvalidValueError(detector_section, "type", "detector type does not exist in registered models");
        }

        // get the position and orientation
        auto position = detector_section.get<Math::XYZPoint>("position", Math::XYZPoint());
        auto orientation = detector_section.get<Math::EulerAngles>("orientation", Math::EulerAngles());

        // create the detector and add it
        auto detector = std::make_shared<Detector>(detector_section.getName(), detector_model, position, orientation);
        geo_manager_->addDetector(detector);
    }
}
GeometryBuilderGeant4Module::~GeometryBuilderGeant4Module() = default;

// check geant4 environment variable
inline static void check_dataset_g4(const std::string& env_name) {
    const char* file_name = std::getenv(env_name.c_str());
    if(file_name == nullptr) {
        throw ModuleError("Geant4 environment variable " + env_name + " is not set, make sure to source a Geant4 "
                                                                      "environment with all datasets");
    }
    std::ifstream file(file_name);
    if(!file.good()) {
        throw ModuleError("Geant4 environment variable " + env_name + " does not point to existing dataset, your Geant4 "
                                                                      "environment is not complete");
    }
    // FIXME: check if file does actually contain a correct dataset
}

// create the run manager, check Geant4 state and construct the Geant4 geometry
void GeometryBuilderGeant4Module::init() {
    // suppress all output (also cout due to a part in Geant4 where G4cout is not used)
    SUPPRESS_STREAM(std::cout);
    SUPPRESS_STREAM(G4cout);

    // create the G4 run manager
    run_manager_g4_ = std::make_unique<G4RunManager>();

    // release stdout again
    RELEASE_STREAM(std::cout);

    // check if all the required geant4 datasets are defined
    LOG(DEBUG) << "checking Geant4 datasets";
    check_dataset_g4("G4LEVELGAMMADATA");
    check_dataset_g4("G4RADIOACTIVEDATA");
    check_dataset_g4("G4PIIDATA");
    check_dataset_g4("G4SAIDXSDATA");
    check_dataset_g4("G4ABLADATA");
    check_dataset_g4("G4REALSURFACEDATA");
    check_dataset_g4("G4NEUTRONHPDATA");
    check_dataset_g4("G4NEUTRONXSDATA");
    check_dataset_g4("G4ENSDFSTATEDATA");
    check_dataset_g4("G4LEDATA");

    // get the world size
    config_.setDefault("world_size", G4ThreeVector(1000, 1000, 2000));
    G4ThreeVector world_size = config_.get<G4ThreeVector>("world_size");
    auto simple_view = config_.get<bool>("simple_view", false);

    // set the geometry constructor
    auto geometry_construction = new GeometryConstructionG4(geo_manager_, world_size, simple_view);
    run_manager_g4_->SetUserInitialization(geometry_construction);

    // run the geometry construct function in GeometryConstructionG4
    LOG(INFO) << "Building Geant4 geometry";
    run_manager_g4_->InitializeGeometry();

    // release output from G4
    RELEASE_STREAM(G4cout);
}
<commit_msg>Added export of the geometry in GDML.<commit_after>#include "GeometryBuilderGeant4Module.hpp"

#include <cassert>
#include <memory>
#include <string>
#include <utility>

#include <G4RunManager.hh>
#include <G4UImanager.hh>
#include <G4UIterminal.hh>
#include <G4VisExecutive.hh>
#include <G4VisManager.hh>

#include <Math/EulerAngles.h>
#include <Math/Vector3D.h>

#include "GeometryConstructionG4.hpp"

#include "tools/ROOT.h"
#include "tools/geant4.h"

#include "core/config/ConfigReader.hpp"
#include "core/config/exceptions.h"
#include "core/geometry/GeometryManager.hpp"
#include "core/utils/log.h"

// temporary common includes
#include "modules/common/DetectorModelG4.hpp"
#include "modules/common/ReadGeoDescription.hpp"

// GDML
#include "G4GDMLParser.hh"

using namespace allpix;
using namespace ROOT;

// constructor and destructor
GeometryBuilderGeant4Module::GeometryBuilderGeant4Module(Configuration config, Messenger*, GeometryManager* geo_manager)
    : config_(std::move(config)), geo_manager_(geo_manager), run_manager_g4_(nullptr) {
    // construct the internal geometry
    // WARNING: we need to do this here to allow for proper instantiation (initialization is only run after loading)
    // FIXME: move this to a separate module or the core?

    LOG(INFO) << "Constructing internal geometry";
    // read the models
    std::vector<std::string> model_paths;
    if(config_.has("model_paths")) {
        model_paths = config_.getPathArray("model_paths", true);
    }
    auto geo_descriptions = ReadGeoDescription(model_paths);

    // construct the detectors from the config file
    std::string detector_file_name = config_.getPath("detectors_file", true);
    std::ifstream file(detector_file_name);
    ConfigReader detector_config(file, detector_file_name);

    // add the configurations to the detectors
    for(auto& detector_section : detector_config.getConfigurations()) {
        std::shared_ptr<DetectorModel> detector_model =
            geo_descriptions.getDetectorModel(detector_section.get<std::string>("type"));

        // check if detector model is defined
        if(detector_model == nullptr) {
            throw InvalidValueError(detector_section, "type", "detector type does not exist in registered models");
        }

        // get the position and orientation
        auto position = detector_section.get<Math::XYZPoint>("position", Math::XYZPoint());
        auto orientation = detector_section.get<Math::EulerAngles>("orientation", Math::EulerAngles());

        // create the detector and add it
        auto detector = std::make_shared<Detector>(detector_section.getName(), detector_model, position, orientation);
        geo_manager_->addDetector(detector);
    }
}
GeometryBuilderGeant4Module::~GeometryBuilderGeant4Module() = default;

// check geant4 environment variable
inline static void check_dataset_g4(const std::string& env_name) {
    const char* file_name = std::getenv(env_name.c_str());
    if(file_name == nullptr) {
        throw ModuleError("Geant4 environment variable " + env_name + " is not set, make sure to source a Geant4 "
                                                                      "environment with all datasets");
    }
    std::ifstream file(file_name);
    if(!file.good()) {
        throw ModuleError("Geant4 environment variable " + env_name + " does not point to existing dataset, your Geant4 "
                                                                      "environment is not complete");
    }
    // FIXME: check if file does actually contain a correct dataset
}

// create the run manager, check Geant4 state and construct the Geant4 geometry
void GeometryBuilderGeant4Module::init() {
    // suppress all output (also cout due to a part in Geant4 where G4cout is not used)
    SUPPRESS_STREAM(std::cout);
    SUPPRESS_STREAM(G4cout);

    // create the G4 run manager
    run_manager_g4_ = std::make_unique<G4RunManager>();

    // release stdout again
    RELEASE_STREAM(std::cout);

    // check if all the required geant4 datasets are defined
    LOG(DEBUG) << "checking Geant4 datasets";
    check_dataset_g4("G4LEVELGAMMADATA");
    check_dataset_g4("G4RADIOACTIVEDATA");
    check_dataset_g4("G4PIIDATA");
    check_dataset_g4("G4SAIDXSDATA");
    check_dataset_g4("G4ABLADATA");
    check_dataset_g4("G4REALSURFACEDATA");
    check_dataset_g4("G4NEUTRONHPDATA");
    check_dataset_g4("G4NEUTRONXSDATA");
    check_dataset_g4("G4ENSDFSTATEDATA");
    check_dataset_g4("G4LEDATA");

    // get the world size
    config_.setDefault("world_size", G4ThreeVector(1000, 1000, 2000));
    G4ThreeVector world_size = config_.get<G4ThreeVector>("world_size");
    auto simple_view = config_.get<bool>("simple_view", false);

    // set the geometry constructor
    auto geometry_construction = new GeometryConstructionG4(geo_manager_, world_size, simple_view);
    run_manager_g4_->SetUserInitialization(geometry_construction);

    // run the geometry construct function in GeometryConstructionG4
    LOG(INFO) << "Building Geant4 geometry";
    run_manager_g4_->InitializeGeometry();

    // export geometry in GDML.
    if(true) {
        G4GDMLParser parser;
        /*
      G4GDMLAuxStructType mysubaux = {"mysubtype", "mysubvalue", "mysubunit", 0};
      G4GDMLAuxListType* myauxlist = new G4GDMLAuxListType();
      myauxlist->push_back(mysubaux);

      G4GDMLAuxStructType myaux = {"mytype", "myvalue", "myunit", myauxlist};
      parser.AddAuxiliary(myaux);

      // example of setting auxiliary info for world volume (can be set for any volume)

      G4GDMLAuxStructType mylocalaux = {"sometype", "somevalue", "someunit", 0};

      parser.AddVolumeAuxiliary(mylocalaux, G4TransportationManager::GetTransportationManager()
      ->GetNavigatorForTracking()->GetWorldVolume()->GetLogicalVolume());
        */
        std::string GDML_export_file = "Geometry.gdml";
        parser.SetRegionExport(true);
        parser.Write(GDML_export_file,
                     G4TransportationManager::GetTransportationManager()
                         ->GetNavigatorForTracking()
                         ->GetWorldVolume()
                         ->GetLogicalVolume());
    }

    // release output from G4
    RELEASE_STREAM(G4cout);
}
<|endoftext|>


<commit_before>/*
 * libqtxdg - An Qt implementation of freedesktop.org xdg specs
 * Copyright (C) 2016  Luís Pereira <luis.artur.pereira@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301  USA
 */

#include <QCoreApplication>
#include <QCommandLineParser>
#include <QFileInfo>

#include <XdgDesktopFile>

#include <iostream>

static void printErr(const QString & out)
{
    std::cerr << qPrintable(out);
}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    QCoreApplication::setApplicationName(QLatin1String("qtxdg-desktop-file-start"));
    QCoreApplication::setApplicationVersion(QLatin1String(QTXDG_VERSION));

    QCommandLineParser parser;
    parser.setApplicationDescription(QLatin1String("QtXdg XdgDesktopFile start Tester"));
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addPositionalArgument(QLatin1String("file [urls...]"), QLatin1String("desktop file to start and it's urls"),QLatin1String("file [urls...]"));
    parser.process(app);

    if (parser.positionalArguments().isEmpty()) {
        parser.showHelp(EXIT_FAILURE);
    }

    QStringList userArgs = parser.positionalArguments();
    const QString userFileName = userArgs.takeFirst();
    const QFileInfo fileInfo(userFileName);
    const QString canonicalFileName = fileInfo.canonicalFilePath();

    if (!fileInfo.exists()) {
        printErr(QString::fromLatin1("File %1 does not exist\n").arg(userFileName));
        return EXIT_FAILURE;
    }

    XdgDesktopFile f;
    const bool valid = f.load(canonicalFileName);
    if (valid) {
        f.startDetached(userArgs);
    } else {
        printErr(QString::fromLatin1("%1 is not a valid .desktop file\n").arg(canonicalFileName));
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
<commit_msg>qtxdg-desktop-file-start: Handle relative paths<commit_after>/*
 * libqtxdg - An Qt implementation of freedesktop.org xdg specs
 * Copyright (C) 2016  Luís Pereira <luis.artur.pereira@gmail.com>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301  USA
 */

#include <QCoreApplication>
#include <QCommandLineParser>
#include <QFileInfo>

#include <XdgDesktopFile>

#include <iostream>

static void printErr(const QString & out)
{
    std::cerr << qPrintable(out);
}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    QCoreApplication::setApplicationName(QLatin1String("qtxdg-desktop-file-start"));
    QCoreApplication::setApplicationVersion(QLatin1String(QTXDG_VERSION));

    QCommandLineParser parser;
    parser.setApplicationDescription(QLatin1String("QtXdg XdgDesktopFile start Tester"));
    parser.addHelpOption();
    parser.addVersionOption();
    parser.addPositionalArgument(QLatin1String("file [urls...]"), QLatin1String("desktop file to start and it's urls"),QLatin1String("file [urls...]"));
    parser.process(app);

    if (parser.positionalArguments().isEmpty()) {
        parser.showHelp(EXIT_FAILURE);
    }

    QStringList userArgs = parser.positionalArguments();
    const QString userFileName = userArgs.takeFirst();

    const QFileInfo fileInfo(userFileName);
    if (fileInfo.isAbsolute()) {
        if (!fileInfo.exists()) {
            printErr(QString::fromLatin1("File %1 does not exist\n").arg(userFileName));
            return EXIT_FAILURE;
        }
    }

    XdgDesktopFile f;
    const bool valid = f.load(userFileName);
    if (valid) {
        f.startDetached(userArgs);
    } else {
        printErr(QString::fromLatin1("%1 is not a valid .desktop file\n").arg(userFileName));
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before><commit_msg>more intricate ambient occlusion demo<commit_after><|endoftext|>


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

#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XENUMERATIONACCESS_HPP_
#include <com/sun/star/container/XEnumerationAccess.hpp>
#endif
#ifndef _HASHMAPS_HXX
#include <HashMaps.hxx>
#endif
#ifndef _ZIP_PACKAGE_ENTRY_HXX
#include <ZipPackageEntry.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

namespace com { namespace sun { namespace star {
namespace beans
{
    struct PropertyValue;
}
} } };
class ZipFile;
class ZipPackage;
class ZipOutputStream;
struct ZipEntry;
typedef void* rtlRandomPool;

class ZipPackageFolder : public cppu::ImplInheritanceHelper2
<
    ZipPackageEntry,
    ::com::sun::star::container::XNameContainer,
    ::com::sun::star::container::XEnumerationAccess
>
{
    static com::sun::star::uno::Sequence < sal_Int8 > aImplementationId;
protected:
    ContentHash maContents;
public:

    ZipPackageFolder ();
    virtual ~ZipPackageFolder();

    void doInsertByName ( ZipPackageEntry *pEntry, sal_Bool bSetParent )
        throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::ElementExistException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    ContentInfo & doGetByName( const ::rtl::OUString& aName )
        throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    static void copyZipEntry( ZipEntry &rDest, const ZipEntry &rSource);
    static ::com::sun::star::uno::Sequence < sal_Int8 > static_getImplementationId()
    {
        return aImplementationId;
    }
    // Recursive functions
    void  saveContents(rtl::OUString &rPath, std::vector < com::sun::star::uno::Sequence < com::sun::star::beans::PropertyValue > > &rManList, ZipOutputStream & rZipOut, com::sun::star::uno::Sequence < sal_Int8 > &rEncryptionKey, rtlRandomPool & rRandomPool)
        throw(::com::sun::star::uno::RuntimeException);
    void  releaseUpwardRef();

    // XNameContainer
    virtual void SAL_CALL insertByName( const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement )
        throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::ElementExistException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeByName( const ::rtl::OUString& Name )
        throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XEnumerationAccess
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XEnumeration > SAL_CALL createEnumeration(  )
        throw(::com::sun::star::uno::RuntimeException);

    // XElementAccess
    virtual ::com::sun::star::uno::Type SAL_CALL getElementType(  )
        throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasElements(  )
        throw(::com::sun::star::uno::RuntimeException);

    // XNameAccess
    virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName )
        throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames(  )
        throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName )
        throw(::com::sun::star::uno::RuntimeException);

    // XNameReplace
    virtual void SAL_CALL replaceByName( const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement )
        throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XPropertySet
    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XUnoTunnel
    virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier )
        throw(::com::sun::star::uno::RuntimeException);

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName(  )
        throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  )
        throw (::com::sun::star::uno::RuntimeException);
};
#endif
<commit_msg>#101685#,#i6886# merge OOO_STABLE_1_PORTS (1.26-1.26.10.1) -> HEAD<commit_after>/*************************************************************************
 *
 *  $RCSfile: ZipPackageFolder.hxx,v $
 *
 *  $Revision: 1.27 $
 *
 *  last change: $Author: hr $ $Date: 2002-08-20 12:38:45 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Martin Gallwey (gallwey@sun.com)
 *
 *
 ************************************************************************/
#ifndef _ZIP_PACKAGE_FOLDER_HXX
#define _ZIP_PACKAGE_FOLDER_HXX

#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XENUMERATIONACCESS_HPP_
#include <com/sun/star/container/XEnumerationAccess.hpp>
#endif
#ifndef _HASHMAPS_HXX
#include <HashMaps.hxx>
#endif
#ifndef _ZIP_PACKAGE_ENTRY_HXX
#include <ZipPackageEntry.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif

namespace com { namespace sun { namespace star {
namespace beans
{
    struct PropertyValue;
}
} } };
class ZipFile;
class ZipPackage;
class ZipOutputStream;
struct ZipEntry;
typedef void* rtlRandomPool;

#ifdef MACOSX
class ZipPackageFolder : public ZipPackageEntry,
                                                 public ::cppu::OWeakObject,
                                                 public ::com::sun::star::container::XNameContainer,
                                                 public ::com::sun::star::container::XEnumerationAccess
#else
class ZipPackageFolder : public cppu::ImplInheritanceHelper2
<
    ZipPackageEntry,
    ::com::sun::star::container::XNameContainer,
    ::com::sun::star::container::XEnumerationAccess
>
#endif
{
    static com::sun::star::uno::Sequence < sal_Int8 > aImplementationId;
protected:
    ContentHash maContents;
public:

    ZipPackageFolder ();
    virtual ~ZipPackageFolder();

    void doInsertByName ( ZipPackageEntry *pEntry, sal_Bool bSetParent )
        throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::ElementExistException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    ContentInfo & doGetByName( const ::rtl::OUString& aName )
        throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    static void copyZipEntry( ZipEntry &rDest, const ZipEntry &rSource);
    static ::com::sun::star::uno::Sequence < sal_Int8 > static_getImplementationId()
    {
        return aImplementationId;
    }
    // Recursive functions
    void  saveContents(rtl::OUString &rPath, std::vector < com::sun::star::uno::Sequence < com::sun::star::beans::PropertyValue > > &rManList, ZipOutputStream & rZipOut, com::sun::star::uno::Sequence < sal_Int8 > &rEncryptionKey, rtlRandomPool & rRandomPool)
        throw(::com::sun::star::uno::RuntimeException);
    void  releaseUpwardRef();

#ifdef MACOSX
    // XInterface
    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& rType )
        throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL acquire(  )
        throw();
    virtual void SAL_CALL release(  )
        throw();
#endif

    // XNameContainer
    virtual void SAL_CALL insertByName( const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement )
        throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::ElementExistException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeByName( const ::rtl::OUString& Name )
        throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XEnumerationAccess
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XEnumeration > SAL_CALL createEnumeration(  )
        throw(::com::sun::star::uno::RuntimeException);

    // XElementAccess
    virtual ::com::sun::star::uno::Type SAL_CALL getElementType(  )
        throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasElements(  )
        throw(::com::sun::star::uno::RuntimeException);

    // XNameAccess
    virtual ::com::sun::star::uno::Any SAL_CALL getByName( const ::rtl::OUString& aName )
        throw(::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getElementNames(  )
        throw(::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL hasByName( const ::rtl::OUString& aName )
        throw(::com::sun::star::uno::RuntimeException);

    // XNameReplace
    virtual void SAL_CALL replaceByName( const ::rtl::OUString& aName, const ::com::sun::star::uno::Any& aElement )
        throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XPropertySet
    virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName )
        throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException);

    // XUnoTunnel
    virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier )
        throw(::com::sun::star::uno::RuntimeException);

    // XServiceInfo
    virtual ::rtl::OUString SAL_CALL getImplementationName(  )
        throw (::com::sun::star::uno::RuntimeException);
    virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName )
        throw (::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames(  )
        throw (::com::sun::star::uno::RuntimeException);
};
#endif
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qmediapluginloader_p.h"
#include <QtCore/qcoreapplication.h>
#include <QtCore/qpluginloader.h>
#include <QtCore/qdir.h>
#include <QtCore/qdebug.h>

#include "qmediaserviceproviderplugin.h"

#if defined(Q_OS_MAC)
# include <CoreFoundation/CoreFoundation.h>
#endif

QT_BEGIN_NAMESPACE

typedef QMap<QString,QObjectList> ObjectListMap;
Q_GLOBAL_STATIC(ObjectListMap, staticMediaPlugins);

QMediaPluginLoader::QMediaPluginLoader(const char *iid, const QString &location, Qt::CaseSensitivity):
    m_iid(iid)
{
    m_location = QString::fromLatin1("/%1").arg(location);
    load();
}

QStringList QMediaPluginLoader::keys() const
{
    return m_instances.keys();
}

QObject* QMediaPluginLoader::instance(QString const &key)
{
    return m_instances.value(key).value(0);
}

QList<QObject*> QMediaPluginLoader::instances(QString const &key)
{
    return m_instances.value(key);
}

//to be used for testing purposes only
void QMediaPluginLoader::setStaticPlugins(const QString &location, const QObjectList& objects)
{
    staticMediaPlugins()->insert(QString::fromLatin1("/%1").arg(location), objects);
}

QStringList QMediaPluginLoader::availablePlugins() const
{
    QStringList paths;
    QStringList plugins;

#if defined(Q_OS_MAC)
    QString imageSuffix(qgetenv("DYLD_IMAGE_SUFFIX"));

    // Bundle plugin directory
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    if (mainBundle != 0) {
        CFURLRef baseUrl = CFBundleCopyBundleURL(mainBundle);
        CFURLRef pluginUrlPart = CFBundleCopyBuiltInPlugInsURL(mainBundle);
        CFStringRef pluginPathPart = CFURLCopyFileSystemPath(pluginUrlPart, kCFURLPOSIXPathStyle);
        CFURLRef pluginUrl = CFURLCreateCopyAppendingPathComponent(0, baseUrl, pluginPathPart, true);
        CFStringRef pluginPath = CFURLCopyFileSystemPath(pluginUrl, kCFURLPOSIXPathStyle);

        CFIndex length = CFStringGetLength(pluginPath);
        UniChar buffer[length];
        CFStringGetCharacters(pluginPath, CFRangeMake(0, length), buffer);

        paths << QString(reinterpret_cast<const QChar *>(buffer), length);

        CFRelease(pluginPath);
        CFRelease(pluginUrl);
        CFRelease(pluginPathPart);
        CFRelease(pluginUrlPart);
        CFRelease(baseUrl);
    }
#endif

    // Qt paths
    paths << QCoreApplication::libraryPaths();

    foreach (const QString &path, paths) {
        QDir typeDir(path + m_location);
        foreach (const QString &file, typeDir.entryList(QDir::Files, QDir::Name)) {
#if defined(Q_OS_MAC)
            if (!imageSuffix.isEmpty()) {   // Only add appropriate images
                if (file.lastIndexOf(imageSuffix, -6) == -1)
                    continue;
            } else {
                int foundSuffix = file.lastIndexOf(QLatin1String("_debug.dylib"));
                if (foundSuffix == -1) {
                    foundSuffix = file.lastIndexOf(QLatin1String("_profile.dylib"));
                }
                if (foundSuffix != -1) {
                    /*
                        If this is a "special" version of the plugin, prefer the release
                        version, where available.
                        Avoids warnings like:

                            objc[23101]: Class TransparentQTMovieView is implemented in both
                            libqqt7engine_debug.dylib and libqqt7engine.dylib. One of the two
                            will be used. Which one is undefined.

                        Note, this code relies on QDir::Name sorting!
                    */

                    QString preferred =
                        typeDir.absoluteFilePath(file.left(foundSuffix) + QLatin1String(".dylib"));

                    if (plugins.contains(preferred)) {
                        continue;
                    }
                }
            }
#elif defined(Q_OS_UNIX)
            // Ignore separate debug files
            if (file.endsWith(QLatin1String(".debug")))
                continue;
#elif defined(Q_OS_WIN)
            // Ignore non-dlls
            if (!file.endsWith(QLatin1String(".dll"), Qt::CaseInsensitive))
                continue;
#endif
            plugins << typeDir.absoluteFilePath(file);
        }
    }

    return  plugins;
}

void QMediaPluginLoader::load()
{
    if (!m_instances.isEmpty())
        return;

#if !defined QT_NO_DEBUG
    const bool showDebug = qgetenv("QT_DEBUG_PLUGINS").toInt() > 0;
#endif

    if (staticMediaPlugins() && staticMediaPlugins()->contains(m_location)) {
        foreach(QObject *o, staticMediaPlugins()->value(m_location)) {
            if (o != 0 && o->qt_metacast(m_iid) != 0) {
                QFactoryInterface* p = qobject_cast<QFactoryInterface*>(o);
                if (p != 0) {
                    foreach (QString const &key, p->keys())
                        m_instances[key].append(o);
                }
            }
        }
    } else {
        QSet<QString> loadedPlugins;

        foreach (const QString &plugin, availablePlugins()) {
            QString fileName = QFileInfo(plugin).fileName();
            //don't try to load plugin with the same name if it's already loaded
            if (loadedPlugins.contains(fileName)) {
#if !defined QT_NO_DEBUG
                if (showDebug)
                    qDebug() << "Skip loading plugin" << plugin;
#endif
                continue;
            }

            QPluginLoader   loader(plugin);

            QObject *o = loader.instance();
            if (o != 0 && o->qt_metacast(m_iid) != 0) {
                QFactoryInterface* p = qobject_cast<QFactoryInterface*>(o);
                if (p != 0) {
                    foreach (const QString &key, p->keys())
                        m_instances[key].append(o);

                    loadedPlugins.insert(fileName);
#if !defined QT_NO_DEBUG
                    if (showDebug)
                        qDebug() << "Loaded plugin" << plugin << "services:" << p->keys();
#endif
                }

                continue;
            } else {
#if !defined QT_NO_DEBUG
                if (showDebug)
                    qWarning() << "QMediaPluginLoader: Failed to load plugin: " << plugin << loader.errorString();
#endif
            }

            delete o;
        }
    }
}

QT_END_NAMESPACE

<commit_msg>Changed plugin loader to try unloading plugin if unused<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qmediapluginloader_p.h"
#include <QtCore/qcoreapplication.h>
#include <QtCore/qpluginloader.h>
#include <QtCore/qdir.h>
#include <QtCore/qdebug.h>

#include "qmediaserviceproviderplugin.h"

#if defined(Q_OS_MAC)
# include <CoreFoundation/CoreFoundation.h>
#endif

QT_BEGIN_NAMESPACE

typedef QMap<QString,QObjectList> ObjectListMap;
Q_GLOBAL_STATIC(ObjectListMap, staticMediaPlugins);

QMediaPluginLoader::QMediaPluginLoader(const char *iid, const QString &location, Qt::CaseSensitivity):
    m_iid(iid)
{
    m_location = QString::fromLatin1("/%1").arg(location);
    load();
}

QStringList QMediaPluginLoader::keys() const
{
    return m_instances.keys();
}

QObject* QMediaPluginLoader::instance(QString const &key)
{
    return m_instances.value(key).value(0);
}

QList<QObject*> QMediaPluginLoader::instances(QString const &key)
{
    return m_instances.value(key);
}

//to be used for testing purposes only
void QMediaPluginLoader::setStaticPlugins(const QString &location, const QObjectList& objects)
{
    staticMediaPlugins()->insert(QString::fromLatin1("/%1").arg(location), objects);
}

QStringList QMediaPluginLoader::availablePlugins() const
{
    QStringList paths;
    QStringList plugins;

#if defined(Q_OS_MAC)
    QString imageSuffix(qgetenv("DYLD_IMAGE_SUFFIX"));

    // Bundle plugin directory
    CFBundleRef mainBundle = CFBundleGetMainBundle();
    if (mainBundle != 0) {
        CFURLRef baseUrl = CFBundleCopyBundleURL(mainBundle);
        CFURLRef pluginUrlPart = CFBundleCopyBuiltInPlugInsURL(mainBundle);
        CFStringRef pluginPathPart = CFURLCopyFileSystemPath(pluginUrlPart, kCFURLPOSIXPathStyle);
        CFURLRef pluginUrl = CFURLCreateCopyAppendingPathComponent(0, baseUrl, pluginPathPart, true);
        CFStringRef pluginPath = CFURLCopyFileSystemPath(pluginUrl, kCFURLPOSIXPathStyle);

        CFIndex length = CFStringGetLength(pluginPath);
        UniChar buffer[length];
        CFStringGetCharacters(pluginPath, CFRangeMake(0, length), buffer);

        paths << QString(reinterpret_cast<const QChar *>(buffer), length);

        CFRelease(pluginPath);
        CFRelease(pluginUrl);
        CFRelease(pluginPathPart);
        CFRelease(pluginUrlPart);
        CFRelease(baseUrl);
    }
#endif

    // Qt paths
    paths << QCoreApplication::libraryPaths();

    foreach (const QString &path, paths) {
        QDir typeDir(path + m_location);
        foreach (const QString &file, typeDir.entryList(QDir::Files, QDir::Name)) {
#if defined(Q_OS_MAC)
            if (!imageSuffix.isEmpty()) {   // Only add appropriate images
                if (file.lastIndexOf(imageSuffix, -6) == -1)
                    continue;
            } else {
                int foundSuffix = file.lastIndexOf(QLatin1String("_debug.dylib"));
                if (foundSuffix == -1) {
                    foundSuffix = file.lastIndexOf(QLatin1String("_profile.dylib"));
                }
                if (foundSuffix != -1) {
                    /*
                        If this is a "special" version of the plugin, prefer the release
                        version, where available.
                        Avoids warnings like:

                            objc[23101]: Class TransparentQTMovieView is implemented in both
                            libqqt7engine_debug.dylib and libqqt7engine.dylib. One of the two
                            will be used. Which one is undefined.

                        Note, this code relies on QDir::Name sorting!
                    */

                    QString preferred =
                        typeDir.absoluteFilePath(file.left(foundSuffix) + QLatin1String(".dylib"));

                    if (plugins.contains(preferred)) {
                        continue;
                    }
                }
            }
#elif defined(Q_OS_UNIX)
            // Ignore separate debug files
            if (file.endsWith(QLatin1String(".debug")))
                continue;
#elif defined(Q_OS_WIN)
            // Ignore non-dlls
            if (!file.endsWith(QLatin1String(".dll"), Qt::CaseInsensitive))
                continue;
#endif
            plugins << typeDir.absoluteFilePath(file);
        }
    }

    return  plugins;
}

void QMediaPluginLoader::load()
{
    if (!m_instances.isEmpty())
        return;

#if !defined QT_NO_DEBUG
    const bool showDebug = qgetenv("QT_DEBUG_PLUGINS").toInt() > 0;
#endif

    if (staticMediaPlugins() && staticMediaPlugins()->contains(m_location)) {
        foreach(QObject *o, staticMediaPlugins()->value(m_location)) {
            if (o != 0 && o->qt_metacast(m_iid) != 0) {
                QFactoryInterface* p = qobject_cast<QFactoryInterface*>(o);
                if (p != 0) {
                    foreach (QString const &key, p->keys())
                        m_instances[key].append(o);
                }
            }
        }
    } else {
        QSet<QString> loadedPlugins;

        foreach (const QString &plugin, availablePlugins()) {
            QString fileName = QFileInfo(plugin).fileName();
            //don't try to load plugin with the same name if it's already loaded
            if (loadedPlugins.contains(fileName)) {
#if !defined QT_NO_DEBUG
                if (showDebug)
                    qDebug() << "Skip loading plugin" << plugin;
#endif
                continue;
            }

            QPluginLoader   loader(plugin);

            QObject *o = loader.instance();
            if (o != 0 && o->qt_metacast(m_iid) != 0) {
                QFactoryInterface* p = qobject_cast<QFactoryInterface*>(o);
                if (p != 0) {
                    foreach (const QString &key, p->keys())
                        m_instances[key].append(o);

                    loadedPlugins.insert(fileName);
#if !defined QT_NO_DEBUG
                    if (showDebug)
                        qDebug() << "Loaded plugin" << plugin << "services:" << p->keys();
#endif
                }

                continue;
            } else {
#if !defined QT_NO_DEBUG
                if (showDebug)
                    qWarning() << "QMediaPluginLoader: Failed to load plugin: " << plugin << loader.errorString();
#endif
            }

            loader.unload();
        }
    }
}

QT_END_NAMESPACE

<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/webui/uber/uber_ui.h"

#include "base/stl_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/chrome_url_data_manager.h"
#include "chrome/browser/ui/webui/chrome_web_ui_data_source.h"
#include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
#include "chrome/browser/ui/webui/extensions/extensions_ui.h"
#include "chrome/browser/ui/webui/options2/options_ui2.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"

using content::WebContents;

namespace {

ChromeWebUIDataSource* CreateUberHTMLSource() {
  ChromeWebUIDataSource* source =
      new ChromeWebUIDataSource(chrome::kChromeUIUberHost);

  source->set_json_path("strings.js");
  source->add_resource_path("uber.js", IDR_UBER_JS);
  source->add_resource_path("uber_utils.js", IDR_UBER_UTILS_JS);
  source->set_default_resource(IDR_UBER_HTML);

  // Hack alert: continue showing "Loading..." until a real title is set.
  source->AddLocalizedString("pageTitle", IDS_TAB_LOADING_TITLE);

  source->AddString("settingsHost",
                    ASCIIToUTF16(chrome::kChromeUISettingsHost));
  source->AddString("extensionsHost",
                    ASCIIToUTF16(chrome::kChromeUIExtensionsHost));
  source->AddString("helpHost",
                    ASCIIToUTF16(chrome::kChromeUIHelpHost));

  return source;
}

ChromeWebUIDataSource* CreateUberFrameHTMLSource() {
  ChromeWebUIDataSource* source =
      new ChromeWebUIDataSource(chrome::kChromeUIUberFrameHost);

  source->set_json_path("strings.js");
  source->add_resource_path("uber_frame.js", IDR_UBER_FRAME_JS);
  source->set_default_resource(IDR_UBER_FRAME_HTML);

  source->AddLocalizedString("shortProductName", IDS_SHORT_PRODUCT_NAME);

  source->AddString("settingsHost",
                    ASCIIToUTF16(chrome::kChromeUISettingsHost));
  source->AddLocalizedString("settingsDisplayName", IDS_SETTINGS_TITLE);
  source->AddString("extensionsHost",
                    ASCIIToUTF16(chrome::kChromeUIExtensionsHost));
  source->AddLocalizedString("extensionsDisplayName",
                             IDS_MANAGE_EXTENSIONS_SETTING_WINDOWS_TITLE);
  source->AddString("helpHost",
                    ASCIIToUTF16(chrome::kChromeUIHelpHost));
  source->AddLocalizedString("helpDisplayName", IDS_HELP_TITLE);

  return source;
}

}  // namespace

UberUI::UberUI(content::WebUI* web_ui) : WebUIController(web_ui) {
  Profile* profile = Profile::FromWebUI(web_ui);
  profile->GetChromeURLDataManager()->AddDataSource(CreateUberHTMLSource());

  RegisterSubpage(chrome::kChromeUIUberFrameURL);
  RegisterSubpage(chrome::kChromeUISettingsFrameURL);
  RegisterSubpage(chrome::kChromeUIExtensionsFrameURL);
  RegisterSubpage(chrome::kChromeUIHelpFrameURL);
}

UberUI::~UberUI() {
  STLDeleteValues(&sub_uis_);
}

void UberUI::RegisterSubpage(const std::string& page_url) {
  content::WebUI* webui =
      web_ui()->GetWebContents()->CreateWebUI(GURL(page_url));

  webui->SetFrameXPath("//iframe[@src='" + page_url + "']");
  sub_uis_[page_url] = webui;
}

void UberUI::RenderViewCreated(RenderViewHost* render_view_host) {
  for (SubpageMap::iterator iter = sub_uis_.begin(); iter != sub_uis_.end();
       ++iter) {
    iter->second->GetController()->RenderViewCreated(render_view_host);
  }
}

void UberUI::RenderViewReused(RenderViewHost* render_view_host) {
  for (SubpageMap::iterator iter = sub_uis_.begin(); iter != sub_uis_.end();
       ++iter) {
    iter->second->GetController()->RenderViewReused(render_view_host);
  }
}

void UberUI::DidBecomeActiveForReusedRenderView() {
  for (SubpageMap::iterator iter = sub_uis_.begin(); iter != sub_uis_.end();
       ++iter) {
    iter->second->GetController()->DidBecomeActiveForReusedRenderView();
  }
}

bool UberUI::OverrideHandleWebUIMessage(const GURL& source_url,
                                        const std::string& message,
                                        const ListValue& args) {
  // Find the appropriate subpage and forward the message.
  SubpageMap::iterator subpage = sub_uis_.find(source_url.GetOrigin().spec());
  if (subpage == sub_uis_.end()) {
    // The message was sent from the uber page itself.
    DCHECK_EQ(std::string(chrome::kChromeUIUberHost), source_url.host());
    return false;
  }

  // The message was sent from a subpage.
  // TODO(jam) fix this to use interface
  // return subpage->second->GetController()->OverrideHandleWebUIMessage(
  //     source_url, message, args);
  subpage->second->ProcessWebUIMessage(source_url, message, args);
  return true;
}

// UberFrameUI

UberFrameUI::UberFrameUI(content::WebUI* web_ui) : WebUIController(web_ui) {
  Profile* profile = Profile::FromWebUI(web_ui);
  profile->GetChromeURLDataManager()->AddDataSource(
      CreateUberFrameHTMLSource());
}

UberFrameUI::~UberFrameUI() {
}
<commit_msg>Uber: Use the OS name for the title on Chrome OS.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/webui/uber/uber_ui.h"

#include "base/stl_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/webui/chrome_url_data_manager.h"
#include "chrome/browser/ui/webui/chrome_web_ui_data_source.h"
#include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
#include "chrome/browser/ui/webui/extensions/extensions_ui.h"
#include "chrome/browser/ui/webui/options2/options_ui2.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_ui.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"

using content::WebContents;

namespace {

ChromeWebUIDataSource* CreateUberHTMLSource() {
  ChromeWebUIDataSource* source =
      new ChromeWebUIDataSource(chrome::kChromeUIUberHost);

  source->set_json_path("strings.js");
  source->add_resource_path("uber.js", IDR_UBER_JS);
  source->add_resource_path("uber_utils.js", IDR_UBER_UTILS_JS);
  source->set_default_resource(IDR_UBER_HTML);

  // Hack alert: continue showing "Loading..." until a real title is set.
  source->AddLocalizedString("pageTitle", IDS_TAB_LOADING_TITLE);

  source->AddString("settingsHost",
                    ASCIIToUTF16(chrome::kChromeUISettingsHost));
  source->AddString("extensionsHost",
                    ASCIIToUTF16(chrome::kChromeUIExtensionsHost));
  source->AddString("helpHost",
                    ASCIIToUTF16(chrome::kChromeUIHelpHost));

  return source;
}

ChromeWebUIDataSource* CreateUberFrameHTMLSource() {
  ChromeWebUIDataSource* source =
      new ChromeWebUIDataSource(chrome::kChromeUIUberFrameHost);

  source->set_json_path("strings.js");
  source->add_resource_path("uber_frame.js", IDR_UBER_FRAME_JS);
  source->set_default_resource(IDR_UBER_FRAME_HTML);

  // TODO(jhawkins): Attempt to get rid of IDS_PRODUCT_OS_NAME.
#if defined(OS_CHROMEOS)
  source->AddLocalizedString("shortProductName", IDS_PRODUCT_OS_NAME);
#else
  source->AddLocalizedString("shortProductName", IDS_SHORT_PRODUCT_NAME);
#endif  // defined(OS_CHROMEOS)

  source->AddString("settingsHost",
                    ASCIIToUTF16(chrome::kChromeUISettingsHost));
  source->AddLocalizedString("settingsDisplayName", IDS_SETTINGS_TITLE);
  source->AddString("extensionsHost",
                    ASCIIToUTF16(chrome::kChromeUIExtensionsHost));
  source->AddLocalizedString("extensionsDisplayName",
                             IDS_MANAGE_EXTENSIONS_SETTING_WINDOWS_TITLE);
  source->AddString("helpHost",
                    ASCIIToUTF16(chrome::kChromeUIHelpHost));
  source->AddLocalizedString("helpDisplayName", IDS_HELP_TITLE);

  return source;
}

}  // namespace

UberUI::UberUI(content::WebUI* web_ui) : WebUIController(web_ui) {
  Profile* profile = Profile::FromWebUI(web_ui);
  profile->GetChromeURLDataManager()->AddDataSource(CreateUberHTMLSource());

  RegisterSubpage(chrome::kChromeUIUberFrameURL);
  RegisterSubpage(chrome::kChromeUISettingsFrameURL);
  RegisterSubpage(chrome::kChromeUIExtensionsFrameURL);
  RegisterSubpage(chrome::kChromeUIHelpFrameURL);
}

UberUI::~UberUI() {
  STLDeleteValues(&sub_uis_);
}

void UberUI::RegisterSubpage(const std::string& page_url) {
  content::WebUI* webui =
      web_ui()->GetWebContents()->CreateWebUI(GURL(page_url));

  webui->SetFrameXPath("//iframe[@src='" + page_url + "']");
  sub_uis_[page_url] = webui;
}

void UberUI::RenderViewCreated(RenderViewHost* render_view_host) {
  for (SubpageMap::iterator iter = sub_uis_.begin(); iter != sub_uis_.end();
       ++iter) {
    iter->second->GetController()->RenderViewCreated(render_view_host);
  }
}

void UberUI::RenderViewReused(RenderViewHost* render_view_host) {
  for (SubpageMap::iterator iter = sub_uis_.begin(); iter != sub_uis_.end();
       ++iter) {
    iter->second->GetController()->RenderViewReused(render_view_host);
  }
}

void UberUI::DidBecomeActiveForReusedRenderView() {
  for (SubpageMap::iterator iter = sub_uis_.begin(); iter != sub_uis_.end();
       ++iter) {
    iter->second->GetController()->DidBecomeActiveForReusedRenderView();
  }
}

bool UberUI::OverrideHandleWebUIMessage(const GURL& source_url,
                                        const std::string& message,
                                        const ListValue& args) {
  // Find the appropriate subpage and forward the message.
  SubpageMap::iterator subpage = sub_uis_.find(source_url.GetOrigin().spec());
  if (subpage == sub_uis_.end()) {
    // The message was sent from the uber page itself.
    DCHECK_EQ(std::string(chrome::kChromeUIUberHost), source_url.host());
    return false;
  }

  // The message was sent from a subpage.
  // TODO(jam) fix this to use interface
  // return subpage->second->GetController()->OverrideHandleWebUIMessage(
  //     source_url, message, args);
  subpage->second->ProcessWebUIMessage(source_url, message, args);
  return true;
}

// UberFrameUI

UberFrameUI::UberFrameUI(content::WebUI* web_ui) : WebUIController(web_ui) {
  Profile* profile = Profile::FromWebUI(web_ui);
  profile->GetChromeURLDataManager()->AddDataSource(
      CreateUberFrameHTMLSource());
}

UberFrameUI::~UberFrameUI() {
}
<|endoftext|>


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

  Library   : Image Registration Toolkit (IRTK)
  Module    : $Id$
  Copyright : Imperial College, Department of Computing
              Visual Information Processing (VIP), 2008 onwards
  Date      : $Date$
  Version   : $Revision$
  Changes   : $Author$

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

#ifdef HAS_VTK

#include <vtkFloatArray.h>
#include <vtkPointData.h>
#include <vtkStructuredGrid.h>
#include <vtkStructuredGridWriter.h>

#include <irtkImage.h>
#include <irtkTransformation.h>
#include <irtkResampling.h>

// Default filenames
char *image_name = NULL, *input_name = NULL, *output_name = NULL;

void usage()
{
  cerr << "Usage: dof2vtk [dof] [vtk]                 Load dof from file output dof in world coordinate in vtk format\n" << endl;
  cerr << "<-image image>                             Load image from file output dof in the reference image coordinate\n"										  ;
  cerr << "<-mask value>                              Mask intensity\n";
  cerr << "<-rmatr>                                   Remove Orientation and Origion info\n";
  cerr << "<-isotropic>							      Resample the image according to the smallest resolution Linear interpolator\n";
  cerr << "<-deformation>							  Use deformation of the material point other then deformation on control points\n";
  exit(1);
}

int main(int argc, char **argv)
{
  int x, y, z;
  double p1[3], p2[3];
  int mask,rmatr,isotropic,ok,deformation;

  if (argc < 3) {
    usage();
  }

  input_name  = argv[1];
  argc--;
  argv++;
  output_name = argv[1];
  argc--;
  argv++;

  mask = -1;
  rmatr = 0;
  isotropic = 0;
  deformation = 0;

  while (argc > 1) {
	  ok = false;
	  if (strcmp(argv[1], "-rmatr") == 0) {
		  argc--;
		  argv++;
		  rmatr = 1;
		  ok = true;
	  }else if (strcmp(argv[1], "-mask") == 0) {
		  argc--;
		  argv++;
		  mask = atoi(argv[1]);
		  argc--;
		  argv++;
		  ok = true;
	  }else if (strcmp(argv[1], "-image") == 0) {
		  argc--;
		  argv++;
		  image_name = argv[1];
		  argc--;
		  argv++;
		  ok = true;
	  }else if (strcmp(argv[1], "-isotropic") == 0) {
      argc--;
      argv++;
	  isotropic = 1;
	  ok = true;
      }
	  else if (strcmp(argv[1], "-deformation") == 0) {
      argc--;
      argv++;
	  deformation = 1;
	  ok = true;
      }
	  else if (!ok) {
		  cerr << "Invalid option : " << argv[1] << endl;
		  exit(1);
	  }
  }

  // Read transformation
  irtkTransformation *transform = irtkTransformation::New(input_name);
  // Create initial multi-level free-form deformation
  irtkMultiLevelFreeFormTransformation *mffd = NULL;
  irtkBSplineFreeFormTransformation *affd = NULL;
  irtkGreyImage image,timage;

  // Set up vtk points
  vtkPoints *points = vtkPoints::New();

  // Set up vtk vectors
  vtkFloatArray *vectors = vtkFloatArray::New();
  vectors->SetNumberOfComponents(3);

  if(image_name){
	  // Read image
	  image.Read(image_name);
	  timage.Read(image_name);

  // Remove Attributes
	  if(rmatr == 1){
		  irtkImageAttributes tmpatr;
		  image.PutOrientation(tmpatr._xaxis,tmpatr._yaxis,tmpatr._zaxis);
		  image.PutOrigin(tmpatr._xorigin,tmpatr._yorigin,tmpatr._zorigin);
		  //image.PutOrigin(tmpatr._xorigin + (image.GetX() - 1)/2.0
			  //,tmpatr._yorigin + (image.GetY() - 1)/2.0,
			  //tmpatr._zorigin + (image.GetZ() - 1)/2.0);
		  //image.PutPixelSize(tmpatr._dx,tmpatr._dy,tmpatr._dz);
	  }

	  if(isotropic == 1){
		  // Resample image to isotropic voxels (smalles voxel dimension)
		  double xsize, ysize, zsize, size;
		  image.GetPixelSize(&xsize, &ysize, &zsize);
		  size = xsize;
		  size = (size < ysize) ? size : ysize;
		  size = (size < zsize) ? size : zsize;
		  cerr << "Resampling image to isotropic voxel size (in mm): "
			  << size << endl;
		  irtkResampling<irtkGreyPixel> resampling(size, size, size);
		  irtkLinearInterpolateImageFunction interpolator;
		  resampling.SetInput (&image);
		  resampling.SetOutput(&image);
		  resampling.SetInterpolator(&interpolator);
		  resampling.Run();
	  }

	  // Initialize point structure with transformed point positions
	  for (z = 0; z < image.GetZ(); z++) {
		  for (y = 0; y < image.GetY(); y++) {
			  for (x = 0; x < image.GetX(); x++) {
				  p1[0] = x;
				  p1[1] = y;
				  p1[2] = z;
				  timage.ImageToWorld(p1[0], p1[1], p1[2]);
				  p2[0] = p1[0];
				  p2[1] = p1[1];
				  p2[2] = p1[2];
				  transform->Transform(p2[0], p2[1], p2[2]);
				  if(rmatr == 1){
					  p1[0] = x;
					  p1[1] = y;
					  p1[2] = z;
					  image.ImageToWorld(p1[0], p1[1], p1[2]);
					  timage.WorldToImage(p2[0],p2[1],p2[2]);
					  image.ImageToWorld(p2[0],p2[1],p2[2]);
				  }
				  p2[0] -= p1[0];
				  p2[1] -= p1[1];
				  p2[2] -= p1[2];
				  points->InsertNextPoint(p1);
				  if(image.GetAsDouble(x,y,z) > mask || mask == -1){
					  vectors->InsertNextTuple(p2);
				  }else{
					  p2[0] = 0;
					  p2[1] = 0;
					  p2[2] = 0;
					  vectors->InsertNextTuple(p2);
				  }
			  }
		  }
	  }
  }else{
	  if (strcmp(transform->NameOfClass(), "irtkMultiLevelFreeFormTransformation") == 0) {
		  mffd = new irtkMultiLevelFreeFormTransformation(*((irtkMultiLevelFreeFormTransformation *)transform));
		  affd = (irtkBSplineFreeFormTransformation *)mffd->PopLocalTransformation();
	  } else {
		  cerr << "Input transformation is not of type multi-level free form deformation" << endl;
		  exit(1);
	  }
	  // Initialize point structure with transformed point positions
	  for (z = 0; z < affd->GetZ(); z++) {
		  for (y = 0; y < affd->GetY(); y++) {
			  for (x = 0; x < affd->GetX(); x++) {
				  p1[0] = x;
				  p1[1] = y;
				  p1[2] = z;
				  affd->LatticeToWorld(p1[0],p1[1],p1[2]);
				  if(deformation == 1){
					  p2[0] = p1[0];
					  p2[1] = p1[1];
					  p2[2] = p1[2];
					  transform->Transform(p2[0], p2[1], p2[2]);
					  p2[0] -= p1[0];
					  p2[1] -= p1[1];
					  p2[2] -= p1[2];
				  }else{
					  affd->Get(x,y,z,p2[0],p2[1],p2[2]);
				  }
				  points->InsertNextPoint(p1);
				  vectors->InsertNextTuple(p2);
			  }
		  }
	  }
  }
  // Allocate objects for vtkStructuredGrid format
  vtkStructuredGrid *grid = vtkStructuredGrid::New();
  vtkStructuredGridWriter *writer = vtkStructuredGridWriter::New();

  // Set structured grid
  if(image_name)
	  grid->SetDimensions(image.GetX(), image.GetY(), image.GetZ());
  else
	  grid->SetDimensions(affd->GetX(), affd->GetY(), affd->GetZ());

  grid->SetPoints(points);
  grid->GetPointData()->SetVectors(vectors);

  // Write structured grid
  writer->SetInput(grid);
  writer->SetFileName(output_name);
  writer->SetFileTypeToBinary();
  writer->SetVectorsName("vectors");
  writer->Update();

}

#else

#include <irtkImage.h>

int main( int argc, char *argv[] )
{
  cerr << argv[0] << " needs to be compiled with the VTK library " << endl;
}
#endif
<commit_msg>removed some commented old code.<commit_after>/*=========================================================================

  Library   : Image Registration Toolkit (IRTK)
  Module    : $Id$
  Copyright : Imperial College, Department of Computing
              Visual Information Processing (VIP), 2008 onwards
  Date      : $Date$
  Version   : $Revision$
  Changes   : $Author$

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

#ifdef HAS_VTK

#include <vtkFloatArray.h>
#include <vtkPointData.h>
#include <vtkStructuredGrid.h>
#include <vtkStructuredGridWriter.h>

#include <irtkImage.h>
#include <irtkTransformation.h>
#include <irtkResampling.h>

// Default filenames
char *image_name = NULL, *input_name = NULL, *output_name = NULL;

void usage()
{
  cerr << "Usage: dof2vtk [dof] [vtk]                 Load dof from file output dof in world coordinate in vtk format\n" << endl;
  cerr << "<-image image>                             Load image from file output dof in the reference image coordinate\n"										  ;
  cerr << "<-mask value>                              Mask intensity\n";
  cerr << "<-rmatr>                                   Remove Orientation and Origion info\n";
  cerr << "<-isotropic>							      Resample the image according to the smallest resolution Linear interpolator\n";
  cerr << "<-deformation>							  Use deformation of the material point other then deformation on control points\n";
  exit(1);
}

int main(int argc, char **argv)
{
  int x, y, z;
  double p1[3], p2[3];
  int mask,rmatr,isotropic,ok,deformation;

  if (argc < 3) {
    usage();
  }

  input_name  = argv[1];
  argc--;
  argv++;
  output_name = argv[1];
  argc--;
  argv++;

  mask = -1;
  rmatr = 0;
  isotropic = 0;
  deformation = 0;

  while (argc > 1) {
	  ok = false;
	  if (strcmp(argv[1], "-rmatr") == 0) {
		  argc--;
		  argv++;
		  rmatr = 1;
		  ok = true;
	  }else if (strcmp(argv[1], "-mask") == 0) {
		  argc--;
		  argv++;
		  mask = atoi(argv[1]);
		  argc--;
		  argv++;
		  ok = true;
	  }else if (strcmp(argv[1], "-image") == 0) {
		  argc--;
		  argv++;
		  image_name = argv[1];
		  argc--;
		  argv++;
		  ok = true;
	  }else if (strcmp(argv[1], "-isotropic") == 0) {
      argc--;
      argv++;
	  isotropic = 1;
	  ok = true;
      }
	  else if (strcmp(argv[1], "-deformation") == 0) {
      argc--;
      argv++;
	  deformation = 1;
	  ok = true;
      }
	  else if (!ok) {
		  cerr << "Invalid option : " << argv[1] << endl;
		  exit(1);
	  }
  }

  // Read transformation
  irtkTransformation *transform = irtkTransformation::New(input_name);
  // Create initial multi-level free-form deformation
  irtkMultiLevelFreeFormTransformation *mffd = NULL;
  irtkBSplineFreeFormTransformation *affd = NULL;
  irtkGreyImage image,timage;

  // Set up vtk points
  vtkPoints *points = vtkPoints::New();

  // Set up vtk vectors
  vtkFloatArray *vectors = vtkFloatArray::New();
  vectors->SetNumberOfComponents(3);

  if(image_name){
	  // Read image
	  image.Read(image_name);
	  timage.Read(image_name);

  // Remove Attributes
	  if(rmatr == 1){
		  irtkImageAttributes tmpatr;
		  image.PutOrientation(tmpatr._xaxis,tmpatr._yaxis,tmpatr._zaxis);
		  image.PutOrigin(tmpatr._xorigin,tmpatr._yorigin,tmpatr._zorigin);
      }

	  if(isotropic == 1){
		  // Resample image to isotropic voxels (smalles voxel dimension)
		  double xsize, ysize, zsize, size;
		  image.GetPixelSize(&xsize, &ysize, &zsize);
		  size = xsize;
		  size = (size < ysize) ? size : ysize;
		  size = (size < zsize) ? size : zsize;
		  cerr << "Resampling image to isotropic voxel size (in mm): "
			  << size << endl;
		  irtkResampling<irtkGreyPixel> resampling(size, size, size);
		  irtkLinearInterpolateImageFunction interpolator;
		  resampling.SetInput (&image);
		  resampling.SetOutput(&image);
		  resampling.SetInterpolator(&interpolator);
		  resampling.Run();
	  }

	  // Initialize point structure with transformed point positions
	  for (z = 0; z < image.GetZ(); z++) {
		  for (y = 0; y < image.GetY(); y++) {
			  for (x = 0; x < image.GetX(); x++) {
				  p1[0] = x;
				  p1[1] = y;
				  p1[2] = z;
				  timage.ImageToWorld(p1[0], p1[1], p1[2]);
				  p2[0] = p1[0];
				  p2[1] = p1[1];
				  p2[2] = p1[2];
				  transform->Transform(p2[0], p2[1], p2[2]);
				  if(rmatr == 1){
					  p1[0] = x;
					  p1[1] = y;
					  p1[2] = z;
					  image.ImageToWorld(p1[0], p1[1], p1[2]);
					  timage.WorldToImage(p2[0],p2[1],p2[2]);
					  image.ImageToWorld(p2[0],p2[1],p2[2]);
				  }
				  p2[0] -= p1[0];
				  p2[1] -= p1[1];
				  p2[2] -= p1[2];
				  points->InsertNextPoint(p1);
				  if(image.GetAsDouble(x,y,z) > mask || mask == -1){
					  vectors->InsertNextTuple(p2);
				  }else{
					  p2[0] = 0;
					  p2[1] = 0;
					  p2[2] = 0;
					  vectors->InsertNextTuple(p2);
				  }
			  }
		  }
	  }
  }else{
	  if (strcmp(transform->NameOfClass(), "irtkMultiLevelFreeFormTransformation") == 0) {
		  mffd = new irtkMultiLevelFreeFormTransformation(*((irtkMultiLevelFreeFormTransformation *)transform));
		  affd = (irtkBSplineFreeFormTransformation *)mffd->PopLocalTransformation();
	  } else {
		  cerr << "Input transformation is not of type multi-level free form deformation" << endl;
		  exit(1);
	  }
	  // Initialize point structure with transformed point positions
	  for (z = 0; z < affd->GetZ(); z++) {
		  for (y = 0; y < affd->GetY(); y++) {
			  for (x = 0; x < affd->GetX(); x++) {
				  p1[0] = x;
				  p1[1] = y;
				  p1[2] = z;
				  affd->LatticeToWorld(p1[0],p1[1],p1[2]);
				  if(deformation == 1){
					  p2[0] = p1[0];
					  p2[1] = p1[1];
					  p2[2] = p1[2];
					  transform->Transform(p2[0], p2[1], p2[2]);
					  p2[0] -= p1[0];
					  p2[1] -= p1[1];
					  p2[2] -= p1[2];
				  }else{
					  affd->Get(x,y,z,p2[0],p2[1],p2[2]);
				  }
				  points->InsertNextPoint(p1);
				  vectors->InsertNextTuple(p2);
			  }
		  }
	  }
  }
  // Allocate objects for vtkStructuredGrid format
  vtkStructuredGrid *grid = vtkStructuredGrid::New();
  vtkStructuredGridWriter *writer = vtkStructuredGridWriter::New();

  // Set structured grid
  if(image_name)
	  grid->SetDimensions(image.GetX(), image.GetY(), image.GetZ());
  else
	  grid->SetDimensions(affd->GetX(), affd->GetY(), affd->GetZ());

  grid->SetPoints(points);
  grid->GetPointData()->SetVectors(vectors);

  // Write structured grid
  writer->SetInput(grid);
  writer->SetFileName(output_name);
  writer->SetFileTypeToBinary();
  writer->SetVectorsName("deformation vectors");
  writer->Update();

}

#else

#include <irtkImage.h>

int main( int argc, char *argv[] )
{
  cerr << argv[0] << " needs to be compiled with the VTK library " << endl;
}
#endif
<|endoftext|>