<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2012-2013 Esteban Tovagliari, Jupiter Jazz Limited
// Copyright (c) 2014-2016 Esteban Tovagliari, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// appleseed.python headers.
#include "pyseed.h" // has to be first, to avoid redefinition warnings
#include "bindentitycontainers.h"
#include "dict2dict.h"

// appleseed.renderer headers.
#include "renderer/api/display.h"
#include "renderer/api/frame.h"
#include "renderer/api/project.h"
#include "renderer/api/scene.h"

// appleseed.foundation headers.
#include "foundation/utility/searchpaths.h"

// Standard headers.
#include <cstddef>
#include <string>

namespace bpy = boost::python;
using namespace foundation;
using namespace renderer;
using namespace std;

// Work around a regression in Visual Studio 2015 Update 3.
#if defined(_MSC_VER) && _MSC_VER == 1900
namespace boost
{
    template <> Configuration const volatile* get_pointer<Configuration const volatile>(Configuration const volatile* p) { return p; }
    template <> Project const volatile* get_pointer<Project const volatile>(Project const volatile* p) { return p; }
}
#endif

namespace
{
    auto_release_ptr<Project> create_project(const string& name)
    {
        return ProjectFactory::create(name.c_str());
    }

    bpy::object create_default_project()
    {
        auto_release_ptr<Project> project(DefaultProjectFactory::create());
        return bpy::object(project);
    }

    bpy::object create_cornell_box_project()
    {
        auto_release_ptr<Project> project(CornellBoxProjectFactory::create());
        return bpy::object(project);
    }

    bpy::list project_get_search_paths(const Project* project)
    {
        bpy::list paths;

        const SearchPaths& search_paths = project->search_paths();

        for (size_t i = 0; i < search_paths.size(); ++i)
            paths.append(search_paths[i]);

        return paths;
    }

    void project_set_search_paths(Project* project, const bpy::list& paths)
    {
        project->search_paths().clear();

        for (bpy::ssize_t i = 0, e = bpy::len(paths); i < e; ++i)
        {
            const bpy::extract<const char*> extractor(paths[i]);
            if (extractor.check())
                project->search_paths().push_back(extractor());
            else
            {
                PyErr_SetString(PyExc_TypeError, "Incompatible type. Only strings accepted.");
                bpy::throw_error_already_set();
            }
        }
    }

    ConfigurationContainer* project_get_configs(Project* project)
    {
        return &(project->configurations());
    }

    bool write_project_default_opts(
        const ProjectFileWriter*            writer,
        const Project*                      project,
        const char*                         filepath)
    {
        return ProjectFileWriter::write(*project, filepath);
    }

    bool write_project_with_opts(
        const ProjectFileWriter*            writer,
        const Project*                      project,
        const char*                         filepath,
        int                                 opts)
    {
        return ProjectFileWriter::write(*project, filepath, opts);
    }

    auto_release_ptr<Configuration> create_config(const string& name)
    {
        return ConfigurationFactory::create(name.c_str());
    }

    auto_release_ptr<Configuration> create_config_with_params(
        const string&                       name,
        const bpy::dict&                    params)
    {
        return ConfigurationFactory::create(name.c_str(), bpy_dict_to_param_array(params));
    }

    bpy::object create_base_final_config()
    {
        auto_release_ptr<Configuration> config(BaseConfigurationFactory::create_base_final());
        return bpy::object(config);
    }

    bpy::object create_base_interactive_config()
    {
        auto_release_ptr<Configuration> config(BaseConfigurationFactory::create_base_interactive());
        return bpy::object(config);
    }

    bpy::dict config_get_inherited_parameters(const Configuration* config)
    {
        ParamArray params(config->get_inherited_parameters());
        return param_array_to_bpy_dict(params);
    }

    void config_insert_path(Configuration* config, const char* path, const bpy::object& value)
    {
        {
            bpy::extract<const char*> extractor(value);
            if (extractor.check())
            {
                config->get_parameters().insert_path(path, extractor());
                return;
            }
        }

        if (PyBool_Check(value.ptr()))
        {
            bpy::extract<bool> extractor(value);
            if (extractor.check())
            {
                config->get_parameters().insert_path(path, extractor());
                return;
            }
        }

#if PY_MAJOR_VERSION == 2
        if (PyInt_Check(value.ptr()))
        {
            bpy::extract<int> extractor(value);
            if (extractor.check())
            {
                config->get_parameters().insert_path(path, extractor());
                return;
            }
        }
#endif

        if (PyLong_Check(value.ptr()))
        {
            bpy::extract<int> extractor(value);
            if (extractor.check())
            {
                config->get_parameters().insert_path(path, extractor());
                return;
            }
        }

        if (PyFloat_Check(value.ptr()))
        {
            bpy::extract<double> extractor(value);
            if (extractor.check())
            {
                config->get_parameters().insert_path(path, extractor());
                return;
            }
        }

        PyErr_SetString(PyExc_TypeError, "Unsupported value type.");
        bpy::throw_error_already_set();
    }

    void config_remove_path(Configuration* config, const char* path)
    {
        config->get_parameters().remove_path(path);
    }

    bpy::dict config_get_metadata()
    {
        return dictionary_to_bpy_dict(Configuration::get_metadata());
    }

    bpy::object project_file_reader_read_default_opts(
        ProjectFileReader*                  reader,
        const char*                         project_filename,
        const char*                         schema_filename)
    {
        auto_release_ptr<Project> project(reader->read(project_filename, schema_filename));
        return bpy::object(project);
    }

    bpy::object project_file_reader_read_with_opts(
        ProjectFileReader*                  reader,
        const char*                         project_filename,
        const char*                         schema_filename,
        const ProjectFileReader::Options    opts)
    {
        auto_release_ptr<Project> project(reader->read(project_filename, schema_filename, opts));
        return bpy::object(project);
    }

    bpy::object project_file_reader_load_builtin(ProjectFileReader* reader, const char* project_name)
    {
        auto_release_ptr<Project> project(reader->load_builtin(project_name));
        return bpy::object(project);
    }
}

void bind_project()
{
    bpy::class_<Configuration, auto_release_ptr<Configuration>, bpy::bases<Entity>, boost::noncopyable>("Configuration", bpy::no_init)
        .def("create_base_final", create_base_final_config).staticmethod("create_base_final")
        .def("create_base_interactive", create_base_interactive_config).staticmethod("create_base_interactive")

        .def("__init__", bpy::make_constructor(create_config))
        .def("__init__", bpy::make_constructor(create_config_with_params))

        .def("set_base", &Configuration::set_base)
        .def("get_base", &Configuration::get_base, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("get_inherited_parameters", config_get_inherited_parameters)

        .def("insert_path", config_insert_path)
        .def("remove_path", config_remove_path)

        .def("get_metadata", config_get_metadata).staticmethod("get_metadata");

    bind_typed_entity_map<Configuration>("ConfigurationContainer");

    bpy::class_<Project, auto_release_ptr<Project>, bpy::bases<Entity>, boost::noncopyable>("Project", bpy::no_init)
        .def("create_default", create_default_project).staticmethod("create_default")
        .def("create_cornell_box", create_cornell_box_project).staticmethod("create_cornell_box")

        .def("__init__", bpy::make_constructor(create_project))

        .def("add_default_configurations", &Project::add_default_configurations)

        .def("has_path", &Project::has_path)
        .def("set_path", &Project::set_path)
        .def("get_path", &Project::get_path)

        .def("get_search_paths", project_get_search_paths)
        .def("set_search_paths", project_set_search_paths)

        .def("set_scene", &Project::set_scene)
        .def("get_scene", &Project::get_scene, bpy::return_value_policy<bpy::reference_existing_object>())

        .def("set_frame", &Project::set_frame)
        .def("get_frame", &Project::get_frame, bpy::return_value_policy<bpy::reference_existing_object>())

        .def("get_display", &Project::get_display, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("set_display", &Project::set_display)

        .def("get_active_camera", &Project::get_uncached_active_camera, bpy::return_value_policy<bpy::reference_existing_object>())

        .def("configurations", project_get_configs, bpy::return_value_policy<bpy::reference_existing_object>())

        .def("create_aov_images", &Project::create_aov_images);

    bpy::enum_<ProjectFileReader::Options>("ProjectFileReaderOptions")
        .value("Defaults", ProjectFileReader::Defaults)
        .value("OmitReadingMeshFiles", ProjectFileReader::OmitReadingMeshFiles)
        .value("OmitProjectFileUpdate", ProjectFileReader::OmitProjectFileUpdate);

    bpy::class_<ProjectFileReader>("ProjectFileReader")
        .def("read", &project_file_reader_read_default_opts)
        .def("read", &project_file_reader_read_with_opts)
        .def("load_builtin", &project_file_reader_load_builtin);

    bpy::enum_<ProjectFileWriter::Options>("ProjectFileWriterOptions")
        .value("Defaults", ProjectFileWriter::Defaults)
        .value("OmitHeaderComment", ProjectFileWriter::OmitHeaderComment)
        .value("OmitWritingGeometryFiles", ProjectFileWriter::OmitWritingGeometryFiles)
        .value("OmitHandlingAssetFiles", ProjectFileWriter::OmitHandlingAssetFiles)
        .value("CopyAllAssets", ProjectFileWriter::CopyAllAssets);

    bpy::class_<ProjectFileWriter>("ProjectFileWriter")
        // These methods are static but for symmetry with ProjectFileReader we're exposing them as non-static.
        .def("write", write_project_default_opts)
        .def("write", write_project_with_opts);
}
<commit_msg>Updated python ProjectFileReader options.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2012-2013 Esteban Tovagliari, Jupiter Jazz Limited
// Copyright (c) 2014-2016 Esteban Tovagliari, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// appleseed.python headers.
#include "pyseed.h" // has to be first, to avoid redefinition warnings
#include "bindentitycontainers.h"
#include "dict2dict.h"

// appleseed.renderer headers.
#include "renderer/api/display.h"
#include "renderer/api/frame.h"
#include "renderer/api/project.h"
#include "renderer/api/scene.h"

// appleseed.foundation headers.
#include "foundation/utility/searchpaths.h"

// Standard headers.
#include <cstddef>
#include <string>

namespace bpy = boost::python;
using namespace foundation;
using namespace renderer;
using namespace std;

// Work around a regression in Visual Studio 2015 Update 3.
#if defined(_MSC_VER) && _MSC_VER == 1900
namespace boost
{
    template <> Configuration const volatile* get_pointer<Configuration const volatile>(Configuration const volatile* p) { return p; }
    template <> Project const volatile* get_pointer<Project const volatile>(Project const volatile* p) { return p; }
}
#endif

namespace
{
    auto_release_ptr<Project> create_project(const string& name)
    {
        return ProjectFactory::create(name.c_str());
    }

    bpy::object create_default_project()
    {
        auto_release_ptr<Project> project(DefaultProjectFactory::create());
        return bpy::object(project);
    }

    bpy::object create_cornell_box_project()
    {
        auto_release_ptr<Project> project(CornellBoxProjectFactory::create());
        return bpy::object(project);
    }

    bpy::list project_get_search_paths(const Project* project)
    {
        bpy::list paths;

        const SearchPaths& search_paths = project->search_paths();

        for (size_t i = 0; i < search_paths.size(); ++i)
            paths.append(search_paths[i]);

        return paths;
    }

    void project_set_search_paths(Project* project, const bpy::list& paths)
    {
        project->search_paths().clear();

        for (bpy::ssize_t i = 0, e = bpy::len(paths); i < e; ++i)
        {
            const bpy::extract<const char*> extractor(paths[i]);
            if (extractor.check())
                project->search_paths().push_back(extractor());
            else
            {
                PyErr_SetString(PyExc_TypeError, "Incompatible type. Only strings accepted.");
                bpy::throw_error_already_set();
            }
        }
    }

    ConfigurationContainer* project_get_configs(Project* project)
    {
        return &(project->configurations());
    }

    bool write_project_default_opts(
        const ProjectFileWriter*            writer,
        const Project*                      project,
        const char*                         filepath)
    {
        return ProjectFileWriter::write(*project, filepath);
    }

    bool write_project_with_opts(
        const ProjectFileWriter*            writer,
        const Project*                      project,
        const char*                         filepath,
        int                                 opts)
    {
        return ProjectFileWriter::write(*project, filepath, opts);
    }

    auto_release_ptr<Configuration> create_config(const string& name)
    {
        return ConfigurationFactory::create(name.c_str());
    }

    auto_release_ptr<Configuration> create_config_with_params(
        const string&                       name,
        const bpy::dict&                    params)
    {
        return ConfigurationFactory::create(name.c_str(), bpy_dict_to_param_array(params));
    }

    bpy::object create_base_final_config()
    {
        auto_release_ptr<Configuration> config(BaseConfigurationFactory::create_base_final());
        return bpy::object(config);
    }

    bpy::object create_base_interactive_config()
    {
        auto_release_ptr<Configuration> config(BaseConfigurationFactory::create_base_interactive());
        return bpy::object(config);
    }

    bpy::dict config_get_inherited_parameters(const Configuration* config)
    {
        ParamArray params(config->get_inherited_parameters());
        return param_array_to_bpy_dict(params);
    }

    void config_insert_path(Configuration* config, const char* path, const bpy::object& value)
    {
        {
            bpy::extract<const char*> extractor(value);
            if (extractor.check())
            {
                config->get_parameters().insert_path(path, extractor());
                return;
            }
        }

        if (PyBool_Check(value.ptr()))
        {
            bpy::extract<bool> extractor(value);
            if (extractor.check())
            {
                config->get_parameters().insert_path(path, extractor());
                return;
            }
        }

#if PY_MAJOR_VERSION == 2
        if (PyInt_Check(value.ptr()))
        {
            bpy::extract<int> extractor(value);
            if (extractor.check())
            {
                config->get_parameters().insert_path(path, extractor());
                return;
            }
        }
#endif

        if (PyLong_Check(value.ptr()))
        {
            bpy::extract<int> extractor(value);
            if (extractor.check())
            {
                config->get_parameters().insert_path(path, extractor());
                return;
            }
        }

        if (PyFloat_Check(value.ptr()))
        {
            bpy::extract<double> extractor(value);
            if (extractor.check())
            {
                config->get_parameters().insert_path(path, extractor());
                return;
            }
        }

        PyErr_SetString(PyExc_TypeError, "Unsupported value type.");
        bpy::throw_error_already_set();
    }

    void config_remove_path(Configuration* config, const char* path)
    {
        config->get_parameters().remove_path(path);
    }

    bpy::dict config_get_metadata()
    {
        return dictionary_to_bpy_dict(Configuration::get_metadata());
    }

    bpy::object project_file_reader_read_default_opts(
        ProjectFileReader*                  reader,
        const char*                         project_filename,
        const char*                         schema_filename)
    {
        auto_release_ptr<Project> project(reader->read(project_filename, schema_filename));
        return bpy::object(project);
    }

    bpy::object project_file_reader_read_with_opts(
        ProjectFileReader*                  reader,
        const char*                         project_filename,
        const char*                         schema_filename,
        const ProjectFileReader::Options    opts)
    {
        auto_release_ptr<Project> project(reader->read(project_filename, schema_filename, opts));
        return bpy::object(project);
    }

    bpy::object project_file_reader_load_builtin(ProjectFileReader* reader, const char* project_name)
    {
        auto_release_ptr<Project> project(reader->load_builtin(project_name));
        return bpy::object(project);
    }
}

void bind_project()
{
    bpy::class_<Configuration, auto_release_ptr<Configuration>, bpy::bases<Entity>, boost::noncopyable>("Configuration", bpy::no_init)
        .def("create_base_final", create_base_final_config).staticmethod("create_base_final")
        .def("create_base_interactive", create_base_interactive_config).staticmethod("create_base_interactive")

        .def("__init__", bpy::make_constructor(create_config))
        .def("__init__", bpy::make_constructor(create_config_with_params))

        .def("set_base", &Configuration::set_base)
        .def("get_base", &Configuration::get_base, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("get_inherited_parameters", config_get_inherited_parameters)

        .def("insert_path", config_insert_path)
        .def("remove_path", config_remove_path)

        .def("get_metadata", config_get_metadata).staticmethod("get_metadata");

    bind_typed_entity_map<Configuration>("ConfigurationContainer");

    bpy::class_<Project, auto_release_ptr<Project>, bpy::bases<Entity>, boost::noncopyable>("Project", bpy::no_init)
        .def("create_default", create_default_project).staticmethod("create_default")
        .def("create_cornell_box", create_cornell_box_project).staticmethod("create_cornell_box")

        .def("__init__", bpy::make_constructor(create_project))

        .def("add_default_configurations", &Project::add_default_configurations)

        .def("has_path", &Project::has_path)
        .def("set_path", &Project::set_path)
        .def("get_path", &Project::get_path)

        .def("get_search_paths", project_get_search_paths)
        .def("set_search_paths", project_set_search_paths)

        .def("set_scene", &Project::set_scene)
        .def("get_scene", &Project::get_scene, bpy::return_value_policy<bpy::reference_existing_object>())

        .def("set_frame", &Project::set_frame)
        .def("get_frame", &Project::get_frame, bpy::return_value_policy<bpy::reference_existing_object>())

        .def("get_display", &Project::get_display, bpy::return_value_policy<bpy::reference_existing_object>())
        .def("set_display", &Project::set_display)

        .def("get_active_camera", &Project::get_uncached_active_camera, bpy::return_value_policy<bpy::reference_existing_object>())

        .def("configurations", project_get_configs, bpy::return_value_policy<bpy::reference_existing_object>())

        .def("create_aov_images", &Project::create_aov_images);

    bpy::enum_<ProjectFileReader::Options>("ProjectFileReaderOptions")
        .value("Defaults", ProjectFileReader::Defaults)
        .value("OmitReadingMeshFiles", ProjectFileReader::OmitReadingMeshFiles)
        .value("OmitProjectFileUpdate", ProjectFileReader::OmitProjectFileUpdate)
        .value("OmitSearchPaths", ProjectFileReader::OmitSearchPaths)
        .value("OmitProjectSchemaValidation", ProjectFileReader::OmitProjectSchemaValidation);

    bpy::class_<ProjectFileReader>("ProjectFileReader")
        .def("read", &project_file_reader_read_default_opts)
        .def("read", &project_file_reader_read_with_opts)
        .def("load_builtin", &project_file_reader_load_builtin);

    bpy::enum_<ProjectFileWriter::Options>("ProjectFileWriterOptions")
        .value("Defaults", ProjectFileWriter::Defaults)
        .value("OmitHeaderComment", ProjectFileWriter::OmitHeaderComment)
        .value("OmitWritingGeometryFiles", ProjectFileWriter::OmitWritingGeometryFiles)
        .value("OmitHandlingAssetFiles", ProjectFileWriter::OmitHandlingAssetFiles)
        .value("CopyAllAssets", ProjectFileWriter::CopyAllAssets);

    bpy::class_<ProjectFileWriter>("ProjectFileWriter")
        // These methods are static but for symmetry with ProjectFileReader we're exposing them as non-static.
        .def("write", write_project_default_opts)
        .def("write", write_project_with_opts);
}
<|endoftext|>


<commit_before>#pragma once

#include <boost/optional.hpp>

#include <glm/vec3.hpp>
#include <glm/gtx/vec1.hpp>

#include "../glew.detail/c.hxx"
#include "../glew.detail/gl_type.hxx"
#include "../glew.detail/error.hxx"

#include "../stblib.hxx"

// assimp::Importer
#include <assimp/Importer.hpp>
// aiPostProcessSteps for assimp::Importer::ReadFile
#include <assimp/postprocess.h>
// aiScene, aiNode
#include <assimp/scene.h>

namespace wonder_rabbit_project
{
  namespace wonderland
  {
    namespace renderer
    {
      namespace model
      {
        class material_t
        {
          boost::optional< glm::vec3 > _diffuse;
          boost::optional< glm::vec3 > _ambient;
          boost::optional< glm::vec3 > _specular;
          boost::optional< glm::vec3 > _emissive;
          boost::optional< glm::vec1 > _transparent;
          boost::optional< glm::vec1 > _reflective;

          glew::gl_type::GLuint _texture_id;
#ifdef GL_VERSION_3_3
          // need  for modern GL3
          glew::gl_type::GLuint _sampler_id;
#endif

        public:

          ~material_t()
          {
            glew::c::glDeleteTextures( 1, &_texture_id );
          }

          material_t( aiMaterial* material, const std::string& path_prefix = "" )
          {
            // マテリアルカラー
            {
              aiColor3D result;
              if( material -> Get( AI_MATKEY_COLOR_DIFFUSE, result ) == aiReturn_SUCCESS )
                _diffuse = { result.r, result.g, result.b };
              if( material -> Get( AI_MATKEY_COLOR_AMBIENT, result ) == aiReturn_SUCCESS )
                _ambient = { result.r, result.g, result.b };
              if( material -> Get( AI_MATKEY_COLOR_SPECULAR, result ) == aiReturn_SUCCESS )
                _specular = { result.r, result.g, result.b };
              if( material -> Get( AI_MATKEY_COLOR_EMISSIVE, result ) == aiReturn_SUCCESS )
                _emissive = { result.r, result.g, result.b };
              if( material -> Get( AI_MATKEY_COLOR_TRANSPARENT, result ) == aiReturn_SUCCESS )
                _transparent = result.r;
              if( material -> Get( AI_MATKEY_COLOR_REFLECTIVE, result ) == aiReturn_SUCCESS )
                _reflective = result.r;
            }

            // テクスチャー
            const auto count_of_textures = material -> GetTextureCount(aiTextureType_DIFFUSE);
            for ( auto number_of_texture = 0u; number_of_texture < count_of_textures; ++number_of_texture )
            {
              aiString path;
              material -> GetTexture( aiTextureType_DIFFUSE, number_of_texture, &path, nullptr, nullptr, nullptr, nullptr, nullptr );

              stblib::image_loader_t loader;

              try
              {
                stblib::image_loader_t loader_( path_prefix.size() ? path_prefix + "/" + path.C_Str() : path.C_Str() );
                loader = std::move( loader_ );
              }
              catch( const std::runtime_error& e )
              {
                std::cerr << "warn: " << e.what() << " " << ( path_prefix.size() ? path_prefix + "/" + path.C_Str() : path.C_Str() ) << "; skip the texture.\n";
                continue;
              }

              glew::gl_type::GLenum internal_format;
              glew::gl_type::GLenum format;
              switch( loader.count_of_pixel_elements() )
              {
                case 4: internal_format = GL_RGBA8; format = GL_RGBA; break;
                case 3: internal_format = GL_RGB8;  format = GL_RGB;  break;
                case 2: internal_format = GL_RG8;   format = GL_RG;   break;
                case 1: internal_format = GL_R8;    format = GL_R;    break;
                default: throw std::runtime_error( "unsupported count_of_pixel_elements" );
              }
              const glew::gl_type::GLsizei width = loader.width();
              const glew::gl_type::GLsizei height = loader.height();
              constexpr glew::gl_type::GLenum type = GL_UNSIGNED_BYTE;
              const void* data = loader.data();

              glew::c::glPixelStorei( GL_UNPACK_ALIGNMENT, loader.count_of_pixel_elements() == 4 ? 4 : 1 );

              glew::test_error( __FILE__, __LINE__ );

              // step.1: generate texture buffer
              // glGenTextures / GL_1_1
              //  http://www.opengl.org/wiki/GLAPI/glGenTextures
              glew::c::glGenTextures( 1, &_texture_id );

              glew::test_error( __FILE__, __LINE__ );

              // glBindTexture / GL_1_1
              //  http://www.opengl.org/wiki/GLAPI/glBindTexture
              glew::c::glBindTexture( GL_TEXTURE_2D, _texture_id );

              glew::test_error( __FILE__, __LINE__ );

              // step.2: generate storage and load image
#if defined( GL_VERSION_4_2 )

              const glew::gl_type::GLsizei level = glm::log2<float>( std::min( width, height ) );
              // glTexStorage2D / GL_4_2
              //  http://www.opengl.org/wiki/GLAPI/glTexStorage2D
              //static auto counter = 0;
              //if ( counter++ == 0 ) internal_format = GL_RGB8; else internal_format = GL_RGB8;
              glew::c::glTexStorage2D( GL_TEXTURE_2D, level, internal_format, width, height );

              glew::test_error( __FILE__, __LINE__ );

              // glTexSubImage2D / GL_1_0
              //  http://www.opengl.org/wiki/GLAPI/glTexSubImage2D
              glew::c::glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, width, height, format, type, data );

              glew::test_error( __FILE__, __LINE__ );

#elif defined( GL_VERSION_3_0 )

              constexpr glew::gl_type::GLint border = 0; // this value must be 0: http://www.opengl.org/sdk/docs/man/html/glTexImage2D.xhtml
              constexpr glew::gl_type::GLint level  = 0;
  #if EMSCRIPTEN
              internal_format = format;
  #endif
              glew::c::glTexImage2D( GL_TEXTURE_2D, level, internal_format, width, height, border, format, type, data );
              glew::test_error( __FILE__, __LINE__ );

#elif defined( GL_VERSION_1_4 )

              // warning: these medhod is deprecated in GL_3_0, removed in GL_3_1.
              //  within throught step.3 and step.4.
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexImage2D( GL_TEXTURE_2D, level, internal_format, width, height, border, format, type, data );
              glew::test_error( __FILE__, __LINE__ );

#else

              // no mipmap
              constexpr glew::gl_type::GLint level = 0;
              glew::c::glTexImage2D( GL_TEXTURE_2D, level, internal_format, width, height, border, format, type, data );

              glew::test_error( __FILE__, __LINE__ );

#endif

              // step.3: generate mipmaps
#if defined( GL_VERSION_3_0 )

              // glGenerateMipmap / GL_3_0
              //  http://www.opengl.org/wiki/GLAPI/glGenerateMipmap
              glew::c::glGenerateMipmap( GL_TEXTURE_2D );

              glew::test_error( __FILE__, __LINE__ );

#endif

              // step.4: set sampler params
#if defined( GL_VERSION_3_3 )
              // glGenSamplers / GL_3_3
              //  http://www.opengl.org/wiki/GLAPI/glGenSamplers
              glew::c::glGenSamplers( 1, &_sampler_id );

              glew::c::glSamplerParameteri( _sampler_id, GL_TEXTURE_WRAP_S, GL_REPEAT );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glSamplerParameteri( _sampler_id, GL_TEXTURE_WRAP_T, GL_REPEAT );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glSamplerParameteri( _sampler_id, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glSamplerParameteri( _sampler_id, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
              glew::test_error( __FILE__, __LINE__ );

#elif defined( GL_VERSION_3_0 )
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
              glew::test_error( __FILE__, __LINE__ );
              #elif defined( GL_VERSION_1_4 )
              // nothing to do. this step done before at this version.
#else
              // no mipmap
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
              glew::test_error( __FILE__, __LINE__ );
#endif

            }
          }

          auto draw() const -> void
          {
            glew::gl_type::GLint program_id;
            glew::c::glGetIntegerv( GL_CURRENT_PROGRAM, &program_id );

            if ( program_id )
            {

#define WRP_TMP( WRP_TMP_X, WRP_TMP_Y, WRP_TMP_Z ) \
              const auto location_of_ ## WRP_TMP_X = glew::c::glGetUniformLocation( program_id, # WRP_TMP_X ); \
              if ( location_of_ ## WRP_TMP_X not_eq -1 ) \
              { \
                if ( _ ## WRP_TMP_X ) \
                  glew::c::glUniform ## WRP_TMP_Y ## fv( location_of_ ## WRP_TMP_X , 1, & _ ## WRP_TMP_X .get().x ); \
                else \
                  glew::c::glUniform ## WRP_TMP_Y ## fv( location_of_ ## WRP_TMP_X , 1, & WRP_TMP_Z [0] ); \
              }

              WRP_TMP( diffuse    , 3, glm::vec3( 1.0f ) )
              WRP_TMP( ambient    , 3, glm::vec3( 0.0f ) )
              WRP_TMP( specular   , 3, glm::vec3( 0.0f ) )
              WRP_TMP( emissive   , 3, glm::vec3( 0.0f ) )
              WRP_TMP( transparent, 1, glm::vec1( 1.0f ) )
              WRP_TMP( reflective , 1, glm::vec1( 0.0f ) )

#undef WRP_TMP
            }
#ifdef GL_VERSION_1_3
            glew::c::glActiveTexture( GL_TEXTURE0 );
#endif
            // GL_1_1
            glew::c::glBindTexture( GL_TEXTURE_2D, _texture_id );
#ifdef GL_VERSION_3_3
            glew::c::glBindSampler( 0, _sampler_id );
#endif
          }
        };
      }
    }
  }
}<commit_msg>fix #20 SEGV if load .x generated from metaseq<commit_after>#pragma once

#include <boost/optional.hpp>

#include <glm/vec3.hpp>
#include <glm/gtx/vec1.hpp>

#include "../glew.detail/c.hxx"
#include "../glew.detail/gl_type.hxx"
#include "../glew.detail/error.hxx"

#include "../stblib.hxx"

// assimp::Importer
#include <assimp/Importer.hpp>
// aiPostProcessSteps for assimp::Importer::ReadFile
#include <assimp/postprocess.h>
// aiScene, aiNode
#include <assimp/scene.h>

namespace wonder_rabbit_project
{
  namespace wonderland
  {
    namespace renderer
    {
      namespace model
      {
        class material_t
        {
          boost::optional< glm::vec3 > _diffuse;
          boost::optional< glm::vec3 > _ambient;
          boost::optional< glm::vec3 > _specular;
          boost::optional< glm::vec3 > _emissive;
          boost::optional< glm::vec1 > _transparent;
          boost::optional< glm::vec1 > _reflective;

          glew::gl_type::GLuint _texture_id;
#ifdef GL_VERSION_3_3
          // need  for modern GL3
          glew::gl_type::GLuint _sampler_id;
#endif

        public:

          ~material_t()
          {
            glew::c::glDeleteTextures( 1, &_texture_id );
          }

          material_t( aiMaterial* material, const std::string& path_prefix = "" )
          {
            // マテリアルカラー
            {
              aiColor3D result;
              if( material -> Get( AI_MATKEY_COLOR_DIFFUSE, result ) == aiReturn_SUCCESS )
                _diffuse = { result.r, result.g, result.b };
              if( material -> Get( AI_MATKEY_COLOR_AMBIENT, result ) == aiReturn_SUCCESS )
                _ambient = { result.r, result.g, result.b };
              if( material -> Get( AI_MATKEY_COLOR_SPECULAR, result ) == aiReturn_SUCCESS )
                _specular = { result.r, result.g, result.b };
              if( material -> Get( AI_MATKEY_COLOR_EMISSIVE, result ) == aiReturn_SUCCESS )
                _emissive = { result.r, result.g, result.b };
              if( material -> Get( AI_MATKEY_COLOR_TRANSPARENT, result ) == aiReturn_SUCCESS )
                _transparent = result.r;
              if( material -> Get( AI_MATKEY_COLOR_REFLECTIVE, result ) == aiReturn_SUCCESS )
                _reflective = result.r;
            }

            // テクスチャー
            const auto count_of_textures = material -> GetTextureCount(aiTextureType_DIFFUSE);
            for ( auto number_of_texture = 0u; number_of_texture < count_of_textures; ++number_of_texture )
            {
              aiString path;
              material -> GetTexture( aiTextureType_DIFFUSE, number_of_texture, &path, nullptr, nullptr, nullptr, nullptr, nullptr );

              stblib::image_loader_t loader;

              try
              {
                stblib::image_loader_t loader_( path_prefix.size() ? path_prefix + "/" + path.C_Str() : path.C_Str() );
                loader = std::move( loader_ );
              }
              catch( const std::runtime_error& e )
              {
                std::cerr << "warn: " << e.what() << " " << ( path_prefix.size() ? path_prefix + "/" + path.C_Str() : path.C_Str() ) << "; skip the texture.\n";
                continue;
              }

              glew::gl_type::GLenum internal_format;
              glew::gl_type::GLenum format;
              switch( loader.count_of_pixel_elements() )
              {
                case 4: internal_format = GL_RGBA8; format = GL_RGBA; break;
                case 3: internal_format = GL_RGB8;  format = GL_RGB;  break;
                case 2: internal_format = GL_RG8;   format = GL_RG;   break;
                case 1: internal_format = GL_R8;    format = GL_R;    break;
                default: throw std::runtime_error( "unsupported count_of_pixel_elements" );
              }
              const glew::gl_type::GLsizei width = loader.width();
              const glew::gl_type::GLsizei height = loader.height();
              constexpr glew::gl_type::GLenum type = GL_UNSIGNED_BYTE;
              const void* data = loader.data();

              glew::c::glPixelStorei( GL_UNPACK_ALIGNMENT, loader.count_of_pixel_elements() == 4 ? 4 : 1 );

              glew::test_error( __FILE__, __LINE__ );

              // step.1: generate texture buffer
              // glGenTextures / GL_1_1
              //  http://www.opengl.org/wiki/GLAPI/glGenTextures
              glew::c::glGenTextures( 1, &_texture_id );

              glew::test_error( __FILE__, __LINE__ );

              // glBindTexture / GL_1_1
              //  http://www.opengl.org/wiki/GLAPI/glBindTexture
              glew::c::glBindTexture( GL_TEXTURE_2D, _texture_id );

              glew::test_error( __FILE__, __LINE__ );

              // step.2: generate storage and load image
#if defined( GL_VERSION_4_2 )

              const glew::gl_type::GLsizei level = glm::log2<float>( std::min( width, height ) );
              // glTexStorage2D / GL_4_2
              //  http://www.opengl.org/wiki/GLAPI/glTexStorage2D
              //static auto counter = 0;
              //if ( counter++ == 0 ) internal_format = GL_RGB8; else internal_format = GL_RGB8;
              glew::c::glTexStorage2D( GL_TEXTURE_2D, level, internal_format, width, height );

              glew::test_error( __FILE__, __LINE__ );

              // glTexSubImage2D / GL_1_0
              //  http://www.opengl.org/wiki/GLAPI/glTexSubImage2D
              glew::c::glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, width, height, format, type, data );

              glew::test_error( __FILE__, __LINE__ );

#elif defined( GL_VERSION_3_0 )

              constexpr glew::gl_type::GLint border = 0; // this value must be 0: http://www.opengl.org/sdk/docs/man/html/glTexImage2D.xhtml
              constexpr glew::gl_type::GLint level  = 0;
  #if EMSCRIPTEN
              internal_format = format;
  #endif
              glew::c::glTexImage2D( GL_TEXTURE_2D, level, internal_format, width, height, border, format, type, data );
              glew::test_error( __FILE__, __LINE__ );

#elif defined( GL_VERSION_1_4 )

              // warning: these medhod is deprecated in GL_3_0, removed in GL_3_1.
              //  within throught step.3 and step.4.
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexImage2D( GL_TEXTURE_2D, level, internal_format, width, height, border, format, type, data );
              glew::test_error( __FILE__, __LINE__ );

#else

              // no mipmap
              constexpr glew::gl_type::GLint level = 0;
              glew::c::glTexImage2D( GL_TEXTURE_2D, level, internal_format, width, height, border, format, type, data );

              glew::test_error( __FILE__, __LINE__ );

#endif

              // step.3: generate mipmaps
#if defined( GL_VERSION_3_0 )

              // glGenerateMipmap / GL_3_0
              //  http://www.opengl.org/wiki/GLAPI/glGenerateMipmap
              glew::c::glGenerateMipmap( GL_TEXTURE_2D );

              glew::test_error( __FILE__, __LINE__ );

#endif

              // step.4: set sampler params
#if defined( GL_VERSION_3_3 )
              // glGenSamplers / GL_3_3
              //  http://www.opengl.org/wiki/GLAPI/glGenSamplers
              glew::c::glGenSamplers( 1, &_sampler_id );

              glew::c::glSamplerParameteri( _sampler_id, GL_TEXTURE_WRAP_S, GL_REPEAT );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glSamplerParameteri( _sampler_id, GL_TEXTURE_WRAP_T, GL_REPEAT );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glSamplerParameteri( _sampler_id, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glSamplerParameteri( _sampler_id, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
              glew::test_error( __FILE__, __LINE__ );

#elif defined( GL_VERSION_3_0 )
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
              glew::test_error( __FILE__, __LINE__ );
              #elif defined( GL_VERSION_1_4 )
              // nothing to do. this step done before at this version.
#else
              // no mipmap
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
              glew::test_error( __FILE__, __LINE__ );
              glew::c::glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
              glew::test_error( __FILE__, __LINE__ );
#endif

            }
          }

          auto draw() const -> void
          {
            glew::gl_type::GLint program_id;
            glew::c::glGetIntegerv( GL_CURRENT_PROGRAM, &program_id );

            if ( program_id )
            {

#define WRP_TMP( WRP_TMP_X, WRP_TMP_Y, WRP_TMP_Z ) \
              const auto location_of_ ## WRP_TMP_X = glew::c::glGetUniformLocation( program_id, # WRP_TMP_X ); \
              if ( location_of_ ## WRP_TMP_X not_eq -1 ) \
              { \
                if ( _ ## WRP_TMP_X ) \
                  glew::c::glUniform ## WRP_TMP_Y ## fv( location_of_ ## WRP_TMP_X , 1, & _ ## WRP_TMP_X .get().x ); \
                else \
                  glew::c::glUniform ## WRP_TMP_Y ## fv( location_of_ ## WRP_TMP_X , 1, & WRP_TMP_Z [0] ); \
              }

              WRP_TMP( diffuse    , 3, glm::vec3( 1.0f ) )
              WRP_TMP( ambient    , 3, glm::vec3( 0.0f ) )
              WRP_TMP( specular   , 3, glm::vec3( 0.0f ) )
              WRP_TMP( emissive   , 3, glm::vec3( 0.0f ) )
              WRP_TMP( transparent, 1, glm::vec1( 1.0f ) )
              WRP_TMP( reflective , 1, glm::vec1( 0.0f ) )

#undef WRP_TMP
            }

#ifdef GL_VERSION_1_3
            glew::c::glActiveTexture( GL_TEXTURE0 );
#endif
            // GL_1_1
            glew::c::glBindTexture( GL_TEXTURE_2D, _texture_id );
#ifdef GL_VERSION_3_3
            glew::c::glBindSampler( 0, _sampler_id );
#endif

          }
        };
      }
    }
  }
}<|endoftext|>


<commit_before>//===--- index-test.cpp - Indexing test bed -------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This utility may be invoked in the following manner:
//   index-test --help                - Output help info.
//   index-test [options]             - Read from stdin.
//   index-test [options] file        - Read from "file".
//   index-test [options] file1 file2 - Read these files.
//
//  Files must be AST files.
//
//===----------------------------------------------------------------------===//
//
//   -point-at  [file:column:line]
//       Point at a declaration/statement/expression. If no other operation is
//       specified, prints some info about it.
//
//   -print-refs
//       Print ASTLocations that reference the -point-at node
//
//   -print-defs
//       Print ASTLocations that define the -point-at node
//
//   -print-decls
//       Print ASTLocations that declare the -point-at node
//
//===----------------------------------------------------------------------===//

#include "clang/Index/Program.h"
#include "clang/Index/IndexProvider.h"
#include "clang/Index/Entity.h"
#include "clang/Index/TranslationUnit.h"
#include "clang/Index/ASTLocation.h"
#include "clang/Index/DeclReferenceMap.h"
#include "clang/Index/Utils.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CommandLineSourceLoc.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Signals.h"
using namespace clang;
using namespace idx;

class TUnit : public TranslationUnit {
public:
  TUnit(ASTUnit *ast, const std::string &filename)
    : AST(ast), Filename(filename) { }

  virtual ASTContext &getASTContext() { return AST->getASTContext(); }

  llvm::OwningPtr<ASTUnit> AST;
  std::string Filename;
};

static llvm::cl::list<ParsedSourceLocation>
PointAtLocation("point-at", llvm::cl::Optional,
                 llvm::cl::value_desc("source-location"),
   llvm::cl::desc("Point at the given source location of the first AST file"));

enum ProgActions {
  PrintPoint,     // Just print the point-at node
  PrintRefs,      // Print references of the point-at node
  PrintDefs,      // Print definitions of the point-at node
  PrintDecls      // Print declarations of the point-at node
};

static llvm::cl::opt<ProgActions>
ProgAction(
        llvm::cl::desc("Choose action to perform on the pointed-at AST node:"),
        llvm::cl::ZeroOrMore,
           llvm::cl::init(PrintPoint),
           llvm::cl::values(
             clEnumValN(PrintRefs, "print-refs",
                        "Print references"),
             clEnumValN(PrintDefs, "print-defs",
                        "Print definitions"),
             clEnumValN(PrintDecls, "print-decls",
                        "Print declarations"),
             clEnumValEnd));

static llvm::cl::opt<bool>
DisableFree("disable-free",
           llvm::cl::desc("Disable freeing of memory on exit"),
           llvm::cl::init(false));

static void ProcessDecl(Decl *D) {
  assert(D);
  llvm::raw_ostream &OS = llvm::outs();

  switch (ProgAction) {
  default: assert(0);
  case PrintRefs: {
    NamedDecl *ND = dyn_cast<NamedDecl>(D);
    if (!ND)
      return;

    DeclReferenceMap RefMap(ND->getASTContext());
    for (DeclReferenceMap::astlocation_iterator
           I = RefMap.refs_begin(ND), E = RefMap.refs_end(ND); I != E; ++I)
      I->print(OS);
    break;
  }

  case PrintDefs: {
    const Decl *DefD = 0;
    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
      const FunctionDecl *DFD = 0;
      FD->getBody(DFD);
      DefD = DFD;
    } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
      const VarDecl *DVD = 0;
      VD->getDefinition(DVD);
      DefD = DVD;
    }

    if (DefD)
      ASTLocation(DefD).print(OS);
    break;
  }

  case PrintDecls :
    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
      while (FD) {
        ASTLocation(FD).print(OS);
        FD = FD->getPreviousDeclaration();
      }
    } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
      while (VD) {
        ASTLocation(VD).print(OS);
        VD = VD->getPreviousDeclaration();
      }
    } else
      ASTLocation(D).print(OS);
    break;

  }
}

static void ProcessASTLocation(ASTLocation ASTLoc, IndexProvider &IdxProvider) {
  assert(ASTLoc.isValid());

  Decl *D = 0;
  if (ASTLoc.isStmt()) {
    if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(ASTLoc.getStmt()))
      D = RefExpr->getDecl();
  } else {
    D = ASTLoc.getDecl();
  }
  assert(D);

  Entity *Ent = Entity::get(D, IdxProvider.getProgram());
  // If there is no Entity associated with this Decl, it means that it's not
  // visible to other translation units.
  if (!Ent)
    return ProcessDecl(D);

  // Find the "same" Decl in other translation units and print information.
  for (IndexProvider::translation_unit_iterator
         I = IdxProvider.translation_units_begin(Ent),
         E = IdxProvider.translation_units_end(Ent); I != E; ++I) {
    TUnit *TU = static_cast<TUnit*>(*I);
    Decl *OtherD = Ent->getDecl(TU->getASTContext());
    assert(OtherD && "Couldn't resolve Entity");
    ProcessDecl(OtherD);
  }
}

static llvm::cl::list<std::string>
InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input AST files>"));

int main(int argc, char **argv) {
  llvm::sys::PrintStackTraceOnErrorSignal();
  llvm::PrettyStackTraceProgram X(argc, argv);
  llvm::cl::ParseCommandLineOptions(argc, argv,
                     "LLVM 'Clang' Indexing Test Bed: http://clang.llvm.org\n");

  FileManager FileMgr;

  Program Prog;
  IndexProvider IdxProvider(Prog);
  llvm::SmallVector<TUnit*, 4> TUnits;

  // If no input was specified, read from stdin.
  if (InputFilenames.empty())
    InputFilenames.push_back("-");

  for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
    const std::string &InFile = InputFilenames[i];

    std::string ErrMsg;
    llvm::OwningPtr<ASTUnit> AST;

    AST.reset(ASTUnit::LoadFromPCHFile(InFile, FileMgr, &ErrMsg));
    if (!AST) {
      llvm::errs() << "[" << InFile << "] Error: " << ErrMsg << '\n';
      return 1;
    }

    TUnit *TU = new TUnit(AST.take(), InFile);
    TUnits.push_back(TU);

    IdxProvider.IndexAST(TU);
  }

  ASTLocation ASTLoc;
  const std::string &FirstFile = TUnits[0]->Filename;
  ASTUnit *FirstAST = TUnits[0]->AST.get();

  if (!PointAtLocation.empty()) {
    const std::string &Filename = PointAtLocation[0].FileName;
    const FileEntry *File = FileMgr.getFile(Filename);

    // Safety check. Using an out-of-date AST file will only lead to crashes
    // or incorrect results.
    // FIXME: Check all the source files that make up the AST file.
    const FileEntry *ASTFile = FileMgr.getFile(FirstFile);
    if (File->getModificationTime() > ASTFile->getModificationTime()) {
      llvm::errs() << "[" << FirstFile << "] Error: " <<
        "Pointing at a source file which was modified after creating "
        "the AST file\n";
      return 1;
    }

    if (File == 0) {
      llvm::errs() << "File '" << Filename << "' does not exist\n";
      return 1;
    }
    unsigned Line = PointAtLocation[0].Line;
    unsigned Col = PointAtLocation[0].Column;

    SourceLocation Loc =
      FirstAST->getSourceManager().getLocation(File, Line, Col);
    if (Loc.isInvalid()) {
      llvm::errs() << "[" << FirstFile << "] Error: " <<
        "Couldn't resolve source location (invalid location)\n";
      return 1;
    }

    ASTLoc = ResolveLocationInAST(FirstAST->getASTContext(), Loc);
    if (ASTLoc.isInvalid()) {
      llvm::errs() << "[" << FirstFile << "] Error: " <<
        "Couldn't resolve source location (no declaration found)\n";
      return 1;
    }
  }

  if (ASTLoc.isValid()) {
    if (ProgAction == PrintPoint) {
      llvm::raw_ostream &OS = llvm::outs();
      ASTLoc.print(OS);
      if (const char *Comment =
            FirstAST->getASTContext().getCommentForDecl(ASTLoc.getDecl()))
        OS << "Comment associated with this declaration:\n" << Comment << "\n";
    } else {
      ProcessASTLocation(ASTLoc, IdxProvider);
    }
  }

  if (!DisableFree) {
    for (int i=0, e=TUnits.size(); i != e; ++i)
      delete TUnits[i];
  }

  // Managed static deconstruction. Useful for making things like
  // -time-passes usable.
  llvm::llvm_shutdown();

  return 0;
}
<commit_msg>Fix comment.<commit_after>//===--- index-test.cpp - Indexing test bed -------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This utility may be invoked in the following manner:
//   index-test --help                - Output help info.
//   index-test [options]             - Read from stdin.
//   index-test [options] file        - Read from "file".
//   index-test [options] file1 file2 - Read these files.
//
//  Files must be AST files.
//
//===----------------------------------------------------------------------===//
//
//   -point-at  [file:line:column]
//       Point at a declaration/statement/expression. If no other operation is
//       specified, prints some info about it.
//
//   -print-refs
//       Print ASTLocations that reference the -point-at node
//
//   -print-defs
//       Print ASTLocations that define the -point-at node
//
//   -print-decls
//       Print ASTLocations that declare the -point-at node
//
//===----------------------------------------------------------------------===//

#include "clang/Index/Program.h"
#include "clang/Index/IndexProvider.h"
#include "clang/Index/Entity.h"
#include "clang/Index/TranslationUnit.h"
#include "clang/Index/ASTLocation.h"
#include "clang/Index/DeclReferenceMap.h"
#include "clang/Index/Utils.h"
#include "clang/Frontend/ASTUnit.h"
#include "clang/Frontend/CommandLineSourceLoc.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Signals.h"
using namespace clang;
using namespace idx;

class TUnit : public TranslationUnit {
public:
  TUnit(ASTUnit *ast, const std::string &filename)
    : AST(ast), Filename(filename) { }

  virtual ASTContext &getASTContext() { return AST->getASTContext(); }

  llvm::OwningPtr<ASTUnit> AST;
  std::string Filename;
};

static llvm::cl::list<ParsedSourceLocation>
PointAtLocation("point-at", llvm::cl::Optional,
                 llvm::cl::value_desc("source-location"),
   llvm::cl::desc("Point at the given source location of the first AST file"));

enum ProgActions {
  PrintPoint,     // Just print the point-at node
  PrintRefs,      // Print references of the point-at node
  PrintDefs,      // Print definitions of the point-at node
  PrintDecls      // Print declarations of the point-at node
};

static llvm::cl::opt<ProgActions>
ProgAction(
        llvm::cl::desc("Choose action to perform on the pointed-at AST node:"),
        llvm::cl::ZeroOrMore,
           llvm::cl::init(PrintPoint),
           llvm::cl::values(
             clEnumValN(PrintRefs, "print-refs",
                        "Print references"),
             clEnumValN(PrintDefs, "print-defs",
                        "Print definitions"),
             clEnumValN(PrintDecls, "print-decls",
                        "Print declarations"),
             clEnumValEnd));

static llvm::cl::opt<bool>
DisableFree("disable-free",
           llvm::cl::desc("Disable freeing of memory on exit"),
           llvm::cl::init(false));

static void ProcessDecl(Decl *D) {
  assert(D);
  llvm::raw_ostream &OS = llvm::outs();

  switch (ProgAction) {
  default: assert(0);
  case PrintRefs: {
    NamedDecl *ND = dyn_cast<NamedDecl>(D);
    if (!ND)
      return;

    DeclReferenceMap RefMap(ND->getASTContext());
    for (DeclReferenceMap::astlocation_iterator
           I = RefMap.refs_begin(ND), E = RefMap.refs_end(ND); I != E; ++I)
      I->print(OS);
    break;
  }

  case PrintDefs: {
    const Decl *DefD = 0;
    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
      const FunctionDecl *DFD = 0;
      FD->getBody(DFD);
      DefD = DFD;
    } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
      const VarDecl *DVD = 0;
      VD->getDefinition(DVD);
      DefD = DVD;
    }

    if (DefD)
      ASTLocation(DefD).print(OS);
    break;
  }

  case PrintDecls :
    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
      while (FD) {
        ASTLocation(FD).print(OS);
        FD = FD->getPreviousDeclaration();
      }
    } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
      while (VD) {
        ASTLocation(VD).print(OS);
        VD = VD->getPreviousDeclaration();
      }
    } else
      ASTLocation(D).print(OS);
    break;

  }
}

static void ProcessASTLocation(ASTLocation ASTLoc, IndexProvider &IdxProvider) {
  assert(ASTLoc.isValid());

  Decl *D = 0;
  if (ASTLoc.isStmt()) {
    if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(ASTLoc.getStmt()))
      D = RefExpr->getDecl();
  } else {
    D = ASTLoc.getDecl();
  }
  assert(D);

  Entity *Ent = Entity::get(D, IdxProvider.getProgram());
  // If there is no Entity associated with this Decl, it means that it's not
  // visible to other translation units.
  if (!Ent)
    return ProcessDecl(D);

  // Find the "same" Decl in other translation units and print information.
  for (IndexProvider::translation_unit_iterator
         I = IdxProvider.translation_units_begin(Ent),
         E = IdxProvider.translation_units_end(Ent); I != E; ++I) {
    TUnit *TU = static_cast<TUnit*>(*I);
    Decl *OtherD = Ent->getDecl(TU->getASTContext());
    assert(OtherD && "Couldn't resolve Entity");
    ProcessDecl(OtherD);
  }
}

static llvm::cl::list<std::string>
InputFilenames(llvm::cl::Positional, llvm::cl::desc("<input AST files>"));

int main(int argc, char **argv) {
  llvm::sys::PrintStackTraceOnErrorSignal();
  llvm::PrettyStackTraceProgram X(argc, argv);
  llvm::cl::ParseCommandLineOptions(argc, argv,
                     "LLVM 'Clang' Indexing Test Bed: http://clang.llvm.org\n");

  FileManager FileMgr;

  Program Prog;
  IndexProvider IdxProvider(Prog);
  llvm::SmallVector<TUnit*, 4> TUnits;

  // If no input was specified, read from stdin.
  if (InputFilenames.empty())
    InputFilenames.push_back("-");

  for (unsigned i = 0, e = InputFilenames.size(); i != e; ++i) {
    const std::string &InFile = InputFilenames[i];

    std::string ErrMsg;
    llvm::OwningPtr<ASTUnit> AST;

    AST.reset(ASTUnit::LoadFromPCHFile(InFile, FileMgr, &ErrMsg));
    if (!AST) {
      llvm::errs() << "[" << InFile << "] Error: " << ErrMsg << '\n';
      return 1;
    }

    TUnit *TU = new TUnit(AST.take(), InFile);
    TUnits.push_back(TU);

    IdxProvider.IndexAST(TU);
  }

  ASTLocation ASTLoc;
  const std::string &FirstFile = TUnits[0]->Filename;
  ASTUnit *FirstAST = TUnits[0]->AST.get();

  if (!PointAtLocation.empty()) {
    const std::string &Filename = PointAtLocation[0].FileName;
    const FileEntry *File = FileMgr.getFile(Filename);

    // Safety check. Using an out-of-date AST file will only lead to crashes
    // or incorrect results.
    // FIXME: Check all the source files that make up the AST file.
    const FileEntry *ASTFile = FileMgr.getFile(FirstFile);
    if (File->getModificationTime() > ASTFile->getModificationTime()) {
      llvm::errs() << "[" << FirstFile << "] Error: " <<
        "Pointing at a source file which was modified after creating "
        "the AST file\n";
      return 1;
    }

    if (File == 0) {
      llvm::errs() << "File '" << Filename << "' does not exist\n";
      return 1;
    }
    unsigned Line = PointAtLocation[0].Line;
    unsigned Col = PointAtLocation[0].Column;

    SourceLocation Loc =
      FirstAST->getSourceManager().getLocation(File, Line, Col);
    if (Loc.isInvalid()) {
      llvm::errs() << "[" << FirstFile << "] Error: " <<
        "Couldn't resolve source location (invalid location)\n";
      return 1;
    }

    ASTLoc = ResolveLocationInAST(FirstAST->getASTContext(), Loc);
    if (ASTLoc.isInvalid()) {
      llvm::errs() << "[" << FirstFile << "] Error: " <<
        "Couldn't resolve source location (no declaration found)\n";
      return 1;
    }
  }

  if (ASTLoc.isValid()) {
    if (ProgAction == PrintPoint) {
      llvm::raw_ostream &OS = llvm::outs();
      ASTLoc.print(OS);
      if (const char *Comment =
            FirstAST->getASTContext().getCommentForDecl(ASTLoc.getDecl()))
        OS << "Comment associated with this declaration:\n" << Comment << "\n";
    } else {
      ProcessASTLocation(ASTLoc, IdxProvider);
    }
  }

  if (!DisableFree) {
    for (int i=0, e=TUnits.size(); i != e; ++i)
      delete TUnits[i];
  }

  // Managed static deconstruction. Useful for making things like
  // -time-passes usable.
  llvm::llvm_shutdown();

  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: ZConnectionWrapper.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: oj $ $Date: 2002-08-23 09:57:53 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_
#define _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_

#ifndef _CPPUHELPER_COMPBASE1_HXX_
#include <cppuhelper/compbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _CONNECTIVITY_ZCONNECTIONWRAPPER_HXX_
#include "connectivity/ConnectionWrapper.hxx"
#endif

#if SUPD < 643
    #define DECLARE_XINTERFACE( )   \
        virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw (::com::sun::star::uno::RuntimeException); \
        virtual void SAL_CALL acquire() throw(); \
        virtual void SAL_CALL release() throw();

    #define IMPLEMENT_FORWARD_REFCOUNT( classname, refcountbase ) \
        void SAL_CALL classname::acquire() throw() { refcountbase::acquire(); } \
        void SAL_CALL classname::release() throw() { refcountbase::release(); }

    #define IMPLEMENT_FORWARD_XINTERFACE2( classname, refcountbase, baseclass2 ) \
        IMPLEMENT_FORWARD_REFCOUNT( classname, refcountbase ) \
        ::com::sun::star::uno::Any SAL_CALL classname::queryInterface( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException) \
        { \
            ::com::sun::star::uno::Any aReturn = refcountbase::queryInterface( _rType ); \
            if ( !aReturn.hasValue() ) \
                aReturn = baseclass2::queryInterface( _rType ); \
            return aReturn; \
        }

    #define IMPLEMENT_FORWARD_XINTERFACE3( classname, refcountbase, baseclass2, baseclass3 ) \
        IMPLEMENT_FORWARD_REFCOUNT( classname, refcountbase ) \
        ::com::sun::star::uno::Any SAL_CALL classname::queryInterface( const ::com::sun::star::uno::Type& _rType ) throw (::com::sun::star::uno::RuntimeException) \
        { \
            ::com::sun::star::uno::Any aReturn = refcountbase::queryInterface( _rType ); \
            if ( !aReturn.hasValue() ) \
            { \
                aReturn = baseclass2::queryInterface( _rType ); \
                if ( !aReturn.hasValue() ) \
                    aReturn = baseclass3::queryInterface( _rType ); \
            } \
            return aReturn; \
        }
    //=====================================================================
    //= forwarding/merging XTypeProvider funtionality
    //=====================================================================
    #define DECLARE_XTYPEPROVIDER( )    \
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(  ) throw (::com::sun::star::uno::RuntimeException); \
        virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId(  ) throw (::com::sun::star::uno::RuntimeException);

    #define IMPLEMENT_GET_IMPLEMENTATION_ID( classname ) \
        ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL classname::getImplementationId(  ) throw (::com::sun::star::uno::RuntimeException) \
        { \
            static ::cppu::OImplementationId* pId = NULL; \
            if (!pId) \
            { \
                ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() ); \
                if (!pId) \
                { \
                    static ::cppu::OImplementationId aId; \
                    pId = &aId; \
                } \
            } \
            return pId->getImplementationId(); \
        }

    #define IMPLEMENT_FORWARD_XTYPEPROVIDER2( classname, baseclass1, baseclass2 ) \
        ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL classname::getTypes(  ) throw (::com::sun::star::uno::RuntimeException) \
        { \
            return ::comphelper::concatSequences( \
                baseclass1::getTypes(), \
                baseclass2::getTypes() \
            ); \
        } \
        \
        IMPLEMENT_GET_IMPLEMENTATION_ID( classname )

    #define IMPLEMENT_FORWARD_XTYPEPROVIDER3( classname, baseclass1, baseclass2, baseclass3 ) \
        ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL classname::getTypes(  ) throw (::com::sun::star::uno::RuntimeException) \
        { \
            return ::comphelper::concatSequences( \
                baseclass1::getTypes(), \
                baseclass2::getTypes(), \
                baseclass3::getTypes() \
            ); \
        } \
        \
        IMPLEMENT_GET_IMPLEMENTATION_ID( classname )
#endif // SUPD < 643

namespace connectivity
{

    //==========================================================================
    //= OConnectionWeakWrapper - wraps all methods to the real connection from the driver
    //= but when disposed it doesn't dispose the real connection
    //==========================================================================
    typedef ::cppu::WeakComponentImplHelper1<       ::com::sun::star::sdbc::XConnection
                                            > OConnectionWeakWrapper_BASE;

    class OConnectionWeakWrapper :   public ::comphelper::OBaseMutex
                                ,public OConnectionWeakWrapper_BASE
                                , public OConnectionWrapper
    {
    protected:
        // OComponentHelper
        virtual void SAL_CALL disposing(void);
        virtual ~OConnectionWeakWrapper();
    public:
        OConnectionWeakWrapper(::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation >& _xConnection);

        // XServiceInfo
        DECLARE_SERVICE_INFO();
        DECLARE_XTYPEPROVIDER()
        DECLARE_XINTERFACE( )

        // XConnection
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL nativeSQL( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL getAutoCommit(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL commit(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL rollback(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isClosed(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL setReadOnly( sal_Bool readOnly ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isReadOnly(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL setCatalog( const ::rtl::OUString& catalog ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getCatalog(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL setTransactionIsolation( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getTransactionIsolation(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTypeMap(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL setTypeMap( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        // XCloseable
        virtual void SAL_CALL close(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
    };
}
#endif // _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_

<commit_msg>INTEGRATION: CWS dba22 (1.5.234); FILE MERGED 2004/12/16 09:03:38 oj 1.5.234.1: #i39123# some clean ups<commit_after>/*************************************************************************
 *
 *  $RCSfile: ZConnectionWrapper.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: kz $ $Date: 2005-01-21 16:39:01 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_
#define _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_

#ifndef _CPPUHELPER_COMPBASE1_HXX_
#include <cppuhelper/compbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_
#include <com/sun/star/sdbc/XConnection.hpp>
#endif
#ifndef _COMPHELPER_BROADCASTHELPER_HXX_
#include <comphelper/broadcasthelper.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _CONNECTIVITY_ZCONNECTIONWRAPPER_HXX_
#include "connectivity/ConnectionWrapper.hxx"
#endif

namespace connectivity
{

    //==========================================================================
    //= OConnectionWeakWrapper - wraps all methods to the real connection from the driver
    //= but when disposed it doesn't dispose the real connection
    //==========================================================================
    typedef ::cppu::WeakComponentImplHelper1<       ::com::sun::star::sdbc::XConnection
                                            > OConnectionWeakWrapper_BASE;

    class OConnectionWeakWrapper :   public ::comphelper::OBaseMutex
                                ,public OConnectionWeakWrapper_BASE
                                , public OConnectionWrapper
    {
    protected:
        // OComponentHelper
        virtual void SAL_CALL disposing(void);
        virtual ~OConnectionWeakWrapper();
    public:
        OConnectionWeakWrapper(::com::sun::star::uno::Reference< ::com::sun::star::uno::XAggregation >& _xConnection);

        // XServiceInfo
        DECLARE_SERVICE_INFO();
        DECLARE_XTYPEPROVIDER()
        DECLARE_XINTERFACE( )

        // XConnection
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XStatement > SAL_CALL createStatement(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareStatement( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XPreparedStatement > SAL_CALL prepareCall( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL nativeSQL( const ::rtl::OUString& sql ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL setAutoCommit( sal_Bool autoCommit ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL getAutoCommit(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL commit(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL rollback(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isClosed(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData > SAL_CALL getMetaData(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL setReadOnly( sal_Bool readOnly ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Bool SAL_CALL isReadOnly(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL setCatalog( const ::rtl::OUString& catalog ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::rtl::OUString SAL_CALL getCatalog(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL setTransactionIsolation( sal_Int32 level ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual sal_Int32 SAL_CALL getTransactionIsolation(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > SAL_CALL getTypeMap(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        virtual void SAL_CALL setTypeMap( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        // XCloseable
        virtual void SAL_CALL close(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
    };
}
#endif // _CONNECTIVITY_ZCONNECTIONWEAKWRAPPER_HXX_

<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: MMFF94ConfigurationDialog.C,v 1.1.6.1 2007/03/25 22:00:39 oliver Exp $
//

#include <BALL/VIEW/DIALOGS/MMFF94ConfigurationDialog.h>
#include <BALL/VIEW/KERNEL/common.h>
#include <BALL/MOLMEC/MMFF94/MMFF94.h>
#include <BALL/MOLMEC/MMFF94/MMFF94NonBonded.h>
#include <BALL/MOLMEC/MMFF94/MMFF94StretchBend.h>
#include <BALL/MOLMEC/MMFF94/MMFF94Torsion.h>
#include <BALL/MOLMEC/MMFF94/MMFF94OutOfPlaneBend.h>
#include <BALL/MOLMEC/MMFF94/MMFF94Torsion.h>
#include <BALL/SYSTEM/path.h>

#include <QtGui/qlineedit.h>
#include <QtGui/qradiobutton.h>
#include <QtGui/qcheckbox.h>
#include <QtGui/qpushbutton.h>
#include <QtGui/QFileDialog>

namespace BALL
{
	namespace VIEW
	{

		MMFF94ConfigurationDialog::MMFF94ConfigurationDialog(QWidget* parent, const char* name)
			:	QDialog(parent),
				Ui_MMFF94ConfigurationDialogData(),
				PreferencesEntry(),
				mmff_(0)
		{
			setupUi(this);

			setINIFileSectionName("MMFF94");
			setObjectName(name);
			registerWidgets_();

			// signals and slots connections
			connect( close_button, SIGNAL( clicked() ), this, SLOT( accept() ) );
			connect( cancel_button, SIGNAL( clicked() ), this, SLOT( reject() ) );
			connect( reset_button, SIGNAL( clicked() ), this, SLOT( resetOptions() ) );
			connect( browse_button, SIGNAL( clicked() ), this, SLOT( browseParameterFiles() ) );
		}

		MMFF94ConfigurationDialog::~MMFF94ConfigurationDialog()
		{
		}

		void MMFF94ConfigurationDialog::browseParameterFiles()
		{
			// look up the full path of the parameter file
			Path p;
			String filename = p.find(ascii(parameter_file_edit->text()));

			if (filename == "")
			{
				filename = ascii(parameter_file_edit->text());
			}
			QString tmp = filename.c_str();
			QString result = QFileDialog::getExistingDirectory(0, "Select a folder with the MMFF94 parameter files", tmp);
			if (!result.isEmpty())
			{
				// store the new filename in the lineedit field
				parameter_file_edit->setText(result);
			}
		}

		void MMFF94ConfigurationDialog::reject()
		{
			hide();
			PreferencesEntry::restoreValues();
		}

		void MMFF94ConfigurationDialog::accept()
		{
			if (mmff_ != 0)
			{
				applyTo(*mmff_);
			}
			hide();
			PreferencesEntry::storeValues();
		}

		String MMFF94ConfigurationDialog::getValue_(const QCheckBox* box) const
		{
			if (box->isChecked()) return "true";
			else 									return "false";
		}

		float MMFF94ConfigurationDialog::getValue_(const QLineEdit* edit) const
			throw(Exception::InvalidFormat)
		{
			return ascii(edit->text()).toFloat();
		}

		void MMFF94ConfigurationDialog::applyTo(MMFF94& mmff)
			throw()
		{
			mmff.options[MMFF94_STRETCHES_ENABLED] = getValue_(stretch_box);
			mmff.options[MMFF94_BENDS_ENABLED] = getValue_(bends_box);
			mmff.options[MMFF94_STRETCHBENDS_ENABLED] = getValue_(stretch_bends_box);
			mmff.options[MMFF94_TORSIONS_ENABLED] = getValue_(torsions_box);
			mmff.options[MMFF94_OUTOFPLANE_ENABLED] = getValue_(plane_box);
			mmff.options[MMFF94_VDW_ENABLED] = getValue_(vdw_box);
			mmff.options[MMFF94_ES_ENABLED] = getValue_(es_box);

			try
			{
				mmff.options[MMFF94::Option::ASSIGN_TYPES] = getValue_(assign_types_checkBox);
				mmff.options[MMFF94::Option::ASSIGN_CHARGES] = getValue_(assign_charges_checkBox);
				mmff.options[MMFF94::Option::ASSIGN_TYPENAMES] = getValue_(assign_types_checkBox);
				mmff.options[MMFF94::Option::OVERWRITE_CHARGES] = getValue_(overwrite_charges_checkBox);
				mmff.options[MMFF94::Option::OVERWRITE_TYPENAMES] = getValue_(overwrite_typenames_checkBox);

//    				bool value = distance_button->isChecked();
//    				MMFF94.options[MMFF94::Option::DISTANCE_DEPENDENT_DIELECTRIC] = value ? "true" : "false";

				mmff.options[MMFF94::Option::FOLDER] = ascii(parameter_file_edit->text());

				bool error = false;
				if (ascii(max_unassigned_atoms->text()).toUnsignedInt() == 0)
				{
					error = true;
				}

				try
				{
					mmff.setMaximumNumberOfErrors(ascii(max_unassigned_atoms->text()).toUnsignedInt());
				}
				catch(...)
				{
					error = true;
				}

				if (error)
				{
					max_unassigned_atoms->setText("10");
					mmff.setMaximumNumberOfErrors(10);
					Log.error() << "Invalid value for max number of unassigned atoms, using default value of 10" << std::endl;
				}
			}
			catch(...)
			{
				Log.error() << "Invalid values for MMFF94" << std::endl;
			}
		}

		void MMFF94ConfigurationDialog::setMMFF94(MMFF94& mmff)
			throw()
		{
			mmff_ = &mmff;
		}

		void MMFF94ConfigurationDialog::resetOptions()
		{
			PreferencesEntry::restoreDefaultValues();
		}

	}//namespace VIEW
}//namespace BALL
<commit_msg>no message<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: MMFF94ConfigurationDialog.C,v 1.1.6.2 2007/05/10 00:05:18 amoll Exp $
//

#include <BALL/VIEW/DIALOGS/MMFF94ConfigurationDialog.h>
#include <BALL/VIEW/KERNEL/common.h>
#include <BALL/MOLMEC/MMFF94/MMFF94.h>
#include <BALL/MOLMEC/MMFF94/MMFF94NonBonded.h>
#include <BALL/MOLMEC/MMFF94/MMFF94StretchBend.h>
#include <BALL/MOLMEC/MMFF94/MMFF94Torsion.h>
#include <BALL/MOLMEC/MMFF94/MMFF94OutOfPlaneBend.h>
#include <BALL/MOLMEC/MMFF94/MMFF94Torsion.h>
#include <BALL/SYSTEM/path.h>

#include <QtGui/qlineedit.h>
#include <QtGui/qradiobutton.h>
#include <QtGui/qcheckbox.h>
#include <QtGui/qpushbutton.h>
#include <QtGui/QFileDialog>

namespace BALL
{
	namespace VIEW
	{

		MMFF94ConfigurationDialog::MMFF94ConfigurationDialog(QWidget* parent, const char* name)
			:	QDialog(parent),
				Ui_MMFF94ConfigurationDialogData(),
				PreferencesEntry(),
				mmff_(0)
		{
			setupUi(this);

			setINIFileSectionName("MMFF94");
			setObjectName(name);
			registerWidgets_();

			// signals and slots connections
			connect( close_button, SIGNAL( clicked() ), this, SLOT( accept() ) );
			connect( cancel_button, SIGNAL( clicked() ), this, SLOT( reject() ) );
			connect( reset_button, SIGNAL( clicked() ), this, SLOT( resetOptions() ) );
			connect( browse_button, SIGNAL( clicked() ), this, SLOT( browseParameterFiles() ) );
		}

		MMFF94ConfigurationDialog::~MMFF94ConfigurationDialog()
		{
		}

		void MMFF94ConfigurationDialog::browseParameterFiles()
		{
			// look up the full path of the parameter file
			Path p;
			String filename = p.find(ascii(parameter_file_edit->text()));

			if (filename == "")
			{
				filename = ascii(parameter_file_edit->text());
			}
			QString tmp = filename.c_str();
			QString result = QFileDialog::getExistingDirectory(0, "Select a folder with the MMFF94 parameter files", tmp);
			if (!result.isEmpty())
			{
				// store the new filename in the lineedit field
				parameter_file_edit->setText(result);
			}
		}

		void MMFF94ConfigurationDialog::reject()
		{
			hide();
			PreferencesEntry::restoreValues();
		}

		void MMFF94ConfigurationDialog::accept()
		{
			if (mmff_ != 0)
			{
				applyTo(*mmff_);
			}
			hide();
			PreferencesEntry::storeValues();
		}

		String MMFF94ConfigurationDialog::getValue_(const QCheckBox* box) const
		{
			if (box->isChecked()) return "true";
			else 									return "false";
		}

		float MMFF94ConfigurationDialog::getValue_(const QLineEdit* edit) const
			throw(Exception::InvalidFormat)
		{
			return ascii(edit->text()).toFloat();
		}

		void MMFF94ConfigurationDialog::applyTo(MMFF94& mmff)
			throw()
		{
			mmff.options[MMFF94_STRETCHES_ENABLED] = getValue_(stretch_box);
			mmff.options[MMFF94_BENDS_ENABLED] = getValue_(bends_box);
			mmff.options[MMFF94_STRETCHBENDS_ENABLED] = getValue_(stretch_bends_box);
			mmff.options[MMFF94_TORSIONS_ENABLED] = getValue_(torsions_box);
			mmff.options[MMFF94_OUTOFPLANE_ENABLED] = getValue_(plane_box);
			mmff.options[MMFF94_VDW_ENABLED] = getValue_(vdw_box);
			mmff.options[MMFF94_ES_ENABLED] = getValue_(es_box);

			try
			{
				mmff.options[MMFF94::Option::ASSIGN_TYPES] = getValue_(assign_types_checkBox);
				mmff.options[MMFF94::Option::ASSIGN_CHARGES] = getValue_(assign_charges_checkBox);
				mmff.options[MMFF94::Option::ASSIGN_TYPENAMES] = getValue_(assign_types_checkBox);
				mmff.options[MMFF94::Option::OVERWRITE_CHARGES] = getValue_(overwrite_charges_checkBox);
				mmff.options[MMFF94::Option::OVERWRITE_TYPENAMES] = getValue_(overwrite_typenames_checkBox);

 				bool value = distance_button->isChecked();
 				mmff.options[MMFF94::Option::DISTANCE_DEPENDENT_DIELECTRIC] = value ? "true" : "false";

				mmff.options[MMFF94::Option::FOLDER] = ascii(parameter_file_edit->text());

				mmff.options[MMFF94::Option::NONBONDED_CUTOFF] = getValue_(nonbonded_cutoff);

				bool error = false;
				if (ascii(max_unassigned_atoms->text()).toUnsignedInt() == 0)
				{
					error = true;
				}

				try
				{
					mmff.setMaximumNumberOfErrors(ascii(max_unassigned_atoms->text()).toUnsignedInt());
				}
				catch(...)
				{
					error = true;
				}

				if (error)
				{
					max_unassigned_atoms->setText("10");
					mmff.setMaximumNumberOfErrors(10);
					Log.error() << "Invalid value for max number of unassigned atoms, using default value of 10" << std::endl;
				}
			}
			catch(...)
			{
				Log.error() << "Invalid values for MMFF94" << std::endl;
			}
		}

		void MMFF94ConfigurationDialog::setMMFF94(MMFF94& mmff)
			throw()
		{
			mmff_ = &mmff;
		}

		void MMFF94ConfigurationDialog::resetOptions()
		{
			PreferencesEntry::restoreDefaultValues();
		}

	}//namespace VIEW
}//namespace BALL
<|endoftext|>