text
stringlengths
54
60.6k
<commit_before>#pragma once #ifdef WIN32 # define kengine_assume(x) __assume(x) #else # define kengine_assume(x) (void)0 #endif #ifdef kengine_ndebug # define kengine_assert(em, x) (void)0 # define kengine_assert_with_message(em, x, message) (void)0 # define kengine_assert_failed(em, x) (void)0 # define kengine_debug_break (void)0 #else # ifdef WIN32 # define kengine_debug_break DebugBreak() # else # define kengine_debub_break (void)0 # endif # define kengine_assert_failed(em, x) \ do {\ kengine::AssertHelper::assertFailed(em, __FILE__, __LINE__, x); \ if (kengine::AssertHelper::isDebuggerPresent()) \ kengine_debug_break; \ } while(false) # define kengine_assert_with_message(em, x, message) \ do {\ if (!!(x)) \ (void)0; \ else \ kengine_assert_failed(em, message); \ kengine_assume(!!(x)); \ } while (false) # define kengine_assert(em, x) \ kengine_assert_with_message(em, x, #x) #endif namespace kengine { class EntityManager; namespace AssertHelper { void assertFailed(EntityManager & em, const char * file, int line, const char * expr); bool isDebuggerPresent(); } }<commit_msg>rename kengine_assert_failed parameter name for clarity<commit_after>#pragma once #ifdef WIN32 # define kengine_assume(x) __assume(x) #else # define kengine_assume(x) (void)0 #endif #ifdef kengine_ndebug # define kengine_assert(em, x) (void)0 # define kengine_assert_with_message(em, x, message) (void)0 # define kengine_assert_failed(em, x) (void)0 # define kengine_debug_break (void)0 #else # ifdef WIN32 # define kengine_debug_break DebugBreak() # else # define kengine_debub_break (void)0 # endif # define kengine_assert_failed(em, message) \ do {\ kengine::AssertHelper::assertFailed(em, __FILE__, __LINE__, message); \ if (kengine::AssertHelper::isDebuggerPresent()) \ kengine_debug_break; \ } while(false) # define kengine_assert_with_message(em, x, message) \ do {\ if (!!(x)) \ (void)0; \ else \ kengine_assert_failed(em, message); \ kengine_assume(!!(x)); \ } while (false) # define kengine_assert(em, x) \ kengine_assert_with_message(em, x, #x) #endif namespace kengine { class EntityManager; namespace AssertHelper { void assertFailed(EntityManager & em, const char * file, int line, const char * expr); bool isDebuggerPresent(); } }<|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 "../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( path_prefix.size() ? path_prefix + "/" + path.C_Str() : path.C_Str() ); 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::GLint border = 0; // this value must be 0: http://www.opengl.org/sdk/docs/man/html/glTexImage2D.xhtml 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 ) constexpr glew::gl_type::GLsizei level = 8; // 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 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 .x ); 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>auto calculate mipmap-level from min(width,height)<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 "../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( path_prefix.size() ? path_prefix + "/" + path.C_Str() : path.C_Str() ); 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::GLint border = 0; // this value must be 0: http://www.opengl.org/sdk/docs/man/html/glTexImage2D.xhtml 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 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 .x ); 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>#ifndef EASYPR_CHARS_HPP #define EASYPR_CHARS_HPP namespace easypr { namespace demo { int test_chars_segment() { std::cout << "test_chars_segment" << std::endl; cv::Mat src = cv::imread("resources/image/chars_segment.jpg"); std::vector<cv::Mat> resultVec; CCharsSegment plate; int result = plate.charsSegment(src, resultVec); if (result == 0) { size_t num = resultVec.size(); for (size_t j = 0; j < num; j++) { cv::Mat resultMat = resultVec[j]; cv::imshow("chars_segment", resultMat); cv::waitKey(0); } cv::destroyWindow("chars_segment"); } return result; } int test_chars_identify() { std::cout << "test_chars_identify" << std::endl; cv::Mat plate = cv::imread("resources/image/chars_identify.jpg"); std::vector<Mat> matChars; std::string license; CCharsSegment cs; int result = cs.charsSegment(plate, matChars); if (result == 0) { for (auto block : matChars) { auto character = CharsIdentify::instance()->identify(block); license.append(character.second); } } const std::string plateLicense = utils::utf8_to_gbk("苏E771H6"); std::cout << "plateLicense: " << plateLicense << std::endl; std::cout << "plateIdentify: " << license << std::endl; if (plateLicense != license) { std::cout << "Identify Not Correct!" << std::endl; return -1; } std::cout << "Identify Correct!" << std::endl; return result; } int test_chars_recognise() { std::cout << "test_chars_recognise" << std::endl; cv::Mat src = cv::imread("resources/image/chars_recognise.jpg"); CCharsRecognise cr; std::string plateLicense = ""; int result = cr.charsRecognise(src, plateLicense); if (result == 0) std::cout << "charsRecognise: " << plateLicense << std::endl; return 0; } } } #endif // EASYPR_CHARS_HPP <commit_msg>fix(test): hard-coded plateLicense leads to test fail<commit_after>#ifndef EASYPR_CHARS_HPP #define EASYPR_CHARS_HPP namespace easypr { namespace demo { int test_chars_segment() { std::cout << "test_chars_segment" << std::endl; cv::Mat src = cv::imread("resources/image/chars_segment.jpg"); std::vector<cv::Mat> resultVec; CCharsSegment plate; int result = plate.charsSegment(src, resultVec); if (result == 0) { size_t num = resultVec.size(); for (size_t j = 0; j < num; j++) { cv::Mat resultMat = resultVec[j]; cv::imshow("chars_segment", resultMat); cv::waitKey(0); } cv::destroyWindow("chars_segment"); } return result; } int test_chars_identify() { std::cout << "test_chars_identify" << std::endl; cv::Mat plate = cv::imread("resources/image/chars_identify.jpg"); std::vector<Mat> matChars; std::string license; CCharsSegment cs; int result = cs.charsSegment(plate, matChars); if (result == 0) { for (auto block : matChars) { auto character = CharsIdentify::instance()->identify(block); license.append(character.second); } } std::string plateLicense = "苏E771H6"; #ifdef OS_WINDOWS plateLicense = utils::utf8_to_gbk(plateLicense.c_str()); #endif std::cout << "plateLicense: " << plateLicense << std::endl; std::cout << "plateIdentify: " << license << std::endl; if (plateLicense != license) { std::cout << "Identify Not Correct!" << std::endl; return -1; } std::cout << "Identify Correct!" << std::endl; return result; } int test_chars_recognise() { std::cout << "test_chars_recognise" << std::endl; cv::Mat src = cv::imread("resources/image/chars_recognise.jpg"); CCharsRecognise cr; std::string plateLicense = ""; int result = cr.charsRecognise(src, plateLicense); if (result == 0) std::cout << "charsRecognise: " << plateLicense << std::endl; return 0; } } } #endif // EASYPR_CHARS_HPP <|endoftext|>
<commit_before>/** @file A brief file description @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "ink_unused.h" /* MAGIC_EDITING_TAG */ /************************************************************************** UIOBuffer.cc **************************************************************************/ #include "P_EventSystem.h" // // General Buffer Allocator // inkcoreapi Allocator ioBufAllocator[DEFAULT_BUFFER_SIZES]; inkcoreapi ClassAllocator<MIOBuffer> ioAllocator("ioAllocator", DEFAULT_BUFFER_NUMBER); inkcoreapi ClassAllocator<IOBufferData> ioDataAllocator("ioDataAllocator", DEFAULT_BUFFER_NUMBER); inkcoreapi ClassAllocator<IOBufferBlock> ioBlockAllocator("ioBlockAllocator", DEFAULT_BUFFER_NUMBER); int default_large_iobuffer_size = DEFAULT_LARGE_BUFFER_SIZE; int default_small_iobuffer_size = DEFAULT_SMALL_BUFFER_SIZE; int max_iobuffer_size = DEFAULT_BUFFER_SIZES - 1; // // Initialization // void init_buffer_allocators() { char *name; for (int i = 0; i < DEFAULT_BUFFER_SIZES; i++) { int s = DEFAULT_BUFFER_BASE_SIZE * (1 << i); int a = DEFAULT_BUFFER_ALIGNMENT; int n = i <= default_large_iobuffer_size ? DEFAULT_BUFFER_NUMBER : DEFAULT_HUGE_BUFFER_NUMBER; if (s < a) a = s; name = NEW(new char[64]); ink_snprintf(name, 64, "ioBufAllocator[%d]", i); ioBufAllocator[i].re_init(name, s, n, a); } } int MIOBuffer::remove_append(IOBufferReader * r) { int l = 0; while (r->block) { Ptr<IOBufferBlock> b = r->block; r->block = r->block->next; b->_start += r->start_offset; if (b->start() >= b->end()) { r->start_offset = -r->start_offset; continue; } r->start_offset = 0; l += b->read_avail(); append_block(b); } r->mbuf->_writer = NULL; return l; } int MIOBuffer::write(const void *abuf, int alen) { char *buf = (char*)abuf; int len = alen; while (len) { if (!_writer) add_block(); int f = _writer->write_avail(); f = f < len ? f : len; if (f > 0) { ::memcpy(_writer->end(), buf, f); _writer->fill(f); buf += f; len -= f; } if (len) { if (!_writer->next) add_block(); else _writer = _writer->next; } } return alen; } #ifdef WRITE_AND_TRANSFER /* * Same functionality as write but for the one small difference. * The space available in the last block is taken from the original * and this space becomes available to the copy. * */ int MIOBuffer::write_and_transfer_left_over_space(IOBufferReader * r, int alen, int offset) { int rval = write(r, alen, offset); // reset the end markers of the original so that it cannot // make use of the space in the current block if (r->mbuf->_writer) r->mbuf->_writer->_buf_end = r->mbuf->_writer->_end; // reset the end marker of the clone so that it can make // use of the space in the current block if (_writer) { _writer->_buf_end = _writer->data->data() + _writer->block_size(); } return rval; } #endif int MIOBuffer::write(IOBufferReader * r, int alen, int offset) { int len = alen; IOBufferBlock *b = r->block; offset += r->start_offset; while (b && len > 0) { int max_bytes = b->read_avail(); max_bytes -= offset; if (max_bytes <= 0) { offset = -max_bytes; b = b->next; continue; } int bytes; if (len<0 || len>= max_bytes) bytes = max_bytes; else bytes = len; IOBufferBlock *bb = b->clone(); bb->_start += offset; bb->_buf_end = bb->_end = bb->_start + bytes; append_block(bb); offset = 0; len -= bytes; b = b->next; } return alen - len; } int MIOBuffer::puts(char *s, int len) { char *pc = end(); char *pb = s; while (pc < buf_end()) { if (len-- <= 0) return -1; if (!*pb || *pb == '\n') { int n = (int) (pb - s); memcpy(end(), s, n + 1); // Upto and including '\n' end()[n + 1] = 0; fill(n + 1); return n + 1; } pc++; pb++; } return 0; } int IOBufferReader::read(void *ab, int len) { char *b = (char*)ab; int max_bytes = read_avail(); int bytes = len <= max_bytes ? len : max_bytes; int n = bytes; while (n) { int l = block_read_avail(); if (n < l) l = n; ::memcpy(b, start(), l); consume(l); b += l; n -= l; } return bytes; } int IOBufferReader::memchr(char c, int len, int offset) { IOBufferBlock *b = block; offset += start_offset; int o = offset; while (b && len) { int max_bytes = b->read_avail(); max_bytes -= offset; if (max_bytes <= 0) { offset = -max_bytes; b = b->next; continue; } int bytes; if (len<0 || len>= max_bytes) bytes = max_bytes; else bytes = len; char *s = b->start() + offset; char *p = (char *) ink_memchr(s, c, bytes); if (p) return (int) (o - start_offset + p - s); o += bytes; len -= bytes; b = b->next; offset = 0; } return -1; } char * IOBufferReader::memcpy(void *ap, int len, int offset) { char *p = (char*)ap; IOBufferBlock *b = block; offset += start_offset; while (b && len) { int max_bytes = b->read_avail(); max_bytes -= offset; if (max_bytes <= 0) { offset = -max_bytes; b = b->next; continue; } int bytes; if (len<0 || len>= max_bytes) bytes = max_bytes; else bytes = len; ::memcpy(p, b->start() + offset, bytes); p += bytes; len -= bytes; b = b->next; offset = 0; } return p; } <commit_msg>restore "const" for IOBuffer::write which was deleted by mistake<commit_after>/** @file A brief file description @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "ink_unused.h" /* MAGIC_EDITING_TAG */ /************************************************************************** UIOBuffer.cc **************************************************************************/ #include "P_EventSystem.h" // // General Buffer Allocator // inkcoreapi Allocator ioBufAllocator[DEFAULT_BUFFER_SIZES]; inkcoreapi ClassAllocator<MIOBuffer> ioAllocator("ioAllocator", DEFAULT_BUFFER_NUMBER); inkcoreapi ClassAllocator<IOBufferData> ioDataAllocator("ioDataAllocator", DEFAULT_BUFFER_NUMBER); inkcoreapi ClassAllocator<IOBufferBlock> ioBlockAllocator("ioBlockAllocator", DEFAULT_BUFFER_NUMBER); int default_large_iobuffer_size = DEFAULT_LARGE_BUFFER_SIZE; int default_small_iobuffer_size = DEFAULT_SMALL_BUFFER_SIZE; int max_iobuffer_size = DEFAULT_BUFFER_SIZES - 1; // // Initialization // void init_buffer_allocators() { char *name; for (int i = 0; i < DEFAULT_BUFFER_SIZES; i++) { int s = DEFAULT_BUFFER_BASE_SIZE * (1 << i); int a = DEFAULT_BUFFER_ALIGNMENT; int n = i <= default_large_iobuffer_size ? DEFAULT_BUFFER_NUMBER : DEFAULT_HUGE_BUFFER_NUMBER; if (s < a) a = s; name = NEW(new char[64]); ink_snprintf(name, 64, "ioBufAllocator[%d]", i); ioBufAllocator[i].re_init(name, s, n, a); } } int MIOBuffer::remove_append(IOBufferReader * r) { int l = 0; while (r->block) { Ptr<IOBufferBlock> b = r->block; r->block = r->block->next; b->_start += r->start_offset; if (b->start() >= b->end()) { r->start_offset = -r->start_offset; continue; } r->start_offset = 0; l += b->read_avail(); append_block(b); } r->mbuf->_writer = NULL; return l; } int MIOBuffer::write(const void *abuf, int alen) { const char *buf = (const char*)abuf; int len = alen; while (len) { if (!_writer) add_block(); int f = _writer->write_avail(); f = f < len ? f : len; if (f > 0) { ::memcpy(_writer->end(), buf, f); _writer->fill(f); buf += f; len -= f; } if (len) { if (!_writer->next) add_block(); else _writer = _writer->next; } } return alen; } #ifdef WRITE_AND_TRANSFER /* * Same functionality as write but for the one small difference. * The space available in the last block is taken from the original * and this space becomes available to the copy. * */ int MIOBuffer::write_and_transfer_left_over_space(IOBufferReader * r, int alen, int offset) { int rval = write(r, alen, offset); // reset the end markers of the original so that it cannot // make use of the space in the current block if (r->mbuf->_writer) r->mbuf->_writer->_buf_end = r->mbuf->_writer->_end; // reset the end marker of the clone so that it can make // use of the space in the current block if (_writer) { _writer->_buf_end = _writer->data->data() + _writer->block_size(); } return rval; } #endif int MIOBuffer::write(IOBufferReader * r, int alen, int offset) { int len = alen; IOBufferBlock *b = r->block; offset += r->start_offset; while (b && len > 0) { int max_bytes = b->read_avail(); max_bytes -= offset; if (max_bytes <= 0) { offset = -max_bytes; b = b->next; continue; } int bytes; if (len<0 || len>= max_bytes) bytes = max_bytes; else bytes = len; IOBufferBlock *bb = b->clone(); bb->_start += offset; bb->_buf_end = bb->_end = bb->_start + bytes; append_block(bb); offset = 0; len -= bytes; b = b->next; } return alen - len; } int MIOBuffer::puts(char *s, int len) { char *pc = end(); char *pb = s; while (pc < buf_end()) { if (len-- <= 0) return -1; if (!*pb || *pb == '\n') { int n = (int) (pb - s); memcpy(end(), s, n + 1); // Upto and including '\n' end()[n + 1] = 0; fill(n + 1); return n + 1; } pc++; pb++; } return 0; } int IOBufferReader::read(void *ab, int len) { char *b = (char*)ab; int max_bytes = read_avail(); int bytes = len <= max_bytes ? len : max_bytes; int n = bytes; while (n) { int l = block_read_avail(); if (n < l) l = n; ::memcpy(b, start(), l); consume(l); b += l; n -= l; } return bytes; } int IOBufferReader::memchr(char c, int len, int offset) { IOBufferBlock *b = block; offset += start_offset; int o = offset; while (b && len) { int max_bytes = b->read_avail(); max_bytes -= offset; if (max_bytes <= 0) { offset = -max_bytes; b = b->next; continue; } int bytes; if (len<0 || len>= max_bytes) bytes = max_bytes; else bytes = len; char *s = b->start() + offset; char *p = (char *) ink_memchr(s, c, bytes); if (p) return (int) (o - start_offset + p - s); o += bytes; len -= bytes; b = b->next; offset = 0; } return -1; } char * IOBufferReader::memcpy(void *ap, int len, int offset) { char *p = (char*)ap; IOBufferBlock *b = block; offset += start_offset; while (b && len) { int max_bytes = b->read_avail(); max_bytes -= offset; if (max_bytes <= 0) { offset = -max_bytes; b = b->next; continue; } int bytes; if (len<0 || len>= max_bytes) bytes = max_bytes; else bytes = len; ::memcpy(p, b->start() + offset, bytes); p += bytes; len -= bytes; b = b->next; offset = 0; } return p; } <|endoftext|>
<commit_before>#include "fmatvec/atom.h" #include <boost/preprocessor/iteration/local.hpp> using namespace std; using namespace boost; namespace fmatvec { // a shared null stream object shared_ptr<ostream> Atom::_nullStream = make_shared<ostream>(static_cast<streambuf*>(NULL)); // initialize the static streams with cout/cerr and corresponding active flags array<shared_ptr<bool> , Atom::SIZE> Atom::_msgActStatic = {{ // initial active flag of the message stream make_shared<bool>(true), // Info make_shared<bool>(true), // Warn make_shared<bool>(false) // Debug // NEW TYPES HERE: initial active flag }}; array<shared_ptr<ostream>, Atom::SIZE> Atom::_msgSavedStatic = {{ // stream to use for the message stream make_shared<ostream>(cout.rdbuf()), // Info make_shared<ostream>(cerr.rdbuf()), // Warn make_shared<ostream>(cout.rdbuf()) // Debug // NEW TYPES HERE: stream }}; #define BOOST_PP_LOCAL_LIMITS (0, FMATVEC_ATOM_MSGTYPE_SIZE-1) #define BOOST_PP_LOCAL_MACRO(type) *_msgActStatic[type] ? _msgSavedStatic[type] : _nullStream, array<shared_ptr<ostream>, Atom::SIZE> Atom::_msgStatic = {{ #include BOOST_PP_LOCAL_ITERATE() }}; Atom::Atom() : _msgAct(_msgActStatic), _msgSaved(_msgSavedStatic), _msg(_msgStatic) { } Atom::Atom(const Atom &) : _msgAct(_msgActStatic), _msgSaved(_msgSavedStatic), _msg(_msgStatic) { } Atom::~Atom() { } Atom& Atom::operator=(const Atom &) { return *this; } void Atom::setCurrentMessageStream(MsgType type, const boost::shared_ptr<std::ostream> &s) { _msgActStatic[type]=boost::make_shared<bool>(true); _msgSavedStatic[type]=s; _msgStatic[type] = _msgSavedStatic[type]; } void Atom::setCurrentMessageStreamActive(MsgType type, bool activeFlag) { *_msgActStatic[type] = activeFlag; _msgStatic[type] = *_msgActStatic[type] ? _msgSavedStatic[type] : _nullStream; } void Atom::setMessageStreamActive(MsgType type, bool activeFlag) { *_msgAct[type] = activeFlag; _msg[type] = *_msgAct[type] ? _msgSaved[type] : _nullStream; } void Atom::adoptMessageStreams(const Atom *src) { if(src) { _msgAct =src->_msgAct; _msgSaved=src->_msgSaved; _msg =src->_msg; } else { _msgAct =_msgActStatic; _msgSaved=_msgSavedStatic; _msg =_msgStatic; } } } <commit_msg>Use envvar to set the default activity of message streams.<commit_after>#include "fmatvec/atom.h" #include <boost/preprocessor/iteration/local.hpp> using namespace std; using namespace boost; namespace { bool msgTypeActive(bool defaultValue, const string &envVarPostfix) { char *env=getenv((string("FMATVEC_MSG_")+envVarPostfix).c_str()); if(env) { if(string(env)=="0") return false; if(string(env)=="1") return true; } return defaultValue; } } namespace fmatvec { // a shared null stream object shared_ptr<ostream> Atom::_nullStream = make_shared<ostream>(static_cast<streambuf*>(NULL)); // initialize the static streams with cout/cerr and corresponding active flags array<shared_ptr<bool> , Atom::SIZE> Atom::_msgActStatic = {{ // initial active flag of the message stream and/or envvar postfix being used as initial value make_shared<bool>(msgTypeActive(true , "Info" )), // Info make_shared<bool>(msgTypeActive(true , "Warn" )), // Warn make_shared<bool>(msgTypeActive(false, "Debug")) // Debug // NEW TYPES HERE: initial active flag }}; array<shared_ptr<ostream>, Atom::SIZE> Atom::_msgSavedStatic = {{ // stream to use for the message stream make_shared<ostream>(cout.rdbuf()), // Info make_shared<ostream>(cerr.rdbuf()), // Warn make_shared<ostream>(cout.rdbuf()) // Debug // NEW TYPES HERE: stream }}; #define BOOST_PP_LOCAL_LIMITS (0, FMATVEC_ATOM_MSGTYPE_SIZE-1) #define BOOST_PP_LOCAL_MACRO(type) *_msgActStatic[type] ? _msgSavedStatic[type] : _nullStream, array<shared_ptr<ostream>, Atom::SIZE> Atom::_msgStatic = {{ #include BOOST_PP_LOCAL_ITERATE() }}; Atom::Atom() : _msgAct(_msgActStatic), _msgSaved(_msgSavedStatic), _msg(_msgStatic) { } Atom::Atom(const Atom &) : _msgAct(_msgActStatic), _msgSaved(_msgSavedStatic), _msg(_msgStatic) { } Atom::~Atom() { } Atom& Atom::operator=(const Atom &) { return *this; } void Atom::setCurrentMessageStream(MsgType type, const boost::shared_ptr<std::ostream> &s) { _msgActStatic[type]=boost::make_shared<bool>(true); _msgSavedStatic[type]=s; _msgStatic[type] = _msgSavedStatic[type]; } void Atom::setCurrentMessageStreamActive(MsgType type, bool activeFlag) { *_msgActStatic[type] = activeFlag; _msgStatic[type] = *_msgActStatic[type] ? _msgSavedStatic[type] : _nullStream; } void Atom::setMessageStreamActive(MsgType type, bool activeFlag) { *_msgAct[type] = activeFlag; _msg[type] = *_msgAct[type] ? _msgSaved[type] : _nullStream; } void Atom::adoptMessageStreams(const Atom *src) { if(src) { _msgAct =src->_msgAct; _msgSaved=src->_msgSaved; _msg =src->_msg; } else { _msgAct =_msgActStatic; _msgSaved=_msgSavedStatic; _msg =_msgStatic; } } } <|endoftext|>
<commit_before> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <netinet/in.h> #include <resolv.h> #include <string> #include <iostream> #include <event2/event.h> #include <event2/http.h> #include <event2/http_struct.h> #include <event2/buffer.h> #include <event2/util.h> #include <event2/keyvalq_struct.h> #include "debug.h" #include "localrepo.h" #include "util.h" #include "zeroconf.h" using namespace std; static struct evhttp *httpd; /* set if a test needs to call loopexit on a base */ static struct event_base *base; LocalRepo repository; int Httpd_authenticate(struct evhttp_request *req, struct evbuffer *buf) { int n; char output[64]; const char *as = evhttp_find_header(req->input_headers, "Authorization"); if (as == NULL) { goto authFailed; } // Select auth type n = b64_pton(strchr(as,' ') + 1, (u_char *) output, 64); output[n] = '\0'; if (strcmp(output, "ali:test") != 0) { goto authFailed; } return 0; authFailed: evhttp_add_header(req->output_headers, "WWW-Authenticate", "Basic realm=\"Secure Area\""); evhttp_send_reply(req, 401, "Authorization Required", buf); return -1; } void Httpd_stop(struct evhttp_request *req, void *arg) { struct evbuffer *buf; buf = evbuffer_new(); if (buf == NULL) { printf("Failed"); } if (Httpd_authenticate(req, buf) < 0) { return; } evbuffer_add_printf(buf, "Stopping\n"); evhttp_send_reply(req, HTTP_OK, "OK", buf); event_base_loopexit(base, NULL); } void Httpd_getId(struct evhttp_request *req, void *arg) { string repoId = repository.getUUID(); struct evbuffer *buf; LOG("httpd: getid"); buf = evbuffer_new(); if (buf == NULL) { LOG("httpd_gethead: evbuffer_new failed!"); return; } evbuffer_add_printf(buf, "%s", repoId.c_str()); evhttp_add_header(req->output_headers, "Content-Type", "text/plain"); evhttp_send_reply(req, HTTP_OK, "OK", buf); } void Httpd_getVersion(struct evhttp_request *req, void *arg) { string ver = repository.getVersion(); struct evbuffer *buf; LOG("httpd: getversion"); buf = evbuffer_new(); if (buf == NULL) { LOG("httpd_getversion: evbuffer_new failed!"); return; } evbuffer_add_printf(buf, "%s", ver.c_str()); evhttp_add_header(req->output_headers, "Content-Type", "text/plain"); evhttp_send_reply(req, HTTP_OK, "OK", buf); } void Httpd_head(struct evhttp_request *req, void *arg) { string headId = repository.getHead(); struct evbuffer *buf; LOG("httpd: gethead"); buf = evbuffer_new(); if (buf == NULL) { LOG("httpd_gethead: evbuffer_new failed!"); return; } evbuffer_add_printf(buf, "%s", headId.c_str()); evhttp_add_header(req->output_headers, "Content-Type", "text/plain"); evhttp_send_reply(req, HTTP_OK, "OK", buf); } void Httpd_getIndex(struct evhttp_request *req, void *arg) { set<ObjectInfo> objs = repository.listObjects(); set<ObjectInfo>::iterator it; struct evbuffer *buf; LOG("httpd: getindex"); buf = evbuffer_new(); if (buf == NULL) { LOG("httpd_getindex: evbuffer_new failed!"); return; } for (it = objs.begin(); it != objs.end(); it++) { int status; string objInfo = (*it).getInfo(); LOG("hash = %s\n", (*it).hash.c_str()); status = evbuffer_add(buf, (*it).hash.c_str(), (*it).hash.size()); if (status != 0) { assert(status == -1); LOG("evbuffer_add failed while adding hash!"); evbuffer_free(buf); buf = evbuffer_new(); evhttp_send_reply(req, HTTP_INTERNAL, "INTERNAL ERROR", buf); return; } status = evbuffer_add(buf, objInfo.data(), objInfo.size()); if (status != 0) { assert(status == -1); LOG("evbuffer_add failed while adding objInfo!"); evbuffer_free(buf); buf = evbuffer_new(); evhttp_send_reply(req, HTTP_INTERNAL, "INTERNAL ERROR", buf); return; } } evhttp_add_header(req->output_headers, "Content-Type", "text/plain"); evhttp_send_reply(req, HTTP_OK, "OK", buf); } void Httpd_stringDeleteCB(const void *data, size_t len, void *extra) { string *p = (string *)extra; delete p; } void Httpd_getObj(struct evhttp_request *req, void *arg) { string objId; auto_ptr<bytestream> bs; string *payload = new string(); Object *obj; string objInfo; struct evbuffer *buf; objId = evhttp_request_get_uri(req); objId = objId.substr(6); buf = evbuffer_new(); if (buf == NULL) { LOG("httpd_getobj: evbuffer_new failed!"); } if (objId.size() != 64) { evhttp_send_reply(req, HTTP_BADREQUEST, "Bad Request", buf); return; } LOG("httpd: getobj %s", objId.c_str()); obj = repository.getObject(objId.c_str()); if (obj == NULL) { evhttp_send_reply(req, HTTP_NOTFOUND, "Object Not Found", buf); return; } bs = obj->getStoredPayloadStream(); *payload = bs->readAll(); objInfo = obj->getInfo().getInfo(); // Transmit evbuffer_add(buf, objInfo.data(), objInfo.size()); evbuffer_add_reference(buf, payload->data(), payload->size(), Httpd_stringDeleteCB, payload); evhttp_add_header(req->output_headers, "Content-Type", "text/plain"); evhttp_send_reply(req, HTTP_OK, "OK", buf); delete obj; return; } void Httpd_pushObj(struct evhttp_request *req, void *arg) { const char *cl = evhttp_find_header(req->input_headers, "Content-Length"); uint32_t length; struct evbuffer *body = evhttp_request_get_input_buffer(req); struct evbuffer *outbuf; unsigned char objId[20]; void *buf; outbuf = evbuffer_new(); if (outbuf == NULL) { printf("Failed"); } // Make sure it makes sense if (cl == NULL) { evhttp_send_error(req, HTTP_BADREQUEST, "Bad Request"); return; } /* Dump Headers struct evkeyvalq *kv = evhttp_request_get_input_headers(req); struct evkeyval *iter; TAILQ_FOREACH(iter, kv, next) { printf("%s: %s\n", iter->key, iter->value); } */ length = atoi(cl); printf("Push: %d bytes, got %zd bytes\n", length, evbuffer_get_length(body)); buf = malloc(length); evbuffer_remove(body, buf, length); // XXX: Add object free(buf); evbuffer_add_printf(outbuf, "%02x%02x%02x%02x" "%02x%02x%02x%02x%02x%02x%02x%02x" "%02x%02x%02x%02x%02x%02x%02x%02x\n", objId[0], objId[1], objId[2], objId[3], objId[4], objId[5], objId[6], objId[7], objId[8], objId[9], objId[10], objId[11], objId[12], objId[13], objId[14], objId[15], objId[16], objId[17], objId[18], objId[19]); evhttp_send_reply(req, HTTP_OK, "OK", outbuf); } void Httpd_logCB(int severity, const char *msg) { const char *sev[] = { "Debug", "Msg", "Warning", "Error", }; LOG("%s: %s", sev[severity]); } void Httpd_main(uint16_t port) { base = event_base_new(); event_set_log_callback(Httpd_logCB); httpd = evhttp_new(base); evhttp_bind_socket(httpd, "0.0.0.0", port); evhttp_set_cb(httpd, "/id", Httpd_getId, NULL); evhttp_set_cb(httpd, "/version", Httpd_getVersion, NULL); evhttp_set_cb(httpd, "/HEAD", Httpd_head, NULL); evhttp_set_cb(httpd, "/index", Httpd_getIndex, NULL); //evhttp_set_cb(httpd, "/objs", Httpd_pushobj, NULL); evhttp_set_cb(httpd, "/stop", Httpd_stop, NULL); evhttp_set_gencb(httpd, Httpd_getObj, NULL); // getObj: /objs/* // mDNS struct event *mdns_evt = MDNS_Start(port, base); if (mdns_evt) event_add(mdns_evt, NULL); event_base_dispatch(base); if (mdns_evt) event_free(mdns_evt); evhttp_free(httpd); } void usage() { cout << "usage: ori_httpd [options] <repository path>" << endl << endl; cout << "Options:" << endl; cout << "-p port Set the HTTP port number (default 8080)" << endl; cout << "-h Show this message" << endl; } int main(int argc, char *argv[]) { bool success; int bflag, ch; unsigned long port = 8080; bflag = 0; while ((ch = getopt(argc, argv, "p:h")) != -1) { switch (ch) { case 'p': { char *p; port = strtoul(optarg, &p, 10); if (*p != '\0' || port > 65535) { cout << "Invalid port number '" << optarg << "'" << endl; usage(); return 1; } break; } case 'h': usage(); return 0; case '?': default: usage(); return 1; } } argc -= optind; argv += optind; if (argc == 1) { success = repository.open(argv[0]); } else { success = repository.open(); } if (!success) { cout << "Could not open the local repository!" << endl; return 1; } ori_open_log(&repository); Httpd_main(port); return 0; } <commit_msg>Adding extra asserts.<commit_after> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <netinet/in.h> #include <resolv.h> #include <string> #include <iostream> #include <event2/event.h> #include <event2/http.h> #include <event2/http_struct.h> #include <event2/buffer.h> #include <event2/util.h> #include <event2/keyvalq_struct.h> #include "debug.h" #include "localrepo.h" #include "util.h" #include "zeroconf.h" using namespace std; static struct evhttp *httpd; /* set if a test needs to call loopexit on a base */ static struct event_base *base; LocalRepo repository; int Httpd_authenticate(struct evhttp_request *req, struct evbuffer *buf) { int n; char output[64]; const char *as = evhttp_find_header(req->input_headers, "Authorization"); if (as == NULL) { goto authFailed; } // Select auth type n = b64_pton(strchr(as,' ') + 1, (u_char *) output, 64); output[n] = '\0'; if (strcmp(output, "ali:test") != 0) { goto authFailed; } return 0; authFailed: evhttp_add_header(req->output_headers, "WWW-Authenticate", "Basic realm=\"Secure Area\""); evhttp_send_reply(req, 401, "Authorization Required", buf); return -1; } void Httpd_stop(struct evhttp_request *req, void *arg) { struct evbuffer *buf; buf = evbuffer_new(); if (buf == NULL) { printf("Failed"); } if (Httpd_authenticate(req, buf) < 0) { return; } evbuffer_add_printf(buf, "Stopping\n"); evhttp_send_reply(req, HTTP_OK, "OK", buf); event_base_loopexit(base, NULL); } void Httpd_getId(struct evhttp_request *req, void *arg) { string repoId = repository.getUUID(); struct evbuffer *buf; LOG("httpd: getid"); buf = evbuffer_new(); if (buf == NULL) { LOG("httpd_gethead: evbuffer_new failed!"); return; } evbuffer_add_printf(buf, "%s", repoId.c_str()); evhttp_add_header(req->output_headers, "Content-Type", "text/plain"); evhttp_send_reply(req, HTTP_OK, "OK", buf); } void Httpd_getVersion(struct evhttp_request *req, void *arg) { string ver = repository.getVersion(); struct evbuffer *buf; LOG("httpd: getversion"); buf = evbuffer_new(); if (buf == NULL) { LOG("httpd_getversion: evbuffer_new failed!"); return; } evbuffer_add_printf(buf, "%s", ver.c_str()); evhttp_add_header(req->output_headers, "Content-Type", "text/plain"); evhttp_send_reply(req, HTTP_OK, "OK", buf); } void Httpd_head(struct evhttp_request *req, void *arg) { string headId = repository.getHead(); struct evbuffer *buf; LOG("httpd: gethead"); buf = evbuffer_new(); if (buf == NULL) { LOG("httpd_gethead: evbuffer_new failed!"); return; } evbuffer_add_printf(buf, "%s", headId.c_str()); evhttp_add_header(req->output_headers, "Content-Type", "text/plain"); evhttp_send_reply(req, HTTP_OK, "OK", buf); } void Httpd_getIndex(struct evhttp_request *req, void *arg) { set<ObjectInfo> objs = repository.listObjects(); set<ObjectInfo>::iterator it; struct evbuffer *buf; LOG("httpd: getindex"); buf = evbuffer_new(); if (buf == NULL) { LOG("httpd_getindex: evbuffer_new failed!"); return; } for (it = objs.begin(); it != objs.end(); it++) { int status; string objInfo = (*it).getInfo(); LOG("hash = %s\n", (*it).hash.c_str()); status = evbuffer_add(buf, (*it).hash.c_str(), (*it).hash.size()); if (status != 0) { assert(status == -1); LOG("evbuffer_add failed while adding hash!"); evbuffer_free(buf); buf = evbuffer_new(); evhttp_send_reply(req, HTTP_INTERNAL, "INTERNAL ERROR", buf); return; } status = evbuffer_add(buf, objInfo.data(), objInfo.size()); if (status != 0) { assert(status == -1); LOG("evbuffer_add failed while adding objInfo!"); evbuffer_free(buf); buf = evbuffer_new(); evhttp_send_reply(req, HTTP_INTERNAL, "INTERNAL ERROR", buf); return; } } evhttp_add_header(req->output_headers, "Content-Type", "text/plain"); evhttp_send_reply(req, HTTP_OK, "OK", buf); } void Httpd_stringDeleteCB(const void *data, size_t len, void *extra) { string *p = (string *)extra; delete p; } void Httpd_getObj(struct evhttp_request *req, void *arg) { string objId; auto_ptr<bytestream> bs; string *payload = new string(); Object *obj; string objInfo; struct evbuffer *buf; objId = evhttp_request_get_uri(req); objId = objId.substr(6); buf = evbuffer_new(); if (buf == NULL) { LOG("httpd_getobj: evbuffer_new failed!"); } if (objId.size() != 64) { evhttp_send_reply(req, HTTP_BADREQUEST, "Bad Request", buf); return; } LOG("httpd: getobj %s", objId.c_str()); obj = repository.getObject(objId.c_str()); if (obj == NULL) { evhttp_send_reply(req, HTTP_NOTFOUND, "Object Not Found", buf); return; } bs = obj->getStoredPayloadStream(); *payload = bs->readAll(); objInfo = obj->getInfo().getInfo(); assert(objInfo.size() == 16); // Transmit evbuffer_add(buf, objInfo.data(), objInfo.size()); evbuffer_add_reference(buf, payload->data(), payload->size(), Httpd_stringDeleteCB, payload); evhttp_add_header(req->output_headers, "Content-Type", "text/plain"); evhttp_send_reply(req, HTTP_OK, "OK", buf); delete obj; return; } void Httpd_pushObj(struct evhttp_request *req, void *arg) { const char *cl = evhttp_find_header(req->input_headers, "Content-Length"); uint32_t length; struct evbuffer *body = evhttp_request_get_input_buffer(req); struct evbuffer *outbuf; unsigned char objId[20]; void *buf; outbuf = evbuffer_new(); if (outbuf == NULL) { printf("Failed"); } // Make sure it makes sense if (cl == NULL) { evhttp_send_error(req, HTTP_BADREQUEST, "Bad Request"); return; } /* Dump Headers struct evkeyvalq *kv = evhttp_request_get_input_headers(req); struct evkeyval *iter; TAILQ_FOREACH(iter, kv, next) { printf("%s: %s\n", iter->key, iter->value); } */ length = atoi(cl); printf("Push: %d bytes, got %zd bytes\n", length, evbuffer_get_length(body)); buf = malloc(length); evbuffer_remove(body, buf, length); // XXX: Add object free(buf); evbuffer_add_printf(outbuf, "%02x%02x%02x%02x" "%02x%02x%02x%02x%02x%02x%02x%02x" "%02x%02x%02x%02x%02x%02x%02x%02x\n", objId[0], objId[1], objId[2], objId[3], objId[4], objId[5], objId[6], objId[7], objId[8], objId[9], objId[10], objId[11], objId[12], objId[13], objId[14], objId[15], objId[16], objId[17], objId[18], objId[19]); evhttp_send_reply(req, HTTP_OK, "OK", outbuf); } void Httpd_logCB(int severity, const char *msg) { const char *sev[] = { "Debug", "Msg", "Warning", "Error", }; LOG("%s: %s", sev[severity]); } void Httpd_main(uint16_t port) { base = event_base_new(); event_set_log_callback(Httpd_logCB); httpd = evhttp_new(base); evhttp_bind_socket(httpd, "0.0.0.0", port); evhttp_set_cb(httpd, "/id", Httpd_getId, NULL); evhttp_set_cb(httpd, "/version", Httpd_getVersion, NULL); evhttp_set_cb(httpd, "/HEAD", Httpd_head, NULL); evhttp_set_cb(httpd, "/index", Httpd_getIndex, NULL); //evhttp_set_cb(httpd, "/objs", Httpd_pushobj, NULL); evhttp_set_cb(httpd, "/stop", Httpd_stop, NULL); evhttp_set_gencb(httpd, Httpd_getObj, NULL); // getObj: /objs/* // mDNS struct event *mdns_evt = MDNS_Start(port, base); if (mdns_evt) event_add(mdns_evt, NULL); event_base_dispatch(base); if (mdns_evt) event_free(mdns_evt); evhttp_free(httpd); } void usage() { cout << "usage: ori_httpd [options] <repository path>" << endl << endl; cout << "Options:" << endl; cout << "-p port Set the HTTP port number (default 8080)" << endl; cout << "-h Show this message" << endl; } int main(int argc, char *argv[]) { bool success; int bflag, ch; unsigned long port = 8080; bflag = 0; while ((ch = getopt(argc, argv, "p:h")) != -1) { switch (ch) { case 'p': { char *p; port = strtoul(optarg, &p, 10); if (*p != '\0' || port > 65535) { cout << "Invalid port number '" << optarg << "'" << endl; usage(); return 1; } break; } case 'h': usage(); return 0; case '?': default: usage(); return 1; } } argc -= optind; argv += optind; if (argc == 1) { success = repository.open(argv[0]); } else { success = repository.open(); } if (!success) { cout << "Could not open the local repository!" << endl; return 1; } ori_open_log(&repository); Httpd_main(port); return 0; } <|endoftext|>
<commit_before>// LAF OS Library // Copyright (C) 2012-2018 David Capello // // This file is released under the terms of the MIT license. // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "base/memory.h" #include "base/string.h" #if _WIN32 #include <windows.h> #elif __APPLE__ #include "os/osx/app.h" #include <CoreServices/CoreServices.h> #else #include "os/x11/x11.h" #endif extern int app_main(int argc, char* argv[]); #if _WIN32 int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR lpCmdLine, int nCmdShow) { int argc = __argc; char** argv; if (__wargv && argc > 0) { argv = new char*[argc]; for (int i=0; i<argc; ++i) argv[i] = base_strdup(base::to_utf8(std::wstring(__wargv[i])).c_str()); } else { argv = new char*[1]; argv[0] = base_strdup(""); argc = 1; } return app_main(argc, argv); } int wmain(int argc, wchar_t* wargv[], wchar_t* envp[]) { char** argv; if (wargv && argc > 0) { argv = new char*[argc]; for (int i=0; i<argc; ++i) argv[i] = base_strdup(base::to_utf8(std::wstring(wargv[i])).c_str()); } else { argv = new char*[1]; argv[0] = base_strdup(""); argc = 1; } return app_main(argc, argv); } #endif int main(int argc, char* argv[]) { #if __APPLE__ os::OSXApp app; if (!app.init()) return 1; #elif !defined(_WIN32) os::X11 x11; #endif return app_main(argc, argv); } <commit_msg>Including CoreServices.h is not needed in common/main.cpp<commit_after>// LAF OS Library // Copyright (C) 2012-2018 David Capello // // This file is released under the terms of the MIT license. // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "base/memory.h" #include "base/string.h" #if _WIN32 #include <windows.h> #elif __APPLE__ #include "os/osx/app.h" #else #include "os/x11/x11.h" #endif extern int app_main(int argc, char* argv[]); #if _WIN32 int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR lpCmdLine, int nCmdShow) { int argc = __argc; char** argv; if (__wargv && argc > 0) { argv = new char*[argc]; for (int i=0; i<argc; ++i) argv[i] = base_strdup(base::to_utf8(std::wstring(__wargv[i])).c_str()); } else { argv = new char*[1]; argv[0] = base_strdup(""); argc = 1; } return app_main(argc, argv); } int wmain(int argc, wchar_t* wargv[], wchar_t* envp[]) { char** argv; if (wargv && argc > 0) { argv = new char*[argc]; for (int i=0; i<argc; ++i) argv[i] = base_strdup(base::to_utf8(std::wstring(wargv[i])).c_str()); } else { argv = new char*[1]; argv[0] = base_strdup(""); argc = 1; } return app_main(argc, argv); } #endif int main(int argc, char* argv[]) { #if __APPLE__ os::OSXApp app; if (!app.init()) return 1; #elif !defined(_WIN32) os::X11 x11; #endif return app_main(argc, argv); } <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 6/14/2020, 3:53:32 AM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- Solve ----- class Solve { ll W, H, K; public: Solve(ll W, ll H, ll K) : W{W}, H{H}, K{K} {} ll answer() { ll ans{0}; for (auto y{1LL}; y < H; ++y) { ans += calc(0, y); } for (auto s{1LL}; s < W; ++s) { for (auto y{1LL}; s * y < 2 * K && y < H; ++y) { ans += calc(s, y); } } return ans; } private: ll calc(ll s, ll y) { ll R{2 * K - (H - y) * s + gcd(H, s) - 1}; if (R < 0) { return 0; } ll ans{min(W - s - 1, R / H)}; ll x{R / H + 1}; if (x + s < W && H * x - gcd(H - y, x) + gcd(y, x + s) <= R) { ++ans; } return ans; } }; // ----- main() ----- int main() { ll W, H, K; cin >> W >> H >> K; Solve solve(W, H, K), solve2(H, W, K); ll ans{2 * (solve.answer() + solve2.answer())}; cout << ans << endl; } <commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 6/14/2020, 3:53:32 AM * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <climits> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <limits> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; using ld = long double; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1'000'000'007LL}; // constexpr ll MOD{998'244'353LL}; // be careful constexpr ll MAX_SIZE{3'000'010LL}; // constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(Mint const &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(Mint const &a) { return *this += -a; } Mint &operator++() { return *this += 1; } Mint operator++(int) { Mint tmp{*this}; ++*this; return tmp; } Mint &operator--() { return *this -= 1; } Mint operator--(int) { Mint tmp{*this}; --*this; return tmp; } Mint &operator*=(Mint const &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(Mint const &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(Mint const &a) const { return Mint(*this) += a; } Mint operator-(Mint const &a) const { return Mint(*this) -= a; } Mint operator*(Mint const &a) const { return Mint(*this) *= a; } Mint operator/(Mint const &a) const { return Mint(*this) /= a; } bool operator<(Mint const &a) const { return x < a.x; } bool operator<=(Mint const &a) const { return x <= a.x; } bool operator>(Mint const &a) const { return x > a.x; } bool operator>=(Mint const &a) const { return x >= a.x; } bool operator==(Mint const &a) const { return x == a.x; } bool operator!=(Mint const &a) const { return !(*this == a); } Mint power(ll N) const { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i{2LL}; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i{1LL}; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } // ----- for C++17 ----- template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- Infty ----- template <typename T> constexpr T Infty() { return numeric_limits<T>::max(); } template <typename T> constexpr T mInfty() { return numeric_limits<T>::min(); } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1'000'000'000'000'010LL}; // or // constexpr int infty{1'000'000'010}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- Solve ----- class Solve { ll W, H, K; public: Solve(ll W, ll H, ll K) : W{W}, H{H}, K{K} {} ll answer() { ll ans{0}; for (auto y{1LL}; y < H; ++y) { ans += calc(0, y); } for (auto s{1LL}; s < W; ++s) { for (auto y{1LL}; (H - s) * y <= 2 * K + H - 2 && y < H; ++y) { ans += calc(s, y); } } return ans; } private: ll calc(ll s, ll y) { ll R{2 * K - (H - y) * s + gcd(H, s) - 1}; if (R < 0) { return 0; } ll ans{min(W - s - 1, R / H)}; ll x{R / H + 1}; if (x + s < W && H * x - gcd(H - y, x) + gcd(y, x + s) <= R) { ++ans; } return ans; } }; // ----- main() ----- int main() { ll W, H, K; cin >> W >> H >> K; Solve solve(W, H, K), solve2(H, W, K); ll ans{2 * (solve.answer() + solve2.answer())}; cout << ans << endl; } <|endoftext|>
<commit_before>#include <iostream> //cout #include <cstdlib> //rand, sran #include <string> #include "complex_matrices.h" #include <gmc.h> //LaGenMatComplex #include <laslv.h> //LUFactorizeIP, LaLUInverseIP, etc. #include <blas3pp.h> using namespace std; /* Total [13/20] */ /* Printing [6/9] */ void print_scalar(const COMPLEX scalar){ cout << scalar << endl; } //working void print_scalar(const COMPLEX scalar, const string name){ cout << name << ":" << scalar << endl; } //working void print_array(const COMPLEX array[], int len){ for(int i = 0; i < len; i++){ cout << array[i] << endl; } } //working void print_array(const COMPLEX array[], int len, const string name){ cout << name << ":" << endl; for(int i = 0; i < len; i++){ cout << array[i] << endl; } } //working void print_matrix(const LaGenMatComplex& matrix){ cout << matrix << endl; } //working void print_matrix(const LaGenMatComplex& matrix, const string name){ cout << name << ":" << endl << matrix << endl; } //working /* Number generation [2/2] */ void generate_scalar(COMPLEX& A, const int x){ A.r = rand() % x; //1 to x A.i = rand() % x; } //working void generate_scalar(int A, const int x){ A = rand() % x; //1 to x } //working void generate_array(COMPLEX array[], const int len, const int x){ srand(time(NULL)); //seed for(int i = 0; i < len; i++){ array[i].r = rand() % x; //1 to x array[i].i = rand() % x; } } //working /* Matrix conversion [3/3] */ void vec_to_array(const LaVectorComplex& vector, const int len, COMPLEX array[ ]){ for(int i = 0; i < len; i++){ array[i] = vector(i); } } //working void array_to_diag(COMPLEX array[], const int len, LaGenMatComplex& diag){ diag = 0; for(int i = 0; i < len; i++){ diag(i, i) = array[i]; } } //working void vec_to_diag(const LaVectorComplex& vector, const int len, LaGenMatComplex& diag){ COMPLEX array[len]; vec_to_array(vector, len, array); array_to_diag(array, len, diag); } //working /* Scalar manipulation [5/8] */ int factorial(int x){ if(x <= 1){ return 1; }else{ return x * factorial(x - 1); } } //working void scalar_addition(const COMPLEX& A, const COMPLEX& B , COMPLEX& result){ result.r = A.r + B.r; result.i = A.i + B.i; } //working void scalar_sum(){ //... } void scalar_multiplication(const COMPLEX& A, const int B, COMPLEX& result){ result.r = A.r * B; result.i = A.i * B; } //to test void scalar_multiplication(const COMPLEX& A, const COMPLEX& B, COMPLEX& result){ la::complex<double> laA = la::complex<double>(A); //convert to la::complex<double> la::complex<double> laB = la::complex<double>(B); la::complex<double> laResult = la::complex<double>(result); laResult = laA * laB; result = laResult.toCOMPLEX(); } //to test void scalar_division(const COMPLEX& A, const int B, COMPLEX& result){ result.r = A.r / B; result.i = A.i / B; } //to test void scalar_division(const COMPLEX& A, const COMPLEX& B, COMPLEX& result){ la::complex<double> laA = la::complex<double>(A); //convert to la::complex<double> la::complex<double> laB = la::complex<double>(B); la::complex<double> laResult = la::complex<double>(result); laResult = laA / laB; result = laResult.toCOMPLEX(); } //to test void scalar_powers(const COMPLEX& number, const int power, COMPLEX& result){ la::complex<double> laResult = la::complex<double>(number); la::complex<double> laNumber = la::complex<double>(number); for(int i = 1; i < power; i++){ laResult *= laNumber; } result = laResult.toCOMPLEX(); } //to test void scalar_exponential_1(const COMPLEX& number, const int iterations, COMPLEX& result){ COMPLEX division, total_division, A, B; result.r = 1; result.i = 1; for(int step = 1; step <= iterations; step++){ //sum (from 1 to n) division.r = 0; division.i = 0; total_division.r = 1; total_division.i = 0; for(int i = 1; i <= step; i++){ // ( num^n / n!) cout << "division = " << division << endl; cout << "total_division = " << total_division << endl; A = total_division; scalar_division(number, i, division); scalar_multiplication(A, division, total_division); } B = result; scalar_addition(B, total_division, result); cout << "sum = " << result << endl; } } void scalar_exponential(const COMPLEX& number, const int iter, COMPLEX& result){ //COMPLEX power; //COMPLEX division; //result.r = 0; //result.i = 0; //for(int i = 0; i < iter; i++){ // scalar_powers(number, i, power); // scalar_division(power, factorial(i), division); // scalar_addition(result, division, result); //} } //empty //COMPLEX rec_scalar_exp_step(const COMPLEX& number, const int step){ // COMPLEX result, division, multiplication; // if(step <= 1){ // result.r = 1; // return result; // }else{ // scalar_division(number,step,division); // scalar_multiplication(division, rec_scalar_exp_step(step-1), multiplication); // return multiplication; // } //} void recursive_scalar_exponential(const COMPLEX& number, const int iter, COMPLEX& result){ //COMPLEX power; //COMPLEX division; //result.r = 0; //result.i = 0; //for(int i = 0; i < iter; i++){ // scalar_powers(number, i, power); // scalar_division(power, factorial(i), division); // scalar_addition(result, division, result); //} } //empty /* array manipulation [0/1] */ void array_powers(COMPLEX array[], const int len, const int power){/**/ /* for(int i = 0; i < len; i++){ array[i] = complex_power(array[i], power, result); } */ } //empty /* Matrix manipulation [2/4] */ void diagonal_matrix_powers(){ //empty //... } void matrix_eigenvstuff(const LaGenMatComplex& matrix, LaVectorComplex& eigenvalues, LaGenMatComplex& eigenvectors){ //working //LaEigSolve: http://lapackpp.sourceforge.net/html/laslv_8h.html#086357d17e9cdcaec69ab7db76998769 LaEigSolve(matrix, eigenvalues, eigenvectors); } void matrix_inverse(LaGenMatComplex& matrix, int len){ //working // LaLUInverseIP: http://lapackpp.sourceforge.net/html/laslv_8h.html#a042c82c5b818f54e7f000d068f14189 LaVectorLongInt PIV = LaVectorLongInt(len); LUFactorizeIP(matrix, PIV); LaLUInverseIP(matrix, PIV); } void matrix_exp_step(){ //empty // } void matrix_exponential(const LaGenMatComplex& eigenvectors, const LaGenMatComplex& eigenvalues){ //LaGenMatComplex step = LaGenMatComplex } //empty /* Testing [3/3] */ void test_scalar_manipulation(const int max_rand){ COMPLEX compA; //initialisation generate_scalar(compA, max_rand); COMPLEX compB; generate_scalar(compB, max_rand); int realB; generate_scalar(realB, max_rand); COMPLEX result; for(int i = 1; i < 5; i++){ //factorials cout << "factorial(" << i << "): " << factorial(i) << endl; } scalar_addition(compA, compB, result); //addition/subtraction cout << "scalar addition: " << result << endl << endl; scalar_multiplication(compA, realB, result); //multiplication cout << "scalar multiplication by scalar: " << result << endl << endl; scalar_multiplication(compA, compB, result); cout << "scalar multiplication by complex: " << result << endl << endl; scalar_division(compA, realB, result); //division cout << "scalar division by scalar: " << result << endl << endl; scalar_division(compA, compB, result); cout << "scalar division by complex: " << result << endl << endl; for(int i = 1; i < 5; i++){ scalar_powers(compA, i, result); cout << "scalar powers - A^" << i << " = " << result << endl; } } //to test void test_eigenvalues(const LaGenMatComplex& initialMatrix, const int size){ LaVectorComplex eigenvalueVec = LaVectorComplex(size); //initialise eigenstuff LaGenMatComplex eigenvalues = LaGenMatComplex::zeros(size, size); LaGenMatComplex eigenvectors = LaGenMatComplex::zeros(size, size); matrix_eigenvstuff(initialMatrix, eigenvalueVec, eigenvectors); //calculate eigenstuff print_matrix(eigenvalueVec, "eigenvalue vector"); //print eigenstuff vec_to_diag(eigenvalueVec, size, eigenvalues); print_matrix(eigenvalues, "eigenvalue matrix"); print_matrix(eigenvectors, "eigenvector matrix"); } //to test void test_inverse(const LaGenMatComplex& initialMatrix, const int size){ LaGenMatComplex inverseMatrix; inverseMatrix = initialMatrix.copy(); matrix_inverse(inverseMatrix, size); print_matrix(inverseMatrix, "inverse matrix"); } //to test void test_scalar_exponential(const int iterations, const int max_rand){ COMPLEX number, result; generate_scalar(number, max_rand); cout << endl << "scalar exponential test no.: " << number << endl << endl; scalar_exponential_1(number, iterations, result); cout << "e^" << number << " = " << result << endl; } void test_matrix_exponential(const LaGenMatComplex& initialMatrix, const int size){ //... } /* Main Program */ int main(){ // int matrix_size = 3, max_rand = 9; // int matrix_volume = matrix_size * matrix_size; /* generate the matrix */ // COMPLEX elements[matrix_volume]; // generate_array(elements, matrix_volume, max_rand); // LaGenMatComplex initialMatrix = LaGenMatComplex(elements, matrix_size, matrix_size, false ); // print_matrix(initialMatrix, "initial matrix"); /* test eigenvalues */ // test_eigenvalues(initialMatrix, matrix_size); /* test scalar manipulation */ // test_scalar_manipulation(4); /* test scalar sum */ COMPLEX A, B, C; A.r = 2; A.i = 1; B.r = 1; B.i = 1; cout << "A = " << A << endl; cout << "B = " << B << endl; for(int i = 0; i < 4; i++){ scalar_addition(A, B, C); // A + B = C A = C; } cout << "A + 4B = " << C << endl; /* test scalar product */ /* test scalar exponentials */ // test_scalar_exponential(3,4); /* test inversion */ // test_inverse(initialMatrix, matrix_size); } <commit_msg>testing<commit_after>#include <iostream> //cout #include <cstdlib> //rand, sran #include <string> #include "complex_matrices.h" #include <gmc.h> //LaGenMatComplex #include <laslv.h> //LUFactorizeIP, LaLUInverseIP, etc. #include <blas3pp.h> using namespace std; /* Total [13/20] */ /* Printing [6/9] */ void print_scalar(const COMPLEX scalar){ cout << scalar << endl; } //working void print_scalar(const COMPLEX scalar, const string name){ cout << name << ":" << scalar << endl; } //working void print_array(const COMPLEX array[], int len){ for(int i = 0; i < len; i++){ cout << array[i] << endl; } } //working void print_array(const COMPLEX array[], int len, const string name){ cout << name << ":" << endl; for(int i = 0; i < len; i++){ cout << array[i] << endl; } } //working void print_matrix(const LaGenMatComplex& matrix){ cout << matrix << endl; } //working void print_matrix(const LaGenMatComplex& matrix, const string name){ cout << name << ":" << endl << matrix << endl; } //working /* Number generation [2/2] */ void generate_scalar(COMPLEX& A, const int x){ A.r = rand() % x; //1 to x A.i = rand() % x; } //working void generate_scalar(int A, const int x){ A = rand() % x; //1 to x } //working void generate_array(COMPLEX array[], const int len, const int x){ srand(time(NULL)); //seed for(int i = 0; i < len; i++){ array[i].r = rand() % x; //1 to x array[i].i = rand() % x; } } //working /* Matrix conversion [3/3] */ void vec_to_array(const LaVectorComplex& vector, const int len, COMPLEX array[ ]){ for(int i = 0; i < len; i++){ array[i] = vector(i); } } //working void array_to_diag(COMPLEX array[], const int len, LaGenMatComplex& diag){ diag = 0; for(int i = 0; i < len; i++){ diag(i, i) = array[i]; } } //working void vec_to_diag(const LaVectorComplex& vector, const int len, LaGenMatComplex& diag){ COMPLEX array[len]; vec_to_array(vector, len, array); array_to_diag(array, len, diag); } //working /* Scalar manipulation [5/8] */ int factorial(int x){ if(x <= 1){ return 1; }else{ return x * factorial(x - 1); } } //working void scalar_addition(const COMPLEX& A, const COMPLEX& B , COMPLEX& result){ result.r = A.r + B.r; result.i = A.i + B.i; } //working void scalar_sum(){ //... } void scalar_multiplication(const COMPLEX& A, const int B, COMPLEX& result){ result.r = A.r * B; result.i = A.i * B; } //to test void scalar_multiplication(const COMPLEX& A, const COMPLEX& B, COMPLEX& result){ la::complex<double> laA = la::complex<double>(A); //convert to la::complex<double> la::complex<double> laB = la::complex<double>(B); la::complex<double> laResult = la::complex<double>(result); laResult = laA * laB; result = laResult.toCOMPLEX(); } //to test void scalar_division(const COMPLEX& A, const int B, COMPLEX& result){ result.r = A.r / B; result.i = A.i / B; } //to test void scalar_division(const COMPLEX& A, const COMPLEX& B, COMPLEX& result){ la::complex<double> laA = la::complex<double>(A); //convert to la::complex<double> la::complex<double> laB = la::complex<double>(B); la::complex<double> laResult = la::complex<double>(result); laResult = laA / laB; result = laResult.toCOMPLEX(); } //to test void scalar_powers(const COMPLEX& number, const int power, COMPLEX& result){ la::complex<double> laResult = la::complex<double>(number); la::complex<double> laNumber = la::complex<double>(number); for(int i = 1; i < power; i++){ laResult *= laNumber; } result = laResult.toCOMPLEX(); } //to test void scalar_exponential_1(const COMPLEX& number, const int iterations, COMPLEX& result){ COMPLEX division, total_division, A, B; result.r = 1; result.i = 1; for(int step = 1; step <= iterations; step++){ //sum (from 1 to n) division.r = 0; division.i = 0; total_division.r = 1; total_division.i = 0; for(int i = 1; i <= step; i++){ // ( num^n / n!) cout << "division = " << division << endl; cout << "total_division = " << total_division << endl; A = total_division; scalar_division(number, i, division); scalar_multiplication(A, division, total_division); } B = result; scalar_addition(B, total_division, result); cout << "sum = " << result << endl; } } void scalar_exponential(const COMPLEX& number, const int iter, COMPLEX& result){ //COMPLEX power; //COMPLEX division; //result.r = 0; //result.i = 0; //for(int i = 0; i < iter; i++){ // scalar_powers(number, i, power); // scalar_division(power, factorial(i), division); // scalar_addition(result, division, result); //} } //empty //COMPLEX rec_scalar_exp_step(const COMPLEX& number, const int step){ // COMPLEX result, division, multiplication; // if(step <= 1){ // result.r = 1; // return result; // }else{ // scalar_division(number,step,division); // scalar_multiplication(division, rec_scalar_exp_step(step-1), multiplication); // return multiplication; // } //} void recursive_scalar_exponential(const COMPLEX& number, const int iter, COMPLEX& result){ //COMPLEX power; //COMPLEX division; //result.r = 0; //result.i = 0; //for(int i = 0; i < iter; i++){ // scalar_powers(number, i, power); // scalar_division(power, factorial(i), division); // scalar_addition(result, division, result); //} } //empty /* array manipulation [0/1] */ void array_powers(COMPLEX array[], const int len, const int power){/**/ /* for(int i = 0; i < len; i++){ array[i] = complex_power(array[i], power, result); } */ } //empty /* Matrix manipulation [2/4] */ void diagonal_matrix_powers(){ //empty //... } void matrix_eigenvstuff(const LaGenMatComplex& matrix, LaVectorComplex& eigenvalues, LaGenMatComplex& eigenvectors){ //working //LaEigSolve: http://lapackpp.sourceforge.net/html/laslv_8h.html#086357d17e9cdcaec69ab7db76998769 LaEigSolve(matrix, eigenvalues, eigenvectors); } void matrix_inverse(LaGenMatComplex& matrix, int len){ //working // LaLUInverseIP: http://lapackpp.sourceforge.net/html/laslv_8h.html#a042c82c5b818f54e7f000d068f14189 LaVectorLongInt PIV = LaVectorLongInt(len); LUFactorizeIP(matrix, PIV); LaLUInverseIP(matrix, PIV); } void matrix_exp_step(){ //empty // } void matrix_exponential(const LaGenMatComplex& eigenvectors, const LaGenMatComplex& eigenvalues){ //LaGenMatComplex step = LaGenMatComplex } //empty /* Testing [3/3] */ void test_scalar_manipulation(const int max_rand){ COMPLEX compA; //initialisation generate_scalar(compA, max_rand); COMPLEX compB; generate_scalar(compB, max_rand); int realB; generate_scalar(realB, max_rand); COMPLEX result; for(int i = 1; i < 5; i++){ //factorials cout << "factorial(" << i << "): " << factorial(i) << endl; } scalar_addition(compA, compB, result); //addition/subtraction cout << "scalar addition: " << result << endl << endl; scalar_multiplication(compA, realB, result); //multiplication cout << "scalar multiplication by scalar: " << result << endl << endl; scalar_multiplication(compA, compB, result); cout << "scalar multiplication by complex: " << result << endl << endl; scalar_division(compA, realB, result); //division cout << "scalar division by scalar: " << result << endl << endl; scalar_division(compA, compB, result); cout << "scalar division by complex: " << result << endl << endl; for(int i = 1; i < 5; i++){ scalar_powers(compA, i, result); cout << "scalar powers - A^" << i << " = " << result << endl; } } //to test void test_eigenvalues(const LaGenMatComplex& initialMatrix, const int size){ LaVectorComplex eigenvalueVec = LaVectorComplex(size); //initialise eigenstuff LaGenMatComplex eigenvalues = LaGenMatComplex::zeros(size, size); LaGenMatComplex eigenvectors = LaGenMatComplex::zeros(size, size); matrix_eigenvstuff(initialMatrix, eigenvalueVec, eigenvectors); //calculate eigenstuff print_matrix(eigenvalueVec, "eigenvalue vector"); //print eigenstuff vec_to_diag(eigenvalueVec, size, eigenvalues); print_matrix(eigenvalues, "eigenvalue matrix"); print_matrix(eigenvectors, "eigenvector matrix"); } //to test void test_inverse(const LaGenMatComplex& initialMatrix, const int size){ LaGenMatComplex inverseMatrix; inverseMatrix = initialMatrix.copy(); matrix_inverse(inverseMatrix, size); print_matrix(inverseMatrix, "inverse matrix"); } //to test void test_scalar_exponential(const int iterations, const int max_rand){ COMPLEX number, result; generate_scalar(number, max_rand); cout << endl << "scalar exponential test no.: " << number << endl << endl; scalar_exponential_1(number, iterations, result); cout << "e^" << number << " = " << result << endl; } void test_matrix_exponential(const LaGenMatComplex& initialMatrix, const int size){ //... } /* Main Program */ int main(){ // int matrix_size = 3, max_rand = 9; // int matrix_volume = matrix_size * matrix_size; /* generate the matrix */ // COMPLEX elements[matrix_volume]; // generate_array(elements, matrix_volume, max_rand); // LaGenMatComplex initialMatrix = LaGenMatComplex(elements, matrix_size, matrix_size, false ); // print_matrix(initialMatrix, "initial matrix"); /* test eigenvalues */ // test_eigenvalues(initialMatrix, matrix_size); /* test scalar manipulation */ // test_scalar_manipulation(4); /* test scalar sum */ COMPLEX A, B, C; A.r = 0; A.i = 0; B.r = 1; B.i = 1; cout << "A = " << A << endl; cout << "B = " << B << endl; for(int i = 0; i < 4; i++){ scalar_addition(A, B, C); // A + B = C A = C; B.r++; } cout << "A + 4B = " << C << endl; /* test scalar product */ /* test scalar exponentials */ // test_scalar_exponential(3,4); /* test inversion */ // test_inverse(initialMatrix, matrix_size); } <|endoftext|>
<commit_before>/* Copyright (c) 2007 Till Adam <adam@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "maildirresource.h" #include "settings.h" #include "settingsadaptor.h" #include "configdialog.h" #include <QtCore/QDir> #include <QtDBus/QDBusConnection> #include <akonadi/kmime/messageparts.h> #include <akonadi/changerecorder.h> #include <akonadi/itemfetchscope.h> #include <kdebug.h> #include <kurl.h> #include <kfiledialog.h> #include <klocale.h> #include <KWindowSystem> #include "libmaildir/maildir.h" #include <kmime/kmime_message.h> #include <boost/shared_ptr.hpp> typedef boost::shared_ptr<KMime::Message> MessagePtr; using namespace Akonadi; using KPIM::Maildir; static QString maildirPath( const QString &remoteId ) { const int pos = remoteId.lastIndexOf( QDir::separator() ); if ( pos >= 0 ) return remoteId.left( pos ); return QString(); } static QString maildirId( const QString &remoteId ) { const int pos = remoteId.lastIndexOf( QDir::separator() ); if ( pos >= 0 ) return remoteId.mid( pos + 1 ); return QString(); } static QString maildirSubdirPath( const QString &parentPath, const QString &subName ) { QString basePath = maildirPath( parentPath ); if ( !basePath.endsWith( QDir::separator() ) ) basePath += QDir::separator(); const QString name = maildirId( parentPath ); return basePath + '.' + name + ".directory" + QDir::separator() + subName; } MaildirResource::MaildirResource( const QString &id ) :ResourceBase( id ) { new SettingsAdaptor( Settings::self() ); QDBusConnection::sessionBus().registerObject( QLatin1String( "/Settings" ), Settings::self(), QDBusConnection::ExportAdaptors ); connect( this, SIGNAL(reloadConfiguration()), SLOT(ensureDirExists()) ); // We need to enable this here, otherwise we neither get the remote ID of the // parent collection when a collection changes, nor the full item when an item // is added. changeRecorder()->fetchCollection( true ); changeRecorder()->itemFetchScope().fetchFullPayload( true ); } MaildirResource::~ MaildirResource() { } bool MaildirResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray> &parts ) { Q_UNUSED( parts ); const QString dir = maildirPath( item.remoteId() ); const QString entry = maildirId( item.remoteId() ); Maildir md( dir ); if ( !md.isValid() ) { cancelTask( i18n( "Unable to fetch item: The maildir folder \"%1\" is not valid.", md.path() ) ); return false; } const QByteArray data = md.readEntry( entry ); KMime::Message *mail = new KMime::Message(); mail->setContent( KMime::CRLFtoLF( data ) ); mail->parse(); Item i( item ); i.setPayload( MessagePtr( mail ) ); itemRetrieved( i ); return true; } void MaildirResource::aboutToQuit() { kDebug( 5254 ) << "Implement me!" ; } void MaildirResource::configure( WId windowId ) { ConfigDialog dlg; if ( windowId ) KWindowSystem::setMainWindow( &dlg, windowId ); dlg.exec(); ensureDirExists(); synchronizeCollectionTree(); } void MaildirResource::itemAdded( const Akonadi::Item & item, const Akonadi::Collection& collection ) { Maildir dir( collection.remoteId() ); QString errMsg; if ( Settings::readOnly() || !dir.isValid( errMsg ) ) { cancelTask( errMsg ); return; } // we can only deal with mail if ( item.mimeType() != "message/rfc822" ) { cancelTask( i18n("Only email messages can be added to the Maildir resource.") ); return; } const MessagePtr mail = item.payload<MessagePtr>(); const QString rid = collection.remoteId() + QDir::separator() + dir.addEntry( mail->encodedContent() ); Item i( item ); i.setRemoteId( rid ); changeCommitted( i ); } void MaildirResource::itemChanged( const Akonadi::Item& item, const QSet<QByteArray>& parts ) { if ( Settings::self()->readOnly() || !parts.contains( MessagePart::Body ) ) { changeProcessed(); return; } const QString path = maildirPath( item.remoteId() ); const QString entry = maildirId( item.remoteId() ); Maildir dir( path ); QString errMsg; if ( !dir.isValid( errMsg ) ) { cancelTask( errMsg ); return; } // we can only deal with mail if ( item.mimeType() != "message/rfc822" ) { cancelTask( i18n("Only email messages can be added to the Maildir resource.") ); return; } const MessagePtr mail = item.payload<MessagePtr>(); dir.writeEntry( entry, mail->encodedContent() ); changeCommitted( item ); } void MaildirResource::itemRemoved(const Akonadi::Item & item) { if ( !Settings::self()->readOnly() ) { const QString path = maildirPath( item.remoteId() ); const QString entry = maildirId( item.remoteId() ); Maildir dir( path ); QString errMsg; if ( !dir.isValid( errMsg ) ) { cancelTask( errMsg ); return; } if ( !dir.removeEntry( entry ) ) { emit error( i18n("Failed to delete item: %1", item.remoteId()) ); } } changeProcessed(); } Collection::List listRecursive( const Collection &root, const Maildir &dir ) { Collection::List list; const QStringList mimeTypes = QStringList() << "message/rfc822" << Collection::mimeType(); foreach ( const QString &sub, dir.subFolderList() ) { const QString path = maildirSubdirPath( root.remoteId(), sub ); Maildir md( path ); if ( !md.isValid() ) continue; Collection c; c.setName( sub ); c.setRemoteId( path ); c.setParent( root ); c.setContentMimeTypes( mimeTypes ); list << c; list += listRecursive( c, md ); } return list; } void MaildirResource::retrieveCollections() { Maildir dir( Settings::self()->path() ); QString errMsg; if ( !dir.isValid( errMsg ) ) { emit error( errMsg ); collectionsRetrieved( Collection::List() ); } Collection root; root.setParent( Collection::root() ); root.setRemoteId( Settings::self()->path() ); root.setName( name() ); QStringList mimeTypes; mimeTypes << "message/rfc822" << Collection::mimeType(); root.setContentMimeTypes( mimeTypes ); Collection::List list; list << root; list += listRecursive( root, dir ); collectionsRetrieved( list ); } void MaildirResource::retrieveItems( const Akonadi::Collection & col ) { Maildir md( col.remoteId() ); if ( !md.isValid() ) { emit error( i18n("Invalid maildir: %1", col.remoteId() ) ); itemsRetrieved( Item::List() ); return; } QStringList entryList = md.entryList(); Item::List items; foreach ( const QString &entry, entryList ) { const QString rid = col.remoteId() + QDir::separator() + entry; Item item; item.setRemoteId( rid ); item.setMimeType( "message/rfc822" ); item.setSize( md.size( entry ) ); KMime::Message *msg = new KMime::Message; msg->setHead( KMime::CRLFtoLF( md.readEntryHeaders( entry ) ) ); msg->parse(); item.setPayload( MessagePtr( msg ) ); items << item; } itemsRetrieved( items ); } void MaildirResource::collectionAdded(const Collection & collection, const Collection &parent) { Maildir md( parent.remoteId() ); kDebug( 5254 ) << md.subFolderList() << md.entryList(); if ( Settings::self()->readOnly() || !md.isValid() ) { changeProcessed(); return; } else { QString newFolderPath = md.addSubFolder( collection.name() ); if ( newFolderPath.isEmpty() ) { changeProcessed(); return; } kDebug( 5254 ) << md.subFolderList() << md.entryList(); Collection col = collection; col.setRemoteId( newFolderPath ); changeCommitted( col ); } } void MaildirResource::collectionChanged(const Collection & collection) { kDebug( 5254 ) << "Implement me!"; AgentBase::Observer::collectionChanged( collection ); } void MaildirResource::collectionRemoved( const Akonadi::Collection &collection ) { kDebug( 5254 ) << "Implement me!"; AgentBase::Observer::collectionRemoved( collection ); } void MaildirResource::ensureDirExists() { Maildir root( Settings::self()->path() ); if ( !root.isValid() ) { if ( !root.create() ) emit status( Broken, i18n( "Unable to create maildir '%1'." ).arg( Settings::self()->path() ) ); } } AKONADI_RESOURCE_MAIN( MaildirResource ) #include "maildirresource.moc" <commit_msg>Make the resource save its settings on exit. They were only saved on 'ok' in the config dialog, and changes made via dbus were lost.<commit_after>/* Copyright (c) 2007 Till Adam <adam@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "maildirresource.h" #include "settings.h" #include "settingsadaptor.h" #include "configdialog.h" #include <QtCore/QDir> #include <QtDBus/QDBusConnection> #include <akonadi/kmime/messageparts.h> #include <akonadi/changerecorder.h> #include <akonadi/itemfetchscope.h> #include <kdebug.h> #include <kurl.h> #include <kfiledialog.h> #include <klocale.h> #include <KWindowSystem> #include "libmaildir/maildir.h" #include <kmime/kmime_message.h> #include <boost/shared_ptr.hpp> typedef boost::shared_ptr<KMime::Message> MessagePtr; using namespace Akonadi; using KPIM::Maildir; static QString maildirPath( const QString &remoteId ) { const int pos = remoteId.lastIndexOf( QDir::separator() ); if ( pos >= 0 ) return remoteId.left( pos ); return QString(); } static QString maildirId( const QString &remoteId ) { const int pos = remoteId.lastIndexOf( QDir::separator() ); if ( pos >= 0 ) return remoteId.mid( pos + 1 ); return QString(); } static QString maildirSubdirPath( const QString &parentPath, const QString &subName ) { QString basePath = maildirPath( parentPath ); if ( !basePath.endsWith( QDir::separator() ) ) basePath += QDir::separator(); const QString name = maildirId( parentPath ); return basePath + '.' + name + ".directory" + QDir::separator() + subName; } MaildirResource::MaildirResource( const QString &id ) :ResourceBase( id ) { new SettingsAdaptor( Settings::self() ); QDBusConnection::sessionBus().registerObject( QLatin1String( "/Settings" ), Settings::self(), QDBusConnection::ExportAdaptors ); connect( this, SIGNAL(reloadConfiguration()), SLOT(ensureDirExists()) ); // We need to enable this here, otherwise we neither get the remote ID of the // parent collection when a collection changes, nor the full item when an item // is added. changeRecorder()->fetchCollection( true ); changeRecorder()->itemFetchScope().fetchFullPayload( true ); } MaildirResource::~ MaildirResource() { } bool MaildirResource::retrieveItem( const Akonadi::Item &item, const QSet<QByteArray> &parts ) { Q_UNUSED( parts ); const QString dir = maildirPath( item.remoteId() ); const QString entry = maildirId( item.remoteId() ); Maildir md( dir ); if ( !md.isValid() ) { cancelTask( i18n( "Unable to fetch item: The maildir folder \"%1\" is not valid.", md.path() ) ); return false; } const QByteArray data = md.readEntry( entry ); KMime::Message *mail = new KMime::Message(); mail->setContent( KMime::CRLFtoLF( data ) ); mail->parse(); Item i( item ); i.setPayload( MessagePtr( mail ) ); itemRetrieved( i ); return true; } void MaildirResource::aboutToQuit() { // The settings may not have been saved if e.g. they have been modified via // DBus instead of the config dialog. Settings::self()->writeConfig(); kDebug( 5254 ) << "Implement me!" ; } void MaildirResource::configure( WId windowId ) { ConfigDialog dlg; if ( windowId ) KWindowSystem::setMainWindow( &dlg, windowId ); dlg.exec(); ensureDirExists(); synchronizeCollectionTree(); } void MaildirResource::itemAdded( const Akonadi::Item & item, const Akonadi::Collection& collection ) { Maildir dir( collection.remoteId() ); QString errMsg; if ( Settings::readOnly() || !dir.isValid( errMsg ) ) { cancelTask( errMsg ); return; } // we can only deal with mail if ( item.mimeType() != "message/rfc822" ) { cancelTask( i18n("Only email messages can be added to the Maildir resource.") ); return; } const MessagePtr mail = item.payload<MessagePtr>(); const QString rid = collection.remoteId() + QDir::separator() + dir.addEntry( mail->encodedContent() ); Item i( item ); i.setRemoteId( rid ); changeCommitted( i ); } void MaildirResource::itemChanged( const Akonadi::Item& item, const QSet<QByteArray>& parts ) { if ( Settings::self()->readOnly() || !parts.contains( MessagePart::Body ) ) { changeProcessed(); return; } const QString path = maildirPath( item.remoteId() ); const QString entry = maildirId( item.remoteId() ); Maildir dir( path ); QString errMsg; if ( !dir.isValid( errMsg ) ) { cancelTask( errMsg ); return; } // we can only deal with mail if ( item.mimeType() != "message/rfc822" ) { cancelTask( i18n("Only email messages can be added to the Maildir resource.") ); return; } const MessagePtr mail = item.payload<MessagePtr>(); dir.writeEntry( entry, mail->encodedContent() ); changeCommitted( item ); } void MaildirResource::itemRemoved(const Akonadi::Item & item) { if ( !Settings::self()->readOnly() ) { const QString path = maildirPath( item.remoteId() ); const QString entry = maildirId( item.remoteId() ); Maildir dir( path ); QString errMsg; if ( !dir.isValid( errMsg ) ) { cancelTask( errMsg ); return; } if ( !dir.removeEntry( entry ) ) { emit error( i18n("Failed to delete item: %1", item.remoteId()) ); } } changeProcessed(); } Collection::List listRecursive( const Collection &root, const Maildir &dir ) { Collection::List list; const QStringList mimeTypes = QStringList() << "message/rfc822" << Collection::mimeType(); foreach ( const QString &sub, dir.subFolderList() ) { const QString path = maildirSubdirPath( root.remoteId(), sub ); Maildir md( path ); if ( !md.isValid() ) continue; Collection c; c.setName( sub ); c.setRemoteId( path ); c.setParent( root ); c.setContentMimeTypes( mimeTypes ); list << c; list += listRecursive( c, md ); } return list; } void MaildirResource::retrieveCollections() { Maildir dir( Settings::self()->path() ); QString errMsg; if ( !dir.isValid( errMsg ) ) { emit error( errMsg ); collectionsRetrieved( Collection::List() ); } Collection root; root.setParent( Collection::root() ); root.setRemoteId( Settings::self()->path() ); root.setName( name() ); QStringList mimeTypes; mimeTypes << "message/rfc822" << Collection::mimeType(); root.setContentMimeTypes( mimeTypes ); Collection::List list; list << root; list += listRecursive( root, dir ); collectionsRetrieved( list ); } void MaildirResource::retrieveItems( const Akonadi::Collection & col ) { Maildir md( col.remoteId() ); if ( !md.isValid() ) { emit error( i18n("Invalid maildir: %1", col.remoteId() ) ); itemsRetrieved( Item::List() ); return; } QStringList entryList = md.entryList(); Item::List items; foreach ( const QString &entry, entryList ) { const QString rid = col.remoteId() + QDir::separator() + entry; Item item; item.setRemoteId( rid ); item.setMimeType( "message/rfc822" ); item.setSize( md.size( entry ) ); KMime::Message *msg = new KMime::Message; msg->setHead( KMime::CRLFtoLF( md.readEntryHeaders( entry ) ) ); msg->parse(); item.setPayload( MessagePtr( msg ) ); items << item; } itemsRetrieved( items ); } void MaildirResource::collectionAdded(const Collection & collection, const Collection &parent) { Maildir md( parent.remoteId() ); kDebug( 5254 ) << md.subFolderList() << md.entryList(); if ( Settings::self()->readOnly() || !md.isValid() ) { changeProcessed(); return; } else { QString newFolderPath = md.addSubFolder( collection.name() ); if ( newFolderPath.isEmpty() ) { changeProcessed(); return; } kDebug( 5254 ) << md.subFolderList() << md.entryList(); Collection col = collection; col.setRemoteId( newFolderPath ); changeCommitted( col ); } } void MaildirResource::collectionChanged(const Collection & collection) { kDebug( 5254 ) << "Implement me!"; AgentBase::Observer::collectionChanged( collection ); } void MaildirResource::collectionRemoved( const Akonadi::Collection &collection ) { kDebug( 5254 ) << "Implement me!"; AgentBase::Observer::collectionRemoved( collection ); } void MaildirResource::ensureDirExists() { Maildir root( Settings::self()->path() ); if ( !root.isValid() ) { if ( !root.create() ) emit status( Broken, i18n( "Unable to create maildir '%1'." ).arg( Settings::self()->path() ) ); } } AKONADI_RESOURCE_MAIN( MaildirResource ) #include "maildirresource.moc" <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: vendorbase.hxx,v $ * $Revision: 1.13 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #if !defined INCLUDED_JFW_PLUGIN_VENDORBASE_HXX #define INCLUDED_JFW_PLUGIN_VENDORBASE_HXX #include "rtl/ustring.hxx" #include "rtl/ref.hxx" #include "osl/endian.h" #include "salhelper/simplereferenceobject.hxx" #include <vector> namespace jfw_plugin { //Used by subclasses of VendorBase to build paths to Java runtime #if defined SPARC #define JFW_PLUGIN_ARCH "sparc" #elif defined X86_64 #define JFW_PLUGIN_ARCH "amd64" #elif defined INTEL #define JFW_PLUGIN_ARCH "i386" #elif defined POWERPC64 #define JFW_PLUGIN_ARCH "ppc64" #elif defined POWERPC #define JFW_PLUGIN_ARCH "ppc" #elif defined MIPS #ifdef OSL_BIGENDIAN # define JFW_PLUGIN_ARCH "mips" #else # define JFW_PLUGIN_ARCH "mips32" #endif #elif defined S390X #define JFW_PLUGIN_ARCH "s390x" #elif defined S390 #define JFW_PLUGIN_ARCH "s390" #elif defined ARM #define JFW_PLUGIN_ARCH "arm" #elif defined IA64 #define JFW_PLUGIN_ARCH "ia64" #else // SPARC, INTEL, POWERPC, MIPS, ARM #error unknown plattform #endif // SPARC, INTEL, POWERPC, MIPS, ARM class MalformedVersionException { public: MalformedVersionException(); MalformedVersionException(const MalformedVersionException &); virtual ~MalformedVersionException(); MalformedVersionException & operator =(const MalformedVersionException &); }; class VendorBase: public salhelper::SimpleReferenceObject { public: VendorBase(); /* returns relativ paths to the java executable as file URLs. For example "bin/java.exe". You need to implement this function in a derived class, if the paths differ. this implmentation provides for Windows "bin/java.exe" and for Unix "bin/java". The paths are relative file URLs. That is, they always contain '/' even on windows. The paths are relative to the installation directory of a JRE. The signature of this function must correspond to getJavaExePaths_func. */ static char const* const * getJavaExePaths(int* size); /* creates an instance of this class. MUST be overridden in a derived class. #################################################### OVERRIDE in derived class ################################################### @param Key - value pairs of the system properties of the JRE. */ static rtl::Reference<VendorBase> createInstance(); /* called automatically on the instance created by createInstance. @return true - the object could completely initialize. false - the object could not completly initialize. In this case it will be discarded by the caller. */ virtual bool initialize( std::vector<std::pair<rtl::OUString, rtl::OUString> > props); /* returns relative file URLs to the runtime library. For example "/bin/client/jvm.dll" */ virtual char const* const* getRuntimePaths(int* size); virtual char const* const* getLibraryPaths(int* size); virtual const rtl::OUString & getVendor() const; virtual const rtl::OUString & getVersion() const; virtual const rtl::OUString & getHome() const; virtual const rtl::OUString & getRuntimeLibrary() const; virtual const rtl::OUString & getLibraryPaths() const; virtual bool supportsAccessibility() const; /* determines if prior to running java something has to be done, like setting the LD_LIBRARY_PATH. This implementation checks if an LD_LIBRARY_PATH (getLD_LIBRARY_PATH) needs to be set and if so, needsRestart returns true. */ virtual bool needsRestart() const; /* compares versions of this vendor. MUST be overridden in a derived class. #################################################### OVERRIDE in derived class ################################################### @return 0 this.version == sSecond 1 this.version > sSecond -1 this.version < sSEcond @throw MalformedVersionException if the version string was not recognized. */ virtual int compareVersions(const rtl::OUString& sSecond) const; protected: rtl::OUString m_sVendor; rtl::OUString m_sVersion; rtl::OUString m_sHome; rtl::OUString m_sRuntimeLibrary; rtl::OUString m_sLD_LIBRARY_PATH; bool m_bAccessibility; typedef rtl::Reference<VendorBase> (* createInstance_func) (); friend rtl::Reference<VendorBase> createInstance( createInstance_func pFunc, std::vector<std::pair<rtl::OUString, rtl::OUString> > properties); }; } #endif <commit_msg>INTEGRATION: CWS hr51 (1.13.4); FILE MERGED 2008/06/06 14:11:17 hr 1.13.4.1: #i88947#: Solaris 64 bit support<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: vendorbase.hxx,v $ * $Revision: 1.14 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #if !defined INCLUDED_JFW_PLUGIN_VENDORBASE_HXX #define INCLUDED_JFW_PLUGIN_VENDORBASE_HXX #include "rtl/ustring.hxx" #include "rtl/ref.hxx" #include "osl/endian.h" #include "salhelper/simplereferenceobject.hxx" #include <vector> namespace jfw_plugin { //Used by subclasses of VendorBase to build paths to Java runtime #if defined(__sparcv9) #define JFW_PLUGIN_ARCH "sparcv9" #elif defined SPARC #define JFW_PLUGIN_ARCH "sparc" #elif defined X86_64 #define JFW_PLUGIN_ARCH "amd64" #elif defined INTEL #define JFW_PLUGIN_ARCH "i386" #elif defined POWERPC64 #define JFW_PLUGIN_ARCH "ppc64" #elif defined POWERPC #define JFW_PLUGIN_ARCH "ppc" #elif defined MIPS #ifdef OSL_BIGENDIAN # define JFW_PLUGIN_ARCH "mips" #else # define JFW_PLUGIN_ARCH "mips32" #endif #elif defined S390X #define JFW_PLUGIN_ARCH "s390x" #elif defined S390 #define JFW_PLUGIN_ARCH "s390" #elif defined ARM #define JFW_PLUGIN_ARCH "arm" #elif defined IA64 #define JFW_PLUGIN_ARCH "ia64" #else // SPARC, INTEL, POWERPC, MIPS, ARM #error unknown plattform #endif // SPARC, INTEL, POWERPC, MIPS, ARM class MalformedVersionException { public: MalformedVersionException(); MalformedVersionException(const MalformedVersionException &); virtual ~MalformedVersionException(); MalformedVersionException & operator =(const MalformedVersionException &); }; class VendorBase: public salhelper::SimpleReferenceObject { public: VendorBase(); /* returns relativ paths to the java executable as file URLs. For example "bin/java.exe". You need to implement this function in a derived class, if the paths differ. this implmentation provides for Windows "bin/java.exe" and for Unix "bin/java". The paths are relative file URLs. That is, they always contain '/' even on windows. The paths are relative to the installation directory of a JRE. The signature of this function must correspond to getJavaExePaths_func. */ static char const* const * getJavaExePaths(int* size); /* creates an instance of this class. MUST be overridden in a derived class. #################################################### OVERRIDE in derived class ################################################### @param Key - value pairs of the system properties of the JRE. */ static rtl::Reference<VendorBase> createInstance(); /* called automatically on the instance created by createInstance. @return true - the object could completely initialize. false - the object could not completly initialize. In this case it will be discarded by the caller. */ virtual bool initialize( std::vector<std::pair<rtl::OUString, rtl::OUString> > props); /* returns relative file URLs to the runtime library. For example "/bin/client/jvm.dll" */ virtual char const* const* getRuntimePaths(int* size); virtual char const* const* getLibraryPaths(int* size); virtual const rtl::OUString & getVendor() const; virtual const rtl::OUString & getVersion() const; virtual const rtl::OUString & getHome() const; virtual const rtl::OUString & getRuntimeLibrary() const; virtual const rtl::OUString & getLibraryPaths() const; virtual bool supportsAccessibility() const; /* determines if prior to running java something has to be done, like setting the LD_LIBRARY_PATH. This implementation checks if an LD_LIBRARY_PATH (getLD_LIBRARY_PATH) needs to be set and if so, needsRestart returns true. */ virtual bool needsRestart() const; /* compares versions of this vendor. MUST be overridden in a derived class. #################################################### OVERRIDE in derived class ################################################### @return 0 this.version == sSecond 1 this.version > sSecond -1 this.version < sSEcond @throw MalformedVersionException if the version string was not recognized. */ virtual int compareVersions(const rtl::OUString& sSecond) const; protected: rtl::OUString m_sVendor; rtl::OUString m_sVersion; rtl::OUString m_sHome; rtl::OUString m_sRuntimeLibrary; rtl::OUString m_sLD_LIBRARY_PATH; bool m_bAccessibility; typedef rtl::Reference<VendorBase> (* createInstance_func) (); friend rtl::Reference<VendorBase> createInstance( createInstance_func pFunc, std::vector<std::pair<rtl::OUString, rtl::OUString> > properties); }; } #endif <|endoftext|>
<commit_before><commit_msg>planning: removed a line to change existing conf value of a gflag<commit_after><|endoftext|>
<commit_before>#include "framework/safaia/Safaia.h" using namespace Safaia; int main(){ auto unitTest = UnitTest(); // Unit Test Diagnostics auto secUnitTest = UnitTest(); auto tstUnitTestSuc = CaseSet("Unit Test Success Exampe"); tstUnitTestSuc.add(ASSERT("THIS MUST BE A SUCCESS", 1, 1, EQUAL)); secUnitTest.add(tstUnitTestSuc); int sec = secUnitTest.run(); std::cout << std::endl; auto failUnitTest = UnitTest(); auto tstUnitTestFail = CaseSet("Unit Test Failure Example"); tstUnitTestFail.add(ASSERT("THIS MUST BE A FAILURE", 1, 0, EQUAL)); failUnitTest.add(tstUnitTestFail); int fail = failUnitTest.run(); std::cout << std::endl; auto setUnitTest = CaseSet("Unit Test Diagnostics"); setUnitTest.add(ASSERT("Integer Equal", 42, 42, EQUAL)); setUnitTest.add(ASSERT("Integer Not Equal", 12, 450, NOT_EQUAL)); setUnitTest.add(ASSERT("Double Equal", 1.5, 1.5, EQUAL)); setUnitTest.add(ASSERT("Double Not Equal", -1.5, 1.5, NOT_EQUAL)); setUnitTest.add(ASSERT("String Equal", "Lolicon", "Lolicon", EQUAL)); setUnitTest.add(ASSERT("String Not Equal", "foo", "bar", NOT_EQUAL)); setUnitTest.add(ASSERT("Example Failure Unit Test Result", fail, 0, NOT_EQUAL)); setUnitTest.add(ASSERT("Example Success Unit Test Result", sec, 0, EQUAL)); unitTest.add(setUnitTest); // Safaia Request Module Unit Test auto setRequest = CaseSet("Safaia Request Module Unit Test"); auto request1 = Req("GET /login.html HTTP/1.1\r\nHost: 127.0.0.1\nConnection: keep-alive\nCache-Control: no-cache\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\nUpgrade-Insecure-Requests: 1\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36\nReferer: http://127.0.0.1/\nAccept-Encoding: gzip, deflate, sdch\nAccept-Language: zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4,ja;q=0.2\r\n\r\nTest Body"); setRequest.add(ASSERT("Request Method", request1.method, "GET", EQUAL)); setRequest.add(ASSERT("Request Url", request1.request_url, "/login.html", EQUAL)); setRequest.add(ASSERT("Protocol", request1.protocol, "HTTP/1.1", EQUAL)); setRequest.add(ASSERT("Fast Header", request1.host, "127.0.0.1", EQUAL)); setRequest.add(ASSERT("Standard Header", request1.header["Connection"], "keep-alive", EQUAL)); setRequest.add(ASSERT("Body", request1.body, "Test Body\n", EQUAL)); unitTest.add(setRequest); // Safaia Response Module Unit Test auto setResponse = CaseSet("Safaia Response Module Unit Test"); auto response1 = Resp("Hello World"); setResponse.add(ASSERT("Response Body", response1.body, "Hello World", EQUAL)); setResponse.add(ASSERT("Response Status Code", response1.status_code, "200 OK", EQUAL)); auto response2 = Resp(201, "Hello World"); setResponse.add(ASSERT("Response Body", response2.body, "Hello World", EQUAL)); setResponse.add(ASSERT("Response Status Code", response2.status_code, "201 Created", EQUAL)); unitTest.add(setResponse); auto response3 = Resp(999, "Hello Internal Error"); setResponse.add(ASSERT("Parse Status Code Error", response3.status_code, "500 Internal Server Error", EQUAL)); // Safaia Route Module Unit Test auto setRoute = CaseSet("Safaia Route Module Unit Test"); auto route1 = Route("GET", "/", [](Req req){return Resp("Hello World");}); setRoute.add(ASSERT("Route Method", route1.method, "GET", EQUAL)); setRoute.add(ASSERT("Route Path", route1.path, "/", EQUAL)); setRoute.add(ASSERT("Match Type", route1.is_regex, false, EQUAL)); auto route2 = Route("POST", std::regex("/(.*)"), [](Req req){return Resp("Hello World");}); setRoute.add(ASSERT("Route Method", route2.method, "POST", EQUAL)); setRoute.add(ASSERT("Route Path", route2.path, "", EQUAL)); setRoute.add(ASSERT("Match Type", route2.is_regex, true, EQUAL)); unitTest.add(setRoute); // Safaia Framework Unit Test auto setSafaia = CaseSet("Safaia Framework Unit Test"); auto server = Server(); unitTest.add(setSafaia); return unitTest.run(); }<commit_msg>Better diagnostics<commit_after>#include "framework/safaia/Safaia.h" using namespace Safaia; int main(){ auto unitTest = UnitTest(); // Unit Test Diagnostics auto secUnitTest = UnitTest(); auto tstUnitTestSuc = CaseSet("Unit Test Success Example"); tstUnitTestSuc.add(ASSERT("Integer Equal", 42, 42, EQUAL)); tstUnitTestSuc.add(ASSERT("Integer Not Equal", 12, 450, NOT_EQUAL)); tstUnitTestSuc.add(ASSERT("Double Equal", 1.5, 1.5, EQUAL)); tstUnitTestSuc.add(ASSERT("Double Not Equal", -1.5, 1.5, NOT_EQUAL)); tstUnitTestSuc.add(ASSERT("String Equal", "Lolicon", "Lolicon", EQUAL)); tstUnitTestSuc.add(ASSERT("String Not Equal", "foo", "bar", NOT_EQUAL)); secUnitTest.add(tstUnitTestSuc); int sec = secUnitTest.run(); std::cout << std::endl; auto failUnitTest = UnitTest(); auto tstUnitTestFail = CaseSet("Unit Test Failure Example"); tstUnitTestFail.add(ASSERT("Integer Equal", 42, 42, NOT_EQUAL)); tstUnitTestFail.add(ASSERT("Integer Not Equal", 12, 450, EQUAL)); tstUnitTestFail.add(ASSERT("Double Equal", 1.5, 1.5, NOT_EQUAL)); tstUnitTestFail.add(ASSERT("Double Not Equal", -1.5, 1.5, EQUAL)); tstUnitTestFail.add(ASSERT("String Equal", "Lolicon", "Lolicon", NOT_EQUAL)); tstUnitTestFail.add(ASSERT("String Not Equal", "foo", "bar", EQUAL)); failUnitTest.add(tstUnitTestFail); int fail = failUnitTest.run(); std::cout << std::endl; auto setUnitTest = CaseSet("Unit Test Diagnostics"); setUnitTest.add(ASSERT("Example Failure Unit Test Result", fail, 0, NOT_EQUAL)); setUnitTest.add(ASSERT("Example Success Unit Test Result", sec, 0, EQUAL)); unitTest.add(setUnitTest); // Safaia Request Module Unit Test auto setRequest = CaseSet("Safaia Request Module Unit Test"); auto request1 = Req("GET /login.html HTTP/1.1\r\nHost: 127.0.0.1\nConnection: keep-alive\nCache-Control: no-cache\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\nUpgrade-Insecure-Requests: 1\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36\nReferer: http://127.0.0.1/\nAccept-Encoding: gzip, deflate, sdch\nAccept-Language: zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4,ja;q=0.2\r\n\r\nTest Body"); setRequest.add(ASSERT("Request Method", request1.method, "GET", EQUAL)); setRequest.add(ASSERT("Request Url", request1.request_url, "/login.html", EQUAL)); setRequest.add(ASSERT("Protocol", request1.protocol, "HTTP/1.1", EQUAL)); setRequest.add(ASSERT("Fast Header", request1.host, "127.0.0.1", EQUAL)); setRequest.add(ASSERT("Standard Header", request1.header["Connection"], "keep-alive", EQUAL)); setRequest.add(ASSERT("Body", request1.body, "Test Body\n", EQUAL)); unitTest.add(setRequest); // Safaia Response Module Unit Test auto setResponse = CaseSet("Safaia Response Module Unit Test"); auto response1 = Resp("Hello World"); setResponse.add(ASSERT("Response Body", response1.body, "Hello World", EQUAL)); setResponse.add(ASSERT("Response Status Code", response1.status_code, "200 OK", EQUAL)); auto response2 = Resp(201, "Hello World"); setResponse.add(ASSERT("Response Body", response2.body, "Hello World", EQUAL)); setResponse.add(ASSERT("Response Status Code", response2.status_code, "201 Created", EQUAL)); unitTest.add(setResponse); auto response3 = Resp(999, "Hello Internal Error"); setResponse.add(ASSERT("Parse Status Code Error", response3.status_code, "500 Internal Server Error", EQUAL)); // Safaia Route Module Unit Test auto setRoute = CaseSet("Safaia Route Module Unit Test"); auto route1 = Route("GET", "/", [](Req req){return Resp("Hello World");}); setRoute.add(ASSERT("Route Method", route1.method, "GET", EQUAL)); setRoute.add(ASSERT("Route Path", route1.path, "/", EQUAL)); setRoute.add(ASSERT("Match Type", route1.is_regex, false, EQUAL)); auto route2 = Route("POST", std::regex("/(.*)"), [](Req req){return Resp("Hello World");}); setRoute.add(ASSERT("Route Method", route2.method, "POST", EQUAL)); setRoute.add(ASSERT("Route Path", route2.path, "", EQUAL)); setRoute.add(ASSERT("Match Type", route2.is_regex, true, EQUAL)); unitTest.add(setRoute); // Safaia Framework Unit Test auto setSafaia = CaseSet("Safaia Framework Unit Test"); auto server = Server(); unitTest.add(setSafaia); return unitTest.run(); }<|endoftext|>
<commit_before>/* kopeteavatarmanager.cpp - Global avatar manager Copyright (c) 2007 by Michaël Larouche <larouche@kde.org> Kopete (c) 2002-2007 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * ************************************************************************* */ #include "kopeteavatarmanager.h" // Qt includes #include <QtCore/QLatin1String> #include <QtCore/QBuffer> #include <QtCore/QCoreApplication> #include <QtCore/QFile> #include <QtCore/QPointer> #include <QtCore/QStringList> #include <QtCore/QDir> #include <QtGui/QPainter> // KDE includes #include <kdebug.h> #include <kstandarddirs.h> #include <kconfig.h> #include <kcodecs.h> #include <kurl.h> #include <kio/job.h> #include <kio/netaccess.h> #include <klocale.h> // Kopete includes #include <kopetecontact.h> #include <kopeteaccount.h> namespace Kopete { //BEGIN AvatarManager AvatarManager *AvatarManager::s_self = 0; AvatarManager *AvatarManager::self() { if( !s_self ) { s_self = new AvatarManager; } return s_self; } class AvatarManager::Private { public: KUrl baseDir; /** * Create directory if needed * @param directory URL of the directory to create */ void createDirectory(const KUrl &directory); /** * Scale the given image to 96x96. * @param source Original image */ QImage scaleImage(const QImage &source); }; static const QString UserDir("User"); static const QString ContactDir("Contacts"); static const QString AvatarConfig("avatarconfig.rc"); AvatarManager::AvatarManager(QObject *parent) : QObject(parent), d(new Private) { // Locate avatar data dir on disk d->baseDir = KUrl( KStandardDirs::locateLocal("appdata", QLatin1String("avatars") ) ); // Create directory on disk, if necessary d->createDirectory( d->baseDir ); } AvatarManager::~AvatarManager() { delete d; } Kopete::AvatarManager::AvatarEntry AvatarManager::add(Kopete::AvatarManager::AvatarEntry newEntry) { Q_ASSERT(!newEntry.name.isEmpty()); KUrl avatarUrl(d->baseDir); // First find where to save the file switch(newEntry.category) { case AvatarManager::User: avatarUrl.addPath( UserDir ); d->createDirectory( avatarUrl ); break; case AvatarManager::Contact: avatarUrl.addPath( ContactDir ); d->createDirectory( avatarUrl ); // Use the account id for sub directory if( newEntry.contact && newEntry.contact->account() ) { QString accountName = newEntry.contact->account()->accountId(); avatarUrl.addPath( accountName ); d->createDirectory( avatarUrl ); } break; default: break; } kDebug(14010) << "Base directory: " << avatarUrl.path(); // Second, open the avatar configuration in current directory. KUrl configUrl = avatarUrl; configUrl.addPath( AvatarConfig ); QImage avatar; if( !newEntry.path.isEmpty() && newEntry.image.isNull() ) { avatar = QImage(newEntry.path); } else { avatar = newEntry.image; } // Scale avatar avatar = d->scaleImage(avatar); QString avatarFilename; // for the contact avatar, save it with the contactId + .png if (newEntry.category == AvatarManager::Contact && newEntry.contact) { avatarFilename = newEntry.contact->contactId() + ".png"; } else { // Find MD5 hash for filename // MD5 always contain ASCII caracteres so it is more save for a filename. // Name can use UTF-8 characters. QByteArray tempArray; QBuffer tempBuffer(&tempArray); tempBuffer.open( QIODevice::WriteOnly ); avatar.save(&tempBuffer, "PNG"); KMD5 context(tempArray); avatarFilename = context.hexDigest() + QLatin1String(".png"); } // Save image on disk kDebug(14010) << "Saving " << avatarFilename << " on disk."; avatarUrl.addPath( avatarFilename ); if( !avatar.save( avatarUrl.path(), "PNG") ) { kDebug(14010) << "Saving of " << avatarUrl.path() << " failed !"; return AvatarEntry(); } else { // Save metadata of image KConfigGroup avatarConfig(KSharedConfig::openConfig( configUrl.path(), KConfig::SimpleConfig), newEntry.name ); avatarConfig.writeEntry( "Filename", avatarFilename ); avatarConfig.writeEntry( "Category", int(newEntry.category) ); avatarConfig.sync(); // Add final path to the new entry for avatarAdded signal newEntry.path = avatarUrl.path(); emit avatarAdded(newEntry); } return newEntry; } bool AvatarManager::remove(Kopete::AvatarManager::AvatarEntry entryToRemove) { // We need name and path to remove an avatar from the storage. if( entryToRemove.name.isEmpty() && entryToRemove.path.isEmpty() ) return false; // We don't allow removing avatars from Contact category if( entryToRemove.category & Kopete::AvatarManager::Contact ) return false; // Delete the image file first, file delete is more likely to fail than config group remove. if( KIO::NetAccess::del(KUrl(entryToRemove.path),0) ) { kDebug(14010) << "Removing avatar from config."; KUrl configUrl(d->baseDir); configUrl.addPath( UserDir ); configUrl.addPath( AvatarConfig ); KConfigGroup avatarConfig ( KSharedConfig::openConfig( configUrl.path(), KConfig::SimpleConfig ), entryToRemove.name ); avatarConfig.deleteGroup(); avatarConfig.sync(); emit avatarRemoved(entryToRemove); return true; } return false; } void AvatarManager::Private::createDirectory(const KUrl &directory) { if( !QFile::exists(directory.path()) ) { kDebug(14010) << "Creating directory: " << directory.path(); if( !KIO::NetAccess::mkdir(directory,0) ) { kDebug(14010) << "Directory " << directory.path() <<" creating failed."; } } } QImage AvatarManager::Private::scaleImage(const QImage &source) { //make an empty image and fill with transparent color QImage result(96, 96, QImage::Format_ARGB32); result.fill(0); QPainter paint(&result); float x = 0, y = 0; // scale and center the image if( source.width() > 96 || source.height() > 96 ) { QImage scaled = source.scaled( 96, 96, Qt::KeepAspectRatio, Qt::SmoothTransformation ); x = (96 - scaled.width()) / 2.0; y = (96 - scaled.height()) / 2.0; paint.translate(x, y); paint.drawImage(QPoint(0, 0), scaled); } else { x = (96 - source.width()) / 2.0; y = (96 - source.height()) / 2.0; paint.translate(x, y); paint.drawImage(QPoint(0, 0), source); } return result; } //END AvatarManager //BEGIN AvatarQueryJob class AvatarQueryJob::Private { public: Private(AvatarQueryJob *parent) : queryJob(parent), category(AvatarManager::All) {} QPointer<AvatarQueryJob> queryJob; AvatarManager::AvatarCategory category; QList<AvatarManager::AvatarEntry> avatarList; KUrl baseDir; void listAvatarDirectory(const QString &path); }; AvatarQueryJob::AvatarQueryJob(QObject *parent) : KJob(parent), d(new Private(this)) { } AvatarQueryJob::~AvatarQueryJob() { delete d; } void AvatarQueryJob::setQueryFilter(Kopete::AvatarManager::AvatarCategory category) { d->category = category; } void AvatarQueryJob::start() { d->baseDir = KUrl( KStandardDirs::locateLocal("appdata", QLatin1String("avatars") ) ); if( d->category & Kopete::AvatarManager::User ) { d->listAvatarDirectory( UserDir ); } if( d->category & Kopete::AvatarManager::Contact ) { KUrl contactUrl(d->baseDir); contactUrl.addPath( ContactDir ); QDir contactDir(contactUrl.path()); QStringList subdirsList = contactDir.entryList( QDir::AllDirs | QDir::NoDotAndDotDot ); QString subdir; foreach(subdir, subdirsList) { d->listAvatarDirectory( ContactDir + QDir::separator() + subdir ); } } // Finish the job emitResult(); } QList<Kopete::AvatarManager::AvatarEntry> AvatarQueryJob::avatarList() const { return d->avatarList; } void AvatarQueryJob::Private::listAvatarDirectory(const QString &relativeDirectory) { KUrl avatarDirectory = baseDir; avatarDirectory.addPath(relativeDirectory); kDebug(14010) << "Listing avatars in " << avatarDirectory.path(); // Look for Avatar configuration KUrl avatarConfigUrl = avatarDirectory; avatarConfigUrl.addPath( AvatarConfig ); if( QFile::exists(avatarConfigUrl.path()) ) { KConfig *avatarConfig = new KConfig( avatarConfigUrl.path(), KConfig::SimpleConfig); // Each avatar entry in configuration is a group QStringList groupEntryList = avatarConfig->groupList(); QString groupEntry; foreach(groupEntry, groupEntryList) { KConfigGroup cg(avatarConfig, groupEntry); Kopete::AvatarManager::AvatarEntry listedEntry; listedEntry.name = groupEntry; listedEntry.category = static_cast<Kopete::AvatarManager::AvatarCategory>( cg.readEntry("Category", 0) ); QString filename = cg.readEntry( "Filename", QString() ); KUrl avatarPath(avatarDirectory); avatarPath.addPath( filename ); listedEntry.path = avatarPath.path(); avatarList << listedEntry; } } } //END AvatarQueryJob } #include "kopeteavatarmanager.moc" <commit_msg>Fix mem leak<commit_after>/* kopeteavatarmanager.cpp - Global avatar manager Copyright (c) 2007 by Michaël Larouche <larouche@kde.org> Kopete (c) 2002-2007 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * ************************************************************************* */ #include "kopeteavatarmanager.h" // Qt includes #include <QtCore/QLatin1String> #include <QtCore/QBuffer> #include <QtCore/QCoreApplication> #include <QtCore/QFile> #include <QtCore/QPointer> #include <QtCore/QStringList> #include <QtCore/QDir> #include <QtGui/QPainter> // KDE includes #include <kdebug.h> #include <kstandarddirs.h> #include <kconfig.h> #include <kcodecs.h> #include <kurl.h> #include <kio/job.h> #include <kio/netaccess.h> #include <klocale.h> // Kopete includes #include <kopetecontact.h> #include <kopeteaccount.h> namespace Kopete { //BEGIN AvatarManager AvatarManager *AvatarManager::s_self = 0; AvatarManager *AvatarManager::self() { if( !s_self ) { s_self = new AvatarManager; } return s_self; } class AvatarManager::Private { public: KUrl baseDir; /** * Create directory if needed * @param directory URL of the directory to create */ void createDirectory(const KUrl &directory); /** * Scale the given image to 96x96. * @param source Original image */ QImage scaleImage(const QImage &source); }; static const QString UserDir("User"); static const QString ContactDir("Contacts"); static const QString AvatarConfig("avatarconfig.rc"); AvatarManager::AvatarManager(QObject *parent) : QObject(parent), d(new Private) { // Locate avatar data dir on disk d->baseDir = KUrl( KStandardDirs::locateLocal("appdata", QLatin1String("avatars") ) ); // Create directory on disk, if necessary d->createDirectory( d->baseDir ); } AvatarManager::~AvatarManager() { delete d; } Kopete::AvatarManager::AvatarEntry AvatarManager::add(Kopete::AvatarManager::AvatarEntry newEntry) { Q_ASSERT(!newEntry.name.isEmpty()); KUrl avatarUrl(d->baseDir); // First find where to save the file switch(newEntry.category) { case AvatarManager::User: avatarUrl.addPath( UserDir ); d->createDirectory( avatarUrl ); break; case AvatarManager::Contact: avatarUrl.addPath( ContactDir ); d->createDirectory( avatarUrl ); // Use the account id for sub directory if( newEntry.contact && newEntry.contact->account() ) { QString accountName = newEntry.contact->account()->accountId(); avatarUrl.addPath( accountName ); d->createDirectory( avatarUrl ); } break; default: break; } kDebug(14010) << "Base directory: " << avatarUrl.path(); // Second, open the avatar configuration in current directory. KUrl configUrl = avatarUrl; configUrl.addPath( AvatarConfig ); QImage avatar; if( !newEntry.path.isEmpty() && newEntry.image.isNull() ) { avatar = QImage(newEntry.path); } else { avatar = newEntry.image; } // Scale avatar avatar = d->scaleImage(avatar); QString avatarFilename; // for the contact avatar, save it with the contactId + .png if (newEntry.category == AvatarManager::Contact && newEntry.contact) { avatarFilename = newEntry.contact->contactId() + ".png"; } else { // Find MD5 hash for filename // MD5 always contain ASCII caracteres so it is more save for a filename. // Name can use UTF-8 characters. QByteArray tempArray; QBuffer tempBuffer(&tempArray); tempBuffer.open( QIODevice::WriteOnly ); avatar.save(&tempBuffer, "PNG"); KMD5 context(tempArray); avatarFilename = context.hexDigest() + QLatin1String(".png"); } // Save image on disk kDebug(14010) << "Saving " << avatarFilename << " on disk."; avatarUrl.addPath( avatarFilename ); if( !avatar.save( avatarUrl.path(), "PNG") ) { kDebug(14010) << "Saving of " << avatarUrl.path() << " failed !"; return AvatarEntry(); } else { // Save metadata of image KConfigGroup avatarConfig(KSharedConfig::openConfig( configUrl.path(), KConfig::SimpleConfig), newEntry.name ); avatarConfig.writeEntry( "Filename", avatarFilename ); avatarConfig.writeEntry( "Category", int(newEntry.category) ); avatarConfig.sync(); // Add final path to the new entry for avatarAdded signal newEntry.path = avatarUrl.path(); emit avatarAdded(newEntry); } return newEntry; } bool AvatarManager::remove(Kopete::AvatarManager::AvatarEntry entryToRemove) { // We need name and path to remove an avatar from the storage. if( entryToRemove.name.isEmpty() && entryToRemove.path.isEmpty() ) return false; // We don't allow removing avatars from Contact category if( entryToRemove.category & Kopete::AvatarManager::Contact ) return false; // Delete the image file first, file delete is more likely to fail than config group remove. if( KIO::NetAccess::del(KUrl(entryToRemove.path),0) ) { kDebug(14010) << "Removing avatar from config."; KUrl configUrl(d->baseDir); configUrl.addPath( UserDir ); configUrl.addPath( AvatarConfig ); KConfigGroup avatarConfig ( KSharedConfig::openConfig( configUrl.path(), KConfig::SimpleConfig ), entryToRemove.name ); avatarConfig.deleteGroup(); avatarConfig.sync(); emit avatarRemoved(entryToRemove); return true; } return false; } void AvatarManager::Private::createDirectory(const KUrl &directory) { if( !QFile::exists(directory.path()) ) { kDebug(14010) << "Creating directory: " << directory.path(); if( !KIO::NetAccess::mkdir(directory,0) ) { kDebug(14010) << "Directory " << directory.path() <<" creating failed."; } } } QImage AvatarManager::Private::scaleImage(const QImage &source) { //make an empty image and fill with transparent color QImage result(96, 96, QImage::Format_ARGB32); result.fill(0); QPainter paint(&result); float x = 0, y = 0; // scale and center the image if( source.width() > 96 || source.height() > 96 ) { QImage scaled = source.scaled( 96, 96, Qt::KeepAspectRatio, Qt::SmoothTransformation ); x = (96 - scaled.width()) / 2.0; y = (96 - scaled.height()) / 2.0; paint.translate(x, y); paint.drawImage(QPoint(0, 0), scaled); } else { x = (96 - source.width()) / 2.0; y = (96 - source.height()) / 2.0; paint.translate(x, y); paint.drawImage(QPoint(0, 0), source); } return result; } //END AvatarManager //BEGIN AvatarQueryJob class AvatarQueryJob::Private { public: Private(AvatarQueryJob *parent) : queryJob(parent), category(AvatarManager::All) {} QPointer<AvatarQueryJob> queryJob; AvatarManager::AvatarCategory category; QList<AvatarManager::AvatarEntry> avatarList; KUrl baseDir; void listAvatarDirectory(const QString &path); }; AvatarQueryJob::AvatarQueryJob(QObject *parent) : KJob(parent), d(new Private(this)) { } AvatarQueryJob::~AvatarQueryJob() { delete d; } void AvatarQueryJob::setQueryFilter(Kopete::AvatarManager::AvatarCategory category) { d->category = category; } void AvatarQueryJob::start() { d->baseDir = KUrl( KStandardDirs::locateLocal("appdata", QLatin1String("avatars") ) ); if( d->category & Kopete::AvatarManager::User ) { d->listAvatarDirectory( UserDir ); } if( d->category & Kopete::AvatarManager::Contact ) { KUrl contactUrl(d->baseDir); contactUrl.addPath( ContactDir ); QDir contactDir(contactUrl.path()); QStringList subdirsList = contactDir.entryList( QDir::AllDirs | QDir::NoDotAndDotDot ); QString subdir; foreach(subdir, subdirsList) { d->listAvatarDirectory( ContactDir + QDir::separator() + subdir ); } } // Finish the job emitResult(); } QList<Kopete::AvatarManager::AvatarEntry> AvatarQueryJob::avatarList() const { return d->avatarList; } void AvatarQueryJob::Private::listAvatarDirectory(const QString &relativeDirectory) { KUrl avatarDirectory = baseDir; avatarDirectory.addPath(relativeDirectory); kDebug(14010) << "Listing avatars in " << avatarDirectory.path(); // Look for Avatar configuration KUrl avatarConfigUrl = avatarDirectory; avatarConfigUrl.addPath( AvatarConfig ); if( QFile::exists(avatarConfigUrl.path()) ) { KConfig *avatarConfig = new KConfig( avatarConfigUrl.path(), KConfig::SimpleConfig); // Each avatar entry in configuration is a group QStringList groupEntryList = avatarConfig->groupList(); QString groupEntry; foreach(groupEntry, groupEntryList) { KConfigGroup cg(avatarConfig, groupEntry); Kopete::AvatarManager::AvatarEntry listedEntry; listedEntry.name = groupEntry; listedEntry.category = static_cast<Kopete::AvatarManager::AvatarCategory>( cg.readEntry("Category", 0) ); QString filename = cg.readEntry( "Filename", QString() ); KUrl avatarPath(avatarDirectory); avatarPath.addPath( filename ); listedEntry.path = avatarPath.path(); avatarList << listedEntry; } delete avatarConfig; } } //END AvatarQueryJob } #include "kopeteavatarmanager.moc" <|endoftext|>
<commit_before>// Copyright 2019 Open Source Robotics Foundation, Inc. // Copyright 2016-2018 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <limits.h> #include <string> #include "fastrtps/config.h" #include "fastrtps/Domain.h" #include "fastrtps/attributes/ParticipantAttributes.h" #include "fastrtps/attributes/PublisherAttributes.h" #include "fastrtps/attributes/SubscriberAttributes.h" #include "fastrtps/participant/Participant.h" #include "fastrtps/publisher/Publisher.h" #include "fastrtps/publisher/PublisherListener.h" #include "fastrtps/rtps/RTPSDomain.h" #include "fastrtps/rtps/common/Locator.h" #include "fastrtps/rtps/builtin/discovery/endpoint/EDPSimple.h" #include "fastrtps/rtps/reader/ReaderListener.h" #include "fastrtps/rtps/reader/RTPSReader.h" #include "fastrtps/rtps/reader/StatefulReader.h" #include "fastrtps/subscriber/Subscriber.h" #include "fastrtps/subscriber/SubscriberListener.h" #include "fastrtps/subscriber/SampleInfo.h" #include "rcutils/filesystem.h" #include "rcutils/get_env.h" #include "rmw/allocators.h" #include "rmw_fastrtps_shared_cpp/custom_participant_info.hpp" #include "rmw_fastrtps_shared_cpp/participant.hpp" #include "rmw_fastrtps_shared_cpp/rmw_common.hpp" using Domain = eprosima::fastrtps::Domain; using IPLocator = eprosima::fastrtps::rtps::IPLocator; using Locator_t = eprosima::fastrtps::rtps::Locator_t; using Participant = eprosima::fastrtps::Participant; using ParticipantAttributes = eprosima::fastrtps::ParticipantAttributes; using StatefulReader = eprosima::fastrtps::rtps::StatefulReader; #if HAVE_SECURITY static bool get_security_file_paths( std::array<std::string, 6> & security_files_paths, const char * secure_root) { // here assume only 6 files for security const char * file_names[6] = { "identity_ca.cert.pem", "cert.pem", "key.pem", "permissions_ca.cert.pem", "governance.p7s", "permissions.p7s" }; size_t num_files = sizeof(file_names) / sizeof(char *); std::string file_prefix("file://"); for (size_t i = 0; i < num_files; i++) { rcutils_allocator_t allocator = rcutils_get_default_allocator(); char * file_path = rcutils_join_path(secure_root, file_names[i], allocator); if (!file_path) { return false; } if (rcutils_is_readable(file_path)) { security_files_paths[i] = file_prefix + std::string(file_path); } else { allocator.deallocate(file_path, allocator.state); return false; } allocator.deallocate(file_path, allocator.state); } return true; } #endif static CustomParticipantInfo * __create_participant( const char * identifier, ParticipantAttributes participantAttrs, bool leave_middleware_default_qos, rmw_dds_common::Context * common_context) { // Declare everything before beginning to create things. ::ParticipantListener * listener = nullptr; Participant * participant = nullptr; CustomParticipantInfo * participant_info = nullptr; try { listener = new ::ParticipantListener( identifier, common_context); } catch (std::bad_alloc &) { RMW_SET_ERROR_MSG("failed to allocate participant listener"); goto fail; } participant = Domain::createParticipant(participantAttrs, listener); if (!participant) { RMW_SET_ERROR_MSG("create_node() could not create participant"); return nullptr; } try { participant_info = new CustomParticipantInfo(); } catch (std::bad_alloc &) { RMW_SET_ERROR_MSG("failed to allocate node impl struct"); goto fail; } participant_info->leave_middleware_default_qos = leave_middleware_default_qos; participant_info->participant = participant; participant_info->listener = listener; return participant_info; fail: rmw_free(listener); if (participant) { Domain::removeParticipant(participant); } return nullptr; } CustomParticipantInfo * rmw_fastrtps_shared_cpp::create_participant( const char * identifier, size_t domain_id, const rmw_security_options_t * security_options, bool localhost_only, const char * enclave, rmw_dds_common::Context * common_context) { if (!security_options) { RMW_SET_ERROR_MSG("security_options is null"); return nullptr; } ParticipantAttributes participantAttrs; // Load default XML profile. Domain::getDefaultParticipantAttributes(participantAttrs); participantAttrs.rtps.builtin.domainId = static_cast<uint32_t>(domain_id); if (localhost_only) { Locator_t local_network_interface_locator; static const std::string local_ip_name("127.0.0.1"); local_network_interface_locator.kind = 1; local_network_interface_locator.port = 0; IPLocator::setIPv4(local_network_interface_locator, local_ip_name); participantAttrs.rtps.builtin.metatrafficUnicastLocatorList.push_back( local_network_interface_locator); participantAttrs.rtps.builtin.initialPeersList.push_back(local_network_interface_locator); } participantAttrs.rtps.builtin.domainId = static_cast<uint32_t>(domain_id); size_t length = snprintf(nullptr, 0, "enclave=%s;", enclave) + 1; participantAttrs.rtps.userData.resize(length); int written = snprintf( reinterpret_cast<char *>(participantAttrs.rtps.userData.data()), length, "enclave=%s;", enclave); if (written < 0 || written > static_cast<int>(length) - 1) { RMW_SET_ERROR_MSG("failed to populate user_data buffer"); return nullptr; } participantAttrs.rtps.setName(enclave); bool leave_middleware_default_qos = false; const char * env_value; const char * error_str; error_str = rcutils_get_env("RMW_FASTRTPS_USE_QOS_FROM_XML", &env_value); if (error_str != NULL) { RCUTILS_LOG_DEBUG_NAMED("rmw_fastrtps_shared_cpp", "Error getting env var: %s\n", error_str); return nullptr; } if (env_value != nullptr) { leave_middleware_default_qos = strcmp(env_value, "1") == 0; } // allow reallocation to support discovery messages bigger than 5000 bytes if (!leave_middleware_default_qos) { participantAttrs.rtps.builtin.readerHistoryMemoryPolicy = eprosima::fastrtps::rtps::PREALLOCATED_WITH_REALLOC_MEMORY_MODE; participantAttrs.rtps.builtin.writerHistoryMemoryPolicy = eprosima::fastrtps::rtps::PREALLOCATED_WITH_REALLOC_MEMORY_MODE; } if (security_options->security_root_path) { // if security_root_path provided, try to find the key and certificate files #if HAVE_SECURITY std::array<std::string, 6> security_files_paths; if (get_security_file_paths(security_files_paths, security_options->security_root_path)) { eprosima::fastrtps::rtps::PropertyPolicy property_policy; using Property = eprosima::fastrtps::rtps::Property; property_policy.properties().emplace_back( Property("dds.sec.auth.plugin", "builtin.PKI-DH")); property_policy.properties().emplace_back( Property( "dds.sec.auth.builtin.PKI-DH.identity_ca", security_files_paths[0])); property_policy.properties().emplace_back( Property( "dds.sec.auth.builtin.PKI-DH.identity_certificate", security_files_paths[1])); property_policy.properties().emplace_back( Property( "dds.sec.auth.builtin.PKI-DH.private_key", security_files_paths[2])); property_policy.properties().emplace_back( Property("dds.sec.crypto.plugin", "builtin.AES-GCM-GMAC")); property_policy.properties().emplace_back( Property( "dds.sec.access.plugin", "builtin.Access-Permissions")); property_policy.properties().emplace_back( Property( "dds.sec.access.builtin.Access-Permissions.permissions_ca", security_files_paths[3])); property_policy.properties().emplace_back( Property( "dds.sec.access.builtin.Access-Permissions.governance", security_files_paths[4])); property_policy.properties().emplace_back( Property( "dds.sec.access.builtin.Access-Permissions.permissions", security_files_paths[5])); participantAttrs.rtps.properties = property_policy; } else if (security_options->enforce_security) { RMW_SET_ERROR_MSG("couldn't find all security files!"); return nullptr; } #else RMW_SET_ERROR_MSG( "This Fast-RTPS version doesn't have the security libraries\n" "Please compile Fast-RTPS using the -DSECURITY=ON CMake option"); return nullptr; #endif } return __create_participant( identifier, participantAttrs, leave_middleware_default_qos, common_context); } rmw_ret_t rmw_fastrtps_shared_cpp::destroy_participant(CustomParticipantInfo * participant_info) { rmw_ret_t result_ret = RMW_RET_OK; if (!participant_info) { RMW_SET_ERROR_MSG("participant_info is null"); return RMW_RET_ERROR; } Domain::removeParticipant(participant_info->participant); delete participant_info->listener; participant_info->listener = nullptr; delete participant_info; return result_ret; } <commit_msg>Support for API break on Fast RTPS 2.0 (#370)<commit_after>// Copyright 2019 Open Source Robotics Foundation, Inc. // Copyright 2016-2018 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <limits.h> #include <string> #include "fastrtps/config.h" #include "fastrtps/Domain.h" #include "fastrtps/attributes/ParticipantAttributes.h" #include "fastrtps/attributes/PublisherAttributes.h" #include "fastrtps/attributes/SubscriberAttributes.h" #include "fastrtps/participant/Participant.h" #include "fastrtps/publisher/Publisher.h" #include "fastrtps/publisher/PublisherListener.h" #include "fastrtps/rtps/RTPSDomain.h" #include "fastrtps/rtps/common/Locator.h" #include "fastrtps/rtps/builtin/discovery/endpoint/EDPSimple.h" #include "fastrtps/rtps/reader/ReaderListener.h" #include "fastrtps/rtps/reader/RTPSReader.h" #include "fastrtps/rtps/reader/StatefulReader.h" #include "fastrtps/subscriber/Subscriber.h" #include "fastrtps/subscriber/SubscriberListener.h" #include "fastrtps/subscriber/SampleInfo.h" #include "rcutils/filesystem.h" #include "rcutils/get_env.h" #include "rmw/allocators.h" #include "rmw_fastrtps_shared_cpp/custom_participant_info.hpp" #include "rmw_fastrtps_shared_cpp/participant.hpp" #include "rmw_fastrtps_shared_cpp/rmw_common.hpp" using Domain = eprosima::fastrtps::Domain; using IPLocator = eprosima::fastrtps::rtps::IPLocator; using Locator_t = eprosima::fastrtps::rtps::Locator_t; using Participant = eprosima::fastrtps::Participant; using ParticipantAttributes = eprosima::fastrtps::ParticipantAttributes; using StatefulReader = eprosima::fastrtps::rtps::StatefulReader; #if HAVE_SECURITY static bool get_security_file_paths( std::array<std::string, 6> & security_files_paths, const char * secure_root) { // here assume only 6 files for security const char * file_names[6] = { "identity_ca.cert.pem", "cert.pem", "key.pem", "permissions_ca.cert.pem", "governance.p7s", "permissions.p7s" }; size_t num_files = sizeof(file_names) / sizeof(char *); std::string file_prefix("file://"); for (size_t i = 0; i < num_files; i++) { rcutils_allocator_t allocator = rcutils_get_default_allocator(); char * file_path = rcutils_join_path(secure_root, file_names[i], allocator); if (!file_path) { return false; } if (rcutils_is_readable(file_path)) { security_files_paths[i] = file_prefix + std::string(file_path); } else { allocator.deallocate(file_path, allocator.state); return false; } allocator.deallocate(file_path, allocator.state); } return true; } #endif static CustomParticipantInfo * __create_participant( const char * identifier, ParticipantAttributes participantAttrs, bool leave_middleware_default_qos, rmw_dds_common::Context * common_context) { // Declare everything before beginning to create things. ::ParticipantListener * listener = nullptr; Participant * participant = nullptr; CustomParticipantInfo * participant_info = nullptr; try { listener = new ::ParticipantListener( identifier, common_context); } catch (std::bad_alloc &) { RMW_SET_ERROR_MSG("failed to allocate participant listener"); goto fail; } participant = Domain::createParticipant(participantAttrs, listener); if (!participant) { RMW_SET_ERROR_MSG("create_node() could not create participant"); return nullptr; } try { participant_info = new CustomParticipantInfo(); } catch (std::bad_alloc &) { RMW_SET_ERROR_MSG("failed to allocate node impl struct"); goto fail; } participant_info->leave_middleware_default_qos = leave_middleware_default_qos; participant_info->participant = participant; participant_info->listener = listener; return participant_info; fail: rmw_free(listener); if (participant) { Domain::removeParticipant(participant); } return nullptr; } CustomParticipantInfo * rmw_fastrtps_shared_cpp::create_participant( const char * identifier, size_t domain_id, const rmw_security_options_t * security_options, bool localhost_only, const char * enclave, rmw_dds_common::Context * common_context) { if (!security_options) { RMW_SET_ERROR_MSG("security_options is null"); return nullptr; } ParticipantAttributes participantAttrs; // Load default XML profile. Domain::getDefaultParticipantAttributes(participantAttrs); if (localhost_only) { Locator_t local_network_interface_locator; static const std::string local_ip_name("127.0.0.1"); local_network_interface_locator.kind = 1; local_network_interface_locator.port = 0; IPLocator::setIPv4(local_network_interface_locator, local_ip_name); participantAttrs.rtps.builtin.metatrafficUnicastLocatorList.push_back( local_network_interface_locator); participantAttrs.rtps.builtin.initialPeersList.push_back(local_network_interface_locator); } #if FASTRTPS_VERSION_MAJOR < 2 participantAttrs.rtps.builtin.domainId = static_cast<uint32_t>(domain_id); #else participantAttrs.domainId = static_cast<uint32_t>(domain_id); #endif size_t length = snprintf(nullptr, 0, "enclave=%s;", enclave) + 1; participantAttrs.rtps.userData.resize(length); int written = snprintf( reinterpret_cast<char *>(participantAttrs.rtps.userData.data()), length, "enclave=%s;", enclave); if (written < 0 || written > static_cast<int>(length) - 1) { RMW_SET_ERROR_MSG("failed to populate user_data buffer"); return nullptr; } participantAttrs.rtps.setName(enclave); bool leave_middleware_default_qos = false; const char * env_value; const char * error_str; error_str = rcutils_get_env("RMW_FASTRTPS_USE_QOS_FROM_XML", &env_value); if (error_str != NULL) { RCUTILS_LOG_DEBUG_NAMED("rmw_fastrtps_shared_cpp", "Error getting env var: %s\n", error_str); return nullptr; } if (env_value != nullptr) { leave_middleware_default_qos = strcmp(env_value, "1") == 0; } // allow reallocation to support discovery messages bigger than 5000 bytes if (!leave_middleware_default_qos) { participantAttrs.rtps.builtin.readerHistoryMemoryPolicy = eprosima::fastrtps::rtps::PREALLOCATED_WITH_REALLOC_MEMORY_MODE; participantAttrs.rtps.builtin.writerHistoryMemoryPolicy = eprosima::fastrtps::rtps::PREALLOCATED_WITH_REALLOC_MEMORY_MODE; } if (security_options->security_root_path) { // if security_root_path provided, try to find the key and certificate files #if HAVE_SECURITY std::array<std::string, 6> security_files_paths; if (get_security_file_paths(security_files_paths, security_options->security_root_path)) { eprosima::fastrtps::rtps::PropertyPolicy property_policy; using Property = eprosima::fastrtps::rtps::Property; property_policy.properties().emplace_back( Property("dds.sec.auth.plugin", "builtin.PKI-DH")); property_policy.properties().emplace_back( Property( "dds.sec.auth.builtin.PKI-DH.identity_ca", security_files_paths[0])); property_policy.properties().emplace_back( Property( "dds.sec.auth.builtin.PKI-DH.identity_certificate", security_files_paths[1])); property_policy.properties().emplace_back( Property( "dds.sec.auth.builtin.PKI-DH.private_key", security_files_paths[2])); property_policy.properties().emplace_back( Property("dds.sec.crypto.plugin", "builtin.AES-GCM-GMAC")); property_policy.properties().emplace_back( Property( "dds.sec.access.plugin", "builtin.Access-Permissions")); property_policy.properties().emplace_back( Property( "dds.sec.access.builtin.Access-Permissions.permissions_ca", security_files_paths[3])); property_policy.properties().emplace_back( Property( "dds.sec.access.builtin.Access-Permissions.governance", security_files_paths[4])); property_policy.properties().emplace_back( Property( "dds.sec.access.builtin.Access-Permissions.permissions", security_files_paths[5])); participantAttrs.rtps.properties = property_policy; } else if (security_options->enforce_security) { RMW_SET_ERROR_MSG("couldn't find all security files!"); return nullptr; } #else RMW_SET_ERROR_MSG( "This Fast-RTPS version doesn't have the security libraries\n" "Please compile Fast-RTPS using the -DSECURITY=ON CMake option"); return nullptr; #endif } return __create_participant( identifier, participantAttrs, leave_middleware_default_qos, common_context); } rmw_ret_t rmw_fastrtps_shared_cpp::destroy_participant(CustomParticipantInfo * participant_info) { rmw_ret_t result_ret = RMW_RET_OK; if (!participant_info) { RMW_SET_ERROR_MSG("participant_info is null"); return RMW_RET_ERROR; } Domain::removeParticipant(participant_info->participant); delete participant_info->listener; participant_info->listener = nullptr; delete participant_info; return result_ret; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dbexception.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: fs $ $Date: 2001-11-08 12:48:37 $ * * 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 EXPRESS 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 _DBHELPER_DBEXCEPTION_HXX_ #define _DBHELPER_DBEXCEPTION_HXX_ #ifndef _COM_SUN_STAR_SDBC_SQLEXCEPTION_HPP_ #include <com/sun/star/sdbc/SQLException.hpp> #endif //#ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_ //#include <com/sun/star/sdbc/SQLWarning.hpp> //#endif //#ifndef _COM_SUN_STAR_SDB_SQLCONTEXT_HPP_ //#include <com/sun/star/sdb/SQLContext.hpp> //#endif namespace com { namespace sun { namespace star { namespace sdb { class SQLContext; struct SQLErrorEvent; } namespace sdbc { class SQLWarning; } } } } //......................................................................... namespace dbtools { //......................................................................... //============================================================================== //= SQLExceptionInfo - encapsulating the type info of an SQLException-derived class //============================================================================== class SQLExceptionInfo { public: enum TYPE { SQL_EXCEPTION, SQL_WARNING, SQL_CONTEXT, UNDEFINED }; private: ::com::sun::star::uno::Any m_aContent; TYPE m_eType; // redundant (could be derived from m_aContent.getValueType()) public: SQLExceptionInfo(); SQLExceptionInfo(const ::com::sun::star::sdbc::SQLException& _rError); SQLExceptionInfo(const ::com::sun::star::sdbc::SQLWarning& _rError); SQLExceptionInfo(const ::com::sun::star::sdb::SQLContext& _rError); // these ctors don't make much sense anymore ... Smart-UNO had some kind of self-made rtti for exceptions, // so we needed only the first ctor to correctly determine the exception type, but now with UNO3 // you have to catch _all_ kinds of exceptions derived from SQLException and use the appropriate ctor ... SQLExceptionInfo(const SQLExceptionInfo& _rCopySource); SQLExceptionInfo(const ::com::sun::star::sdb::SQLErrorEvent& _rError); // use for events got via XSQLErrorListener::errorOccured SQLExceptionInfo(const ::com::sun::star::uno::Any& _rError); // use with the Reason member of an SQLErrorEvent or with NextElement of an SQLException const SQLExceptionInfo& operator=(const ::com::sun::star::sdbc::SQLException& _rError); const SQLExceptionInfo& operator=(const ::com::sun::star::sdbc::SQLWarning& _rError); const SQLExceptionInfo& operator=(const ::com::sun::star::sdb::SQLContext& _rError); sal_Bool isKindOf(TYPE _eType) const; // not just a simple comparisation ! e.g. getType() == SQL_CONTEXT implies isKindOf(SQL_EXCEPTION) == sal_True ! sal_Bool isValid() const { return m_eType != UNDEFINED; } TYPE getType() const { return m_eType; } operator const ::com::sun::star::sdbc::SQLException* () const; operator const ::com::sun::star::sdbc::SQLWarning* () const; operator const ::com::sun::star::sdb::SQLContext* () const; ::com::sun::star::uno::Any get() const { return m_aContent; } protected: void implDetermineType(); }; //============================================================================== //= SQLExceptionIteratorHelper - iterating through an SQLException chain //============================================================================== class SQLExceptionIteratorHelper { public: // specifying the type of the elements to include enum NODES_INCLUDED { NI_EXCEPTIONS, NI_WARNINGS, NI_CONTEXTINFOS }; // as ContextInfos are derived from Warnings and Warnings from Exceptions this is sufficient ... protected: const ::com::sun::star::sdbc::SQLException* m_pCurrent; SQLExceptionInfo::TYPE m_eCurrentType; NODES_INCLUDED m_eMask; public: SQLExceptionIteratorHelper(const ::com::sun::star::sdbc::SQLException* _pStart, NODES_INCLUDED _eMask = NI_EXCEPTIONS); SQLExceptionIteratorHelper(const ::com::sun::star::sdbc::SQLWarning* _pStart, NODES_INCLUDED _eMask = NI_EXCEPTIONS); SQLExceptionIteratorHelper(const ::com::sun::star::sdb::SQLContext* _pStart, NODES_INCLUDED _eMask = NI_EXCEPTIONS); // same note as above for the SQLExceptionInfo ctors SQLExceptionIteratorHelper(const SQLExceptionInfo& _rStart, NODES_INCLUDED _eMask = NI_EXCEPTIONS); sal_Bool hasMoreElements() const { return (m_pCurrent != NULL); } const ::com::sun::star::sdbc::SQLException* next(); void next(SQLExceptionInfo& _rOutInfo); }; //================================================================================== //= StandardExceptions //================================================================================== //---------------------------------------------------------------------------------- void throwFunctionNotSupportedException( const ::rtl::OUString& _rMsg, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _Context, const ::com::sun::star::uno::Any& _Next ) throw ( ::com::sun::star::sdbc::SQLException ); //---------------------------------------------------------------------------------- /** throw a function sequence exception */ void throwFunctionSequenceException(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _Context, const ::com::sun::star::uno::Any& _Next = ::com::sun::star::uno::Any()) throw ( ::com::sun::star::sdbc::SQLException ); //---------------------------------------------------------------------------------- /** throw a invalid index sqlexception */ void throwInvalidIndexException(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _Context, const ::com::sun::star::uno::Any& _Next = ::com::sun::star::uno::Any()) throw ( ::com::sun::star::sdbc::SQLException ); //---------------------------------------------------------------------------------- /** throw a generic SQLException, i.e. one with an SQLState of S1000, an ErrorCode of 0 and no NextException */ void throwGenericSQLException(const ::rtl::OUString& _rMsg, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxSource) throw (::com::sun::star::sdbc::SQLException); //---------------------------------------------------------------------------------- /** throw a generic SQLException, i.e. one with an SQLState of S1000, an ErrorCode of 0 and no NextException */ void throwGenericSQLException( const ::rtl::OUString& _rMsg, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxSource, const ::com::sun::star::uno::Any& _rNextException ) throw (::com::sun::star::sdbc::SQLException); //......................................................................... } // namespace dbtools //......................................................................... #endif _DBHELPER_DBEXCEPTION_HXX_ /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.6 2001/06/26 07:53:17 fs * throwGenericSQLException version with additional NextException parameter * * Revision 1.5 2001/05/14 11:40:39 oj * #86528# lower size need * * Revision 1.4 2001/04/19 07:04:21 fs * +throwFunctionSequenceException * * Revision 1.3 2001/03/01 17:01:18 fs * operator= for SQLExceptionInfo, new ctor for SQLExceptionIteratorHelper, new next method * * Revision 1.2 2000/10/24 15:19:40 oj * make strings unique for lib's * * Revision 1.1 2000/10/05 08:56:37 fs * moved the files from unotools to here * * * Revision 1.0 29.09.00 08:31:15 fs ************************************************************************/ <commit_msg>#93274# defaulted the third param of throwFunctionNotSupportedException<commit_after>/************************************************************************* * * $RCSfile: dbexception.hxx,v $ * * $Revision: 1.8 $ * * last change: $Author: fs $ $Date: 2001-11-08 15:26:11 $ * * 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 EXPRESS 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 _DBHELPER_DBEXCEPTION_HXX_ #define _DBHELPER_DBEXCEPTION_HXX_ #ifndef _COM_SUN_STAR_SDBC_SQLEXCEPTION_HPP_ #include <com/sun/star/sdbc/SQLException.hpp> #endif //#ifndef _COM_SUN_STAR_SDBC_SQLWARNING_HPP_ //#include <com/sun/star/sdbc/SQLWarning.hpp> //#endif //#ifndef _COM_SUN_STAR_SDB_SQLCONTEXT_HPP_ //#include <com/sun/star/sdb/SQLContext.hpp> //#endif namespace com { namespace sun { namespace star { namespace sdb { class SQLContext; struct SQLErrorEvent; } namespace sdbc { class SQLWarning; } } } } //......................................................................... namespace dbtools { //......................................................................... //============================================================================== //= SQLExceptionInfo - encapsulating the type info of an SQLException-derived class //============================================================================== class SQLExceptionInfo { public: enum TYPE { SQL_EXCEPTION, SQL_WARNING, SQL_CONTEXT, UNDEFINED }; private: ::com::sun::star::uno::Any m_aContent; TYPE m_eType; // redundant (could be derived from m_aContent.getValueType()) public: SQLExceptionInfo(); SQLExceptionInfo(const ::com::sun::star::sdbc::SQLException& _rError); SQLExceptionInfo(const ::com::sun::star::sdbc::SQLWarning& _rError); SQLExceptionInfo(const ::com::sun::star::sdb::SQLContext& _rError); // these ctors don't make much sense anymore ... Smart-UNO had some kind of self-made rtti for exceptions, // so we needed only the first ctor to correctly determine the exception type, but now with UNO3 // you have to catch _all_ kinds of exceptions derived from SQLException and use the appropriate ctor ... SQLExceptionInfo(const SQLExceptionInfo& _rCopySource); SQLExceptionInfo(const ::com::sun::star::sdb::SQLErrorEvent& _rError); // use for events got via XSQLErrorListener::errorOccured SQLExceptionInfo(const ::com::sun::star::uno::Any& _rError); // use with the Reason member of an SQLErrorEvent or with NextElement of an SQLException const SQLExceptionInfo& operator=(const ::com::sun::star::sdbc::SQLException& _rError); const SQLExceptionInfo& operator=(const ::com::sun::star::sdbc::SQLWarning& _rError); const SQLExceptionInfo& operator=(const ::com::sun::star::sdb::SQLContext& _rError); sal_Bool isKindOf(TYPE _eType) const; // not just a simple comparisation ! e.g. getType() == SQL_CONTEXT implies isKindOf(SQL_EXCEPTION) == sal_True ! sal_Bool isValid() const { return m_eType != UNDEFINED; } TYPE getType() const { return m_eType; } operator const ::com::sun::star::sdbc::SQLException* () const; operator const ::com::sun::star::sdbc::SQLWarning* () const; operator const ::com::sun::star::sdb::SQLContext* () const; ::com::sun::star::uno::Any get() const { return m_aContent; } protected: void implDetermineType(); }; //============================================================================== //= SQLExceptionIteratorHelper - iterating through an SQLException chain //============================================================================== class SQLExceptionIteratorHelper { public: // specifying the type of the elements to include enum NODES_INCLUDED { NI_EXCEPTIONS, NI_WARNINGS, NI_CONTEXTINFOS }; // as ContextInfos are derived from Warnings and Warnings from Exceptions this is sufficient ... protected: const ::com::sun::star::sdbc::SQLException* m_pCurrent; SQLExceptionInfo::TYPE m_eCurrentType; NODES_INCLUDED m_eMask; public: SQLExceptionIteratorHelper(const ::com::sun::star::sdbc::SQLException* _pStart, NODES_INCLUDED _eMask = NI_EXCEPTIONS); SQLExceptionIteratorHelper(const ::com::sun::star::sdbc::SQLWarning* _pStart, NODES_INCLUDED _eMask = NI_EXCEPTIONS); SQLExceptionIteratorHelper(const ::com::sun::star::sdb::SQLContext* _pStart, NODES_INCLUDED _eMask = NI_EXCEPTIONS); // same note as above for the SQLExceptionInfo ctors SQLExceptionIteratorHelper(const SQLExceptionInfo& _rStart, NODES_INCLUDED _eMask = NI_EXCEPTIONS); sal_Bool hasMoreElements() const { return (m_pCurrent != NULL); } const ::com::sun::star::sdbc::SQLException* next(); void next(SQLExceptionInfo& _rOutInfo); }; //================================================================================== //= StandardExceptions //================================================================================== //---------------------------------------------------------------------------------- void throwFunctionNotSupportedException( const ::rtl::OUString& _rMsg, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _Context, const ::com::sun::star::uno::Any& _Next = ::com::sun::star::uno::Any() ) throw ( ::com::sun::star::sdbc::SQLException ); //---------------------------------------------------------------------------------- /** throw a function sequence exception */ void throwFunctionSequenceException(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _Context, const ::com::sun::star::uno::Any& _Next = ::com::sun::star::uno::Any()) throw ( ::com::sun::star::sdbc::SQLException ); //---------------------------------------------------------------------------------- /** throw a invalid index sqlexception */ void throwInvalidIndexException(const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _Context, const ::com::sun::star::uno::Any& _Next = ::com::sun::star::uno::Any()) throw ( ::com::sun::star::sdbc::SQLException ); //---------------------------------------------------------------------------------- /** throw a generic SQLException, i.e. one with an SQLState of S1000, an ErrorCode of 0 and no NextException */ void throwGenericSQLException(const ::rtl::OUString& _rMsg, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxSource) throw (::com::sun::star::sdbc::SQLException); //---------------------------------------------------------------------------------- /** throw a generic SQLException, i.e. one with an SQLState of S1000, an ErrorCode of 0 and no NextException */ void throwGenericSQLException( const ::rtl::OUString& _rMsg, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxSource, const ::com::sun::star::uno::Any& _rNextException ) throw (::com::sun::star::sdbc::SQLException); //......................................................................... } // namespace dbtools //......................................................................... #endif _DBHELPER_DBEXCEPTION_HXX_ /************************************************************************* * history: * $Log: not supported by cvs2svn $ * Revision 1.7 2001/11/08 12:48:37 fs * #93274# +throwFunctionNotSupportedException * * Revision 1.6 2001/06/26 07:53:17 fs * throwGenericSQLException version with additional NextException parameter * * Revision 1.5 2001/05/14 11:40:39 oj * #86528# lower size need * * Revision 1.4 2001/04/19 07:04:21 fs * +throwFunctionSequenceException * * Revision 1.3 2001/03/01 17:01:18 fs * operator= for SQLExceptionInfo, new ctor for SQLExceptionIteratorHelper, new next method * * Revision 1.2 2000/10/24 15:19:40 oj * make strings unique for lib's * * Revision 1.1 2000/10/05 08:56:37 fs * moved the files from unotools to here * * * Revision 1.0 29.09.00 08:31:15 fs ************************************************************************/ <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: BIndex.cxx,v $ * * $Revision: 1.12 $ * * last change: $Author: rt $ $Date: 2005-09-08 05:21:45 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CONNECTIVITY_ADABAS_INDEX_HXX_ #include "adabas/BIndex.hxx" #endif #ifndef _CONNECTIVITY_ADABAS_INDEXCOLUMNS_HXX_ #include "adabas/BIndexColumns.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _CONNECTIVITY_ADABAS_TABLE_HXX_ #include "adabas/BTable.hxx" #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif using namespace connectivity::adabas; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; // using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; // ------------------------------------------------------------------------- OAdabasIndex::OAdabasIndex( OAdabasTable* _pTable, const ::rtl::OUString& _Name, const ::rtl::OUString& _Catalog, sal_Bool _isUnique, sal_Bool _isPrimaryKeyIndex, sal_Bool _isClustered ) : connectivity::sdbcx::OIndex(_Name, _Catalog, _isUnique, _isPrimaryKeyIndex, _isClustered,sal_True) ,m_pTable(_pTable) { construct(); refreshColumns(); } // ------------------------------------------------------------------------- OAdabasIndex::OAdabasIndex(OAdabasTable* _pTable) : connectivity::sdbcx::OIndex(sal_True) ,m_pTable(_pTable) { construct(); } // ----------------------------------------------------------------------------- void OAdabasIndex::refreshColumns() { if(!m_pTable) return; TStringVector aVector; if(!isNew()) { Reference< XResultSet > xResult = m_pTable->getConnection()->getMetaData()->getIndexInfo(Any(), m_pTable->getSchema(),m_pTable->getTableName(),sal_False,sal_False); if(xResult.is()) { Reference< XRow > xRow(xResult,UNO_QUERY); ::rtl::OUString aColName; while(xResult->next()) { if(xRow->getString(6) == m_Name) { aColName = xRow->getString(9); if(!xRow->wasNull()) aVector.push_back(aColName); } } ::comphelper::disposeComponent(xResult); } } if(m_pColumns) m_pColumns->reFill(aVector); else m_pColumns = new OIndexColumns(this,m_aMutex,aVector); } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS warnings01 (1.12.30); FILE MERGED 2006/06/08 09:46:16 fs 1.12.30.2: #136883# renaming getMetaData was a bad idea - it's a overridden virtual method 2005/11/21 10:07:41 fs 1.12.30.1: #i57457# warning-free code on unx*<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: BIndex.cxx,v $ * * $Revision: 1.13 $ * * last change: $Author: hr $ $Date: 2006-06-20 01:08:58 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CONNECTIVITY_ADABAS_INDEX_HXX_ #include "adabas/BIndex.hxx" #endif #ifndef _CONNECTIVITY_ADABAS_INDEXCOLUMNS_HXX_ #include "adabas/BIndexColumns.hxx" #endif #ifndef _COM_SUN_STAR_SDBC_XROW_HPP_ #include <com/sun/star/sdbc/XRow.hpp> #endif #ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_ #include <com/sun/star/sdbc/XResultSet.hpp> #endif #ifndef _CONNECTIVITY_ADABAS_TABLE_HXX_ #include "adabas/BTable.hxx" #endif #ifndef _COMPHELPER_TYPES_HXX_ #include <comphelper/types.hxx> #endif using namespace connectivity::adabas; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; // using namespace ::com::sun::star::sdbcx; using namespace ::com::sun::star::sdbc; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; // ------------------------------------------------------------------------- OAdabasIndex::OAdabasIndex( OAdabasTable* _pTable, const ::rtl::OUString& _Name, const ::rtl::OUString& _Catalog, sal_Bool _isUnique, sal_Bool _isPrimaryKeyIndex, sal_Bool _isClustered ) : connectivity::sdbcx::OIndex(_Name, _Catalog, _isUnique, _isPrimaryKeyIndex, _isClustered,sal_True) ,m_pTable(_pTable) { construct(); refreshColumns(); } // ------------------------------------------------------------------------- OAdabasIndex::OAdabasIndex(OAdabasTable* _pTable) : connectivity::sdbcx::OIndex(sal_True) ,m_pTable(_pTable) { construct(); } // ----------------------------------------------------------------------------- void OAdabasIndex::refreshColumns() { if(!m_pTable) return; TStringVector aVector; if(!isNew()) { Reference< XResultSet > xResult = m_pTable->getMetaData()->getIndexInfo(Any(), m_pTable->getSchema(),m_pTable->getTableName(),sal_False,sal_False); if(xResult.is()) { Reference< XRow > xRow(xResult,UNO_QUERY); ::rtl::OUString aColName; while(xResult->next()) { if(xRow->getString(6) == m_Name) { aColName = xRow->getString(9); if(!xRow->wasNull()) aVector.push_back(aColName); } } ::comphelper::disposeComponent(xResult); } } if(m_pColumns) m_pColumns->reFill(aVector); else m_pColumns = new OIndexColumns(this,m_aMutex,aVector); } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: DConnection.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: oj $ $Date: 2002-07-05 08:09:56 $ * * 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_DBASE_DCONNECTION_HXX_ #define _CONNECTIVITY_DBASE_DCONNECTION_HXX_ #ifndef _CONNECTIVITY_FILE_OCONNECTION_HXX_ #include "file/FConnection.hxx" #endif namespace connectivity { namespace dbase { class ODriver; typedef file::OConnection ODbaseConnection_Base; class ODbaseConnection : public ODbaseConnection_Base { protected: virtual ~ODbaseConnection(); public: ODbaseConnection(ODriver* _pDriver); // XServiceInfo DECLARE_SERVICE_INFO(); // XConnection 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 ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > createCatalog(); 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); }; } } #endif // _CONNECTIVITY_DBASE_DCONNECTION_HXX_ <commit_msg>INTEGRATION: CWS ooo19126 (1.5.326); FILE MERGED 2005/09/05 17:25:14 rt 1.5.326.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: DConnection.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2005-09-08 07:02:03 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _CONNECTIVITY_DBASE_DCONNECTION_HXX_ #define _CONNECTIVITY_DBASE_DCONNECTION_HXX_ #ifndef _CONNECTIVITY_FILE_OCONNECTION_HXX_ #include "file/FConnection.hxx" #endif namespace connectivity { namespace dbase { class ODriver; typedef file::OConnection ODbaseConnection_Base; class ODbaseConnection : public ODbaseConnection_Base { protected: virtual ~ODbaseConnection(); public: ODbaseConnection(ODriver* _pDriver); // XServiceInfo DECLARE_SERVICE_INFO(); // XConnection 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 ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > createCatalog(); 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); }; } } #endif // _CONNECTIVITY_DBASE_DCONNECTION_HXX_ <|endoftext|>
<commit_before>/*! * Copyright (c) 2016 by Contributors * \file q_fully_connected.cc * \brief Quantized FC operator * \author HPI-DeepLearning */ #include "./q_fully_connected-inl.h" #include "./xnor_cpu.h" namespace mshadow { using namespace mxnet::op::xnor_cpu; inline void QFullyConnectedForward(const Tensor<cpu, 2, float> &data, const Tensor<cpu, 2, float> &wmat, const Tensor<cpu, 2, float> &out, const mxnet::op::QFullyConnectedParam &param) { CHECK_EQ(data.size(1) % BITS_PER_BINARY_WORD, 0) << "input channel number for binary fully_connected layer is not divisible by 32."; int m = data.size(0); int n = data.size(1); int k = wmat.size(1); //check matrix dims: // data.size(1) should equal wmat.size(0) // out should have dims (m, k) CHECK_EQ((int)data.size(1), (int)wmat.size(0)); CHECK_EQ((int)out.size(0), (int)data.size(0)); BINARY_WORD* binary_row = (BINARY_WORD*) malloc(m * n/BITS_PER_BINARY_WORD * sizeof(BINARY_WORD)); BINARY_WORD* binary_col = (BINARY_WORD*) malloc(n * k/BITS_PER_BINARY_WORD * sizeof(BINARY_WORD)); get_binary_row(data.dptr_, binary_row, m*n); get_binary_col(wmat.dptr_, binary_col, n, k); xnor_gemm(m, k, n/BITS_PER_BINARY_WORD, binary_row, n/BITS_PER_BINARY_WORD, binary_col, k, out.dptr_, k); free(binary_row); free(binary_col); } template<typename DType> inline void QFullyConnectedForward(const Tensor<cpu, 2, DType> &data, const Tensor<cpu, 2, DType> &wmat, const Tensor<cpu, 2, DType> &out, const mxnet::op::QFullyConnectedParam &param) { CHECK(false) << "only float supported"; } } namespace mxnet { namespace op { template<> Operator* CreateOp<cpu>(QFullyConnectedParam param, int dtype, std::vector<TShape> *in_shape, std::vector<TShape> *out_shape, Context ctx) { Operator *op = NULL; MSHADOW_REAL_TYPE_SWITCH(dtype, DType, { op = new QFullyConnectedOp<cpu, DType>(param); }) return op; } // DO_BIND_DISPATCH comes from operator_common.h Operator *QFullyConnectedProp::CreateOperatorEx(Context ctx, std::vector<TShape> *in_shape, std::vector<int> *in_type) const { std::vector<TShape> out_shape, aux_shape; std::vector<int> out_type, aux_type; CHECK(InferType(in_type, &out_type, &aux_type)); CHECK(InferShape(in_shape, &out_shape, &aux_shape)); DO_BIND_DISPATCH(CreateOp, param_, (*in_type)[0], in_shape, &out_shape, ctx); } DMLC_REGISTER_PARAMETER(QFullyConnectedParam); MXNET_REGISTER_OP_PROPERTY(QFullyConnected, QFullyConnectedProp) .describe(R"(Apply matrix multiplication to input then add a bias. It maps the input of shape `(batch_size, input_dim)` to the shape of `(batch_size, num_hidden)`. Learnable parameters include the weights of the linear transform and an optional bias vector.)") .add_argument("data", "Symbol", "Input data to the FullyConnectedOp.") .add_argument("weight", "Symbol", "Weight matrix.") .add_argument("bias", "Symbol", "Bias parameter.") .add_arguments(QFullyConnectedParam::__FIELDS__()); } // namespace op } // namespace mxnet <commit_msg>fix cpu binary fully_connected layer (zero-init out put array)<commit_after>/*! * Copyright (c) 2016 by Contributors * \file q_fully_connected.cc * \brief Quantized FC operator * \author HPI-DeepLearning */ #include "./q_fully_connected-inl.h" #include "./xnor_cpu.h" namespace mshadow { using namespace mxnet::op::xnor_cpu; inline void QFullyConnectedForward(const Tensor<cpu, 2, float> &data, const Tensor<cpu, 2, float> &wmat, const Tensor<cpu, 2, float> &out, const mxnet::op::QFullyConnectedParam &param) { CHECK_EQ(data.size(1) % BITS_PER_BINARY_WORD, 0) << "input channel number for binary fully_connected layer is not divisible by 32."; int m = data.size(0); int n = data.size(1); int k = wmat.size(1); //check matrix dims: // data.size(1) should equal wmat.size(0) // out should have dims (m, k) CHECK_EQ((int)data.size(1), (int)wmat.size(0)); CHECK_EQ((int)out.size(0), (int)data.size(0)); BINARY_WORD* binary_row = (BINARY_WORD*) malloc(m * n/BITS_PER_BINARY_WORD * sizeof(BINARY_WORD)); BINARY_WORD* binary_col = (BINARY_WORD*) malloc(n * k/BITS_PER_BINARY_WORD * sizeof(BINARY_WORD)); get_binary_row(data.dptr_, binary_row, m*n); get_binary_col(wmat.dptr_, binary_col, n, k); for (int i = 0; i < out.shape_.Size(); ++i) { out.dptr_[i] = 0; } xnor_gemm(m, k, n/BITS_PER_BINARY_WORD, binary_row, n/BITS_PER_BINARY_WORD, binary_col, k, out.dptr_, k); free(binary_row); free(binary_col); } template<typename DType> inline void QFullyConnectedForward(const Tensor<cpu, 2, DType> &data, const Tensor<cpu, 2, DType> &wmat, const Tensor<cpu, 2, DType> &out, const mxnet::op::QFullyConnectedParam &param) { CHECK(false) << "only float supported"; } } namespace mxnet { namespace op { template<> Operator* CreateOp<cpu>(QFullyConnectedParam param, int dtype, std::vector<TShape> *in_shape, std::vector<TShape> *out_shape, Context ctx) { Operator *op = NULL; MSHADOW_REAL_TYPE_SWITCH(dtype, DType, { op = new QFullyConnectedOp<cpu, DType>(param); }) return op; } // DO_BIND_DISPATCH comes from operator_common.h Operator *QFullyConnectedProp::CreateOperatorEx(Context ctx, std::vector<TShape> *in_shape, std::vector<int> *in_type) const { std::vector<TShape> out_shape, aux_shape; std::vector<int> out_type, aux_type; CHECK(InferType(in_type, &out_type, &aux_type)); CHECK(InferShape(in_shape, &out_shape, &aux_shape)); DO_BIND_DISPATCH(CreateOp, param_, (*in_type)[0], in_shape, &out_shape, ctx); } DMLC_REGISTER_PARAMETER(QFullyConnectedParam); MXNET_REGISTER_OP_PROPERTY(QFullyConnected, QFullyConnectedProp) .describe(R"(Apply matrix multiplication to input then add a bias. It maps the input of shape `(batch_size, input_dim)` to the shape of `(batch_size, num_hidden)`. Learnable parameters include the weights of the linear transform and an optional bias vector.)") .add_argument("data", "Symbol", "Input data to the FullyConnectedOp.") .add_argument("weight", "Symbol", "Weight matrix.") .add_argument("bias", "Symbol", "Bias parameter.") .add_arguments(QFullyConnectedParam::__FIELDS__()); } // namespace op } // namespace mxnet <|endoftext|>
<commit_before>/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com) ** ** ** ** 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. ** ***********************************************************************************/ #include "Widgets/FloatingButton.hpp" #include <QtMath> #include <QCursor> #include <QGraphicsDropShadowEffect> #include <QMessageBox> #include <QPropertyAnimation> #include "Application.hpp" #include "BrowserWindow.hpp" #include "Web/Tab/WebTab.hpp" #include "Widgets/Tab/TabWidget.hpp" namespace Sn { static const int ANIMATION_DURATION = 1000 * 0.2; FloatingButton::FloatingButton(RootFloatingButton* parent, const QString& name, const QString& toolTip) : QPushButton(parent->parentWidget()) { setFixedSize(QSize(48, 48)); setIconSize(QSize(48, 48)); setFlat(true); setObjectName(name); setToolTip(toolTip); QGraphicsDropShadowEffect* effect{new QGraphicsDropShadowEffect(this)}; effect->setBlurRadius(4); effect->setOffset(0, 2); setGraphicsEffect(effect); m_parent = parent->parentWidget(); hide(); } void FloatingButton::setIndex(int index) { m_index = index; } void FloatingButton::mousePressEvent(QMouseEvent* event) { m_offset = event->pos(); m_oldPosition = pos(); QPushButton::mousePressEvent(event); } void FloatingButton::mouseMoveEvent(QMouseEvent* event) { if (event->buttons() & Qt::LeftButton) { QPoint position{mapToParent(event->pos() - m_offset)}; int x{}; int y{}; x = (position.x() >= 0) ? qMin(m_parent->width() - width(), position.x()) : qMax(0, position.x()); y = (position.y() >= 0) ? qMin(m_parent->height() - height(), position.y()) : qMax(0, position.y()); move(QPoint(x, y)); m_blockClick = true; } } void FloatingButton::mouseReleaseEvent(QMouseEvent* event) { setAttribute(Qt::WA_TransparentForMouseEvents, true); if (Application::widgetAt(mapToGlobal(event->pos()))) { FloatingButton* button = qobject_cast<FloatingButton*>(Application::widgetAt(mapToGlobal(event->pos()))); if (button) { int buttonIndex = button->index(); button->setIndex(m_index); m_index = buttonIndex; move(button->pos()); button->moveButton(m_oldPosition); emit statusChanged(); } else { moveButton(m_oldPosition); } } setAttribute(Qt::WA_TransparentForMouseEvents, false); if (!m_blockClick) emit isClicked(); m_blockClick = false; } void FloatingButton::moveButton(QPoint destination, int animationTime, bool hideAtEnd) { if (!isVisible()) show(); setAttribute(Qt::WA_TransparentForMouseEvents, true); QPropertyAnimation* animation = new QPropertyAnimation(this, "geometry"); animation->setDuration(animationTime); animation->setStartValue(QRect(pos().x(), pos().y(), width(), height())); animation->setEndValue(QRect(destination.x(), destination.y(), width(), height())); animation->start(QAbstractAnimation::DeleteWhenStopped); connect(animation, &QPropertyAnimation::finished, this, [=]() { setAttribute(Qt::WA_TransparentForMouseEvents, false); if (hideAtEnd) { hide(); } }); } RootFloatingButton::RootFloatingButton(BrowserWindow* window, QWidget* parent, Pattern pattern) : QPushButton(parent), m_pattern(pattern), m_window(window), m_blockClick(false) { setFixedSize(QSize(48, 48)); setIconSize(QSize(48, 48)); setFlat(true); setObjectName("fbutton-root"); setToolTip(tr("Floating button")); setCursor(Qt::SizeAllCursor); setContextMenuPolicy(Qt::CustomContextMenu); QGraphicsDropShadowEffect* effect{new QGraphicsDropShadowEffect(this)}; effect->setBlurRadius(4); effect->setOffset(0, 4); setGraphicsEffect(effect); connect(this, &QPushButton::customContextMenuRequested, this, &RootFloatingButton::showMenu); } void RootFloatingButton::addButton(const QString& name, const QString& toolTip) { FloatingButton* newButton{new FloatingButton(this, name)}; newButton->setIndex(m_buttons.size()); newButton->setToolTip(toolTip); connect(newButton, SIGNAL(statusChanged()), this, SIGNAL(statusChanged())); m_buttons.insert(name, newButton); } FloatingButton* RootFloatingButton::button(const QString& name) { return m_buttons.value(name); } void RootFloatingButton::setPattern(Pattern pattern) { m_pattern = pattern; } void RootFloatingButton::expandAround(QPoint around) { if (m_childrenExpanded) return; m_childrenExpanded = true; float deegresSpace = 360 / m_buttons.size(); int radius = width() + 15; for (int i{0}; i < m_buttons.size(); ++i) { float degrees = deegresSpace * (i + 1); int x = around.x() + radius * qCos(qDegreesToRadians(degrees)); int y = around.y() + radius * qSin(qDegreesToRadians(degrees)); foreach (FloatingButton* button, m_buttons) { if (button->index() == i) { button->move(around); button->show(); button->moveButton(QPoint(x, y)); break; } } } } void RootFloatingButton::expandInToolbar(TabWidget* tabWidget) { if (m_childrenExpanded) return; m_childrenExpanded = true; for (int i{1}; i <= m_buttons.size(); ++i) { foreach (FloatingButton* button, m_buttons) { if (button->index() == i - 1) { QPoint relativePos{tabWidget->mapTo(m_window, tabWidget->pos())}; QPoint destination{0, 0}; if (m_pattern == Pattern::TopToolbar) destination = QPoint(relativePos.x() + i * width(), relativePos.y()); if (m_pattern == Pattern::BottomToolbar) destination = QPoint(relativePos.x() + i * width(), relativePos.y() + (tabWidget->height() - height() * 2)); if (m_pattern == Pattern::LeftToolbar) destination = QPoint(relativePos.x(), relativePos.y() + i * height()); if (m_pattern == Pattern::RightToolbar) destination = QPoint(relativePos.x() + (tabWidget->width() - width() * 2), relativePos.y() + i * height()); button->move(pos()); button->show(); button->moveButton(destination); break; } } } } void RootFloatingButton::closeButton() { if (!m_childrenExpanded) return; foreach (FloatingButton* button, m_buttons) { button->moveButton(pos(), 100, true); } m_childrenExpanded = false; } void RootFloatingButton::tabWidgetChanged(TabWidget* tabWidget) { closeButton(); move(tabWidget->mapTo(m_window, tabWidget->pos()).x(), tabWidget->mapTo(m_window, tabWidget->pos()).y()); if (m_pattern != Pattern::Floating) { if (m_pattern == BottomToolbar) move(x(), y() + (tabWidget->height() - height() * 2)); else if (m_pattern == RightToolbar) move(x() + (tabWidget->width() - width() * 2), y()); expandInToolbar(tabWidget); } } void RootFloatingButton::mousePressEvent(QMouseEvent* event) { m_offset = event->pos(); QPushButton::mousePressEvent(event); } void RootFloatingButton::mouseMoveEvent(QMouseEvent* event) { if (event->buttons() & Qt::LeftButton) { if (m_pattern != Pattern::Floating) { m_pattern = Pattern::Floating; emit statusChanged(); } if (m_childrenExpanded) closeButton(); QPoint position{mapToParent(event->pos() - m_offset)}; int x{}; int y{}; x = (position.x() >= 0) ? qMin(m_window->width() - width(), position.x()) : qMax(0, position.x()); y = (position.y() >= 0) ? qMin(m_window->height() - height(), position.y()) : qMax(0, position.y()); move(QPoint(x, y)); m_blockClick = true; } } void RootFloatingButton::mouseReleaseEvent(QMouseEvent* event) { if (!m_blockClick) { if (!m_childrenExpanded && m_pattern == Pattern::Floating) expandAround(mapToParent(event->pos() - m_offset)); else if (m_pattern == Floating) closeButton(); } m_blockClick = false; } void RootFloatingButton::showMenu(const QPoint& pos) { QMenu menu{m_window}; QMenu patternsMenu{"Patterns", m_window}; patternsMenu.addAction(tr("Floating"), this, &RootFloatingButton::changePattern)->setData(Pattern::Floating); patternsMenu.addSeparator(); patternsMenu.addAction(tr("Left Toolbar"), this, &RootFloatingButton::changePattern)->setData(Pattern::LeftToolbar); patternsMenu.addAction(tr("Right Toolbar"), this, &RootFloatingButton::changePattern)->setData( Pattern::RightToolbar); patternsMenu.addAction(tr("Top Toolbar"), this, &RootFloatingButton::changePattern)->setData(Pattern::TopToolbar); patternsMenu.addAction(tr("Bottom Toolbar"), this, &RootFloatingButton::changePattern)->setData( Pattern::BottomToolbar); menu.addMenu(&patternsMenu); menu.exec(mapToGlobal(QPoint(pos.x(), pos.y() + 1))); } void RootFloatingButton::changePattern() { QAction* action{qobject_cast<QAction*>(sender())}; if (!action) return; m_pattern = static_cast<Pattern>(action->data().toInt()); emit patternChanged(m_pattern); emit statusChanged(); } }<commit_msg>Change behaviour of the click on root button<commit_after>/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com) ** ** ** ** 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. ** ***********************************************************************************/ #include "Widgets/FloatingButton.hpp" #include <QtMath> #include <QCursor> #include <QGraphicsDropShadowEffect> #include <QMessageBox> #include <QPropertyAnimation> #include "Application.hpp" #include "BrowserWindow.hpp" #include "Web/Tab/WebTab.hpp" #include "Widgets/Tab/TabWidget.hpp" namespace Sn { static const int ANIMATION_DURATION = 1000 * 0.2; FloatingButton::FloatingButton(RootFloatingButton* parent, const QString& name, const QString& toolTip) : QPushButton(parent->parentWidget()) { setFixedSize(QSize(48, 48)); setIconSize(QSize(48, 48)); setFlat(true); setObjectName(name); setToolTip(toolTip); QGraphicsDropShadowEffect* effect{new QGraphicsDropShadowEffect(this)}; effect->setBlurRadius(4); effect->setOffset(0, 2); setGraphicsEffect(effect); m_parent = parent->parentWidget(); hide(); } void FloatingButton::setIndex(int index) { m_index = index; } void FloatingButton::mousePressEvent(QMouseEvent* event) { m_offset = event->pos(); m_oldPosition = pos(); QPushButton::mousePressEvent(event); } void FloatingButton::mouseMoveEvent(QMouseEvent* event) { if (event->buttons() & Qt::LeftButton) { QPoint position{mapToParent(event->pos() - m_offset)}; int x{}; int y{}; x = (position.x() >= 0) ? qMin(m_parent->width() - width(), position.x()) : qMax(0, position.x()); y = (position.y() >= 0) ? qMin(m_parent->height() - height(), position.y()) : qMax(0, position.y()); move(QPoint(x, y)); m_blockClick = true; } } void FloatingButton::mouseReleaseEvent(QMouseEvent* event) { setAttribute(Qt::WA_TransparentForMouseEvents, true); if (Application::widgetAt(mapToGlobal(event->pos()))) { FloatingButton* button = qobject_cast<FloatingButton*>(Application::widgetAt(mapToGlobal(event->pos()))); if (button) { int buttonIndex = button->index(); button->setIndex(m_index); m_index = buttonIndex; move(button->pos()); button->moveButton(m_oldPosition); emit statusChanged(); } else { moveButton(m_oldPosition); } } setAttribute(Qt::WA_TransparentForMouseEvents, false); if (!m_blockClick) emit isClicked(); m_blockClick = false; } void FloatingButton::moveButton(QPoint destination, int animationTime, bool hideAtEnd) { if (!isVisible()) show(); setAttribute(Qt::WA_TransparentForMouseEvents, true); QPropertyAnimation* animation = new QPropertyAnimation(this, "geometry"); animation->setDuration(animationTime); animation->setStartValue(QRect(pos().x(), pos().y(), width(), height())); animation->setEndValue(QRect(destination.x(), destination.y(), width(), height())); animation->start(QAbstractAnimation::DeleteWhenStopped); connect(animation, &QPropertyAnimation::finished, this, [=]() { setAttribute(Qt::WA_TransparentForMouseEvents, false); if (hideAtEnd) { hide(); } }); } RootFloatingButton::RootFloatingButton(BrowserWindow* window, QWidget* parent, Pattern pattern) : QPushButton(parent), m_pattern(pattern), m_window(window), m_blockClick(false) { setFixedSize(QSize(48, 48)); setIconSize(QSize(48, 48)); setFlat(true); setObjectName("fbutton-root"); setToolTip(tr("Floating button")); setCursor(Qt::SizeAllCursor); setContextMenuPolicy(Qt::CustomContextMenu); QGraphicsDropShadowEffect* effect{new QGraphicsDropShadowEffect(this)}; effect->setBlurRadius(4); effect->setOffset(0, 4); setGraphicsEffect(effect); connect(this, &QPushButton::customContextMenuRequested, this, &RootFloatingButton::showMenu); } void RootFloatingButton::addButton(const QString& name, const QString& toolTip) { FloatingButton* newButton{new FloatingButton(this, name)}; newButton->setIndex(m_buttons.size()); newButton->setToolTip(toolTip); connect(newButton, SIGNAL(statusChanged()), this, SIGNAL(statusChanged())); m_buttons.insert(name, newButton); } FloatingButton* RootFloatingButton::button(const QString& name) { return m_buttons.value(name); } void RootFloatingButton::setPattern(Pattern pattern) { m_pattern = pattern; } void RootFloatingButton::expandAround(QPoint around) { if (m_childrenExpanded) return; m_childrenExpanded = true; float deegresSpace = 360 / m_buttons.size(); int radius = width() + 15; for (int i{0}; i < m_buttons.size(); ++i) { float degrees = deegresSpace * (i + 1); int x = around.x() + radius * qCos(qDegreesToRadians(degrees)); int y = around.y() + radius * qSin(qDegreesToRadians(degrees)); foreach (FloatingButton* button, m_buttons) { if (button->index() == i) { button->move(around); button->show(); button->moveButton(QPoint(x, y)); break; } } } } void RootFloatingButton::expandInToolbar(TabWidget* tabWidget) { if (m_childrenExpanded) return; m_childrenExpanded = true; for (int i{1}; i <= m_buttons.size(); ++i) { foreach (FloatingButton* button, m_buttons) { if (button->index() == i - 1) { QPoint relativePos{tabWidget->mapTo(m_window, tabWidget->pos())}; QPoint destination{0, 0}; if (m_pattern == Pattern::TopToolbar) destination = QPoint(relativePos.x() + i * width(), relativePos.y()); if (m_pattern == Pattern::BottomToolbar) destination = QPoint(relativePos.x() + i * width(), relativePos.y() + (tabWidget->height() - height() * 2)); if (m_pattern == Pattern::LeftToolbar) destination = QPoint(relativePos.x(), relativePos.y() + i * height()); if (m_pattern == Pattern::RightToolbar) destination = QPoint(relativePos.x() + (tabWidget->width() - width() * 2), relativePos.y() + i * height()); button->move(pos()); button->show(); button->moveButton(destination); break; } } } } void RootFloatingButton::closeButton() { if (!m_childrenExpanded) return; foreach (FloatingButton* button, m_buttons) { button->moveButton(pos(), 100, true); } m_childrenExpanded = false; } void RootFloatingButton::tabWidgetChanged(TabWidget* tabWidget) { closeButton(); move(tabWidget->mapTo(m_window, tabWidget->pos()).x(), tabWidget->mapTo(m_window, tabWidget->pos()).y()); if (m_pattern != Pattern::Floating) { if (m_pattern == BottomToolbar) move(x(), y() + (tabWidget->height() - height() * 2)); else if (m_pattern == RightToolbar) move(x() + (tabWidget->width() - width() * 2), y()); expandInToolbar(tabWidget); } } void RootFloatingButton::mousePressEvent(QMouseEvent* event) { m_offset = event->pos(); QPushButton::mousePressEvent(event); } void RootFloatingButton::mouseMoveEvent(QMouseEvent* event) { if (event->buttons() & Qt::LeftButton) { if (m_pattern != Pattern::Floating) { m_pattern = Pattern::Floating; emit statusChanged(); } if (m_childrenExpanded) closeButton(); QPoint position{mapToParent(event->pos() - m_offset)}; int x{}; int y{}; x = (position.x() >= 0) ? qMin(m_window->width() - width(), position.x()) : qMax(0, position.x()); y = (position.y() >= 0) ? qMin(m_window->height() - height(), position.y()) : qMax(0, position.y()); move(QPoint(x, y)); m_blockClick = true; } } void RootFloatingButton::mouseReleaseEvent(QMouseEvent* event) { if (!m_blockClick && event->button() == Qt::LeftButton) { if (!m_childrenExpanded && m_pattern == Pattern::Floating) expandAround(mapToParent(event->pos() - m_offset)); else if (m_pattern == Floating) closeButton(); } m_blockClick = false; } void RootFloatingButton::showMenu(const QPoint& pos) { QMenu menu{m_window}; QMenu patternsMenu{"Patterns", m_window}; patternsMenu.addAction(tr("Floating"), this, &RootFloatingButton::changePattern)->setData(Pattern::Floating); patternsMenu.addSeparator(); patternsMenu.addAction(tr("Left Toolbar"), this, &RootFloatingButton::changePattern)->setData(Pattern::LeftToolbar); patternsMenu.addAction(tr("Right Toolbar"), this, &RootFloatingButton::changePattern)->setData( Pattern::RightToolbar); patternsMenu.addAction(tr("Top Toolbar"), this, &RootFloatingButton::changePattern)->setData(Pattern::TopToolbar); patternsMenu.addAction(tr("Bottom Toolbar"), this, &RootFloatingButton::changePattern)->setData( Pattern::BottomToolbar); menu.addMenu(&patternsMenu); menu.exec(mapToGlobal(QPoint(pos.x(), pos.y() + 1))); } void RootFloatingButton::changePattern() { QAction* action{qobject_cast<QAction*>(sender())}; if (!action) return; m_pattern = static_cast<Pattern>(action->data().toInt()); emit patternChanged(m_pattern); emit statusChanged(); } } <|endoftext|>
<commit_before>/* Copyright (c) 2016-2016, Vasil Dimov 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. */ #include <iostream> #include <sstream> #include <stdexcept> #include <string> #include <vector> #include <ipfs/client.h> /** Check if a given set of properties exist in a JSON. */ static inline void check_if_properties_exist( /** [in] Label to use when throwing an exception if a failure occurs. */ const std::string& label, /** [in] JSON to check for the properties. */ const ipfs::Json& j, /** [in] List of properties. */ const std::vector<const char*>& properties) { for (const char* property : properties) { if (j.find(property) == j.end()) { throw std::runtime_error(label + ": the property \"" + property + "\" was not found in the response:\n" + j.dump(2)); } } } /** Check if a string contains another string and throw an exception if it does * not. */ static inline void check_if_string_contains( /** [in] Label to use when throwing an exception if a failure occurs. */ const std::string& label, /** [in] String to search into. */ const std::string& big, /** [in] String to search for. */ const std::string& needle) { if (big.find(needle) == big.npos) { throw std::runtime_error(label + ": \"" + needle + "\" was not found in the response:\n" + big); } } /** Convert a string to hex. For example: "abcd" -> "61626364". */ static inline std::string string_to_hex( /** [in] String to convert. */ const std::string& input) { std::stringstream ss; ss << std::hex; for (size_t i = 0; i < input.length(); ++i) { ss << std::setw(2) << std::setfill('0') << (int)input[i]; } return ss.str(); } int main(int, char**) { try { /** [ipfs::Client::Client] */ ipfs::Client client("localhost", 5001); /** [ipfs::Client::Client] */ /** [ipfs::Client::Id] */ ipfs::Json id; client.Id(&id); std::cout << "Peer's public key: " << id["PublicKey"] << std::endl; /** [ipfs::Client::Id] */ check_if_properties_exist("ipfs.Id()", id, {"Addresses", "ID", "PublicKey"}); /** [ipfs::Client::Version] */ ipfs::Json version; client.Version(&version); std::cout << "Peer's version: " << version << std::endl; /** [ipfs::Client::Version] */ check_if_properties_exist("ipfs.Version()", version, {"Repo", "System", "Version"}); /** [ipfs::Client::BlockGet] */ std::stringstream block; client.BlockGet("QmWPyMW2u7J2Zyzut7TcBMT8pG6F2cB4hmZk1vBJFBt1nP", &block); std::cout << "Block (hex): " << string_to_hex(block.str()) << std::endl; /* An example output: Block (hex): 0a0a08021204616263641804 */ /** [ipfs::Client::BlockGet] */ /** [ipfs::Client::BlockStat] */ ipfs::Json stat; client.BlockStat("QmWPyMW2u7J2Zyzut7TcBMT8pG6F2cB4hmZk1vBJFBt1nP", &stat); std::cout << "Block info: " << stat << std::endl; /* An example output: {"Key":"QmWPyMW2u7J2Zyzut7TcBMT8pG6F2cB4hmZk1vBJFBt1nP","Size":12} */ /** [ipfs::Client::BlockStat] */ check_if_properties_exist("client.BlockStat()", stat, {"Key", "Size"}); /** [ipfs::Client::FilesGet] */ std::stringstream contents; client.FilesGet( "/ipfs/QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG/readme", &contents); std::cout << "Retrieved contents: " << contents.str().substr(0, 8) << "..." << std::endl; /** [ipfs::Client::FilesGet] */ check_if_string_contains("client.FilesGet()", contents.str(), "Hello and Welcome to IPFS!"); /** [ipfs::Client::FilesAdd] */ ipfs::Json add_result; client.FilesAdd( {{"foo.txt", ipfs::http::FileUpload::Type::kFileContents, "abcd"}, {"bar.txt", ipfs::http::FileUpload::Type::kFileName, "compile_commands.json"}}, &add_result); std::cout << "FilesAdd() result:\n" << add_result.dump(2) << std::endl; /* An example output: [ { "path": "foo.txt", "hash": "QmWPyMW2u7J2Zyzut7TcBMT8pG6F2cB4hmZk1vBJFBt1nP", "size": 4 } { "path": "bar.txt", "hash": "QmVjQsMgtRsRKpNM8amTCDRuUPriY8tGswsTpo137jPWwL", "size": 1176 }, ] */ /** [ipfs::Client::FilesAdd] */ } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return 1; } return 0; } <commit_msg>Fix old names in error labels<commit_after>/* Copyright (c) 2016-2016, Vasil Dimov 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. */ #include <iostream> #include <sstream> #include <stdexcept> #include <string> #include <vector> #include <ipfs/client.h> /** Check if a given set of properties exist in a JSON. */ static inline void check_if_properties_exist( /** [in] Label to use when throwing an exception if a failure occurs. */ const std::string& label, /** [in] JSON to check for the properties. */ const ipfs::Json& j, /** [in] List of properties. */ const std::vector<const char*>& properties) { for (const char* property : properties) { if (j.find(property) == j.end()) { throw std::runtime_error(label + ": the property \"" + property + "\" was not found in the response:\n" + j.dump(2)); } } } /** Check if a string contains another string and throw an exception if it does * not. */ static inline void check_if_string_contains( /** [in] Label to use when throwing an exception if a failure occurs. */ const std::string& label, /** [in] String to search into. */ const std::string& big, /** [in] String to search for. */ const std::string& needle) { if (big.find(needle) == big.npos) { throw std::runtime_error(label + ": \"" + needle + "\" was not found in the response:\n" + big); } } /** Convert a string to hex. For example: "abcd" -> "61626364". */ static inline std::string string_to_hex( /** [in] String to convert. */ const std::string& input) { std::stringstream ss; ss << std::hex; for (size_t i = 0; i < input.length(); ++i) { ss << std::setw(2) << std::setfill('0') << (int)input[i]; } return ss.str(); } int main(int, char**) { try { /** [ipfs::Client::Client] */ ipfs::Client client("localhost", 5001); /** [ipfs::Client::Client] */ /** [ipfs::Client::Id] */ ipfs::Json id; client.Id(&id); std::cout << "Peer's public key: " << id["PublicKey"] << std::endl; /** [ipfs::Client::Id] */ check_if_properties_exist("client.Id()", id, {"Addresses", "ID", "PublicKey"}); /** [ipfs::Client::Version] */ ipfs::Json version; client.Version(&version); std::cout << "Peer's version: " << version << std::endl; /** [ipfs::Client::Version] */ check_if_properties_exist("client.Version()", version, {"Repo", "System", "Version"}); /** [ipfs::Client::BlockGet] */ std::stringstream block; client.BlockGet("QmWPyMW2u7J2Zyzut7TcBMT8pG6F2cB4hmZk1vBJFBt1nP", &block); std::cout << "Block (hex): " << string_to_hex(block.str()) << std::endl; /* An example output: Block (hex): 0a0a08021204616263641804 */ /** [ipfs::Client::BlockGet] */ /** [ipfs::Client::BlockStat] */ ipfs::Json stat; client.BlockStat("QmWPyMW2u7J2Zyzut7TcBMT8pG6F2cB4hmZk1vBJFBt1nP", &stat); std::cout << "Block info: " << stat << std::endl; /* An example output: {"Key":"QmWPyMW2u7J2Zyzut7TcBMT8pG6F2cB4hmZk1vBJFBt1nP","Size":12} */ /** [ipfs::Client::BlockStat] */ check_if_properties_exist("client.BlockStat()", stat, {"Key", "Size"}); /** [ipfs::Client::FilesGet] */ std::stringstream contents; client.FilesGet( "/ipfs/QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG/readme", &contents); std::cout << "Retrieved contents: " << contents.str().substr(0, 8) << "..." << std::endl; /** [ipfs::Client::FilesGet] */ check_if_string_contains("client.FilesGet()", contents.str(), "Hello and Welcome to IPFS!"); /** [ipfs::Client::FilesAdd] */ ipfs::Json add_result; client.FilesAdd( {{"foo.txt", ipfs::http::FileUpload::Type::kFileContents, "abcd"}, {"bar.txt", ipfs::http::FileUpload::Type::kFileName, "compile_commands.json"}}, &add_result); std::cout << "FilesAdd() result:\n" << add_result.dump(2) << std::endl; /* An example output: [ { "path": "foo.txt", "hash": "QmWPyMW2u7J2Zyzut7TcBMT8pG6F2cB4hmZk1vBJFBt1nP", "size": 4 } { "path": "bar.txt", "hash": "QmVjQsMgtRsRKpNM8amTCDRuUPriY8tGswsTpo137jPWwL", "size": 1176 }, ] */ /** [ipfs::Client::FilesAdd] */ } catch (const std::exception& e) { std::cerr << e.what() << std::endl; return 1; } return 0; } <|endoftext|>
<commit_before>#include "acmacs-base/pybind11.hh" // chart #include "acmacs-chart-2/factory-import.hh" #include "acmacs-chart-2/factory-export.hh" #include "acmacs-chart-2/chart-modify.hh" // merge #include "acmacs-chart-2/merge.hh" // ====================================================================== inline unsigned make_info_data(bool column_bases, bool tables, bool tables_for_sera, bool antigen_dates) { using namespace acmacs::chart; return (column_bases ? info_data::column_bases : 0) // | (tables ? info_data::tables : 0) // | (tables_for_sera ? info_data::tables_for_sera : 0) // | (antigen_dates ? info_data::dates : 0); } // ---------------------------------------------------------------------- inline acmacs::chart::ChartClone::clone_data clone_type(const std::string& type) { using namespace acmacs::chart; if (type == "titers") return ChartClone::clone_data::titers; else if (type == "projections") return ChartClone::clone_data::projections; else if (type == "plot_spec") return ChartClone::clone_data::plot_spec; else if (type == "projections_plot_spec") return ChartClone::clone_data::projections_plot_spec; else throw std::invalid_argument{fmt::format("Unrecognized clone \"type\": \"{}\"", type)}; } // ---------------------------------------------------------------------- template <typename AgSr> struct AgSrIndexes { AgSrIndexes() = default; AgSrIndexes(std::shared_ptr<AgSr> a_ag_sr) : ag_sr{a_ag_sr}, indexes{a_ag_sr->all_indexes()} {} bool empty() const { return indexes.empty(); } std::shared_ptr<AgSr> ag_sr; acmacs::chart::Indexes indexes; }; struct AntigenIndexes : public AgSrIndexes<acmacs::chart::Antigens> { using AgSrIndexes<acmacs::chart::Antigens>::AgSrIndexes; }; struct SerumIndexes : public AgSrIndexes<acmacs::chart::Sera> { using AgSrIndexes<acmacs::chart::Sera>::AgSrIndexes; }; // ---------------------------------------------------------------------- inline void py_chart(py::module_& mdl) { using namespace pybind11::literals; using namespace acmacs::chart; py::class_<ChartModify, std::shared_ptr<ChartModify>>(mdl, "Chart") // .def(py::init([](const std::string& filename) { return std::make_shared<ChartModify>(import_from_file(filename)); }), py::doc("imports chart from a file")) .def( "clone", // [](ChartModify& chart, const std::string& type) -> std::shared_ptr<ChartModify> { return std::make_shared<ChartClone>(chart, clone_type(type)); }, // "type"_a = "titers", // py::doc(R"(type: "titers", "projections", "plot_spec", "projections_plot_spec")")) // .def( "make_name", // [](const ChartModify& chart) { return chart.make_name(std::nullopt); }, // py::doc("returns name of the chart")) // .def( "make_name", // [](const ChartModify& chart, size_t projection_no) { return chart.make_name(projection_no); }, // "projection_no"_a, // py::doc("returns name of the chart with the stress of the passed projection")) // .def("subtype", [](const ChartModify& chart) { return *chart.info()->virus_type(); }) // .def("subtype_short", [](const ChartModify& chart) { return std::string{chart.info()->virus_type().h_or_b()}; }) // .def("subset", [](const ChartModify& chart) { return chart.info()->subset(); }) // .def("assay", [](const ChartModify& chart) { return *chart.info()->assay(); }) // .def("assay_hi_or_neut", [](const ChartModify& chart) { return chart.info()->assay().hi_or_neut(); }) // .def("lab", [](const ChartModify& chart) { return *chart.info()->lab(); }) // .def("rbc", [](const ChartModify& chart) { return *chart.info()->rbc_species(); }) // .def("date", [](const ChartModify& chart) { return *chart.info()->date(Info::Compute::Yes); }) // .def( "lineage", [](const ChartModify& chart) { return *chart.lineage(); }, py::doc("returns chart lineage: VICTORIA, YAMAGATA")) // .def("description", // &Chart::description, // py::doc("returns chart one line description")) // .def( "make_info", // [](const ChartModify& chart, size_t max_number_of_projections_to_show, bool column_bases, bool tables, bool tables_for_sera, bool antigen_dates) { return chart.make_info(max_number_of_projections_to_show, make_info_data(column_bases, tables, tables_for_sera, antigen_dates)); }, // "max_number_of_projections_to_show"_a = 20, "column_bases"_a = true, "tables"_a = false, "tables_for_sera"_a = false, "antigen_dates"_a = false, // py::doc("returns detailed chart description")) // .def("number_of_antigens", &Chart::number_of_antigens) .def("number_of_sera", &Chart::number_of_sera) .def("number_of_projections", &Chart::number_of_projections) .def( "relax", // [](ChartModify& chart, size_t number_of_dimensions, size_t number_of_optimizations, const std::string& minimum_column_basis, bool dimension_annealing, bool rough, size_t /*number_of_best_distinct_projections_to_keep*/) { if (number_of_optimizations == 0) number_of_optimizations = 100; chart.relax(number_of_optimizations_t{number_of_optimizations}, MinimumColumnBasis{minimum_column_basis}, acmacs::number_of_dimensions_t{number_of_dimensions}, use_dimension_annealing_from_bool(dimension_annealing), optimization_options{optimization_precision{rough ? optimization_precision::rough : optimization_precision::fine}}); chart.projections_modify().sort(); }, // "number_of_dimensions"_a = 2, "number_of_optimizations"_a = 0, "minimum_column_basis"_a = "none", "dimension_annealing"_a = false, "rough"_a = false, "number_of_best_distinct_projections_to_keep"_a = 5, // py::doc{"makes one or more antigenic maps from random starting layouts, adds new projections, projections are sorted by stress"}) // .def( "relax_incremental", // [](ChartModify& chart, size_t number_of_optimizations, bool rough, size_t number_of_best_distinct_projections_to_keep, bool remove_source_projection, bool unmovable_non_nan_points) { if (number_of_optimizations == 0) number_of_optimizations = 100; chart.relax_incremental(0, number_of_optimizations_t{number_of_optimizations}, optimization_options{optimization_precision{rough ? optimization_precision::rough : optimization_precision::fine}}, acmacs::chart::remove_source_projection{remove_source_projection ? acmacs::chart::remove_source_projection::yes : acmacs::chart::remove_source_projection::no}, acmacs::chart::unmovable_non_nan_points{unmovable_non_nan_points ? acmacs::chart::unmovable_non_nan_points::yes : acmacs::chart::unmovable_non_nan_points::no}); chart.projections_modify().sort(); }, // "number_of_optimizations"_a = 0, "rough"_a = false, "number_of_best_distinct_projections_to_keep"_a = 5, "remove_source_projection"_a = true, "unmovable_non_nan_points"_a = false) // .def( "projection", // [](ChartModify& chart, size_t projection_no) { return chart.projection_modify(projection_no); }, // "projection_no"_a = 0) // .def("remove_all_projections", // [](ChartModify& chart) { return chart.projections_modify().remove_all(); }) // .def( "keep_projections", // [](ChartModify& chart, size_t to_keep) { return chart.projections_modify().keep_just(to_keep); }, // "keep"_a) // .def( "export", // [](ChartModify& chart, const std::string& filename, const std::string& program_name) { acmacs::chart::export_factory(chart, filename, program_name); }, // "filename"_a, "program_name"_a) // .def("antigen_indexes", // [](ChartModify& chart) { return std::make_shared<AntigenIndexes>(chart.antigens()); }) // .def("serum_indexes", // [](ChartModify& chart) { return std::make_shared<SerumIndexes>(chart.sera()); }) // .def( "remove_antigens_sera", [](ChartModify& chart, std::shared_ptr<AntigenIndexes> antigens, std::shared_ptr<SerumIndexes> sera, bool remove_projections) { if (remove_projections) chart.projections_modify().remove_all(); if (!antigens->empty()) chart.remove_antigens(acmacs::ReverseSortedIndexes{*antigens->indexes}); if (!sera->empty()) chart.remove_sera(acmacs::ReverseSortedIndexes{*sera->indexes}); }, // "antigens"_a = nullptr, "sera"_a = nullptr, "remove_projections"_a = false) // ; // ---------------------------------------------------------------------- py::class_<ProjectionModify, std::shared_ptr<ProjectionModify>>(mdl, "Projection") // .def( "stress", // [](const ProjectionModify& projection, bool recalculate) { return projection.stress(recalculate ? RecalculateStress::if_necessary : RecalculateStress::no); }, // "recalculate"_a = false) // ; py::class_<AntigenIndexes, std::shared_ptr<AntigenIndexes>>(mdl, "AntigenIndexes") // .def("__str__", [](const AntigenIndexes& indexes) { return fmt::format("AntigenIndexes({}){}", indexes.indexes.size(), indexes.indexes); }) .def("empty", &AntigenIndexes::empty) .def( "filter_lineage", [](AntigenIndexes& indexes, const std::string& lineage) { indexes.ag_sr->filter_lineage(indexes.indexes, acmacs::chart::BLineage{lineage}); return indexes; }, // "lineage"_a) // ; py::class_<SerumIndexes, std::shared_ptr<SerumIndexes>>(mdl, "SerumIndexes") // .def("__str__", [](const SerumIndexes& indexes) { return fmt::format("SerumIndexes({}){}", indexes.indexes.size(), indexes.indexes); }) .def("empty", &SerumIndexes::empty) .def( "filter_lineage", [](SerumIndexes& indexes, const std::string& lineage) { indexes.ag_sr->filter_lineage(indexes.indexes, acmacs::chart::BLineage{lineage}); return indexes; }, // "lineage"_a) // ; } // ====================================================================== inline void py_merge(py::module_& mdl) { using namespace pybind11::literals; using namespace acmacs::chart; mdl.def( "merge", [](std::shared_ptr<ChartModify> chart1, std::shared_ptr<ChartModify> chart2, const std::string& merge_type, const std::string& match, bool remove_distinct) { CommonAntigensSera::match_level_t match_level{CommonAntigensSera::match_level_t::automatic}; if (match == "auto" || match == "automatic") match_level = CommonAntigensSera::match_level_t::automatic; else if (match == "strict") match_level = CommonAntigensSera::match_level_t::strict; else if (match == "relaxed") match_level = CommonAntigensSera::match_level_t::relaxed; else if (match == "ignored") match_level = CommonAntigensSera::match_level_t::ignored; else throw std::invalid_argument{fmt::format("Unrecognized \"match\": \"{}\"", match)}; projection_merge_t merge_typ{projection_merge_t::type1}; if (merge_type == "type1" || merge_type == "tables-only") merge_typ = projection_merge_t::type1; else if (merge_type == "type2" || merge_type == "incremental") merge_typ = projection_merge_t::type2; else if (merge_type == "type3") merge_typ = projection_merge_t::type3; else if (merge_type == "type4") merge_typ = projection_merge_t::type4; else if (merge_type == "type5") merge_typ = projection_merge_t::type5; else throw std::invalid_argument{fmt::format("Unrecognized \"merge_type\": \"{}\"", merge_type)}; return merge(*chart1, *chart2, MergeSettings{match_level, merge_typ, remove_distinct}); }, // "chart1"_a, "chart2"_a, "type"_a, "match"_a = "auto", "remove_distinct"_a = false, // py::doc(R"(merges two charts type: "type1" ("tables-only"), "type2" ("incremental"), "type3", "type4", "type5" see https://github.com/acorg/acmacs-chart-2/blob/master/doc/merge-types.org match: "strict", "relaxed", "ignored", "automatic" ("auto") )")); py::class_<MergeReport>(mdl, "MergeReport") ; } // py_merge // ---------------------------------------------------------------------- // https://pybind11.readthedocs.io/en/latest/faq.html#how-can-i-reduce-the-build-time PYBIND11_MODULE(acmacs, mdl) { mdl.doc() = "Acmacs backend"; py_chart(mdl); py_merge(mdl); } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>py: chart.remove_antigens_sera<commit_after>#include "acmacs-base/pybind11.hh" // chart #include "acmacs-chart-2/factory-import.hh" #include "acmacs-chart-2/factory-export.hh" #include "acmacs-chart-2/chart-modify.hh" // merge #include "acmacs-chart-2/merge.hh" // ====================================================================== inline unsigned make_info_data(bool column_bases, bool tables, bool tables_for_sera, bool antigen_dates) { using namespace acmacs::chart; return (column_bases ? info_data::column_bases : 0) // | (tables ? info_data::tables : 0) // | (tables_for_sera ? info_data::tables_for_sera : 0) // | (antigen_dates ? info_data::dates : 0); } // ---------------------------------------------------------------------- inline acmacs::chart::ChartClone::clone_data clone_type(const std::string& type) { using namespace acmacs::chart; if (type == "titers") return ChartClone::clone_data::titers; else if (type == "projections") return ChartClone::clone_data::projections; else if (type == "plot_spec") return ChartClone::clone_data::plot_spec; else if (type == "projections_plot_spec") return ChartClone::clone_data::projections_plot_spec; else throw std::invalid_argument{fmt::format("Unrecognized clone \"type\": \"{}\"", type)}; } // ---------------------------------------------------------------------- template <typename AgSr> struct AgSrIndexes { AgSrIndexes() = default; AgSrIndexes(std::shared_ptr<AgSr> a_ag_sr) : ag_sr{a_ag_sr}, indexes{a_ag_sr->all_indexes()} {} bool empty() const { return indexes.empty(); } std::shared_ptr<AgSr> ag_sr; acmacs::chart::Indexes indexes; }; struct AntigenIndexes : public AgSrIndexes<acmacs::chart::Antigens> { using AgSrIndexes<acmacs::chart::Antigens>::AgSrIndexes; }; struct SerumIndexes : public AgSrIndexes<acmacs::chart::Sera> { using AgSrIndexes<acmacs::chart::Sera>::AgSrIndexes; }; // ---------------------------------------------------------------------- inline void py_chart(py::module_& mdl) { using namespace pybind11::literals; using namespace acmacs::chart; py::class_<ChartModify, std::shared_ptr<ChartModify>>(mdl, "Chart") // .def(py::init([](const std::string& filename) { return std::make_shared<ChartModify>(import_from_file(filename)); }), py::doc("imports chart from a file")) .def( "clone", // [](ChartModify& chart, const std::string& type) -> std::shared_ptr<ChartModify> { return std::make_shared<ChartClone>(chart, clone_type(type)); }, // "type"_a = "titers", // py::doc(R"(type: "titers", "projections", "plot_spec", "projections_plot_spec")")) // .def( "make_name", // [](const ChartModify& chart) { return chart.make_name(std::nullopt); }, // py::doc("returns name of the chart")) // .def( "make_name", // [](const ChartModify& chart, size_t projection_no) { return chart.make_name(projection_no); }, // "projection_no"_a, // py::doc("returns name of the chart with the stress of the passed projection")) // .def("subtype", [](const ChartModify& chart) { return *chart.info()->virus_type(); }) // .def("subtype_short", [](const ChartModify& chart) { return std::string{chart.info()->virus_type().h_or_b()}; }) // .def("subset", [](const ChartModify& chart) { return chart.info()->subset(); }) // .def("assay", [](const ChartModify& chart) { return *chart.info()->assay(); }) // .def("assay_hi_or_neut", [](const ChartModify& chart) { return chart.info()->assay().hi_or_neut(); }) // .def("lab", [](const ChartModify& chart) { return *chart.info()->lab(); }) // .def("rbc", [](const ChartModify& chart) { return *chart.info()->rbc_species(); }) // .def("date", [](const ChartModify& chart) { return *chart.info()->date(Info::Compute::Yes); }) // .def( "lineage", [](const ChartModify& chart) { return *chart.lineage(); }, py::doc("returns chart lineage: VICTORIA, YAMAGATA")) // .def("description", // &Chart::description, // py::doc("returns chart one line description")) // .def( "make_info", // [](const ChartModify& chart, size_t max_number_of_projections_to_show, bool column_bases, bool tables, bool tables_for_sera, bool antigen_dates) { return chart.make_info(max_number_of_projections_to_show, make_info_data(column_bases, tables, tables_for_sera, antigen_dates)); }, // "max_number_of_projections_to_show"_a = 20, "column_bases"_a = true, "tables"_a = false, "tables_for_sera"_a = false, "antigen_dates"_a = false, // py::doc("returns detailed chart description")) // .def("number_of_antigens", &Chart::number_of_antigens) .def("number_of_sera", &Chart::number_of_sera) .def("number_of_projections", &Chart::number_of_projections) .def( "relax", // [](ChartModify& chart, size_t number_of_dimensions, size_t number_of_optimizations, const std::string& minimum_column_basis, bool dimension_annealing, bool rough, size_t /*number_of_best_distinct_projections_to_keep*/) { if (number_of_optimizations == 0) number_of_optimizations = 100; chart.relax(number_of_optimizations_t{number_of_optimizations}, MinimumColumnBasis{minimum_column_basis}, acmacs::number_of_dimensions_t{number_of_dimensions}, use_dimension_annealing_from_bool(dimension_annealing), optimization_options{optimization_precision{rough ? optimization_precision::rough : optimization_precision::fine}}); chart.projections_modify().sort(); }, // "number_of_dimensions"_a = 2, "number_of_optimizations"_a = 0, "minimum_column_basis"_a = "none", "dimension_annealing"_a = false, "rough"_a = false, "number_of_best_distinct_projections_to_keep"_a = 5, // py::doc{"makes one or more antigenic maps from random starting layouts, adds new projections, projections are sorted by stress"}) // .def( "relax_incremental", // [](ChartModify& chart, size_t number_of_optimizations, bool rough, size_t number_of_best_distinct_projections_to_keep, bool remove_source_projection, bool unmovable_non_nan_points) { if (number_of_optimizations == 0) number_of_optimizations = 100; chart.relax_incremental(0, number_of_optimizations_t{number_of_optimizations}, optimization_options{optimization_precision{rough ? optimization_precision::rough : optimization_precision::fine}}, acmacs::chart::remove_source_projection{remove_source_projection ? acmacs::chart::remove_source_projection::yes : acmacs::chart::remove_source_projection::no}, acmacs::chart::unmovable_non_nan_points{unmovable_non_nan_points ? acmacs::chart::unmovable_non_nan_points::yes : acmacs::chart::unmovable_non_nan_points::no}); chart.projections_modify().sort(); }, // "number_of_optimizations"_a = 0, "rough"_a = false, "number_of_best_distinct_projections_to_keep"_a = 5, "remove_source_projection"_a = true, "unmovable_non_nan_points"_a = false) // .def( "projection", // [](ChartModify& chart, size_t projection_no) { return chart.projection_modify(projection_no); }, // "projection_no"_a = 0) // .def("remove_all_projections", // [](ChartModify& chart) { return chart.projections_modify().remove_all(); }) // .def( "keep_projections", // [](ChartModify& chart, size_t to_keep) { return chart.projections_modify().keep_just(to_keep); }, // "keep"_a) // .def( "export", // [](ChartModify& chart, const std::string& filename, const std::string& program_name) { acmacs::chart::export_factory(chart, filename, program_name); }, // "filename"_a, "program_name"_a) // .def("antigen_indexes", // [](ChartModify& chart) { return std::make_shared<AntigenIndexes>(chart.antigens()); }) // .def("serum_indexes", // [](ChartModify& chart) { return std::make_shared<SerumIndexes>(chart.sera()); }) // .def( "remove_antigens_sera", [](ChartModify& chart, std::shared_ptr<AntigenIndexes> antigens, std::shared_ptr<SerumIndexes> sera, bool remove_projections) { if (remove_projections) chart.projections_modify().remove_all(); if (!antigens->empty()) chart.remove_antigens(acmacs::ReverseSortedIndexes{*antigens->indexes}); if (!sera->empty()) chart.remove_sera(acmacs::ReverseSortedIndexes{*sera->indexes}); }, // "antigens"_a = nullptr, "sera"_a = nullptr, "remove_projections"_a = false, // py::doc("Usage:\nchart.remove_antigens_sera(antigens=c.antigen_indexes().filter_lineage(\"yamagata\"), sera=c.serum_indexes().filter_lineage(\"yamagata\"))")) // ; // ---------------------------------------------------------------------- py::class_<ProjectionModify, std::shared_ptr<ProjectionModify>>(mdl, "Projection") // .def( "stress", // [](const ProjectionModify& projection, bool recalculate) { return projection.stress(recalculate ? RecalculateStress::if_necessary : RecalculateStress::no); }, // "recalculate"_a = false) // ; py::class_<AntigenIndexes, std::shared_ptr<AntigenIndexes>>(mdl, "AntigenIndexes") // .def("__str__", [](const AntigenIndexes& indexes) { return fmt::format("AntigenIndexes({}){}", indexes.indexes.size(), indexes.indexes); }) .def("empty", &AntigenIndexes::empty) .def( "filter_lineage", [](AntigenIndexes& indexes, const std::string& lineage) { indexes.ag_sr->filter_lineage(indexes.indexes, acmacs::chart::BLineage{lineage}); return indexes; }, // "lineage"_a) // ; py::class_<SerumIndexes, std::shared_ptr<SerumIndexes>>(mdl, "SerumIndexes") // .def("__str__", [](const SerumIndexes& indexes) { return fmt::format("SerumIndexes({}){}", indexes.indexes.size(), indexes.indexes); }) .def("empty", &SerumIndexes::empty) .def( "filter_lineage", [](SerumIndexes& indexes, const std::string& lineage) { indexes.ag_sr->filter_lineage(indexes.indexes, acmacs::chart::BLineage{lineage}); return indexes; }, // "lineage"_a) // ; } // ====================================================================== inline void py_merge(py::module_& mdl) { using namespace pybind11::literals; using namespace acmacs::chart; mdl.def( "merge", [](std::shared_ptr<ChartModify> chart1, std::shared_ptr<ChartModify> chart2, const std::string& merge_type, const std::string& match, bool remove_distinct) { CommonAntigensSera::match_level_t match_level{CommonAntigensSera::match_level_t::automatic}; if (match == "auto" || match == "automatic") match_level = CommonAntigensSera::match_level_t::automatic; else if (match == "strict") match_level = CommonAntigensSera::match_level_t::strict; else if (match == "relaxed") match_level = CommonAntigensSera::match_level_t::relaxed; else if (match == "ignored") match_level = CommonAntigensSera::match_level_t::ignored; else throw std::invalid_argument{fmt::format("Unrecognized \"match\": \"{}\"", match)}; projection_merge_t merge_typ{projection_merge_t::type1}; if (merge_type == "type1" || merge_type == "tables-only") merge_typ = projection_merge_t::type1; else if (merge_type == "type2" || merge_type == "incremental") merge_typ = projection_merge_t::type2; else if (merge_type == "type3") merge_typ = projection_merge_t::type3; else if (merge_type == "type4") merge_typ = projection_merge_t::type4; else if (merge_type == "type5") merge_typ = projection_merge_t::type5; else throw std::invalid_argument{fmt::format("Unrecognized \"merge_type\": \"{}\"", merge_type)}; return merge(*chart1, *chart2, MergeSettings{match_level, merge_typ, remove_distinct}); }, // "chart1"_a, "chart2"_a, "type"_a, "match"_a = "auto", "remove_distinct"_a = false, // py::doc(R"(merges two charts type: "type1" ("tables-only"), "type2" ("incremental"), "type3", "type4", "type5" see https://github.com/acorg/acmacs-chart-2/blob/master/doc/merge-types.org match: "strict", "relaxed", "ignored", "automatic" ("auto") )")); py::class_<MergeReport>(mdl, "MergeReport") ; } // py_merge // ---------------------------------------------------------------------- // https://pybind11.readthedocs.io/en/latest/faq.html#how-can-i-reduce-the-build-time PYBIND11_MODULE(acmacs, mdl) { mdl.doc() = "Acmacs backend"; py_chart(mdl); py_merge(mdl); } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the ** following disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ #include "CodeComposite.h" #include "Export/src/tree/CompositeFragment.h" #include "OOModel/src/declarations/Class.h" namespace CppExport { CodeComposite::CodeComposite(const QString& name) : name_{name} {} void CodeComposite::addUnit(CodeUnit* unit) { units_.append(unit); // assert every unit belongs to only one composite Q_ASSERT(!unit->composite()); unit->setComposite(this); } QString CodeComposite::relativePath(CodeComposite* other) { QStringList otherName = other->name().split("/"); if (name() == other->name()) return otherName.last(); QStringList thisName = name().split("/"); while (!thisName.empty() && !otherName.empty() && thisName.first() == otherName.first()) { thisName.takeFirst(); otherName.takeFirst(); } int backSteps = thisName.size() - otherName.size(); for (auto i = 0; i < backSteps; i++) otherName.prepend(".."); return otherName.join("/"); } QSet<Model::Node*> CodeComposite::reduceSoftDependencies(QSet<CodeComposite*> hardDependencies, QSet<Model::Node*> softDependencies) { auto result = softDependencies; auto workList = QList<CodeComposite*>::fromSet(hardDependencies); QSet<CodeComposite*> processed; while (!workList.empty()) { auto hardDependency = workList.takeFirst(); if (!processed.contains(hardDependency)) { for (auto unit : hardDependency->units()) { for (auto transitiveDependencyHeaderPart : unit->headerPart()->dependencies()) workList.append(transitiveDependencyHeaderPart->parent()->composite()); for (auto softDependency : softDependencies) if (result.contains(softDependency)) if (unit->node() == softDependency || unit->node()->isAncestorOf(softDependency)) result.remove(softDependency); } processed.insert(hardDependency); } } return result; } Export::SourceFragment* CodeComposite::partFragment(CodeUnitPart* (CodeUnit::*part) ()) { Q_ASSERT(!units().empty()); QSet<CodeComposite*> compositeDependencies; for (auto unit : units()) for (CodeUnitPart* dependency : (unit->*part)()->dependencies()) { if (!dependency->parent()->composite()->name().isEmpty()) // skip ExternalMacros compositeDependencies.insert(dependency->parent()->composite()); } if ((units().first()->*part)() == units().first()->headerPart()) { compositeDependencies.insert(new CodeComposite("Core/src/core_api")); compositeDependencies.remove(this); } auto composite = new Export::CompositeFragment(units().first()->node()); if (!compositeDependencies.empty()) { for (auto compositeDependency : compositeDependencies) *composite << "#include \"" + relativePath(compositeDependency) + ".h\"\n"; *composite << "\n"; } Export::CompositeFragment* unitsComposite = nullptr; if (!units().isEmpty()) { unitsComposite = new Export::CompositeFragment(units().first()->node(), "spacedSections"); OOModel::Module* currentNamespace{}; for (auto unit : units()) { auto codeUnitPart = (unit->*part)(); if (codeUnitPart->isSourceFragmentEmpty()) continue; auto neededNamespace = unit->node()->firstAncestorOfType<OOModel::Module>(); if (neededNamespace != currentNamespace) { if (currentNamespace) *unitsComposite << "\n}\n\n"; if (neededNamespace) { auto namespaceComposite = new Export::CompositeFragment(unitsComposite->node()); *namespaceComposite << "namespace " << neededNamespace->symbolName() << " {\n\n"; unitsComposite->append(namespaceComposite); } currentNamespace = neededNamespace; } auto softDependenciesReduced = reduceSoftDependencies(compositeDependencies, codeUnitPart->softDependencies()); if (!softDependenciesReduced.empty()) { auto softDependencyComposite = new Export::CompositeFragment(units().first()->node()); for (auto softDependency : softDependenciesReduced) { if (auto classs = DCast<OOModel::Class>(softDependency)) { if (OOModel::Class::ConstructKind::Class == classs->constructKind()) *softDependencyComposite << "class "; else if (OOModel::Class::ConstructKind::Struct == classs->constructKind()) *softDependencyComposite << "struct "; else if (OOModel::Class::ConstructKind::Enum == classs->constructKind()) *softDependencyComposite << "enum "; else Q_ASSERT(false); *softDependencyComposite << softDependency->symbolName() + ";\n"; } } *unitsComposite << softDependencyComposite; } unitsComposite->append(codeUnitPart->sourceFragment()); } if (currentNamespace) *unitsComposite << "\n}"; } if (unitsComposite && !unitsComposite->fragments().empty()) { composite->append(unitsComposite); return composite; } SAFE_DELETE(unitsComposite); SAFE_DELETE(composite); return nullptr; } Export::SourceFragment* CodeComposite::addPragmaOnce(Export::SourceFragment* fragment) { auto compositeFragment = new Export::CompositeFragment(fragment->node()); *compositeFragment << "#pragma once\n\n" << fragment; return compositeFragment; } void CodeComposite::sortUnitsByHeaderPartDependencies() { if (units().size() <= 1) return; QHash<CodeUnitPart*, QSet<CodeUnitPart*>> headerPartDependencies; for (auto unit : units()) headerPartDependencies.insert(unit->headerPart(), unit->headerPart()->dependencies()); units_.clear(); for (auto headerPart : topologicalSort(headerPartDependencies)) units_.append(headerPart->parent()); } void CodeComposite::sortUnitsBySourcePartDependencies() { if (units().size() <= 1) return; QHash<CodeUnitPart*, QSet<CodeUnitPart*>> sourcePartDependencies; for (auto unit : units()) { sourcePartDependencies[unit->sourcePart()] = {}; for (auto referenceNode : unit->sourcePart()->referenceNodes()) if (auto target = referenceNode->target()) for (auto otherUnit : units()) if (otherUnit->sourcePart() != unit->sourcePart() && otherUnit->sourcePart()->nameNodes().contains(target)) sourcePartDependencies[unit->sourcePart()].insert(otherUnit->sourcePart()); } units_.clear(); for (auto sourcePart : topologicalSort(sourcePartDependencies)) units_.append(sourcePart->parent()); } void CodeComposite::fragments(Export::SourceFragment*& header, Export::SourceFragment*& source) { sortUnitsByHeaderPartDependencies(); header = headerFragment(); sortUnitsBySourcePartDependencies(); source = sourceFragment(); } template <typename T> QList<T*> CodeComposite::topologicalSort(QHash<T*, QSet<T*>> dependsOn) { // calculate a list of elements with no dependencies. // calculate a map that maps from an element to all elements that depend on it. QList<T*> noPendingDependencies; QHash<T*, QSet<T*>> neededFor; for (auto it = dependsOn.begin(); it != dependsOn.end(); it++) if (it.value().empty()) // this element depends on no other elements noPendingDependencies.append(it.key()); else { // for every other element this element depends on add it to the neededFor map for said other element bool notNeededForAnything = true; for (auto dependency : it.value()) if (dependsOn.contains(dependency)) { neededFor[dependency].insert(it.key()); notNeededForAnything = false; } if (notNeededForAnything) noPendingDependencies.append(it.key()); } QList<T*> result; while (!noPendingDependencies.empty()) { // take any item form the list of item with no more dependencies and add it to the result auto n = noPendingDependencies.takeFirst(); result.append(n); // check if we are neededFor another node auto it = neededFor.find(n); if (it == neededFor.end()) continue; // for every node we are neededFor for (auto m : *it) { // find the nodes the node we are needed for dependsOn auto dIt = dependsOn.find(m); Q_ASSERT(dIt != dependsOn.end()); // remove us from its dependencies dIt->remove(n); // if this node has no more dependencies add it to the list of items with no more dependencies bool noPendingDependency = true; for (auto d : *dIt) if (dependsOn.contains(d)) { noPendingDependency = false; break; } if (noPendingDependency) noPendingDependencies.append(m); } } // test graph for cycles for (auto dependencies : dependsOn.values()) Q_ASSERT(dependencies.empty()); return result; } } <commit_msg>remove unnecessary check<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the ** following disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ #include "CodeComposite.h" #include "Export/src/tree/CompositeFragment.h" #include "OOModel/src/declarations/Class.h" namespace CppExport { CodeComposite::CodeComposite(const QString& name) : name_{name} {} void CodeComposite::addUnit(CodeUnit* unit) { units_.append(unit); // assert every unit belongs to only one composite Q_ASSERT(!unit->composite()); unit->setComposite(this); } QString CodeComposite::relativePath(CodeComposite* other) { QStringList otherName = other->name().split("/"); if (name() == other->name()) return otherName.last(); QStringList thisName = name().split("/"); while (!thisName.empty() && !otherName.empty() && thisName.first() == otherName.first()) { thisName.takeFirst(); otherName.takeFirst(); } int backSteps = thisName.size() - otherName.size(); for (auto i = 0; i < backSteps; i++) otherName.prepend(".."); return otherName.join("/"); } QSet<Model::Node*> CodeComposite::reduceSoftDependencies(QSet<CodeComposite*> hardDependencies, QSet<Model::Node*> softDependencies) { auto result = softDependencies; auto workList = QList<CodeComposite*>::fromSet(hardDependencies); QSet<CodeComposite*> processed; while (!workList.empty()) { auto hardDependency = workList.takeFirst(); if (!processed.contains(hardDependency)) { for (auto unit : hardDependency->units()) { for (auto transitiveDependencyHeaderPart : unit->headerPart()->dependencies()) workList.append(transitiveDependencyHeaderPart->parent()->composite()); for (auto softDependency : softDependencies) if (result.contains(softDependency)) if (unit->node() == softDependency || unit->node()->isAncestorOf(softDependency)) result.remove(softDependency); } processed.insert(hardDependency); } } return result; } Export::SourceFragment* CodeComposite::partFragment(CodeUnitPart* (CodeUnit::*part) ()) { Q_ASSERT(!units().empty()); QSet<CodeComposite*> compositeDependencies; for (auto unit : units()) for (CodeUnitPart* dependency : (unit->*part)()->dependencies()) compositeDependencies.insert(dependency->parent()->composite()); if ((units().first()->*part)() == units().first()->headerPart()) { compositeDependencies.insert(new CodeComposite("Core/src/core_api")); compositeDependencies.remove(this); } auto composite = new Export::CompositeFragment(units().first()->node()); if (!compositeDependencies.empty()) { for (auto compositeDependency : compositeDependencies) *composite << "#include \"" + relativePath(compositeDependency) + ".h\"\n"; *composite << "\n"; } Export::CompositeFragment* unitsComposite = nullptr; if (!units().isEmpty()) { unitsComposite = new Export::CompositeFragment(units().first()->node(), "spacedSections"); OOModel::Module* currentNamespace{}; for (auto unit : units()) { auto codeUnitPart = (unit->*part)(); if (codeUnitPart->isSourceFragmentEmpty()) continue; auto neededNamespace = unit->node()->firstAncestorOfType<OOModel::Module>(); if (neededNamespace != currentNamespace) { if (currentNamespace) *unitsComposite << "\n}\n\n"; if (neededNamespace) { auto namespaceComposite = new Export::CompositeFragment(unitsComposite->node()); *namespaceComposite << "namespace " << neededNamespace->symbolName() << " {\n\n"; unitsComposite->append(namespaceComposite); } currentNamespace = neededNamespace; } auto softDependenciesReduced = reduceSoftDependencies(compositeDependencies, codeUnitPart->softDependencies()); if (!softDependenciesReduced.empty()) { auto softDependencyComposite = new Export::CompositeFragment(units().first()->node()); for (auto softDependency : softDependenciesReduced) { if (auto classs = DCast<OOModel::Class>(softDependency)) { if (OOModel::Class::ConstructKind::Class == classs->constructKind()) *softDependencyComposite << "class "; else if (OOModel::Class::ConstructKind::Struct == classs->constructKind()) *softDependencyComposite << "struct "; else if (OOModel::Class::ConstructKind::Enum == classs->constructKind()) *softDependencyComposite << "enum "; else Q_ASSERT(false); *softDependencyComposite << softDependency->symbolName() + ";\n"; } } *unitsComposite << softDependencyComposite; } unitsComposite->append(codeUnitPart->sourceFragment()); } if (currentNamespace) *unitsComposite << "\n}"; } if (unitsComposite && !unitsComposite->fragments().empty()) { composite->append(unitsComposite); return composite; } SAFE_DELETE(unitsComposite); SAFE_DELETE(composite); return nullptr; } Export::SourceFragment* CodeComposite::addPragmaOnce(Export::SourceFragment* fragment) { auto compositeFragment = new Export::CompositeFragment(fragment->node()); *compositeFragment << "#pragma once\n\n" << fragment; return compositeFragment; } void CodeComposite::sortUnitsByHeaderPartDependencies() { if (units().size() <= 1) return; QHash<CodeUnitPart*, QSet<CodeUnitPart*>> headerPartDependencies; for (auto unit : units()) headerPartDependencies.insert(unit->headerPart(), unit->headerPart()->dependencies()); units_.clear(); for (auto headerPart : topologicalSort(headerPartDependencies)) units_.append(headerPart->parent()); } void CodeComposite::sortUnitsBySourcePartDependencies() { if (units().size() <= 1) return; QHash<CodeUnitPart*, QSet<CodeUnitPart*>> sourcePartDependencies; for (auto unit : units()) { sourcePartDependencies[unit->sourcePart()] = {}; for (auto referenceNode : unit->sourcePart()->referenceNodes()) if (auto target = referenceNode->target()) for (auto otherUnit : units()) if (otherUnit->sourcePart() != unit->sourcePart() && otherUnit->sourcePart()->nameNodes().contains(target)) sourcePartDependencies[unit->sourcePart()].insert(otherUnit->sourcePart()); } units_.clear(); for (auto sourcePart : topologicalSort(sourcePartDependencies)) units_.append(sourcePart->parent()); } void CodeComposite::fragments(Export::SourceFragment*& header, Export::SourceFragment*& source) { sortUnitsByHeaderPartDependencies(); header = headerFragment(); sortUnitsBySourcePartDependencies(); source = sourceFragment(); } template <typename T> QList<T*> CodeComposite::topologicalSort(QHash<T*, QSet<T*>> dependsOn) { // calculate a list of elements with no dependencies. // calculate a map that maps from an element to all elements that depend on it. QList<T*> noPendingDependencies; QHash<T*, QSet<T*>> neededFor; for (auto it = dependsOn.begin(); it != dependsOn.end(); it++) if (it.value().empty()) // this element depends on no other elements noPendingDependencies.append(it.key()); else { // for every other element this element depends on add it to the neededFor map for said other element bool notNeededForAnything = true; for (auto dependency : it.value()) if (dependsOn.contains(dependency)) { neededFor[dependency].insert(it.key()); notNeededForAnything = false; } if (notNeededForAnything) noPendingDependencies.append(it.key()); } QList<T*> result; while (!noPendingDependencies.empty()) { // take any item form the list of item with no more dependencies and add it to the result auto n = noPendingDependencies.takeFirst(); result.append(n); // check if we are neededFor another node auto it = neededFor.find(n); if (it == neededFor.end()) continue; // for every node we are neededFor for (auto m : *it) { // find the nodes the node we are needed for dependsOn auto dIt = dependsOn.find(m); Q_ASSERT(dIt != dependsOn.end()); // remove us from its dependencies dIt->remove(n); // if this node has no more dependencies add it to the list of items with no more dependencies bool noPendingDependency = true; for (auto d : *dIt) if (dependsOn.contains(d)) { noPendingDependency = false; break; } if (noPendingDependency) noPendingDependencies.append(m); } } // test graph for cycles for (auto dependencies : dependsOn.values()) Q_ASSERT(dependencies.empty()); return result; } } <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "attribute_manager_initializer.h" #include "attributes_initializer_base.h" #include "attribute_collection_spec_factory.h" #include <vespa/searchcorespi/index/i_thread_service.h> #include <future> using search::AttributeVector; using search::GrowStrategy; using search::SerialNum; using vespa::config::search::AttributesConfig; namespace proton { using initializer::InitializerTask; namespace { class AttributeInitializerTask : public InitializerTask { private: AttributeInitializer::UP _initializer; DocumentMetaStore::SP _documentMetaStore; InitializedAttributesResult &_result; public: AttributeInitializerTask(AttributeInitializer::UP initializer, DocumentMetaStore::SP documentMetaStore, InitializedAttributesResult &result) : _initializer(std::move(initializer)), _documentMetaStore(documentMetaStore), _result(result) {} void run() override { AttributeInitializerResult result = _initializer->init(); if (result) { AttributesInitializerBase::considerPadAttribute(*result.getAttribute(), _initializer->getCurrentSerialNum(), _documentMetaStore->getCommittedDocIdLimit()); _result.add(result); } } }; class AttributeManagerInitializerTask : public vespalib::Executor::Task { std::promise<void> _promise; search::SerialNum _configSerialNum; DocumentMetaStore::SP _documentMetaStore; AttributeManager::SP _attrMgr; InitializedAttributesResult &_attributesResult; public: AttributeManagerInitializerTask(std::promise<void> &&promise, search::SerialNum configSerialNum, DocumentMetaStore::SP documentMetaStore, AttributeManager::SP attrMgr, InitializedAttributesResult &attributesResult); ~AttributeManagerInitializerTask() override; void run() override; }; AttributeManagerInitializerTask::AttributeManagerInitializerTask(std::promise<void> &&promise, search::SerialNum configSerialNum, DocumentMetaStore::SP documentMetaStore, AttributeManager::SP attrMgr, InitializedAttributesResult &attributesResult) : _promise(std::move(promise)), _configSerialNum(configSerialNum), _documentMetaStore(documentMetaStore), _attrMgr(attrMgr), _attributesResult(attributesResult) { } AttributeManagerInitializerTask::~AttributeManagerInitializerTask() { } void AttributeManagerInitializerTask::run() { _attrMgr->addExtraAttribute(_documentMetaStore); _attrMgr->addInitializedAttributes(_attributesResult.get()); _attrMgr->pruneRemovedFields(_configSerialNum); _promise.set_value(); } class AttributeInitializerTasksBuilder : public IAttributeInitializerRegistry { private: InitializerTask &_attrMgrInitTask; InitializerTask::SP _documentMetaStoreInitTask; DocumentMetaStore::SP _documentMetaStore; InitializedAttributesResult &_attributesResult; public: AttributeInitializerTasksBuilder(InitializerTask &attrMgrInitTask, InitializerTask::SP documentMetaStoreInitTask, DocumentMetaStore::SP documentMetaStore, InitializedAttributesResult &attributesResult); ~AttributeInitializerTasksBuilder(); void add(AttributeInitializer::UP initializer) override; }; AttributeInitializerTasksBuilder::AttributeInitializerTasksBuilder(InitializerTask &attrMgrInitTask, InitializerTask::SP documentMetaStoreInitTask, DocumentMetaStore::SP documentMetaStore, InitializedAttributesResult &attributesResult) : _attrMgrInitTask(attrMgrInitTask), _documentMetaStoreInitTask(documentMetaStoreInitTask), _documentMetaStore(documentMetaStore), _attributesResult(attributesResult) { } AttributeInitializerTasksBuilder::~AttributeInitializerTasksBuilder() {} void AttributeInitializerTasksBuilder::add(AttributeInitializer::UP initializer) { InitializerTask::SP attributeInitTask = std::make_shared<AttributeInitializerTask>(std::move(initializer), _documentMetaStore, _attributesResult); attributeInitTask->addDependency(_documentMetaStoreInitTask); _attrMgrInitTask.addDependency(attributeInitTask); } } AttributeCollectionSpec::UP AttributeManagerInitializer::createAttributeSpec() const { uint32_t docIdLimit = 1; // The real docIdLimit is used after attributes are loaded to pad them AttributeCollectionSpecFactory factory(_attributeGrow, _attributeGrowNumDocs, _fastAccessAttributesOnly); return factory.create(_attrCfg, docIdLimit, _configSerialNum); } AttributeManagerInitializer::AttributeManagerInitializer(SerialNum configSerialNum, initializer::InitializerTask::SP documentMetaStoreInitTask, DocumentMetaStore::SP documentMetaStore, AttributeManager::SP baseAttrMgr, const AttributesConfig &attrCfg, const GrowStrategy &attributeGrow, size_t attributeGrowNumDocs, bool fastAccessAttributesOnly, searchcorespi::index::IThreadService &master, std::shared_ptr<AttributeManager::SP> attrMgrResult) : _configSerialNum(configSerialNum), _documentMetaStore(documentMetaStore), _attrMgr(), _attrCfg(attrCfg), _attributeGrow(attributeGrow), _attributeGrowNumDocs(attributeGrowNumDocs), _fastAccessAttributesOnly(fastAccessAttributesOnly), _master(master), _attributesResult(), _attrMgrResult(attrMgrResult) { addDependency(documentMetaStoreInitTask); AttributeInitializerTasksBuilder tasksBuilder(*this, documentMetaStoreInitTask, documentMetaStore, _attributesResult); AttributeCollectionSpec::UP attrSpec = createAttributeSpec(); _attrMgr = std::make_shared<AttributeManager>(*baseAttrMgr, *attrSpec, tasksBuilder); } void AttributeManagerInitializer::run() { std::promise<void> promise; auto future = promise.get_future(); /* * Attribute manager and some its members (e.g. _attributeFieldWriter) assumes that work is performed * by document db master thread and lacks locking to handle calls from multiple threads. */ _master.execute(std::make_unique<AttributeManagerInitializerTask>(std::move(promise), _configSerialNum, _documentMetaStore, _attrMgr, _attributesResult)); future.wait(); *_attrMgrResult = _attrMgr; } } // namespace proton <commit_msg>= default<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "attribute_manager_initializer.h" #include "attributes_initializer_base.h" #include "attribute_collection_spec_factory.h" #include <vespa/searchcorespi/index/i_thread_service.h> #include <future> using search::AttributeVector; using search::GrowStrategy; using search::SerialNum; using vespa::config::search::AttributesConfig; namespace proton { using initializer::InitializerTask; namespace { class AttributeInitializerTask : public InitializerTask { private: AttributeInitializer::UP _initializer; DocumentMetaStore::SP _documentMetaStore; InitializedAttributesResult &_result; public: AttributeInitializerTask(AttributeInitializer::UP initializer, DocumentMetaStore::SP documentMetaStore, InitializedAttributesResult &result) : _initializer(std::move(initializer)), _documentMetaStore(documentMetaStore), _result(result) {} void run() override { AttributeInitializerResult result = _initializer->init(); if (result) { AttributesInitializerBase::considerPadAttribute(*result.getAttribute(), _initializer->getCurrentSerialNum(), _documentMetaStore->getCommittedDocIdLimit()); _result.add(result); } } }; class AttributeManagerInitializerTask : public vespalib::Executor::Task { std::promise<void> _promise; search::SerialNum _configSerialNum; DocumentMetaStore::SP _documentMetaStore; AttributeManager::SP _attrMgr; InitializedAttributesResult &_attributesResult; public: AttributeManagerInitializerTask(std::promise<void> &&promise, search::SerialNum configSerialNum, DocumentMetaStore::SP documentMetaStore, AttributeManager::SP attrMgr, InitializedAttributesResult &attributesResult); ~AttributeManagerInitializerTask() override; void run() override; }; AttributeManagerInitializerTask::AttributeManagerInitializerTask(std::promise<void> &&promise, search::SerialNum configSerialNum, DocumentMetaStore::SP documentMetaStore, AttributeManager::SP attrMgr, InitializedAttributesResult &attributesResult) : _promise(std::move(promise)), _configSerialNum(configSerialNum), _documentMetaStore(documentMetaStore), _attrMgr(attrMgr), _attributesResult(attributesResult) { } AttributeManagerInitializerTask::~AttributeManagerInitializerTask() = default; void AttributeManagerInitializerTask::run() { _attrMgr->addExtraAttribute(_documentMetaStore); _attrMgr->addInitializedAttributes(_attributesResult.get()); _attrMgr->pruneRemovedFields(_configSerialNum); _promise.set_value(); } class AttributeInitializerTasksBuilder : public IAttributeInitializerRegistry { private: InitializerTask &_attrMgrInitTask; InitializerTask::SP _documentMetaStoreInitTask; DocumentMetaStore::SP _documentMetaStore; InitializedAttributesResult &_attributesResult; public: AttributeInitializerTasksBuilder(InitializerTask &attrMgrInitTask, InitializerTask::SP documentMetaStoreInitTask, DocumentMetaStore::SP documentMetaStore, InitializedAttributesResult &attributesResult); ~AttributeInitializerTasksBuilder(); void add(AttributeInitializer::UP initializer) override; }; AttributeInitializerTasksBuilder::AttributeInitializerTasksBuilder(InitializerTask &attrMgrInitTask, InitializerTask::SP documentMetaStoreInitTask, DocumentMetaStore::SP documentMetaStore, InitializedAttributesResult &attributesResult) : _attrMgrInitTask(attrMgrInitTask), _documentMetaStoreInitTask(documentMetaStoreInitTask), _documentMetaStore(documentMetaStore), _attributesResult(attributesResult) { } AttributeInitializerTasksBuilder::~AttributeInitializerTasksBuilder() = default; void AttributeInitializerTasksBuilder::add(AttributeInitializer::UP initializer) { InitializerTask::SP attributeInitTask = std::make_shared<AttributeInitializerTask>(std::move(initializer), _documentMetaStore, _attributesResult); attributeInitTask->addDependency(_documentMetaStoreInitTask); _attrMgrInitTask.addDependency(attributeInitTask); } } AttributeCollectionSpec::UP AttributeManagerInitializer::createAttributeSpec() const { uint32_t docIdLimit = 1; // The real docIdLimit is used after attributes are loaded to pad them AttributeCollectionSpecFactory factory(_attributeGrow, _attributeGrowNumDocs, _fastAccessAttributesOnly); return factory.create(_attrCfg, docIdLimit, _configSerialNum); } AttributeManagerInitializer::AttributeManagerInitializer(SerialNum configSerialNum, initializer::InitializerTask::SP documentMetaStoreInitTask, DocumentMetaStore::SP documentMetaStore, AttributeManager::SP baseAttrMgr, const AttributesConfig &attrCfg, const GrowStrategy &attributeGrow, size_t attributeGrowNumDocs, bool fastAccessAttributesOnly, searchcorespi::index::IThreadService &master, std::shared_ptr<AttributeManager::SP> attrMgrResult) : _configSerialNum(configSerialNum), _documentMetaStore(documentMetaStore), _attrMgr(), _attrCfg(attrCfg), _attributeGrow(attributeGrow), _attributeGrowNumDocs(attributeGrowNumDocs), _fastAccessAttributesOnly(fastAccessAttributesOnly), _master(master), _attributesResult(), _attrMgrResult(attrMgrResult) { addDependency(documentMetaStoreInitTask); AttributeInitializerTasksBuilder tasksBuilder(*this, documentMetaStoreInitTask, documentMetaStore, _attributesResult); AttributeCollectionSpec::UP attrSpec = createAttributeSpec(); _attrMgr = std::make_shared<AttributeManager>(*baseAttrMgr, *attrSpec, tasksBuilder); } void AttributeManagerInitializer::run() { std::promise<void> promise; auto future = promise.get_future(); /* * Attribute manager and some its members (e.g. _attributeFieldWriter) assumes that work is performed * by document db master thread and lacks locking to handle calls from multiple threads. */ _master.execute(std::make_unique<AttributeManagerInitializerTask>(std::move(promise), _configSerialNum, _documentMetaStore, _attrMgr, _attributesResult)); future.wait(); *_attrMgrResult = _attrMgr; } } // namespace proton <|endoftext|>
<commit_before> #include "deferred_allocator.h" using namespace gcpp; #include <iostream> #include <iomanip> #include <memory> #include <vector> #include <algorithm> using namespace std; class Counter { public: Counter() { ++count_; } ~Counter() { --count_; } static int count() { return count_; } private: static int count_; }; int Counter::count_ = 0; /*--- Solution 1 (default) ---------------------------------------------------- class MyGraph { public: class Node : public Counter { vector<shared_ptr<Node>> children; public: void AddChild(const shared_ptr<Node>& node) { children.push_back(node); } void RemoveChild(const shared_ptr<Node>& node) { auto it = find(children.begin(), children.end(), node); Expects(it != children.end() && "trying to remove a child that was never added"); children.erase(it); } }; void SetRoot(const shared_ptr<Node>& node) { root = node; } void ShrinkToFit() { } static auto MakeNode() { return make_shared<MyGraph::Node>(); } private: shared_ptr<Node> root; }; //--- Solution 2 (deferred_ptr) ----------------------------------------------- /*/ static deferred_heap heap; class MyGraph { public: class Node : public Counter { deferred_vector<deferred_ptr<Node>> children{ heap }; public: void AddChild(const deferred_ptr<Node>& node) { children.push_back(node); } void RemoveChild(const deferred_ptr<Node>& node) { auto it = find(children.begin(), children.end(), node); Expects(it != children.end() && "trying to remove a child that was never added"); //children.erase(it); *it = nullptr; } }; void SetRoot(const deferred_ptr<Node>& node) { root = node; } void ShrinkToFit() { heap.collect(); } static auto MakeNode() { return heap.make<MyGraph::Node>(); } private: deferred_ptr<Node> root; }; // ---------------------------------------------------------------------------- //*/ bool TestCase1() { MyGraph g; { auto a = MyGraph::MakeNode(); g.SetRoot(a); auto b = MyGraph::MakeNode(); a->AddChild(b); auto c = MyGraph::MakeNode(); b->AddChild(c); a->RemoveChild(b); } g.ShrinkToFit(); return Counter::count() == 1; } bool TestCase2() { MyGraph g; { auto a = MyGraph::MakeNode(); g.SetRoot(a); auto b = MyGraph::MakeNode(); a->AddChild(b); auto c = MyGraph::MakeNode(); b->AddChild(c); auto d = MyGraph::MakeNode(); b->AddChild(d); d->AddChild(b); a->RemoveChild(b); } g.ShrinkToFit(); return Counter::count() == 1; } bool TestCase3() { MyGraph g; { auto a = MyGraph::MakeNode(); g.SetRoot(a); auto b = MyGraph::MakeNode(); a->AddChild(b); auto c = MyGraph::MakeNode(); b->AddChild(c); auto d = MyGraph::MakeNode(); b->AddChild(d); d->AddChild(b); } g.ShrinkToFit(); return Counter::count() == 4; } int main() { cout.setf(ios::boolalpha); bool passed1 = TestCase1(); cout << passed1 << endl; bool passed2 = TestCase2(); cout << passed2 << endl; bool passed3 = TestCase3(); cout << passed3 << endl; return 0; } <commit_msg>Add Motti Lanzkron's fourth test case.<commit_after> #include "deferred_allocator.h" using namespace gcpp; #include <iostream> #include <iomanip> #include <memory> #include <vector> #include <algorithm> using namespace std; class Counter { public: Counter() { ++count_; } ~Counter() { --count_; } static int count() { return count_; } private: static int count_; }; int Counter::count_ = 0; /*--- Solution 1 (default) ---------------------------------------------------- class MyGraph { public: class Node : public Counter { vector<shared_ptr<Node>> children; public: void AddChild(const shared_ptr<Node>& node) { children.push_back(node); } void RemoveChild(const shared_ptr<Node>& node) { auto it = find(children.begin(), children.end(), node); Expects(it != children.end() && "trying to remove a child that was never added"); children.erase(it); } }; void SetRoot(const shared_ptr<Node>& node) { root = node; } void ShrinkToFit() { } static auto MakeNode() { return make_shared<MyGraph::Node>(); } private: shared_ptr<Node> root; }; //--- Solution 2 (deferred_ptr) ----------------------------------------------- /*/ static deferred_heap heap; class MyGraph { public: class Node : public Counter { deferred_vector<deferred_ptr<Node>> children{ heap }; public: void AddChild(const deferred_ptr<Node>& node) { children.push_back(node); } void RemoveChild(const deferred_ptr<Node>& node) { auto it = find(children.begin(), children.end(), node); Expects(it != children.end() && "trying to remove a child that was never added"); //children.erase(it); *it = nullptr; } }; void SetRoot(const deferred_ptr<Node>& node) { root = node; } void ShrinkToFit() { heap.collect(); } static auto MakeNode() { return heap.make<MyGraph::Node>(); } private: deferred_ptr<Node> root; }; // ---------------------------------------------------------------------------- //*/ bool TestCase1() { MyGraph g; { auto a = MyGraph::MakeNode(); g.SetRoot(a); auto b = MyGraph::MakeNode(); a->AddChild(b); auto c = MyGraph::MakeNode(); b->AddChild(c); a->RemoveChild(b); } g.ShrinkToFit(); return Counter::count() == 1; } bool TestCase2() { MyGraph g; { auto a = MyGraph::MakeNode(); g.SetRoot(a); auto b = MyGraph::MakeNode(); a->AddChild(b); auto c = MyGraph::MakeNode(); b->AddChild(c); auto d = MyGraph::MakeNode(); b->AddChild(d); d->AddChild(b); a->RemoveChild(b); } g.ShrinkToFit(); return Counter::count() == 1; } bool TestCase3() { MyGraph g; { auto a = MyGraph::MakeNode(); g.SetRoot(a); auto b = MyGraph::MakeNode(); a->AddChild(b); auto c = MyGraph::MakeNode(); b->AddChild(c); auto d = MyGraph::MakeNode(); b->AddChild(d); d->AddChild(b); } g.ShrinkToFit(); return Counter::count() == 4; } bool TestCase4() { MyGraph g; { auto a = MyGraph::MakeNode(); g.SetRoot(a); auto b = MyGraph::MakeNode(); a->AddChild(b); auto c = MyGraph::MakeNode(); b->AddChild(c); auto d = MyGraph::MakeNode(); b->AddChild(d); d->AddChild(b); d->RemoveChild(b); } g.ShrinkToFit(); return Counter::count() == 4; } int main() { cout.setf(ios::boolalpha); bool passed1 = TestCase1(); cout << passed1 << endl; bool passed2 = TestCase2(); cout << passed2 << endl; bool passed3 = TestCase3(); cout << passed3 << endl; bool passed4 = TestCase4(); cout << passed4 << endl; return 0; } <|endoftext|>
<commit_before>#include <matrix.hpp> #include <catch.hpp> #include <iostream> using namespace std; SCENARIO("matrix init", "[init]") { Matrix matrix; REQUIRE(matrix.rows() == 0); REQUIRE(matrix.columns() == 0); } SCENARIO("params init", "[init with params]") { int init = 5; Matrix matrix(init, init); REQUIRE(matrix.rows() == 5); REQUIRE(matrix.columns() == 5); } SCENARIO("copy", "[copy]") { int init = 2; Matrix m1(init, init); Matrix copy(m1); REQUIRE(copy.rows() == 2); REQUIRE(copy.columns() == 2); } SCENARIO("+", "[+]") { Matrix A(2, 2); Matrix B(2, 2); Matrix C(2, 2); std::ifstream ("f1.txt") >> A; std::ifstream ("f2.txt") >> B; std::ifstream ("f3.txt") >> C; REQUIRE((A + B) == C); } SCENARIO("*", "[*]") { Matrix A (2, 2); Matrix B (2, 2); Matrix C (2, 2); std::ifstream("f1.txt") >> A; std::ifstream("f2.txt") >> B; std::ifstream("f4.txt") >> C; REQUIRE((A*B) == C); } SCENARIO("=", "[=]") { Matrix A(2, 2); Matrix B = A; REQUIRE(B == A); } SCENARIO("read", "[read]") { Matrix A(2, 2); Matrix B (2, 2); std::ifstream("f1.txt") >> A; std::ofstream("f5.txt") << A; std::ifstream("f5.txt") >> B; REQUIRE(B == A); } <commit_msg>Update init.cpp<commit_after>#include <matrix.hpp> #include <catch.hpp> #include <iostream> using namespace std; SCENARIO("matrix init", "[init]") { Matrix matrix; REQUIRE(matrix.rows() == 0); REQUIRE(matrix.columns() == 0); } SCENARIO("params init", "[init with params]") { int init = 5; Matrix matrix(init, init); REQUIRE(matrix.rows() == 5); REQUIRE(matrix.columns() == 5); } SCENARIO("copy", "[copy]") { int init = 2; Matrix m1(init, init); Matrix copy(m1); REQUIRE(copy.rows() == 2); REQUIRE(copy.columns() == 2); } SCENARIO("m+", "[m+]") { Matrix A(2, 2); Matrix B(2, 2); Matrix C(2, 2); std::ifstream ("f1.txt") >> A; std::ifstream ("f2.txt") >> B; std::ifstream ("f3.txt") >> C; REQUIRE((A + B) == C); } SCENARIO("m*", "[m*]") { Matrix A (2, 2); Matrix B (2, 2); Matrix C (2, 2); std::ifstream("f1.txt") >> A; std::ifstream("f2.txt") >> B; std::ifstream("f4.txt") >> C; REQUIRE((A*B) == C); } SCENARIO("m=", "[m=]") { Matrix A(2, 2); Matrix B = A; REQUIRE(B == A); } SCENARIO("read", "[read]") { Matrix A(2, 2); Matrix B (2, 2); std::ifstream("f1.txt") >> A; std::ofstream("f5.txt") << A; std::ifstream("f5.txt") >> B; REQUIRE(B == A); } <|endoftext|>
<commit_before>#include <stack.cpp> #include <catch.hpp> #include <iostream> using namespace std; SCENARIO("count", "[count]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); } SCENARIO("push", "[push]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); REQUIRE(s.pop()==1); } SCENARIO("top", "[top]"){ stack<int> s; s.push(1); REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("pop", "[pop]"){ stack<int> s; s.push(1); s.push(2); s.pop(); REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("prisv", "[prisv]"){ stack<int> s; s.push(1); stack<int> s2; s2=s; REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("copy", "[copy]"){ stack<int> s; s.push(1); stack <int> a = s; REQUIRE(a.count()==1); REQUIRE(a.top()==1); } <commit_msg>Update init.cpp<commit_after>#include <stack.cpp> #include <catch.hpp> #include <iostream> using namespace std; SCENARIO("count", "[count]") { stack<int> s; s.push(1); REQUIRE(s.count()==1); } SCENARIO("push", "[push]") { stack<int> s; s.push(1); REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("top", "[top]") { stack<int> s; s.push(1); REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("pop", "[pop]") { stack<int> s; s.push(1); s.push(2); s.pop(); REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("prisv", "[prisv]") { stack<int> s; s.push(1); stack<int> s2; s2=s; REQUIRE(s.count()==1); REQUIRE(s.top()==1); } SCENARIO("copy", "[copy]") { stack<int> s; s.push(1); stack <int> a = s; REQUIRE(a.count()==1); REQUIRE(a.top()==1); } SCENARIO("test", "[test]") { stack<int> s; REQUIRE(s.count()==0); } <|endoftext|>
<commit_before>#include <BinaryTree.hpp> #include <catch.hpp> SSCENARIO ("init", "[init]") { BinaryTree<int> obj; REQUIRE(obj.root_() == NULLPTR); REQUIRE(obj.data() == 0); }<commit_msg>Update init.cpp<commit_after>#include <BinaryTree.hpp> #include <catch.hpp> SSCENARIO ("init", "[init]") { BinaryTree<int> obj; REQUIRE(obj.root() == NULLPTR); REQUIRE(obj.data() == 0); } <|endoftext|>
<commit_before> #include <tree.hpp> #include <catch.hpp> SCENARIO("null") { Tree<int> a; REQUIRE(a.tree_one()==NULL); } <commit_msg>Update init.cpp<commit_after> #include <tree.hpp> #include <catch.hpp> SCENARIO("null") { Tree<int> a; REQUIRE(a.tree_one()==NULL); } SCENARIO("find") { Tree<int> a; a.add(5); bool b=a.find(5); REQUIRE(b == 1); } <|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2017 Jeff Hutchinson // // 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. //----------------------------------------------------------------------------- #include <cstdio> #include <vector> #include <duktape.h> const char * script = "var gSharedVariable = 0;\n" "function add(a, b) {\n" " return a + b;\n" "}\n" "\n" "Animal.prototype.test = function() {\n" " print('Test Call to javacript from C++.');\n" "};\n" "\n" "function main() {\n" " print('Hello World!');\n" " print('Value of shared variable is ' + gSharedVariable);\n" "}\n" "\n" "var animal = new Animal();\n" "print('Animal: ' + JSON.stringify(animal));\n" "for (var i = 0; i < 5; i++) {\n" " animal.speak();\n" "}\n" "\n" "var dog = new Dog();\n" "print('Dog: ' + JSON.stringify(dog));\n" "dog.speakDog();\n" "dog.speak();\n"; duk_context *ctx = nullptr; void viewStack(duk_context *ctx); // https://github.com/svaarala/duktape-wiki/blob/master/HowtoNativeConstructor.md class Animal { public: Animal() { } void speak() { printf("SPEAK!!!!\n"); } void *dukPtr; }; class Dog : public Animal { public: Dog() { } void speakDog() { printf("DOG!\n"); } }; std::vector<Animal*> gAnimals; static duk_ret_t Animal_New(duk_context *ctx) { if (!duk_is_constructor_call(ctx)) return DUK_RET_TYPE_ERROR; // Stack: [] Animal *ptr = new Animal(); gAnimals.push_back(ptr); duk_push_this(ctx); // [ this ] ptr->dukPtr = duk_get_heapptr(ctx, -1); // [ this ] // Bind the native pointer to the js pointer. duk_push_string(ctx, "__ptr"); // [ this "__ptr" ] duk_push_pointer(ctx, ptr); // [ this "__ptr" 0xPTR ] duk_put_prop(ctx, -3); // [ this ] return 0; } static duk_ret_t Animal_speak(duk_context *ctx) { // Get the object we are modifiying, or the thisptr duk_push_this(ctx); // Get the native pointer handle. duk_get_prop_string(ctx, -1, "__ptr"); void *ptr = duk_get_pointer(ctx, -1); // Call speak static_cast<Animal*>(ptr)->speak(); return 0; } static void firePrototypeCb_Animal(Animal *animal) { duk_push_heapptr(ctx, animal->dukPtr); // [ ... dukPtr ] duk_get_prop_string(ctx, -1, "test"); // [ ... dukPtr test_fn ] duk_pcall(ctx, 0); // [ ... dukPtr return_value ] // Ignore return value duk_pop(ctx); // [ ... dukPtr ] // pop obj that we pushed. duk_pop(ctx); // [ ... ] } static duk_ret_t Dog_New(duk_context *ctx) { if (!duk_is_constructor_call(ctx)) return DUK_RET_TYPE_ERROR; // Stack: [] Dog *ptr = new Dog(); gAnimals.push_back(ptr); duk_push_this(ctx); // [ this ] ptr->dukPtr = duk_get_heapptr(ctx, -1); // [ this ] // Bind the native pointer to the js pointer. duk_push_string(ctx, "__ptr"); // [ this "__ptr" ] duk_push_pointer(ctx, ptr); // [ this "__ptr" 0xPTR ] duk_put_prop(ctx, -3); // [ this ] return 0; } static duk_ret_t Dog_speakDog(duk_context *ctx) { // Get the object we are modifiying, or the thisptr duk_push_this(ctx); // Get the native pointer handle. duk_get_prop_string(ctx, -1, "__ptr"); void *ptr = duk_get_pointer(ctx, -1); // Call speak static_cast<Dog*>(ptr)->speakDog(); return 0; } void viewStack(duk_context *ctx) { // duk_to_string modifies the stack, so we have to duplicate the current // value that we are inspecting to the top of the stack by pushing it, // modifying it, and then poping it so we don't screw up the stack. // This is probably slow, but this function is used for inspecting the stack. // http://duktape.org/api.html#duk_to_string printf("----- Viewing Stack -----\n"); int count = duk_get_top_index(ctx); for (int i = count; i > -1; i--) { duk_dup(ctx, i); if (duk_is_function(ctx, count + 1)) printf("%s\n", duk_to_string(ctx, count + 1)); else if (duk_is_string(ctx, count + 1) || duk_is_number(ctx, count + 1)) printf("%s\n", duk_to_string(ctx, count + 1)); else printf("%s\n", duk_json_encode(ctx, count + 1)); duk_pop(ctx); } printf("---- end Stack ----\n"); } // https://github.com/svaarala/duktape/blob/master/examples/guide/primecheck.c static duk_ret_t script_print(duk_context *ctxx) { duk_push_string(ctxx, " "); duk_insert(ctxx, 0); duk_join(ctxx, duk_get_top(ctxx) - 1); printf("%s\n", duk_to_string(ctxx, -1)); return 0; } // after each line is executed, the comments that follow is what the stack looks like int main(int argc, const char **argv) { ctx = duk_create_heap_default(); // Stack: [ ... ] duk_push_global_object(ctx);// Stack: [ ... global_object ] duk_push_c_function(ctx, script_print, DUK_VARARGS); // [ ... global_object script_print_fn ] duk_put_prop_string(ctx, -2, "print"); // [ ... global_object ] /// { /// Initialize Animal Prototype // Bind the prototype constructor and object. duk_push_c_function(ctx, Animal_New, 0); // [ ... global_object AnimalCSTR ] duk_push_object(ctx); // [ ... global_object AnimalCSTR PrototypeObj ] // Bind methods to the prototype { duk_push_c_function(ctx, Animal_speak, 0); // [ ... global_object AnimalCSTR PrototypeObj Animal_SpeakFN ] duk_put_prop_string(ctx, -2, "speak"); // [ ... global_object AnimalCSTR PrototypeObj ] } // Bind prototype property and the name of the prototype to use with new stmts. duk_put_prop_string(ctx, -2, "prototype"); // [ ... global_object AnimalCSTR ] duk_put_global_string(ctx, "Animal"); // [ ... global_object ] /// } /// { /// Initialize Dog Prototype duk_push_c_function(ctx, Dog_New, 0); // [ ... global_object DogCSTR ] duk_get_global_string(ctx, "Animal"); // [ ... global_object DogCSTR Animal ] duk_new(ctx, 0); // [ ... global_object DogCSTR DogPrototype ] // Bind dog methods { duk_push_c_function(ctx, Dog_speakDog, 0); // [ ... global_object DogCSTR DogPrototype Dog_speakDogFn ] duk_put_prop_string(ctx, -2, "speakDog"); // [ ... global_object DogCSTR DogPrototype ] } duk_put_prop_string(ctx, -2, "prototype"); // [ ... global_object DogCSTR ] duk_put_global_string(ctx, "Dog"); // [ ... global_object ] /// } if (duk_peval_string(ctx, script) != 0) { // [ ... global_object result ] printf("Script pEval Failure: %s\n", duk_safe_to_string(ctx, -1)); #ifdef _WIN32 system("pause"); #endif exit(1); } duk_pop(ctx); // [ ... global_object ] duk_get_prop_string(ctx, -1, "main"); // [ ... global_object main_fn ] if (duk_pcall(ctx, 0) != 0) { // [ ... global_object return_value ] printf("Error: %s\n", duk_safe_to_string(ctx, -1)); // [ ... global_object return_value ] } duk_pop(ctx); // [ ... global_object ] // Call add // currently stack is just global object which has add fn. duk_get_prop_string(ctx, -1, "add"); // [ ... global_object add_fn ] duk_push_int(ctx, 4); // [ ... global_object add_fn 4 ] duk_push_int(ctx, 5); // [ ... global_object add_fn 4 5 ] if (duk_pcall(ctx, 2) == DUK_EXEC_SUCCESS) { // [ ... global_object return_value ] printf("Result of add() is %d\n", duk_get_int(ctx, -1)); // [ ... global_object return_value ] } else { printf("Error: %s\n", duk_safe_to_string(ctx, -1)); // [ ... global_object return_value ] } duk_pop(ctx); // [ ... global_object ] firePrototypeCb_Animal(gAnimals[0]); duk_pop(ctx); // [ ... ] duk_destroy_heap(ctx); // [] #ifdef _WIN32 system("pause"); #endif return 0; }<commit_msg>getters/setters test<commit_after>//----------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2017 Jeff Hutchinson // // 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. //----------------------------------------------------------------------------- #include <cstdio> #include <vector> #include <string> #include <duktape.h> const char * script = "var gSharedVariable = 0;\n" "function add(a, b) {\n" " return a + b;\n" "}\n" "\n" "Animal.prototype.test = function() {\n" " print('Test Call to javacript from C++.');\n" "};\n" "\n" "function main() {\n" " print('Hello World!');\n" " print('Value of shared variable is ' + gSharedVariable);\n" "}\n" "\n" "var animal = new Animal();\n" "print('Animal name: ' + animal.name);\n" "animal.name = 'Billy';\n" "print('Animal name should be Billy: ' + animal.name);\n" "print('Animal: ' + JSON.stringify(animal));\n" "for (var i = 0; i < 5; i++) {\n" " animal.speak();\n" "}\n" "\n" "var dog = new Dog();\n" "dog.bananas = true;\n" "print('Dog: ' + JSON.stringify(dog));\n" "dog.speakDog();\n" "print('Dog name: ' + dog.name);\n" "print('Going to loop through properties of dog:');\n" "for (var key in dog) {\n" " print('Key: ' + key + ' Val: ' + dog[key]);\n" "}\n" "dog.speak();\n"; duk_context *ctx = nullptr; void viewStack(duk_context *ctx); // https://github.com/svaarala/duktape-wiki/blob/master/HowtoNativeConstructor.md class Animal { public: Animal() { } void speak() { printf("SPEAK!!!!\n"); } void *dukPtr; std::string mName; }; class Dog : public Animal { public: Dog() { } void speakDog() { printf("DOG!\n"); } }; std::vector<Animal*> gAnimals; static duk_ret_t Animal_New(duk_context *ctx) { if (!duk_is_constructor_call(ctx)) return DUK_RET_TYPE_ERROR; // Stack: [] Animal *ptr = new Animal(); gAnimals.push_back(ptr); duk_push_this(ctx); // [ this ] ptr->dukPtr = duk_get_heapptr(ctx, -1); // [ this ] // Bind the native pointer to the js pointer. duk_push_string(ctx, "__ptr"); // [ this "__ptr" ] duk_push_pointer(ctx, ptr); // [ this "__ptr" 0xPTR ] duk_put_prop(ctx, -3); // [ this ] return 0; } static duk_ret_t Animal_speak(duk_context *ctx) { // Get the object we are modifiying, or the thisptr duk_push_this(ctx); // Get the native pointer handle. duk_get_prop_string(ctx, -1, "__ptr"); void *ptr = duk_get_pointer(ctx, -1); // Call speak static_cast<Animal*>(ptr)->speak(); return 0; } static void firePrototypeCb_Animal(Animal *animal) { duk_push_heapptr(ctx, animal->dukPtr); // [ ... dukPtr ] duk_get_prop_string(ctx, -1, "test"); // [ ... dukPtr test_fn ] duk_pcall(ctx, 0); // [ ... dukPtr return_value ] // Ignore return value duk_pop(ctx); // [ ... dukPtr ] // pop obj that we pushed. duk_pop(ctx); // [ ... ] } static duk_ret_t Dog_New(duk_context *ctx) { if (!duk_is_constructor_call(ctx)) return DUK_RET_TYPE_ERROR; // Stack: [] Dog *ptr = new Dog(); gAnimals.push_back(ptr); duk_push_this(ctx); // [ this ] ptr->dukPtr = duk_get_heapptr(ctx, -1); // [ this ] // Bind the native pointer to the js pointer. duk_push_string(ctx, "__ptr"); // [ this "__ptr" ] duk_push_pointer(ctx, ptr); // [ this "__ptr" 0xPTR ] duk_put_prop(ctx, -3); // [ this ] return 0; } static duk_ret_t Dog_speakDog(duk_context *ctx) { // Get the object we are modifiying, or the thisptr duk_push_this(ctx); // Get the native pointer handle. duk_get_prop_string(ctx, -1, "__ptr"); void *ptr = duk_get_pointer(ctx, -1); // Call speak static_cast<Dog*>(ptr)->speakDog(); return 0; } static duk_ret_t Animal_prop_name_get(duk_context *ctx) { duk_push_this(ctx); // get C++ object duk_get_prop_string(ctx, -1, "__ptr"); void *ptr = duk_require_pointer(ctx, -1); // Return duk_push_string(ctx, static_cast<Animal*>(ptr)->mName.c_str()); return 1; /* duk_push_current_function(ctx); duk_get_prop_string(ctx, -1, "name"); const char *name = duk_require_string(ctx, -1); // Store static_cast<Animal*>(ptr)->mName = std::string(name); */ } static duk_ret_t Animal_prop_name_set(duk_context *ctx) { // get value that is being set const char *setString = duk_require_string(ctx, -1); duk_push_this(ctx); // get c++ object duk_get_prop_string(ctx, -1, "__ptr"); void *ptr = duk_require_pointer(ctx, -1); // set value static_cast<Animal*>(ptr)->mName = setString; return 0; } void viewStack(duk_context *ctx) { // duk_to_string modifies the stack, so we have to duplicate the current // value that we are inspecting to the top of the stack by pushing it, // modifying it, and then poping it so we don't screw up the stack. // This is probably slow, but this function is used for inspecting the stack. // http://duktape.org/api.html#duk_to_string printf("----- Viewing Stack -----\n"); int count = duk_get_top_index(ctx); for (int i = count; i > -1; i--) { duk_dup(ctx, i); if (duk_is_function(ctx, count + 1)) printf("%s\n", duk_to_string(ctx, count + 1)); else if (duk_is_string(ctx, count + 1) || duk_is_number(ctx, count + 1)) printf("%s\n", duk_to_string(ctx, count + 1)); else printf("%s\n", duk_json_encode(ctx, count + 1)); duk_pop(ctx); } printf("---- end Stack ----\n"); } // https://github.com/svaarala/duktape/blob/master/examples/guide/primecheck.c static duk_ret_t script_print(duk_context *ctxx) { duk_push_string(ctxx, " "); duk_insert(ctxx, 0); duk_join(ctxx, duk_get_top(ctxx) - 1); printf("%s\n", duk_to_string(ctxx, -1)); return 0; } // after each line is executed, the comments that follow is what the stack looks like int main(int argc, const char **argv) { ctx = duk_create_heap_default(); // Stack: [ ... ] duk_push_global_object(ctx);// Stack: [ ... global_object ] duk_push_c_function(ctx, script_print, DUK_VARARGS); // [ ... global_object script_print_fn ] duk_put_prop_string(ctx, -2, "print"); // [ ... global_object ] /// { /// Initialize Animal Prototype // Bind the prototype constructor and object. duk_push_c_function(ctx, Animal_New, 0); // [ ... global_object AnimalCSTR ] duk_push_object(ctx); // [ ... global_object AnimalCSTR PrototypeObj ] // Bind methods to the prototype { duk_push_c_function(ctx, Animal_speak, 0); // [ ... global_object AnimalCSTR PrototypeObj Animal_SpeakFN ] duk_put_prop_string(ctx, -2, "speak"); // [ ... global_object AnimalCSTR PrototypeObj ] } // Bind properties to the prototype { duk_push_string(ctx, "name"); // prop duk_push_c_function(ctx, Animal_prop_name_get, 0); duk_push_c_function(ctx, Animal_prop_name_set, 1); viewStack(ctx); duk_def_prop( ctx, -4, DUK_DEFPROP_HAVE_GETTER | DUK_DEFPROP_HAVE_SETTER | DUK_DEFPROP_HAVE_CONFIGURABLE | DUK_DEFPROP_CONFIGURABLE | DUK_DEFPROP_HAVE_ENUMERABLE | DUK_DEFPROP_ENUMERABLE ); } // Bind prototype property and the name of the prototype to use with new stmts. duk_put_prop_string(ctx, -2, "prototype"); // [ ... global_object AnimalCSTR ] duk_put_global_string(ctx, "Animal"); // [ ... global_object ] /// } /// { /// Initialize Dog Prototype duk_push_c_function(ctx, Dog_New, 0); // [ ... global_object DogCSTR ] duk_get_global_string(ctx, "Animal"); // [ ... global_object DogCSTR Animal ] duk_new(ctx, 0); // [ ... global_object DogCSTR DogPrototype ] // Bind dog methods { duk_push_c_function(ctx, Dog_speakDog, 0); // [ ... global_object DogCSTR DogPrototype Dog_speakDogFn ] duk_put_prop_string(ctx, -2, "speakDog"); // [ ... global_object DogCSTR DogPrototype ] } duk_put_prop_string(ctx, -2, "prototype"); // [ ... global_object DogCSTR ] duk_put_global_string(ctx, "Dog"); // [ ... global_object ] /// } if (duk_peval_string(ctx, script) != 0) { // [ ... global_object result ] printf("Script pEval Failure: %s\n", duk_safe_to_string(ctx, -1)); #ifdef _WIN32 system("pause"); #endif exit(1); } duk_pop(ctx); // [ ... global_object ] duk_get_prop_string(ctx, -1, "main"); // [ ... global_object main_fn ] if (duk_pcall(ctx, 0) != 0) { // [ ... global_object return_value ] printf("Error: %s\n", duk_safe_to_string(ctx, -1)); // [ ... global_object return_value ] } duk_pop(ctx); // [ ... global_object ] // Call add // currently stack is just global object which has add fn. duk_get_prop_string(ctx, -1, "add"); // [ ... global_object add_fn ] duk_push_int(ctx, 4); // [ ... global_object add_fn 4 ] duk_push_int(ctx, 5); // [ ... global_object add_fn 4 5 ] if (duk_pcall(ctx, 2) == DUK_EXEC_SUCCESS) { // [ ... global_object return_value ] printf("Result of add() is %d\n", duk_get_int(ctx, -1)); // [ ... global_object return_value ] } else { printf("Error: %s\n", duk_safe_to_string(ctx, -1)); // [ ... global_object return_value ] } duk_pop(ctx); // [ ... global_object ] firePrototypeCb_Animal(gAnimals[0]); duk_pop(ctx); // [ ... ] duk_destroy_heap(ctx); // [] #ifdef _WIN32 system("pause"); #endif return 0; }<|endoftext|>
<commit_before>#include "gtest/gtest.h" int main(int argc, char *argv[]) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>Make ASSERTs in helper functions fail the parent testcase<commit_after>#include "gtest/gtest.h" class ThrowListener : public testing::EmptyTestEventListener { void OnTestPartResult(const testing::TestPartResult& result) override { if (result.type() == testing::TestPartResult::kFatalFailure) { throw testing::AssertionException(result); } } }; int main(int argc, char *argv[]) { ::testing::InitGoogleTest(&argc, argv); ::testing::UnitTest::GetInstance()->listeners().Append(new ThrowListener); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>#include "SharedResource.h" #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE(Basic_construction) { SharedResource<int> shared_int; } BOOST_AUTO_TEST_CASE(Construction_with_argument) { SharedResource<int> shared_int(5); } BOOST_AUTO_TEST_CASE(Construction_no_default_constructor) { struct TestClass { TestClass() = delete; TestClass(int) { } }; SharedResource<TestClass> stc2(5); } BOOST_AUTO_TEST_CASE(Basic_Locking) { SharedResource<int> shared_int(0); shared_int.lock(); } BOOST_AUTO_TEST_CASE(Locking_with_accessor) { SharedResource<int> shared_int(0); auto shared_int_accessor = shared_int.lock(); } BOOST_AUTO_TEST_CASE(Accessor_isValid) { SharedResource<int> shared_int(0); auto shared_int_accessor = shared_int.lock(); BOOST_CHECK(shared_int_accessor.isValid()); auto shared_int_accessor_new(std::move(shared_int_accessor)); BOOST_CHECK(!shared_int_accessor.isValid()); BOOST_CHECK(shared_int_accessor_new.isValid()); } BOOST_AUTO_TEST_CASE(Acessor_dereferencing_1) { SharedResource<int> shared_int(0); auto shared_int_accessor = shared_int.lock(); BOOST_CHECK_EQUAL(0, *shared_int_accessor); *shared_int_accessor = 5; BOOST_CHECK_EQUAL(5, *shared_int_accessor); } BOOST_AUTO_TEST_CASE(Acessor_dereferencing_2) { struct TestClass { TestClass(int a) : m_a(a) { } void set(int a) noexcept { m_a = a; } int get() const noexcept { return m_a; } private: int m_a; }; SharedResource<TestClass> shared_test_class(0); auto shared_int_accessor = shared_test_class.lock(); BOOST_CHECK_EQUAL(0, shared_int_accessor->get()); shared_int_accessor->set(5); BOOST_CHECK_EQUAL(5, shared_int_accessor->get()); } <commit_msg>Concurrency test added<commit_after>#include <thread> #include <chrono> #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include "SharedResource.h" BOOST_AUTO_TEST_CASE(Basic_construction) { SharedResource<int> shared_int; } BOOST_AUTO_TEST_CASE(Construction_with_argument) { SharedResource<int> shared_int(5); } BOOST_AUTO_TEST_CASE(Construction_no_default_constructor) { struct TestClass { TestClass() = delete; TestClass(int) { } }; SharedResource<TestClass> stc2(5); } BOOST_AUTO_TEST_CASE(Basic_Locking) { SharedResource<int> shared_int(0); shared_int.lock(); } BOOST_AUTO_TEST_CASE(Locking_with_accessor) { SharedResource<int> shared_int(0); auto shared_int_accessor = shared_int.lock(); } BOOST_AUTO_TEST_CASE(Accessor_isValid) { SharedResource<int> shared_int(0); auto shared_int_accessor = shared_int.lock(); BOOST_CHECK(shared_int_accessor.isValid()); auto shared_int_accessor_new(std::move(shared_int_accessor)); BOOST_CHECK(!shared_int_accessor.isValid()); BOOST_CHECK(shared_int_accessor_new.isValid()); } BOOST_AUTO_TEST_CASE(Acessor_dereferencing_1) { SharedResource<int> shared_int(0); auto shared_int_accessor = shared_int.lock(); BOOST_CHECK_EQUAL(0, *shared_int_accessor); *shared_int_accessor = 5; BOOST_CHECK_EQUAL(5, *shared_int_accessor); } BOOST_AUTO_TEST_CASE(Acessor_dereferencing_2) { struct TestClass { TestClass(int a) : m_a(a) { } void set(int a) noexcept { m_a = a; } int get() const noexcept { return m_a; } private: int m_a; }; SharedResource<TestClass> shared_test_class(0); auto shared_int_accessor = shared_test_class.lock(); BOOST_CHECK_EQUAL(0, shared_int_accessor->get()); shared_int_accessor->set(5); BOOST_CHECK_EQUAL(5, shared_int_accessor->get()); } BOOST_AUTO_TEST_CASE(Concurrency_test) { SharedResource<int> shared_int(0); std::thread test_thread([&shared_int]() { std::this_thread::sleep_for(std::chrono::milliseconds(250)); auto shared_int_accessor = shared_int.lock(); *shared_int_accessor = 7; }); { auto shared_int_accessor = shared_int.lock(); BOOST_CHECK_EQUAL(0, *shared_int_accessor); *shared_int_accessor = 5; BOOST_CHECK_EQUAL(5, *shared_int_accessor); std::this_thread::sleep_for(std::chrono::milliseconds(500)); BOOST_CHECK_EQUAL(5, *shared_int_accessor); } test_thread.join(); auto shared_int_accessor = shared_int.lock(); BOOST_CHECK_EQUAL(7, *shared_int_accessor); } <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <array> #include <valarray> #include "aaa.hpp" void test_std_algorithms(); void test_algorithms(); void test_vector_space_operations(); void test_euclidean_space_operations(); void test_logical_operations(); int main() { test_std_algorithms(); test_algorithms(); test_vector_space_operations(); test_euclidean_space_operations(); test_logical_operations(); using namespace std; cout << "Press enter to quit." << endl; cin.get(); return 0; } void test_std_algorithms() { using namespace aaa; const std::vector<int> c1 = { 1, 2, 3, 4, 5 }; std::array<float, 5> c2 = { 1, 2, 3, 4, 5 }; std::valarray<double> c3 = { 1, 2, 3, 4, 5 }; double x = 3.14; copy(c1, c2); fill(c3, x); auto min1 = min_element(c1); auto min2 = min_element(c2); auto max1 = max_element(c1); auto max2 = max_element(c2); auto minmax1 = minmax_element(c1); auto minmax2 = minmax_element(c2); //*min1 = 3; *min2 = 3; //*max1 = 3; *max2 = 3; //*minmax1.first = 3; *minmax2.first = 3; //*minmax1.second = 3; *minmax2.second = 3; } void test_algorithms() { using namespace aaa; std::vector<int> c1 = { 1, 2, 3, 4, 5 }; std::array<float, 5> c2 = { 1, 2, 3, 4, 5 }; std::valarray<double> c3 = { 1, 2, 3, 4, 5 }; convert(c1, c2); convert(c3, c1); sum(c1); using std::begin; using std::end; convert(begin(c1), end(c1), begin(c2)); convert(begin(c3), end(c3), begin(c1)); sum(begin(c1), end(c1)); } void test_vector_space_operations() { using namespace aaa; std::vector<int> c1 = { 1, 2, 3, 4, 5 }; std::array<int, 5> c2 = { 1, 2, 3, 4, 5 }; std::valarray<int> c3 = { 1, 2, 3, 4, 5 }; int e = 10; negate(c1, c2); add(c1, c2, c3); add(e, c2, c3); add(c2, e, c3); subtract(c1, c2, c3); subtract(e, c2, c3); subtract(c2, e, c3); multiply(c1, c2, c3); multiply(e, c2, c3); multiply(c1, e, c3); divide(c1, c2, c3); divide(e, c2, c3); divide(c1, e, c3); #if !_MSC_VER || __clang__ std::vector<float> c1f = { 1.f, 2.f, 3.f, 4.f, 5.f }; std::array<float, 5> c2f = { 1.f, 2.f, 3.f, 4.f, 5.f }; std::valarray<float> c3f = { 1.f, 2.f, 3.f, 4.f, 5.f }; int ef = 10.f; add(c1, c2f, c3f); add(e, c2f, c3f); add(c2, ef, c3f); subtract(c1, c2f, c3f); subtract(e, c2f, c3f); subtract(c2, ef, c3f); multiply(c1, c2f, c3f); multiply(e, c2f, c3f); multiply(c1, ef, c3f); divide(c1, c2f, c3f); divide(e, c2f, c3f); divide(c1, ef, c3f); #endif using std::begin; using std::end; negate(begin(c1), end(c1), begin(c2)); add(begin(c1), end(c1), begin(c2), begin(c3)); add(e, begin(c1), end(c1), begin(c3)); add(begin(c1), end(c1), e, begin(c3)); subtract(begin(c1), end(c1), begin(c2), begin(c3)); subtract(e, begin(c1), end(c1), begin(c3)); subtract(begin(c1), end(c1), e, begin(c3)); multiply(begin(c1), end(c1), begin(c2), begin(c3)); multiply(e, begin(c1), end(c1), begin(c3)); multiply(begin(c1), end(c1), e, begin(c3)); divide(begin(c1), end(c1), begin(c2), begin(c3)); divide(e, begin(c1), end(c1), begin(c3)); divide(begin(c1), end(c1), e, begin(c3)); c1 = negate(c1); c1 = add(c1, c1); c1 = add(c1, e); c1 = add(e, c1); c1 = subtract(c1, c1); c1 = subtract(c1, e); c1 = subtract(e, c1); c1 = multiply(c1, c1); c1 = multiply(c1, e); c1 = multiply(e, c1); c1 = divide(c1, c1); c1 = divide(c1, e); c1 = divide(e, c1); } void test_euclidean_space_operations() { using namespace aaa; std::vector<int> c1 = { 1, 2, 3, 4, 5 }; std::array<int, 5> c2 = { 1, 2, 3, 4, 5 }; std::valarray<int> c3 = { 1, 2, 3, 4, 5 }; dot(c1, c2); squared_norm(c1); norm(c1); squared_distance(c1, c2); distance(c1, c2); using std::begin; using std::end; dot(begin(c1), end(c1), begin(c2)); squared_norm(begin(c1), end(c1)); norm(begin(c1), end(c1)); squared_distance(begin(c1), end(c1), begin(c2)); distance(begin(c1), end(c1), begin(c2)); } void test_logical_operations() { using namespace aaa; std::vector<bool> c1 = { true, true, false }; std::array<bool, 3> c2 = { true, false, true }; std::valarray<bool> c3 = { true, false, false }; logical_and(c1, c2, c3); assert(c3[0] == true); assert(c3[1] == false); assert(c3[2] == false); logical_or(c1, c2, c3); assert(c3[0] == true); assert(c3[1] == true); assert(c3[2] == true); logical_not(c1, c2); assert(c2[0] == false); assert(c2[1] == false); assert(c2[2] == true); using std::begin; using std::end; logical_and(begin(c1), end(c1), begin(c2), begin(c3)); logical_or(begin(c1), end(c1), begin(c2), begin(c3)); logical_not(begin(c1), end(c1), begin(c2)); c1 = logical_and(c1, c1); c2 = logical_or(c2, c2); c3 = logical_not(c3); } <commit_msg>Add compile tests<commit_after>#include <iostream> #include <vector> #include <array> #include <valarray> #include "aaa.hpp" void test_std_algorithms(); void test_algorithms(); void test_vector_space_operations(); void test_euclidean_space_operations(); void test_logical_operations(); int main() { test_std_algorithms(); test_algorithms(); test_vector_space_operations(); test_euclidean_space_operations(); test_logical_operations(); using namespace std; cout << "Press enter to quit." << endl; cin.get(); return 0; } void test_std_algorithms() { using namespace aaa; const std::vector<int> c1 = { 1, 2, 3, 4, 5 }; std::array<float, 5> c2 = { 1, 2, 3, 4, 5 }; std::valarray<double> c3 = { 1, 2, 3, 4, 5 }; double x = 3.14; copy(c1, c2); fill(c3, x); auto min1 = min_element(c1); auto min2 = min_element(c2); auto max1 = max_element(c1); auto max2 = max_element(c2); auto minmax1 = minmax_element(c1); auto minmax2 = minmax_element(c2); //*min1 = 3; *min2 = 3; //*max1 = 3; *max2 = 3; //*minmax1.first = 3; *minmax2.first = 3; //*minmax1.second = 3; *minmax2.second = 3; } void test_algorithms() { using namespace aaa; std::vector<int> c1 = { 1, 2, 3, 4, 5 }; std::array<float, 5> c2 = { 1, 2, 3, 4, 5 }; std::valarray<double> c3 = { 1, 2, 3, 4, 5 }; convert(c1, c2); convert(c3, c1); sum(c1); using std::begin; using std::end; convert(begin(c1), end(c1), begin(c2)); convert(begin(c3), end(c3), begin(c1)); sum(begin(c1), end(c1)); } void test_vector_space_operations() { using namespace aaa; std::vector<int> c1 = { 1, 2, 3, 4, 5 }; std::array<int, 5> c2 = { 1, 2, 3, 4, 5 }; std::valarray<int> c3 = { 1, 2, 3, 4, 5 }; int e = 10; negate(c1, c2); add(c1, c2, c3); add(e, c2, c3); add(c2, e, c3); subtract(c1, c2, c3); subtract(e, c2, c3); subtract(c2, e, c3); multiply(c1, c2, c3); multiply(e, c2, c3); multiply(c1, e, c3); divide(c1, c2, c3); divide(e, c2, c3); divide(c1, e, c3); #if !_MSC_VER || __clang__ std::vector<float> c1f = { 1.f, 2.f, 3.f, 4.f, 5.f }; std::array<float, 5> c2f = { 1.f, 2.f, 3.f, 4.f, 5.f }; std::valarray<float> c3f = { 1.f, 2.f, 3.f, 4.f, 5.f }; int ef = 10.f; add(c1, c2f, c3f); add(e, c2f, c3f); add(c2, ef, c3f); subtract(c1, c2f, c3f); subtract(e, c2f, c3f); subtract(c2, ef, c3f); multiply(c1, c2f, c3f); multiply(e, c2f, c3f); multiply(c1, ef, c3f); divide(c1, c2f, c3f); divide(e, c2f, c3f); divide(c1, ef, c3f); #endif using std::begin; using std::end; negate(begin(c1), end(c1), begin(c2)); add(begin(c1), end(c1), begin(c2), begin(c3)); add(e, begin(c1), end(c1), begin(c3)); add(begin(c1), end(c1), e, begin(c3)); subtract(begin(c1), end(c1), begin(c2), begin(c3)); subtract(e, begin(c1), end(c1), begin(c3)); subtract(begin(c1), end(c1), e, begin(c3)); multiply(begin(c1), end(c1), begin(c2), begin(c3)); multiply(e, begin(c1), end(c1), begin(c3)); multiply(begin(c1), end(c1), e, begin(c3)); divide(begin(c1), end(c1), begin(c2), begin(c3)); divide(e, begin(c1), end(c1), begin(c3)); divide(begin(c1), end(c1), e, begin(c3)); c1 = negate(c1); c2 = negate(c2); c3 = negate(c3); c1 = add(c1, c1); c1 = add(c1, e); c1 = add(e, c1); c2 = add(c2, c2); c2 = add(c2, e); c2 = add(e, c2); c3 = add(c3, c3); c3 = add(c3, e); c3 = add(e, c3); c1 = subtract(c1, c1); c1 = subtract(c1, e); c1 = subtract(e, c1); c2 = subtract(c2, c2); c2 = subtract(c2, e); c2 = subtract(e, c2); c3 = subtract(c3, c3); c3 = subtract(c3, e); c3 = subtract(e, c3); c1 = multiply(c1, c1); c1 = multiply(c1, e); c1 = multiply(e, c1); c2 = multiply(c2, c2); c2 = multiply(c2, e); c2 = multiply(e, c2); c3 = multiply(c3, c3); c3 = multiply(c3, e); c3 = multiply(e, c3); c1 = divide(c1, c1); c1 = divide(c1, e); c1 = divide(e, c1); c2 = divide(c2, c2); c2 = divide(c2, e); c2 = divide(e, c2); c3 = divide(c3, c3); c3 = divide(c3, e); c3 = divide(e, c3); } void test_euclidean_space_operations() { using namespace aaa; std::vector<int> c1 = { 1, 2, 3, 4, 5 }; std::array<int, 5> c2 = { 1, 2, 3, 4, 5 }; std::valarray<int> c3 = { 1, 2, 3, 4, 5 }; dot(c1, c2); squared_norm(c1); norm(c1); squared_distance(c1, c2); distance(c1, c2); using std::begin; using std::end; dot(begin(c1), end(c1), begin(c2)); squared_norm(begin(c1), end(c1)); norm(begin(c1), end(c1)); squared_distance(begin(c1), end(c1), begin(c2)); distance(begin(c1), end(c1), begin(c2)); } void test_logical_operations() { using namespace aaa; std::vector<bool> c1 = { true, true, false }; std::array<bool, 3> c2 = { true, false, true }; std::valarray<bool> c3 = { true, false, false }; logical_and(c1, c2, c3); assert(c3[0] == true); assert(c3[1] == false); assert(c3[2] == false); logical_or(c1, c2, c3); assert(c3[0] == true); assert(c3[1] == true); assert(c3[2] == true); logical_not(c1, c2); assert(c2[0] == false); assert(c2[1] == false); assert(c2[2] == true); using std::begin; using std::end; logical_and(begin(c1), end(c1), begin(c2), begin(c3)); logical_or(begin(c1), end(c1), begin(c2), begin(c3)); logical_not(begin(c1), end(c1), begin(c2)); c1 = logical_and(c1, c1); c2 = logical_or(c2, c2); c3 = logical_not(c3); } <|endoftext|>
<commit_before>#include <iostream> #include "lua-cpp/luacpp.h" using namespace luacpp; using namespace std; static void test_number() { LuaState l; l.Set("var", 5); auto lobj = l.Get("var"); cout << "var: type -> " << lobj.GetTypeStr() << ", value = " << lobj.ToNumber() << endl; } static void test_nil() { LuaState l; auto lobj = l.Get("nilobj"); cout << "nilobj: type -> " << lobj.GetTypeStr() << endl; } static void test_string() { LuaState l; string var("ouonline"); l.Set("var", var.c_str(), var.size()); auto lobj = l.Get("var"); cout << "var: type -> " << lobj.GetTypeStr() << ", value = " << lobj.ToString() << endl; } static void test_table() { LuaState l; auto iterfunc = [] (const LuaObject& key, const LuaObject& value) -> bool { cout << " "; // indention if (key.GetType() == LUA_TNUMBER) { cout << key.ToNumber(); } else if (key.GetType() == LUA_TSTRING) { cout << key.ToString(); } else { cout << "unsupported key type -> " << key.GetTypeStr() << endl; return false; } if (value.GetType() == LUA_TNUMBER) { cout << " -> " << value.ToNumber() << endl; } else if (value.GetType() == LUA_TSTRING) { cout << " -> " << value.ToString() << endl; } else { cout << " -> unsupported iter value type: " << value.GetTypeStr() << endl; } return true; }; cout << "table1:" << endl; l.DoString("var = {'mykey', value = 'myvalue', others = 'myothers'}"); l.Get("var").ToTable().ForEach(iterfunc); cout << "table2:" << endl; auto ltable = l.CreateTable(); ltable.Set("x", 5); ltable.Set("o", "ouonline"); ltable.Set("t", ltable); ltable.ForEach(iterfunc); } class GenericFunctionHelper final : public LuaFunctionHelper { public: GenericFunctionHelper(const std::function<bool (int, const LuaObject&)>& f) : m_func(f) {} bool BeforeProcess(int) override { return true; } bool Process(int i, const LuaObject& lobj) override { return m_func(i, lobj); } void AfterProcess() {} private: std::function<bool (int, const LuaObject&)> m_func; }; static void test_function_with_return_value() { LuaState l; auto resiter1 = [] (int, const LuaObject& lobj) -> bool { cout << "output from resiter1: " << lobj.ToString() << endl; return true; }; auto resiter2 = [] (int n, const LuaObject& lobj) -> bool { cout << "output from resiter2: "; if (n == 0) { cout << lobj.ToNumber() << endl; } else if (n == 1) { cout << lobj.ToString() << endl; } return true; }; GenericFunctionHelper helper1(resiter1), helper2(resiter2); std::function<int (const char*)> Echo = [] (const char* msg) -> int { cout << msg; return 5; }; auto lfunc = l.CreateFunction(Echo, "Echo"); l.Set("msg", "calling cpp function with return value from cpp: "); lfunc.Exec(nullptr, &helper1, l.Get("msg")); l.DoString("res = Echo('calling cpp function with return value from lua: ');" "io.write('return value -> ', res, '\\n')"); l.DoString("function return2(a, b) return a, b end"); l.Get("return2").ToFunctiong().Exec(nullptr, &helper2, 5, "ouonline"); } static void Echo(const char* msg) { cout << msg; } static void test_function_without_return_value() { LuaState l; auto lfunc = l.CreateFunction(Echo, "Echo"); lfunc.Exec(0, nullptr, nullptr, "calling cpp function without return value from cpp\n"); l.DoString("Echo('calling cpp function without return value from lua\\n')"); } class TestClass final { public: TestClass() { cout << "TestClass::TestClass() is called without value." << endl; } TestClass(const char* msg, int x) { if (msg) { m_msg = msg; } cout << "TestClass::TestClass() is called with string -> '" << m_msg << "' and value -> " << x << "." << endl; } ~TestClass() { cout << "TestClass::~TestClass() is called." << endl; } void Set(const char* msg) { m_msg = msg; } void Print() const { cout << "TestClass::Print(): " << m_msg << endl; } void Echo(const char* msg) const { cout << "TestClass::Echo(string): " << msg << endl; } void Echo(int v) const { cout << "TestClass::Echo(int): " << v << endl; } static void StaticEcho(const char* msg) { cout << "TestClass::StaticEcho(string): " << msg << endl; } private: string m_msg; }; static void test_class() { LuaState l; l.CreateClass<TestClass>("TestClass") .SetConstructor<const char*, int>() .Set("set", &TestClass::Set) .Set("Print", &TestClass::Print); l.CreateClass<TestClass>("TestClass2"); l.DoString("tc1 = TestClass();" "tc1:set('test class 1');" "tc1:print();" "tc2 = TestClass2();" "tc2:set('duplicated test class 2');" "tc2:print()"); } static void test_class_constructor() { LuaState l; auto lclass = l.CreateClass<TestClass>("TestClass").SetConstructor(); l.DoString("tc = TestClass()"); lclass.SetConstructor<const char*, int>(); l.DoString("tc = TestClass('ouonline', 5)"); } static void test_class_member_function() { LuaState l; l.CreateClass<TestClass>("TestClass") .SetConstructor<const char*, int>() .Set("set", &TestClass::Set) .Set("Print", &TestClass::Print) .Set<void, const char*>("echo_str", &TestClass::Echo) // overloaded function .Set<void, int>("echo_int", &TestClass::Echo); l.DoString("tc = TestClass();" // calling TestClass::TestClass(const char*, int) with default values provided by Lua "tc:set('content from lua'); tc:Print();" "tc:echo_str('calling class member function from lua')"); } static void test_class_static_member_function() { LuaState l; string errstr; auto lclass = l.CreateClass<TestClass>("TestClass") .Set("s_echo", &TestClass::StaticEcho); bool ok = l.DoString("TestClass:s_echo('static member function is called without being instantiated');" "tc = TestClass('ouonline', 5);" // error: missing constructor "tc:s_echo('static member function is called by an instance')", &errstr); if (!ok) { cerr << "error: " << errstr << endl; } } static int test_print_all_str(lua_State* l) { int argc = lua_gettop(l); for (int i = 2; i <= argc; ++i) { const char* s = lua_tostring(l, i); cout << "arg[" << i - 2 << "] -> " << s << endl; } return 0; } static void test_class_common_lua_member_function() { LuaState l; string errstr; auto lclass = l.CreateClass<TestClass>("TestClass") .SetConstructor<const char*, int>() .Set("print_all_str", &test_print_all_str); bool ok = l.DoString("t = TestClass('a', 1); t:print_all_str('3', '5', 'ouonline', '1', '2')", &errstr); if (!ok) { cerr << "error: " << errstr << endl; } } static void test_userdata_1() { LuaState l; l.CreateClass<TestClass>("TestClass") .SetConstructor<const char*, int>() .Set("Print", &TestClass::Print); l.CreateUserData<TestClass>("tc", "ouonline", 5).Get<TestClass>()->Set("in lua: Print test data from cpp"); l.DoString("tc:Print()"); } static void test_userdata_2() { LuaState l; l.CreateClass<TestClass>("TestClass") .SetConstructor<const char*, int>() .Set("set", &TestClass::Set); l.DoString("tc = TestClass('ouonline', 5); tc:set('in cpp: Print test data from lua')"); l.Get("tc").ToUserData().Get<TestClass>()->Print(); } static void test_dostring() { LuaState l; string errstr; auto resiter = [] (int n, const LuaObject& lobj) -> bool { cout << "output from resiter: "; if (n == 0) { cout << lobj.ToString() << endl; } else if (n == 1) { cout << lobj.ToNumber() << endl; } return true; }; GenericFunctionHelper helper(resiter); if (!l.DoString("return 'ouonline', 5", &errstr, &helper)) { cerr << "DoString() failed: " << errstr << endl; } } static void test_misc() { LuaState l; string errstr; if (!l.DoFile(__FILE__, &errstr)) { cerr << "loading " << __FILE__ << " failed: " << errstr << endl; } } static struct { const char* name; void (*func)(); } test_suite[] = { {"test_number", test_number}, {"test_nil", test_nil}, {"test_string", test_string}, {"test_table", test_table}, {"test_function_with_return_value", test_function_with_return_value}, {"test_function_without_return_value", test_function_without_return_value}, {"test_class", test_class}, {"test_class_constructor", test_class_constructor}, {"test_class_member_function", test_class_member_function}, {"test_class_static_member_function", test_class_static_member_function}, {"test_class_common_lua_member_function", test_class_common_lua_member_function}, {"test_userdata_1", test_userdata_1}, {"test_userdata_2", test_userdata_2}, {"test_dostring", test_dostring}, {"test_misc", test_misc}, {nullptr, nullptr}, }; int main(void) { for (int i = 0; test_suite[i].func; ++i) { cout << "-------------------- " << test_suite[i].name << " --------------------" << endl; test_suite[i].func(); } return 0; } <commit_msg>test demo fix<commit_after>#include <iostream> #include "lua-cpp/luacpp.h" using namespace luacpp; using namespace std; static void test_number() { LuaState l; l.Set("var", 5); auto lobj = l.Get("var"); cout << "var: type -> " << lobj.GetTypeStr() << ", value = " << lobj.ToNumber() << endl; } static void test_nil() { LuaState l; auto lobj = l.Get("nilobj"); cout << "nilobj: type -> " << lobj.GetTypeStr() << endl; } static void test_string() { LuaState l; string var("ouonline"); l.Set("var", var.c_str(), var.size()); auto lobj = l.Get("var"); cout << "var: type -> " << lobj.GetTypeStr() << ", value = " << lobj.ToString() << endl; } static void test_table() { LuaState l; auto iterfunc = [] (const LuaObject& key, const LuaObject& value) -> bool { cout << " "; // indention if (key.GetType() == LUA_TNUMBER) { cout << key.ToNumber(); } else if (key.GetType() == LUA_TSTRING) { cout << key.ToString(); } else { cout << "unsupported key type -> " << key.GetTypeStr() << endl; return false; } if (value.GetType() == LUA_TNUMBER) { cout << " -> " << value.ToNumber() << endl; } else if (value.GetType() == LUA_TSTRING) { cout << " -> " << value.ToString() << endl; } else { cout << " -> unsupported iter value type: " << value.GetTypeStr() << endl; } return true; }; cout << "table1:" << endl; l.DoString("var = {'mykey', value = 'myvalue', others = 'myothers'}"); l.Get("var").ToTable().ForEach(iterfunc); cout << "table2:" << endl; auto ltable = l.CreateTable(); ltable.Set("x", 5); ltable.Set("o", "ouonline"); ltable.Set("t", ltable); ltable.ForEach(iterfunc); } class GenericFunctionHelper final : public LuaFunctionHelper { public: GenericFunctionHelper(const std::function<bool (int, const LuaObject&)>& f) : m_func(f) {} bool BeforeProcess(int) override { return true; } bool Process(int i, const LuaObject& lobj) override { return m_func(i, lobj); } void AfterProcess() {} private: std::function<bool (int, const LuaObject&)> m_func; }; static void test_function_with_return_value() { LuaState l; auto resiter1 = [] (int, const LuaObject& lobj) -> bool { cout << "output from resiter1: " << lobj.ToString() << endl; return true; }; auto resiter2 = [] (int n, const LuaObject& lobj) -> bool { cout << "output from resiter2: "; if (n == 0) { cout << lobj.ToNumber() << endl; } else if (n == 1) { cout << lobj.ToString() << endl; } return true; }; GenericFunctionHelper helper1(resiter1), helper2(resiter2); std::function<int (const char*)> Echo = [] (const char* msg) -> int { cout << msg; return 5; }; auto lfunc = l.CreateFunction(Echo, "Echo"); l.Set("msg", "calling cpp function with return value from cpp: "); lfunc.Exec(nullptr, &helper1, l.Get("msg")); l.DoString("res = Echo('calling cpp function with return value from lua: ');" "io.write('return value -> ', res, '\\n')"); l.DoString("function return2(a, b) return a, b end"); l.Get("return2").ToFunctiong().Exec(nullptr, &helper2, 5, "ouonline"); } static void Echo(const char* msg) { cout << msg << endl; } static void test_function_without_return_value() { LuaState l; auto lfunc = l.CreateFunction(Echo, "Echo"); lfunc.Exec(nullptr, nullptr, "calling cpp function without return value from cpp"); l.DoString("Echo('calling cpp function without return value from lua')"); } class TestClass final { public: TestClass() { cout << "TestClass::TestClass() is called without value." << endl; } TestClass(const char* msg, int x) { if (msg) { m_msg = msg; } cout << "TestClass::TestClass() is called with string -> '" << m_msg << "' and value -> " << x << "." << endl; } ~TestClass() { cout << "TestClass::~TestClass() is called." << endl; } void Set(const char* msg) { m_msg = msg; } void Print() const { cout << "TestClass::Print(): " << m_msg << endl; } void Echo(const char* msg) const { cout << "TestClass::Echo(string): " << msg << endl; } void Echo(int v) const { cout << "TestClass::Echo(int): " << v << endl; } static void StaticEcho(const char* msg) { cout << "TestClass::StaticEcho(string): " << msg << endl; } private: string m_msg; }; static void test_class() { LuaState l; l.CreateClass<TestClass>("TestClass") .SetConstructor<const char*, int>() .Set("set", &TestClass::Set) .Set("print", &TestClass::Print); l.CreateClass<TestClass>("TestClass2") .Set("print", &TestClass::Print); string errmsg; bool ok = l.DoString("tc1 = TestClass();" "tc1:set('test class 1');" "tc1:print();" "tc2 = TestClass2();" "tc2:set('duplicated test class 2');" "tc2:print()", &errmsg); if (!ok) { cerr << "error: " << errmsg << endl; exit(-1); } } static void test_class_constructor() { LuaState l; string errmsg; auto lclass = l.CreateClass<TestClass>("TestClass").SetConstructor(); bool ok = l.DoString("tc = TestClass()", &errmsg); if (!ok) { cerr << "error: " << errmsg << endl; exit(-1); } lclass.SetConstructor<const char*, int>(); ok = l.DoString("tc = TestClass('ouonline', 5)", &errmsg); if (!ok) { cerr << "error: " << errmsg << endl; exit(-1); } } static void test_class_member_function() { LuaState l; l.CreateClass<TestClass>("TestClass") .SetConstructor<const char*, int>() .Set("set", &TestClass::Set) .Set("Print", &TestClass::Print) .Set<void, const char*>("echo_str", &TestClass::Echo) // overloaded function .Set<void, int>("echo_int", &TestClass::Echo); l.DoString("tc = TestClass();" // calling TestClass::TestClass(const char*, int) with default values provided by Lua "tc:set('content from lua'); tc:Print();" "tc:echo_str('calling class member function from lua')"); } static void test_class_static_member_function() { LuaState l; string errstr; auto lclass = l.CreateClass<TestClass>("TestClass") .Set("s_echo", &TestClass::StaticEcho); bool ok = l.DoString("TestClass:s_echo('static member function is called without being instantiated');" "tc = TestClass('ouonline', 5);" // error: missing constructor "tc:s_echo('static member function is called by an instance')", &errstr); if (!ok) { cerr << "error: " << errstr << endl; } } static int test_print_all_str(lua_State* l) { int argc = lua_gettop(l); for (int i = 2; i <= argc; ++i) { const char* s = lua_tostring(l, i); cout << "arg[" << i - 2 << "] -> " << s << endl; } return 0; } static void test_class_common_lua_member_function() { LuaState l; string errstr; auto lclass = l.CreateClass<TestClass>("TestClass") .SetConstructor<const char*, int>() .Set("print_all_str", &test_print_all_str); bool ok = l.DoString("t = TestClass('a', 1); t:print_all_str('3', '5', 'ouonline', '1', '2')", &errstr); if (!ok) { cerr << "error: " << errstr << endl; exit(-1); } } static void test_userdata_1() { LuaState l; l.CreateClass<TestClass>("TestClass") .SetConstructor<const char*, int>() .Set("Print", &TestClass::Print); l.CreateUserData<TestClass>("tc", "ouonline", 5).Get<TestClass>()->Set("in lua: Print test data from cpp"); l.DoString("tc:Print()"); } static void test_userdata_2() { LuaState l; l.CreateClass<TestClass>("TestClass") .SetConstructor<const char*, int>() .Set("set", &TestClass::Set); l.DoString("tc = TestClass('ouonline', 5); tc:set('in cpp: Print test data from lua')"); l.Get("tc").ToUserData().Get<TestClass>()->Print(); } static void test_dostring() { LuaState l; string errstr; auto resiter = [] (int n, const LuaObject& lobj) -> bool { cout << "output from resiter: "; if (n == 0) { cout << lobj.ToString() << endl; } else if (n == 1) { cout << lobj.ToNumber() << endl; } return true; }; GenericFunctionHelper helper(resiter); if (!l.DoString("return 'ouonline', 5", &errstr, &helper)) { cerr << "DoString() failed: " << errstr << endl; exit(-1); } } static void test_misc() { LuaState l; string errstr; if (!l.DoFile(__FILE__, &errstr)) { cerr << "loading " << __FILE__ << " failed: " << errstr << endl; exit(-1); } } static struct { const char* name; void (*func)(); } test_suite[] = { {"test_number", test_number}, {"test_nil", test_nil}, {"test_string", test_string}, {"test_table", test_table}, {"test_function_with_return_value", test_function_with_return_value}, {"test_function_without_return_value", test_function_without_return_value}, {"test_class", test_class}, {"test_class_constructor", test_class_constructor}, {"test_class_member_function", test_class_member_function}, {"test_class_static_member_function", test_class_static_member_function}, {"test_class_common_lua_member_function", test_class_common_lua_member_function}, {"test_userdata_1", test_userdata_1}, {"test_userdata_2", test_userdata_2}, {"test_dostring", test_dostring}, {"test_misc", test_misc}, {nullptr, nullptr}, }; int main(void) { for (int i = 0; test_suite[i].func; ++i) { cout << "-------------------- " << test_suite[i].name << " --------------------" << endl; test_suite[i].func(); } return 0; } <|endoftext|>
<commit_before>/* SPIDER.h - Library for flashing LED code. Created by Craig I. Hagan 10/25/2019 Released into the public domain. */ #include "Arduino.h" #include "SPIDER.h" #include "Sleep.h" #include "DFRobotDFPlayerMini.h" //#include "NewPing.h" #define NR_BLINKS 20 #define DELAY_TIME 120 SPIDER::SPIDER(LED leds[], int nr_leds, DFRobotDFPlayerMini *mp3, NewPing *sonar, int activation_distance) { _leds = leds; _nr_leds = nr_leds; _mp3 = mp3; _sonar = sonar; _activation_distance = activation_distance; } void SPIDER::strobe_up() { int led; for (led = 0; led < _nr_leds; led++) { _leds[led].blink(100); do_sleep(10); } } void SPIDER::strobe_down() { int led; for (led = _nr_leds - 1; led >= 0; led--) { _leds[led].blink(100); do_sleep(10); } } void SPIDER::glow_up() { int led; for (led = 0; led < _nr_leds - 1; led++) { _leds[led].glow(100); } } void SPIDER::glow_down() { int led; for (led = _nr_leds - 1; led >= 0; led--) { _leds[led].glow(100); } } void SPIDER::glow_purple() { int led; int amount; for (amount = 0; amount <= 255; amount += GLOW_RATE) { for (led = _nr_leds / 2; led < _nr_leds; led++) { _leds[led].dim(amount); } do_sleep(10); } do_sleep(100); for (amount = 255; amount >= 0; amount -= GLOW_RATE) { for (led = _nr_leds / 2; led < _nr_leds; led++) { _leds[led].dim(amount); } do_sleep(10); } } void SPIDER::glow_orange() { int led; int amount; for (amount = 0; amount <= 255; amount += GLOW_RATE) { for (led = 0; led < _nr_leds / 2; led++) { _leds[led].dim(amount); } do_sleep(10); } do_sleep(100); for (amount = 255; amount >= 0; amount -= GLOW_RATE) { for (led = 0; led < _nr_leds / 2; led++) { _leds[led].dim(amount); } do_sleep(10); } } void SPIDER::glow_all() { int led; int amount; for (amount = 0; amount <= 255; amount += GLOW_RATE) { for (led = 0; led < _nr_leds; led++) { _leds[led].dim(amount); } do_sleep(10); } do_sleep(100); for (amount = 255; amount >= 0; amount -= GLOW_RATE) { for (led = 0; led < _nr_leds; led++) { _leds[led].dim(amount); } do_sleep(10); } } void SPIDER::blink_all(int nr_times) { int led, nr_blinks; for (nr_blinks = 0; nr_blinks < nr_times; nr_blinks++) { for (led = 0; led < _nr_leds; led++) { _leds[led].on(); } do_sleep(10); for (led = 0; led < _nr_leds; led++) { _leds[led].off(); } } } void SPIDER::alternate_color(int middle_led, int nr_times, int blink_delay) { int led, nr_blinks; boolean turn_on = false; for (nr_blinks = 0; nr_blinks < nr_times; nr_blinks++) { for (led = 0; led < middle_led; led++) { _leds[led].on(); } for (led = middle_led; led < _nr_leds; led++) { _leds[led].off(); } do_sleep(blink_delay); for (led = 0; led < middle_led; led++) { _leds[led].off(); } for (led = middle_led; led < _nr_leds; led++) { _leds[led].on(); } do_sleep(blink_delay); } for (led = 0; led < _nr_leds; led++) { _leds[led].off(); } } void SPIDER::alternate(int nr_times, int blink_delay) { int led, nr_blinks; boolean turn_on = false; for (nr_blinks = 0; nr_blinks < nr_times; nr_blinks++) { for (led = 0; led < _nr_leds; led++) { if (led % 2) { _leds[led].on(); } else { _leds[led].off(); } turn_on = !turn_on; } do_sleep(blink_delay); for (led = 0; led < _nr_leds; led++) { if (led % 2) { _leds[led].off(); } else { _leds[led].on(); } turn_on = !turn_on; } do_sleep(blink_delay); } for (led = 0; led < _nr_leds; led++) { _leds[led].off(); } } void SPIDER::shira_morse() { // shira : // s : ... // h : .... // i : .. // r : .-. // a : .- int led; int after_letter_delay = 128; int between_letter_delay = 532; // s led = random(_nr_leds); _leds[led].dot(); do_sleep(after_letter_delay); _leds[led].dot(); do_sleep(after_letter_delay); _leds[led].dot(); do_sleep(between_letter_delay); // h led += 1; if (led > _nr_leds) led = 0; _leds[led].dot(); do_sleep(after_letter_delay); _leds[led].dot(); do_sleep(after_letter_delay); _leds[led].dot(); do_sleep(after_letter_delay); _leds[led].dot(); do_sleep(between_letter_delay); // i led += 1; if (led > _nr_leds) led = 0; _leds[led].dot(); do_sleep(after_letter_delay); _leds[led].dot(); do_sleep(between_letter_delay); // r led += 1; if (led > _nr_leds) led = 0; _leds[led].dot(); do_sleep(after_letter_delay); _leds[led].dash(); do_sleep(after_letter_delay); _leds[led].dot(); do_sleep(between_letter_delay); // a led += 1; if (led > _nr_leds) led = 0; _leds[led].dot(); do_sleep(after_letter_delay); _leds[led].dash(); do_sleep(between_letter_delay); } void SPIDER::all_on() { int led; for (led = 0; led < _nr_leds; led++) { _leds[led].on(); } do_sleep(64); for (led = 0; led < _nr_leds; led++) { _leds[led].off(); } } void SPIDER::print_detail(uint8_t type, int value) { switch (type) { case TimeOut: Serial.println(F("Time Out!")); break; case WrongStack: Serial.println(F("Stack Wrong!")); break; case DFPlayerCardInserted: Serial.println(F("Card Inserted!")); break; case DFPlayerCardRemoved: Serial.println(F("Card Removed!")); break; case DFPlayerCardOnline: Serial.println(F("Card Online!")); break; case DFPlayerPlayFinished: Serial.print(F("Number:")); Serial.print(value); Serial.println(F(" Play Finished!")); break; case DFPlayerError: Serial.print(F("DFPlayerError:")); switch (value) { case Busy: Serial.println(F("Card not found")); break; case Sleeping: Serial.println(F("Sleeping")); break; case SerialWrongStack: Serial.println(F("Get Wrong Stack")); break; case CheckSumNotMatch: Serial.println(F("Check Sum Not Match")); break; case FileIndexOut: Serial.println(F("File Index Out of Bound")); break; case FileMismatch: Serial.println(F("Cannot Find File")); break; case Advertise: Serial.println(F("In Advertise")); break; default: break; } break; default: break; } } void SPIDER::play_sound() { _mp3->next(); print_detail(_mp3->readType(), _mp3->read()); //Print the detail message from DFPlayer to handle different errors and states. } void SPIDER::play_sound(int file_nr) { _mp3->play(file_nr); print_detail(_mp3->readType(), _mp3->read()); //Print the detail message from DFPlayer to handle different errors and states. } void SPIDER::test() { int led; for (led = 0; led < _nr_leds; led++) { _leds[led].on(); do_sleep(1024); _leds[led].off(); } play_sound(2); } void SPIDER::wait_sensor_activated() { float distance = 0; while (true) { distance = _sonar->ping_in(); Serial.print("Distance = "); Serial.print(distance); Serial.println(" in"); // Send results to Serial Monitor if (distance > 0 and distance <= 36) { return; } } do_sleep(250); } void SPIDER::start() { int led; //int action = random(17); int action = random(3) + 10; Serial.println(action); //action = 11; //deleteme switch (action) { case 0: case 1: // strobe up play_sound(); strobe_up(); break; case 2: case 3: // strobe down play_sound(); strobe_down(); break; case 5: play_sound(); strobe_up(); strobe_down(); break; case 6: play_sound(); alternate_color(2, NR_BLINKS, DELAY_TIME); break; case 7: play_sound(); glow_orange(); break; case 8: play_sound(); glow_purple(); break; case 9: led = random(_nr_leds); _leds[led].choose(); break; case 10: play_sound(); alternate(NR_BLINKS, DELAY_TIME); break; case 11: play_sound(); alternate_color(2, NR_BLINKS, DELAY_TIME); break; case 12: play_sound(); blink_all(NR_BLINKS); break; case 13: play_sound(); glow_all(); break; case 14: play_sound(); shira_morse(); break; case 15: play_sound(); alternate(NR_BLINKS, DELAY_TIME); break; case 16: play_sound(); all_on(); break; } do_sleep(3000); wait_sensor_activated(); } <commit_msg>finalize choices<commit_after>/* SPIDER.h - Library for flashing LED code. Created by Craig I. Hagan 10/25/2019 Released into the public domain. */ #include "Arduino.h" #include "SPIDER.h" #include "Sleep.h" #include "DFRobotDFPlayerMini.h" //#include "NewPing.h" #define NR_BLINKS 20 #define DELAY_TIME 120 SPIDER::SPIDER(LED leds[], int nr_leds, DFRobotDFPlayerMini *mp3, NewPing *sonar, int activation_distance) { _leds = leds; _nr_leds = nr_leds; _mp3 = mp3; _sonar = sonar; _activation_distance = activation_distance; } void SPIDER::strobe_up() { int led; for (led = 0; led < _nr_leds; led++) { _leds[led].blink(100); do_sleep(10); } } void SPIDER::strobe_down() { int led; for (led = _nr_leds - 1; led >= 0; led--) { _leds[led].blink(100); do_sleep(10); } } void SPIDER::glow_up() { int led; for (led = 0; led < _nr_leds - 1; led++) { _leds[led].glow(100); } } void SPIDER::glow_down() { int led; for (led = _nr_leds - 1; led >= 0; led--) { _leds[led].glow(100); } } void SPIDER::glow_purple() { int led; int amount; for (amount = 0; amount <= 255; amount += GLOW_RATE) { for (led = _nr_leds / 2; led < _nr_leds; led++) { _leds[led].dim(amount); } do_sleep(10); } do_sleep(100); for (amount = 255; amount >= 0; amount -= GLOW_RATE) { for (led = _nr_leds / 2; led < _nr_leds; led++) { _leds[led].dim(amount); } do_sleep(10); } } void SPIDER::glow_orange() { int led; int amount; for (amount = 0; amount <= 255; amount += GLOW_RATE) { for (led = 0; led < _nr_leds / 2; led++) { _leds[led].dim(amount); } do_sleep(10); } do_sleep(100); for (amount = 255; amount >= 0; amount -= GLOW_RATE) { for (led = 0; led < _nr_leds / 2; led++) { _leds[led].dim(amount); } do_sleep(10); } } void SPIDER::glow_all() { int led; int amount; for (amount = 0; amount <= 255; amount += GLOW_RATE) { for (led = 0; led < _nr_leds; led++) { _leds[led].dim(amount); } do_sleep(10); } do_sleep(100); for (amount = 255; amount >= 0; amount -= GLOW_RATE) { for (led = 0; led < _nr_leds; led++) { _leds[led].dim(amount); } do_sleep(10); } } void SPIDER::blink_all(int nr_times) { int led, nr_blinks; for (nr_blinks = 0; nr_blinks < nr_times; nr_blinks++) { for (led = 0; led < _nr_leds; led++) { _leds[led].on(); } do_sleep(10); for (led = 0; led < _nr_leds; led++) { _leds[led].off(); } } } void SPIDER::alternate_color(int middle_led, int nr_times, int blink_delay) { int led, nr_blinks; boolean turn_on = false; for (nr_blinks = 0; nr_blinks < nr_times; nr_blinks++) { for (led = 0; led < middle_led; led++) { _leds[led].on(); } for (led = middle_led; led < _nr_leds; led++) { _leds[led].off(); } do_sleep(blink_delay); for (led = 0; led < middle_led; led++) { _leds[led].off(); } for (led = middle_led; led < _nr_leds; led++) { _leds[led].on(); } do_sleep(blink_delay); } for (led = 0; led < _nr_leds; led++) { _leds[led].off(); } } void SPIDER::alternate(int nr_times, int blink_delay) { int led, nr_blinks; boolean turn_on = false; for (nr_blinks = 0; nr_blinks < nr_times; nr_blinks++) { for (led = 0; led < _nr_leds; led++) { if (led % 2) { _leds[led].on(); } else { _leds[led].off(); } turn_on = !turn_on; } do_sleep(blink_delay); for (led = 0; led < _nr_leds; led++) { if (led % 2) { _leds[led].off(); } else { _leds[led].on(); } turn_on = !turn_on; } do_sleep(blink_delay); } for (led = 0; led < _nr_leds; led++) { _leds[led].off(); } } void SPIDER::shira_morse() { // shira : // s : ... // h : .... // i : .. // r : .-. // a : .- int led; int after_letter_delay = 128; int between_letter_delay = 532; // s led = random(_nr_leds); _leds[led].dot(); do_sleep(after_letter_delay); _leds[led].dot(); do_sleep(after_letter_delay); _leds[led].dot(); do_sleep(between_letter_delay); // h led += 1; if (led > _nr_leds) led = 0; _leds[led].dot(); do_sleep(after_letter_delay); _leds[led].dot(); do_sleep(after_letter_delay); _leds[led].dot(); do_sleep(after_letter_delay); _leds[led].dot(); do_sleep(between_letter_delay); // i led += 1; if (led > _nr_leds) led = 0; _leds[led].dot(); do_sleep(after_letter_delay); _leds[led].dot(); do_sleep(between_letter_delay); // r led += 1; if (led > _nr_leds) led = 0; _leds[led].dot(); do_sleep(after_letter_delay); _leds[led].dash(); do_sleep(after_letter_delay); _leds[led].dot(); do_sleep(between_letter_delay); // a led += 1; if (led > _nr_leds) led = 0; _leds[led].dot(); do_sleep(after_letter_delay); _leds[led].dash(); do_sleep(between_letter_delay); } void SPIDER::all_on() { int led; for (led = 0; led < _nr_leds; led++) { _leds[led].on(); } do_sleep(64); for (led = 0; led < _nr_leds; led++) { _leds[led].off(); } } void SPIDER::print_detail(uint8_t type, int value) { switch (type) { case TimeOut: Serial.println(F("Time Out!")); break; case WrongStack: Serial.println(F("Stack Wrong!")); break; case DFPlayerCardInserted: Serial.println(F("Card Inserted!")); break; case DFPlayerCardRemoved: Serial.println(F("Card Removed!")); break; case DFPlayerCardOnline: Serial.println(F("Card Online!")); break; case DFPlayerPlayFinished: Serial.print(F("Number:")); Serial.print(value); Serial.println(F(" Play Finished!")); break; case DFPlayerError: Serial.print(F("DFPlayerError:")); switch (value) { case Busy: Serial.println(F("Card not found")); break; case Sleeping: Serial.println(F("Sleeping")); break; case SerialWrongStack: Serial.println(F("Get Wrong Stack")); break; case CheckSumNotMatch: Serial.println(F("Check Sum Not Match")); break; case FileIndexOut: Serial.println(F("File Index Out of Bound")); break; case FileMismatch: Serial.println(F("Cannot Find File")); break; case Advertise: Serial.println(F("In Advertise")); break; default: break; } break; default: break; } } void SPIDER::play_sound() { _mp3->next(); print_detail(_mp3->readType(), _mp3->read()); //Print the detail message from DFPlayer to handle different errors and states. } void SPIDER::play_sound(int file_nr) { _mp3->play(file_nr); print_detail(_mp3->readType(), _mp3->read()); //Print the detail message from DFPlayer to handle different errors and states. } void SPIDER::test() { int led; for (led = 0; led < _nr_leds; led++) { _leds[led].on(); do_sleep(1024); _leds[led].off(); } play_sound(2); } void SPIDER::wait_sensor_activated() { float distance = 0; while (true) { distance = _sonar->ping_in(); Serial.print("Distance = "); Serial.print(distance); Serial.println(" in"); // Send results to Serial Monitor if (distance > 0 and distance <= 36) { return; } } do_sleep(250); } void SPIDER::start() { int led; //int action = random(17); int action = random(3); action = 0; Serial.println(action); switch (action) { case 0: play_sound(); alternate(NR_BLINKS, DELAY_TIME); break; case 1: play_sound(); alternate_color(2, NR_BLINKS, DELAY_TIME); break; case 2: play_sound(); blink_all(NR_BLINKS); break; } do_sleep(3000); wait_sensor_activated(); } <|endoftext|>
<commit_before> // Date Created: January 03, 2014 // Last Modified: January 03, 2014 // // Author: Vallentin <mail@vallentinsource.com> // // Github: https://github.com/VallentinSource/SimpleBMP #include "simplebmp.h" #define _CRT_SECURE_NO_WARNINGS #include <fstream> int SimpleBMP::save(const int width, const int height, const unsigned char *pixels, const char *path) { unsigned char bmp_file_header[14] = { 'B', 'M', 0, 0, 0, 0, 0, 0, 0, 0, 54, 0, 0, 0, }; unsigned char bmp_info_header[40] = { 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 24, 0, }; unsigned char bmp_pad[3] = { 0, 0, 0, }; const int size = 54 + width * height * 3; bmp_file_header[2] = static_cast<unsigned char>(size); bmp_file_header[3] = static_cast<unsigned char>(size >> 8); bmp_file_header[4] = static_cast<unsigned char>(size >> 16); bmp_file_header[5] = static_cast<unsigned char>(size >> 24); bmp_info_header[4] = static_cast<unsigned char>(width); bmp_info_header[5] = static_cast<unsigned char>(width >> 8); bmp_info_header[6] = static_cast<unsigned char>(width >> 16); bmp_info_header[7] = static_cast<unsigned char>(width >> 24); bmp_info_header[8] = static_cast<unsigned char>(height); bmp_info_header[9] = static_cast<unsigned char>(height >> 8); bmp_info_header[10] = static_cast<unsigned char>(height >> 16); bmp_info_header[11] = static_cast<unsigned char>(height >> 24); FILE *file = fopen(path, "wb"); if (file) { fwrite(bmp_file_header, 1, 14, file); fwrite(bmp_info_header, 1, 40, file); // for (int i = 0; i < height; i++) for (int i = (height - 1); i >= 0; i--) { fwrite(pixels + (width * i * 3), 3, width, file); fwrite(bmp_pad, 1, ((4 - (width * 3) % 4) % 4), file); } fclose(file); return SIMPLEBMP_NO_ERROR; } return SIMPLEBMP_FOPEN_ERROR; } int SimpleBMP::load(int *width, int *height, unsigned char **pixels, const char *path) { FILE *file = fopen(path, "rb"); if (file) { unsigned char bmp_file_header[14] = { 'B', 'M', 0, 0, 0, 0, 0, 0, 0, 0, 54, 0, 0, 0, }; unsigned char bmp_info_header[40] = { 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 24, 0, }; unsigned char bmp_pad[3] = { 0, 0, 0, }; memset(bmp_file_header, 0, sizeof(bmp_file_header)); memset(bmp_info_header, 0, sizeof(bmp_info_header)); fread(bmp_file_header, sizeof(bmp_file_header), 1, file); fread(bmp_info_header, sizeof(bmp_info_header), 1, file); if ((bmp_file_header[0] != 'B') || (bmp_file_header[1] != 'M')) { fclose(file); return SIMPLEBMP_INVALID_SIGNATURE; } if ((bmp_info_header[14] != 24) && (bmp_info_header[14] != 32)) { fclose(file); return SIMPLEBMP_INVALID_BITS_PER_PIXEL; } int w = (bmp_info_header[4] + (bmp_info_header[5] << 8) + (bmp_info_header[6] << 16) + (bmp_info_header[7] << 24)); int h = (bmp_info_header[8] + (bmp_info_header[9] << 8) + (bmp_info_header[10] << 16) + (bmp_info_header[11] << 24)); unsigned char *p = new unsigned char[w * h * 3]; // for (int i = 0; i < height; i++) for (int i = (h - 1); i >= 0; i--) { fread(p + (w * i * 3), 3, w, file); fread(bmp_pad, 1, (4 - (w * 3) % 4) % 4, file); } (*width) = w; (*height) = h; (*pixels) = p; fclose(file); return SIMPLEBMP_NO_ERROR; } return SIMPLEBMP_FOPEN_ERROR; } void SimpleBMP::setPixel(const int width, const int height, unsigned char *pixels, const int x, const int y, const unsigned char red, const unsigned char green, const unsigned char blue) { pixels[x * 3 + y * width * 3 + 2] = red; pixels[x * 3 + y * width * 3 + 1] = green; pixels[x * 3 + y * width * 3 + 0] = blue; } void SimpleBMP::getPixel(const int width, const int height, const unsigned char *pixels, const int x, const int y, unsigned char *red, unsigned char *green, unsigned char *blue) { if (red) { (*red) = pixels[x * 3 + y * width * 3 + 2]; } if (green) { (*green) = pixels[x * 3 + y * width * 3 + 1]; } if (blue) { (*blue) = pixels[x * 3 + y * width * 3 + 0]; } } void SimpleBMP::setRGB(const int width, const int height, unsigned char *pixels, const int x, const int y, const int rgb) { const int red = ((rgb >> 16) & 0xFF); const int green = ((rgb >> 8) & 0xFF); const int blue = (rgb & 0xFF); // const int alpha = ((rgb >> 24) & 0xFF); SimpleBMP::setPixel(width, height, pixels, x, y, red, green, blue); } int SimpleBMP::getRGB(const int width, const int height, const unsigned char *pixels, const int x, const int y) { unsigned char red, green, blue; SimpleBMP::getPixel(width, height, pixels, x, y, &red, &green, &blue); return ((red << 16) | (green << 8) | blue); // return ((alpha << 24) | (red << 16) | (green << 8) | blue); } // SimpleBMP::SimpleBMP(void) {} SimpleBMP::SimpleBMP(const int square) { this->setSize(square, square); } SimpleBMP::SimpleBMP(const int width, const int height, unsigned char *pixels) { if (pixels) { this->setPixels(width, height, pixels); } else { this->setSize(width, height); } } SimpleBMP::~SimpleBMP(void) { this->destroy(); } int SimpleBMP::save(const char *path) const { return SimpleBMP::save(this->width, this->height, this->pixels, path); } int SimpleBMP::load(const char *path) { this->destroy(); return SimpleBMP::load(&this->width, &this->height, &this->pixels, path); } void SimpleBMP::setPixel(const int x, const int y, const unsigned char red, const unsigned char green, const unsigned char blue) { SimpleBMP::setPixel(this->width, this->height, this->pixels, x, y, red, green, blue); } void SimpleBMP::getPixel(const int x, const int y, unsigned char *red, unsigned char *green, unsigned char *blue) const { SimpleBMP::getPixel(this->width, this->height, this->pixels, x, y, red, green, blue); } void SimpleBMP::setRGB(const int x, const int y, const int rgb) { SimpleBMP::setRGB(this->width, this->height, this->pixels, x, y, rgb); } int SimpleBMP::getRGB(const int x, const int y) const { return SimpleBMP::getRGB(this->width, this->height, this->pixels, x, y); } void SimpleBMP::setPixels(unsigned char *pixels) { for (int i = (this->width * this->height * 3 - 1); i >= 0; i--) { this->pixels[i] = pixels[i]; } } void SimpleBMP::setPixels(const int width, const int height, unsigned char *pixels) { this->setSize(width, height); this->setPixels(pixels); } void SimpleBMP::setSize(const int width, const int height) { this->destroy(); this->width = width; this->height = height; this->pixels = new unsigned char[width * height * 3]; // 3 = R, G, B } void SimpleBMP::destroy(void) { this->width = 0; this->height = 0; if (this->pixels) { delete[] this->pixels; this->pixels = nullptr; } } bool SimpleBMP::isValid(void) const { if (this->pixels) { return ((this->width > 0) && (this->height > 0)); } return true; } bool SimpleBMP::isValid(const int x, const int y) const { if (this->isValid()) { if (x < 0) { return false; } if (y < 0) { return false; } if (x >= this->width) { return false; } if (y >= this->height) { return false; } return true; } return false; } unsigned int SimpleBMP::getWidth(void) const { return this->width; } unsigned int SimpleBMP::getHeight(void) const { return this->height; } unsigned char* SimpleBMP::getPixels(void) const { return this->pixels; } <commit_msg>Added a few features and changes some stuff. Though everything is still backward-compatible!<commit_after> // Date Created: January 03, 2014 // Last Modified: January 05, 2014 // // Author: Vallentin <mail@vallentinsource.com> // // Github: https://github.com/VallentinSource/SimpleBMP #include "simplebmp.h" #define _CRT_SECURE_NO_WARNINGS #include <fstream> int SimpleBMP::save(const int width, const int height, const unsigned char *pixels, const char *path) { unsigned char bmp_file_header[14] = { 'B', 'M', 0, 0, 0, 0, 0, 0, 0, 0, 54, 0, 0, 0, }; unsigned char bmp_info_header[40] = { 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 24, 0, }; unsigned char bmp_pad[3] = { 0, 0, 0, }; const int size = 54 + width * height * 3; bmp_file_header[2] = static_cast<unsigned char>(size); bmp_file_header[3] = static_cast<unsigned char>(size >> 8); bmp_file_header[4] = static_cast<unsigned char>(size >> 16); bmp_file_header[5] = static_cast<unsigned char>(size >> 24); bmp_info_header[4] = static_cast<unsigned char>(width); bmp_info_header[5] = static_cast<unsigned char>(width >> 8); bmp_info_header[6] = static_cast<unsigned char>(width >> 16); bmp_info_header[7] = static_cast<unsigned char>(width >> 24); bmp_info_header[8] = static_cast<unsigned char>(height); bmp_info_header[9] = static_cast<unsigned char>(height >> 8); bmp_info_header[10] = static_cast<unsigned char>(height >> 16); bmp_info_header[11] = static_cast<unsigned char>(height >> 24); FILE *file = fopen(path, "wb"); if (file) { fwrite(bmp_file_header, 1, 14, file); fwrite(bmp_info_header, 1, 40, file); for (int i = 0; i < height; i++) // for (int i = (height - 1); i >= 0; i--) { fwrite(pixels + (width * i * 3), 3, width, file); fwrite(bmp_pad, 1, ((4 - (width * 3) % 4) % 4), file); } fclose(file); return SIMPLEBMP_NO_ERROR; } return SIMPLEBMP_FOPEN_ERROR; } int SimpleBMP::load(int *width, int *height, unsigned char **pixels, const char *path) { FILE *file = fopen(path, "rb"); if (file) { unsigned char bmp_file_header[14] = { 'B', 'M', 0, 0, 0, 0, 0, 0, 0, 0, 54, 0, 0, 0, }; unsigned char bmp_info_header[40] = { 40, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 24, 0, }; unsigned char bmp_pad[3] = { 0, 0, 0, }; memset(bmp_file_header, 0, sizeof(bmp_file_header)); memset(bmp_info_header, 0, sizeof(bmp_info_header)); fread(bmp_file_header, sizeof(bmp_file_header), 1, file); fread(bmp_info_header, sizeof(bmp_info_header), 1, file); if ((bmp_file_header[0] != 'B') || (bmp_file_header[1] != 'M')) { fclose(file); return SIMPLEBMP_INVALID_SIGNATURE; } if ((bmp_info_header[14] != 24) && (bmp_info_header[14] != 32)) { fclose(file); return SIMPLEBMP_INVALID_BITS_PER_PIXEL; } int w = (bmp_info_header[4] + (bmp_info_header[5] << 8) + (bmp_info_header[6] << 16) + (bmp_info_header[7] << 24)); int h = (bmp_info_header[8] + (bmp_info_header[9] << 8) + (bmp_info_header[10] << 16) + (bmp_info_header[11] << 24)); unsigned char *p = new unsigned char[w * h * 3]; for (int i = 0; i < h; i++) // for (int i = (h - 1); i >= 0; i--) { fread(p + (w * i * 3), 3, w, file); fread(bmp_pad, 1, (4 - (w * 3) % 4) % 4, file); } (*width) = w; (*height) = h; (*pixels) = p; fclose(file); return SIMPLEBMP_NO_ERROR; } return SIMPLEBMP_FOPEN_ERROR; } void SimpleBMP::setPixel(const int width, const int height, unsigned char *pixels, const int x, const int y, const unsigned char red, const unsigned char green, const unsigned char blue) { pixels[x * 3 + (height - y - 1) * width * 3 + 2] = red; pixels[x * 3 + (height - y - 1) * width * 3 + 1] = green; pixels[x * 3 + (height - y - 1) * width * 3 + 0] = blue; } void SimpleBMP::getPixel(const int width, const int height, const unsigned char *pixels, const int x, const int y, unsigned char *red, unsigned char *green, unsigned char *blue) { if (red) { (*red) = pixels[x * 3 + (height - y - 1) * width * 3 + 2]; } if (green) { (*green) = pixels[x * 3 + (height - y - 1) * width * 3 + 1]; } if (blue) { (*blue) = pixels[x * 3 + (height - y - 1) * width * 3 + 0]; } } void SimpleBMP::setRGB(const int width, const int height, unsigned char *pixels, const int x, const int y, const int rgb) { const int red = ((rgb >> 16) & 0xFF); const int green = ((rgb >> 8) & 0xFF); const int blue = (rgb & 0xFF); // const int alpha = ((rgb >> 24) & 0xFF); SimpleBMP::setPixel(width, height, pixels, x, y, red, green, blue); } int SimpleBMP::getRGB(const int width, const int height, const unsigned char *pixels, const int x, const int y) { unsigned char red, green, blue; SimpleBMP::getPixel(width, height, pixels, x, y, &red, &green, &blue); return ((red << 16) | (green << 8) | blue); // return ((alpha << 24) | (red << 16) | (green << 8) | blue); } // SimpleBMP::SimpleBMP(void) {} SimpleBMP::SimpleBMP(const int square) { this->setSize(square, square); } SimpleBMP::SimpleBMP(const int width, const int height, unsigned char *pixels) { if (pixels) { this->setPixels(width, height, pixels); } else { this->setSize(width, height); } } SimpleBMP::~SimpleBMP(void) { this->destroy(); } int SimpleBMP::save(const char *path) const { return SimpleBMP::save(this->width, this->height, this->pixels, path); } int SimpleBMP::load(const char *path) { this->destroy(); return SimpleBMP::load(&this->width, &this->height, &this->pixels, path); } void SimpleBMP::setPixel(const int x, const int y, const unsigned char red, const unsigned char green, const unsigned char blue) { SimpleBMP::setPixel(this->width, this->height, this->pixels, x, y, red, green, blue); } void SimpleBMP::getPixel(const int x, const int y, unsigned char *red, unsigned char *green, unsigned char *blue) const { SimpleBMP::getPixel(this->width, this->height, this->pixels, x, y, red, green, blue); } void SimpleBMP::setRGB(const int x, const int y, const int rgb) { SimpleBMP::setRGB(this->width, this->height, this->pixels, x, y, rgb); } int SimpleBMP::getRGB(const int x, const int y) const { return SimpleBMP::getRGB(this->width, this->height, this->pixels, x, y); } void SimpleBMP::setPixels(unsigned char *pixels) { for (int i = (this->width * this->height * 3 - 1); i >= 0; i--) { this->pixels[i] = pixels[i]; } } void SimpleBMP::setPixels(const int width, const int height, unsigned char *pixels) { this->setSize(width, height); this->setPixels(pixels); } void SimpleBMP::setSize(const int width, const int height) { this->destroy(); this->width = width; this->height = height; this->pixels = new unsigned char[width * height * 3]; // 3 = R, G, B } void SimpleBMP::destroy(void) { this->width = 0; this->height = 0; if (this->pixels) { delete[] this->pixels; this->pixels = nullptr; } } bool SimpleBMP::isValid(void) const { if (this->pixels) { return ((this->width > 0) && (this->height > 0)); } return true; } bool SimpleBMP::isValid(const int x, const int y) const { if (this->isValid()) { if (x < 0) { return false; } if (y < 0) { return false; } if (x >= this->width) { return false; } if (y >= this->height) { return false; } return true; } return false; } unsigned int SimpleBMP::getWidth(void) const { return this->width; } unsigned int SimpleBMP::getHeight(void) const { return this->height; } unsigned char* SimpleBMP::getPixels(void) const { return this->pixels; } <|endoftext|>
<commit_before>extern "C" { #include "thumbnailer.h" #include <string.h> } #include "util.hh" #include <Magick++.h> #include <functional> #include <stdexcept> #ifndef MIT_LICENSE #include "compress_png.hh" #endif // MIT_LICENSE // Iterates over all pixels and checks, if any transparency present static bool has_transparency(const Magick::Image& img) { // No alpha channel if (!img.matte()) { return false; } // Transparent pixels are most likely to also be in the first row, so // retrieve one row at a time. It is also more performant to retrieve // entire rows instead of individual pixels. for (unsigned long i = 0; i < img.rows(); i++) { const auto packets = img.getConstPixels(0, i, img.columns(), 1); for (unsigned long j = 0; j < img.columns(); j++) { if (packets[j].opacity > 0) { return true; } } } return false; } // Convert thumbnail to appropriate file type and write to buffer static void write_thumb( Magick::Image& img, struct Thumbnail* thumb, const struct Options opts) { const bool need_png = img.magick() != "JPEG" && has_transparency(img); if (need_png) { thumb->isPNG = true; #ifndef MIT_LICENSE return compress_png(img, thumb, opts.PNGCompression); #else img.magick("PNG"); img.quality(105); img.depth(8); #endif // MIT_LICENSE } else { img.magick("JPEG"); img.quality(get_quality(75, opts.JPEGCompression)); } Magick::Blob out; img.write(&out); thumb->img.data = (uint8_t*)malloc(out.length()); memcpy(thumb->img.data, out.data(), out.length()); thumb->img.size = out.length(); } static void _thumbnail( struct Buffer* src, struct Thumbnail* thumb, const struct Options opts) { Magick::Blob blob; blob.updateNoCopy(src->data, src->size, Magick::Blob::MallocAllocator); // If width and height are already defined, then a frame from ffmpeg has // been passed Magick::Image img = (src->width && src->height) ? Magick::Image( blob, Magick::Geometry(src->width, src->height), 8, "RGBA") : Magick::Image(blob, Magick::Geometry(src->width, src->height)); src->width = img.columns(); src->height = img.rows(); // Read only the first frame/page of GIFs and PDFs img.subImage(0); img.subRange(1); // Validate dimensions if (img.magick() != "PDF") { const unsigned long maxW = opts.maxSrcDims.width; const unsigned long maxH = opts.maxSrcDims.height; if (maxW && img.columns() > maxW) { throw std::invalid_argument("too wide"); } if (maxH && img.rows() > maxH) { throw std::invalid_argument("too tall"); } } // Rotate image based on EXIF metadata, if needed if (img.orientation() > Magick::OrientationType::TopLeftOrientation) { // As of writing the Magick::Image::autoOrient() method is not yet in // the GraphicsMagick++ version in Debian stable repos. Inlined it here. MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo(&exceptionInfo); MagickLib::Image* newImage = AutoOrientImage(img.image(), img.orientation(), &exceptionInfo); img.replaceImage(newImage); Magick::throwException(exceptionInfo); } // Strip EXIF metadata, if any img.strip(); // Maintain aspect ratio const double scale = img.columns() >= img.rows() ? (double)img.columns() / (double)opts.thumbDims.width : (double)img.rows() / (double)opts.thumbDims.height; thumb->img.width = (unsigned long)((double)img.columns() / scale); thumb->img.height = (unsigned long)((double)img.rows() / scale); img.thumbnail(Magick::Geometry(thumb->img.width, thumb->img.height)); write_thumb(img, thumb, opts); } // Catches amd converts exception, if any, to C string and returns it. // Otherwise returns NULL. static char* pass_exception(std::function<void()> fn) { try { fn(); return NULL; } catch (...) { auto e = std::current_exception(); try { if (e) { std::rethrow_exception(e); } return NULL; } catch (const std::exception& e) { char* buf = (char*)malloc(strlen(e.what()) + 1); strcpy(buf, e.what()); return buf; } } } extern "C" char* thumbnail( struct Buffer* src, struct Thumbnail* thumb, const struct Options opts) { return pass_exception([=]() { _thumbnail(src, thumb, opts); }); } <commit_msg>Prevent upscaling small images<commit_after>extern "C" { #include "thumbnailer.h" #include <string.h> } #include "util.hh" #include <Magick++.h> #include <functional> #include <stdexcept> #ifndef MIT_LICENSE #include "compress_png.hh" #endif // MIT_LICENSE // Iterates over all pixels and checks, if any transparency present static bool has_transparency(const Magick::Image& img) { // No alpha channel if (!img.matte()) { return false; } // Transparent pixels are most likely to also be in the first row, so // retrieve one row at a time. It is also more performant to retrieve // entire rows instead of individual pixels. for (unsigned long i = 0; i < img.rows(); i++) { const auto packets = img.getConstPixels(0, i, img.columns(), 1); for (unsigned long j = 0; j < img.columns(); j++) { if (packets[j].opacity > 0) { return true; } } } return false; } // Convert thumbnail to appropriate file type and write to buffer static void write_thumb( Magick::Image& img, struct Thumbnail* thumb, const struct Options opts) { const bool need_png = img.magick() != "JPEG" && has_transparency(img); if (need_png) { thumb->isPNG = true; #ifndef MIT_LICENSE return compress_png(img, thumb, opts.PNGCompression); #else img.magick("PNG"); img.quality(105); img.depth(8); #endif // MIT_LICENSE } else { img.magick("JPEG"); img.quality(get_quality(75, opts.JPEGCompression)); } Magick::Blob out; img.write(&out); thumb->img.data = (uint8_t*)malloc(out.length()); memcpy(thumb->img.data, out.data(), out.length()); thumb->img.size = out.length(); } static void _thumbnail( struct Buffer* src, struct Thumbnail* thumb, const struct Options opts) { Magick::Blob blob; blob.updateNoCopy(src->data, src->size, Magick::Blob::MallocAllocator); // If width and height are already defined, then a frame from ffmpeg has // been passed Magick::Image img = (src->width && src->height) ? Magick::Image( blob, Magick::Geometry(src->width, src->height), 8, "RGBA") : Magick::Image(blob, Magick::Geometry(src->width, src->height)); src->width = img.columns(); src->height = img.rows(); // Read only the first frame/page of GIFs and PDFs img.subImage(0); img.subRange(1); // Validate dimensions if (img.magick() != "PDF") { const unsigned long maxW = opts.maxSrcDims.width; const unsigned long maxH = opts.maxSrcDims.height; if (maxW && img.columns() > maxW) { throw std::invalid_argument("too wide"); } if (maxH && img.rows() > maxH) { throw std::invalid_argument("too tall"); } } // Rotate image based on EXIF metadata, if needed if (img.orientation() > Magick::OrientationType::TopLeftOrientation) { // As of writing the Magick::Image::autoOrient() method is not yet in // the GraphicsMagick++ version in Debian stable repos. Inlined it here. MagickLib::ExceptionInfo exceptionInfo; MagickLib::GetExceptionInfo(&exceptionInfo); MagickLib::Image* newImage = AutoOrientImage(img.image(), img.orientation(), &exceptionInfo); img.replaceImage(newImage); Magick::throwException(exceptionInfo); } // Strip EXIF metadata, if any img.strip(); const unsigned long thumbW = opts.thumbDims.width; const unsigned long thumbH = opts.thumbDims.height; if (img.columns() <= thumbW && img.rows() <= thumbH) { // Image already fits thumbnail thumb->img.width = img.columns(); thumb->img.height = img.rows(); } else { // Maintain aspect ratio const double scale = img.columns() >= img.rows() ? (double)img.columns() / (double)thumbW : (double)img.rows() / (double)thumbH; thumb->img.width = (unsigned long)((double)img.columns() / scale); thumb->img.height = (unsigned long)((double)img.rows() / scale); img.thumbnail(Magick::Geometry(thumb->img.width, thumb->img.height)); } write_thumb(img, thumb, opts); } // Catches amd converts exception, if any, to C string and returns it. // Otherwise returns NULL. static char* pass_exception(std::function<void()> fn) { try { fn(); return NULL; } catch (...) { auto e = std::current_exception(); try { if (e) { std::rethrow_exception(e); } return NULL; } catch (const std::exception& e) { char* buf = (char*)malloc(strlen(e.what()) + 1); strcpy(buf, e.what()); return buf; } } } extern "C" char* thumbnail( struct Buffer* src, struct Thumbnail* thumb, const struct Options opts) { return pass_exception([=]() { _thumbnail(src, thumb, opts); }); } <|endoftext|>
<commit_before>#include <BALL/STRUCTURE/logP.h> namespace BALL { LogP::LogP() { molecular_similarity_ = new MolecularSimilarity("fragments/functionalGroups.smarts"); addRule("[$([CH4]),$([CH3]C),$([CH2](C)C)]",0.14441); // C1 addRule("[$([CH](C)(C)C),$([C](C)(C)(C)C)]",0.00000); // C2 addRule("[$([CH3][#7,#8,#15,#16,#9,Cl,Br,I]),$([CH2X4][#7,#8,#15,#16,#9,Cl,Br,I])]",-0.2035); // C3 addRule("[$([CH1X4][#7,#8,#15,#16,#9,Cl,Br,I]),$([CH0X4][#7,#8,#15,#16,#9,Cl,Br,I])]",-0.2051); // C4 addRule("[C]=[A;!#1;!#6]",-0.2783); // C5, ali. heteroatom addRule("[$([CH2]=C),$([CH1](=C)A),$([CH0](=C)(A)A),$([C](=C)=C)]",0.1551); // C6 addRule("[CX2]#A",0.00170); // C7 addRule("[CH3]c",0.08452); // C8 addRule("[CH3][a;!#1;!#6]",-0.1444); // C9, aro. heteroatom addRule("[CH2X4]a",-0.0516); // C10 addRule("[CHX4]a",0.1193); // C11 addRule("[CH0X4]a",-0.0967); // C12 addRule("[cH0]-[!#6;!#7;!#8;!#16;!#9;!Cl;!Br;!I]",-0.5443); // C13 //"[$([c][#5],$([c][#14]),$([c][#15]),$([c][#33]),$([c][#34]),$([c][#50]),$([c][#80])]" // C13 alternative addRule("[c][#9]",0.0000); // C14 addRule("[c][#17]",0.2450); // C15 addRule("[c][#35]",0.1980); // C16 addRule("[c][#53]",0.0000); // C17 addRule("[cH]",0.1581); // C18 addRule("[c](:a)(:a):a",0.2955); // C19 addRule("[c](:a)(:a)-a",0.2713); // C20 addRule("[c](:a)(:a)-C",0.1360); // C21 addRule("[c](:a)(:a)-N",0.4619); // C22 addRule("[c](:a)(:a)-O",0.5437); // C23 addRule("[c](:a)(:a)-S",0.1893); // C24 addRule("[$([c](:a)(:a)=C),$([c](:a)(:a)=N),$([c](:a)(:a)=O)]",-0.8186); // C25 addRule("[$([C](=C)(a)A),$([C](=C)(c)a),$([CH](=C)a),$([C]=c)]",0.2640); // C26 addRule("[CX4][!#5;!#7;!#8;!#15;!#16;!#9;!Cl;!Br;!I]",0.2148); // C27 addRule("remaining [C,c]",0.08129); addRule("[$([H,h][#6]),$([H,h][H,h])]",0.1230); // H1, hydrocarbon addRule("[$([H,h]O[CX4]),$([H,h]Oc),$([H,h]O[!#6;!#7;!#8;!16]),$([H,h][!#6;!#7;!#8])]",-0.2677); // H2, alcohol addRule("[$([H,h][#7]),$([H,h]O[#7])]",0.2142); // H3, amine addRule("[$([H,h]OC=[#6]),$([H,h]OC=[#7]),$([H,h]OC=O),$([H,h]OC=S),$([H,h]OO),$([H,h]OS)]",0.2980); // H4, acid addRule("remaining [H,h]",0.1125); addRule("[NH2+0]A",-1.0190); // N1 addRule("[NH+0](A)A",-0.7096); // N2 addRule("[NH2+0]a",-1.0270); // N3 addRule("[$([NH+0](A)a),$([NH+0](a)a)]",-0.5188); // N4 addRule("[$([NH+0]=A),$([NH+0]=a)]",0.08387); // N5 addRule("[$([N+0](=A)A),$([N+0](=A)a),$([N+0](=a)A),$([N+0](=a)a)]",0.1836); // N6 addRule("[N+0](A)(A)A",-0.3187); // N7 addRule("[$([N+0](a)(A)A),$([N+0](a)(a)A),$([N+0](a)(a)a)]",-0.4458); // N8 addRule("[N+0]#A",0.01508); // N9 addRule("[$([NH3+*]),$([NH2+*]),$([NH+*])]",-1.950); // N10 addRule("[n+0]",-0.3239); // N11 addRule("[n+*]",-1.119); // N12 addRule("[$([NH0+*](A)(A)(A)A),$([NH0+*](=A)(A)A),$([NH0+*](=A)(A)a),$([NH0+*](=[#6])=[#7])]",-0.3396); // N13 addRule("[$([N+*]#A),$([N-*]),$([N+*](=[N-*])=N)]",0.2887); // N14 addRule("remaining [N,n]",-0.4806); addRule("[o]",0.1552); // O1 addRule("[$([OH]),$([OH2])]",-0.2893); // O2, alcohol addRule("[$([O](C)C),$([O](C)[A;N,O,P,S,F,Cl,Br,I]),$([O]([A;N,O,P,S,F,Cl,Br,I])[A;N,O,P,S,F,Cl,Br,I])]",-0.0684); // O3, ali. ether addRule("[$([O](A)a),$([O](a)a)]",-0.4195); // O4, aro. ether addRule("[$([O]=[#8]),$([O]=[#7]),$([OX1-*][#7])]",0.0335); // O5, oxide addRule("[OX1-*][#16]",-0.3339); // O6, oxide addRule("[OX1-*][!N;!S]",-1.189); // O7, oxide addRule("[O]=c",0.1788); // O8, aro. carbonyl addRule("[$([O]=[CH]C),$([O]=C(C)C),$([O]=C(C)[A;!#1;!#6]),$([O]=[CH]N),$([O]=[CH]O),$([O]=[CH2]),$([O]=[CX2]=O)]",-0.1525); // O9, carbonyl ali. addRule("[$([O]=[CH]c),$([O]=C(C)c),$([O]=C(c)c),$([O]=C(c)[a;!#1;!#6]),$([O]=C(c)[A;!#1;!#6]),$([O]=C(C)[a;!#1;!#6])]",0.1129); // O10, carbonyl aro. addRule("[$([O]=C([A;!#1;!#6])[A;!#1;!#6]),$([O]=C([A;!#1;!#6])[a;!#1;!#6]),$([O]=C([a;!#1;!#6])[a;!#1;!#6])]",0.4833); // O11, carbonyl heteroatom addRule("[O-1]C(=O)",-1.326); // O12, acid addRule("remaining [O,o]",-0.1188); addRule("[#9-0]",0.4202); // flourine addRule("remaining [#9]",-2.996); addRule("[#17-0]",0.6895); // chlorine addRule("remaining [#17]",-2.996); addRule("[#35-0]",0.8456); // bromine addRule("remaining [#35]",-2.996); addRule("[#53-0]",0.8857); // iodine addRule("remaining [#53]",-2.996); addRule("[#15]",0.8612); // phosphorous addRule("[S-0]",0.6482); // aliphatic sulfur addRule("[$([S-*]),$([S-*])]",-0.0024); // ionic sulfur addRule("[s]",0.6237); // aromatic sulfur addRule("[B,Si,Ga,Ge,As,Se,Sn,Te,Pb,Ne,Ar,Kr,Xe,Rn]",-0.3808); // remaining p-block elements addRule("[Fe,Cu,Zn,Tc,Cd,Pt,Au,Hg]",-0.0025); // remaining d-block elements } LogP::~LogP() { delete molecular_similarity_; } void LogP::addRule(String smarts, double value) { rules_.push_back(make_pair(smarts,value)); } double LogP::calculate(const String& usmile) { double logP = 0; Size match_sum = 0; for(Size i=0; i<rules_.size(); i++) { if(!rules_[i].first.hasPrefix("remaining")) { Size matches; molecular_similarity_->matchSmarts(usmile,rules_[i].first,matches); logP += matches*rules_[i].second; match_sum += matches; // if(matches>0) cout<<rules_[i].first<<" : "<<matches<<endl; } else { Size no_atoms; String smarts = rules_[i].first.after("remaining"); smarts.trim(); molecular_similarity_->matchSmarts(usmile,smarts,no_atoms); if(no_atoms>match_sum) { logP += (no_atoms-match_sum)*rules_[i].second; } // if(match_sum>no_atoms) // { // cout<<"Error: Atoms "<<smarts<<" were matches mulitple times!!"<<endl; // cout<<match_sum<<" "<<no_atoms<<endl; // } match_sum=0; } } return logP; } } <commit_msg>Fixed a compile error due to missing namespace qualifier<commit_after>#include <BALL/STRUCTURE/logP.h> using namespace std; namespace BALL { LogP::LogP() { molecular_similarity_ = new MolecularSimilarity("fragments/functionalGroups.smarts"); addRule("[$([CH4]),$([CH3]C),$([CH2](C)C)]",0.14441); // C1 addRule("[$([CH](C)(C)C),$([C](C)(C)(C)C)]",0.00000); // C2 addRule("[$([CH3][#7,#8,#15,#16,#9,Cl,Br,I]),$([CH2X4][#7,#8,#15,#16,#9,Cl,Br,I])]",-0.2035); // C3 addRule("[$([CH1X4][#7,#8,#15,#16,#9,Cl,Br,I]),$([CH0X4][#7,#8,#15,#16,#9,Cl,Br,I])]",-0.2051); // C4 addRule("[C]=[A;!#1;!#6]",-0.2783); // C5, ali. heteroatom addRule("[$([CH2]=C),$([CH1](=C)A),$([CH0](=C)(A)A),$([C](=C)=C)]",0.1551); // C6 addRule("[CX2]#A",0.00170); // C7 addRule("[CH3]c",0.08452); // C8 addRule("[CH3][a;!#1;!#6]",-0.1444); // C9, aro. heteroatom addRule("[CH2X4]a",-0.0516); // C10 addRule("[CHX4]a",0.1193); // C11 addRule("[CH0X4]a",-0.0967); // C12 addRule("[cH0]-[!#6;!#7;!#8;!#16;!#9;!Cl;!Br;!I]",-0.5443); // C13 //"[$([c][#5],$([c][#14]),$([c][#15]),$([c][#33]),$([c][#34]),$([c][#50]),$([c][#80])]" // C13 alternative addRule("[c][#9]",0.0000); // C14 addRule("[c][#17]",0.2450); // C15 addRule("[c][#35]",0.1980); // C16 addRule("[c][#53]",0.0000); // C17 addRule("[cH]",0.1581); // C18 addRule("[c](:a)(:a):a",0.2955); // C19 addRule("[c](:a)(:a)-a",0.2713); // C20 addRule("[c](:a)(:a)-C",0.1360); // C21 addRule("[c](:a)(:a)-N",0.4619); // C22 addRule("[c](:a)(:a)-O",0.5437); // C23 addRule("[c](:a)(:a)-S",0.1893); // C24 addRule("[$([c](:a)(:a)=C),$([c](:a)(:a)=N),$([c](:a)(:a)=O)]",-0.8186); // C25 addRule("[$([C](=C)(a)A),$([C](=C)(c)a),$([CH](=C)a),$([C]=c)]",0.2640); // C26 addRule("[CX4][!#5;!#7;!#8;!#15;!#16;!#9;!Cl;!Br;!I]",0.2148); // C27 addRule("remaining [C,c]",0.08129); addRule("[$([H,h][#6]),$([H,h][H,h])]",0.1230); // H1, hydrocarbon addRule("[$([H,h]O[CX4]),$([H,h]Oc),$([H,h]O[!#6;!#7;!#8;!16]),$([H,h][!#6;!#7;!#8])]",-0.2677); // H2, alcohol addRule("[$([H,h][#7]),$([H,h]O[#7])]",0.2142); // H3, amine addRule("[$([H,h]OC=[#6]),$([H,h]OC=[#7]),$([H,h]OC=O),$([H,h]OC=S),$([H,h]OO),$([H,h]OS)]",0.2980); // H4, acid addRule("remaining [H,h]",0.1125); addRule("[NH2+0]A",-1.0190); // N1 addRule("[NH+0](A)A",-0.7096); // N2 addRule("[NH2+0]a",-1.0270); // N3 addRule("[$([NH+0](A)a),$([NH+0](a)a)]",-0.5188); // N4 addRule("[$([NH+0]=A),$([NH+0]=a)]",0.08387); // N5 addRule("[$([N+0](=A)A),$([N+0](=A)a),$([N+0](=a)A),$([N+0](=a)a)]",0.1836); // N6 addRule("[N+0](A)(A)A",-0.3187); // N7 addRule("[$([N+0](a)(A)A),$([N+0](a)(a)A),$([N+0](a)(a)a)]",-0.4458); // N8 addRule("[N+0]#A",0.01508); // N9 addRule("[$([NH3+*]),$([NH2+*]),$([NH+*])]",-1.950); // N10 addRule("[n+0]",-0.3239); // N11 addRule("[n+*]",-1.119); // N12 addRule("[$([NH0+*](A)(A)(A)A),$([NH0+*](=A)(A)A),$([NH0+*](=A)(A)a),$([NH0+*](=[#6])=[#7])]",-0.3396); // N13 addRule("[$([N+*]#A),$([N-*]),$([N+*](=[N-*])=N)]",0.2887); // N14 addRule("remaining [N,n]",-0.4806); addRule("[o]",0.1552); // O1 addRule("[$([OH]),$([OH2])]",-0.2893); // O2, alcohol addRule("[$([O](C)C),$([O](C)[A;N,O,P,S,F,Cl,Br,I]),$([O]([A;N,O,P,S,F,Cl,Br,I])[A;N,O,P,S,F,Cl,Br,I])]",-0.0684); // O3, ali. ether addRule("[$([O](A)a),$([O](a)a)]",-0.4195); // O4, aro. ether addRule("[$([O]=[#8]),$([O]=[#7]),$([OX1-*][#7])]",0.0335); // O5, oxide addRule("[OX1-*][#16]",-0.3339); // O6, oxide addRule("[OX1-*][!N;!S]",-1.189); // O7, oxide addRule("[O]=c",0.1788); // O8, aro. carbonyl addRule("[$([O]=[CH]C),$([O]=C(C)C),$([O]=C(C)[A;!#1;!#6]),$([O]=[CH]N),$([O]=[CH]O),$([O]=[CH2]),$([O]=[CX2]=O)]",-0.1525); // O9, carbonyl ali. addRule("[$([O]=[CH]c),$([O]=C(C)c),$([O]=C(c)c),$([O]=C(c)[a;!#1;!#6]),$([O]=C(c)[A;!#1;!#6]),$([O]=C(C)[a;!#1;!#6])]",0.1129); // O10, carbonyl aro. addRule("[$([O]=C([A;!#1;!#6])[A;!#1;!#6]),$([O]=C([A;!#1;!#6])[a;!#1;!#6]),$([O]=C([a;!#1;!#6])[a;!#1;!#6])]",0.4833); // O11, carbonyl heteroatom addRule("[O-1]C(=O)",-1.326); // O12, acid addRule("remaining [O,o]",-0.1188); addRule("[#9-0]",0.4202); // flourine addRule("remaining [#9]",-2.996); addRule("[#17-0]",0.6895); // chlorine addRule("remaining [#17]",-2.996); addRule("[#35-0]",0.8456); // bromine addRule("remaining [#35]",-2.996); addRule("[#53-0]",0.8857); // iodine addRule("remaining [#53]",-2.996); addRule("[#15]",0.8612); // phosphorous addRule("[S-0]",0.6482); // aliphatic sulfur addRule("[$([S-*]),$([S-*])]",-0.0024); // ionic sulfur addRule("[s]",0.6237); // aromatic sulfur addRule("[B,Si,Ga,Ge,As,Se,Sn,Te,Pb,Ne,Ar,Kr,Xe,Rn]",-0.3808); // remaining p-block elements addRule("[Fe,Cu,Zn,Tc,Cd,Pt,Au,Hg]",-0.0025); // remaining d-block elements } LogP::~LogP() { delete molecular_similarity_; } void LogP::addRule(String smarts, double value) { rules_.push_back(make_pair(smarts,value)); } double LogP::calculate(const String& usmile) { double logP = 0; Size match_sum = 0; for(Size i=0; i<rules_.size(); i++) { if(!rules_[i].first.hasPrefix("remaining")) { Size matches; molecular_similarity_->matchSmarts(usmile,rules_[i].first,matches); logP += matches*rules_[i].second; match_sum += matches; // if(matches>0) cout<<rules_[i].first<<" : "<<matches<<endl; } else { Size no_atoms; String smarts = rules_[i].first.after("remaining"); smarts.trim(); molecular_similarity_->matchSmarts(usmile,smarts,no_atoms); if(no_atoms>match_sum) { logP += (no_atoms-match_sum)*rules_[i].second; } // if(match_sum>no_atoms) // { // cout<<"Error: Atoms "<<smarts<<" were matches mulitple times!!"<<endl; // cout<<match_sum<<" "<<no_atoms<<endl; // } match_sum=0; } } return logP; } } <|endoftext|>
<commit_before>//===-- ValueObjectChild.cpp ------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/Core/ValueObjectChild.h" #include "lldb/Core/Value.h" #include "lldb/Symbol/CompilerType.h" #include "lldb/Target/ExecutionContext.h" #include "lldb/Target/Process.h" #include "lldb/Utility/Flags.h" #include "lldb/Utility/Scalar.h" #include "lldb/Utility/Status.h" #include "lldb/lldb-forward.h" #include <functional> #include <memory> #include <vector> #include <stdio.h> #include <string.h> using namespace lldb_private; ValueObjectChild::ValueObjectChild( ValueObject &parent, const CompilerType &compiler_type, const ConstString &name, uint64_t byte_size, int32_t byte_offset, uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset, bool is_base_class, bool is_deref_of_parent, AddressType child_ptr_or_ref_addr_type, uint64_t language_flags) : ValueObject(parent), m_compiler_type(compiler_type), m_byte_size(byte_size), m_byte_offset(byte_offset), m_bitfield_bit_size(bitfield_bit_size), m_bitfield_bit_offset(bitfield_bit_offset), m_is_base_class(is_base_class), m_is_deref_of_parent(is_deref_of_parent), m_can_update_with_invalid_exe_ctx() { m_name = name; SetAddressTypeOfChildren(child_ptr_or_ref_addr_type); SetLanguageFlags(language_flags); } ValueObjectChild::~ValueObjectChild() {} lldb::ValueType ValueObjectChild::GetValueType() const { return m_parent->GetValueType(); } size_t ValueObjectChild::CalculateNumChildren(uint32_t max) { ExecutionContext exe_ctx(GetExecutionContextRef()); auto children_count = GetCompilerType().GetNumChildren(true, &exe_ctx); return children_count <= max ? children_count : max; } static void AdjustForBitfieldness(ConstString &name, uint8_t bitfield_bit_size) { if (name && bitfield_bit_size) { const char *compiler_type_name = name.AsCString(); if (compiler_type_name) { std::vector<char> bitfield_type_name(strlen(compiler_type_name) + 32, 0); ::snprintf(&bitfield_type_name.front(), bitfield_type_name.size(), "%s:%u", compiler_type_name, bitfield_bit_size); name.SetCString(&bitfield_type_name.front()); } } } ConstString ValueObjectChild::GetTypeName() { if (m_type_name.IsEmpty()) { m_type_name = GetCompilerType().GetConstTypeName(); AdjustForBitfieldness(m_type_name, m_bitfield_bit_size); } return m_type_name; } ConstString ValueObjectChild::GetQualifiedTypeName() { ConstString qualified_name = GetCompilerType().GetConstTypeName(); AdjustForBitfieldness(qualified_name, m_bitfield_bit_size); return qualified_name; } ConstString ValueObjectChild::GetDisplayTypeName() { ConstString display_name = GetCompilerType().GetDisplayTypeName(); AdjustForBitfieldness(display_name, m_bitfield_bit_size); return display_name; } LazyBool ValueObjectChild::CanUpdateWithInvalidExecutionContext() { if (m_can_update_with_invalid_exe_ctx.hasValue()) return m_can_update_with_invalid_exe_ctx.getValue(); if (m_parent) { ValueObject *opinionated_parent = m_parent->FollowParentChain([](ValueObject *valobj) -> bool { return (valobj->CanUpdateWithInvalidExecutionContext() == eLazyBoolCalculate); }); if (opinionated_parent) return (m_can_update_with_invalid_exe_ctx = opinionated_parent->CanUpdateWithInvalidExecutionContext()) .getValue(); } return (m_can_update_with_invalid_exe_ctx = this->ValueObject::CanUpdateWithInvalidExecutionContext()) .getValue(); } bool ValueObjectChild::UpdateValue() { m_error.Clear(); SetValueIsValid(false); ValueObject *parent = m_parent; if (parent) { if (parent->UpdateValueIfNeeded(false)) { m_value.SetCompilerType(GetCompilerType()); CompilerType parent_type(parent->GetCompilerType()); // Copy the parent scalar value and the scalar value type m_value.GetScalar() = parent->GetValue().GetScalar(); Value::ValueType value_type = parent->GetValue().GetValueType(); m_value.SetValueType(value_type); Flags parent_type_flags(parent_type.GetTypeInfo()); const bool is_instance_ptr_base = ((m_is_base_class) && (parent_type_flags.AnySet(lldb::eTypeInstanceIsPointer))); if (parent->GetCompilerType().ShouldTreatScalarValueAsAddress()) { lldb::addr_t addr = parent->GetPointerValue(); m_value.GetScalar() = addr; if (addr == LLDB_INVALID_ADDRESS) { m_error.SetErrorString("parent address is invalid."); } else if (addr == 0) { m_error.SetErrorString("parent is NULL"); } else { m_value.GetScalar() += m_byte_offset; AddressType addr_type = parent->GetAddressTypeOfChildren(); switch (addr_type) { case eAddressTypeFile: { lldb::ProcessSP process_sp(GetProcessSP()); if (process_sp && process_sp->IsAlive()) m_value.SetValueType(Value::eValueTypeLoadAddress); else m_value.SetValueType(Value::eValueTypeFileAddress); } break; case eAddressTypeLoad: m_value.SetValueType(is_instance_ptr_base ? Value::eValueTypeScalar : Value::eValueTypeLoadAddress); break; case eAddressTypeHost: m_value.SetValueType(Value::eValueTypeHostAddress); break; case eAddressTypeInvalid: // TODO: does this make sense? m_value.SetValueType(Value::eValueTypeScalar); break; } } } else { switch (value_type) { case Value::eValueTypeLoadAddress: case Value::eValueTypeFileAddress: case Value::eValueTypeHostAddress: { lldb::addr_t addr = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS); if (addr == LLDB_INVALID_ADDRESS) { m_error.SetErrorString("parent address is invalid."); } else if (addr == 0) { m_error.SetErrorString("parent is NULL"); } else { // Set this object's scalar value to the address of its value by // adding its byte offset to the parent address m_value.GetScalar() += GetByteOffset(); } } break; case Value::eValueTypeScalar: // try to extract the child value from the parent's scalar value { Scalar scalar(m_value.GetScalar()); if (m_bitfield_bit_size) scalar.ExtractBitfield(m_bitfield_bit_size, m_bitfield_bit_offset); else scalar.ExtractBitfield(8 * m_byte_size, 8 * m_byte_offset); m_value.GetScalar() = scalar; } break; default: m_error.SetErrorString("parent has invalid value."); break; } } if (m_error.Success()) { const bool thread_and_frame_only_if_stopped = true; ExecutionContext exe_ctx( GetExecutionContextRef().Lock(thread_and_frame_only_if_stopped)); if (GetCompilerType().GetTypeInfo() & lldb::eTypeHasValue) { if (!is_instance_ptr_base) m_error = m_value.GetValueAsData(&exe_ctx, m_data, 0, GetModule().get()); else m_error = m_parent->GetValue().GetValueAsData(&exe_ctx, m_data, 0, GetModule().get()); } else { m_error.Clear(); // No value so nothing to read... } } } else { m_error.SetErrorStringWithFormat("parent failed to evaluate: %s", parent->GetError().AsCString()); } } else { m_error.SetErrorString("ValueObjectChild has a NULL parent ValueObject."); } return m_error.Success(); } bool ValueObjectChild::IsInScope() { ValueObject *root(GetRoot()); if (root) return root->IsInScope(); return false; } <commit_msg>Simplify code for readability. (NFC)<commit_after>//===-- ValueObjectChild.cpp ------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/Core/ValueObjectChild.h" #include "lldb/Core/Value.h" #include "lldb/Symbol/CompilerType.h" #include "lldb/Target/ExecutionContext.h" #include "lldb/Target/Process.h" #include "lldb/Utility/Flags.h" #include "lldb/Utility/Scalar.h" #include "lldb/Utility/Status.h" #include "lldb/lldb-forward.h" #include <functional> #include <memory> #include <vector> #include <stdio.h> #include <string.h> using namespace lldb_private; ValueObjectChild::ValueObjectChild( ValueObject &parent, const CompilerType &compiler_type, const ConstString &name, uint64_t byte_size, int32_t byte_offset, uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset, bool is_base_class, bool is_deref_of_parent, AddressType child_ptr_or_ref_addr_type, uint64_t language_flags) : ValueObject(parent), m_compiler_type(compiler_type), m_byte_size(byte_size), m_byte_offset(byte_offset), m_bitfield_bit_size(bitfield_bit_size), m_bitfield_bit_offset(bitfield_bit_offset), m_is_base_class(is_base_class), m_is_deref_of_parent(is_deref_of_parent), m_can_update_with_invalid_exe_ctx() { m_name = name; SetAddressTypeOfChildren(child_ptr_or_ref_addr_type); SetLanguageFlags(language_flags); } ValueObjectChild::~ValueObjectChild() {} lldb::ValueType ValueObjectChild::GetValueType() const { return m_parent->GetValueType(); } size_t ValueObjectChild::CalculateNumChildren(uint32_t max) { ExecutionContext exe_ctx(GetExecutionContextRef()); auto children_count = GetCompilerType().GetNumChildren(true, &exe_ctx); return children_count <= max ? children_count : max; } static void AdjustForBitfieldness(ConstString &name, uint8_t bitfield_bit_size) { if (name && bitfield_bit_size) { const char *compiler_type_name = name.AsCString(); if (compiler_type_name) { std::vector<char> bitfield_type_name(strlen(compiler_type_name) + 32, 0); ::snprintf(&bitfield_type_name.front(), bitfield_type_name.size(), "%s:%u", compiler_type_name, bitfield_bit_size); name.SetCString(&bitfield_type_name.front()); } } } ConstString ValueObjectChild::GetTypeName() { if (m_type_name.IsEmpty()) { m_type_name = GetCompilerType().GetConstTypeName(); AdjustForBitfieldness(m_type_name, m_bitfield_bit_size); } return m_type_name; } ConstString ValueObjectChild::GetQualifiedTypeName() { ConstString qualified_name = GetCompilerType().GetConstTypeName(); AdjustForBitfieldness(qualified_name, m_bitfield_bit_size); return qualified_name; } ConstString ValueObjectChild::GetDisplayTypeName() { ConstString display_name = GetCompilerType().GetDisplayTypeName(); AdjustForBitfieldness(display_name, m_bitfield_bit_size); return display_name; } LazyBool ValueObjectChild::CanUpdateWithInvalidExecutionContext() { if (m_can_update_with_invalid_exe_ctx.hasValue()) return m_can_update_with_invalid_exe_ctx.getValue(); if (m_parent) { ValueObject *opinionated_parent = m_parent->FollowParentChain([](ValueObject *valobj) -> bool { return (valobj->CanUpdateWithInvalidExecutionContext() == eLazyBoolCalculate); }); if (opinionated_parent) return (m_can_update_with_invalid_exe_ctx = opinionated_parent->CanUpdateWithInvalidExecutionContext()) .getValue(); } return (m_can_update_with_invalid_exe_ctx = this->ValueObject::CanUpdateWithInvalidExecutionContext()) .getValue(); } bool ValueObjectChild::UpdateValue() { m_error.Clear(); SetValueIsValid(false); ValueObject *parent = m_parent; if (parent) { if (parent->UpdateValueIfNeeded(false)) { m_value.SetCompilerType(GetCompilerType()); CompilerType parent_type(parent->GetCompilerType()); // Copy the parent scalar value and the scalar value type m_value.GetScalar() = parent->GetValue().GetScalar(); Value::ValueType value_type = parent->GetValue().GetValueType(); m_value.SetValueType(value_type); Flags parent_type_flags(parent_type.GetTypeInfo()); const bool is_instance_ptr_base = ((m_is_base_class) && (parent_type_flags.AnySet(lldb::eTypeInstanceIsPointer))); if (parent->GetCompilerType().ShouldTreatScalarValueAsAddress()) { lldb::addr_t addr = parent->GetPointerValue(); m_value.GetScalar() = addr; if (addr == LLDB_INVALID_ADDRESS) { m_error.SetErrorString("parent address is invalid."); } else if (addr == 0) { m_error.SetErrorString("parent is NULL"); } else { m_value.GetScalar() += m_byte_offset; AddressType addr_type = parent->GetAddressTypeOfChildren(); switch (addr_type) { case eAddressTypeFile: { lldb::ProcessSP process_sp(GetProcessSP()); if (process_sp && process_sp->IsAlive()) m_value.SetValueType(Value::eValueTypeLoadAddress); else m_value.SetValueType(Value::eValueTypeFileAddress); } break; case eAddressTypeLoad: m_value.SetValueType(is_instance_ptr_base ? Value::eValueTypeScalar : Value::eValueTypeLoadAddress); break; case eAddressTypeHost: m_value.SetValueType(Value::eValueTypeHostAddress); break; case eAddressTypeInvalid: // TODO: does this make sense? m_value.SetValueType(Value::eValueTypeScalar); break; } } } else { switch (value_type) { case Value::eValueTypeLoadAddress: case Value::eValueTypeFileAddress: case Value::eValueTypeHostAddress: { lldb::addr_t addr = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS); if (addr == LLDB_INVALID_ADDRESS) { m_error.SetErrorString("parent address is invalid."); } else if (addr == 0) { m_error.SetErrorString("parent is NULL"); } else { // Set this object's scalar value to the address of its value by // adding its byte offset to the parent address m_value.GetScalar() += GetByteOffset(); } } break; case Value::eValueTypeScalar: // try to extract the child value from the parent's scalar value { Scalar scalar(m_value.GetScalar()); if (m_bitfield_bit_size) scalar.ExtractBitfield(m_bitfield_bit_size, m_bitfield_bit_offset); else scalar.ExtractBitfield(8 * m_byte_size, 8 * m_byte_offset); m_value.GetScalar() = scalar; } break; default: m_error.SetErrorString("parent has invalid value."); break; } } if (m_error.Success()) { const bool thread_and_frame_only_if_stopped = true; ExecutionContext exe_ctx( GetExecutionContextRef().Lock(thread_and_frame_only_if_stopped)); if (GetCompilerType().GetTypeInfo() & lldb::eTypeHasValue) { Value &value = is_instance_ptr_base ? m_parent->GetValue() : m_value; m_error = value.GetValueAsData(&exe_ctx, m_data, 0, GetModule().get()); } else { m_error.Clear(); // No value so nothing to read... } } } else { m_error.SetErrorStringWithFormat("parent failed to evaluate: %s", parent->GetError().AsCString()); } } else { m_error.SetErrorString("ValueObjectChild has a NULL parent ValueObject."); } return m_error.Success(); } bool ValueObjectChild::IsInScope() { ValueObject *root(GetRoot()); if (root) return root->IsInScope(); return false; } <|endoftext|>
<commit_before>// $Id: AnalyticalSES_test.C,v 1.2 2000/05/23 10:23:45 oliver Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/STRUCTURE/analyticalSES.h> #include <BALL/KERNEL/fragment.h> /////////////////////////// START_TEST(AnalyticalSES, "$Id: AnalyticalSES_test.C,v 1.2 2000/05/23 10:23:45 oliver Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; CHECK(calculateSESArea(const Composite&, float)) Fragment f; Atom a1, a2; a1.setRadius(1.0); a2.setRadius(1.0); a2.setPosition(Vector3(10.0, 0.0, 0.0)); f.insert(a1); f.insert(a2); float area = calculateSESArea(f, 1.5); PRECISION(0.001) TEST_REAL_EQUAL(area, 25.13274) a2.setPosition(Vector3(1.0, 0.0, 0.0)); area = calculateSESArea(f, 1.5); TEST_REAL_EQUAL(area, 18.722) RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <commit_msg>changed: adapted to new interface<commit_after>// $Id: AnalyticalSES_test.C,v 1.3 2000/05/30 10:29:16 oliver Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/STRUCTURE/analyticalSES.h> #include <BALL/KERNEL/fragment.h> /////////////////////////// START_TEST(AnalyticalSES, "$Id: AnalyticalSES_test.C,v 1.3 2000/05/30 10:29:16 oliver Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; CHECK(calculateSESArea(const BaseFragment&, float)) Fragment f; Atom a1, a2; a1.setRadius(1.0); a2.setRadius(1.0); a2.setPosition(Vector3(10.0, 0.0, 0.0)); f.insert(a1); f.insert(a2); float area = calculateSESArea(f, 1.5); PRECISION(0.001) TEST_REAL_EQUAL(area, 25.13274) a2.setPosition(Vector3(1.0, 0.0, 0.0)); area = calculateSESArea(f, 1.5); TEST_REAL_EQUAL(area, 18.722) RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <|endoftext|>
<commit_before>// $Id: RegularData1D_test.C,v 1.7 2001/07/10 17:50:11 amoll Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/DATATYPE/regularData1D.h> /////////////////////////// START_TEST(class_name, "$Id: RegularData1D_test.C,v 1.7 2001/07/10 17:50:11 amoll Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; using namespace std; RegularData1D* rd_ptr; CHECK(TRegularData1D::TRegularData1D()) rd_ptr = new RegularData1D; TEST_NOT_EQUAL(rd_ptr, 0) RESULT CHECK(TRegularData1D::~TRegularData1D()) delete rd_ptr; RESULT CHECK(TRegularData1D::BALL_CREATE(RegularData1D<T>)) RESULT RegularData1D rd; CHECK(TRegularData1D::TRegularData1D(const TRegularData1D& data)) rd.setBoundaries(1.1, 2.1); rd.resize(1); rd[0] = 1.2; RegularData1D rd2(rd); TEST_REAL_EQUAL(rd2.getLowerBound(), 1.1) TEST_REAL_EQUAL(rd2.getUpperBound(), 2.1) TEST_REAL_EQUAL(rd2[0], 1.2) TEST_EQUAL(rd2.getSize(), 1) RESULT RegularData1D::VectorType v; v.push_back(1.1); v.push_back(1.2); v.push_back(1.3); v.push_back(1.4); CHECK(TRegularData1D(const VectorType& data, double lower, double upper)) RegularData1D rd2(v, 1.0, 1.5); TEST_REAL_EQUAL(rd2.getLowerBound(), 1.0) TEST_REAL_EQUAL(rd2.getUpperBound(), 1.5) TEST_EQUAL(rd2.getSize(), 4) TEST_REAL_EQUAL(rd2[0], 1.1) TEST_REAL_EQUAL(rd2[3], 1.4) RegularData1D rd3(v); TEST_REAL_EQUAL(rd3.getLowerBound(), 0.0) TEST_REAL_EQUAL(rd3.getUpperBound(), 0.0) TEST_EQUAL(rd3.getSize(), 4) RESULT CHECK(TRegularData1D::clear()) rd.clear(); TEST_REAL_EQUAL(rd.getLowerBound(), 1.1) TEST_REAL_EQUAL(rd.getUpperBound(), 2.1) TEST_EQUAL(rd.getSize(), 1) TEST_REAL_EQUAL(rd[0], 0.0) RESULT CHECK(TRegularData1D::destroy()) rd[0] = 2.3; rd.destroy(); TEST_REAL_EQUAL(rd.getLowerBound(), 0.0) TEST_REAL_EQUAL(rd.getUpperBound(), 0.0) TEST_EQUAL(rd.getSize(), 0) RESULT CHECK(TRegularData1D::TRegularData1D& operator = (const TRegularData1D& data)) rd.setBoundaries(1.1, 2.1); rd.resize(1); rd[0] = 1.2; RegularData1D rd2 = rd; TEST_REAL_EQUAL(rd2.getLowerBound(), 1.1) TEST_REAL_EQUAL(rd2.getUpperBound(), 2.1) TEST_REAL_EQUAL(rd2[0], 1.2) TEST_EQUAL(rd2.getSize(), 1) RESULT CHECK(TRegularData1D::TRegularData1D& operator = (const VectorType& data)) RegularData1D::VectorType v; v.push_back(1.1); v.push_back(1.2); v.push_back(1.3); v.push_back(1.4); RegularData1D rd2; rd2.setBoundaries(0.0, 1.0); rd2 = v; TEST_REAL_EQUAL(rd2.getLowerBound(), 0.0) TEST_REAL_EQUAL(rd2.getUpperBound(), 1.0) TEST_EQUAL(rd2.getSize(), 4) TEST_REAL_EQUAL(rd2[0], 1.1) TEST_REAL_EQUAL(rd2[1], 1.2) TEST_REAL_EQUAL(rd2[2], 1.3) TEST_REAL_EQUAL(rd2[3], 1.4) RESULT CHECK(TRegularData1D::bool operator == (const TRegularData1D& data) const ) rd.destroy(); rd.resize(4); rd[0] = 1.1; rd[1] = 1.2; rd[2] = 1.3; rd[3] = 1.4; RegularData1D rd2 = rd; TEST_EQUAL(rd == rd2, true) rd2[3] = 1.41; TEST_EQUAL(rd == rd2, false) rd2[3] = 1.4; TEST_EQUAL(rd == rd2, true) rd.setBoundaries(1.1, 1.4); TEST_EQUAL(rd == rd2, false) rd2.setBoundaries(1.1, 1.4); TEST_EQUAL(rd == rd2, true) RESULT CHECK(TRegularData1D::T& operator [] (Position index) const ) TEST_REAL_EQUAL(rd[3], 1.4) TEST_EXCEPTION(Exception::IndexOverflow, rd[4]) RESULT CHECK(TRegularData1D::T& operator [] (Position index)) rd[3] = 1.5; TEST_REAL_EQUAL(rd[3], 1.5) TEST_EXCEPTION(Exception::IndexOverflow, rd[4] = 44.4) RESULT RegularData1D rd2; CHECK(TRegularData1D::getSize() const ) TEST_EQUAL(rd.getSize(), 4) TEST_EQUAL(rd2.getSize(), 0) RESULT CHECK(TRegularData1D::getLowerBound() const ) rd.setBoundaries(1.1, 1.5); TEST_REAL_EQUAL(rd.getLowerBound(), 1.1) TEST_REAL_EQUAL(rd2.getLowerBound(), 0.0) RESULT CHECK(TRegularData1D::getUpperBound() const ) TEST_REAL_EQUAL(rd.getUpperBound(), 1.5) TEST_REAL_EQUAL(rd2.getUpperBound(), 0.0) RESULT CHECK(TRegularData1D::setLowerBound()) rd.setBoundaries(-99.9, 99.9); TEST_REAL_EQUAL(rd.getLowerBound(), -99.9) TEST_REAL_EQUAL(rd.getUpperBound(), 99.9) rd.setBoundaries(99.9, -99.9); TEST_REAL_EQUAL(rd.getLowerBound(), -99.9) TEST_REAL_EQUAL(rd.getUpperBound(), 99.9) RESULT CHECK(TRegularData1D::resize(Size new_size)) TEST_EQUAL(rd.getSize(), 4) rd.resize(99); TEST_EQUAL(rd.getSize(), 99) TEST_REAL_EQUAL(rd[98], 0.0) rd.resize(3); TEST_EQUAL(rd.getSize(), 3) TEST_REAL_EQUAL(rd[2], 1.3) TEST_EXCEPTION(Exception::IndexOverflow, rd[3]) RESULT CHECK(TRegularData1D::rescale(Size new_size)) TRegularData1D<float> data; TEST_EQUAL(data.getSize(), 0) data.rescale(1); TEST_EQUAL(data.getSize(), 1) TEST_EQUAL(data[0], 0.0) data[0] = 2.0; data.rescale(2); TEST_EQUAL(data.getSize(), 2) TEST_EQUAL(data[0], 2.0) TEST_EQUAL(data[0], 2.0) data[0] = 1.0; data.rescale(3); TEST_EQUAL(data.getSize(), 3) TEST_REAL_EQUAL(data[0], 1.0) TEST_REAL_EQUAL(data[1], 1.5) TEST_REAL_EQUAL(data[2], 2.0) data.rescale(4); TEST_EQUAL(data.getSize(), 4) TEST_REAL_EQUAL(data[0], 1.0) TEST_REAL_EQUAL(data[1], 1.3333333) TEST_REAL_EQUAL(data[2], 1.6666667) TEST_REAL_EQUAL(data[3], 2.0) RESULT CHECK(TRegularData1D::rescale(double lower, double upper, Size new_size)) TRegularData1D<float> data; data.resize(2); data.setBoundaries(0.0, 1.0); data[0] = 1.0; data[1] = 2.0; data.rescale(0.0, 1.0, 3); TEST_EQUAL(data.getSize(), 3) TEST_REAL_EQUAL(data[0], 1.0) TEST_REAL_EQUAL(data[1], 1.5) TEST_REAL_EQUAL(data[2], 2.0) data.rescale(0.0, 1.0, 4); TEST_EQUAL(data.getSize(), 4) TEST_REAL_EQUAL(data[0], 1.0) TEST_REAL_EQUAL(data[1], 1.3333333) TEST_REAL_EQUAL(data[2], 1.6666667) TEST_REAL_EQUAL(data[3], 2.0) data.rescale(0.0, 1.0, 4); TEST_EQUAL(data.getSize(), 4) TEST_REAL_EQUAL(data[0], 1.0) TEST_REAL_EQUAL(data[1], 1.3333333) TEST_REAL_EQUAL(data[2], 1.6666667) TEST_REAL_EQUAL(data[3], 2.0) data.rescale(-1.0, 2.0, 10); TEST_EQUAL(data.getSize(), 10) TEST_REAL_EQUAL(data[0], 0.0) TEST_REAL_EQUAL(data[1], 0.0) TEST_REAL_EQUAL(data[2], 0.0) TEST_REAL_EQUAL(data[3], 1.0) TEST_REAL_EQUAL(data[4], 1.3333333) TEST_REAL_EQUAL(data[5], 1.6666667) TEST_REAL_EQUAL(data[6], 2.0) TEST_REAL_EQUAL(data[7], 0.0) TEST_REAL_EQUAL(data[8], 0.0) TEST_REAL_EQUAL(data[9], 0.0) data.rescale(0.0, 1.0, 3); TEST_EQUAL(data.getSize(), 3) TEST_REAL_EQUAL(data[0], 1.0) TEST_REAL_EQUAL(data[1], 1.5) TEST_REAL_EQUAL(data[2], 2.0) RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <commit_msg>fixed: test for detailled cstr<commit_after>// $Id: RegularData1D_test.C,v 1.8 2001/07/10 17:58:30 amoll Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/DATATYPE/regularData1D.h> /////////////////////////// START_TEST(class_name, "$Id: RegularData1D_test.C,v 1.8 2001/07/10 17:58:30 amoll Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; using namespace std; RegularData1D* rd_ptr; CHECK(TRegularData1D::TRegularData1D()) rd_ptr = new RegularData1D; TEST_NOT_EQUAL(rd_ptr, 0) RESULT CHECK(TRegularData1D::~TRegularData1D()) delete rd_ptr; RESULT CHECK(TRegularData1D::BALL_CREATE(RegularData1D<T>)) RESULT RegularData1D rd; CHECK(TRegularData1D::TRegularData1D(const TRegularData1D& data)) rd.setBoundaries(1.1, 2.1); rd.resize(1); rd[0] = 1.2; RegularData1D rd2(rd); TEST_REAL_EQUAL(rd2.getLowerBound(), 1.1) TEST_REAL_EQUAL(rd2.getUpperBound(), 2.1) TEST_REAL_EQUAL(rd2[0], 1.2) TEST_EQUAL(rd2.getSize(), 1) RESULT RegularData1D::VectorType v; v.push_back(1.1); v.push_back(1.2); v.push_back(1.3); v.push_back(1.4); CHECK(TRegularData1D(const VectorType& data, double lower, double upper)) RegularData1D rd2(v, 1.0, 1.5); TEST_REAL_EQUAL(rd2.getLowerBound(), 1.0) TEST_REAL_EQUAL(rd2.getUpperBound(), 1.5) TEST_EQUAL(rd2.getSize(), 4) TEST_REAL_EQUAL(rd2[0], 1.1) TEST_REAL_EQUAL(rd2[3], 1.4) RegularData1D rd3(v); TEST_REAL_EQUAL(rd3.getLowerBound(), 0.0) TEST_REAL_EQUAL(rd3.getUpperBound(), 0.0) TEST_EQUAL(rd3.getSize(), 4) RegularData1D rd4(v, 2.0, 1.0); TEST_REAL_EQUAL(rd4.getLowerBound(), 1.0) TEST_REAL_EQUAL(rd4.getUpperBound(), 2.0) TEST_EQUAL(rd4.getSize(), 4) RESULT CHECK(TRegularData1D::clear()) rd.clear(); TEST_REAL_EQUAL(rd.getLowerBound(), 1.1) TEST_REAL_EQUAL(rd.getUpperBound(), 2.1) TEST_EQUAL(rd.getSize(), 1) TEST_REAL_EQUAL(rd[0], 0.0) RESULT CHECK(TRegularData1D::destroy()) rd[0] = 2.3; rd.destroy(); TEST_REAL_EQUAL(rd.getLowerBound(), 0.0) TEST_REAL_EQUAL(rd.getUpperBound(), 0.0) TEST_EQUAL(rd.getSize(), 0) RESULT CHECK(TRegularData1D::TRegularData1D& operator = (const TRegularData1D& data)) rd.setBoundaries(1.1, 2.1); rd.resize(1); rd[0] = 1.2; RegularData1D rd2 = rd; TEST_REAL_EQUAL(rd2.getLowerBound(), 1.1) TEST_REAL_EQUAL(rd2.getUpperBound(), 2.1) TEST_REAL_EQUAL(rd2[0], 1.2) TEST_EQUAL(rd2.getSize(), 1) RESULT CHECK(TRegularData1D::TRegularData1D& operator = (const VectorType& data)) RegularData1D::VectorType v; v.push_back(1.1); v.push_back(1.2); v.push_back(1.3); v.push_back(1.4); RegularData1D rd2; rd2.setBoundaries(0.0, 1.0); rd2 = v; TEST_REAL_EQUAL(rd2.getLowerBound(), 0.0) TEST_REAL_EQUAL(rd2.getUpperBound(), 1.0) TEST_EQUAL(rd2.getSize(), 4) TEST_REAL_EQUAL(rd2[0], 1.1) TEST_REAL_EQUAL(rd2[1], 1.2) TEST_REAL_EQUAL(rd2[2], 1.3) TEST_REAL_EQUAL(rd2[3], 1.4) RESULT CHECK(TRegularData1D::bool operator == (const TRegularData1D& data) const ) rd.destroy(); rd.resize(4); rd[0] = 1.1; rd[1] = 1.2; rd[2] = 1.3; rd[3] = 1.4; RegularData1D rd2 = rd; TEST_EQUAL(rd == rd2, true) rd2[3] = 1.41; TEST_EQUAL(rd == rd2, false) rd2[3] = 1.4; TEST_EQUAL(rd == rd2, true) rd.setBoundaries(1.1, 1.4); TEST_EQUAL(rd == rd2, false) rd2.setBoundaries(1.1, 1.4); TEST_EQUAL(rd == rd2, true) RESULT CHECK(TRegularData1D::T& operator [] (Position index) const ) TEST_REAL_EQUAL(rd[3], 1.4) TEST_EXCEPTION(Exception::IndexOverflow, rd[4]) RESULT CHECK(TRegularData1D::T& operator [] (Position index)) rd[3] = 1.5; TEST_REAL_EQUAL(rd[3], 1.5) TEST_EXCEPTION(Exception::IndexOverflow, rd[4] = 44.4) RESULT RegularData1D rd2; CHECK(TRegularData1D::getSize() const ) TEST_EQUAL(rd.getSize(), 4) TEST_EQUAL(rd2.getSize(), 0) RESULT CHECK(TRegularData1D::getLowerBound() const ) rd.setBoundaries(1.1, 1.5); TEST_REAL_EQUAL(rd.getLowerBound(), 1.1) TEST_REAL_EQUAL(rd2.getLowerBound(), 0.0) RESULT CHECK(TRegularData1D::getUpperBound() const ) TEST_REAL_EQUAL(rd.getUpperBound(), 1.5) TEST_REAL_EQUAL(rd2.getUpperBound(), 0.0) RESULT CHECK(TRegularData1D::setLowerBound()) rd.setBoundaries(-99.9, 99.9); TEST_REAL_EQUAL(rd.getLowerBound(), -99.9) TEST_REAL_EQUAL(rd.getUpperBound(), 99.9) rd.setBoundaries(99.9, -99.9); TEST_REAL_EQUAL(rd.getLowerBound(), -99.9) TEST_REAL_EQUAL(rd.getUpperBound(), 99.9) RESULT CHECK(TRegularData1D::resize(Size new_size)) TEST_EQUAL(rd.getSize(), 4) rd.resize(99); TEST_EQUAL(rd.getSize(), 99) TEST_REAL_EQUAL(rd[98], 0.0) rd.resize(3); TEST_EQUAL(rd.getSize(), 3) TEST_REAL_EQUAL(rd[2], 1.3) TEST_EXCEPTION(Exception::IndexOverflow, rd[3]) RESULT CHECK(TRegularData1D::rescale(Size new_size)) TRegularData1D<float> data; TEST_EQUAL(data.getSize(), 0) data.rescale(1); TEST_EQUAL(data.getSize(), 1) TEST_EQUAL(data[0], 0.0) data[0] = 2.0; data.rescale(2); TEST_EQUAL(data.getSize(), 2) TEST_EQUAL(data[0], 2.0) TEST_EQUAL(data[0], 2.0) data[0] = 1.0; data.rescale(3); TEST_EQUAL(data.getSize(), 3) TEST_REAL_EQUAL(data[0], 1.0) TEST_REAL_EQUAL(data[1], 1.5) TEST_REAL_EQUAL(data[2], 2.0) data.rescale(4); TEST_EQUAL(data.getSize(), 4) TEST_REAL_EQUAL(data[0], 1.0) TEST_REAL_EQUAL(data[1], 1.3333333) TEST_REAL_EQUAL(data[2], 1.6666667) TEST_REAL_EQUAL(data[3], 2.0) RESULT CHECK(TRegularData1D::rescale(double lower, double upper, Size new_size)) TRegularData1D<float> data; data.resize(2); data.setBoundaries(0.0, 1.0); data[0] = 1.0; data[1] = 2.0; data.rescale(0.0, 1.0, 3); TEST_EQUAL(data.getSize(), 3) TEST_REAL_EQUAL(data[0], 1.0) TEST_REAL_EQUAL(data[1], 1.5) TEST_REAL_EQUAL(data[2], 2.0) data.rescale(0.0, 1.0, 4); TEST_EQUAL(data.getSize(), 4) TEST_REAL_EQUAL(data[0], 1.0) TEST_REAL_EQUAL(data[1], 1.3333333) TEST_REAL_EQUAL(data[2], 1.6666667) TEST_REAL_EQUAL(data[3], 2.0) data.rescale(0.0, 1.0, 4); TEST_EQUAL(data.getSize(), 4) TEST_REAL_EQUAL(data[0], 1.0) TEST_REAL_EQUAL(data[1], 1.3333333) TEST_REAL_EQUAL(data[2], 1.6666667) TEST_REAL_EQUAL(data[3], 2.0) data.rescale(-1.0, 2.0, 10); TEST_EQUAL(data.getSize(), 10) TEST_REAL_EQUAL(data[0], 0.0) TEST_REAL_EQUAL(data[1], 0.0) TEST_REAL_EQUAL(data[2], 0.0) TEST_REAL_EQUAL(data[3], 1.0) TEST_REAL_EQUAL(data[4], 1.3333333) TEST_REAL_EQUAL(data[5], 1.6666667) TEST_REAL_EQUAL(data[6], 2.0) TEST_REAL_EQUAL(data[7], 0.0) TEST_REAL_EQUAL(data[8], 0.0) TEST_REAL_EQUAL(data[9], 0.0) data.rescale(0.0, 1.0, 3); TEST_EQUAL(data.getSize(), 3) TEST_REAL_EQUAL(data[0], 1.0) TEST_REAL_EQUAL(data[1], 1.5) TEST_REAL_EQUAL(data[2], 2.0) RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <|endoftext|>
<commit_before>// // Aspia Project // Copyright (C) 2018 Dmitry Chapyshev <dmitry@aspia.ru> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "net/srp_client_context.h" #include "base/logging.h" #include "crypto/generic_hash.h" #include "crypto/random.h" #include "crypto/secure_memory.h" #include "crypto/srp_constants.h" #include "crypto/srp_math.h" namespace net { namespace { bool verifyNg(const std::string& N, const std::string& g) { switch (N.size()) { case 256: // 2048 bit { if (memcmp(N.data(), crypto::kSrpNg_2048.N.data(), crypto::kSrpNg_2048.N.size()) != 0) return false; if (g.size() != crypto::kSrpNg_2048.g.size()) return false; if (memcmp(g.data(), crypto::kSrpNg_2048.g.data(), crypto::kSrpNg_2048.g.size()) != 0) return false; } break; case 384: // 3072 bit { if (memcmp(N.data(), crypto::kSrpNg_3072.N.data(), crypto::kSrpNg_3072.N.size()) != 0) return false; if (g.size() != crypto::kSrpNg_3072.g.size()) return false; if (memcmp(g.data(), crypto::kSrpNg_3072.g.data(), crypto::kSrpNg_3072.g.size()) != 0) return false; } break; case 512: // 4096 bit { if (memcmp(N.data(), crypto::kSrpNg_4096.N.data(), crypto::kSrpNg_4096.N.size()) != 0) return false; if (g.size() != crypto::kSrpNg_4096.g.size()) return false; if (memcmp(g.data(), crypto::kSrpNg_4096.g.data(), crypto::kSrpNg_4096.g.size()) != 0) return false; } break; case 768: // 6144 bit { if (memcmp(N.data(), crypto::kSrpNg_6144.N.data(), crypto::kSrpNg_6144.N.size()) != 0) return false; if (g.size() != crypto::kSrpNg_6144.g.size()) return false; if (memcmp(g.data(), crypto::kSrpNg_6144.g.data(), crypto::kSrpNg_6144.g.size()) != 0) return false; } break; case 1024: // 8192 bit { if (memcmp(N.data(), crypto::kSrpNg_8192.N.data(), crypto::kSrpNg_8192.N.size()) != 0) return false; if (g.size() != crypto::kSrpNg_8192.g.size()) return false; if (memcmp(g.data(), crypto::kSrpNg_8192.g.data(), crypto::kSrpNg_8192.g.size()) != 0) return false; } break; // We do not allow groups with a length of 1024 and 1536 bits. case 128: case 192: default: return false; } return true; } size_t ivSizeForMethod(proto::Method method) { switch (method) { case proto::METHOD_SRP_AES256_GCM: case proto::METHOD_SRP_CHACHA20_POLY1305: return 12; default: return 0; } } } // namespace SrpClientContext::SrpClientContext(proto::Method method, const QString& I, const QString& p) : method_(method), I_(I), p_(p) { // Nothing } SrpClientContext::~SrpClientContext() { crypto::memZero(&p_); crypto::memZero(&encrypt_iv_); crypto::memZero(&decrypt_iv_); } // static SrpClientContext* SrpClientContext::create(proto::Method method, const QString& username, const QString& password) { switch (method) { case proto::METHOD_SRP_AES256_GCM: case proto::METHOD_SRP_CHACHA20_POLY1305: break; default: return nullptr; } if (username.isEmpty() || password.isEmpty()) return nullptr; return new SrpClientContext(method, username, password); } proto::SrpIdentify* SrpClientContext::identify() { std::unique_ptr<proto::SrpIdentify> identify = std::make_unique<proto::SrpIdentify>(); identify->set_username(I_.toStdString()); return identify.release(); } proto::SrpClientKeyExchange* SrpClientContext::readServerKeyExchange( const proto::SrpServerKeyExchange& server_key_exchange) { static const size_t kMin_s = 64; static const size_t kMin_B = 128; if (server_key_exchange.salt().size() < kMin_s) { LOG(LS_WARNING) << "Wrong salt size:" << server_key_exchange.salt().size(); return nullptr; } if (server_key_exchange.b().size() < kMin_B) { LOG(LS_WARNING) << "Wrong B size:" << server_key_exchange.b().size(); return nullptr; } if (!verifyNg(server_key_exchange.number(), server_key_exchange.generator())) { LOG(LS_WARNING) << "Wrong number or generator"; return nullptr; } N_ = crypto::BigNum::fromStdString(server_key_exchange.number()); g_ = crypto::BigNum::fromStdString(server_key_exchange.generator()); s_ = crypto::BigNum::fromStdString(server_key_exchange.salt()); B_ = crypto::BigNum::fromStdString(server_key_exchange.b()); decrypt_iv_ = QByteArray::fromStdString(server_key_exchange.iv()); a_ = crypto::BigNum::fromByteArray(crypto::Random::generateBuffer(128)); // 1024 bits. A_ = crypto::SrpMath::calc_A(a_, N_, g_); size_t iv_size = ivSizeForMethod(method_); if (!iv_size) return nullptr; encrypt_iv_ = crypto::Random::generateBuffer(iv_size); std::unique_ptr<proto::SrpClientKeyExchange> client_key_exchange = std::make_unique<proto::SrpClientKeyExchange>(); client_key_exchange->set_a(A_.toStdString()); client_key_exchange->set_iv(encrypt_iv_.toStdString()); return client_key_exchange.release(); } QByteArray SrpClientContext::key() const { if (!crypto::SrpMath::verify_B_mod_N(B_, N_)) { LOG(LS_WARNING) << "Invalid B or N"; return QByteArray(); } crypto::BigNum u = crypto::SrpMath::calc_u(A_, B_, N_); crypto::BigNum x = crypto::SrpMath::calc_x(s_, I_.toUtf8(), p_.toUtf8()); crypto::BigNum client_key = crypto::SrpMath::calcClientKey(N_, B_, g_, x, a_, u); QByteArray client_key_string = client_key.toByteArray(); if (client_key_string.isEmpty()) { LOG(LS_WARNING) << "Empty encryption key generated"; return QByteArray(); } switch (method_) { // AES256-GCM and ChaCha20-Poly1305 requires 256 bit key. case proto::METHOD_SRP_AES256_GCM: case proto::METHOD_SRP_CHACHA20_POLY1305: return crypto::GenericHash::hash(crypto::GenericHash::BLAKE2s256, client_key_string); default: LOG(LS_WARNING) << "Unknown encryption method: " << method_; return QByteArray(); } } } // namespace net <commit_msg>- We do not allow groups less than 512 bytes (4096 bits).<commit_after>// // Aspia Project // Copyright (C) 2018 Dmitry Chapyshev <dmitry@aspia.ru> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "net/srp_client_context.h" #include "base/logging.h" #include "crypto/generic_hash.h" #include "crypto/random.h" #include "crypto/secure_memory.h" #include "crypto/srp_constants.h" #include "crypto/srp_math.h" namespace net { namespace { bool verifyNg(const std::string& N, const std::string& g) { switch (N.size()) { case 512: // 4096 bit { if (memcmp(N.data(), crypto::kSrpNg_4096.N.data(), crypto::kSrpNg_4096.N.size()) != 0) return false; if (g.size() != crypto::kSrpNg_4096.g.size()) return false; if (memcmp(g.data(), crypto::kSrpNg_4096.g.data(), crypto::kSrpNg_4096.g.size()) != 0) return false; } break; case 768: // 6144 bit { if (memcmp(N.data(), crypto::kSrpNg_6144.N.data(), crypto::kSrpNg_6144.N.size()) != 0) return false; if (g.size() != crypto::kSrpNg_6144.g.size()) return false; if (memcmp(g.data(), crypto::kSrpNg_6144.g.data(), crypto::kSrpNg_6144.g.size()) != 0) return false; } break; case 1024: // 8192 bit { if (memcmp(N.data(), crypto::kSrpNg_8192.N.data(), crypto::kSrpNg_8192.N.size()) != 0) return false; if (g.size() != crypto::kSrpNg_8192.g.size()) return false; if (memcmp(g.data(), crypto::kSrpNg_8192.g.data(), crypto::kSrpNg_8192.g.size()) != 0) return false; } break; // We do not allow groups less than 512 bytes (4096 bits). case 128: case 192: case 256: case 384: default: return false; } return true; } size_t ivSizeForMethod(proto::Method method) { switch (method) { case proto::METHOD_SRP_AES256_GCM: case proto::METHOD_SRP_CHACHA20_POLY1305: return 12; default: return 0; } } } // namespace SrpClientContext::SrpClientContext(proto::Method method, const QString& I, const QString& p) : method_(method), I_(I), p_(p) { // Nothing } SrpClientContext::~SrpClientContext() { crypto::memZero(&p_); crypto::memZero(&encrypt_iv_); crypto::memZero(&decrypt_iv_); } // static SrpClientContext* SrpClientContext::create(proto::Method method, const QString& username, const QString& password) { switch (method) { case proto::METHOD_SRP_AES256_GCM: case proto::METHOD_SRP_CHACHA20_POLY1305: break; default: return nullptr; } if (username.isEmpty() || password.isEmpty()) return nullptr; return new SrpClientContext(method, username, password); } proto::SrpIdentify* SrpClientContext::identify() { std::unique_ptr<proto::SrpIdentify> identify = std::make_unique<proto::SrpIdentify>(); identify->set_username(I_.toStdString()); return identify.release(); } proto::SrpClientKeyExchange* SrpClientContext::readServerKeyExchange( const proto::SrpServerKeyExchange& server_key_exchange) { static const size_t kMin_s = 64; static const size_t kMin_B = 128; if (server_key_exchange.salt().size() < kMin_s) { LOG(LS_WARNING) << "Wrong salt size:" << server_key_exchange.salt().size(); return nullptr; } if (server_key_exchange.b().size() < kMin_B) { LOG(LS_WARNING) << "Wrong B size:" << server_key_exchange.b().size(); return nullptr; } if (!verifyNg(server_key_exchange.number(), server_key_exchange.generator())) { LOG(LS_WARNING) << "Wrong number or generator"; return nullptr; } N_ = crypto::BigNum::fromStdString(server_key_exchange.number()); g_ = crypto::BigNum::fromStdString(server_key_exchange.generator()); s_ = crypto::BigNum::fromStdString(server_key_exchange.salt()); B_ = crypto::BigNum::fromStdString(server_key_exchange.b()); decrypt_iv_ = QByteArray::fromStdString(server_key_exchange.iv()); a_ = crypto::BigNum::fromByteArray(crypto::Random::generateBuffer(128)); // 1024 bits. A_ = crypto::SrpMath::calc_A(a_, N_, g_); size_t iv_size = ivSizeForMethod(method_); if (!iv_size) return nullptr; encrypt_iv_ = crypto::Random::generateBuffer(iv_size); std::unique_ptr<proto::SrpClientKeyExchange> client_key_exchange = std::make_unique<proto::SrpClientKeyExchange>(); client_key_exchange->set_a(A_.toStdString()); client_key_exchange->set_iv(encrypt_iv_.toStdString()); return client_key_exchange.release(); } QByteArray SrpClientContext::key() const { if (!crypto::SrpMath::verify_B_mod_N(B_, N_)) { LOG(LS_WARNING) << "Invalid B or N"; return QByteArray(); } crypto::BigNum u = crypto::SrpMath::calc_u(A_, B_, N_); crypto::BigNum x = crypto::SrpMath::calc_x(s_, I_.toUtf8(), p_.toUtf8()); crypto::BigNum client_key = crypto::SrpMath::calcClientKey(N_, B_, g_, x, a_, u); QByteArray client_key_string = client_key.toByteArray(); if (client_key_string.isEmpty()) { LOG(LS_WARNING) << "Empty encryption key generated"; return QByteArray(); } switch (method_) { // AES256-GCM and ChaCha20-Poly1305 requires 256 bit key. case proto::METHOD_SRP_AES256_GCM: case proto::METHOD_SRP_CHACHA20_POLY1305: return crypto::GenericHash::hash(crypto::GenericHash::BLAKE2s256, client_key_string); default: LOG(LS_WARNING) << "Unknown encryption method: " << method_; return QByteArray(); } } } // namespace net <|endoftext|>
<commit_before>// // Aspia Project // Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "router/database_sqlite.h" #include "base/logging.h" #include "base/files/base_paths.h" #include "base/strings/strcat.h" #include "base/strings/unicode.h" #include "build/build_config.h" #include <optional> namespace router { namespace { bool writeText(sqlite3_stmt* statement, const std::string& text, int column) { int error_code = sqlite3_bind_text( statement, column, text.c_str(), text.size(), SQLITE_STATIC); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_bind_text failed: " << sqlite3_errstr(error_code) << " (column: " << column << ")"; return false; } return true; } bool writeBlob(sqlite3_stmt* statement, const base::ByteArray& blob, int column) { int error_code = sqlite3_bind_blob(statement, column, blob.data(), blob.size(), SQLITE_STATIC); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_bind_blob failed: " << sqlite3_errstr(error_code) << " (column: " << column << ")"; return false; } return true; } bool writeInt(sqlite3_stmt* statement, int number, int column) { int error_code = sqlite3_bind_int(statement, column, number); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_bind_int failed: " << sqlite3_errstr(error_code) << " (column: " << column << ")"; return false; } return true; } bool writeInt64(sqlite3_stmt* statement, int64_t number, int column) { int error_code = sqlite3_bind_int64(statement, column, number); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_bind_int64 failed: " << sqlite3_errstr(error_code) << " (column: " << column << ")"; return false; } return true; } template <typename T> std::optional<T> readInteger(sqlite3_stmt* statement, int column) { int column_type = sqlite3_column_type(statement, column); if (column_type != SQLITE_INTEGER) { LOG(LS_ERROR) << "Type is not SQLITE_INTEGER"; return std::nullopt; } return static_cast<T>(sqlite3_column_int64(statement, column)); } std::optional<base::ByteArray> readBlob(sqlite3_stmt* statement, int column) { int column_type = sqlite3_column_type(statement, column); if (column_type != SQLITE_BLOB) { LOG(LS_ERROR) << "Type is not SQLITE_BLOB"; return std::nullopt; } int blob_size = sqlite3_column_bytes(statement, column); if (blob_size <= 0) { LOG(LS_ERROR) << "Field has an invalid size"; return std::nullopt; } const void* blob = sqlite3_column_blob(statement, column); if (!blob) { LOG(LS_ERROR) << "Failed to get the pointer to the field"; return std::nullopt; } return base::fromData(blob, static_cast<size_t>(blob_size)); } std::optional<std::string> readText(sqlite3_stmt* statement, int column) { int column_type = sqlite3_column_type(statement, column); if (column_type != SQLITE_TEXT) { LOG(LS_ERROR) << "Type is not SQLITE_TEXT"; return std::nullopt; } int string_size = sqlite3_column_bytes(statement, column); if (string_size <= 0) { LOG(LS_ERROR) << "Field has an invalid size"; return std::nullopt; } const uint8_t* string = sqlite3_column_text(statement, column); if (!string) { LOG(LS_ERROR) << "Failed to get the pointer to the field"; return std::nullopt; } return std::string(reinterpret_cast<const char*>(string), string_size); } std::optional<std::u16string> readText16(sqlite3_stmt* statement, int column) { std::optional<std::string> str = readText(statement, column); if (!str.has_value()) return std::nullopt; return base::utf16FromUtf8(str.value()); } std::optional<peer::User> readUser(sqlite3_stmt* statement) { std::optional<int64_t> entry_id = readInteger<int64_t>(statement, 0); if (!entry_id.has_value()) { LOG(LS_ERROR) << "Failed to get field 'id'"; return std::nullopt; } std::optional<std::u16string> name = readText16(statement, 1); if (!name.has_value()) { LOG(LS_ERROR) << "Failed to get field 'name'"; return std::nullopt; } std::optional<std::string> group = readText(statement, 2); if (!group.has_value()) { LOG(LS_ERROR) << "Failed to get field 'group'"; return std::nullopt; } std::optional<base::ByteArray> salt = readBlob(statement, 3); if (!salt.has_value()) { LOG(LS_ERROR) << "Failed to get field 'salt'"; return std::nullopt; } std::optional<base::ByteArray> verifier = readBlob(statement, 4); if (!verifier.has_value()) { LOG(LS_ERROR) << "Failed to get field 'verifier'"; return std::nullopt; } std::optional<uint32_t> sessions = readInteger<uint32_t>(statement, 5); if (!sessions.has_value()) { LOG(LS_ERROR) << "Failed to get field 'sessions'"; return std::nullopt; } std::optional<uint32_t> flags = readInteger<uint32_t>(statement, 6); if (!flags.has_value()) { LOG(LS_ERROR) << "Failed to get field 'flags'"; return std::nullopt; } peer::User user; user.entry_id = entry_id.value(); user.name = std::move(name.value()); user.group = std::move(group.value()); user.salt = std::move(salt.value()); user.verifier = std::move(verifier.value()); user.sessions = sessions.value(); user.flags = flags.value(); return user; } } // namespace DatabaseSqlite::DatabaseSqlite(sqlite3* db) : db_(db) { DCHECK(db_); } DatabaseSqlite::~DatabaseSqlite() { sqlite3_close(db_); } // static std::unique_ptr<DatabaseSqlite> DatabaseSqlite::open() { std::filesystem::path file_path = filePath(); if (file_path.empty()) { LOG(LS_WARNING) << "Invalid file path"; return nullptr; } sqlite3* db = nullptr; int error_code = sqlite3_open(file_path.u8string().c_str(), &db); if (error_code != SQLITE_OK) { LOG(LS_WARNING) << "sqlite3_open failed: " << sqlite3_errstr(error_code); return nullptr; } return std::unique_ptr<DatabaseSqlite>(new DatabaseSqlite(db)); } // static std::filesystem::path DatabaseSqlite::filePath() { std::filesystem::path file_path; #if defined(OS_WIN) if (!base::BasePaths::currentExecDir(&file_path)) return std::filesystem::path(); file_path.append(u"aspia_router.db3"); #else // defined(OS_*) #error Not implemented #endif // defined(OS_*) return file_path; } peer::UserList DatabaseSqlite::userList() const { const char kQuery[] = "SELECT * FROM users"; sqlite3_stmt* statement; int error_code = sqlite3_prepare(db_, kQuery, std::size(kQuery), &statement, nullptr); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_prepare failed: " << sqlite3_errstr(error_code); return peer::UserList(); } peer::UserList users; for (;;) { if (sqlite3_step(statement) != SQLITE_ROW) break; std::optional<peer::User> user = readUser(statement); if (user.has_value()) users.add(std::move(user.value())); } sqlite3_finalize(statement); return users; } bool DatabaseSqlite::addUser(const peer::User& user) { if (!user.isValid()) { LOG(LS_ERROR) << "Not valid user"; return false; } static const char kQuery[] = "INSERT INTO users ('id', 'name', 'group', 'salt', 'verifier', 'sessions', 'flags') " "VALUES (NULL, ?, ?, ?, ?, ?, ?)"; sqlite3_stmt* statement = nullptr; int error_code = sqlite3_prepare(db_, kQuery, std::size(kQuery), &statement, nullptr); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_prepare failed: " << sqlite3_errstr(error_code); return false; } std::string username = base::utf8FromUtf16(user.name); bool result = false; do { if (!writeText(statement, username, 1)) break; if (!writeText(statement, user.group, 2)) break; if (!writeBlob(statement, user.salt, 3)) break; if (!writeBlob(statement, user.verifier, 4)) break; if (!writeInt(statement, static_cast<int>(user.sessions), 5)) break; if (!writeInt(statement, static_cast<int>(user.flags), 6)) break; error_code = sqlite3_step(statement); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_step failed: " << sqlite3_errstr(error_code); break; } result = true; } while (false); sqlite3_finalize(statement); return result; } bool DatabaseSqlite::removeUser(int64_t entry_id) { static const char kQuery[] = "DELETE FROM users WHERE id=?"; sqlite3_stmt* statement = nullptr; int error_code = sqlite3_prepare(db_, kQuery, std::size(kQuery), &statement, nullptr); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_prepare failed: " << sqlite3_errstr(error_code); return false; } bool result = false; do { if (!writeInt64(statement, entry_id, 1)) break; error_code = sqlite3_step(statement); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_step failed: " << sqlite3_errstr(error_code); break; } result = true; } while (false); sqlite3_finalize(statement); return result; } peer::PeerId DatabaseSqlite::peerId(const base::ByteArray& keyHash) const { if (keyHash.empty()) { LOG(LS_ERROR) << "Invalid parameters"; return peer::kInvalidPeerId; } const char kQuery[] = "SELECT * FROM peers WHERE key=?"; sqlite3_stmt* statement; int error_code = sqlite3_prepare(db_, kQuery, std::size(kQuery), &statement, nullptr); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_prepare failed: " << sqlite3_errstr(error_code); return peer::kInvalidPeerId; } peer::PeerId result = peer::kInvalidPeerId; do { if (!writeBlob(statement, keyHash, 1)) break; if (sqlite3_step(statement) != SQLITE_ROW) { LOG(LS_ERROR) << "sqlite3_step failed: " << sqlite3_errstr(error_code); break; } std::optional<int64_t> entry_id = readInteger<int64_t>(statement, 0); if (!entry_id.has_value()) { LOG(LS_ERROR) << "Failed to get field 'id'"; break; } result = entry_id.value(); } while (false); sqlite3_finalize(statement); return result; } bool DatabaseSqlite::addPeer(const base::ByteArray& keyHash) { if (keyHash.empty()) { LOG(LS_ERROR) << "Invalid parameters"; return false; } const char kQuery[] = "INSERT INTO peers ('id', 'key') VALUES (NULL, ?)"; sqlite3_stmt* statement = nullptr; int error_code = sqlite3_prepare(db_, kQuery, std::size(kQuery), &statement, nullptr); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_prepare failed: " << sqlite3_errstr(error_code); return false; } bool result = false; do { if (!writeBlob(statement, keyHash, 1)) break; error_code = sqlite3_step(statement); if (error_code != SQLITE_OK && error_code != SQLITE_DONE) { LOG(LS_ERROR) << "sqlite3_step failed: " << sqlite3_errstr(error_code) << " (" << error_code << ")"; break; } result = true; } while (false); sqlite3_finalize(statement); return result; } } // namespace router <commit_msg>Headers reorganize/cleanup.<commit_after>// // Aspia Project // Copyright (C) 2020 Dmitry Chapyshev <dmitry@aspia.ru> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // #include "router/database_sqlite.h" #include "base/logging.h" #include "base/files/base_paths.h" #include "base/strings/unicode.h" #include "build/build_config.h" #include <optional> namespace router { namespace { bool writeText(sqlite3_stmt* statement, const std::string& text, int column) { int error_code = sqlite3_bind_text( statement, column, text.c_str(), text.size(), SQLITE_STATIC); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_bind_text failed: " << sqlite3_errstr(error_code) << " (column: " << column << ")"; return false; } return true; } bool writeBlob(sqlite3_stmt* statement, const base::ByteArray& blob, int column) { int error_code = sqlite3_bind_blob(statement, column, blob.data(), blob.size(), SQLITE_STATIC); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_bind_blob failed: " << sqlite3_errstr(error_code) << " (column: " << column << ")"; return false; } return true; } bool writeInt(sqlite3_stmt* statement, int number, int column) { int error_code = sqlite3_bind_int(statement, column, number); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_bind_int failed: " << sqlite3_errstr(error_code) << " (column: " << column << ")"; return false; } return true; } bool writeInt64(sqlite3_stmt* statement, int64_t number, int column) { int error_code = sqlite3_bind_int64(statement, column, number); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_bind_int64 failed: " << sqlite3_errstr(error_code) << " (column: " << column << ")"; return false; } return true; } template <typename T> std::optional<T> readInteger(sqlite3_stmt* statement, int column) { int column_type = sqlite3_column_type(statement, column); if (column_type != SQLITE_INTEGER) { LOG(LS_ERROR) << "Type is not SQLITE_INTEGER"; return std::nullopt; } return static_cast<T>(sqlite3_column_int64(statement, column)); } std::optional<base::ByteArray> readBlob(sqlite3_stmt* statement, int column) { int column_type = sqlite3_column_type(statement, column); if (column_type != SQLITE_BLOB) { LOG(LS_ERROR) << "Type is not SQLITE_BLOB"; return std::nullopt; } int blob_size = sqlite3_column_bytes(statement, column); if (blob_size <= 0) { LOG(LS_ERROR) << "Field has an invalid size"; return std::nullopt; } const void* blob = sqlite3_column_blob(statement, column); if (!blob) { LOG(LS_ERROR) << "Failed to get the pointer to the field"; return std::nullopt; } return base::fromData(blob, static_cast<size_t>(blob_size)); } std::optional<std::string> readText(sqlite3_stmt* statement, int column) { int column_type = sqlite3_column_type(statement, column); if (column_type != SQLITE_TEXT) { LOG(LS_ERROR) << "Type is not SQLITE_TEXT"; return std::nullopt; } int string_size = sqlite3_column_bytes(statement, column); if (string_size <= 0) { LOG(LS_ERROR) << "Field has an invalid size"; return std::nullopt; } const uint8_t* string = sqlite3_column_text(statement, column); if (!string) { LOG(LS_ERROR) << "Failed to get the pointer to the field"; return std::nullopt; } return std::string(reinterpret_cast<const char*>(string), string_size); } std::optional<std::u16string> readText16(sqlite3_stmt* statement, int column) { std::optional<std::string> str = readText(statement, column); if (!str.has_value()) return std::nullopt; return base::utf16FromUtf8(str.value()); } std::optional<peer::User> readUser(sqlite3_stmt* statement) { std::optional<int64_t> entry_id = readInteger<int64_t>(statement, 0); if (!entry_id.has_value()) { LOG(LS_ERROR) << "Failed to get field 'id'"; return std::nullopt; } std::optional<std::u16string> name = readText16(statement, 1); if (!name.has_value()) { LOG(LS_ERROR) << "Failed to get field 'name'"; return std::nullopt; } std::optional<std::string> group = readText(statement, 2); if (!group.has_value()) { LOG(LS_ERROR) << "Failed to get field 'group'"; return std::nullopt; } std::optional<base::ByteArray> salt = readBlob(statement, 3); if (!salt.has_value()) { LOG(LS_ERROR) << "Failed to get field 'salt'"; return std::nullopt; } std::optional<base::ByteArray> verifier = readBlob(statement, 4); if (!verifier.has_value()) { LOG(LS_ERROR) << "Failed to get field 'verifier'"; return std::nullopt; } std::optional<uint32_t> sessions = readInteger<uint32_t>(statement, 5); if (!sessions.has_value()) { LOG(LS_ERROR) << "Failed to get field 'sessions'"; return std::nullopt; } std::optional<uint32_t> flags = readInteger<uint32_t>(statement, 6); if (!flags.has_value()) { LOG(LS_ERROR) << "Failed to get field 'flags'"; return std::nullopt; } peer::User user; user.entry_id = entry_id.value(); user.name = std::move(name.value()); user.group = std::move(group.value()); user.salt = std::move(salt.value()); user.verifier = std::move(verifier.value()); user.sessions = sessions.value(); user.flags = flags.value(); return user; } } // namespace DatabaseSqlite::DatabaseSqlite(sqlite3* db) : db_(db) { DCHECK(db_); } DatabaseSqlite::~DatabaseSqlite() { sqlite3_close(db_); } // static std::unique_ptr<DatabaseSqlite> DatabaseSqlite::open() { std::filesystem::path file_path = filePath(); if (file_path.empty()) { LOG(LS_WARNING) << "Invalid file path"; return nullptr; } sqlite3* db = nullptr; int error_code = sqlite3_open(file_path.u8string().c_str(), &db); if (error_code != SQLITE_OK) { LOG(LS_WARNING) << "sqlite3_open failed: " << sqlite3_errstr(error_code); return nullptr; } return std::unique_ptr<DatabaseSqlite>(new DatabaseSqlite(db)); } // static std::filesystem::path DatabaseSqlite::filePath() { std::filesystem::path file_path; #if defined(OS_WIN) if (!base::BasePaths::currentExecDir(&file_path)) return std::filesystem::path(); file_path.append(u"aspia_router.db3"); #else // defined(OS_*) #error Not implemented #endif // defined(OS_*) return file_path; } peer::UserList DatabaseSqlite::userList() const { const char kQuery[] = "SELECT * FROM users"; sqlite3_stmt* statement; int error_code = sqlite3_prepare(db_, kQuery, std::size(kQuery), &statement, nullptr); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_prepare failed: " << sqlite3_errstr(error_code); return peer::UserList(); } peer::UserList users; for (;;) { if (sqlite3_step(statement) != SQLITE_ROW) break; std::optional<peer::User> user = readUser(statement); if (user.has_value()) users.add(std::move(user.value())); } sqlite3_finalize(statement); return users; } bool DatabaseSqlite::addUser(const peer::User& user) { if (!user.isValid()) { LOG(LS_ERROR) << "Not valid user"; return false; } static const char kQuery[] = "INSERT INTO users ('id', 'name', 'group', 'salt', 'verifier', 'sessions', 'flags') " "VALUES (NULL, ?, ?, ?, ?, ?, ?)"; sqlite3_stmt* statement = nullptr; int error_code = sqlite3_prepare(db_, kQuery, std::size(kQuery), &statement, nullptr); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_prepare failed: " << sqlite3_errstr(error_code); return false; } std::string username = base::utf8FromUtf16(user.name); bool result = false; do { if (!writeText(statement, username, 1)) break; if (!writeText(statement, user.group, 2)) break; if (!writeBlob(statement, user.salt, 3)) break; if (!writeBlob(statement, user.verifier, 4)) break; if (!writeInt(statement, static_cast<int>(user.sessions), 5)) break; if (!writeInt(statement, static_cast<int>(user.flags), 6)) break; error_code = sqlite3_step(statement); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_step failed: " << sqlite3_errstr(error_code); break; } result = true; } while (false); sqlite3_finalize(statement); return result; } bool DatabaseSqlite::removeUser(int64_t entry_id) { static const char kQuery[] = "DELETE FROM users WHERE id=?"; sqlite3_stmt* statement = nullptr; int error_code = sqlite3_prepare(db_, kQuery, std::size(kQuery), &statement, nullptr); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_prepare failed: " << sqlite3_errstr(error_code); return false; } bool result = false; do { if (!writeInt64(statement, entry_id, 1)) break; error_code = sqlite3_step(statement); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_step failed: " << sqlite3_errstr(error_code); break; } result = true; } while (false); sqlite3_finalize(statement); return result; } peer::PeerId DatabaseSqlite::peerId(const base::ByteArray& keyHash) const { if (keyHash.empty()) { LOG(LS_ERROR) << "Invalid parameters"; return peer::kInvalidPeerId; } const char kQuery[] = "SELECT * FROM peers WHERE key=?"; sqlite3_stmt* statement; int error_code = sqlite3_prepare(db_, kQuery, std::size(kQuery), &statement, nullptr); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_prepare failed: " << sqlite3_errstr(error_code); return peer::kInvalidPeerId; } peer::PeerId result = peer::kInvalidPeerId; do { if (!writeBlob(statement, keyHash, 1)) break; if (sqlite3_step(statement) != SQLITE_ROW) { LOG(LS_ERROR) << "sqlite3_step failed: " << sqlite3_errstr(error_code); break; } std::optional<int64_t> entry_id = readInteger<int64_t>(statement, 0); if (!entry_id.has_value()) { LOG(LS_ERROR) << "Failed to get field 'id'"; break; } result = entry_id.value(); } while (false); sqlite3_finalize(statement); return result; } bool DatabaseSqlite::addPeer(const base::ByteArray& keyHash) { if (keyHash.empty()) { LOG(LS_ERROR) << "Invalid parameters"; return false; } const char kQuery[] = "INSERT INTO peers ('id', 'key') VALUES (NULL, ?)"; sqlite3_stmt* statement = nullptr; int error_code = sqlite3_prepare(db_, kQuery, std::size(kQuery), &statement, nullptr); if (error_code != SQLITE_OK) { LOG(LS_ERROR) << "sqlite3_prepare failed: " << sqlite3_errstr(error_code); return false; } bool result = false; do { if (!writeBlob(statement, keyHash, 1)) break; error_code = sqlite3_step(statement); if (error_code != SQLITE_OK && error_code != SQLITE_DONE) { LOG(LS_ERROR) << "sqlite3_step failed: " << sqlite3_errstr(error_code) << " (" << error_code << ")"; break; } result = true; } while (false); sqlite3_finalize(statement); return result; } } // namespace router <|endoftext|>
<commit_before>/* This file is part of the E_Rendering library. Copyright (C) 2014-2015 Sascha Brandt <myeti@mail.upb.de> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #ifdef RENDERING_HAS_LIB_OPENCL #include "E_Event.h" #include <EScript/Basics.h> #include <EScript/StdObjects.h> namespace E_Rendering{ namespace E_CL{ //! (static) EScript::Type * E_Event::getTypeObject() { // E_Event ---|> Object static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject()); return typeObject.get(); } //! (static) init members void E_Event::init(EScript::Namespace & lib) { EScript::Type * typeObject = E_Event::getTypeObject(); declareConstant(&lib,getClassName(),typeObject); using namespace Rendering::CL; //! [ESMF] Event new Event() ES_CTOR(typeObject,0,0,new E_Event(new Event())) // uint64_t getProfilingCommandEnd() const //! [ESMF] Number Event.getProfilingCommandEnd() ES_MFUN(typeObject,const Event,"getProfilingCommandEnd",0,0, EScript::Number::create(thisObj->getProfilingCommandEnd())) // uint64_t getProfilingCommandQueued() const //! [ESMF] Number Event.getProfilingCommandQueued() ES_MFUN(typeObject,const Event,"getProfilingCommandQueued",0,0, EScript::Number::create(thisObj->getProfilingCommandQueued())) // uint64_t getProfilingCommandStart() const //! [ESMF] Number Event.getProfilingCommandStart() ES_MFUN(typeObject,const Event,"getProfilingCommandStart",0,0, EScript::Number::create(thisObj->getProfilingCommandStart())) // uint64_t getProfilingCommandSubmit() const //! [ESMF] Number Event.getProfilingCommandSubmit() ES_MFUN(typeObject,const Event,"getProfilingCommandSubmit",0,0, EScript::Number::create(thisObj->getProfilingCommandSubmit())) // uint64_t getProfilingNanoseconds() const //! [ESMF] Number Event.getProfilingNanoseconds() ES_MFUN(typeObject,const Event,"getProfilingNanoseconds",0,0, EScript::Number::create(thisObj->getProfilingNanoseconds())) // double getProfilingMicroseconds() const //! [ESMF] Number Event.getProfilingMicroseconds() ES_MFUN(typeObject,const Event,"getProfilingMicroseconds",0,0, EScript::Number::create(thisObj->getProfilingMicroseconds())) // double getProfilingNanoseconds() const //! [ESMF] Number Event.getProfilingMilliseconds() ES_MFUN(typeObject,const Event,"getProfilingMilliseconds",0,0, EScript::Number::create(thisObj->getProfilingMilliseconds())) // double getProfilingSeconds() const //! [ESMF] Number Event.getProfilingSeconds() ES_MFUN(typeObject,const Event,"getProfilingSeconds",0,0, EScript::Number::create(thisObj->getProfilingSeconds())) // void setCallback(CallbackFn_t fun) //! [ESMF] self Event.setCallback(p0) // ES_MFUN(typeObject,Event,"setCallback",1,1, // (thisObj->setCallback(parameter[0].to<XXX>(rt)),thisEObj)) // void wait() //! [ESMF] self Event.wait() ES_MFUN(typeObject,Event,"wait",0,0, (thisObj->wait(),thisEObj)) // static void waitForEvents(const std::vector<Event*>& events) //! [ESF] Void Event.waitForEvents(p0) ES_FUNCTION(typeObject,"waitForEvents",1,1, { const EScript::Array * a = parameter[0].to<EScript::Array*>(rt); std::vector<Event*> events; for(auto e : *a) events.push_back(e.to<Event*>(rt)); Event::waitForEvents(events); return thisEObj; }) } } } #endif // RENDERING_HAS_LIB_OPENCL <commit_msg>added getStatus<commit_after>/* This file is part of the E_Rendering library. Copyright (C) 2014-2015 Sascha Brandt <myeti@mail.upb.de> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #ifdef RENDERING_HAS_LIB_OPENCL #include "E_Event.h" #include <EScript/Basics.h> #include <EScript/StdObjects.h> namespace E_Rendering{ namespace E_CL{ //! (static) EScript::Type * E_Event::getTypeObject() { // E_Event ---|> Object static EScript::ERef<EScript::Type> typeObject = new EScript::Type(EScript::Object::getTypeObject()); return typeObject.get(); } //! (static) init members void E_Event::init(EScript::Namespace & lib) { EScript::Type * typeObject = E_Event::getTypeObject(); declareConstant(&lib,getClassName(),typeObject); using namespace Rendering::CL; //! [ESMF] Event new Event() ES_CTOR(typeObject,0,0,new E_Event(new Event())) // uint64_t getProfilingCommandEnd() const //! [ESMF] Number Event.getProfilingCommandEnd() ES_MFUN(typeObject,const Event,"getProfilingCommandEnd",0,0, EScript::Number::create(thisObj->getProfilingCommandEnd())) // uint64_t getProfilingCommandQueued() const //! [ESMF] Number Event.getProfilingCommandQueued() ES_MFUN(typeObject,const Event,"getProfilingCommandQueued",0,0, EScript::Number::create(thisObj->getProfilingCommandQueued())) // uint64_t getProfilingCommandStart() const //! [ESMF] Number Event.getProfilingCommandStart() ES_MFUN(typeObject,const Event,"getProfilingCommandStart",0,0, EScript::Number::create(thisObj->getProfilingCommandStart())) // uint64_t getProfilingCommandSubmit() const //! [ESMF] Number Event.getProfilingCommandSubmit() ES_MFUN(typeObject,const Event,"getProfilingCommandSubmit",0,0, EScript::Number::create(thisObj->getProfilingCommandSubmit())) // uint64_t getProfilingNanoseconds() const //! [ESMF] Number Event.getProfilingNanoseconds() ES_MFUN(typeObject,const Event,"getProfilingNanoseconds",0,0, EScript::Number::create(thisObj->getProfilingNanoseconds())) // double getProfilingMicroseconds() const //! [ESMF] Number Event.getProfilingMicroseconds() ES_MFUN(typeObject,const Event,"getProfilingMicroseconds",0,0, EScript::Number::create(thisObj->getProfilingMicroseconds())) // double getProfilingNanoseconds() const //! [ESMF] Number Event.getProfilingMilliseconds() ES_MFUN(typeObject,const Event,"getProfilingMilliseconds",0,0, EScript::Number::create(thisObj->getProfilingMilliseconds())) // double getProfilingSeconds() const //! [ESMF] Number Event.getProfilingSeconds() ES_MFUN(typeObject,const Event,"getProfilingSeconds",0,0, EScript::Number::create(thisObj->getProfilingSeconds())) // uint32_t getStatus() const //! [ESMF] Number Event.getStatus() ES_MFUN(typeObject,const Event,"getStatus",0,0, EScript::Number::create(thisObj->getStatus())) // void setCallback(CallbackFn_t fun) //! [ESMF] self Event.setCallback(p0) // ES_MFUN(typeObject,Event,"setCallback",1,1, // (thisObj->setCallback(parameter[0].to<XXX>(rt)),thisEObj)) // void wait() //! [ESMF] self Event.wait() ES_MFUN(typeObject,Event,"wait",0,0, (thisObj->wait(),thisEObj)) // static void waitForEvents(const std::vector<Event*>& events) //! [ESF] Void Event.waitForEvents(p0) ES_FUNCTION(typeObject,"waitForEvents",1,1, { const EScript::Array * a = parameter[0].to<EScript::Array*>(rt); std::vector<Event*> events; for(auto e : *a) events.push_back(e.to<Event*>(rt)); Event::waitForEvents(events); return thisEObj; }) } } } #endif // RENDERING_HAS_LIB_OPENCL <|endoftext|>
<commit_before>/* This file is part of KAddressBook. Copyright (c) 2002 Tobias Koenig <tokoe@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qbuttongroup.h> #include <qcombobox.h> #include <qlabel.h> #include <qlayout.h> #include <qlistview.h> #include <qpushbutton.h> #include <qradiobutton.h> #include <kaccelmanager.h> #include <kdebug.h> #include <klineeditdlg.h> #include <klocale.h> #include <kmessagebox.h> #include <kabc/addressbook.h> #include <kabc/addresseedialog.h> #include <kabc/distributionlist.h> #include <kabc/vcardconverter.h> #include <libkdepim/kvcarddrag.h> #include "distributionlistwidget.h" class DistributionListFactory : public ExtensionFactory { public: ExtensionWidget *extension( ViewManager *vm, QWidget *parent, const char *name ) { return new DistributionListWidget( vm, parent, name ); } QString identifier() const { return "distribution_list_editor"; } }; extern "C" { void *init_libkaddrbk_distributionlist() { return ( new DistributionListFactory ); } } class ContactItem : public QListViewItem { public: ContactItem( DistributionListView *parent, const KABC::Addressee &addressee, const QString &email = QString::null ) : QListViewItem( parent ), mAddressee( addressee ), mEmail( email ) { setText( 0, addressee.realName() ); if( email.isEmpty() ) { setText( 1, addressee.preferredEmail() ); setText( 2, i18n( "Yes" ) ); } else { setText( 1, email ); setText( 2, i18n( "No" ) ); } } KABC::Addressee addressee() const { return mAddressee; } QString email() const { return mEmail; } protected: bool acceptDrop( const QMimeSource* ) { return true; } private: KABC::Addressee mAddressee; QString mEmail; }; DistributionListWidget::DistributionListWidget( ViewManager *vm, QWidget *parent, const char *name ) : ExtensionWidget( vm, parent, name ), mManager( 0 ) { QGridLayout *topLayout = new QGridLayout( this, 3, 4, KDialog::marginHint(), KDialog::spacingHint() ); mNameCombo = new QComboBox( this ); topLayout->addWidget( mNameCombo, 0, 0 ); connect( mNameCombo, SIGNAL( activated( int ) ), SLOT( updateContactView() ) ); mCreateListButton = new QPushButton( i18n( "New List..." ), this ); topLayout->addWidget( mCreateListButton, 0, 1 ); connect( mCreateListButton, SIGNAL( clicked() ), SLOT( createList() ) ); mEditListButton = new QPushButton( i18n( "Rename List..." ), this ); topLayout->addWidget( mEditListButton, 0, 2 ); connect( mEditListButton, SIGNAL( clicked() ), SLOT( editList() ) ); mRemoveListButton = new QPushButton( i18n( "Remove List" ), this ); topLayout->addWidget( mRemoveListButton, 0, 3 ); connect( mRemoveListButton, SIGNAL( clicked() ), SLOT( removeList() ) ); mContactView = new DistributionListView( this ); mContactView->addColumn( i18n( "Name" ) ); mContactView->addColumn( i18n( "Email" ) ); mContactView->addColumn( i18n( "Use Preferred" ) ); mContactView->setEnabled( false ); mContactView->setAllColumnsShowFocus( true ); topLayout->addMultiCellWidget( mContactView, 1, 1, 0, 3 ); connect( mContactView, SIGNAL( selectionChanged() ), SLOT( selectionContactViewChanged() ) ); connect( mContactView, SIGNAL( dropped( QDropEvent*, QListViewItem* ) ), SLOT( dropped( QDropEvent*, QListViewItem* ) ) ); mAddContactButton = new QPushButton( i18n( "Add Contact" ), this ); mAddContactButton->setEnabled( false ); topLayout->addWidget( mAddContactButton, 2, 0 ); connect( mAddContactButton, SIGNAL( clicked() ), SLOT( addContact() ) ); mChangeEmailButton = new QPushButton( i18n( "Change Email..." ), this ); topLayout->addWidget( mChangeEmailButton, 2, 2 ); connect( mChangeEmailButton, SIGNAL( clicked() ), SLOT( changeEmail() ) ); mRemoveContactButton = new QPushButton( i18n( "Remove Contact" ), this ); topLayout->addWidget( mRemoveContactButton, 2, 3 ); connect( mRemoveContactButton, SIGNAL( clicked() ), SLOT( removeContact() ) ); mManager = new KABC::DistributionListManager( addressBook() ); mManager->load(); updateNameCombo(); KAcceleratorManager::manage( this ); } DistributionListWidget::~DistributionListWidget() { delete mManager; } void DistributionListWidget::save() { mManager->save(); } void DistributionListWidget::selectionContactViewChanged() { ContactItem *contactItem = static_cast<ContactItem *>( mContactView->selectedItem() ); bool state = contactItem; mChangeEmailButton->setEnabled( state ); mRemoveContactButton->setEnabled( state ); } void DistributionListWidget::createList() { KLineEditDlg dlg( i18n( "Please enter name:" ), QString::null, this ); dlg.setCaption( i18n( "New Distribution List" ) ); if ( !dlg.exec() ) return; new KABC::DistributionList( mManager, dlg.text() ); mNameCombo->clear(); mNameCombo->insertStringList( mManager->listNames() ); mNameCombo->setCurrentItem( mNameCombo->count() - 1 ); updateContactView(); changed(); } void DistributionListWidget::editList() { QString oldName = mNameCombo->currentText(); KLineEditDlg dlg( i18n( "Please change name:" ), oldName, this ); dlg.setCaption( i18n("Distribution List") ); if ( !dlg.exec() ) return; KABC::DistributionList *list = mManager->list( oldName ); list->setName( dlg.text() ); mNameCombo->clear(); mNameCombo->insertStringList( mManager->listNames() ); mNameCombo->setCurrentItem( mNameCombo->count() - 1 ); updateContactView(); changed(); } void DistributionListWidget::removeList() { int result = KMessageBox::warningContinueCancel( this, i18n( "Delete distribution list '%1'?" ) .arg( mNameCombo->currentText() ), QString::null, i18n( "Delete" ) ); if ( result != KMessageBox::Continue ) return; delete mManager->list( mNameCombo->currentText() ); mNameCombo->removeItem( mNameCombo->currentItem() ); updateContactView(); changed(); } void DistributionListWidget::addContact() { KABC::DistributionList *list = mManager->list( mNameCombo->currentText() ); if ( !list ) return; KABC::Addressee::List addrList = selectedAddressees(); KABC::Addressee::List::Iterator it; for ( it = addrList.begin(); it != addrList.end(); ++it ) list->insertEntry( *it ); updateContactView(); changed(); } void DistributionListWidget::removeContact() { KABC::DistributionList *list = mManager->list( mNameCombo->currentText() ); if ( !list ) return; ContactItem *contactItem = static_cast<ContactItem *>( mContactView->selectedItem() ); if ( !contactItem ) return; list->removeEntry( contactItem->addressee(), contactItem->email() ); delete contactItem; changed(); } void DistributionListWidget::changeEmail() { KABC::DistributionList *list = mManager->list( mNameCombo->currentText() ); if ( !list ) return; ContactItem *contactItem = static_cast<ContactItem *>( mContactView->selectedItem() ); if ( !contactItem ) return; QString email = EmailSelector::getEmail( contactItem->addressee().emails(), contactItem->email(), this ); list->removeEntry( contactItem->addressee(), contactItem->email() ); list->insertEntry( contactItem->addressee(), email ); updateContactView(); changed(); } void DistributionListWidget::updateContactView() { mContactView->clear(); KABC::DistributionList *list = mManager->list( mNameCombo->currentText() ); if ( !list ) { mEditListButton->setEnabled( false ); mRemoveListButton->setEnabled( false ); mChangeEmailButton->setEnabled( false ); mRemoveContactButton->setEnabled( false ); mContactView->setEnabled( false ); return; } else { mEditListButton->setEnabled( true ); mRemoveListButton->setEnabled( true ); mContactView->setEnabled( true ); } KABC::DistributionList::Entry::List entries = list->entries(); KABC::DistributionList::Entry::List::ConstIterator it; for( it = entries.begin(); it != entries.end(); ++it ) new ContactItem( mContactView, (*it).addressee, (*it).email ); ContactItem *contactItem = static_cast<ContactItem *>( mContactView->selectedItem() ); bool state = contactItem; mChangeEmailButton->setEnabled( state ); mRemoveContactButton->setEnabled( state ); } void DistributionListWidget::updateNameCombo() { mNameCombo->insertStringList( mManager->listNames() ); updateContactView(); } void DistributionListWidget::dropEvent( QDropEvent *e ) { KABC::DistributionList *distributionList = mManager->list( mNameCombo->currentText() ); if ( !distributionList ) return; QString vcards; if ( KVCardDrag::decode( e, vcards ) ) { QStringList list = QStringList::split( "\r\n\r\n", vcards ); QStringList::Iterator it; KABC::VCardConverter converter; for ( it = list.begin(); it != list.end(); ++it ) { KABC::Addressee addr; if ( converter.vCardToAddressee( (*it).stripWhiteSpace(), addr ) ) distributionList->insertEntry( addr ); } changed(); updateContactView(); } } void DistributionListWidget::addresseeSelectionChanged() { mAddContactButton->setEnabled( addresseesSelected() && mNameCombo->count() > 0 ); } QString DistributionListWidget::title() const { return i18n( "Distribution List Editor" ); } QString DistributionListWidget::identifier() const { return "distribution_list_editor"; } void DistributionListWidget::dropped( QDropEvent *e, QListViewItem* ) { dropEvent( e ); } void DistributionListWidget::changed() { save(); emit modified( KABC::Addressee::List() ); } DistributionListView::DistributionListView( QWidget *parent, const char* name ) : KListView( parent, name ) { setDragEnabled( true ); setAcceptDrops( true ); setAllColumnsShowFocus( true ); } void DistributionListView::dragEnterEvent( QDragEnterEvent* e ) { bool canDecode = QTextDrag::canDecode( e ); e->accept( canDecode ); } void DistributionListView::viewportDragMoveEvent( QDragMoveEvent *e ) { bool canDecode = QTextDrag::canDecode( e ); e->accept( canDecode ); } void DistributionListView::viewportDropEvent( QDropEvent *e ) { emit dropped( e, 0 ); } void DistributionListView::dropEvent( QDropEvent *e ) { emit dropped( e, 0 ); } EmailSelector::EmailSelector( const QStringList &emails, const QString &current, QWidget *parent ) : KDialogBase( KDialogBase::Plain, i18n("Select Email Address"), Ok, Ok, parent ) { QFrame *topFrame = plainPage(); QBoxLayout *topLayout = new QVBoxLayout( topFrame ); mButtonGroup = new QButtonGroup( 1, Horizontal, i18n("Email Addresses"), topFrame ); topLayout->addWidget( mButtonGroup ); QStringList::ConstIterator it; for( it = emails.begin(); it != emails.end(); ++it ) { QRadioButton *button = new QRadioButton( *it, mButtonGroup ); if ( (*it) == current ) { button->setDown( true ); } } } QString EmailSelector::selected() { QButton *button = mButtonGroup->selected(); if ( button ) return button->text(); return QString::null; } QString EmailSelector::getEmail( const QStringList &emails, const QString &current, QWidget *parent ) { EmailSelector dlg( emails, current, parent ); dlg.exec(); return dlg.selected(); } #include "distributionlistwidget.moc" <commit_msg>Use HTML tags (<b></b>) for highlighting<commit_after>/* This file is part of KAddressBook. Copyright (c) 2002 Tobias Koenig <tokoe@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include <qbuttongroup.h> #include <qcombobox.h> #include <qlabel.h> #include <qlayout.h> #include <qlistview.h> #include <qpushbutton.h> #include <qradiobutton.h> #include <kaccelmanager.h> #include <kdebug.h> #include <klineeditdlg.h> #include <klocale.h> #include <kmessagebox.h> #include <kabc/addressbook.h> #include <kabc/addresseedialog.h> #include <kabc/distributionlist.h> #include <kabc/vcardconverter.h> #include <libkdepim/kvcarddrag.h> #include "distributionlistwidget.h" class DistributionListFactory : public ExtensionFactory { public: ExtensionWidget *extension( ViewManager *vm, QWidget *parent, const char *name ) { return new DistributionListWidget( vm, parent, name ); } QString identifier() const { return "distribution_list_editor"; } }; extern "C" { void *init_libkaddrbk_distributionlist() { return ( new DistributionListFactory ); } } class ContactItem : public QListViewItem { public: ContactItem( DistributionListView *parent, const KABC::Addressee &addressee, const QString &email = QString::null ) : QListViewItem( parent ), mAddressee( addressee ), mEmail( email ) { setText( 0, addressee.realName() ); if( email.isEmpty() ) { setText( 1, addressee.preferredEmail() ); setText( 2, i18n( "Yes" ) ); } else { setText( 1, email ); setText( 2, i18n( "No" ) ); } } KABC::Addressee addressee() const { return mAddressee; } QString email() const { return mEmail; } protected: bool acceptDrop( const QMimeSource* ) { return true; } private: KABC::Addressee mAddressee; QString mEmail; }; DistributionListWidget::DistributionListWidget( ViewManager *vm, QWidget *parent, const char *name ) : ExtensionWidget( vm, parent, name ), mManager( 0 ) { QGridLayout *topLayout = new QGridLayout( this, 3, 4, KDialog::marginHint(), KDialog::spacingHint() ); mNameCombo = new QComboBox( this ); topLayout->addWidget( mNameCombo, 0, 0 ); connect( mNameCombo, SIGNAL( activated( int ) ), SLOT( updateContactView() ) ); mCreateListButton = new QPushButton( i18n( "New List..." ), this ); topLayout->addWidget( mCreateListButton, 0, 1 ); connect( mCreateListButton, SIGNAL( clicked() ), SLOT( createList() ) ); mEditListButton = new QPushButton( i18n( "Rename List..." ), this ); topLayout->addWidget( mEditListButton, 0, 2 ); connect( mEditListButton, SIGNAL( clicked() ), SLOT( editList() ) ); mRemoveListButton = new QPushButton( i18n( "Remove List" ), this ); topLayout->addWidget( mRemoveListButton, 0, 3 ); connect( mRemoveListButton, SIGNAL( clicked() ), SLOT( removeList() ) ); mContactView = new DistributionListView( this ); mContactView->addColumn( i18n( "Name" ) ); mContactView->addColumn( i18n( "Email" ) ); mContactView->addColumn( i18n( "Use Preferred" ) ); mContactView->setEnabled( false ); mContactView->setAllColumnsShowFocus( true ); topLayout->addMultiCellWidget( mContactView, 1, 1, 0, 3 ); connect( mContactView, SIGNAL( selectionChanged() ), SLOT( selectionContactViewChanged() ) ); connect( mContactView, SIGNAL( dropped( QDropEvent*, QListViewItem* ) ), SLOT( dropped( QDropEvent*, QListViewItem* ) ) ); mAddContactButton = new QPushButton( i18n( "Add Contact" ), this ); mAddContactButton->setEnabled( false ); topLayout->addWidget( mAddContactButton, 2, 0 ); connect( mAddContactButton, SIGNAL( clicked() ), SLOT( addContact() ) ); mChangeEmailButton = new QPushButton( i18n( "Change Email..." ), this ); topLayout->addWidget( mChangeEmailButton, 2, 2 ); connect( mChangeEmailButton, SIGNAL( clicked() ), SLOT( changeEmail() ) ); mRemoveContactButton = new QPushButton( i18n( "Remove Contact" ), this ); topLayout->addWidget( mRemoveContactButton, 2, 3 ); connect( mRemoveContactButton, SIGNAL( clicked() ), SLOT( removeContact() ) ); mManager = new KABC::DistributionListManager( addressBook() ); mManager->load(); updateNameCombo(); KAcceleratorManager::manage( this ); } DistributionListWidget::~DistributionListWidget() { delete mManager; } void DistributionListWidget::save() { mManager->save(); } void DistributionListWidget::selectionContactViewChanged() { ContactItem *contactItem = static_cast<ContactItem *>( mContactView->selectedItem() ); bool state = contactItem; mChangeEmailButton->setEnabled( state ); mRemoveContactButton->setEnabled( state ); } void DistributionListWidget::createList() { KLineEditDlg dlg( i18n( "Please enter name:" ), QString::null, this ); dlg.setCaption( i18n( "New Distribution List" ) ); if ( !dlg.exec() ) return; new KABC::DistributionList( mManager, dlg.text() ); mNameCombo->clear(); mNameCombo->insertStringList( mManager->listNames() ); mNameCombo->setCurrentItem( mNameCombo->count() - 1 ); updateContactView(); changed(); } void DistributionListWidget::editList() { QString oldName = mNameCombo->currentText(); KLineEditDlg dlg( i18n( "Please change name:" ), oldName, this ); dlg.setCaption( i18n("Distribution List") ); if ( !dlg.exec() ) return; KABC::DistributionList *list = mManager->list( oldName ); list->setName( dlg.text() ); mNameCombo->clear(); mNameCombo->insertStringList( mManager->listNames() ); mNameCombo->setCurrentItem( mNameCombo->count() - 1 ); updateContactView(); changed(); } void DistributionListWidget::removeList() { int result = KMessageBox::warningContinueCancel( this, i18n( "<qt>Delete distribution list <b>%1</b>?</qt>" ) .arg( mNameCombo->currentText() ), QString::null, i18n( "Delete" ) ); if ( result != KMessageBox::Continue ) return; delete mManager->list( mNameCombo->currentText() ); mNameCombo->removeItem( mNameCombo->currentItem() ); updateContactView(); changed(); } void DistributionListWidget::addContact() { KABC::DistributionList *list = mManager->list( mNameCombo->currentText() ); if ( !list ) return; KABC::Addressee::List addrList = selectedAddressees(); KABC::Addressee::List::Iterator it; for ( it = addrList.begin(); it != addrList.end(); ++it ) list->insertEntry( *it ); updateContactView(); changed(); } void DistributionListWidget::removeContact() { KABC::DistributionList *list = mManager->list( mNameCombo->currentText() ); if ( !list ) return; ContactItem *contactItem = static_cast<ContactItem *>( mContactView->selectedItem() ); if ( !contactItem ) return; list->removeEntry( contactItem->addressee(), contactItem->email() ); delete contactItem; changed(); } void DistributionListWidget::changeEmail() { KABC::DistributionList *list = mManager->list( mNameCombo->currentText() ); if ( !list ) return; ContactItem *contactItem = static_cast<ContactItem *>( mContactView->selectedItem() ); if ( !contactItem ) return; QString email = EmailSelector::getEmail( contactItem->addressee().emails(), contactItem->email(), this ); list->removeEntry( contactItem->addressee(), contactItem->email() ); list->insertEntry( contactItem->addressee(), email ); updateContactView(); changed(); } void DistributionListWidget::updateContactView() { mContactView->clear(); KABC::DistributionList *list = mManager->list( mNameCombo->currentText() ); if ( !list ) { mEditListButton->setEnabled( false ); mRemoveListButton->setEnabled( false ); mChangeEmailButton->setEnabled( false ); mRemoveContactButton->setEnabled( false ); mContactView->setEnabled( false ); return; } else { mEditListButton->setEnabled( true ); mRemoveListButton->setEnabled( true ); mContactView->setEnabled( true ); } KABC::DistributionList::Entry::List entries = list->entries(); KABC::DistributionList::Entry::List::ConstIterator it; for( it = entries.begin(); it != entries.end(); ++it ) new ContactItem( mContactView, (*it).addressee, (*it).email ); ContactItem *contactItem = static_cast<ContactItem *>( mContactView->selectedItem() ); bool state = contactItem; mChangeEmailButton->setEnabled( state ); mRemoveContactButton->setEnabled( state ); } void DistributionListWidget::updateNameCombo() { mNameCombo->insertStringList( mManager->listNames() ); updateContactView(); } void DistributionListWidget::dropEvent( QDropEvent *e ) { KABC::DistributionList *distributionList = mManager->list( mNameCombo->currentText() ); if ( !distributionList ) return; QString vcards; if ( KVCardDrag::decode( e, vcards ) ) { QStringList list = QStringList::split( "\r\n\r\n", vcards ); QStringList::Iterator it; KABC::VCardConverter converter; for ( it = list.begin(); it != list.end(); ++it ) { KABC::Addressee addr; if ( converter.vCardToAddressee( (*it).stripWhiteSpace(), addr ) ) distributionList->insertEntry( addr ); } changed(); updateContactView(); } } void DistributionListWidget::addresseeSelectionChanged() { mAddContactButton->setEnabled( addresseesSelected() && mNameCombo->count() > 0 ); } QString DistributionListWidget::title() const { return i18n( "Distribution List Editor" ); } QString DistributionListWidget::identifier() const { return "distribution_list_editor"; } void DistributionListWidget::dropped( QDropEvent *e, QListViewItem* ) { dropEvent( e ); } void DistributionListWidget::changed() { save(); emit modified( KABC::Addressee::List() ); } DistributionListView::DistributionListView( QWidget *parent, const char* name ) : KListView( parent, name ) { setDragEnabled( true ); setAcceptDrops( true ); setAllColumnsShowFocus( true ); } void DistributionListView::dragEnterEvent( QDragEnterEvent* e ) { bool canDecode = QTextDrag::canDecode( e ); e->accept( canDecode ); } void DistributionListView::viewportDragMoveEvent( QDragMoveEvent *e ) { bool canDecode = QTextDrag::canDecode( e ); e->accept( canDecode ); } void DistributionListView::viewportDropEvent( QDropEvent *e ) { emit dropped( e, 0 ); } void DistributionListView::dropEvent( QDropEvent *e ) { emit dropped( e, 0 ); } EmailSelector::EmailSelector( const QStringList &emails, const QString &current, QWidget *parent ) : KDialogBase( KDialogBase::Plain, i18n("Select Email Address"), Ok, Ok, parent ) { QFrame *topFrame = plainPage(); QBoxLayout *topLayout = new QVBoxLayout( topFrame ); mButtonGroup = new QButtonGroup( 1, Horizontal, i18n("Email Addresses"), topFrame ); topLayout->addWidget( mButtonGroup ); QStringList::ConstIterator it; for( it = emails.begin(); it != emails.end(); ++it ) { QRadioButton *button = new QRadioButton( *it, mButtonGroup ); if ( (*it) == current ) { button->setDown( true ); } } } QString EmailSelector::selected() { QButton *button = mButtonGroup->selected(); if ( button ) return button->text(); return QString::null; } QString EmailSelector::getEmail( const QStringList &emails, const QString &current, QWidget *parent ) { EmailSelector dlg( emails, current, parent ); dlg.exec(); return dlg.selected(); } #include "distributionlistwidget.moc" <|endoftext|>
<commit_before>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/video/video_receive_stream.h" #include <stdlib.h> #include <string> #include "webrtc/base/checks.h" #include "webrtc/common_video/libyuv/include/webrtc_libyuv.h" #include "webrtc/system_wrappers/interface/clock.h" #include "webrtc/system_wrappers/interface/logging.h" #include "webrtc/video/receive_statistics_proxy.h" #include "webrtc/video_encoder.h" #include "webrtc/video_engine/include/vie_base.h" #include "webrtc/video_engine/include/vie_capture.h" #include "webrtc/video_engine/include/vie_codec.h" #include "webrtc/video_engine/include/vie_external_codec.h" #include "webrtc/video_engine/include/vie_image_process.h" #include "webrtc/video_engine/include/vie_network.h" #include "webrtc/video_engine/include/vie_render.h" #include "webrtc/video_engine/include/vie_rtp_rtcp.h" #include "webrtc/video_receive_stream.h" namespace webrtc { std::string VideoReceiveStream::Decoder::ToString() const { std::stringstream ss; ss << "{decoder: " << (decoder != nullptr ? "(VideoDecoder)" : "nullptr"); ss << ", payload_type: " << payload_type; ss << ", payload_name: " << payload_name; ss << ", is_renderer: " << (is_renderer ? "yes" : "no"); ss << ", expected_delay_ms: " << expected_delay_ms; ss << '}'; return ss.str(); } std::string VideoReceiveStream::Config::ToString() const { std::stringstream ss; ss << "{decoders: ["; for (size_t i = 0; i < decoders.size(); ++i) { ss << decoders[i].ToString(); if (i != decoders.size() - 1) ss << ", "; } ss << ']'; ss << ", rtp: " << rtp.ToString(); ss << ", renderer: " << (renderer != nullptr ? "(renderer)" : "nullptr"); ss << ", render_delay_ms: " << render_delay_ms; ss << ", audio_channel_id: " << audio_channel_id; ss << ", pre_decode_callback: " << (pre_decode_callback != nullptr ? "(EncodedFrameObserver)" : "nullptr"); ss << ", pre_render_callback: " << (pre_render_callback != nullptr ? "(I420FrameCallback)" : "nullptr"); ss << ", target_delay_ms: " << target_delay_ms; ss << '}'; return ss.str(); } std::string VideoReceiveStream::Config::Rtp::ToString() const { std::stringstream ss; ss << "{remote_ssrc: " << remote_ssrc; ss << ", local_ssrc: " << local_ssrc; ss << ", rtcp_mode: " << (rtcp_mode == newapi::kRtcpCompound ? "kRtcpCompound" : "kRtcpReducedSize"); ss << ", rtcp_xr: "; ss << "{receiver_reference_time_report: " << (rtcp_xr.receiver_reference_time_report ? "on" : "off"); ss << '}'; ss << ", remb: " << (remb ? "on" : "off"); ss << ", nack: {rtp_history_ms: " << nack.rtp_history_ms << '}'; ss << ", fec: " << fec.ToString(); ss << ", rtx: {"; for (auto& kv : rtx) { ss << kv.first << " -> "; ss << "{ssrc: " << kv.second.ssrc; ss << ", payload_type: " << kv.second.payload_type; ss << '}'; } ss << '}'; ss << ", extensions: ["; for (size_t i = 0; i < extensions.size(); ++i) { ss << extensions[i].ToString(); if (i != extensions.size() - 1) ss << ", "; } ss << ']'; ss << '}'; return ss.str(); } namespace internal { namespace { VideoCodec CreateDecoderVideoCodec(const VideoReceiveStream::Decoder& decoder) { VideoCodec codec; memset(&codec, 0, sizeof(codec)); codec.plType = decoder.payload_type; strcpy(codec.plName, decoder.payload_name.c_str()); if (decoder.payload_name == "VP8") { codec.codecType = kVideoCodecVP8; } else if (decoder.payload_name == "H264") { codec.codecType = kVideoCodecH264; } else { codec.codecType = kVideoCodecGeneric; } if (codec.codecType == kVideoCodecVP8) { codec.codecSpecific.VP8 = VideoEncoder::GetDefaultVp8Settings(); } else if (codec.codecType == kVideoCodecH264) { codec.codecSpecific.H264 = VideoEncoder::GetDefaultH264Settings(); } codec.width = 320; codec.height = 180; codec.startBitrate = codec.minBitrate = codec.maxBitrate = Call::Config::kDefaultStartBitrateBps / 1000; return codec; } } // namespace VideoReceiveStream::VideoReceiveStream(webrtc::VideoEngine* video_engine, ChannelGroup* channel_group, const VideoReceiveStream::Config& config, newapi::Transport* transport, webrtc::VoiceEngine* voice_engine, int base_channel) : transport_adapter_(transport), encoded_frame_proxy_(config.pre_decode_callback), config_(config), clock_(Clock::GetRealTimeClock()), channel_group_(channel_group), voe_sync_interface_(nullptr), channel_(-1) { video_engine_base_ = ViEBase::GetInterface(video_engine); video_engine_base_->CreateReceiveChannel(channel_, base_channel); DCHECK(channel_ != -1); vie_channel_ = video_engine_base_->GetChannel(channel_); // TODO(pbos): This is not fine grained enough... vie_channel_->SetNACKStatus(config_.rtp.nack.rtp_history_ms > 0); vie_channel_->SetKeyFrameRequestMethod(kKeyFrameReqPliRtcp); SetRtcpMode(config_.rtp.rtcp_mode); DCHECK(config_.rtp.remote_ssrc != 0); // TODO(pbos): What's an appropriate local_ssrc for receive-only streams? DCHECK(config_.rtp.local_ssrc != 0); DCHECK(config_.rtp.remote_ssrc != config_.rtp.local_ssrc); vie_channel_->SetSSRC(config_.rtp.local_ssrc, kViEStreamTypeNormal, 0); // TODO(pbos): Support multiple RTX, per video payload. Config::Rtp::RtxMap::const_iterator it = config_.rtp.rtx.begin(); for (; it != config_.rtp.rtx.end(); ++it) { DCHECK(it->second.ssrc != 0); DCHECK(it->second.payload_type != 0); vie_channel_->SetRemoteSSRCType(kViEStreamTypeRtx, it->second.ssrc); vie_channel_->SetRtxReceivePayloadType(it->second.payload_type, it->first); } // TODO(pbos): Remove channel_group_ usage from VideoReceiveStream. This // should be configured in call.cc. channel_group_->SetChannelRembStatus(false, config_.rtp.remb, vie_channel_); for (size_t i = 0; i < config_.rtp.extensions.size(); ++i) { const std::string& extension = config_.rtp.extensions[i].name; int id = config_.rtp.extensions[i].id; // One-byte-extension local identifiers are in the range 1-14 inclusive. DCHECK_GE(id, 1); DCHECK_LE(id, 14); if (extension == RtpExtension::kTOffset) { CHECK_EQ(0, vie_channel_->SetReceiveTimestampOffsetStatus(true, id)); } else if (extension == RtpExtension::kAbsSendTime) { CHECK_EQ(0, vie_channel_->SetReceiveAbsoluteSendTimeStatus(true, id)); } else if (extension == RtpExtension::kVideoRotation) { CHECK_EQ(0, vie_channel_->SetReceiveVideoRotationStatus(true, id)); } else { RTC_NOTREACHED() << "Unsupported RTP extension."; } } vie_channel_->RegisterSendTransport(&transport_adapter_); if (config_.rtp.fec.ulpfec_payload_type != -1) { // ULPFEC without RED doesn't make sense. DCHECK(config_.rtp.fec.red_payload_type != -1); VideoCodec codec; memset(&codec, 0, sizeof(codec)); codec.codecType = kVideoCodecULPFEC; strcpy(codec.plName, "ulpfec"); codec.plType = config_.rtp.fec.ulpfec_payload_type; CHECK_EQ(0, vie_channel_->SetReceiveCodec(codec)); } if (config_.rtp.fec.red_payload_type != -1) { VideoCodec codec; memset(&codec, 0, sizeof(codec)); codec.codecType = kVideoCodecRED; strcpy(codec.plName, "red"); codec.plType = config_.rtp.fec.red_payload_type; CHECK_EQ(0, vie_channel_->SetReceiveCodec(codec)); if (config_.rtp.fec.red_rtx_payload_type != -1) { vie_channel_->SetRtxReceivePayloadType( config_.rtp.fec.red_rtx_payload_type, config_.rtp.fec.red_payload_type); } } if (config.rtp.rtcp_xr.receiver_reference_time_report) vie_channel_->SetRtcpXrRrtrStatus(true); stats_proxy_.reset( new ReceiveStatisticsProxy(config_.rtp.remote_ssrc, clock_)); vie_channel_->RegisterReceiveChannelRtcpStatisticsCallback( stats_proxy_.get()); vie_channel_->RegisterReceiveChannelRtpStatisticsCallback(stats_proxy_.get()); vie_channel_->RegisterRtcpPacketTypeCounterObserver(stats_proxy_.get()); vie_channel_->RegisterCodecObserver(stats_proxy_.get()); vie_channel_->RegisterReceiveStatisticsProxy(stats_proxy_.get()); DCHECK(!config_.decoders.empty()); for (size_t i = 0; i < config_.decoders.size(); ++i) { const Decoder& decoder = config_.decoders[i]; CHECK_EQ(0, vie_channel_->RegisterExternalDecoder( decoder.payload_type, decoder.decoder, decoder.is_renderer, decoder.expected_delay_ms)); VideoCodec codec = CreateDecoderVideoCodec(decoder); CHECK_EQ(0, vie_channel_->SetReceiveCodec(codec)); } // Register a renderer without a window handle, at depth 0, that covers the // entire rendered area (0->1 both axes). This registers a renderer that // renders the entire video. incoming_video_stream_.reset(new IncomingVideoStream(channel_)); incoming_video_stream_->SetExpectedRenderDelay(config.render_delay_ms); incoming_video_stream_->SetExternalCallback(this); vie_channel_->SetIncomingVideoStream(incoming_video_stream_.get()); if (voice_engine && config_.audio_channel_id != -1) { voe_sync_interface_ = VoEVideoSync::GetInterface(voice_engine); vie_channel_->SetVoiceChannel(config.audio_channel_id, voe_sync_interface_); } if (config.pre_decode_callback) vie_channel_->RegisterPreDecodeImageCallback(&encoded_frame_proxy_); vie_channel_->RegisterPreRenderCallback(this); } VideoReceiveStream::~VideoReceiveStream() { vie_channel_->RegisterPreRenderCallback(nullptr); vie_channel_->RegisterPreDecodeImageCallback(nullptr); for (size_t i = 0; i < config_.decoders.size(); ++i) vie_channel_->DeRegisterExternalDecoder(config_.decoders[i].payload_type); vie_channel_->DeregisterSendTransport(); if (voe_sync_interface_ != nullptr) { vie_channel_->SetVoiceChannel(-1, nullptr); voe_sync_interface_->Release(); } vie_channel_->RegisterCodecObserver(nullptr); vie_channel_->RegisterReceiveChannelRtpStatisticsCallback(nullptr); vie_channel_->RegisterReceiveChannelRtcpStatisticsCallback(nullptr); vie_channel_->RegisterRtcpPacketTypeCounterObserver(nullptr); video_engine_base_->DeleteChannel(channel_); video_engine_base_->Release(); } void VideoReceiveStream::Start() { transport_adapter_.Enable(); incoming_video_stream_->Start(); vie_channel_->StartReceive(); } void VideoReceiveStream::Stop() { incoming_video_stream_->Stop(); vie_channel_->StopReceive(); transport_adapter_.Disable(); } VideoReceiveStream::Stats VideoReceiveStream::GetStats() const { return stats_proxy_->GetStats(); } bool VideoReceiveStream::DeliverRtcp(const uint8_t* packet, size_t length) { return vie_channel_->ReceivedRTCPPacket(packet, length) == 0; } bool VideoReceiveStream::DeliverRtp(const uint8_t* packet, size_t length) { return vie_channel_->ReceivedRTPPacket(packet, length, PacketTime()) == 0; } void VideoReceiveStream::FrameCallback(I420VideoFrame* video_frame) { stats_proxy_->OnDecodedFrame(); if (config_.pre_render_callback) config_.pre_render_callback->FrameCallback(video_frame); } int VideoReceiveStream::RenderFrame(const uint32_t /*stream_id*/, const I420VideoFrame& video_frame) { // TODO(pbos): Wire up config_.render->IsTextureSupported() and convert if not // supported. Or provide methods for converting a texture frame in // I420VideoFrame. if (config_.renderer != nullptr) config_.renderer->RenderFrame( video_frame, video_frame.render_time_ms() - clock_->TimeInMilliseconds()); stats_proxy_->OnRenderedFrame(); return 0; } void VideoReceiveStream::SignalNetworkState(Call::NetworkState state) { if (state == Call::kNetworkUp) SetRtcpMode(config_.rtp.rtcp_mode); if (state == Call::kNetworkDown) vie_channel_->SetRTCPMode(kRtcpOff); } void VideoReceiveStream::SetRtcpMode(newapi::RtcpMode mode) { switch (mode) { case newapi::kRtcpCompound: vie_channel_->SetRTCPMode(kRtcpCompound); break; case newapi::kRtcpReducedSize: vie_channel_->SetRTCPMode(kRtcpNonCompound); break; } } } // namespace internal } // namespace webrtc <commit_msg>Stop IncomingVideoStream on delete.<commit_after>/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/video/video_receive_stream.h" #include <stdlib.h> #include <string> #include "webrtc/base/checks.h" #include "webrtc/common_video/libyuv/include/webrtc_libyuv.h" #include "webrtc/system_wrappers/interface/clock.h" #include "webrtc/system_wrappers/interface/logging.h" #include "webrtc/video/receive_statistics_proxy.h" #include "webrtc/video_encoder.h" #include "webrtc/video_engine/include/vie_base.h" #include "webrtc/video_engine/include/vie_capture.h" #include "webrtc/video_engine/include/vie_codec.h" #include "webrtc/video_engine/include/vie_external_codec.h" #include "webrtc/video_engine/include/vie_image_process.h" #include "webrtc/video_engine/include/vie_network.h" #include "webrtc/video_engine/include/vie_render.h" #include "webrtc/video_engine/include/vie_rtp_rtcp.h" #include "webrtc/video_receive_stream.h" namespace webrtc { std::string VideoReceiveStream::Decoder::ToString() const { std::stringstream ss; ss << "{decoder: " << (decoder != nullptr ? "(VideoDecoder)" : "nullptr"); ss << ", payload_type: " << payload_type; ss << ", payload_name: " << payload_name; ss << ", is_renderer: " << (is_renderer ? "yes" : "no"); ss << ", expected_delay_ms: " << expected_delay_ms; ss << '}'; return ss.str(); } std::string VideoReceiveStream::Config::ToString() const { std::stringstream ss; ss << "{decoders: ["; for (size_t i = 0; i < decoders.size(); ++i) { ss << decoders[i].ToString(); if (i != decoders.size() - 1) ss << ", "; } ss << ']'; ss << ", rtp: " << rtp.ToString(); ss << ", renderer: " << (renderer != nullptr ? "(renderer)" : "nullptr"); ss << ", render_delay_ms: " << render_delay_ms; ss << ", audio_channel_id: " << audio_channel_id; ss << ", pre_decode_callback: " << (pre_decode_callback != nullptr ? "(EncodedFrameObserver)" : "nullptr"); ss << ", pre_render_callback: " << (pre_render_callback != nullptr ? "(I420FrameCallback)" : "nullptr"); ss << ", target_delay_ms: " << target_delay_ms; ss << '}'; return ss.str(); } std::string VideoReceiveStream::Config::Rtp::ToString() const { std::stringstream ss; ss << "{remote_ssrc: " << remote_ssrc; ss << ", local_ssrc: " << local_ssrc; ss << ", rtcp_mode: " << (rtcp_mode == newapi::kRtcpCompound ? "kRtcpCompound" : "kRtcpReducedSize"); ss << ", rtcp_xr: "; ss << "{receiver_reference_time_report: " << (rtcp_xr.receiver_reference_time_report ? "on" : "off"); ss << '}'; ss << ", remb: " << (remb ? "on" : "off"); ss << ", nack: {rtp_history_ms: " << nack.rtp_history_ms << '}'; ss << ", fec: " << fec.ToString(); ss << ", rtx: {"; for (auto& kv : rtx) { ss << kv.first << " -> "; ss << "{ssrc: " << kv.second.ssrc; ss << ", payload_type: " << kv.second.payload_type; ss << '}'; } ss << '}'; ss << ", extensions: ["; for (size_t i = 0; i < extensions.size(); ++i) { ss << extensions[i].ToString(); if (i != extensions.size() - 1) ss << ", "; } ss << ']'; ss << '}'; return ss.str(); } namespace internal { namespace { VideoCodec CreateDecoderVideoCodec(const VideoReceiveStream::Decoder& decoder) { VideoCodec codec; memset(&codec, 0, sizeof(codec)); codec.plType = decoder.payload_type; strcpy(codec.plName, decoder.payload_name.c_str()); if (decoder.payload_name == "VP8") { codec.codecType = kVideoCodecVP8; } else if (decoder.payload_name == "H264") { codec.codecType = kVideoCodecH264; } else { codec.codecType = kVideoCodecGeneric; } if (codec.codecType == kVideoCodecVP8) { codec.codecSpecific.VP8 = VideoEncoder::GetDefaultVp8Settings(); } else if (codec.codecType == kVideoCodecH264) { codec.codecSpecific.H264 = VideoEncoder::GetDefaultH264Settings(); } codec.width = 320; codec.height = 180; codec.startBitrate = codec.minBitrate = codec.maxBitrate = Call::Config::kDefaultStartBitrateBps / 1000; return codec; } } // namespace VideoReceiveStream::VideoReceiveStream(webrtc::VideoEngine* video_engine, ChannelGroup* channel_group, const VideoReceiveStream::Config& config, newapi::Transport* transport, webrtc::VoiceEngine* voice_engine, int base_channel) : transport_adapter_(transport), encoded_frame_proxy_(config.pre_decode_callback), config_(config), clock_(Clock::GetRealTimeClock()), channel_group_(channel_group), voe_sync_interface_(nullptr), channel_(-1) { video_engine_base_ = ViEBase::GetInterface(video_engine); video_engine_base_->CreateReceiveChannel(channel_, base_channel); DCHECK(channel_ != -1); vie_channel_ = video_engine_base_->GetChannel(channel_); // TODO(pbos): This is not fine grained enough... vie_channel_->SetNACKStatus(config_.rtp.nack.rtp_history_ms > 0); vie_channel_->SetKeyFrameRequestMethod(kKeyFrameReqPliRtcp); SetRtcpMode(config_.rtp.rtcp_mode); DCHECK(config_.rtp.remote_ssrc != 0); // TODO(pbos): What's an appropriate local_ssrc for receive-only streams? DCHECK(config_.rtp.local_ssrc != 0); DCHECK(config_.rtp.remote_ssrc != config_.rtp.local_ssrc); vie_channel_->SetSSRC(config_.rtp.local_ssrc, kViEStreamTypeNormal, 0); // TODO(pbos): Support multiple RTX, per video payload. Config::Rtp::RtxMap::const_iterator it = config_.rtp.rtx.begin(); for (; it != config_.rtp.rtx.end(); ++it) { DCHECK(it->second.ssrc != 0); DCHECK(it->second.payload_type != 0); vie_channel_->SetRemoteSSRCType(kViEStreamTypeRtx, it->second.ssrc); vie_channel_->SetRtxReceivePayloadType(it->second.payload_type, it->first); } // TODO(pbos): Remove channel_group_ usage from VideoReceiveStream. This // should be configured in call.cc. channel_group_->SetChannelRembStatus(false, config_.rtp.remb, vie_channel_); for (size_t i = 0; i < config_.rtp.extensions.size(); ++i) { const std::string& extension = config_.rtp.extensions[i].name; int id = config_.rtp.extensions[i].id; // One-byte-extension local identifiers are in the range 1-14 inclusive. DCHECK_GE(id, 1); DCHECK_LE(id, 14); if (extension == RtpExtension::kTOffset) { CHECK_EQ(0, vie_channel_->SetReceiveTimestampOffsetStatus(true, id)); } else if (extension == RtpExtension::kAbsSendTime) { CHECK_EQ(0, vie_channel_->SetReceiveAbsoluteSendTimeStatus(true, id)); } else if (extension == RtpExtension::kVideoRotation) { CHECK_EQ(0, vie_channel_->SetReceiveVideoRotationStatus(true, id)); } else { RTC_NOTREACHED() << "Unsupported RTP extension."; } } vie_channel_->RegisterSendTransport(&transport_adapter_); if (config_.rtp.fec.ulpfec_payload_type != -1) { // ULPFEC without RED doesn't make sense. DCHECK(config_.rtp.fec.red_payload_type != -1); VideoCodec codec; memset(&codec, 0, sizeof(codec)); codec.codecType = kVideoCodecULPFEC; strcpy(codec.plName, "ulpfec"); codec.plType = config_.rtp.fec.ulpfec_payload_type; CHECK_EQ(0, vie_channel_->SetReceiveCodec(codec)); } if (config_.rtp.fec.red_payload_type != -1) { VideoCodec codec; memset(&codec, 0, sizeof(codec)); codec.codecType = kVideoCodecRED; strcpy(codec.plName, "red"); codec.plType = config_.rtp.fec.red_payload_type; CHECK_EQ(0, vie_channel_->SetReceiveCodec(codec)); if (config_.rtp.fec.red_rtx_payload_type != -1) { vie_channel_->SetRtxReceivePayloadType( config_.rtp.fec.red_rtx_payload_type, config_.rtp.fec.red_payload_type); } } if (config.rtp.rtcp_xr.receiver_reference_time_report) vie_channel_->SetRtcpXrRrtrStatus(true); stats_proxy_.reset( new ReceiveStatisticsProxy(config_.rtp.remote_ssrc, clock_)); vie_channel_->RegisterReceiveChannelRtcpStatisticsCallback( stats_proxy_.get()); vie_channel_->RegisterReceiveChannelRtpStatisticsCallback(stats_proxy_.get()); vie_channel_->RegisterRtcpPacketTypeCounterObserver(stats_proxy_.get()); vie_channel_->RegisterCodecObserver(stats_proxy_.get()); vie_channel_->RegisterReceiveStatisticsProxy(stats_proxy_.get()); DCHECK(!config_.decoders.empty()); for (size_t i = 0; i < config_.decoders.size(); ++i) { const Decoder& decoder = config_.decoders[i]; CHECK_EQ(0, vie_channel_->RegisterExternalDecoder( decoder.payload_type, decoder.decoder, decoder.is_renderer, decoder.expected_delay_ms)); VideoCodec codec = CreateDecoderVideoCodec(decoder); CHECK_EQ(0, vie_channel_->SetReceiveCodec(codec)); } // Register a renderer without a window handle, at depth 0, that covers the // entire rendered area (0->1 both axes). This registers a renderer that // renders the entire video. incoming_video_stream_.reset(new IncomingVideoStream(channel_)); incoming_video_stream_->SetExpectedRenderDelay(config.render_delay_ms); incoming_video_stream_->SetExternalCallback(this); vie_channel_->SetIncomingVideoStream(incoming_video_stream_.get()); if (voice_engine && config_.audio_channel_id != -1) { voe_sync_interface_ = VoEVideoSync::GetInterface(voice_engine); vie_channel_->SetVoiceChannel(config.audio_channel_id, voe_sync_interface_); } if (config.pre_decode_callback) vie_channel_->RegisterPreDecodeImageCallback(&encoded_frame_proxy_); vie_channel_->RegisterPreRenderCallback(this); } VideoReceiveStream::~VideoReceiveStream() { incoming_video_stream_->Stop(); vie_channel_->RegisterPreRenderCallback(nullptr); vie_channel_->RegisterPreDecodeImageCallback(nullptr); for (size_t i = 0; i < config_.decoders.size(); ++i) vie_channel_->DeRegisterExternalDecoder(config_.decoders[i].payload_type); vie_channel_->DeregisterSendTransport(); if (voe_sync_interface_ != nullptr) { vie_channel_->SetVoiceChannel(-1, nullptr); voe_sync_interface_->Release(); } vie_channel_->RegisterCodecObserver(nullptr); vie_channel_->RegisterReceiveChannelRtpStatisticsCallback(nullptr); vie_channel_->RegisterReceiveChannelRtcpStatisticsCallback(nullptr); vie_channel_->RegisterRtcpPacketTypeCounterObserver(nullptr); video_engine_base_->DeleteChannel(channel_); video_engine_base_->Release(); } void VideoReceiveStream::Start() { transport_adapter_.Enable(); incoming_video_stream_->Start(); vie_channel_->StartReceive(); } void VideoReceiveStream::Stop() { incoming_video_stream_->Stop(); vie_channel_->StopReceive(); transport_adapter_.Disable(); } VideoReceiveStream::Stats VideoReceiveStream::GetStats() const { return stats_proxy_->GetStats(); } bool VideoReceiveStream::DeliverRtcp(const uint8_t* packet, size_t length) { return vie_channel_->ReceivedRTCPPacket(packet, length) == 0; } bool VideoReceiveStream::DeliverRtp(const uint8_t* packet, size_t length) { return vie_channel_->ReceivedRTPPacket(packet, length, PacketTime()) == 0; } void VideoReceiveStream::FrameCallback(I420VideoFrame* video_frame) { stats_proxy_->OnDecodedFrame(); if (config_.pre_render_callback) config_.pre_render_callback->FrameCallback(video_frame); } int VideoReceiveStream::RenderFrame(const uint32_t /*stream_id*/, const I420VideoFrame& video_frame) { // TODO(pbos): Wire up config_.render->IsTextureSupported() and convert if not // supported. Or provide methods for converting a texture frame in // I420VideoFrame. if (config_.renderer != nullptr) config_.renderer->RenderFrame( video_frame, video_frame.render_time_ms() - clock_->TimeInMilliseconds()); stats_proxy_->OnRenderedFrame(); return 0; } void VideoReceiveStream::SignalNetworkState(Call::NetworkState state) { if (state == Call::kNetworkUp) SetRtcpMode(config_.rtp.rtcp_mode); if (state == Call::kNetworkDown) vie_channel_->SetRTCPMode(kRtcpOff); } void VideoReceiveStream::SetRtcpMode(newapi::RtcpMode mode) { switch (mode) { case newapi::kRtcpCompound: vie_channel_->SetRTCPMode(kRtcpCompound); break; case newapi::kRtcpReducedSize: vie_channel_->SetRTCPMode(kRtcpNonCompound); break; } } } // namespace internal } // namespace webrtc <|endoftext|>
<commit_before>/* This file is part of Kontact. Copyright (c) 2003 Tobias Koenig <tokoe@kde.org> Copyright (c) 2005-2006,2008 Allen Winter <winter@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "apptsummarywidget.h" #include "korganizerplugin.h" #include "korganizerinterface.h" #include <korganizer/stdcalendar.h> #include <kontactinterfaces/core.h> #include <kcal/incidenceformatter.h> #include <kcal/resourcecalendar.h> #include <kconfiggroup.h> #include <kiconloader.h> #include <klocale.h> #include <kmenu.h> #include <kurllabel.h> #include <QDateTime> #include <QGridLayout> #include <QLabel> #include <QVBoxLayout> #include <QTextDocument> ApptSummaryWidget::ApptSummaryWidget( KOrganizerPlugin *plugin, QWidget *parent ) : Kontact::Summary( parent ), mPlugin( plugin ), mCalendar( 0 ) { QVBoxLayout *mainLayout = new QVBoxLayout( this ); mainLayout->setSpacing( 3 ); mainLayout->setMargin( 3 ); QWidget *header = createHeader( this, "view-calendar-upcoming-events", i18n( "Upcoming Events" ) ); mainLayout->addWidget( header ); mLayout = new QGridLayout(); mainLayout->addItem( mLayout ); mLayout->setSpacing( 3 ); mLayout->setRowStretch( 6, 1 ); mCalendar = KOrg::StdCalendar::self(); mCalendar->load(); connect( mCalendar, SIGNAL(calendarChanged()), SLOT(updateView()) ); connect( mPlugin->core(), SIGNAL(dayChanged(const QDate&)), SLOT(updateView()) ); updateView(); } ApptSummaryWidget::~ApptSummaryWidget() { } void ApptSummaryWidget::updateView() { qDeleteAll( mLabels ); mLabels.clear(); KConfig _config( "kcmapptsummaryrc" ); KConfigGroup config(&_config, "Days" ); int days = config.readEntry( "DaysToShow", 7 ); // The event print consists of the following fields: // icon:start date:days-to-go:summary:time range // where, // the icon is the typical event icon // the start date is the event start date // the days-to-go is the #days until the event starts // the summary is the event summary // the time range is the start-end time (only for non-floating events) QLabel *label = 0; int counter = 0; KIconLoader loader( "korganizer" ); QPixmap pm = loader.loadIcon( "view-calendar-day", KIconLoader::Small ); QString str; QDate dt; QDate currentDate = QDate::currentDate(); for ( dt=currentDate; dt<=currentDate.addDays( days - 1 ); dt=dt.addDays(1) ) { KCal::Event *ev; KCal::Event::List events_orig = mCalendar->events( dt, mCalendar->timeSpec() ); KCal::Event::List::ConstIterator it = events_orig.begin(); KCal::Event::List events; events.setAutoDelete( true ); KDateTime qdt; // prevent implicitely sharing while finding recurring events // replacing the QDate with the currentDate for ( ; it != events_orig.end(); ++it ) { ev = (*it)->clone(); if ( ev->recursOn( dt, mCalendar->timeSpec() ) ) { qdt = ev->dtStart(); qdt.setDate( dt ); ev->setDtStart( qdt ); } events.append( ev ); } // sort the events for this date by summary events = KCal::Calendar::sortEvents( &events, KCal::EventSortSummary, KCal::SortDirectionAscending ); // sort the events for this date by start date events = KCal::Calendar::sortEvents( &events, KCal::EventSortStartDate, KCal::SortDirectionAscending ); for ( it=events.begin(); it != events.end(); ++it ) { ev = *it; bool makeBold = false; int daysTo = -1; // ### If you change anything in the multiday logic below, make sure // you test it with: // - a multiday, all-day event currently in progress // - a multiday, all-day event in the future // - a multiday event with associated time which is in progress // - a multiday event with associated time which is in the future // Count number of days remaining in multiday event int span = 1; int dayof = 1; if ( ev->isMultiDay() ) { QDate d = ev->dtStart().date(); if ( d < currentDate ) { dayof += d.daysTo( currentDate ); span += d.daysTo( currentDate ); d = currentDate; } while ( d < ev->dtEnd().date() ) { if ( d < dt ) { dayof++; } span++; d = d.addDays( 1 ); } } QDate startOfMultiday = ev->dtStart().date(); if ( startOfMultiday < currentDate ) startOfMultiday = currentDate; bool firstDayOfMultiday = ( dt == startOfMultiday ); // If this date is part of a floating, multiday event, then we // only make a print for the first day of the event. if ( ev->isMultiDay() && ev->allDay() && ( currentDate > ev->dtStart().date() || !firstDayOfMultiday ) ) { continue; } // Icon label label = new QLabel( this ); label->setPixmap( pm ); label->setMaximumWidth( label->minimumSizeHint().width() ); mLayout->addWidget( label, counter, 0 ); mLabels.append( label ); // Start date label str = ""; QDate sD = QDate( dt.year(), dt.month(), dt.day() ); if ( ( sD.month() == currentDate.month() ) && ( sD.day() == currentDate.day() ) ) { str = i18nc( "@label the appointment is today", "Today" ); makeBold = true; } else if ( ( sD.month() == currentDate.addDays( 1 ).month() ) && ( sD.day() == currentDate.addDays( 1 ).day() ) ) { str = i18nc( "@label the appointment is tomorrow", "Tomorrow" ); } else { str = KGlobal::locale()->formatDate( sD, KLocale::FancyLongDate ); } // Print the date span for multiday, floating events, for the // first day of the event only. if ( ev->isMultiDay() && ev->allDay() && firstDayOfMultiday && span > 1 ) { str = KGlobal::locale()->formatDate( ev->dtStart().date(), KLocale::FancyLongDate ); str += " -\n " + KGlobal::locale()->formatDate( ev->dtEnd().date(), KLocale::FancyLongDate ); } label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 1 ); mLabels.append( label ); if ( makeBold ) { QFont font = label->font(); font.setBold( true ); label->setFont( font ); } // Days to go label str = ""; dateDiff( startOfMultiday, daysTo ); if ( ev->isMultiDay() && !ev->allDay() ) dateDiff( dt, daysTo ); if ( daysTo > 0 ) { str = i18np( "in 1 day", "in %1 days", daysTo ); } else { str = i18n( "now" ); } label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 2 ); mLabels.append( label ); // Summary label str = ev->richSummary(); if ( ev->isMultiDay() && !ev->allDay() ) { str.append( QString( " (%1/%2)" ).arg( dayof ).arg( span ) ); } KUrlLabel *urlLabel = new KUrlLabel( this ); urlLabel->setText( str ); urlLabel->setUrl( ev->uid() ); urlLabel->installEventFilter( this ); urlLabel->setTextFormat( Qt::RichText ); mLayout->addWidget( urlLabel, counter, 3 ); mLabels.append( urlLabel ); connect( urlLabel, SIGNAL(leftClickedUrl(const QString&)), this, SLOT(viewEvent(const QString&)) ); connect( urlLabel, SIGNAL(rightClickedUrl(const QString&)), this, SLOT(popupMenu(const QString&)) ); QString tipText( KCal::IncidenceFormatter::toolTipString( ev, true ) ); if ( !tipText.isEmpty() ) { urlLabel->setToolTip( tipText ); } // Time range label (only for non-floating events) str = ""; if ( !ev->allDay() ) { QTime sST = ev->dtStart().time(); QTime sET = ev->dtEnd().time(); if ( ev->isMultiDay() ) { if ( ev->dtStart().date() < dt ) { sST = QTime( 0, 0 ); } if ( ev->dtEnd().date() > dt ) { sET = QTime( 23, 59 ); } } str = i18nc( "Time from - to", "%1 - %2", KGlobal::locale()->formatTime( sST ), KGlobal::locale()->formatTime( sET ) ); label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 4 ); mLabels.append( label ); } counter++; } } if ( !counter ) { QLabel *noEvents = new QLabel( i18np( "No upcoming events starting within the next day", "No upcoming events starting within the next %1 days", days ), this ); noEvents->setObjectName( "nothing to see" ); noEvents->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter ); mLayout->addWidget( noEvents, 0, 2 ); mLabels.append( noEvents ); } Q_FOREACH( label, mLabels ) label->show(); } void ApptSummaryWidget::viewEvent( const QString &uid ) { mPlugin->core()->selectPlugin( "kontact_korganizerplugin" ); //ensure loaded OrgKdeKorganizerKorganizerInterface korganizer( "org.kde.korganizer", "/Korganizer", QDBusConnection::sessionBus() ); korganizer.editIncidence( uid ); } void ApptSummaryWidget::removeEvent( const QString &uid ) { mPlugin->core()->selectPlugin( "kontact_korganizerplugin" ); //ensure loaded OrgKdeKorganizerKorganizerInterface korganizer( "org.kde.korganizer", "/Korganizer", QDBusConnection::sessionBus() ); korganizer.deleteIncidence( uid, false ); } void ApptSummaryWidget::popupMenu( const QString &uid ) { KMenu popup( this ); QAction *editIt = popup.addAction( i18n( "&Edit Appointment..." ) ); QAction *delIt = popup.addAction( i18n( "&Delete Appointment" ) ); delIt->setIcon( KIconLoader::global()-> loadIcon( "edit-delete", KIconLoader::Small ) ); const QAction *selectedAction = popup.exec( QCursor::pos() ); if ( selectedAction == editIt ) { viewEvent( uid ); } else if ( selectedAction == delIt ) { removeEvent( uid ); } } bool ApptSummaryWidget::eventFilter( QObject *obj, QEvent *e ) { if ( obj->inherits( "KUrlLabel" ) ) { KUrlLabel *label = static_cast<KUrlLabel*>( obj ); if ( e->type() == QEvent::Enter ) { emit message( i18n( "Edit Event: \"%1\"", label->text() ) ); } if ( e->type() == QEvent::Leave ) { emit message( QString::null ); //krazy:exclude=nullstrassign for old broken gcc } } return Kontact::Summary::eventFilter( obj, e ); } void ApptSummaryWidget::dateDiff( const QDate &date, int &days ) { QDate currentDate; QDate eventDate; if ( QDate::isLeapYear( date.year() ) && date.month() == 2 && date.day() == 29 ) { currentDate = QDate( date.year(), QDate::currentDate().month(), QDate::currentDate().day() ); if ( !QDate::isLeapYear( QDate::currentDate().year() ) ) { eventDate = QDate( date.year(), date.month(), 28 ); // celebrate one day earlier ;) } else { eventDate = QDate( date.year(), date.month(), date.day() ); } } else { currentDate = QDate( QDate::currentDate().year(), QDate::currentDate().month(), QDate::currentDate().day() ); eventDate = QDate( QDate::currentDate().year(), date.month(), date.day() ); } int offset = currentDate.daysTo( eventDate ); if ( offset < 0 ) { days = 365 + offset; } else { days = offset; } } QStringList ApptSummaryWidget::configModules() const { return QStringList( "kcmapptsummary.desktop" ); } #include "apptsummarywidget.moc" <commit_msg>Backport r866647 by tmcguire from trunk to the 4.1 branch:<commit_after>/* This file is part of Kontact. Copyright (c) 2003 Tobias Koenig <tokoe@kde.org> Copyright (c) 2005-2006,2008 Allen Winter <winter@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "apptsummarywidget.h" #include "korganizerplugin.h" #include "korganizerinterface.h" #include <korganizer/stdcalendar.h> #include <kontactinterfaces/core.h> #include <kcal/incidenceformatter.h> #include <kcal/resourcecalendar.h> #include <kconfiggroup.h> #include <kiconloader.h> #include <klocale.h> #include <kmenu.h> #include <kurllabel.h> #include <QDateTime> #include <QGridLayout> #include <QLabel> #include <QVBoxLayout> #include <QTextDocument> ApptSummaryWidget::ApptSummaryWidget( KOrganizerPlugin *plugin, QWidget *parent ) : Kontact::Summary( parent ), mPlugin( plugin ), mCalendar( 0 ) { QVBoxLayout *mainLayout = new QVBoxLayout( this ); mainLayout->setSpacing( 3 ); mainLayout->setMargin( 3 ); QWidget *header = createHeader( this, "view-calendar-upcoming-events", i18n( "Upcoming Events" ) ); mainLayout->addWidget( header ); mLayout = new QGridLayout(); mainLayout->addItem( mLayout ); mLayout->setSpacing( 3 ); mLayout->setRowStretch( 6, 1 ); mCalendar = KOrg::StdCalendar::self(); mCalendar->load(); connect( mCalendar, SIGNAL(calendarChanged()), SLOT(updateView()) ); connect( mPlugin->core(), SIGNAL(dayChanged(const QDate&)), SLOT(updateView()) ); updateView(); } ApptSummaryWidget::~ApptSummaryWidget() { } void ApptSummaryWidget::updateView() { qDeleteAll( mLabels ); mLabels.clear(); KConfig _config( "kcmapptsummaryrc" ); KConfigGroup config(&_config, "Days" ); int days = config.readEntry( "DaysToShow", 7 ); // The event print consists of the following fields: // icon:start date:days-to-go:summary:time range // where, // the icon is the typical event icon // the start date is the event start date // the days-to-go is the #days until the event starts // the summary is the event summary // the time range is the start-end time (only for non-floating events) QLabel *label = 0; int counter = 0; KIconLoader loader( "korganizer" ); QPixmap pm = loader.loadIcon( "view-calendar-day", KIconLoader::Small ); QString str; QDate dt; QDate currentDate = QDate::currentDate(); for ( dt=currentDate; dt<=currentDate.addDays( days - 1 ); dt=dt.addDays(1) ) { KCal::Event *ev; KCal::Event::List events_orig = mCalendar->events( dt, mCalendar->timeSpec() ); KCal::Event::List::ConstIterator it = events_orig.begin(); KCal::Event::List events; events.setAutoDelete( true ); KDateTime qdt; // prevent implicitely sharing while finding recurring events // replacing the QDate with the currentDate for ( ; it != events_orig.end(); ++it ) { ev = (*it)->clone(); if ( ev->recursOn( dt, mCalendar->timeSpec() ) ) { qdt = ev->dtStart(); qdt.setDate( dt ); ev->setDtStart( qdt ); } events.append( ev ); } // sort the events for this date by summary events = KCal::Calendar::sortEvents( &events, KCal::EventSortSummary, KCal::SortDirectionAscending ); // sort the events for this date by start date events = KCal::Calendar::sortEvents( &events, KCal::EventSortStartDate, KCal::SortDirectionAscending ); for ( it=events.begin(); it != events.end(); ++it ) { ev = *it; bool makeBold = false; int daysTo = -1; // ### If you change anything in the multiday logic below, make sure // you test it with: // - a multiday, all-day event currently in progress // - a multiday, all-day event in the future // - a multiday event with associated time which is in progress // - a multiday event with associated time which is in the future // Count number of days remaining in multiday event int span = 1; int dayof = 1; if ( ev->isMultiDay() ) { QDate d = ev->dtStart().date(); if ( d < currentDate ) { dayof += d.daysTo( currentDate ); span += d.daysTo( currentDate ); d = currentDate; } while ( d < ev->dtEnd().date() ) { if ( d < dt ) { dayof++; } span++; d = d.addDays( 1 ); } } QDate startOfMultiday = ev->dtStart().date(); if ( startOfMultiday < currentDate ) startOfMultiday = currentDate; bool firstDayOfMultiday = ( dt == startOfMultiday ); // If this date is part of a floating, multiday event, then we // only make a print for the first day of the event. if ( ev->isMultiDay() && ev->allDay() && ( currentDate > ev->dtStart().date() || !firstDayOfMultiday ) ) { continue; } // Icon label label = new QLabel( this ); label->setPixmap( pm ); label->setMaximumWidth( label->minimumSizeHint().width() ); mLayout->addWidget( label, counter, 0 ); mLabels.append( label ); // Start date label str = ""; QDate sD = QDate( dt.year(), dt.month(), dt.day() ); if ( ( sD.month() == currentDate.month() ) && ( sD.day() == currentDate.day() ) ) { str = i18nc( "@label the appointment is today", "Today" ); makeBold = true; } else if ( ( sD.month() == currentDate.addDays( 1 ).month() ) && ( sD.day() == currentDate.addDays( 1 ).day() ) ) { str = i18nc( "@label the appointment is tomorrow", "Tomorrow" ); } else { str = KGlobal::locale()->formatDate( sD, KLocale::FancyLongDate ); } // Print the date span for multiday, floating events, for the // first day of the event only. if ( ev->isMultiDay() && ev->allDay() && firstDayOfMultiday && span > 1 ) { str = KGlobal::locale()->formatDate( ev->dtStart().date(), KLocale::FancyLongDate ); str += " -\n " + KGlobal::locale()->formatDate( ev->dtEnd().date(), KLocale::FancyLongDate ); } label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 1 ); mLabels.append( label ); if ( makeBold ) { QFont font = label->font(); font.setBold( true ); label->setFont( font ); } // Days to go label str = ""; dateDiff( startOfMultiday, daysTo ); if ( ev->isMultiDay() && !ev->allDay() ) dateDiff( dt, daysTo ); if ( daysTo > 0 ) { str = i18np( "in 1 day", "in %1 days", daysTo ); } else { str = i18n( "now" ); } label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 2 ); mLabels.append( label ); // Summary label str = ev->richSummary(); if ( ev->isMultiDay() && !ev->allDay() ) { str.append( QString( " (%1/%2)" ).arg( dayof ).arg( span ) ); } KUrlLabel *urlLabel = new KUrlLabel( this ); urlLabel->setText( str ); urlLabel->setUrl( ev->uid() ); urlLabel->installEventFilter( this ); urlLabel->setTextFormat( Qt::RichText ); mLayout->addWidget( urlLabel, counter, 3 ); mLabels.append( urlLabel ); connect( urlLabel, SIGNAL(leftClickedUrl(const QString&)), this, SLOT(viewEvent(const QString&)) ); connect( urlLabel, SIGNAL(rightClickedUrl(const QString&)), this, SLOT(popupMenu(const QString&)) ); QString tipText( KCal::IncidenceFormatter::toolTipString( ev, true ) ); if ( !tipText.isEmpty() ) { urlLabel->setToolTip( tipText ); } // Time range label (only for non-floating events) str = ""; if ( !ev->allDay() ) { QTime sST = ev->dtStart().time(); QTime sET = ev->dtEnd().time(); if ( ev->isMultiDay() ) { if ( ev->dtStart().date() < dt ) { sST = QTime( 0, 0 ); } if ( ev->dtEnd().date() > dt ) { sET = QTime( 23, 59 ); } } str = i18nc( "Time from - to", "%1 - %2", KGlobal::locale()->formatTime( sST ), KGlobal::locale()->formatTime( sET ) ); label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 4 ); mLabels.append( label ); } counter++; } } if ( !counter ) { QLabel *noEvents = new QLabel( i18np( "No upcoming events starting within the next day", "No upcoming events starting within the next %1 days", days ), this ); noEvents->setObjectName( "nothing to see" ); noEvents->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter ); mLayout->addWidget( noEvents, 0, 2 ); mLabels.append( noEvents ); } Q_FOREACH( label, mLabels ) label->show(); } void ApptSummaryWidget::viewEvent( const QString &uid ) { mPlugin->core()->selectPlugin( "kontact_korganizerplugin" ); //ensure loaded OrgKdeKorganizerKorganizerInterface korganizer( "org.kde.korganizer", "/Korganizer", QDBusConnection::sessionBus() ); korganizer.editIncidence( uid ); } void ApptSummaryWidget::removeEvent( const QString &uid ) { mPlugin->core()->selectPlugin( "kontact_korganizerplugin" ); //ensure loaded OrgKdeKorganizerKorganizerInterface korganizer( "org.kde.korganizer", "/Korganizer", QDBusConnection::sessionBus() ); korganizer.deleteIncidence( uid, false ); } void ApptSummaryWidget::popupMenu( const QString &uid ) { KMenu popup( this ); QAction *editIt = popup.addAction( i18n( "&Edit Appointment..." ) ); QAction *delIt = popup.addAction( i18n( "&Delete Appointment" ) ); delIt->setIcon( KIconLoader::global()-> loadIcon( "edit-delete", KIconLoader::Small ) ); const QAction *selectedAction = popup.exec( QCursor::pos() ); if ( selectedAction == editIt ) { viewEvent( uid ); } else if ( selectedAction == delIt ) { removeEvent( uid ); } } bool ApptSummaryWidget::eventFilter( QObject *obj, QEvent *e ) { if ( obj->inherits( "KUrlLabel" ) ) { KUrlLabel *label = static_cast<KUrlLabel*>( obj ); if ( e->type() == QEvent::Enter ) { emit message( i18n( "Edit Event: \"%1\"", label->text() ) ); } if ( e->type() == QEvent::Leave ) { emit message( QString::null ); //krazy:exclude=nullstrassign for old broken gcc } } return Kontact::Summary::eventFilter( obj, e ); } void ApptSummaryWidget::dateDiff( const QDate &date, int &days ) { QDate currentDate; QDate eventDate; if ( QDate::isLeapYear( date.year() ) && date.month() == 2 && date.day() == 29 ) { currentDate = QDate( date.year(), QDate::currentDate().month(), QDate::currentDate().day() ); if ( !QDate::isLeapYear( QDate::currentDate().year() ) ) { eventDate = QDate( date.year(), date.month(), 28 ); // celebrate one day earlier ;) } else { eventDate = QDate( date.year(), date.month(), date.day() ); } } else { currentDate = QDate( QDate::currentDate().year(), QDate::currentDate().month(), QDate::currentDate().day() ); eventDate = QDate( QDate::currentDate().year(), date.month(), date.day() ); } int offset = currentDate.daysTo( eventDate ); if ( offset < 0 ) { days = 365 + offset; if ( QDate::isLeapYear( QDate::currentDate().year() ) ) days++; } else { days = offset; } } QStringList ApptSummaryWidget::configModules() const { return QStringList( "kcmapptsummary.desktop" ); } #include "apptsummarywidget.moc" <|endoftext|>
<commit_before>/* This file is part of Kontact. Copyright (c) 2003 Tobias Koenig <tokoe@kde.org> Copyright (c) 2005-2006,2008 Allen Winter <winter@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "apptsummarywidget.h" #include "korganizerplugin.h" #include "korganizerinterface.h" #include <korganizer/stdcalendar.h> #include <kontactinterfaces/core.h> #include <kcal/incidenceformatter.h> #include <kcal/resourcecalendar.h> #include <kconfiggroup.h> #include <kiconloader.h> #include <klocale.h> #include <kmenu.h> #include <kurllabel.h> #include <QDateTime> #include <QGridLayout> #include <QLabel> #include <QVBoxLayout> ApptSummaryWidget::ApptSummaryWidget( KOrganizerPlugin *plugin, QWidget *parent ) : Kontact::Summary( parent ), mPlugin( plugin ), mCalendar( 0 ) { QVBoxLayout *mainLayout = new QVBoxLayout( this ); mainLayout->setSpacing( 3 ); mainLayout->setMargin( 3 ); QWidget *header = createHeader( this, "view-calendar-upcoming-events", i18n( "Upcoming Events" ) ); mainLayout->addWidget( header ); mLayout = new QGridLayout(); mainLayout->addItem( mLayout ); mLayout->setSpacing( 3 ); mLayout->setRowStretch( 6, 1 ); mCalendar = KOrg::StdCalendar::self(); mCalendar->load(); connect( mCalendar, SIGNAL(calendarChanged()), SLOT(updateView()) ); connect( mPlugin->core(), SIGNAL(dayChanged(const QDate&)), SLOT(updateView()) ); updateView(); } ApptSummaryWidget::~ApptSummaryWidget() { } void ApptSummaryWidget::updateView() { qDeleteAll( mLabels ); mLabels.clear(); KConfig _config( "kcmapptsummaryrc" ); KConfigGroup config(&_config, "Days" ); int days = config.readEntry( "DaysToShow", 7 ); // The event print consists of the following fields: // icon:start date:days-to-go:summary:time range // where, // the icon is the typical event icon // the start date is the event start date // the days-to-go is the #days until the event starts // the summary is the event summary // the time range is the start-end time (only for non-floating events) // No reason to show the date year QString savefmt = KGlobal::locale()->dateFormat(); KGlobal::locale()->setDateFormat( KGlobal::locale()-> dateFormat().replace( 'Y', ' ' ) ); QLabel *label = 0; int counter = 0; KIconLoader loader( "korganizer" ); QPixmap pm = loader.loadIcon( "view-calendar-day", KIconLoader::Small ); QString str; QDate dt; QDate currentDate = QDate::currentDate(); for ( dt=currentDate; dt<=currentDate.addDays( days - 1 ); dt=dt.addDays(1) ) { KCal::Event *ev; KCal::Event::List events_orig = mCalendar->events( dt, mCalendar->timeSpec() ); KCal::Event::List::ConstIterator it = events_orig.begin(); KCal::Event::List events; events.setAutoDelete( true ); KDateTime qdt; // prevent implicitely sharing while finding recurring events // replacing the QDate with the currentDate for ( ; it != events_orig.end(); ++it ) { ev = (*it)->clone(); if ( ev->recursOn( dt, mCalendar->timeSpec() ) ) { qdt = ev->dtStart(); qdt.setDate( dt ); ev->setDtStart( qdt ); } events.append( ev ); } // sort the events for this date by summary events = KCal::Calendar::sortEvents( &events, KCal::EventSortSummary, KCal::SortDirectionAscending ); // sort the events for this date by start date events = KCal::Calendar::sortEvents( &events, KCal::EventSortStartDate, KCal::SortDirectionAscending ); for ( it=events.begin(); it != events.end(); ++it ) { ev = *it; bool makeBold = false; int daysTo = -1; // Count number of days remaining in multiday event int span = 1; int dayof = 1; if ( ev->isMultiDay() ) { QDate d = ev->dtStart().date(); if ( d < currentDate ) { d = currentDate; } while ( d < ev->dtEnd().date() ) { if ( d < dt ) { dayof++; } span++; d=d.addDays( 1 ); } } // If this date is part of a floating, multiday event, then we // only make a print for the first day of the event. if ( ev->isMultiDay() && ev->allDay() && dayof != 1 ) { continue; } // Icon label label = new QLabel( this ); label->setPixmap( pm ); label->setMaximumWidth( label->minimumSizeHint().width() ); mLayout->addWidget( label, counter, 0 ); mLabels.append( label ); // Start date label str = ""; QDate sD = QDate( dt.year(), dt.month(), dt.day() ); if ( ( sD.month() == currentDate.month() ) && ( sD.day() == currentDate.day() ) ) { str = i18nc( "@label the appointment is today", "Today" ); makeBold = true; } else if ( ( sD.month() == currentDate.addDays( 1 ).month() ) && ( sD.day() == currentDate.addDays( 1 ).day() ) ) { str = i18nc( "@label the appointment is tomorrow", "Tomorrow" ); } else { str = KGlobal::locale()->formatDate( sD ); } // Print the date span for multiday, floating events, for the // first day of the event only. if ( ev->isMultiDay() && ev->allDay() && dayof == 1 && span > 1 ) { str = KGlobal::locale()->formatDate( ev->dtStart().date() ); str += " -\n " + KGlobal::locale()->formatDate( sD.addDays( span-1 ) ); } label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 1 ); mLabels.append( label ); if ( makeBold ) { QFont font = label->font(); font.setBold( true ); label->setFont( font ); } // Days togo label str = ""; dateDiff( ev->dtStart().date(), daysTo ); if ( daysTo > 0 ) { str = i18np( "in 1 day", "in %1 days", daysTo ); } else { str = i18n( "now" ); } label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 2 ); mLabels.append( label ); // Summary label str = ev->summary(); if ( ev->isMultiDay() && !ev->allDay() ) { str.append( QString( " (%1/%2)" ).arg( dayof ).arg( span ) ); } KUrlLabel *urlLabel = new KUrlLabel( this ); urlLabel->setText( str ); urlLabel->setUrl( ev->uid() ); urlLabel->installEventFilter( this ); urlLabel->setTextFormat( Qt::RichText ); mLayout->addWidget( urlLabel, counter, 3 ); mLabels.append( urlLabel ); connect( urlLabel, SIGNAL(leftClickedUrl(const QString&)), this, SLOT(viewEvent(const QString&)) ); connect( urlLabel, SIGNAL(rightClickedUrl(const QString&)), this, SLOT(popupMenu(const QString&)) ); QString tipText( KCal::IncidenceFormatter::toolTipString( ev, true ) ); if ( !tipText.isEmpty() ) { urlLabel->setToolTip( tipText ); } // Time range label (only for non-floating events) str = ""; if ( !ev->allDay() ) { QTime sST = ev->dtStart().time(); QTime sET = ev->dtEnd().time(); if ( ev->isMultiDay() ) { if ( ev->dtStart().date() < dt ) { sST = QTime( 0, 0 ); } if ( ev->dtEnd().date() > dt ) { sET = QTime( 23, 59 ); } } str = i18nc( "Time from - to", "%1 - %2", KGlobal::locale()->formatTime( sST ), KGlobal::locale()->formatTime( sET ) ); label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 4 ); mLabels.append( label ); } counter++; } } if ( !counter ) { QLabel *noEvents = new QLabel( i18np( "No upcoming events starting within the next day", "No upcoming events starting within the next %1 days", days ), this ); noEvents->setObjectName( "nothing to see" ); noEvents->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter ); mLayout->addWidget( noEvents, 0, 2 ); mLabels.append( noEvents ); } Q_FOREACH( label, mLabels ) label->show(); KGlobal::locale()->setDateFormat( savefmt ); } void ApptSummaryWidget::viewEvent( const QString &uid ) { mPlugin->core()->selectPlugin( "kontact_korganizerplugin" ); //ensure loaded OrgKdeKorganizerKorganizerInterface korganizer( "org.kde.korganizer", "/Korganizer", QDBusConnection::sessionBus() ); korganizer.editIncidence( uid ); } void ApptSummaryWidget::removeEvent( const QString &uid ) { mPlugin->core()->selectPlugin( "kontact_korganizerplugin" ); //ensure loaded OrgKdeKorganizerKorganizerInterface korganizer( "org.kde.korganizer", "/Korganizer", QDBusConnection::sessionBus() ); korganizer.deleteIncidence( uid, false ); } void ApptSummaryWidget::popupMenu( const QString &uid ) { KMenu popup( this ); QAction *editIt = popup.addAction( i18n( "&Edit Appointment..." ) ); QAction *delIt = popup.addAction( i18n( "&Delete Appointment" ) ); delIt->setIcon( KIconLoader::global()-> loadIcon( "edit-delete", KIconLoader::Small ) ); const QAction *selectedAction = popup.exec( QCursor::pos() ); if ( selectedAction == editIt ) { viewEvent( uid ); } else if ( selectedAction == delIt ) { removeEvent( uid ); } } bool ApptSummaryWidget::eventFilter( QObject *obj, QEvent *e ) { if ( obj->inherits( "KUrlLabel" ) ) { KUrlLabel *label = static_cast<KUrlLabel*>( obj ); if ( e->type() == QEvent::Enter ) { emit message( i18n( "Edit Event: \"%1\"", label->text() ) ); } if ( e->type() == QEvent::Leave ) { emit message( QString::null ); //krazy:exclude=nullstrassign for old broken gcc } } return Kontact::Summary::eventFilter( obj, e ); } void ApptSummaryWidget::dateDiff( const QDate &date, int &days ) { QDate currentDate; QDate eventDate; if ( QDate::isLeapYear( date.year() ) && date.month() == 2 && date.day() == 29 ) { currentDate = QDate( date.year(), QDate::currentDate().month(), QDate::currentDate().day() ); if ( !QDate::isLeapYear( QDate::currentDate().year() ) ) { eventDate = QDate( date.year(), date.month(), 28 ); // celebrate one day earlier ;) } else { eventDate = QDate( date.year(), date.month(), date.day() ); } } else { currentDate = QDate( QDate::currentDate().year(), QDate::currentDate().month(), QDate::currentDate().day() ); eventDate = QDate( QDate::currentDate().year(), date.month(), date.day() ); } int offset = currentDate.daysTo( eventDate ); if ( offset < 0 ) { days = 365 + offset; } else { days = offset; } } QStringList ApptSummaryWidget::configModules() const { return QStringList( "kcmapptsummary.desktop" ); } #include "apptsummarywidget.moc" <commit_msg>escape <,>,& in summaries, if necessary<commit_after>/* This file is part of Kontact. Copyright (c) 2003 Tobias Koenig <tokoe@kde.org> Copyright (c) 2005-2006,2008 Allen Winter <winter@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "apptsummarywidget.h" #include "korganizerplugin.h" #include "korganizerinterface.h" #include <korganizer/stdcalendar.h> #include <kontactinterfaces/core.h> #include <kcal/incidenceformatter.h> #include <kcal/resourcecalendar.h> #include <kconfiggroup.h> #include <kiconloader.h> #include <klocale.h> #include <kmenu.h> #include <kurllabel.h> #include <QDateTime> #include <QGridLayout> #include <QLabel> #include <QVBoxLayout> #include <QTextDocument> ApptSummaryWidget::ApptSummaryWidget( KOrganizerPlugin *plugin, QWidget *parent ) : Kontact::Summary( parent ), mPlugin( plugin ), mCalendar( 0 ) { QVBoxLayout *mainLayout = new QVBoxLayout( this ); mainLayout->setSpacing( 3 ); mainLayout->setMargin( 3 ); QWidget *header = createHeader( this, "view-calendar-upcoming-events", i18n( "Upcoming Events" ) ); mainLayout->addWidget( header ); mLayout = new QGridLayout(); mainLayout->addItem( mLayout ); mLayout->setSpacing( 3 ); mLayout->setRowStretch( 6, 1 ); mCalendar = KOrg::StdCalendar::self(); mCalendar->load(); connect( mCalendar, SIGNAL(calendarChanged()), SLOT(updateView()) ); connect( mPlugin->core(), SIGNAL(dayChanged(const QDate&)), SLOT(updateView()) ); updateView(); } ApptSummaryWidget::~ApptSummaryWidget() { } void ApptSummaryWidget::updateView() { qDeleteAll( mLabels ); mLabels.clear(); KConfig _config( "kcmapptsummaryrc" ); KConfigGroup config(&_config, "Days" ); int days = config.readEntry( "DaysToShow", 7 ); // The event print consists of the following fields: // icon:start date:days-to-go:summary:time range // where, // the icon is the typical event icon // the start date is the event start date // the days-to-go is the #days until the event starts // the summary is the event summary // the time range is the start-end time (only for non-floating events) // No reason to show the date year QString savefmt = KGlobal::locale()->dateFormat(); KGlobal::locale()->setDateFormat( KGlobal::locale()-> dateFormat().replace( 'Y', ' ' ) ); QLabel *label = 0; int counter = 0; KIconLoader loader( "korganizer" ); QPixmap pm = loader.loadIcon( "view-calendar-day", KIconLoader::Small ); QString str; QDate dt; QDate currentDate = QDate::currentDate(); for ( dt=currentDate; dt<=currentDate.addDays( days - 1 ); dt=dt.addDays(1) ) { KCal::Event *ev; KCal::Event::List events_orig = mCalendar->events( dt, mCalendar->timeSpec() ); KCal::Event::List::ConstIterator it = events_orig.begin(); KCal::Event::List events; events.setAutoDelete( true ); KDateTime qdt; // prevent implicitely sharing while finding recurring events // replacing the QDate with the currentDate for ( ; it != events_orig.end(); ++it ) { ev = (*it)->clone(); if ( ev->recursOn( dt, mCalendar->timeSpec() ) ) { qdt = ev->dtStart(); qdt.setDate( dt ); ev->setDtStart( qdt ); } events.append( ev ); } // sort the events for this date by summary events = KCal::Calendar::sortEvents( &events, KCal::EventSortSummary, KCal::SortDirectionAscending ); // sort the events for this date by start date events = KCal::Calendar::sortEvents( &events, KCal::EventSortStartDate, KCal::SortDirectionAscending ); for ( it=events.begin(); it != events.end(); ++it ) { ev = *it; bool makeBold = false; int daysTo = -1; // Count number of days remaining in multiday event int span = 1; int dayof = 1; if ( ev->isMultiDay() ) { QDate d = ev->dtStart().date(); if ( d < currentDate ) { d = currentDate; } while ( d < ev->dtEnd().date() ) { if ( d < dt ) { dayof++; } span++; d=d.addDays( 1 ); } } // If this date is part of a floating, multiday event, then we // only make a print for the first day of the event. if ( ev->isMultiDay() && ev->allDay() && dayof != 1 ) { continue; } // Icon label label = new QLabel( this ); label->setPixmap( pm ); label->setMaximumWidth( label->minimumSizeHint().width() ); mLayout->addWidget( label, counter, 0 ); mLabels.append( label ); // Start date label str = ""; QDate sD = QDate( dt.year(), dt.month(), dt.day() ); if ( ( sD.month() == currentDate.month() ) && ( sD.day() == currentDate.day() ) ) { str = i18nc( "@label the appointment is today", "Today" ); makeBold = true; } else if ( ( sD.month() == currentDate.addDays( 1 ).month() ) && ( sD.day() == currentDate.addDays( 1 ).day() ) ) { str = i18nc( "@label the appointment is tomorrow", "Tomorrow" ); } else { str = KGlobal::locale()->formatDate( sD ); } // Print the date span for multiday, floating events, for the // first day of the event only. if ( ev->isMultiDay() && ev->allDay() && dayof == 1 && span > 1 ) { str = KGlobal::locale()->formatDate( ev->dtStart().date() ); str += " -\n " + KGlobal::locale()->formatDate( sD.addDays( span-1 ) ); } label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 1 ); mLabels.append( label ); if ( makeBold ) { QFont font = label->font(); font.setBold( true ); label->setFont( font ); } // Days togo label str = ""; dateDiff( ev->dtStart().date(), daysTo ); if ( daysTo > 0 ) { str = i18np( "in 1 day", "in %1 days", daysTo ); } else { str = i18n( "now" ); } label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 2 ); mLabels.append( label ); // Summary label str = ev->summary(); if ( ev->isMultiDay() && !ev->allDay() ) { str.append( QString( " (%1/%2)" ).arg( dayof ).arg( span ) ); } if ( !Qt::mightBeRichText( str ) ) { str = Qt::escape( str ); } KUrlLabel *urlLabel = new KUrlLabel( this ); urlLabel->setText( str ); urlLabel->setUrl( ev->uid() ); urlLabel->installEventFilter( this ); urlLabel->setTextFormat( Qt::RichText ); mLayout->addWidget( urlLabel, counter, 3 ); mLabels.append( urlLabel ); connect( urlLabel, SIGNAL(leftClickedUrl(const QString&)), this, SLOT(viewEvent(const QString&)) ); connect( urlLabel, SIGNAL(rightClickedUrl(const QString&)), this, SLOT(popupMenu(const QString&)) ); QString tipText( KCal::IncidenceFormatter::toolTipString( ev, true ) ); if ( !tipText.isEmpty() ) { urlLabel->setToolTip( tipText ); } // Time range label (only for non-floating events) str = ""; if ( !ev->allDay() ) { QTime sST = ev->dtStart().time(); QTime sET = ev->dtEnd().time(); if ( ev->isMultiDay() ) { if ( ev->dtStart().date() < dt ) { sST = QTime( 0, 0 ); } if ( ev->dtEnd().date() > dt ) { sET = QTime( 23, 59 ); } } str = i18nc( "Time from - to", "%1 - %2", KGlobal::locale()->formatTime( sST ), KGlobal::locale()->formatTime( sET ) ); label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 4 ); mLabels.append( label ); } counter++; } } if ( !counter ) { QLabel *noEvents = new QLabel( i18np( "No upcoming events starting within the next day", "No upcoming events starting within the next %1 days", days ), this ); noEvents->setObjectName( "nothing to see" ); noEvents->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter ); mLayout->addWidget( noEvents, 0, 2 ); mLabels.append( noEvents ); } Q_FOREACH( label, mLabels ) label->show(); KGlobal::locale()->setDateFormat( savefmt ); } void ApptSummaryWidget::viewEvent( const QString &uid ) { mPlugin->core()->selectPlugin( "kontact_korganizerplugin" ); //ensure loaded OrgKdeKorganizerKorganizerInterface korganizer( "org.kde.korganizer", "/Korganizer", QDBusConnection::sessionBus() ); korganizer.editIncidence( uid ); } void ApptSummaryWidget::removeEvent( const QString &uid ) { mPlugin->core()->selectPlugin( "kontact_korganizerplugin" ); //ensure loaded OrgKdeKorganizerKorganizerInterface korganizer( "org.kde.korganizer", "/Korganizer", QDBusConnection::sessionBus() ); korganizer.deleteIncidence( uid, false ); } void ApptSummaryWidget::popupMenu( const QString &uid ) { KMenu popup( this ); QAction *editIt = popup.addAction( i18n( "&Edit Appointment..." ) ); QAction *delIt = popup.addAction( i18n( "&Delete Appointment" ) ); delIt->setIcon( KIconLoader::global()-> loadIcon( "edit-delete", KIconLoader::Small ) ); const QAction *selectedAction = popup.exec( QCursor::pos() ); if ( selectedAction == editIt ) { viewEvent( uid ); } else if ( selectedAction == delIt ) { removeEvent( uid ); } } bool ApptSummaryWidget::eventFilter( QObject *obj, QEvent *e ) { if ( obj->inherits( "KUrlLabel" ) ) { KUrlLabel *label = static_cast<KUrlLabel*>( obj ); if ( e->type() == QEvent::Enter ) { emit message( i18n( "Edit Event: \"%1\"", label->text() ) ); } if ( e->type() == QEvent::Leave ) { emit message( QString::null ); //krazy:exclude=nullstrassign for old broken gcc } } return Kontact::Summary::eventFilter( obj, e ); } void ApptSummaryWidget::dateDiff( const QDate &date, int &days ) { QDate currentDate; QDate eventDate; if ( QDate::isLeapYear( date.year() ) && date.month() == 2 && date.day() == 29 ) { currentDate = QDate( date.year(), QDate::currentDate().month(), QDate::currentDate().day() ); if ( !QDate::isLeapYear( QDate::currentDate().year() ) ) { eventDate = QDate( date.year(), date.month(), 28 ); // celebrate one day earlier ;) } else { eventDate = QDate( date.year(), date.month(), date.day() ); } } else { currentDate = QDate( QDate::currentDate().year(), QDate::currentDate().month(), QDate::currentDate().day() ); eventDate = QDate( QDate::currentDate().year(), date.month(), date.day() ); } int offset = currentDate.daysTo( eventDate ); if ( offset < 0 ) { days = 365 + offset; } else { days = offset; } } QStringList ApptSummaryWidget::configModules() const { return QStringList( "kcmapptsummary.desktop" ); } #include "apptsummarywidget.moc" <|endoftext|>
<commit_before>#include <iostream> #include "sbe/list/list.hpp" struct FooItem: public sbe::ListItem<FooItem> { size_t index; inline FooItem( void ) : index (0) {} inline ~FooItem( void ) {} explicit inline FooItem( size_t in_index ) : index (in_index) {} FooItem( FooItem const & item ) : sbe::ListItem<FooItem>(), index (item.index) {} FooItem& operator=( FooItem const & item ) { this->index = item.index; return *this; } }; bool operator==( FooItem const & item1, FooItem const & item2 ) { return item1.index == item2.index; } typedef sbe::List<FooItem> FooList; //---------------------------------------------------------------------------// static void test_listitem( void ) { FooItem nodes[10]; FooItem* root = &nodes[0]; for (size_t i = 0; i < sizeof(nodes)/sizeof(nodes[0]); ++i) { nodes[i].index = i; } SBE_ASSERT(root->find( FooItem( nodes[0] )) == &nodes[0]); SBE_ASSERT(root->find( FooItem( 1 )) == NULL); SBE_ASSERT(root->find( FooItem( 2 )) == NULL); for (size_t i = 1; i < sizeof(nodes)/sizeof(nodes[0]); ++i) { root->pushBack( &nodes[i] ); SBE_ASSERT(root->find( FooItem( i )) == &nodes[i]); SBE_ASSERT(nodes[i-1].next() == &nodes[i]); SBE_ASSERT(nodes[i].previous() == &nodes[i-1]); SBE_ASSERT(const_cast<FooItem const *>(&nodes[i-1])->next() == &nodes[i]); SBE_ASSERT(const_cast<FooItem const *>(&nodes[i])->previous() == &nodes[i-1]); } SBE_ASSERT( root->test() ); //-------------------------------------------------------// FooItem nodes2[5]; FooItem* root2 = &nodes2[0]; SBE_ASSERT(root->find( FooItem( 0 )) == root); for (size_t i = 1; i < sizeof(nodes2)/sizeof(nodes2[0]); ++i) { root2->pushFront( &nodes2[i] ); } SBE_ASSERT( root2->test() ); root->pushBack( root2 ); SBE_ASSERT( root->test() ); //-------------------------------------------------------// FooItem nodes3[5]; FooItem* root3 = &nodes3[0]; for (size_t i = 1; i < sizeof(nodes3)/sizeof(nodes3[0]); ++i) { root3->pushBack( &nodes3[i] ); } SBE_ASSERT( root3->test() ); root->pushFront( root3 ); SBE_ASSERT( root->test() ); //-------------------------------------------------------// for (size_t i = 1; i < sizeof(nodes2)/sizeof(nodes2[0]); ++i) { nodes2[i].pop(); SBE_ASSERT( nodes2[i].single() ); nodes2[i].pop(); SBE_ASSERT( nodes2[i].single() ); SBE_ASSERT( nodes2[i].test() ); } SBE_ASSERT( root->test() ); std::cout << "Test: 'test_listitem' - " << "PASSED" << std::endl; } static void test_list( void ) { FooItem nodes[10]; FooList head; for (size_t i = 0; i < sizeof(nodes)/sizeof(nodes[0]); ++i) { nodes[i].index = i; } SBE_ASSERT( head.find( FooItem(0) ) == NULL ); for (size_t i = 0; i < sizeof(nodes)/sizeof(nodes[0]); ++i) { head.pushBack( &nodes[i] ); SBE_ASSERT( head.find( FooItem(i) ) == &nodes[i] ); SBE_ASSERT( head.back() == &nodes[i] ); SBE_ASSERT( head.front() == nodes[i].next() ); SBE_ASSERT( head.front() == &nodes[0] ); } for (size_t i = 0; i < sizeof(nodes)/sizeof(nodes[0]); ++i) { FooItem* next = head.front()->next(); if (next == head.front()) { next = NULL; } FooItem* item = head.front(); SBE_ASSERT( item == head.popFront() ); SBE_ASSERT( head.front() == next ); } SBE_ASSERT( head.front() == NULL ); for (size_t i = 0; i < sizeof(nodes)/sizeof(nodes[0]); ++i) { FooItem* item = head.front(); head.pushFront( &nodes[i] ); SBE_ASSERT( (item == NULL) || (head.front()->next() == item) ); SBE_ASSERT( (item == NULL) || (item->previous() == head.front()) ); SBE_ASSERT( head.front() == &nodes[i] ); } for (size_t i = 0; i < sizeof(nodes)/sizeof(nodes[0]); ++i) { FooItem* back = head.back(); SBE_ASSERT( back == head.popBack() ); } SBE_ASSERT( head.front() == NULL ); SBE_ASSERT( head.back() == NULL ); SBE_ASSERT( head.popFront() == NULL ); SBE_ASSERT( head.popBack() == NULL ); std::cout << "Test: 'test_list' - " << "PASSED" << std::endl; } int main( void ) { test_listitem(); test_list(); return 0; } <commit_msg>Refactored list implementation<commit_after>#include <iostream> #include "sbe/list/list.hpp" struct FooItem: public sbe::ListItem { size_t index; inline FooItem( void ) : index (0) {} inline ~FooItem( void ) {} explicit inline FooItem( size_t in_index ) : index (in_index) {} FooItem( FooItem const & item ) : sbe::ListItem(), index (item.index) {} FooItem& operator=( FooItem const & item ) { this->index = item.index; return *this; } }; bool operator==( FooItem const & item1, FooItem const & item2 ) { return item1.index == item2.index; } typedef sbe::List<FooItem> FooList; //---------------------------------------------------------------------------// //~ static void test_listitem( void ) //~ { //~ FooItem nodes[10]; //~ FooItem* root = &nodes[0]; //~ for (size_t i = 0; i < sizeof(nodes)/sizeof(nodes[0]); ++i) //~ { //~ nodes[i].index = i; //~ } //~ SBE_ASSERT(root->find( FooItem( nodes[0] )) == &nodes[0]); //~ SBE_ASSERT(root->find( FooItem( 1 )) == NULL); //~ SBE_ASSERT(root->find( FooItem( 2 )) == NULL); //~ for (size_t i = 1; i < sizeof(nodes)/sizeof(nodes[0]); ++i) //~ { //~ root->pushBack( &nodes[i] ); //~ SBE_ASSERT(root->find( FooItem( i )) == &nodes[i]); //~ SBE_ASSERT(nodes[i-1].next() == &nodes[i]); //~ SBE_ASSERT(nodes[i].previous() == &nodes[i-1]); //~ SBE_ASSERT(const_cast<FooItem const *>(&nodes[i-1])->next() == &nodes[i]); //~ SBE_ASSERT(const_cast<FooItem const *>(&nodes[i])->previous() == &nodes[i-1]); //~ } //~ SBE_ASSERT( root->test() ); //~ //-------------------------------------------------------// //~ FooItem nodes2[5]; //~ FooItem* root2 = &nodes2[0]; //~ SBE_ASSERT(root->find( FooItem( 0 )) == root); //~ for (size_t i = 1; i < sizeof(nodes2)/sizeof(nodes2[0]); ++i) //~ { //~ root2->pushFront( &nodes2[i] ); //~ } //~ SBE_ASSERT( root2->test() ); //~ root->pushBack( root2 ); //~ SBE_ASSERT( root->test() ); //~ //-------------------------------------------------------// //~ FooItem nodes3[5]; //~ FooItem* root3 = &nodes3[0]; //~ for (size_t i = 1; i < sizeof(nodes3)/sizeof(nodes3[0]); ++i) //~ { //~ root3->pushBack( &nodes3[i] ); //~ } //~ SBE_ASSERT( root3->test() ); //~ root->pushFront( root3 ); //~ SBE_ASSERT( root->test() ); //~ //-------------------------------------------------------// //~ for (size_t i = 1; i < sizeof(nodes2)/sizeof(nodes2[0]); ++i) //~ { //~ nodes2[i].pop(); //~ SBE_ASSERT( nodes2[i].single() ); //~ nodes2[i].pop(); //~ SBE_ASSERT( nodes2[i].single() ); //~ SBE_ASSERT( nodes2[i].test() ); //~ } //~ SBE_ASSERT( root->test() ); //~ std::cout << "Test: 'test_listitem' - " << "PASSED" << std::endl; //~ } static void test_list( void ) { FooItem nodes[10]; FooList head; for (size_t i = 0; i < sizeof(nodes)/sizeof(nodes[0]); ++i) { nodes[i].index = i; } SBE_ASSERT( head.find( FooItem(0) ) == NULL ); for (size_t i = 0; i < sizeof(nodes)/sizeof(nodes[0]); ++i) { head.pushBack( &nodes[i] ); SBE_ASSERT( head.find( FooItem(i) ) == &nodes[i] ); SBE_ASSERT( head.back() == &nodes[i] ); //~ SBE_ASSERT( head.front() == nodes[i].next() ); SBE_ASSERT( head.front() == &nodes[0] ); } for (size_t i = 0; i < sizeof(nodes)/sizeof(nodes[0]); ++i) { //~ FooItem* next = head.front()->next(); //~ if (next == head.front()) //~ { //~ next = NULL; //~ } FooItem* item = head.front(); SBE_ASSERT( item == head.popFront() ); //~ SBE_ASSERT( head.front() == next ); } SBE_ASSERT( head.front() == NULL ); for (size_t i = 0; i < sizeof(nodes)/sizeof(nodes[0]); ++i) { //~ FooItem* item = head.front(); head.pushFront( &nodes[i] ); //~ SBE_ASSERT( (item == NULL) || (head.front()->next() == item) ); //~ SBE_ASSERT( (item == NULL) || (item->previous() == head.front()) ); SBE_ASSERT( head.front() == &nodes[i] ); } for (size_t i = 0; i < sizeof(nodes)/sizeof(nodes[0]); ++i) { FooItem* back = head.back(); SBE_ASSERT( back == head.popBack() ); } SBE_ASSERT( head.front() == NULL ); SBE_ASSERT( head.back() == NULL ); SBE_ASSERT( head.popFront() == NULL ); SBE_ASSERT( head.popBack() == NULL ); std::cout << "Test: 'test_list' - " << "PASSED" << std::endl; } int main( void ) { //~ test_listitem(); test_list(); return 0; } <|endoftext|>
<commit_before>/* Copyright (c) 2006 Volker Krause <vkrause@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "messagesearchprovider.h" #include <libakonadi/itemfetchjob.h> #include <libakonadi/job.h> #include <libakonadi/session.h> #include <libakonadi/monitor.h> #include <kmime/kmime_message.h> #include <boost/shared_ptr.hpp> #include <kcomponentdata.h> #include <nepomuk/resource.h> #include <nepomuk/variant.h> #include <kurl.h> #include <QtCore/QCoreApplication> using namespace Akonadi; typedef boost::shared_ptr<KMime::Message> MessagePtr; Akonadi::MessageSearchProvider::MessageSearchProvider( const QString &id ) : SearchProviderBase( id ) { Monitor* monitor = new Monitor( this ); monitor->addFetchPart( Item::PartAll ); monitor->monitorMimeType( "message/rfc822" ); monitor->monitorMimeType( "message/news" ); connect( monitor, SIGNAL(itemAdded(Akonadi::Item,Akonadi::Collection)), SLOT(itemChanged(Akonadi::Item)) ); connect( monitor, SIGNAL(itemChanged(const Akonadi::Item&, const QStringList&)), SLOT(itemChanged(const Akonadi::Item&)) ); connect( monitor, SIGNAL(itemRemoved(const Akonadi::DataReference&)), SLOT(itemRemoved(const Akonadi::DataReference&)) ); mSession = new Session( id.toLatin1(), this ); monitor->ignoreSession( mSession ); } QStringList Akonadi::MessageSearchProvider::supportedMimeTypes() const { QStringList mimeTypes; mimeTypes << QString::fromLatin1( "message/rfc822" ) << QString::fromLatin1( "message/news" ); return mimeTypes; } void MessageSearchProvider::itemRemoved(const Akonadi::DataReference & ref) { Nepomuk::Resource r( Item( ref ).url().url() ); r.remove(); } void MessageSearchProvider::itemChanged(const Akonadi::Item & item) { if ( !item.hasPayload<MessagePtr>() ) return; MessagePtr msg = item.payload<MessagePtr>(); Nepomuk::Resource r( item.url().url() ); if ( msg->subject( false ) ) r.setProperty( "Subject", Nepomuk::Variant(msg->subject()->asUnicodeString()) ); if ( msg->date( false ) ) r.setProperty( "Date", Nepomuk::Variant(msg->date()->dateTime().dateTime()) ); if ( msg->from( false ) ) r.setProperty( "From", Nepomuk::Variant(msg->from()->prettyAddresses()) ); if ( msg->to( false ) ) r.setProperty( "To", Nepomuk::Variant( msg->to()->prettyAddresses()) ); if ( msg->cc( false ) ) r.setProperty( "Cc", Nepomuk::Variant(msg->cc()->prettyAddresses()) ); if ( msg->bcc( false ) ) r.setProperty( "Bcc", Nepomuk::Variant(msg->bcc()->prettyAddresses()) ); if ( msg->messageID( false ) ) r.setProperty( "Message-Id", Nepomuk::Variant(msg->messageID()->asUnicodeString()) ); } int main( int argc, char **argv ) { QCoreApplication app( argc, argv ); KComponentData kcd( "nepomukfeeder" ); Akonadi::SearchProviderBase::init<Akonadi::MessageSearchProvider>( argc, argv, QLatin1String("akonadi_message_searchprovider") ); return app.exec(); } #include "messagesearchprovider.moc" <commit_msg>Also add References and In-Reply-To to Nepomuk<commit_after>/* Copyright (c) 2006 Volker Krause <vkrause@kde.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "messagesearchprovider.h" #include <libakonadi/itemfetchjob.h> #include <libakonadi/job.h> #include <libakonadi/session.h> #include <libakonadi/monitor.h> #include <kmime/kmime_message.h> #include <boost/shared_ptr.hpp> #include <kcomponentdata.h> #include <nepomuk/resource.h> #include <nepomuk/variant.h> #include <kurl.h> #include <QtCore/QCoreApplication> using namespace Akonadi; typedef boost::shared_ptr<KMime::Message> MessagePtr; Akonadi::MessageSearchProvider::MessageSearchProvider( const QString &id ) : SearchProviderBase( id ) { Monitor* monitor = new Monitor( this ); monitor->addFetchPart( Item::PartAll ); monitor->monitorMimeType( "message/rfc822" ); monitor->monitorMimeType( "message/news" ); connect( monitor, SIGNAL(itemAdded(Akonadi::Item,Akonadi::Collection)), SLOT(itemChanged(Akonadi::Item)) ); connect( monitor, SIGNAL(itemChanged(const Akonadi::Item&, const QStringList&)), SLOT(itemChanged(const Akonadi::Item&)) ); connect( monitor, SIGNAL(itemRemoved(const Akonadi::DataReference&)), SLOT(itemRemoved(const Akonadi::DataReference&)) ); mSession = new Session( id.toLatin1(), this ); monitor->ignoreSession( mSession ); } QStringList Akonadi::MessageSearchProvider::supportedMimeTypes() const { QStringList mimeTypes; mimeTypes << QString::fromLatin1( "message/rfc822" ) << QString::fromLatin1( "message/news" ); return mimeTypes; } void MessageSearchProvider::itemRemoved(const Akonadi::DataReference & ref) { Nepomuk::Resource r( Item( ref ).url().url() ); r.remove(); } void MessageSearchProvider::itemChanged(const Akonadi::Item & item) { if ( !item.hasPayload<MessagePtr>() ) return; MessagePtr msg = item.payload<MessagePtr>(); Nepomuk::Resource r( item.url().url() ); if ( msg->subject( false ) ) r.setProperty( "Subject", Nepomuk::Variant(msg->subject()->asUnicodeString()) ); if ( msg->date( false ) ) r.setProperty( "Date", Nepomuk::Variant(msg->date()->dateTime().dateTime()) ); if ( msg->from( false ) ) r.setProperty( "From", Nepomuk::Variant(msg->from()->prettyAddresses()) ); if ( msg->to( false ) ) r.setProperty( "To", Nepomuk::Variant( msg->to()->prettyAddresses()) ); if ( msg->cc( false ) ) r.setProperty( "Cc", Nepomuk::Variant(msg->cc()->prettyAddresses()) ); if ( msg->bcc( false ) ) r.setProperty( "Bcc", Nepomuk::Variant(msg->bcc()->prettyAddresses()) ); if ( msg->messageID( false ) ) r.setProperty( "Message-Id", Nepomuk::Variant(msg->messageID()->asUnicodeString()) ); if ( msg->references( false ) ) r.setProperty( "References", Nepomuk::Variant(msg->references()->asUnicodeString() ); if ( msg->inReplyTo( false ) ) r.setProperty( "In-Reply-to", Nepomuk::Variant(msg->inReplyTo()->asUnicodeString() ); } int main( int argc, char **argv ) { QCoreApplication app( argc, argv ); KComponentData kcd( "nepomukfeeder" ); Akonadi::SearchProviderBase::init<Akonadi::MessageSearchProvider>( argc, argv, QLatin1String("akonadi_message_searchprovider") ); return app.exec(); } #include "messagesearchprovider.moc" <|endoftext|>
<commit_before>#include "../Flare.h" #include "FlareSectorInterface.h" #include "FlareSimulatedSector.h" #include "../Spacecrafts/FlareSpacecraftInterface.h" #include "../Economy/FlareCargoBay.h" #include "../Game/FlareGame.h" #define LOCTEXT_NAMESPACE "FlareSectorInterface" /*---------------------------------------------------- Constructor ----------------------------------------------------*/ UFlareSectorInterface::UFlareSectorInterface(const class FObjectInitializer& PCIP) : Super(PCIP) { } void UFlareSectorInterface::LoadResourcePrices() { ResourcePrices.Empty(); LastResourcePrices.Empty(); for (int PriceIndex = 0; PriceIndex < SectorData.ResourcePrices.Num(); PriceIndex++) { FFFlareResourcePrice* ResourcePrice = &SectorData.ResourcePrices[PriceIndex]; FFlareResourceDescription* Resource = Game->GetResourceCatalog()->Get(ResourcePrice->ResourceIdentifier); float Price = ResourcePrice->Price; ResourcePrices.Add(Resource, Price); FFlareFloatBuffer* Prices = &ResourcePrice->Prices; Prices->Resize(50); LastResourcePrices.Add(Resource, *Prices); } } void UFlareSectorInterface::SaveResourcePrices() { SectorData.ResourcePrices.Empty(); for(int32 ResourceIndex = 0; ResourceIndex < Game->GetResourceCatalog()->Resources.Num(); ResourceIndex++) { FFlareResourceDescription* Resource = &Game->GetResourceCatalog()->Resources[ResourceIndex]->Data; if (ResourcePrices.Contains(Resource)) { FFFlareResourcePrice Price; Price.ResourceIdentifier = Resource->Identifier; Price.Price = ResourcePrices[Resource]; if (LastResourcePrices.Contains(Resource)) { Price.Prices = LastResourcePrices[Resource]; SectorData.ResourcePrices.Add(Price); } } } } FText UFlareSectorInterface::GetSectorName() { if (SectorData.GivenName.ToString().Len()) { return SectorData.GivenName; } else if (SectorDescription->Name.ToString().Len()) { return SectorDescription->Name; } else { return FText::FromString(GetSectorCode()); } } FString UFlareSectorInterface::GetSectorCode() { // TODO cache ? return SectorOrbitParameters.CelestialBodyIdentifier.ToString() + "-" + FString::FromInt(SectorOrbitParameters.Altitude) + "-" + FString::FromInt(SectorOrbitParameters.Phase); } EFlareSectorFriendlyness::Type UFlareSectorInterface::GetSectorFriendlyness(UFlareCompany* Company) { if (!Company->HasVisitedSector(GetSimulatedSector())) { return EFlareSectorFriendlyness::NotVisited; } if (GetSimulatedSector()->GetSectorSpacecrafts().Num() == 0) { return EFlareSectorFriendlyness::Neutral; } int HostileSpacecraftCount = 0; int NeutralSpacecraftCount = 0; int FriendlySpacecraftCount = 0; for (int SpacecraftIndex = 0 ; SpacecraftIndex < GetSimulatedSector()->GetSectorSpacecrafts().Num(); SpacecraftIndex++) { UFlareCompany* OtherCompany = GetSimulatedSector()->GetSectorSpacecrafts()[SpacecraftIndex]->GetCompany(); if (OtherCompany == Company) { FriendlySpacecraftCount++; } else if (OtherCompany->GetWarState(Company) == EFlareHostility::Hostile) { HostileSpacecraftCount++; } else { NeutralSpacecraftCount++; } } if (FriendlySpacecraftCount > 0 && HostileSpacecraftCount > 0) { return EFlareSectorFriendlyness::Contested; } if (FriendlySpacecraftCount > 0) { return EFlareSectorFriendlyness::Friendly; } else if (HostileSpacecraftCount > 0) { return EFlareSectorFriendlyness::Hostile; } else { return EFlareSectorFriendlyness::Neutral; } } EFlareSectorBattleState::Type UFlareSectorInterface::GetSectorBattleState(UFlareCompany* Company) { if (GetSectorShipInterfaces().Num() == 0) { return EFlareSectorBattleState::NoBattle; } int HostileSpacecraftCount = 0; int DangerousHostileSpacecraftCount = 0; int FriendlySpacecraftCount = 0; int DangerousFriendlySpacecraftCount = 0; int CrippledFriendlySpacecraftCount = 0; for (int SpacecraftIndex = 0 ; SpacecraftIndex < GetSectorShipInterfaces().Num(); SpacecraftIndex++) { IFlareSpacecraftInterface* Spacecraft = GetSectorShipInterfaces()[SpacecraftIndex]; UFlareCompany* OtherCompany = Spacecraft->GetCompany(); if (!Spacecraft->GetDamageSystem()->IsAlive()) { continue; } if (OtherCompany == Company) { FriendlySpacecraftCount++; if (Spacecraft->GetDamageSystem()->GetSubsystemHealth(EFlareSubsystem::SYS_Weapon) > 0) { DangerousFriendlySpacecraftCount++; } if (Spacecraft->GetDamageSystem()->GetSubsystemHealth(EFlareSubsystem::SYS_Propulsion) == 0) { CrippledFriendlySpacecraftCount++; } } else if (OtherCompany->GetWarState(Company) == EFlareHostility::Hostile) { HostileSpacecraftCount++; if (Spacecraft->GetDamageSystem()->GetSubsystemHealth(EFlareSubsystem::SYS_Weapon) > 0) { DangerousHostileSpacecraftCount++; } } } // No friendly or no hostile ship if (FriendlySpacecraftCount == 0 || HostileSpacecraftCount == 0) { return EFlareSectorBattleState::NoBattle; } // No friendly and hostile ship are not dangerous if (DangerousFriendlySpacecraftCount == 0 && DangerousHostileSpacecraftCount == 0) { return EFlareSectorBattleState::NoBattle; } // No friendly dangerous ship so the enemy have one. Battle is lost if (DangerousFriendlySpacecraftCount == 0) { if (CrippledFriendlySpacecraftCount == FriendlySpacecraftCount) { return EFlareSectorBattleState::BattleLostNoRetreat; } else { return EFlareSectorBattleState::BattleLost; } } if (DangerousHostileSpacecraftCount == 0) { return EFlareSectorBattleState::BattleWon; } if (CrippledFriendlySpacecraftCount == FriendlySpacecraftCount) { return EFlareSectorBattleState::BattleNoRetreat; } else { return EFlareSectorBattleState::Battle; } } FText UFlareSectorInterface::GetSectorFriendlynessText(UFlareCompany* Company) { FText Status; switch (GetSectorFriendlyness(Company)) { case EFlareSectorFriendlyness::NotVisited: Status = LOCTEXT("Unknown", "UNKNOWN"); break; case EFlareSectorFriendlyness::Neutral: Status = LOCTEXT("Neutral", "NEUTRAL"); break; case EFlareSectorFriendlyness::Friendly: Status = LOCTEXT("Friendly", "FRIENDLY"); break; case EFlareSectorFriendlyness::Contested: Status = LOCTEXT("Contested", "CONTESTED"); break; case EFlareSectorFriendlyness::Hostile: Status = LOCTEXT("Hostile", "HOSTILE"); break; } return Status; } FLinearColor UFlareSectorInterface::GetSectorFriendlynessColor(UFlareCompany* Company) { FLinearColor Color; const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); switch (GetSectorFriendlyness(Company)) { case EFlareSectorFriendlyness::NotVisited: Color = Theme.UnknownColor; break; case EFlareSectorFriendlyness::Neutral: Color = Theme.NeutralColor; break; case EFlareSectorFriendlyness::Friendly: Color = Theme.FriendlyColor; break; case EFlareSectorFriendlyness::Contested: Color = Theme.DisputedColor; break; case EFlareSectorFriendlyness::Hostile: Color = Theme.EnemyColor; break; } return Color; } float UFlareSectorInterface::GetPreciseResourcePrice(FFlareResourceDescription* Resource, int32 Age) { if(Age == 0) { if (!ResourcePrices.Contains(Resource)) { ResourcePrices.Add(Resource, GetDefaultResourcePrice(Resource)); } return ResourcePrices[Resource]; } else { if (!LastResourcePrices.Contains(Resource)) { FFlareFloatBuffer Prices; Prices.Init(50); Prices.Append(GetPreciseResourcePrice(Resource, 0)); LastResourcePrices.Add(Resource, Prices); } return LastResourcePrices[Resource].GetValue(Age); } } void UFlareSectorInterface::SwapPrices() { for(int32 ResourceIndex = 0; ResourceIndex < Game->GetResourceCatalog()->Resources.Num(); ResourceIndex++) { FFlareResourceDescription* Resource = &Game->GetResourceCatalog()->Resources[ResourceIndex]->Data; if (!LastResourcePrices.Contains(Resource)) { FFlareFloatBuffer Prices; Prices.Init(50); LastResourcePrices.Add(Resource, Prices); } LastResourcePrices[Resource].Append(GetPreciseResourcePrice(Resource, 0)); } } void UFlareSectorInterface::SetPreciseResourcePrice(FFlareResourceDescription* Resource, float NewPrice) { ResourcePrices[Resource] = FMath::Clamp(NewPrice, (float) Resource->MinPrice, (float) Resource->MaxPrice); } int64 UFlareSectorInterface::GetResourcePrice(FFlareResourceDescription* Resource, EFlareResourcePriceContext::Type PriceContext, int32 Age) { int64 DefaultPrice = FMath::RoundToInt(GetPreciseResourcePrice(Resource, Age)); switch (PriceContext) { case EFlareResourcePriceContext::Default: return DefaultPrice; break; case EFlareResourcePriceContext::FactoryOutput: return DefaultPrice - Resource->TransportFee; break; case EFlareResourcePriceContext::FactoryInput: return DefaultPrice + Resource->TransportFee; break; case EFlareResourcePriceContext::ConsumerConsumption: return DefaultPrice * 1.5; break; case EFlareResourcePriceContext::MaintenanceConsumption: return DefaultPrice * 1.5; break; default: return 0; break; } } float UFlareSectorInterface::GetDefaultResourcePrice(FFlareResourceDescription* Resource) { return Resource->MinPrice * 0.75 + Resource->MaxPrice * 0.25; } uint32 UFlareSectorInterface::GetTransfertResourcePrice(IFlareSpacecraftInterface* SourceSpacecraft, IFlareSpacecraftInterface* DestinationSpacecraft, FFlareResourceDescription* Resource) { IFlareSpacecraftInterface* Station = NULL; // Which one is any is a station ? if (SourceSpacecraft->IsStation()) { Station = SourceSpacecraft; } else if (DestinationSpacecraft->IsStation()) { Station = DestinationSpacecraft; } else { return GetResourcePrice(Resource, EFlareResourcePriceContext::Default); } // Get context EFlareResourcePriceContext::Type ResourceUsage = Station->GetResourceUseType(Resource); if (ResourceUsage == EFlareResourcePriceContext::ConsumerConsumption || ResourceUsage == EFlareResourcePriceContext::MaintenanceConsumption) { ResourceUsage = EFlareResourcePriceContext::FactoryInput; } // Get the usage and price return GetResourcePrice(Resource, ResourceUsage); } uint32 UFlareSectorInterface::TransfertResources(IFlareSpacecraftInterface* SourceSpacecraft, IFlareSpacecraftInterface* DestinationSpacecraft, FFlareResourceDescription* Resource, uint32 Quantity) { // TODO Check docking capabilities if(SourceSpacecraft->GetCurrentSectorInterface() != DestinationSpacecraft->GetCurrentSectorInterface()) { FLOG("Warning cannot transfert resource because both ship are not in the same sector"); return 0; } if(SourceSpacecraft->IsStation() && DestinationSpacecraft->IsStation()) { FLOG("Warning cannot transfert resource between 2 stations"); return 0; } int32 ResourcePrice = GetTransfertResourcePrice(SourceSpacecraft, DestinationSpacecraft, Resource); int32 QuantityToTake = Quantity; if (SourceSpacecraft->GetCompany() != DestinationSpacecraft->GetCompany()) { // Limit transaction bay available money int32 MaxAffordableQuantity = DestinationSpacecraft->GetCompany()->GetMoney() / ResourcePrice; QuantityToTake = FMath::Min(QuantityToTake, MaxAffordableQuantity); } int32 ResourceCapacity = DestinationSpacecraft->GetCargoBay()->GetFreeSpaceForResource(Resource); QuantityToTake = FMath::Min(QuantityToTake, ResourceCapacity); int32 TakenResources = SourceSpacecraft->GetCargoBay()->TakeResources(Resource, QuantityToTake); int32 GivenResources = DestinationSpacecraft->GetCargoBay()->GiveResources(Resource, TakenResources); if (GivenResources > 0 && SourceSpacecraft->GetCompany() != DestinationSpacecraft->GetCompany()) { // Pay int64 Price = ResourcePrice * GivenResources; DestinationSpacecraft->GetCompany()->TakeMoney(Price); SourceSpacecraft->GetCompany()->GiveMoney(Price); SourceSpacecraft->GetCompany()->GiveReputation(DestinationSpacecraft->GetCompany(), 0.5f, true); DestinationSpacecraft->GetCompany()->GiveReputation(SourceSpacecraft->GetCompany(), 0.5f, true); } return GivenResources; } bool UFlareSectorInterface::CanUpgrade(UFlareCompany* Company) { EFlareSectorBattleState::Type BattleState = GetSectorBattleState(Company); if(BattleState != EFlareSectorBattleState::NoBattle && BattleState != EFlareSectorBattleState::BattleWon) { return false; } for(int StationIndex = 0 ; StationIndex < GetSectorStationInterfaces().Num(); StationIndex ++ ) { IFlareSpacecraftInterface* StationInterface = GetSectorStationInterfaces()[StationIndex]; if (StationInterface->GetCompany()->GetWarState(Company) != EFlareHostility::Hostile) { return true; } } return false; } #undef LOCTEXT_NAMESPACE <commit_msg>Make default resource price the mean between min and max<commit_after>#include "../Flare.h" #include "FlareSectorInterface.h" #include "FlareSimulatedSector.h" #include "../Spacecrafts/FlareSpacecraftInterface.h" #include "../Economy/FlareCargoBay.h" #include "../Game/FlareGame.h" #define LOCTEXT_NAMESPACE "FlareSectorInterface" /*---------------------------------------------------- Constructor ----------------------------------------------------*/ UFlareSectorInterface::UFlareSectorInterface(const class FObjectInitializer& PCIP) : Super(PCIP) { } void UFlareSectorInterface::LoadResourcePrices() { ResourcePrices.Empty(); LastResourcePrices.Empty(); for (int PriceIndex = 0; PriceIndex < SectorData.ResourcePrices.Num(); PriceIndex++) { FFFlareResourcePrice* ResourcePrice = &SectorData.ResourcePrices[PriceIndex]; FFlareResourceDescription* Resource = Game->GetResourceCatalog()->Get(ResourcePrice->ResourceIdentifier); float Price = ResourcePrice->Price; ResourcePrices.Add(Resource, Price); FFlareFloatBuffer* Prices = &ResourcePrice->Prices; Prices->Resize(50); LastResourcePrices.Add(Resource, *Prices); } } void UFlareSectorInterface::SaveResourcePrices() { SectorData.ResourcePrices.Empty(); for(int32 ResourceIndex = 0; ResourceIndex < Game->GetResourceCatalog()->Resources.Num(); ResourceIndex++) { FFlareResourceDescription* Resource = &Game->GetResourceCatalog()->Resources[ResourceIndex]->Data; if (ResourcePrices.Contains(Resource)) { FFFlareResourcePrice Price; Price.ResourceIdentifier = Resource->Identifier; Price.Price = ResourcePrices[Resource]; if (LastResourcePrices.Contains(Resource)) { Price.Prices = LastResourcePrices[Resource]; SectorData.ResourcePrices.Add(Price); } } } } FText UFlareSectorInterface::GetSectorName() { if (SectorData.GivenName.ToString().Len()) { return SectorData.GivenName; } else if (SectorDescription->Name.ToString().Len()) { return SectorDescription->Name; } else { return FText::FromString(GetSectorCode()); } } FString UFlareSectorInterface::GetSectorCode() { // TODO cache ? return SectorOrbitParameters.CelestialBodyIdentifier.ToString() + "-" + FString::FromInt(SectorOrbitParameters.Altitude) + "-" + FString::FromInt(SectorOrbitParameters.Phase); } EFlareSectorFriendlyness::Type UFlareSectorInterface::GetSectorFriendlyness(UFlareCompany* Company) { if (!Company->HasVisitedSector(GetSimulatedSector())) { return EFlareSectorFriendlyness::NotVisited; } if (GetSimulatedSector()->GetSectorSpacecrafts().Num() == 0) { return EFlareSectorFriendlyness::Neutral; } int HostileSpacecraftCount = 0; int NeutralSpacecraftCount = 0; int FriendlySpacecraftCount = 0; for (int SpacecraftIndex = 0 ; SpacecraftIndex < GetSimulatedSector()->GetSectorSpacecrafts().Num(); SpacecraftIndex++) { UFlareCompany* OtherCompany = GetSimulatedSector()->GetSectorSpacecrafts()[SpacecraftIndex]->GetCompany(); if (OtherCompany == Company) { FriendlySpacecraftCount++; } else if (OtherCompany->GetWarState(Company) == EFlareHostility::Hostile) { HostileSpacecraftCount++; } else { NeutralSpacecraftCount++; } } if (FriendlySpacecraftCount > 0 && HostileSpacecraftCount > 0) { return EFlareSectorFriendlyness::Contested; } if (FriendlySpacecraftCount > 0) { return EFlareSectorFriendlyness::Friendly; } else if (HostileSpacecraftCount > 0) { return EFlareSectorFriendlyness::Hostile; } else { return EFlareSectorFriendlyness::Neutral; } } EFlareSectorBattleState::Type UFlareSectorInterface::GetSectorBattleState(UFlareCompany* Company) { if (GetSectorShipInterfaces().Num() == 0) { return EFlareSectorBattleState::NoBattle; } int HostileSpacecraftCount = 0; int DangerousHostileSpacecraftCount = 0; int FriendlySpacecraftCount = 0; int DangerousFriendlySpacecraftCount = 0; int CrippledFriendlySpacecraftCount = 0; for (int SpacecraftIndex = 0 ; SpacecraftIndex < GetSectorShipInterfaces().Num(); SpacecraftIndex++) { IFlareSpacecraftInterface* Spacecraft = GetSectorShipInterfaces()[SpacecraftIndex]; UFlareCompany* OtherCompany = Spacecraft->GetCompany(); if (!Spacecraft->GetDamageSystem()->IsAlive()) { continue; } if (OtherCompany == Company) { FriendlySpacecraftCount++; if (Spacecraft->GetDamageSystem()->GetSubsystemHealth(EFlareSubsystem::SYS_Weapon) > 0) { DangerousFriendlySpacecraftCount++; } if (Spacecraft->GetDamageSystem()->GetSubsystemHealth(EFlareSubsystem::SYS_Propulsion) == 0) { CrippledFriendlySpacecraftCount++; } } else if (OtherCompany->GetWarState(Company) == EFlareHostility::Hostile) { HostileSpacecraftCount++; if (Spacecraft->GetDamageSystem()->GetSubsystemHealth(EFlareSubsystem::SYS_Weapon) > 0) { DangerousHostileSpacecraftCount++; } } } // No friendly or no hostile ship if (FriendlySpacecraftCount == 0 || HostileSpacecraftCount == 0) { return EFlareSectorBattleState::NoBattle; } // No friendly and hostile ship are not dangerous if (DangerousFriendlySpacecraftCount == 0 && DangerousHostileSpacecraftCount == 0) { return EFlareSectorBattleState::NoBattle; } // No friendly dangerous ship so the enemy have one. Battle is lost if (DangerousFriendlySpacecraftCount == 0) { if (CrippledFriendlySpacecraftCount == FriendlySpacecraftCount) { return EFlareSectorBattleState::BattleLostNoRetreat; } else { return EFlareSectorBattleState::BattleLost; } } if (DangerousHostileSpacecraftCount == 0) { return EFlareSectorBattleState::BattleWon; } if (CrippledFriendlySpacecraftCount == FriendlySpacecraftCount) { return EFlareSectorBattleState::BattleNoRetreat; } else { return EFlareSectorBattleState::Battle; } } FText UFlareSectorInterface::GetSectorFriendlynessText(UFlareCompany* Company) { FText Status; switch (GetSectorFriendlyness(Company)) { case EFlareSectorFriendlyness::NotVisited: Status = LOCTEXT("Unknown", "UNKNOWN"); break; case EFlareSectorFriendlyness::Neutral: Status = LOCTEXT("Neutral", "NEUTRAL"); break; case EFlareSectorFriendlyness::Friendly: Status = LOCTEXT("Friendly", "FRIENDLY"); break; case EFlareSectorFriendlyness::Contested: Status = LOCTEXT("Contested", "CONTESTED"); break; case EFlareSectorFriendlyness::Hostile: Status = LOCTEXT("Hostile", "HOSTILE"); break; } return Status; } FLinearColor UFlareSectorInterface::GetSectorFriendlynessColor(UFlareCompany* Company) { FLinearColor Color; const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); switch (GetSectorFriendlyness(Company)) { case EFlareSectorFriendlyness::NotVisited: Color = Theme.UnknownColor; break; case EFlareSectorFriendlyness::Neutral: Color = Theme.NeutralColor; break; case EFlareSectorFriendlyness::Friendly: Color = Theme.FriendlyColor; break; case EFlareSectorFriendlyness::Contested: Color = Theme.DisputedColor; break; case EFlareSectorFriendlyness::Hostile: Color = Theme.EnemyColor; break; } return Color; } float UFlareSectorInterface::GetPreciseResourcePrice(FFlareResourceDescription* Resource, int32 Age) { if(Age == 0) { if (!ResourcePrices.Contains(Resource)) { ResourcePrices.Add(Resource, GetDefaultResourcePrice(Resource)); } return ResourcePrices[Resource]; } else { if (!LastResourcePrices.Contains(Resource)) { FFlareFloatBuffer Prices; Prices.Init(50); Prices.Append(GetPreciseResourcePrice(Resource, 0)); LastResourcePrices.Add(Resource, Prices); } return LastResourcePrices[Resource].GetValue(Age); } } void UFlareSectorInterface::SwapPrices() { for(int32 ResourceIndex = 0; ResourceIndex < Game->GetResourceCatalog()->Resources.Num(); ResourceIndex++) { FFlareResourceDescription* Resource = &Game->GetResourceCatalog()->Resources[ResourceIndex]->Data; if (!LastResourcePrices.Contains(Resource)) { FFlareFloatBuffer Prices; Prices.Init(50); LastResourcePrices.Add(Resource, Prices); } LastResourcePrices[Resource].Append(GetPreciseResourcePrice(Resource, 0)); } } void UFlareSectorInterface::SetPreciseResourcePrice(FFlareResourceDescription* Resource, float NewPrice) { ResourcePrices[Resource] = FMath::Clamp(NewPrice, (float) Resource->MinPrice, (float) Resource->MaxPrice); } int64 UFlareSectorInterface::GetResourcePrice(FFlareResourceDescription* Resource, EFlareResourcePriceContext::Type PriceContext, int32 Age) { int64 DefaultPrice = FMath::RoundToInt(GetPreciseResourcePrice(Resource, Age)); switch (PriceContext) { case EFlareResourcePriceContext::Default: return DefaultPrice; break; case EFlareResourcePriceContext::FactoryOutput: return DefaultPrice - Resource->TransportFee; break; case EFlareResourcePriceContext::FactoryInput: return DefaultPrice + Resource->TransportFee; break; case EFlareResourcePriceContext::ConsumerConsumption: return DefaultPrice * 1.5; break; case EFlareResourcePriceContext::MaintenanceConsumption: return DefaultPrice * 1.5; break; default: return 0; break; } } float UFlareSectorInterface::GetDefaultResourcePrice(FFlareResourceDescription* Resource) { return (Resource->MinPrice + Resource->MaxPrice)/2; } uint32 UFlareSectorInterface::GetTransfertResourcePrice(IFlareSpacecraftInterface* SourceSpacecraft, IFlareSpacecraftInterface* DestinationSpacecraft, FFlareResourceDescription* Resource) { IFlareSpacecraftInterface* Station = NULL; // Which one is any is a station ? if (SourceSpacecraft->IsStation()) { Station = SourceSpacecraft; } else if (DestinationSpacecraft->IsStation()) { Station = DestinationSpacecraft; } else { return GetResourcePrice(Resource, EFlareResourcePriceContext::Default); } // Get context EFlareResourcePriceContext::Type ResourceUsage = Station->GetResourceUseType(Resource); if (ResourceUsage == EFlareResourcePriceContext::ConsumerConsumption || ResourceUsage == EFlareResourcePriceContext::MaintenanceConsumption) { ResourceUsage = EFlareResourcePriceContext::FactoryInput; } // Get the usage and price return GetResourcePrice(Resource, ResourceUsage); } uint32 UFlareSectorInterface::TransfertResources(IFlareSpacecraftInterface* SourceSpacecraft, IFlareSpacecraftInterface* DestinationSpacecraft, FFlareResourceDescription* Resource, uint32 Quantity) { // TODO Check docking capabilities if(SourceSpacecraft->GetCurrentSectorInterface() != DestinationSpacecraft->GetCurrentSectorInterface()) { FLOG("Warning cannot transfert resource because both ship are not in the same sector"); return 0; } if(SourceSpacecraft->IsStation() && DestinationSpacecraft->IsStation()) { FLOG("Warning cannot transfert resource between 2 stations"); return 0; } int32 ResourcePrice = GetTransfertResourcePrice(SourceSpacecraft, DestinationSpacecraft, Resource); int32 QuantityToTake = Quantity; if (SourceSpacecraft->GetCompany() != DestinationSpacecraft->GetCompany()) { // Limit transaction bay available money int32 MaxAffordableQuantity = DestinationSpacecraft->GetCompany()->GetMoney() / ResourcePrice; QuantityToTake = FMath::Min(QuantityToTake, MaxAffordableQuantity); } int32 ResourceCapacity = DestinationSpacecraft->GetCargoBay()->GetFreeSpaceForResource(Resource); QuantityToTake = FMath::Min(QuantityToTake, ResourceCapacity); int32 TakenResources = SourceSpacecraft->GetCargoBay()->TakeResources(Resource, QuantityToTake); int32 GivenResources = DestinationSpacecraft->GetCargoBay()->GiveResources(Resource, TakenResources); if (GivenResources > 0 && SourceSpacecraft->GetCompany() != DestinationSpacecraft->GetCompany()) { // Pay int64 Price = ResourcePrice * GivenResources; DestinationSpacecraft->GetCompany()->TakeMoney(Price); SourceSpacecraft->GetCompany()->GiveMoney(Price); SourceSpacecraft->GetCompany()->GiveReputation(DestinationSpacecraft->GetCompany(), 0.5f, true); DestinationSpacecraft->GetCompany()->GiveReputation(SourceSpacecraft->GetCompany(), 0.5f, true); } return GivenResources; } bool UFlareSectorInterface::CanUpgrade(UFlareCompany* Company) { EFlareSectorBattleState::Type BattleState = GetSectorBattleState(Company); if(BattleState != EFlareSectorBattleState::NoBattle && BattleState != EFlareSectorBattleState::BattleWon) { return false; } for(int StationIndex = 0 ; StationIndex < GetSectorStationInterfaces().Num(); StationIndex ++ ) { IFlareSpacecraftInterface* StationInterface = GetSectorStationInterfaces()[StationIndex]; if (StationInterface->GetCompany()->GetWarState(Company) != EFlareHostility::Hostile) { return true; } } return false; } #undef LOCTEXT_NAMESPACE <|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include "SDL.h" #include "SDL_gfxPrimitives.h" #include "SDL_ttf.h" #include "sdlwindow.h" #include "misc/fpscounter.h" #include "controller/sdlcontroller.h" #include "resources/imageresource.h" #include "resources/stringfontresource.h" namespace Zabbr { /** * Public constructor for the SDL initialization exception. * * @param s The initialization error. */ SDLInitializationException::SDLInitializationException(std::string s) : fError(s) { } /** * Returns the error of the exception. * * @return The error of the exception. */ std::string SDLInitializationException::getError() { return fError; } /** * Public constructor. */ SDLWindow::SDLWindow() { } /** * Open the window. * * @param xres The X resolution. * @param yres The Y resolution. * @param fs True if running in fullscreen, false if not. * * @throw An SDLInitializationException if initialization fails. */ void SDLWindow::open(int xres, int yres, bool fs) { if (SDL_Init(SDL_INIT_VIDEO) != 0) { throw SDLInitializationException(SDL_GetError()); } atexit(SDL_Quit); screen = SDL_SetVideoMode(xres, yres, 32, SDL_RESIZABLE); if (screen == NULL) { throw SDLInitializationException(SDL_GetError()); } if(TTF_Init() == -1) { throw SDLInitializationException(TTF_GetError()); } } /** * Close the window. */ void SDLWindow::close() { if (screen) SDL_FreeSurface(screen); TTF_Quit(); } /** * Run the mainloop. * * @param controller The first controller to get control of what happens. */ void SDLWindow::run(VSDLController* controller) { FPSCounter fpsCounter(500); fController = controller; SDL_Event event; fRunning = true; while (fRunning) { while (fRunning && SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: fController->keyDown(event.key); break; case SDL_KEYUP: fController->keyRelease(event.key); break; case SDL_MOUSEMOTION: fController->mouseMotion(event.motion); break; case SDL_MOUSEBUTTONUP: fController->mouseButton(event.button); break; case SDL_QUIT: fController->requestQuit(); break; case SDL_VIDEORESIZE: screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 32, SDL_RESIZABLE); break; } } if (fOldController) { delete fOldController; fOldController = NULL; } if (fRunning) { // it is possible we quit when firing events. drawRectangle(0, 0, screen->w, screen->h, 0, 0, 0); fController->draw(); draw(); SDL_Delay(1); } else { freeController(fController); fController = NULL; screen = NULL; SDL_Quit(); } if (fpsCounter.frame()) { std::stringstream ssWMCaption; ssWMCaption << fpsCounter.fps(); std::string WMCaption; ssWMCaption >> WMCaption; WMCaption = "Space-Invadors " + WMCaption + " FPS"; SDL_WM_SetCaption(WMCaption.c_str(), "Icon Title"); } } } /** * Updates the physical screen so it contains the same information as the screen buffer. */ void SDLWindow::draw() { SDL_Flip(screen); } /** * Close the current controller and pass control to the next controller. * * @param next The next controller. If 0 the window closes. */ void SDLWindow::closeController(VSDLController* next) { if (next != NULL) { fOldController = fController; fController = next; } else { // We keep the old controller. fRunning = false; } } /** * Gives control back to the parent controller, and close the current controller. * * @param prev The parent controller. */ void SDLWindow::openParentController(VSDLController* prev) { if (prev != NULL) { fOldController = fController; fController = prev; } else { fRunning = false; } } /** * Opens a new controller, but keep the current controller active. * * @param c The new active controller. */ void SDLWindow::openController(VSDLController* c) { fController = c; } /** * Draws a surface on the window. * * @param surface The surface to draw. * @param x The x coordinate on the screen. * @param y The y coordinate on the screen. */ void SDLWindow::drawSurface(SDLSurfaceResource* surface, int x, int y) { drawSurface(surface, x, y, 1.0); } /** * Draws a surface on the window. * * @param surface The surface to draw. * @param x The x coordinate on the screen. * @param y The y coordinate on the screen. * @param scale Scale factor of the surface. Not yet implemented. */ void SDLWindow::drawSurface(SDLSurfaceResource* surface, int x, int y, double scale) { SDL_Rect src, dest; src.x = 0; src.y = 0; src.w = surface->getWidth(); src.h = surface->getHeight(); dest.x = x; dest.y = y; dest.w = surface->getWidth() * scale; dest.h = surface->getHeight() * scale; SDL_BlitSurface(surface->getSurface(), &src, screen, &dest); } /** * Draws a rectangle on the screen. * * @param x The x coordinate of the rectangle on the screen. * @param y The y coordinate of the rectangle on the screen. * @param w The width of the rectangle. * @param h The height of the rectangle. * @param r The red component of the color of the rectangle. * @param g The green component of the color of the rectangle. * @param b The blue component of the color of the rectangle. */ void SDLWindow::drawRectangle(int x, int y, int w, int h, int r, int g, int b) { SDL_Rect dest; dest.x = x; dest.y = y; dest.w = w; dest.h = h; SDL_FillRect(screen, &dest, SDL_MapRGB(screen->format, r, g, b)); } /** * Draws a transparant rectangle on the screen. * * @param x The x coordinate of the rectangle on the screen. * @param y The y coordinate of the rectangle on the screen. * @param w The width of the rectangle. * @param h The height of the rectangle. * @param r The red component of the color of the rectangle. * @param g The green component of the color of the rectangle. * @param b The blue component of the color of the rectangle. * @param a The alpha-channel of the rectangle, 0.0 for completely transparant, 1.0 for opaque. */ void SDLWindow::drawRectangle(int x, int y, int w, int h, int r, int g, int b, double a) { boxRGBA(screen, x, y, x + w, y + h, r, g, b, a*255); } /** * Get the x-resolution of the window * * @return The X resolution (width) of the window. */ int SDLWindow::getXResolution() { return screen->w; } /** * Get the y-resolution of the window * * @return The Y resolution (height) of the window. */ int SDLWindow::getYResolution() { return screen->h; } /** * Free a controller and all of its parent controllers. * * @param c The controller to free. */ void SDLWindow::freeController(VSDLController* c) { if (c->fParentController) { freeController(c->fParentController); } delete c; } } <commit_msg>Fix mem leak in zabbr<commit_after>#include <iostream> #include <sstream> #include "SDL.h" #include "SDL_gfxPrimitives.h" #include "SDL_ttf.h" #include "sdlwindow.h" #include "misc/fpscounter.h" #include "controller/sdlcontroller.h" #include "resources/imageresource.h" #include "resources/stringfontresource.h" namespace Zabbr { /** * Public constructor for the SDL initialization exception. * * @param s The initialization error. */ SDLInitializationException::SDLInitializationException(std::string s) : fError(s) { } /** * Returns the error of the exception. * * @return The error of the exception. */ std::string SDLInitializationException::getError() { return fError; } /** * Public constructor. */ SDLWindow::SDLWindow() { } /** * Open the window. * * @param xres The X resolution. * @param yres The Y resolution. * @param fs True if running in fullscreen, false if not. * * @throw An SDLInitializationException if initialization fails. */ void SDLWindow::open(int xres, int yres, bool fs) { if (SDL_Init(SDL_INIT_VIDEO) != 0) { throw SDLInitializationException(SDL_GetError()); } atexit(SDL_Quit); screen = SDL_SetVideoMode(xres, yres, 32, SDL_RESIZABLE); if (screen == NULL) { throw SDLInitializationException(SDL_GetError()); } if(TTF_Init() == -1) { throw SDLInitializationException(TTF_GetError()); } } /** * Close the window. */ void SDLWindow::close() { if (screen) SDL_FreeSurface(screen); TTF_Quit(); } /** * Run the mainloop. * * @param controller The first controller to get control of what happens. */ void SDLWindow::run(VSDLController* controller) { FPSCounter fpsCounter(500); fController = controller; SDL_Event event; fRunning = true; while (fRunning) { while (fRunning && SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: fController->keyDown(event.key); break; case SDL_KEYUP: fController->keyRelease(event.key); break; case SDL_MOUSEMOTION: fController->mouseMotion(event.motion); break; case SDL_MOUSEBUTTONUP: fController->mouseButton(event.button); break; case SDL_QUIT: fController->requestQuit(); break; case SDL_VIDEORESIZE: screen = SDL_SetVideoMode(event.resize.w, event.resize.h, 32, SDL_RESIZABLE); break; } } if (fOldController) { delete fOldController; fOldController = NULL; } if (fRunning) { // it is possible we quit when firing events. drawRectangle(0, 0, screen->w, screen->h, 0, 0, 0); fController->draw(); } if (fRunning) { // It is possible we stop running in the draw. draw(); SDL_Delay(1); } else { freeController(fController); fController = NULL; screen = NULL; SDL_Quit(); } if (fpsCounter.frame()) { std::stringstream ssWMCaption; ssWMCaption << fpsCounter.fps(); std::string WMCaption; ssWMCaption >> WMCaption; WMCaption = "Space-Invadors " + WMCaption + " FPS"; SDL_WM_SetCaption(WMCaption.c_str(), "Icon Title"); } } } /** * Updates the physical screen so it contains the same information as the screen buffer. */ void SDLWindow::draw() { SDL_Flip(screen); } /** * Close the current controller and pass control to the next controller. * * @param next The next controller. If 0 the window closes. */ void SDLWindow::closeController(VSDLController* next) { if (next != NULL) { fOldController = fController; fController = next; } else { // We keep the old controller. fRunning = false; } } /** * Gives control back to the parent controller, and close the current controller. * * @param prev The parent controller. */ void SDLWindow::openParentController(VSDLController* prev) { if (prev != NULL) { fOldController = fController; fController = prev; } else { fRunning = false; } } /** * Opens a new controller, but keep the current controller active. * * @param c The new active controller. */ void SDLWindow::openController(VSDLController* c) { fController = c; } /** * Draws a surface on the window. * * @param surface The surface to draw. * @param x The x coordinate on the screen. * @param y The y coordinate on the screen. */ void SDLWindow::drawSurface(SDLSurfaceResource* surface, int x, int y) { drawSurface(surface, x, y, 1.0); } /** * Draws a surface on the window. * * @param surface The surface to draw. * @param x The x coordinate on the screen. * @param y The y coordinate on the screen. * @param scale Scale factor of the surface. Not yet implemented. */ void SDLWindow::drawSurface(SDLSurfaceResource* surface, int x, int y, double scale) { SDL_Rect src, dest; src.x = 0; src.y = 0; src.w = surface->getWidth(); src.h = surface->getHeight(); dest.x = x; dest.y = y; dest.w = surface->getWidth() * scale; dest.h = surface->getHeight() * scale; SDL_BlitSurface(surface->getSurface(), &src, screen, &dest); } /** * Draws a rectangle on the screen. * * @param x The x coordinate of the rectangle on the screen. * @param y The y coordinate of the rectangle on the screen. * @param w The width of the rectangle. * @param h The height of the rectangle. * @param r The red component of the color of the rectangle. * @param g The green component of the color of the rectangle. * @param b The blue component of the color of the rectangle. */ void SDLWindow::drawRectangle(int x, int y, int w, int h, int r, int g, int b) { SDL_Rect dest; dest.x = x; dest.y = y; dest.w = w; dest.h = h; SDL_FillRect(screen, &dest, SDL_MapRGB(screen->format, r, g, b)); } /** * Draws a transparant rectangle on the screen. * * @param x The x coordinate of the rectangle on the screen. * @param y The y coordinate of the rectangle on the screen. * @param w The width of the rectangle. * @param h The height of the rectangle. * @param r The red component of the color of the rectangle. * @param g The green component of the color of the rectangle. * @param b The blue component of the color of the rectangle. * @param a The alpha-channel of the rectangle, 0.0 for completely transparant, 1.0 for opaque. */ void SDLWindow::drawRectangle(int x, int y, int w, int h, int r, int g, int b, double a) { boxRGBA(screen, x, y, x + w, y + h, r, g, b, a*255); } /** * Get the x-resolution of the window * * @return The X resolution (width) of the window. */ int SDLWindow::getXResolution() { return screen->w; } /** * Get the y-resolution of the window * * @return The Y resolution (height) of the window. */ int SDLWindow::getYResolution() { return screen->h; } /** * Free a controller and all of its parent controllers. * * @param c The controller to free. */ void SDLWindow::freeController(VSDLController* c) { if (c->fParentController) { freeController(c->fParentController); } delete c; } } <|endoftext|>
<commit_before>#include "GraphicsRendererSystem.h" #include <RenderInterface.h> #include "GraphicsBackendSystem.h" #include <GraphicsWrapper.h> #include <RenderStateEnums.h> #include "ShadowSystem.h" #include <GPUTimer.h> #include <AntTweakBarWrapper.h> #include "ParticleRenderSystem.h" GraphicsRendererSystem::GraphicsRendererSystem(GraphicsBackendSystem* p_graphicsBackend, ShadowSystem* p_shadowSystem, RenderInterface* p_mesh, RenderInterface* p_libRocket, RenderInterface* p_particle, RenderInterface* p_antTweakBar, RenderInterface* p_light) : EntitySystem( SystemType::GraphicsRendererSystem){ m_backend = p_graphicsBackend; m_shadowSystem = p_shadowSystem; m_meshRenderer = p_mesh; m_libRocketRenderSystem = p_libRocket; m_particleRenderSystem = p_particle; m_antTweakBarSystem = p_antTweakBar; m_lightRenderSystem = p_light; m_totalTime = 0.0f; m_activeShadows = new int[MAXSHADOWS]; m_shadowViewProjections = new AglMatrix[MAXSHADOWS]; m_profiles.push_back(GPUTimerProfile("SHADOW")); m_profiles.push_back(GPUTimerProfile("MESH")); m_profiles.push_back(GPUTimerProfile("LIGHT")); m_profiles.push_back(GPUTimerProfile("SSAO")); m_profiles.push_back(GPUTimerProfile("COMPOSE")); m_profiles.push_back(GPUTimerProfile("PARTICLE")); m_profiles.push_back(GPUTimerProfile("GUI")); clearShadowStuf(); } GraphicsRendererSystem::~GraphicsRendererSystem(){ delete[] m_shadowViewProjections; delete[] m_activeShadows; } void GraphicsRendererSystem::initialize(){ for (unsigned int i=0;i < NUMRENDERINGPASSES; i++) { AntTweakBarWrapper::getInstance()->addReadOnlyVariable( AntTweakBarWrapper::MEASUREMENT, m_profiles[i].profile.c_str(),TwType::TW_TYPE_DOUBLE, &m_profiles[i].renderingTime,"group=GPU"); m_backend->getGfxWrapper()->getGPUTimer()->addProfile(m_profiles[i].profile); } AntTweakBarWrapper::getInstance()->addReadOnlyVariable( AntTweakBarWrapper::MEASUREMENT,"Total",TwType::TW_TYPE_DOUBLE, &m_totalTime,"group=GPU"); } void GraphicsRendererSystem::process(){ m_wrapper = m_backend->getGfxWrapper(); //Shadows //m_wrapper->getGPUTimer()->Start(m_profiles[SHADOW].profile); clearShadowStuf(); //Fill the shadow view projections for (unsigned int i = 0; i < m_shadowSystem->getNumberOfShadowCameras(); i++){ m_activeShadows[m_shadowSystem->getShadowIdx(i)] = 1; m_shadowViewProjections[m_shadowSystem->getShadowIdx(i)] = m_shadowSystem->getViewProjection(i); } /* initShadowPass(); for(unsigned int i = 0; i < MAXSHADOWS; i++){ if(m_activeShadows[i] != -1){ m_wrapper->setShadowMapAsRenderTarget(i); //m_wrapper->setActiveShadow(i); m_meshRenderer->render(); } } endShadowPass(); */ //m_wrapper->getGPUTimer()->Stop(m_profiles[SHADOW].profile); // Meshes //m_wrapper->getGPUTimer()->Start(m_profiles[MESH].profile); initMeshPass(); m_meshRenderer->render(); endMeshPass(); //m_wrapper->getGPUTimer()->Stop(m_profiles[MESH].profile); // Lights //m_wrapper->getGPUTimer()->Start(m_profiles[LIGHT].profile); initLightPass(); m_lightRenderSystem->render(); endLightPass(); //m_wrapper->getGPUTimer()->Stop(m_profiles[LIGHT].profile); //SSAO //m_wrapper->getGPUTimer()->Start(m_profiles[SSAO].profile); beginSsao(); m_wrapper->renderSsao(); endSsao(); //m_wrapper->getGPUTimer()->Stop(m_profiles[SSAO].profile); //Compose //m_wrapper->getGPUTimer()->Start(m_profiles[COMPOSE].profile); initComposePass(); m_wrapper->renderComposeStage(); endComposePass(); //m_wrapper->getGPUTimer()->Stop(m_profiles[COMPOSE].profile); //Particles //m_wrapper->getGPUTimer()->Start(m_profiles[PARTICLE].profile); initParticlePass(); renderParticles(); endParticlePass(); //m_wrapper->getGPUTimer()->Stop(m_profiles[PARTICLE].profile); //GUI //m_wrapper->getGPUTimer()->Start(m_profiles[GUI].profile); initGUIPass(); m_libRocketRenderSystem->render(); m_antTweakBarSystem->render(); endGUIPass(); //m_wrapper->getGPUTimer()->Stop(m_profiles[GUI].profile); flipBackbuffer(); //updateTimers(); } void GraphicsRendererSystem::initShadowPass(){ m_wrapper->setRasterizerStateSettings(RasterizerState::FILLED_CW_FRONTCULL); m_wrapper->setBlendStateSettings(BlendState::DEFAULT); //m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST); m_wrapper->setViewportToShadowMapSize(); m_wrapper->setRenderingShadows(); m_wrapper->setShadowViewProjections(m_shadowViewProjections); } void GraphicsRendererSystem::endShadowPass(){ m_wrapper->resetViewportToOriginalSize(); m_wrapper->stopedRenderingShadows(); //m_wrapper->unmapPerShadowBuffer(); } void GraphicsRendererSystem::initMeshPass(){ m_wrapper->mapSceneInfo(); m_wrapper->setRasterizerStateSettings(RasterizerState::DEFAULT); m_wrapper->setBlendStateSettings(BlendState::DEFAULT); //m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST); m_wrapper->clearRenderTargets(); m_wrapper->setBaseRenderTargets(); } void GraphicsRendererSystem::endMeshPass(){ m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST); } void GraphicsRendererSystem::initLightPass(){ m_wrapper->setRasterizerStateSettings( //RasterizerState::WIREFRAME_NOCULL, false); // For debug /ML RasterizerState::FILLED_CW_FRONTCULL, false); m_wrapper->setBlendStateSettings(BlendState::LIGHT); m_wrapper->setLightPassRenderTarget(); //m_wrapper->mapDeferredBaseToShader(); m_wrapper->mapNeededShaderResourceToLightPass(m_activeShadows); } void GraphicsRendererSystem::endLightPass(){ //m_wrapper->setRasterizerStateSettings(RasterizerState::DEFAULT); //m_wrapper->setBlendStateSettings(BlendState::DEFAULT); //m_wrapper->unmapDeferredBaseFromShader(); //m_wrapper->unmapUsedShaderResourceFromLightPass(m_activeShadows); } void GraphicsRendererSystem::beginSsao() { // not used anymore //m_wrapper->mapRandomVecTexture(); m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLESTRIP); m_wrapper->setBlendStateSettings(BlendState::SSAO); m_wrapper->setRasterizerStateSettings( RasterizerState::FILLED_NOCULL_NOCLIP, false); } void GraphicsRendererSystem::endSsao() { m_wrapper->setRasterizerStateSettings(RasterizerState::DEFAULT); m_wrapper->setBlendStateSettings(BlendState::DEFAULT); m_wrapper->unmapDeferredBaseFromShader(); m_wrapper->unmapUsedShaderResourceFromLightPass(m_activeShadows); } void GraphicsRendererSystem::initComposePass() { m_wrapper->setRasterizerStateSettings( RasterizerState::DEFAULT, false); m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLESTRIP); m_wrapper->setComposedRenderTargetWithNoDepthStencil(); m_wrapper->mapVariousStagesForCompose(); } void GraphicsRendererSystem::endComposePass() { m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST); m_wrapper->unmapVariousStagesForCompose(); m_wrapper->unmapDepthFromShader(); } void GraphicsRendererSystem::initParticlePass(){ m_wrapper->setParticleRenderState(); //m_wrapper->setBlendStateSettings(BlendState::PARTICLE); m_wrapper->setBlendStateSettings(BlendState::ADDITIVE); m_wrapper->setPrimitiveTopology(PrimitiveTopology::POINTLIST); } void GraphicsRendererSystem::renderParticles() { // A ugly way to be able to call the different rendering functions. Needs refactoring /ML. ParticleRenderSystem* psRender = static_cast<ParticleRenderSystem*>( m_particleRenderSystem ); for( int i=0; i<AglParticleSystemHeader::AglBlendMode_CNT; i++ ) { for( int j=0; j<AglParticleSystemHeader::AglRasterizerMode_CNT; j++ ) { AglParticleSystemHeader::AglBlendMode blend = (AglParticleSystemHeader::AglBlendMode)i; AglParticleSystemHeader::AglRasterizerMode rast = (AglParticleSystemHeader::AglRasterizerMode)j; m_wrapper->setRasterizerStateSettings( psRender->rasterizerStateFromAglRasterizerMode(rast) ); m_wrapper->setBlendStateSettings( psRender->blendStateFromAglBlendMode(blend) ); psRender->render( blend, rast ); } } } void GraphicsRendererSystem::endParticlePass(){ m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST); m_wrapper->setBlendStateSettings(BlendState::DEFAULT); m_wrapper->setComposedRenderTargetWithNoDepthStencil(); } void GraphicsRendererSystem::initGUIPass(){ m_wrapper->setBlendStateSettings(BlendState::ALPHA); } void GraphicsRendererSystem::endGUIPass(){ m_wrapper->setBlendStateSettings(BlendState::DEFAULT); } void GraphicsRendererSystem::flipBackbuffer(){ m_wrapper->flipBackBuffer(); } void GraphicsRendererSystem::clearShadowStuf() { for(int i = 0; i < MAXSHADOWS; i++){ m_activeShadows[i] = -1; m_shadowViewProjections[i] = AglMatrix::identityMatrix(); } } void GraphicsRendererSystem::updateTimers() { m_totalTime = 0; GPUTimer* timer = m_wrapper->getGPUTimer(); for(unsigned int i = 0; i < NUMRENDERINGPASSES; i++){ m_profiles[i].renderingTime = timer->getTheTimeAndReset(m_profiles[i].profile); m_totalTime += m_profiles[i].renderingTime; } m_wrapper->getGPUTimer()->tick(); }<commit_msg>Enabled measuring of GPU again.<commit_after>#include "GraphicsRendererSystem.h" #include <RenderInterface.h> #include "GraphicsBackendSystem.h" #include <GraphicsWrapper.h> #include <RenderStateEnums.h> #include "ShadowSystem.h" #include <GPUTimer.h> #include <AntTweakBarWrapper.h> #include "ParticleRenderSystem.h" GraphicsRendererSystem::GraphicsRendererSystem(GraphicsBackendSystem* p_graphicsBackend, ShadowSystem* p_shadowSystem, RenderInterface* p_mesh, RenderInterface* p_libRocket, RenderInterface* p_particle, RenderInterface* p_antTweakBar, RenderInterface* p_light) : EntitySystem( SystemType::GraphicsRendererSystem){ m_backend = p_graphicsBackend; m_shadowSystem = p_shadowSystem; m_meshRenderer = p_mesh; m_libRocketRenderSystem = p_libRocket; m_particleRenderSystem = p_particle; m_antTweakBarSystem = p_antTweakBar; m_lightRenderSystem = p_light; m_totalTime = 0.0f; m_activeShadows = new int[MAXSHADOWS]; m_shadowViewProjections = new AglMatrix[MAXSHADOWS]; m_profiles.push_back(GPUTimerProfile("SHADOW")); m_profiles.push_back(GPUTimerProfile("MESH")); m_profiles.push_back(GPUTimerProfile("LIGHT")); m_profiles.push_back(GPUTimerProfile("SSAO")); m_profiles.push_back(GPUTimerProfile("COMPOSE")); m_profiles.push_back(GPUTimerProfile("PARTICLE")); m_profiles.push_back(GPUTimerProfile("GUI")); clearShadowStuf(); } GraphicsRendererSystem::~GraphicsRendererSystem(){ delete[] m_shadowViewProjections; delete[] m_activeShadows; } void GraphicsRendererSystem::initialize(){ for (unsigned int i=0;i < NUMRENDERINGPASSES; i++) { AntTweakBarWrapper::getInstance()->addReadOnlyVariable( AntTweakBarWrapper::MEASUREMENT, m_profiles[i].profile.c_str(),TwType::TW_TYPE_DOUBLE, &m_profiles[i].renderingTime,"group=GPU"); m_backend->getGfxWrapper()->getGPUTimer()->addProfile(m_profiles[i].profile); } AntTweakBarWrapper::getInstance()->addReadOnlyVariable( AntTweakBarWrapper::MEASUREMENT,"Total",TwType::TW_TYPE_DOUBLE, &m_totalTime,"group=GPU"); } void GraphicsRendererSystem::process(){ m_wrapper = m_backend->getGfxWrapper(); //Shadows //m_wrapper->getGPUTimer()->Start(m_profiles[SHADOW].profile); clearShadowStuf(); //Fill the shadow view projections for (unsigned int i = 0; i < m_shadowSystem->getNumberOfShadowCameras(); i++){ m_activeShadows[m_shadowSystem->getShadowIdx(i)] = 1; m_shadowViewProjections[m_shadowSystem->getShadowIdx(i)] = m_shadowSystem->getViewProjection(i); } /* initShadowPass(); for(unsigned int i = 0; i < MAXSHADOWS; i++){ if(m_activeShadows[i] != -1){ m_wrapper->setShadowMapAsRenderTarget(i); //m_wrapper->setActiveShadow(i); m_meshRenderer->render(); } } endShadowPass(); */ //m_wrapper->getGPUTimer()->Stop(m_profiles[SHADOW].profile); // Meshes m_wrapper->getGPUTimer()->Start(m_profiles[MESH].profile); initMeshPass(); m_meshRenderer->render(); endMeshPass(); m_wrapper->getGPUTimer()->Stop(m_profiles[MESH].profile); // Lights m_wrapper->getGPUTimer()->Start(m_profiles[LIGHT].profile); initLightPass(); m_lightRenderSystem->render(); endLightPass(); m_wrapper->getGPUTimer()->Stop(m_profiles[LIGHT].profile); //SSAO m_wrapper->getGPUTimer()->Start(m_profiles[SSAO].profile); beginSsao(); m_wrapper->renderSsao(); endSsao(); m_wrapper->getGPUTimer()->Stop(m_profiles[SSAO].profile); //Compose m_wrapper->getGPUTimer()->Start(m_profiles[COMPOSE].profile); initComposePass(); m_wrapper->renderComposeStage(); endComposePass(); m_wrapper->getGPUTimer()->Stop(m_profiles[COMPOSE].profile); //Particles m_wrapper->getGPUTimer()->Start(m_profiles[PARTICLE].profile); initParticlePass(); renderParticles(); endParticlePass(); m_wrapper->getGPUTimer()->Stop(m_profiles[PARTICLE].profile); //GUI m_wrapper->getGPUTimer()->Start(m_profiles[GUI].profile); initGUIPass(); m_libRocketRenderSystem->render(); m_antTweakBarSystem->render(); endGUIPass(); m_wrapper->getGPUTimer()->Stop(m_profiles[GUI].profile); flipBackbuffer(); updateTimers(); } void GraphicsRendererSystem::initShadowPass(){ m_wrapper->setRasterizerStateSettings(RasterizerState::FILLED_CW_FRONTCULL); m_wrapper->setBlendStateSettings(BlendState::DEFAULT); //m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST); m_wrapper->setViewportToShadowMapSize(); m_wrapper->setRenderingShadows(); m_wrapper->setShadowViewProjections(m_shadowViewProjections); } void GraphicsRendererSystem::endShadowPass(){ m_wrapper->resetViewportToOriginalSize(); m_wrapper->stopedRenderingShadows(); //m_wrapper->unmapPerShadowBuffer(); } void GraphicsRendererSystem::initMeshPass(){ m_wrapper->mapSceneInfo(); m_wrapper->setRasterizerStateSettings(RasterizerState::DEFAULT); m_wrapper->setBlendStateSettings(BlendState::DEFAULT); //m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST); m_wrapper->clearRenderTargets(); m_wrapper->setBaseRenderTargets(); } void GraphicsRendererSystem::endMeshPass(){ m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST); } void GraphicsRendererSystem::initLightPass(){ m_wrapper->setRasterizerStateSettings( //RasterizerState::WIREFRAME_NOCULL, false); // For debug /ML RasterizerState::FILLED_CW_FRONTCULL, false); m_wrapper->setBlendStateSettings(BlendState::LIGHT); m_wrapper->setLightPassRenderTarget(); //m_wrapper->mapDeferredBaseToShader(); m_wrapper->mapNeededShaderResourceToLightPass(m_activeShadows); } void GraphicsRendererSystem::endLightPass(){ //m_wrapper->setRasterizerStateSettings(RasterizerState::DEFAULT); //m_wrapper->setBlendStateSettings(BlendState::DEFAULT); //m_wrapper->unmapDeferredBaseFromShader(); //m_wrapper->unmapUsedShaderResourceFromLightPass(m_activeShadows); } void GraphicsRendererSystem::beginSsao() { // not used anymore //m_wrapper->mapRandomVecTexture(); m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLESTRIP); m_wrapper->setBlendStateSettings(BlendState::SSAO); m_wrapper->setRasterizerStateSettings( RasterizerState::FILLED_NOCULL_NOCLIP, false); } void GraphicsRendererSystem::endSsao() { m_wrapper->setRasterizerStateSettings(RasterizerState::DEFAULT); m_wrapper->setBlendStateSettings(BlendState::DEFAULT); m_wrapper->unmapDeferredBaseFromShader(); m_wrapper->unmapUsedShaderResourceFromLightPass(m_activeShadows); } void GraphicsRendererSystem::initComposePass() { m_wrapper->setRasterizerStateSettings( RasterizerState::DEFAULT, false); m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLESTRIP); m_wrapper->setComposedRenderTargetWithNoDepthStencil(); m_wrapper->mapVariousStagesForCompose(); } void GraphicsRendererSystem::endComposePass() { m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST); m_wrapper->unmapVariousStagesForCompose(); m_wrapper->unmapDepthFromShader(); } void GraphicsRendererSystem::initParticlePass(){ m_wrapper->setParticleRenderState(); //m_wrapper->setBlendStateSettings(BlendState::PARTICLE); m_wrapper->setBlendStateSettings(BlendState::ADDITIVE); m_wrapper->setPrimitiveTopology(PrimitiveTopology::POINTLIST); } void GraphicsRendererSystem::renderParticles() { // A ugly way to be able to call the different rendering functions. Needs refactoring /ML. ParticleRenderSystem* psRender = static_cast<ParticleRenderSystem*>( m_particleRenderSystem ); for( int i=0; i<AglParticleSystemHeader::AglBlendMode_CNT; i++ ) { for( int j=0; j<AglParticleSystemHeader::AglRasterizerMode_CNT; j++ ) { AglParticleSystemHeader::AglBlendMode blend = (AglParticleSystemHeader::AglBlendMode)i; AglParticleSystemHeader::AglRasterizerMode rast = (AglParticleSystemHeader::AglRasterizerMode)j; m_wrapper->setRasterizerStateSettings( psRender->rasterizerStateFromAglRasterizerMode(rast) ); m_wrapper->setBlendStateSettings( psRender->blendStateFromAglBlendMode(blend) ); psRender->render( blend, rast ); } } } void GraphicsRendererSystem::endParticlePass(){ m_wrapper->setPrimitiveTopology(PrimitiveTopology::TRIANGLELIST); m_wrapper->setBlendStateSettings(BlendState::DEFAULT); m_wrapper->setComposedRenderTargetWithNoDepthStencil(); } void GraphicsRendererSystem::initGUIPass(){ m_wrapper->setBlendStateSettings(BlendState::ALPHA); } void GraphicsRendererSystem::endGUIPass(){ m_wrapper->setBlendStateSettings(BlendState::DEFAULT); } void GraphicsRendererSystem::flipBackbuffer(){ m_wrapper->flipBackBuffer(); } void GraphicsRendererSystem::clearShadowStuf() { for(int i = 0; i < MAXSHADOWS; i++){ m_activeShadows[i] = -1; m_shadowViewProjections[i] = AglMatrix::identityMatrix(); } } void GraphicsRendererSystem::updateTimers() { m_totalTime = 0; GPUTimer* timer = m_wrapper->getGPUTimer(); for(unsigned int i = 0; i < NUMRENDERINGPASSES; i++){ m_profiles[i].renderingTime = timer->getTheTimeAndReset(m_profiles[i].profile); m_totalTime += m_profiles[i].renderingTime; } m_wrapper->getGPUTimer()->tick(); }<|endoftext|>
<commit_before>//===- fpcmp.cpp - A fuzzy "cmp" that permits floating point noise --------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // fpcmp is a tool that basically works like the 'cmp' tool, except that it can // tolerate errors due to floating point noise, with the -r option. // //===----------------------------------------------------------------------===// #include "Support/CommandLine.h" #include "Support/FileUtilities.h" #include "Config/fcntl.h" #include "Config/sys/mman.h" #include <iostream> #include <cmath> using namespace llvm; namespace { cl::opt<std::string> File1(cl::Positional, cl::desc("<input file #1>"), cl::Required); cl::opt<std::string> File2(cl::Positional, cl::desc("<input file #2>"), cl::Required); cl::opt<double> RelTolerance("r", cl::desc("Relative error tolerated"), cl::init(0)); cl::opt<double> AbsTolerance("a", cl::desc("Absolute error tolerated"), cl::init(0)); } /// OpenFile - mmap the specified file into the address space for reading, and /// return the length and address of the buffer. static void OpenFile(const std::string &Filename, unsigned &Len, char* &BufPtr){ int FD = open(Filename.c_str(), O_RDONLY); if (FD == -1 || (Len = getFileSize(Filename)) == ~0U) { std::cerr << "Error: cannot open file '" << Filename << "'\n"; exit(2); } // mmap in the file all at once... BufPtr = (char*)mmap(0, Len, PROT_READ, MAP_PRIVATE, FD, 0); if (BufPtr == (char*)MAP_FAILED) { std::cerr << "Error: cannot open file '" << Filename << "'\n"; exit(2); } // If mmap decided that the files were empty, it might have returned a // null pointer. If so, make a new, fake pointer -- it shouldn't matter // what it contains, because Len is 0, and it should never be read. if (BufPtr == 0 && Len == 0) BufPtr = new char[1]; } static bool isNumberChar(char C) { switch (C) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': case '+': case '-': case 'e': case 'E': return true; default: return false; } } static char *BackupNumber(char *Pos, char *FirstChar) { while (Pos > FirstChar && isNumberChar(Pos[-1])) --Pos; return Pos; } static void CompareNumbers(char *&F1P, char *&F2P, char *F1End, char *F2End) { char *F1NumEnd, *F2NumEnd; double V1 = strtod(F1P, &F1NumEnd); double V2 = strtod(F2P, &F2NumEnd); if (F1NumEnd == F1P || F2NumEnd == F2P) { std::cerr << "Comparison failed, not a numeric difference.\n"; exit(1); } // Check to see if these are inside the absolute tolerance if (AbsTolerance < std::abs(V1-V2)) { // Nope, check the relative tolerance... double Diff; if (V2) Diff = std::abs(V1/V2 - 1.0); else if (V1) Diff = std::abs(V2/V1 - 1.0); else Diff = 0; // Both zero. if (Diff > RelTolerance) { std::cerr << "Compared: " << V1 << " and " << V2 << ": diff = " << Diff << "\n"; std::cerr << "Out of tolerance: rel/abs: " << RelTolerance << "/" << AbsTolerance << "\n"; exit(1); } } // Otherwise, advance our read pointers to the end of the numbers. F1P = F1NumEnd; F2P = F2NumEnd; } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); // mmap in the files. unsigned File1Len, File2Len; char *File1Start, *File2Start; OpenFile(File1, File1Len, File1Start); OpenFile(File2, File2Len, File2Start); // Okay, now that we opened the files, scan them for the first difference. char *File1End = File1Start+File1Len; char *File2End = File2Start+File2Len; char *F1P = File1Start; char *F2P = File2Start; while (1) { // Scan for the end of file or first difference. while (F1P < File1End && F2P < File2End && *F1P == *F2P) ++F1P, ++F2P; if (F1P >= File1End || F2P >= File2End) break; // Okay, we must have found a difference. Backup to the start of the // current number each stream is at so that we can compare from the // beginning. F1P = BackupNumber(F1P, File1Start); F2P = BackupNumber(F2P, File2Start); // Now that we are at the start of the numbers, compare them, exiting if // they don't match. CompareNumbers(F1P, F2P, File1End, File2End); } // Okay, we reached the end of file. If both files are at the end, we // succeeded. if (F1P >= File1End && F2P >= File2End) return 0; // Otherwise, we might have run off the end due to a number, backup and retry. F1P = BackupNumber(F1P, File1Start); F2P = BackupNumber(F2P, File2Start); // Now that we are at the start of the numbers, compare them, exiting if // they don't match. CompareNumbers(F1P, F2P, File1End, File2End); // If we found the end, we succeeded. if (F1P >= File1End && F2P >= File2End) return 0; return 1; } <commit_msg>Use fileutilities instead of mmap directly<commit_after>//===- fpcmp.cpp - A fuzzy "cmp" that permits floating point noise --------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // fpcmp is a tool that basically works like the 'cmp' tool, except that it can // tolerate errors due to floating point noise, with the -r option. // //===----------------------------------------------------------------------===// #include "Support/CommandLine.h" #include "Support/FileUtilities.h" #include "Config/fcntl.h" #include "Config/sys/mman.h" #include <iostream> #include <cmath> using namespace llvm; namespace { cl::opt<std::string> File1(cl::Positional, cl::desc("<input file #1>"), cl::Required); cl::opt<std::string> File2(cl::Positional, cl::desc("<input file #2>"), cl::Required); cl::opt<double> RelTolerance("r", cl::desc("Relative error tolerated"), cl::init(0)); cl::opt<double> AbsTolerance("a", cl::desc("Absolute error tolerated"), cl::init(0)); } /// OpenFile - mmap the specified file into the address space for reading, and /// return the length and address of the buffer. static void OpenFile(const std::string &Filename, unsigned &Len, char* &BufPtr){ BufPtr = (char*)ReadFileIntoAddressSpace(Filename, Len); if (BufPtr == 0) { std::cerr << "Error: cannot open file '" << Filename << "'\n"; exit(2); } } static bool isNumberChar(char C) { switch (C) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '.': case '+': case '-': case 'e': case 'E': return true; default: return false; } } static char *BackupNumber(char *Pos, char *FirstChar) { while (Pos > FirstChar && isNumberChar(Pos[-1])) --Pos; return Pos; } static void CompareNumbers(char *&F1P, char *&F2P, char *F1End, char *F2End) { char *F1NumEnd, *F2NumEnd; double V1 = strtod(F1P, &F1NumEnd); double V2 = strtod(F2P, &F2NumEnd); if (F1NumEnd == F1P || F2NumEnd == F2P) { std::cerr << "Comparison failed, not a numeric difference.\n"; exit(1); } // Check to see if these are inside the absolute tolerance if (AbsTolerance < std::abs(V1-V2)) { // Nope, check the relative tolerance... double Diff; if (V2) Diff = std::abs(V1/V2 - 1.0); else if (V1) Diff = std::abs(V2/V1 - 1.0); else Diff = 0; // Both zero. if (Diff > RelTolerance) { std::cerr << "Compared: " << V1 << " and " << V2 << ": diff = " << Diff << "\n"; std::cerr << "Out of tolerance: rel/abs: " << RelTolerance << "/" << AbsTolerance << "\n"; exit(1); } } // Otherwise, advance our read pointers to the end of the numbers. F1P = F1NumEnd; F2P = F2NumEnd; } int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv); // mmap in the files. unsigned File1Len, File2Len; char *File1Start, *File2Start; OpenFile(File1, File1Len, File1Start); OpenFile(File2, File2Len, File2Start); // Okay, now that we opened the files, scan them for the first difference. char *File1End = File1Start+File1Len; char *File2End = File2Start+File2Len; char *F1P = File1Start; char *F2P = File2Start; while (1) { // Scan for the end of file or first difference. while (F1P < File1End && F2P < File2End && *F1P == *F2P) ++F1P, ++F2P; if (F1P >= File1End || F2P >= File2End) break; // Okay, we must have found a difference. Backup to the start of the // current number each stream is at so that we can compare from the // beginning. F1P = BackupNumber(F1P, File1Start); F2P = BackupNumber(F2P, File2Start); // Now that we are at the start of the numbers, compare them, exiting if // they don't match. CompareNumbers(F1P, F2P, File1End, File2End); } // Okay, we reached the end of file. If both files are at the end, we // succeeded. if (F1P >= File1End && F2P >= File2End) return 0; // Otherwise, we might have run off the end due to a number, backup and retry. F1P = BackupNumber(F1P, File1Start); F2P = BackupNumber(F2P, File2Start); // Now that we are at the start of the numbers, compare them, exiting if // they don't match. CompareNumbers(F1P, F2P, File1End, File2End); // If we found the end, we succeeded. if (F1P >= File1End && F2P >= File2End) return 0; return 1; } <|endoftext|>
<commit_before>#include <string> #include <vector> #include <algorithm> #include <fstream> #include <time.h> using namespace std; // Loads in names of all roommates from the input file into a string vector vector<string> getProblem(const string f) { ifstream input(f); vector<string> answer; for( std::string line; getline( input, line ); ) answer.push_back(line); return answer; } /* Outputs your solution to a text file * The solutions should be a two dimensional vector of names * Each vector inside the solution vector represents a room */ void outputSolutionsToFile(const string & name, const vector< vector<string> > & s) { ofstream output(name + '-' + to_string(time(NULL)) + ".txt"); if(output.is_open()) for(auto a = s.begin(); a != s.end(); a++) for(auto b = a->begin(); b != a->end(); b++) output << *b << ' '; output << '\n'; else throw runtime_error("Couldn't open file"); } int main() { // Get the names of all the roommates and put them in the names vector // Make sure that this code can access the input file // and that the input file is named rm.txt vector<string> names = getProblem("rm.txt"); // Will be a 2-d vector of names. Every vector inside this vector represents a room. vector< vector<string> > solution; // EXAMPLE SOLUTION: put people into rooms of two using their order in the names vector for(int a = 0; a < names.size(); a += 4) { vector<string> room; room.push_back(names[a]); room.push_back(names[a+1]); room.push_back(names[a+2]); room.push_back(names[a+3]); solution.push_back(room); } outputSolutionsToFile("PUT YOUR NAME HERE", solution); return EXIT_SUCCESS; } <commit_msg>Revert "Fixed Formatting"<commit_after>#include <string> #include <vector> #include <algorithm> #include <fstream> #include <time.h> using namespace std; // Loads in names of all roommates from the input file into a string vector vector<string> getProblem(const string f) { ifstream input(f); vector<string> answer; for( std::string line; getline( input, line ); ) { answer.push_back(line); } return answer; } /* Outputs your solution to a text file * The solutions should be a two dimensional vector of names * Each vector inside the solution vector represents a room */ void outputSolutionsToFile(const string & name, const vector< vector<string> > & s) { ofstream output(name + '-' + to_string(time(NULL)) + ".txt"); if(output.is_open()) for(auto a = s.begin(); a != s.end(); a++) { for(auto b = a->begin(); b != a->end(); b++) output << *b << ' '; output << '\n'; } else throw runtime_error("Couldn't open file"); } int main() { // Get the names of all the roommates and put them in the names vector // Make sure that this code can access the input file // and that the input file is named rm.txt vector<string> names = getProblem("rm.txt"); // Will be a 2-d vector of names. Every vector inside this vector represents a room. vector< vector<string> > solution; // EXAMPLE SOLUTION: put people into rooms of two using their order in the names vector for(int a = 0; a < names.size(); a += 4) { vector<string> room; room.push_back(names[a]); room.push_back(names[a+1]); room.push_back(names[a+2]); room.push_back(names[a+3]); solution.push_back(room); } outputSolutionsToFile("PUT YOUR NAME HERE", solution); return EXIT_SUCCESS; }<|endoftext|>
<commit_before>/* This file is part of Kontact. Copyright (c) 2003 Tobias Koenig <tokoe@kde.org> Copyright (c) 2005-2006 Allen Winter <winter@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "todosummarywidget.h" #include "todoplugin.h" #include "korganizerinterface.h" #include <korganizer/stdcalendar.h> #include <korganizer/koglobals.h> #include <korganizer/incidencechanger.h> #include <kontactinterfaces/core.h> #include <libkdepim/kpimprefs.h> #include <kcal/calendar.h> #include <kcal/resourcecalendar.h> #include <kcal/resourcelocal.h> #include <kcal/todo.h> #include <kcal/incidenceformatter.h> #include <kdialog.h> #include <kglobal.h> #include <kicon.h> #include <kiconloader.h> #include <klocale.h> #include <kmenu.h> #include <kstandarddirs.h> #include <kurllabel.h> #include <kparts/part.h> #include <QCursor> #include <QEvent> #include <QGridLayout> #include <QLabel> #include <QLayout> #include <QPixmap> #include <QVBoxLayout> TodoSummaryWidget::TodoSummaryWidget( TodoPlugin *plugin, QWidget *parent ) : Kontact::Summary( parent ), mPlugin( plugin ) { QVBoxLayout *mainLayout = new QVBoxLayout( this ); mainLayout->setSpacing( 3 ); mainLayout->setMargin( 3 ); QWidget *header = createHeader( this, "view-pim-tasks", i18n( "Pending To-dos" ) ); mainLayout->addWidget( header ); mLayout = new QGridLayout(); mainLayout->addItem( mLayout ); mLayout->setSpacing( 3 ); mLayout->setRowStretch( 6, 1 ); mCalendar = KOrg::StdCalendar::self(); mCalendar->load(); connect( mCalendar, SIGNAL(calendarChanged()), SLOT(updateView()) ); connect( mPlugin->core(), SIGNAL(dayChanged(const QDate&)), SLOT(updateView()) ); updateView(); } TodoSummaryWidget::~TodoSummaryWidget() { } void TodoSummaryWidget::updateView() { qDeleteAll( mLabels ); mLabels.clear(); KConfig _config( "kcmtodosummaryrc" ); KConfigGroup config( &_config, "Days" ); int mDaysToGo = config.readEntry( "DaysToShow", 7 ); config.changeGroup( "Hide" ); mHideInProgress = config.readEntry( "InProgress", false ); mHideOverdue = config.readEntry( "Overdue", false ); mHideCompleted = config.readEntry( "Completed", true ); mHideOpenEnded = config.readEntry( "OpenEnded", true ); mHideNotStarted = config.readEntry( "NotStarted", false ); // for each todo, // if it passes the filter, append to a list // else continue // sort todolist by summary // sort todolist by priority // sort todolist by due-date // print todolist // the filter is created by the configuration summary options, but includes // days to go before to-do is due // which types of to-dos to hide KCal::Todo::List prList; Q_FOREACH ( KCal::Todo *todo, mCalendar->todos() ) { if ( todo->hasDueDate() ) { int daysTo = QDate::currentDate().daysTo( todo->dtDue().date() ); if ( daysTo >= mDaysToGo ) { continue; } } if ( mHideOverdue && overdue( todo ) ) { continue; } if ( mHideInProgress && inProgress( todo ) ) { continue; } if ( mHideCompleted && completed( todo ) ) { continue; } if ( mHideOpenEnded && openEnded( todo ) ) { continue; } if ( mHideNotStarted && notStarted( todo ) ) { continue; } prList.append( todo ); } if ( !prList.isEmpty() ) { prList = KCal::Calendar::sortTodos( &prList, KCal::TodoSortSummary, KCal::SortDirectionAscending ); prList = KCal::Calendar::sortTodos( &prList, KCal::TodoSortPriority, KCal::SortDirectionAscending ); prList = KCal::Calendar::sortTodos( &prList, KCal::TodoSortDueDate, KCal::SortDirectionAscending ); } // The to-do print consists of the following fields: // icon:due date:days-to-go:priority:summary:status // where, // the icon is the typical to-do icon // the due date it the to-do due date // the days-to-go/past is the #days until/since the to-do is due // this field is left blank if the to-do is open-ended // the priority is the to-do priority // the summary is the to-do summary // the status is comma-separated list of: // overdue // in-progress (started, or >0% completed) // complete (100% completed) // open-ended // not-started (no start date and 0% completed) // No reason to show the date year QString savefmt = KGlobal::locale()->dateFormat(); KGlobal::locale()->setDateFormat( KGlobal::locale()-> dateFormat().replace( 'Y', ' ' ) ); int counter = 0; QLabel *label = 0; if ( !prList.isEmpty() ) { KIconLoader loader( "korganizer" ); QPixmap pm = loader.loadIcon( "view-calendar-tasks", KIconLoader::Small ); QString str; Q_FOREACH ( KCal::Todo *todo, prList ) { bool makeBold = false; int daysTo = -1; // Icon label label = new QLabel( this ); label->setPixmap( pm ); label->setMaximumWidth( label->minimumSizeHint().width() ); mLayout->addWidget( label, counter, 0 ); mLabels.append( label ); // Due date label str = ""; if ( todo->hasDueDate() && todo->dtDue().date().isValid() ) { daysTo = QDate::currentDate().daysTo( todo->dtDue().date() ); if ( daysTo == 0 ) { makeBold = true; str = i18n( "Today" ); } else if ( daysTo == 1 ) { str = i18n( "Tomorrow" ); } else { str = KGlobal::locale()->formatDate( todo->dtDue().date() ); } } label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 1 ); mLabels.append( label ); if ( makeBold ) { QFont font = label->font(); font.setBold( true ); label->setFont( font ); } // Days togo/ago label str = ""; if ( todo->hasDueDate() && todo->dtDue().date().isValid() ) { if ( daysTo > 0 ) { str = i18np( "in 1 day", "in %1 days", daysTo ); } else if ( daysTo < 0 ) { str = i18np( "1 day ago", "%1 days ago", -daysTo ); } else { str = i18n( "due" ); } } label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 2 ); mLabels.append( label ); // Priority label str = '[' + QString::number( todo->priority() ) + ']'; label = new QLabel( str, this ); label->setAlignment( Qt::AlignRight | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 3 ); mLabels.append( label ); // Summary label str = todo->summary(); if ( todo->relatedTo() ) { // show parent only, not entire ancestry str = todo->relatedTo()->summary() + ':' + str; } KUrlLabel *urlLabel = new KUrlLabel( this ); urlLabel->setText( str ); urlLabel->setUrl( todo->uid() ); urlLabel->installEventFilter( this ); urlLabel->setTextFormat( Qt::RichText ); mLayout->addWidget( urlLabel, counter, 4 ); mLabels.append( urlLabel ); connect( urlLabel, SIGNAL(leftClickedUrl(const QString&)), this, SLOT(viewTodo(const QString&)) ); connect( urlLabel, SIGNAL(rightClickedUrl(const QString&)), this, SLOT(popupMenu(const QString&)) ); QString tipText( KCal::IncidenceFormatter::toolTipString( todo, true ) ); if ( !tipText.isEmpty() ) { urlLabel->setToolTip( tipText ); } // State text label str = stateStr( todo ); label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 5 ); mLabels.append( label ); counter++; } } //foreach if ( counter == 0 ) { QLabel *noTodos = new QLabel( i18np( "No pending to-dos due within the next day", "No pending to-dos due within the next %1 days", mDaysToGo ), this ); noTodos->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter ); mLayout->addWidget( noTodos, 0, 2 ); mLabels.append( noTodos ); } Q_FOREACH( label, mLabels ) { label->show(); } KGlobal::locale()->setDateFormat( savefmt ); } void TodoSummaryWidget::viewTodo( const QString &uid ) { mPlugin->core()->selectPlugin( "kontact_todoplugin" );//ensure loaded OrgKdeKorganizerKorganizerInterface korganizer( "org.kde.korganizer", "/Korganizer", QDBusConnection::sessionBus() ); korganizer.editIncidence( uid ); } void TodoSummaryWidget::removeTodo( const QString &uid ) { mPlugin->core()->selectPlugin( "kontact_todoplugin" );//ensure loaded OrgKdeKorganizerKorganizerInterface korganizer( "org.kde.korganizer", "/Korganizer", QDBusConnection::sessionBus() ); korganizer.deleteIncidence( uid, false ); } void TodoSummaryWidget::completeTodo( const QString &uid ) { KCal::Todo *todo = mCalendar->todo( uid ); IncidenceChanger *changer = new IncidenceChanger( mCalendar, this ); if ( !todo->isReadOnly() && changer->beginChange( todo ) ) { KCal::Todo *oldTodo = todo->clone(); todo->setCompleted( KDateTime::currentLocalDateTime() ); changer->changeIncidence( oldTodo, todo, KOGlobals::COMPLETION_MODIFIED ); changer->endChange( todo ); delete oldTodo; updateView(); } } void TodoSummaryWidget::popupMenu( const QString &uid ) { KMenu popup( this ); QAction *editIt = popup.addAction( i18n( "&Edit To-do..." ) ); QAction *delIt = popup.addAction( i18n( "&Delete To-do" ) ); delIt->setIcon( KIconLoader::global()->loadIcon( "edit-delete", KIconLoader::Small ) ); QAction *doneIt = 0; KCal::Todo *todo = mCalendar->todo( uid ); if ( !todo->isCompleted() ) { doneIt = popup.addAction( i18n( "&Mark To-do Completed" ) ); doneIt->setIcon( KIconLoader::global()->loadIcon( "task-complete", KIconLoader::Small ) ); } // TODO: add icons to the menu actions const QAction *selectedAction = popup.exec( QCursor::pos() ); if ( selectedAction == editIt ) { viewTodo( uid ); } else if ( selectedAction == delIt ) { removeTodo( uid ); } else if ( doneIt && selectedAction == doneIt ) { completeTodo( uid ); } } bool TodoSummaryWidget::eventFilter( QObject *obj, QEvent *e ) { if ( obj->inherits( "KUrlLabel" ) ) { KUrlLabel* label = static_cast<KUrlLabel*>( obj ); if ( e->type() == QEvent::Enter ) { emit message( i18n( "Edit To-do: \"%1\"", label->text() ) ); } if ( e->type() == QEvent::Leave ) { emit message( QString::null ); //krazy:exclude=nullstrassign for old broken gcc } } return Kontact::Summary::eventFilter( obj, e ); } QStringList TodoSummaryWidget::configModules() const { return QStringList( "kcmtodosummary.desktop" ); } bool TodoSummaryWidget::overdue( KCal::Todo *todo ) { if ( todo->hasDueDate() && !todo->isCompleted() && todo->dtDue().date() < QDate::currentDate() ) { return true; } return false; } bool TodoSummaryWidget::starts( KCal::Todo *todo ) { if ( todo->hasStartDate() && todo->dtStart().date() == QDate::currentDate() ) { return true; } return false; } bool TodoSummaryWidget::completed( KCal::Todo *todo ) { return todo->isCompleted(); } bool TodoSummaryWidget::openEnded( KCal::Todo *todo ) { if ( !todo->hasDueDate() && !todo->isCompleted() ) { return true; } return false; } bool TodoSummaryWidget::inProgress( KCal::Todo *todo ) { if ( todo->percentComplete() > 0 ) { return true; } if ( todo->hasStartDate() && todo->hasDueDate() && todo->dtStart().date() < QDate::currentDate() && QDate::currentDate() < todo->dtDue().date() ) { return true; } return false; } bool TodoSummaryWidget::notStarted( KCal::Todo *todo ) { if ( todo->percentComplete() > 0 ) { return false; } if ( !todo->hasStartDate() ) { return false; } if ( todo->dtStart().date() >= QDate::currentDate() ) { return false; } return true; } const QString TodoSummaryWidget::stateStr( KCal::Todo *todo ) { QString str1, str2; if ( openEnded( todo ) ) { str1 = i18n( "open-ended" ); } else if ( overdue( todo ) ) { str1 = i18n( "overdue" ); } else if ( starts( todo ) ) { str1 = i18n( "starts today" ); } if ( notStarted( todo ) ) { str2 += i18n( "not-started" ); } else if ( completed( todo ) ) { str2 += i18n( "completed" ); } else if ( inProgress( todo ) ) { str2 += i18n( "in-progress " ); str2 += " (" + QString::number( todo->percentComplete() ) + "%)"; } if ( !str1.isEmpty() && !str2.isEmpty() ) { str1 += i18nc( "Separator for status like this: overdue, completed", "," ); } return str1 + str2; } #include "todosummarywidget.moc" <commit_msg>escape <,>,& in non-richtext summaries BUGS: 146670<commit_after>/* This file is part of Kontact. Copyright (c) 2003 Tobias Koenig <tokoe@kde.org> Copyright (c) 2005-2006,2008 Allen Winter <winter@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "todosummarywidget.h" #include "todoplugin.h" #include "korganizerinterface.h" #include <korganizer/stdcalendar.h> #include <korganizer/koglobals.h> #include <korganizer/incidencechanger.h> #include <kontactinterfaces/core.h> #include <libkdepim/kpimprefs.h> #include <kcal/calendar.h> #include <kcal/resourcecalendar.h> #include <kcal/resourcelocal.h> #include <kcal/todo.h> #include <kcal/incidenceformatter.h> #include <kdialog.h> #include <kglobal.h> #include <kicon.h> #include <kiconloader.h> #include <klocale.h> #include <kmenu.h> #include <kstandarddirs.h> #include <kurllabel.h> #include <kparts/part.h> #include <QCursor> #include <QEvent> #include <QGridLayout> #include <QLabel> #include <QLayout> #include <QPixmap> #include <QVBoxLayout> #include <QTextDocument> TodoSummaryWidget::TodoSummaryWidget( TodoPlugin *plugin, QWidget *parent ) : Kontact::Summary( parent ), mPlugin( plugin ) { QVBoxLayout *mainLayout = new QVBoxLayout( this ); mainLayout->setSpacing( 3 ); mainLayout->setMargin( 3 ); QWidget *header = createHeader( this, "view-pim-tasks", i18n( "Pending To-dos" ) ); mainLayout->addWidget( header ); mLayout = new QGridLayout(); mainLayout->addItem( mLayout ); mLayout->setSpacing( 3 ); mLayout->setRowStretch( 6, 1 ); mCalendar = KOrg::StdCalendar::self(); mCalendar->load(); connect( mCalendar, SIGNAL(calendarChanged()), SLOT(updateView()) ); connect( mPlugin->core(), SIGNAL(dayChanged(const QDate&)), SLOT(updateView()) ); updateView(); } TodoSummaryWidget::~TodoSummaryWidget() { } void TodoSummaryWidget::updateView() { qDeleteAll( mLabels ); mLabels.clear(); KConfig _config( "kcmtodosummaryrc" ); KConfigGroup config( &_config, "Days" ); int mDaysToGo = config.readEntry( "DaysToShow", 7 ); config.changeGroup( "Hide" ); mHideInProgress = config.readEntry( "InProgress", false ); mHideOverdue = config.readEntry( "Overdue", false ); mHideCompleted = config.readEntry( "Completed", true ); mHideOpenEnded = config.readEntry( "OpenEnded", true ); mHideNotStarted = config.readEntry( "NotStarted", false ); // for each todo, // if it passes the filter, append to a list // else continue // sort todolist by summary // sort todolist by priority // sort todolist by due-date // print todolist // the filter is created by the configuration summary options, but includes // days to go before to-do is due // which types of to-dos to hide KCal::Todo::List prList; Q_FOREACH ( KCal::Todo *todo, mCalendar->todos() ) { if ( todo->hasDueDate() ) { int daysTo = QDate::currentDate().daysTo( todo->dtDue().date() ); if ( daysTo >= mDaysToGo ) { continue; } } if ( mHideOverdue && overdue( todo ) ) { continue; } if ( mHideInProgress && inProgress( todo ) ) { continue; } if ( mHideCompleted && completed( todo ) ) { continue; } if ( mHideOpenEnded && openEnded( todo ) ) { continue; } if ( mHideNotStarted && notStarted( todo ) ) { continue; } prList.append( todo ); } if ( !prList.isEmpty() ) { prList = KCal::Calendar::sortTodos( &prList, KCal::TodoSortSummary, KCal::SortDirectionAscending ); prList = KCal::Calendar::sortTodos( &prList, KCal::TodoSortPriority, KCal::SortDirectionAscending ); prList = KCal::Calendar::sortTodos( &prList, KCal::TodoSortDueDate, KCal::SortDirectionAscending ); } // The to-do print consists of the following fields: // icon:due date:days-to-go:priority:summary:status // where, // the icon is the typical to-do icon // the due date it the to-do due date // the days-to-go/past is the #days until/since the to-do is due // this field is left blank if the to-do is open-ended // the priority is the to-do priority // the summary is the to-do summary // the status is comma-separated list of: // overdue // in-progress (started, or >0% completed) // complete (100% completed) // open-ended // not-started (no start date and 0% completed) // No reason to show the date year QString savefmt = KGlobal::locale()->dateFormat(); KGlobal::locale()->setDateFormat( KGlobal::locale()-> dateFormat().replace( 'Y', ' ' ) ); int counter = 0; QLabel *label = 0; if ( !prList.isEmpty() ) { KIconLoader loader( "korganizer" ); QPixmap pm = loader.loadIcon( "view-calendar-tasks", KIconLoader::Small ); QString str; Q_FOREACH ( KCal::Todo *todo, prList ) { bool makeBold = false; int daysTo = -1; // Icon label label = new QLabel( this ); label->setPixmap( pm ); label->setMaximumWidth( label->minimumSizeHint().width() ); mLayout->addWidget( label, counter, 0 ); mLabels.append( label ); // Due date label str = ""; if ( todo->hasDueDate() && todo->dtDue().date().isValid() ) { daysTo = QDate::currentDate().daysTo( todo->dtDue().date() ); if ( daysTo == 0 ) { makeBold = true; str = i18n( "Today" ); } else if ( daysTo == 1 ) { str = i18n( "Tomorrow" ); } else { str = KGlobal::locale()->formatDate( todo->dtDue().date() ); } } label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 1 ); mLabels.append( label ); if ( makeBold ) { QFont font = label->font(); font.setBold( true ); label->setFont( font ); } // Days togo/ago label str = ""; if ( todo->hasDueDate() && todo->dtDue().date().isValid() ) { if ( daysTo > 0 ) { str = i18np( "in 1 day", "in %1 days", daysTo ); } else if ( daysTo < 0 ) { str = i18np( "1 day ago", "%1 days ago", -daysTo ); } else { str = i18n( "due" ); } } label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 2 ); mLabels.append( label ); // Priority label str = '[' + QString::number( todo->priority() ) + ']'; label = new QLabel( str, this ); label->setAlignment( Qt::AlignRight | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 3 ); mLabels.append( label ); // Summary label str = todo->summary(); if ( todo->relatedTo() ) { // show parent only, not entire ancestry str = todo->relatedTo()->summary() + ':' + str; } if ( !Qt::mightBeRichText( str ) ) { str = Qt::escape( str ); } KUrlLabel *urlLabel = new KUrlLabel( this ); urlLabel->setText( str ); urlLabel->setUrl( todo->uid() ); urlLabel->installEventFilter( this ); urlLabel->setTextFormat( Qt::RichText ); mLayout->addWidget( urlLabel, counter, 4 ); mLabels.append( urlLabel ); connect( urlLabel, SIGNAL(leftClickedUrl(const QString&)), this, SLOT(viewTodo(const QString&)) ); connect( urlLabel, SIGNAL(rightClickedUrl(const QString&)), this, SLOT(popupMenu(const QString&)) ); QString tipText( KCal::IncidenceFormatter::toolTipString( todo, true ) ); if ( !tipText.isEmpty() ) { urlLabel->setToolTip( tipText ); } // State text label str = stateStr( todo ); label = new QLabel( str, this ); label->setAlignment( Qt::AlignLeft | Qt::AlignVCenter ); mLayout->addWidget( label, counter, 5 ); mLabels.append( label ); counter++; } } //foreach if ( counter == 0 ) { QLabel *noTodos = new QLabel( i18np( "No pending to-dos due within the next day", "No pending to-dos due within the next %1 days", mDaysToGo ), this ); noTodos->setAlignment( Qt::AlignHCenter | Qt::AlignVCenter ); mLayout->addWidget( noTodos, 0, 2 ); mLabels.append( noTodos ); } Q_FOREACH( label, mLabels ) { label->show(); } KGlobal::locale()->setDateFormat( savefmt ); } void TodoSummaryWidget::viewTodo( const QString &uid ) { mPlugin->core()->selectPlugin( "kontact_todoplugin" );//ensure loaded OrgKdeKorganizerKorganizerInterface korganizer( "org.kde.korganizer", "/Korganizer", QDBusConnection::sessionBus() ); korganizer.editIncidence( uid ); } void TodoSummaryWidget::removeTodo( const QString &uid ) { mPlugin->core()->selectPlugin( "kontact_todoplugin" );//ensure loaded OrgKdeKorganizerKorganizerInterface korganizer( "org.kde.korganizer", "/Korganizer", QDBusConnection::sessionBus() ); korganizer.deleteIncidence( uid, false ); } void TodoSummaryWidget::completeTodo( const QString &uid ) { KCal::Todo *todo = mCalendar->todo( uid ); IncidenceChanger *changer = new IncidenceChanger( mCalendar, this ); if ( !todo->isReadOnly() && changer->beginChange( todo ) ) { KCal::Todo *oldTodo = todo->clone(); todo->setCompleted( KDateTime::currentLocalDateTime() ); changer->changeIncidence( oldTodo, todo, KOGlobals::COMPLETION_MODIFIED ); changer->endChange( todo ); delete oldTodo; updateView(); } } void TodoSummaryWidget::popupMenu( const QString &uid ) { KMenu popup( this ); QAction *editIt = popup.addAction( i18n( "&Edit To-do..." ) ); QAction *delIt = popup.addAction( i18n( "&Delete To-do" ) ); delIt->setIcon( KIconLoader::global()->loadIcon( "edit-delete", KIconLoader::Small ) ); QAction *doneIt = 0; KCal::Todo *todo = mCalendar->todo( uid ); if ( !todo->isCompleted() ) { doneIt = popup.addAction( i18n( "&Mark To-do Completed" ) ); doneIt->setIcon( KIconLoader::global()->loadIcon( "task-complete", KIconLoader::Small ) ); } // TODO: add icons to the menu actions const QAction *selectedAction = popup.exec( QCursor::pos() ); if ( selectedAction == editIt ) { viewTodo( uid ); } else if ( selectedAction == delIt ) { removeTodo( uid ); } else if ( doneIt && selectedAction == doneIt ) { completeTodo( uid ); } } bool TodoSummaryWidget::eventFilter( QObject *obj, QEvent *e ) { if ( obj->inherits( "KUrlLabel" ) ) { KUrlLabel* label = static_cast<KUrlLabel*>( obj ); if ( e->type() == QEvent::Enter ) { emit message( i18n( "Edit To-do: \"%1\"", label->text() ) ); } if ( e->type() == QEvent::Leave ) { emit message( QString::null ); //krazy:exclude=nullstrassign for old broken gcc } } return Kontact::Summary::eventFilter( obj, e ); } QStringList TodoSummaryWidget::configModules() const { return QStringList( "kcmtodosummary.desktop" ); } bool TodoSummaryWidget::overdue( KCal::Todo *todo ) { if ( todo->hasDueDate() && !todo->isCompleted() && todo->dtDue().date() < QDate::currentDate() ) { return true; } return false; } bool TodoSummaryWidget::starts( KCal::Todo *todo ) { if ( todo->hasStartDate() && todo->dtStart().date() == QDate::currentDate() ) { return true; } return false; } bool TodoSummaryWidget::completed( KCal::Todo *todo ) { return todo->isCompleted(); } bool TodoSummaryWidget::openEnded( KCal::Todo *todo ) { if ( !todo->hasDueDate() && !todo->isCompleted() ) { return true; } return false; } bool TodoSummaryWidget::inProgress( KCal::Todo *todo ) { if ( todo->percentComplete() > 0 ) { return true; } if ( todo->hasStartDate() && todo->hasDueDate() && todo->dtStart().date() < QDate::currentDate() && QDate::currentDate() < todo->dtDue().date() ) { return true; } return false; } bool TodoSummaryWidget::notStarted( KCal::Todo *todo ) { if ( todo->percentComplete() > 0 ) { return false; } if ( !todo->hasStartDate() ) { return false; } if ( todo->dtStart().date() >= QDate::currentDate() ) { return false; } return true; } const QString TodoSummaryWidget::stateStr( KCal::Todo *todo ) { QString str1, str2; if ( openEnded( todo ) ) { str1 = i18n( "open-ended" ); } else if ( overdue( todo ) ) { str1 = i18n( "overdue" ); } else if ( starts( todo ) ) { str1 = i18n( "starts today" ); } if ( notStarted( todo ) ) { str2 += i18n( "not-started" ); } else if ( completed( todo ) ) { str2 += i18n( "completed" ); } else if ( inProgress( todo ) ) { str2 += i18n( "in-progress " ); str2 += " (" + QString::number( todo->percentComplete() ) + "%)"; } if ( !str1.isEmpty() && !str2.isEmpty() ) { str1 += i18nc( "Separator for status like this: overdue, completed", "," ); } return str1 + str2; } #include "todosummarywidget.moc" <|endoftext|>
<commit_before>#include <boost/test/unit_test.hpp> //This header includes the default definitions of ports #include <flexcore/ports.hpp> // This Header includes the code for multiplexing streams. #include <flexcore/pure/mux_ports.hpp> // This header includes several useful connectables. #include <flexcore/core/connectables.hpp> // This header includes the algorithms which work on ranges. #include <flexcore/range/actions.hpp> #include <flexcore/extended/nodes/terminal.hpp> #include <flexcore/extended/nodes/buffer.hpp> #include <flexcore/pure/pure_node.hpp> // We need to pull operator >> of flexcore to our local namespace. // Otherwise the operator cannot be found if we connect elements, // which are not from the flexcore namespace. using fc::operator>>; BOOST_AUTO_TEST_SUITE(examples) // This test shows how to send events between nodes in flexcore. BOOST_AUTO_TEST_CASE(events_example) { // in this example we don't use the full extended infrastructure. // Nodes and ports from the pure namespace have no notion of parallel region. // Ownership of these nodes can and has to be managed manually. // Terminal nodes just forward all data and do no computations at all. fc::event_terminal<int, fc::pure::pure_node> source; //Hold last stores the last event received and provides it as state. fc::hold_last<int, fc::pure::pure_node> sink{0}; //connections can be chained // with as many lambdas or other connectables in between as we want. source.out() >> fc::increment >> [](int i){ return i * 10; } >> sink.in(); // we can call event sinks with their operator() to send inputs. source.in()(0); BOOST_CHECK_EQUAL(sink.out()(), 10); fc::event_terminal<int, fc::pure::pure_node> source_2; // an event_sink can be connected to more than one source // it will receive tokens from all sources, when they fire events. source_2.out() >> sink.in(); source.in()(42); BOOST_CHECK_EQUAL(sink.out()(), (42+1)*10); source_2.in()(42); BOOST_CHECK_EQUAL(sink.out()(), 42); fc::hold_last<int, fc::pure::pure_node> sink_2{0}; // an event source can be connected to more than one sink // it will send tokens to all sinks, when it fires events. source_2.out() >> sink_2.in(); source_2.in()(666); BOOST_CHECK_EQUAL(sink.out()(), 666); BOOST_CHECK_EQUAL(sink_2.out()(), 666); } // This test shows how to transmit states between nodes. // See tests/nodes/test_state_nodes for uses of several nodes which operate on states. BOOST_AUTO_TEST_CASE(state_example) { // in this example we don't use the full extended infrastructure. // Nodes and ports from the pure namespace have no notion of parallel region. // Ownership of these nodes can and has to be managed manually. fc::state_terminal<int, fc::pure::pure_node> source; fc::state_terminal<int, fc::pure::pure_node> sink; //provide a constant state as inputs to our node fc::constant(42) >> source.in(); // this simple chain increments all data from our source // and makes them available to our sink source.out() >> fc::increment >> sink.in(); //every time we pull data from our sink we get the result from the chain. BOOST_CHECK_EQUAL(sink.out()(), 42 +1); fc::state_terminal<int, fc::pure::pure_node> sink_2; // a state source an be connected to more than one state sink // each sink is able to pull the tokens separately. // Calculations within the chain might be done twice. source.out() >> sink_2.in(); BOOST_CHECK_EQUAL(sink_2.out()(), 42); // Every State sink can only pull from a single source. // this the following line would overwrite the previous connection to source //fc::constant(2) >> source.in() } // This test shows the mechanics flexcore provides to operator on ranges and lists of values. BOOST_AUTO_TEST_CASE(range_example) { std::vector<int> vec {-4, -3, -2, -1, 0, 1, 2, 3, 4}; fc::pure::state_source<std::vector<int>> source(fc::constant(vec)); fc::pure::state_sink<int> sink; source // This filters the source range and only lets the elements smaller than zero through >> fc::actions::filter([](int i){ return i < 0;}) // This multiplies every element in the filtered range by two >> fc::actions::map([](int i){ return i*2;}) // this sums all elements up and starts with zero. >> fc::sum(0) >> sink; BOOST_CHECK_EQUAL(sink.get(), -20); } // This test shows how to use the mux mechanic to combine streams. // See tests/extended/ports/test/mux_ports.cpp for more uses of mux. BOOST_AUTO_TEST_CASE(mux_example) { //use the shortcut for a passive source, which provides a constant value. auto source_1 = fc::constant(1.234); auto source_2 = fc::constant(5.678); fc::pure::state_sink<double> sink; //mux creates a multiplexed connectable from the two sources. fc::mux(source_1, source_2) // connectables in a multiplexed connection // are applied to all of the multiplexed streams. >> [](double in){ return in * -1;} // this merges the multiplex streams to one stream // in this case it adds the values from the to streams >> fc::merge([](auto a, auto b) { return a + b; }) >> sink; BOOST_CHECK_EQUAL(sink.get(), -1.234 - 5.678); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>Add example tag to examples for doxygen page<commit_after>#include <boost/test/unit_test.hpp> ///\example examples.cpp //This header includes the default definitions of ports #include <flexcore/ports.hpp> // This Header includes the code for multiplexing streams. #include <flexcore/pure/mux_ports.hpp> // This header includes several useful connectables. #include <flexcore/core/connectables.hpp> // This header includes the algorithms which work on ranges. #include <flexcore/range/actions.hpp> #include <flexcore/extended/nodes/terminal.hpp> #include <flexcore/extended/nodes/buffer.hpp> #include <flexcore/pure/pure_node.hpp> // We need to pull operator >> of flexcore to our local namespace. // Otherwise the operator cannot be found if we connect elements, // which are not from the flexcore namespace. using fc::operator>>; BOOST_AUTO_TEST_SUITE(examples) // This test shows how to send events between nodes in flexcore. BOOST_AUTO_TEST_CASE(events_example) { // in this example we don't use the full extended infrastructure. // Nodes and ports from the pure namespace have no notion of parallel region. // Ownership of these nodes can and has to be managed manually. // Terminal nodes just forward all data and do no computations at all. fc::event_terminal<int, fc::pure::pure_node> source; //Hold last stores the last event received and provides it as state. fc::hold_last<int, fc::pure::pure_node> sink{0}; //connections can be chained // with as many lambdas or other connectables in between as we want. source.out() >> fc::increment >> [](int i){ return i * 10; } >> sink.in(); // we can call event sinks with their operator() to send inputs. source.in()(0); BOOST_CHECK_EQUAL(sink.out()(), 10); fc::event_terminal<int, fc::pure::pure_node> source_2; // an event_sink can be connected to more than one source // it will receive tokens from all sources, when they fire events. source_2.out() >> sink.in(); source.in()(42); BOOST_CHECK_EQUAL(sink.out()(), (42+1)*10); source_2.in()(42); BOOST_CHECK_EQUAL(sink.out()(), 42); fc::hold_last<int, fc::pure::pure_node> sink_2{0}; // an event source can be connected to more than one sink // it will send tokens to all sinks, when it fires events. source_2.out() >> sink_2.in(); source_2.in()(666); BOOST_CHECK_EQUAL(sink.out()(), 666); BOOST_CHECK_EQUAL(sink_2.out()(), 666); } // This test shows how to transmit states between nodes. // See tests/nodes/test_state_nodes for uses of several nodes which operate on states. BOOST_AUTO_TEST_CASE(state_example) { // in this example we don't use the full extended infrastructure. // Nodes and ports from the pure namespace have no notion of parallel region. // Ownership of these nodes can and has to be managed manually. fc::state_terminal<int, fc::pure::pure_node> source; fc::state_terminal<int, fc::pure::pure_node> sink; //provide a constant state as inputs to our node fc::constant(42) >> source.in(); // this simple chain increments all data from our source // and makes them available to our sink source.out() >> fc::increment >> sink.in(); //every time we pull data from our sink we get the result from the chain. BOOST_CHECK_EQUAL(sink.out()(), 42 +1); fc::state_terminal<int, fc::pure::pure_node> sink_2; // a state source an be connected to more than one state sink // each sink is able to pull the tokens separately. // Calculations within the chain might be done twice. source.out() >> sink_2.in(); BOOST_CHECK_EQUAL(sink_2.out()(), 42); // Every State sink can only pull from a single source. // this the following line would overwrite the previous connection to source //fc::constant(2) >> source.in() } // This test shows the mechanics flexcore provides to operator on ranges and lists of values. BOOST_AUTO_TEST_CASE(range_example) { std::vector<int> vec {-4, -3, -2, -1, 0, 1, 2, 3, 4}; fc::pure::state_source<std::vector<int>> source(fc::constant(vec)); fc::pure::state_sink<int> sink; source // This filters the source range and only lets the elements smaller than zero through >> fc::actions::filter([](int i){ return i < 0;}) // This multiplies every element in the filtered range by two >> fc::actions::map([](int i){ return i*2;}) // this sums all elements up and starts with zero. >> fc::sum(0) >> sink; BOOST_CHECK_EQUAL(sink.get(), -20); } // This test shows how to use the mux mechanic to combine streams. // See tests/extended/ports/test/mux_ports.cpp for more uses of mux. BOOST_AUTO_TEST_CASE(mux_example) { //use the shortcut for a passive source, which provides a constant value. auto source_1 = fc::constant(1.234); auto source_2 = fc::constant(5.678); fc::pure::state_sink<double> sink; //mux creates a multiplexed connectable from the two sources. fc::mux(source_1, source_2) // connectables in a multiplexed connection // are applied to all of the multiplexed streams. >> [](double in){ return in * -1;} // this merges the multiplex streams to one stream // in this case it adds the values from the to streams >> fc::merge([](auto a, auto b) { return a + b; }) >> sink; BOOST_CHECK_EQUAL(sink.get(), -1.234 - 5.678); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/* Copyright(c) 2016-2017 Panos Karabelas 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. */ //= INCLUDES ==================== #include "Hierarchy.h" #include "../imgui/imgui.h" #include "Scene/Scene.h" #include "Scene/GameObject.h" #include "Components/Transform.h" #include "Core/Engine.h" //=============================== //= NAMESPACES ========== using namespace std; using namespace Directus; //======================= weak_ptr<GameObject> Hierarchy::m_gameObjectSelected; weak_ptr<GameObject> g_gameObjectEmpty; static Engine* g_engine = nullptr; static Scene* g_scene = nullptr; static bool g_wasItemHovered = false; Hierarchy::Hierarchy() { m_title = "Hierarchy"; m_context = nullptr; g_scene = nullptr; } void Hierarchy::Initialize(Context* context) { Widget::Initialize(context); g_engine = m_context->GetSubsystem<Engine>(); g_scene = m_context->GetSubsystem<Scene>(); } void Hierarchy::Update() { g_wasItemHovered = false; // If the engine is not updating, don't populate the hierarchy yet if (!g_engine->IsUpdating()) return; if (ImGui::TreeNodeEx("Scene", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, ImGui::GetFontSize() * 3); // Increase spacing to differentiate leaves from expanded contents. Tree_Populate(); ImGui::PopStyleVar(); ImGui::TreePop(); } } void Hierarchy::Tree_Populate() { auto rootGameObjects = g_scene->GetRootGameObjects(); for (const auto& gameObject : rootGameObjects) { Tree_AddGameObject(gameObject); } } void Hierarchy::Tree_AddGameObject(const weak_ptr<GameObject>& currentGameObject) { GameObject* gameObjPtr = currentGameObject.lock().get(); // Node children visibility bool hasVisibleChildren = false; auto children = gameObjPtr->GetTransform()->GetChildren(); for (const auto& child : children) { if (child->GetGameObject()->IsVisibleInHierarchy()) { hasVisibleChildren = true; break; } } // Node flags -> Default ImGuiTreeNodeFlags node_flags = ImGuiTreeNodeFlags_OpenOnDoubleClick; // Node flags -> Expandable? node_flags |= hasVisibleChildren ? ImGuiTreeNodeFlags_OpenOnArrow : ImGuiTreeNodeFlags_Leaf; // Node flags -> Selected? if (!m_gameObjectSelected.expired()) { node_flags |= (m_gameObjectSelected.lock()->GetID() == gameObjPtr->GetID()) ? ImGuiTreeNodeFlags_Selected : 0; } // Node bool isNodeOpen = ImGui::TreeNodeEx((void*)(intptr_t)gameObjPtr->GetID(), node_flags, gameObjPtr->GetName().c_str()); // Handle clicking if (ImGui::IsMouseHoveringWindow()) { // Left click if (ImGui::IsMouseClicked(0) && ImGui::IsItemHovered(ImGuiHoveredFlags_Default)) { m_gameObjectSelected = currentGameObject; g_wasItemHovered = true; } // Right click if (ImGui::IsMouseClicked(1) && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) { m_gameObjectSelected = currentGameObject; ImGui::OpenPopup("##HierarchyContextMenu"); g_wasItemHovered = true; } // Clicking inside the window (but not on an item) if ((ImGui::IsMouseClicked(0) || ImGui::IsMouseClicked(1)) && !g_wasItemHovered) { m_gameObjectSelected = g_gameObjectEmpty; } } // Context menu if (ImGui::BeginPopup("##HierarchyContextMenu")) { if (!m_gameObjectSelected.expired()) { ImGui::MenuItem("Rename"); if (ImGui::MenuItem("Delete")) { GameObject_Delete(m_gameObjectSelected); } ImGui::Separator(); } if (ImGui::MenuItem("Creaty Empty")) { GameObject_CreateEmpty(); } ImGui::EndPopup(); } // Child nodes if (isNodeOpen) { if (hasVisibleChildren) { for (const auto& child : children) { if (!child->GetGameObject()->IsVisibleInHierarchy()) continue; Tree_AddGameObject(child->GetGameObjectRef()); } } ImGui::TreePop(); } } void Hierarchy::GameObject_Delete(weak_ptr<GameObject> gameObject) { g_scene->RemoveGameObject(gameObject); } void Hierarchy::GameObject_CreateEmpty() { g_scene->CreateGameObject(); } <commit_msg>Fixed a bug where clicking in empty space in the hierarchy, would not show the context menu.<commit_after>/* Copyright(c) 2016-2017 Panos Karabelas 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. */ //= INCLUDES ==================== #include "Hierarchy.h" #include "../imgui/imgui.h" #include "Scene/Scene.h" #include "Scene/GameObject.h" #include "Components/Transform.h" #include "Core/Engine.h" //=============================== //= NAMESPACES ========== using namespace std; using namespace Directus; //======================= weak_ptr<GameObject> Hierarchy::m_gameObjectSelected; weak_ptr<GameObject> g_gameObjectEmpty; static Engine* g_engine = nullptr; static Scene* g_scene = nullptr; static bool g_wasItemHovered = false; Hierarchy::Hierarchy() { m_title = "Hierarchy"; m_context = nullptr; g_scene = nullptr; } void Hierarchy::Initialize(Context* context) { Widget::Initialize(context); g_engine = m_context->GetSubsystem<Engine>(); g_scene = m_context->GetSubsystem<Scene>(); } void Hierarchy::Update() { g_wasItemHovered = false; // If the engine is not updating, don't populate the hierarchy yet if (!g_engine->IsUpdating()) return; if (ImGui::TreeNodeEx("Scene", ImGuiTreeNodeFlags_DefaultOpen)) { ImGui::PushStyleVar(ImGuiStyleVar_IndentSpacing, ImGui::GetFontSize() * 3); // Increase spacing to differentiate leaves from expanded contents. Tree_Populate(); ImGui::PopStyleVar(); ImGui::TreePop(); } } void Hierarchy::Tree_Populate() { auto rootGameObjects = g_scene->GetRootGameObjects(); for (const auto& gameObject : rootGameObjects) { Tree_AddGameObject(gameObject); } } void Hierarchy::Tree_AddGameObject(const weak_ptr<GameObject>& currentGameObject) { GameObject* gameObjPtr = currentGameObject.lock().get(); // Node children visibility bool hasVisibleChildren = false; auto children = gameObjPtr->GetTransform()->GetChildren(); for (const auto& child : children) { if (child->GetGameObject()->IsVisibleInHierarchy()) { hasVisibleChildren = true; break; } } // Node flags -> Default ImGuiTreeNodeFlags node_flags = ImGuiTreeNodeFlags_OpenOnDoubleClick; // Node flags -> Expandable? node_flags |= hasVisibleChildren ? ImGuiTreeNodeFlags_OpenOnArrow : ImGuiTreeNodeFlags_Leaf; // Node flags -> Selected? if (!m_gameObjectSelected.expired()) { node_flags |= (m_gameObjectSelected.lock()->GetID() == gameObjPtr->GetID()) ? ImGuiTreeNodeFlags_Selected : 0; } // Node bool isNodeOpen = ImGui::TreeNodeEx((void*)(intptr_t)gameObjPtr->GetID(), node_flags, gameObjPtr->GetName().c_str()); // Handle clicking if (ImGui::IsMouseHoveringWindow()) { // Left click if (ImGui::IsMouseClicked(0) && ImGui::IsItemHovered(ImGuiHoveredFlags_Default)) { m_gameObjectSelected = currentGameObject; g_wasItemHovered = true; } // Right click if (ImGui::IsMouseClicked(1)) { if (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup)) { m_gameObjectSelected = currentGameObject; } else { ImGui::OpenPopup("##HierarchyContextMenu"); } g_wasItemHovered = true; } // Clicking inside the window (but not on an item) if ((ImGui::IsMouseClicked(0) || ImGui::IsMouseClicked(1)) && !g_wasItemHovered) { m_gameObjectSelected = g_gameObjectEmpty; } } // Context menu if (ImGui::BeginPopup("##HierarchyContextMenu")) { if (!m_gameObjectSelected.expired()) { ImGui::MenuItem("Rename"); if (ImGui::MenuItem("Delete")) { GameObject_Delete(m_gameObjectSelected); } ImGui::Separator(); } if (ImGui::MenuItem("Creaty Empty")) { GameObject_CreateEmpty(); } ImGui::EndPopup(); } // Child nodes if (isNodeOpen) { if (hasVisibleChildren) { for (const auto& child : children) { if (!child->GetGameObject()->IsVisibleInHierarchy()) continue; Tree_AddGameObject(child->GetGameObjectRef()); } } ImGui::TreePop(); } } void Hierarchy::GameObject_Delete(weak_ptr<GameObject> gameObject) { g_scene->RemoveGameObject(gameObject); } void Hierarchy::GameObject_CreateEmpty() { g_scene->CreateGameObject(); } <|endoftext|>
<commit_before>/* ** ** Copyright (C) 2012 Aldebaran Robotics */ #include <map> #include <boost/lexical_cast.hpp> #include <gtest/gtest.h> #include <qi/qi.hpp> #include <qi/application.hpp> #include <qitype/type.hpp> #include <qitype/genericobject.hpp> #include <qitype/genericobjectbuilder.hpp> #include <qimessaging/session.hpp> #include <qimessaging/servicedirectory.hpp> qi::GenericValue v; static qi::Promise<int> *payload; void onFire(const int& pl) { std::cout << "onFire:" << pl << std::endl; std::cout.flush(); payload->setValue(pl); } void value(qi::GenericValue mv) { v = mv.clone(); payload->setValue(0); } void valueList(std::vector<qi::GenericValue> mv) { v = qi::GenericValue::from(mv).clone(); payload->setValue(0); } class TestObject: public ::testing::Test { public: TestObject() { qi::GenericObjectBuilder ob; ob.advertiseEvent<void (*)(const int&)>("fire"); ob.advertiseMethod("value", &value); ob.advertiseMethod("value", &valueList); oserver = ob.object(); } protected: void SetUp() { ASSERT_TRUE(sd.listen("tcp://127.0.0.1:0")); ASSERT_TRUE(session.connect(sd.endpoints()[0])); ASSERT_TRUE(session.listen("tcp://0.0.0.0:0")); ASSERT_GT(session.registerService("coin", oserver).wait(), 0); EXPECT_EQ(1U, session.services(qi::Session::ServiceLocality_Local).value().size()); ASSERT_TRUE(sclient.connect(sd.endpoints()[0])); std::vector<qi::ServiceInfo> services = sclient.services(); EXPECT_EQ(2U, services.size()); oclient = sclient.service("coin"); payload = &prom; } void TearDown() { payload = 0; sclient.close(); session.close(); sd.close(); } public: qi::Promise<int> prom; qi::ServiceDirectory sd; qi::Session session; qi::ObjectPtr oserver; qi::Session sclient; qi::ObjectPtr oclient; }; TEST_F(TestObject, meta) { using namespace qi; qi::int64_t time = os::ustime(); // Remote test ObjectPtr target = oclient; ASSERT_TRUE(target); { /* WATCH OUT, qi::AutoGenericValue(12) is what call expects! * So call(AutoGenericValue(12)) will *not* call with the value * "a metavalue containing 12", it will call with "12". */ target->call<void>("value", 12).wait(); ASSERT_EQ(v.asDouble(), 12); { int myint = 12; qi::Future<void> fut = target->call<void>("value", myint); myint = 5; fut.wait(); ASSERT_EQ(v.asDouble(), 12); } { int myint = 12; qi::Future<void> fut = target->call<void>("value", GenericValue(AutoGenericValue(myint))); myint = 5; fut.wait(); ASSERT_EQ(v.asDouble(), 12); } target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(12))).wait(); ASSERT_EQ(v.asDouble(), 12); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(12.0))).wait(); ASSERT_EQ(v.asDouble(), 12); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(12.0f))).wait(); ASSERT_EQ(v.asDouble(), 12); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue("foo"))).wait(); ASSERT_EQ(v.asString(), "foo"); target->call<void>("value", "foo").wait(); ASSERT_EQ(v.asString(), "foo"); std::vector<double> in; in.push_back(1); in.push_back(2); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(in))).wait(); ASSERT_EQ(v.as<std::vector<double> >(), in); target->call<void>("value", in).wait(); ASSERT_EQ(v.as<std::vector<double> >(), in); std::vector<GenericValue> args; args.push_back(AutoGenericValue(12)); args.push_back(AutoGenericValue("foo")); args.push_back(AutoGenericValue(in)); target->call<void>("value", args).wait(); ASSERT_EQ(v.kind(), Type::List); GenericList l = v.asList(); GenericListIterator i = l.begin(); // iterate ASSERT_EQ(12, (*i).asDouble()); i++; ASSERT_EQ("foo", (*i).asString()); i++; ASSERT_EQ(in, (*i).as<std::vector<double> >()); } qiLogVerbose("test") << "remote us: " << os::ustime() - time; time = os::ustime(); // Plugin copy test target = oserver; { target->call<void>("value", 12).wait(); ASSERT_EQ(v.asDouble(), 12); { int myint = 12; qi::Future<void> fut = target->call<void>("value", myint); myint = 5; fut.wait(); ASSERT_EQ(v.asDouble(), 12); } { int myint = 12; qi::Future<void> fut = target->call<void>("value", GenericValue(AutoGenericValue(myint))); myint = 5; fut.wait(); ASSERT_EQ(v.asDouble(), 12); } target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(12))).wait(); ASSERT_EQ(v.asDouble(), 12); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(12.0))).wait(); ASSERT_EQ(v.asDouble(), 12); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(12.0f))).wait(); ASSERT_EQ(v.asDouble(), 12); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue("foo"))).wait(); ASSERT_EQ(v.asString(), "foo"); target->call<void>("value", "foo").wait(); ASSERT_EQ(v.asString(), "foo"); std::vector<double> in; in.push_back(1); in.push_back(2); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(in))).wait(); ASSERT_EQ(v.as<std::vector<double> >(), in); target->call<void>("value", in).wait(); ASSERT_EQ(v.as<std::vector<double> >(), in); target->call<void>("value", in).wait(); ASSERT_EQ(v.as<std::vector<double> >(), in); std::vector<GenericValue> args; args.push_back(AutoGenericValue(12)); args.push_back(AutoGenericValue("foo")); args.push_back(AutoGenericValue(in)); target->call<void>("value", args).wait(); ASSERT_EQ(v.kind(), Type::List); GenericList l = v.asList(); GenericListIterator i = l.begin(); // iterate ASSERT_EQ(12, (*i).asDouble()); i++; ASSERT_EQ("foo", (*i).asString()); i++; ASSERT_EQ(in, (*i).as<std::vector<double> >()); } qiLogVerbose("test") << "plugin async us: " << os::ustime() - time; time = os::ustime(); // plugin direct test target->moveToEventLoop(0); { target->call<void>("value", 12).wait(); ASSERT_EQ(v.asDouble(), 12); { int myint = 12; qi::Future<void> fut = target->call<void>("value", myint); myint = 5; fut.wait(); ASSERT_EQ(v.asDouble(), 12); } { int myint = 12; qi::Future<void> fut = target->call<void>("value", GenericValue(AutoGenericValue(myint))); myint = 5; fut.wait(); ASSERT_EQ(v.asDouble(), 12); } target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(12))).wait(); ASSERT_EQ(v.asDouble(), 12); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(12.0))).wait(); ASSERT_EQ(v.asDouble(), 12); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(12.0f))).wait(); ASSERT_EQ(v.asDouble(), 12); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue("foo"))).wait(); ASSERT_EQ(v.asString(), "foo"); target->call<void>("value", "foo").wait(); ASSERT_EQ(v.asString(), "foo"); std::vector<double> in; in.push_back(1); in.push_back(2); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(in))).wait(); ASSERT_EQ(v.as<std::vector<double> >(), in); target->call<void>("value", in).wait(); ASSERT_EQ(v.as<std::vector<double> >(), in); std::vector<GenericValue> args; args.push_back(AutoGenericValue(12)); args.push_back(AutoGenericValue("foo")); args.push_back(AutoGenericValue(in)); target->call<void>("value", args).wait(); ASSERT_EQ(v.kind(), Type::List); GenericList l = v.asList(); GenericListIterator i = l.begin(); // iterate ASSERT_EQ(12, (*i).asDouble()); i++; ASSERT_EQ("foo", (*i).asString()); i++; ASSERT_EQ(in, (*i).as<std::vector<double> >()); } qiLogVerbose("test") << "plugin sync us: " << os::ustime() - time; time = os::ustime(); } int main(int argc, char *argv[]) { #if defined(__APPLE__) || defined(__linux__) setsid(); #endif qi::Application app(argc, argv); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <commit_msg>test_metavalue_argument: Remove unused promise.<commit_after>/* ** ** Copyright (C) 2012 Aldebaran Robotics */ #include <map> #include <boost/lexical_cast.hpp> #include <gtest/gtest.h> #include <qi/qi.hpp> #include <qi/application.hpp> #include <qitype/type.hpp> #include <qitype/genericobject.hpp> #include <qitype/genericobjectbuilder.hpp> #include <qimessaging/session.hpp> #include <qimessaging/servicedirectory.hpp> qi::GenericValue v; void onFire(const int& pl) { std::cout << "onFire:" << pl << std::endl; std::cout.flush(); } void value(qi::GenericValue mv) { v = mv.clone(); } void valueList(std::vector<qi::GenericValue> mv) { v = qi::GenericValue::from(mv).clone(); } class TestObject: public ::testing::Test { public: TestObject() { qi::GenericObjectBuilder ob; ob.advertiseEvent<void (*)(const int&)>("fire"); ob.advertiseMethod("value", &value); ob.advertiseMethod("value", &valueList); oserver = ob.object(); } protected: void SetUp() { ASSERT_TRUE(sd.listen("tcp://127.0.0.1:0")); ASSERT_TRUE(session.connect(sd.endpoints()[0])); ASSERT_TRUE(session.listen("tcp://0.0.0.0:0")); ASSERT_GT(session.registerService("coin", oserver).wait(), 0); EXPECT_EQ(1U, session.services(qi::Session::ServiceLocality_Local).value().size()); ASSERT_TRUE(sclient.connect(sd.endpoints()[0])); std::vector<qi::ServiceInfo> services = sclient.services(); EXPECT_EQ(2U, services.size()); oclient = sclient.service("coin"); } void TearDown() { sclient.close(); session.close(); sd.close(); } public: qi::Promise<int> prom; qi::ServiceDirectory sd; qi::Session session; qi::ObjectPtr oserver; qi::Session sclient; qi::ObjectPtr oclient; }; TEST_F(TestObject, meta) { using namespace qi; qi::int64_t time = os::ustime(); // Remote test ObjectPtr target = oclient; ASSERT_TRUE(target); { /* WATCH OUT, qi::AutoGenericValue(12) is what call expects! * So call(AutoGenericValue(12)) will *not* call with the value * "a metavalue containing 12", it will call with "12". */ target->call<void>("value", 12).wait(); ASSERT_EQ(v.asDouble(), 12); { int myint = 12; qi::Future<void> fut = target->call<void>("value", myint); myint = 5; fut.wait(); ASSERT_EQ(v.asDouble(), 12); } { int myint = 12; qi::Future<void> fut = target->call<void>("value", GenericValue(AutoGenericValue(myint))); myint = 5; fut.wait(); ASSERT_EQ(v.asDouble(), 12); } target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(12))).wait(); ASSERT_EQ(v.asDouble(), 12); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(12.0))).wait(); ASSERT_EQ(v.asDouble(), 12); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(12.0f))).wait(); ASSERT_EQ(v.asDouble(), 12); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue("foo"))).wait(); ASSERT_EQ(v.asString(), "foo"); target->call<void>("value", "foo").wait(); ASSERT_EQ(v.asString(), "foo"); std::vector<double> in; in.push_back(1); in.push_back(2); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(in))).wait(); ASSERT_EQ(v.as<std::vector<double> >(), in); target->call<void>("value", in).wait(); ASSERT_EQ(v.as<std::vector<double> >(), in); std::vector<GenericValue> args; args.push_back(AutoGenericValue(12)); args.push_back(AutoGenericValue("foo")); args.push_back(AutoGenericValue(in)); target->call<void>("value", args).wait(); ASSERT_EQ(v.kind(), Type::List); GenericList l = v.asList(); GenericListIterator i = l.begin(); // iterate ASSERT_EQ(12, (*i).asDouble()); i++; ASSERT_EQ("foo", (*i).asString()); i++; ASSERT_EQ(in, (*i).as<std::vector<double> >()); } qiLogVerbose("test") << "remote us: " << os::ustime() - time; time = os::ustime(); // Plugin copy test target = oserver; { target->call<void>("value", 12).wait(); ASSERT_EQ(v.asDouble(), 12); { int myint = 12; qi::Future<void> fut = target->call<void>("value", myint); myint = 5; fut.wait(); ASSERT_EQ(v.asDouble(), 12); } { int myint = 12; qi::Future<void> fut = target->call<void>("value", GenericValue(AutoGenericValue(myint))); myint = 5; fut.wait(); ASSERT_EQ(v.asDouble(), 12); } target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(12))).wait(); ASSERT_EQ(v.asDouble(), 12); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(12.0))).wait(); ASSERT_EQ(v.asDouble(), 12); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(12.0f))).wait(); ASSERT_EQ(v.asDouble(), 12); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue("foo"))).wait(); ASSERT_EQ(v.asString(), "foo"); target->call<void>("value", "foo").wait(); ASSERT_EQ(v.asString(), "foo"); std::vector<double> in; in.push_back(1); in.push_back(2); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(in))).wait(); ASSERT_EQ(v.as<std::vector<double> >(), in); target->call<void>("value", in).wait(); ASSERT_EQ(v.as<std::vector<double> >(), in); target->call<void>("value", in).wait(); ASSERT_EQ(v.as<std::vector<double> >(), in); std::vector<GenericValue> args; args.push_back(AutoGenericValue(12)); args.push_back(AutoGenericValue("foo")); args.push_back(AutoGenericValue(in)); target->call<void>("value", args).wait(); ASSERT_EQ(v.kind(), Type::List); GenericList l = v.asList(); GenericListIterator i = l.begin(); // iterate ASSERT_EQ(12, (*i).asDouble()); i++; ASSERT_EQ("foo", (*i).asString()); i++; ASSERT_EQ(in, (*i).as<std::vector<double> >()); } qiLogVerbose("test") << "plugin async us: " << os::ustime() - time; time = os::ustime(); // plugin direct test target->moveToEventLoop(0); { target->call<void>("value", 12).wait(); ASSERT_EQ(v.asDouble(), 12); { int myint = 12; qi::Future<void> fut = target->call<void>("value", myint); myint = 5; fut.wait(); ASSERT_EQ(v.asDouble(), 12); } { int myint = 12; qi::Future<void> fut = target->call<void>("value", GenericValue(AutoGenericValue(myint))); myint = 5; fut.wait(); ASSERT_EQ(v.asDouble(), 12); } target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(12))).wait(); ASSERT_EQ(v.asDouble(), 12); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(12.0))).wait(); ASSERT_EQ(v.asDouble(), 12); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(12.0f))).wait(); ASSERT_EQ(v.asDouble(), 12); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue("foo"))).wait(); ASSERT_EQ(v.asString(), "foo"); target->call<void>("value", "foo").wait(); ASSERT_EQ(v.asString(), "foo"); std::vector<double> in; in.push_back(1); in.push_back(2); target->call<void>("value", qi::GenericValue(qi::AutoGenericValue(in))).wait(); ASSERT_EQ(v.as<std::vector<double> >(), in); target->call<void>("value", in).wait(); ASSERT_EQ(v.as<std::vector<double> >(), in); std::vector<GenericValue> args; args.push_back(AutoGenericValue(12)); args.push_back(AutoGenericValue("foo")); args.push_back(AutoGenericValue(in)); target->call<void>("value", args).wait(); ASSERT_EQ(v.kind(), Type::List); GenericList l = v.asList(); GenericListIterator i = l.begin(); // iterate ASSERT_EQ(12, (*i).asDouble()); i++; ASSERT_EQ("foo", (*i).asString()); i++; ASSERT_EQ(in, (*i).as<std::vector<double> >()); } qiLogVerbose("test") << "plugin sync us: " << os::ustime() - time; time = os::ustime(); } int main(int argc, char *argv[]) { #if defined(__APPLE__) || defined(__linux__) setsid(); #endif qi::Application app(argc, argv); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } <|endoftext|>
<commit_before>/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2016, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #include "kinematics-precomp.h" // Precompiled header #include <mrpt/kinematics/CVehicleSimulVirtualBase.h> using namespace mrpt::kinematics; CVehicleSimulVirtualBase::CVehicleSimulVirtualBase() : m_firmware_control_period(500e-6) { } CVehicleSimulVirtualBase::~CVehicleSimulVirtualBase() { } void CVehicleSimulVirtualBase::setCurrentGTPose(const mrpt::math::TPose2D &pose) { m_pose=pose; } void CVehicleSimulVirtualBase::simulateOneTimeStep(const double dt) { const double final_t = m_time + dt; while (m_time <= final_t) { this->internal_simulStep(m_firmware_control_period); m_time += m_firmware_control_period; // Move forward } } void CVehicleSimulVirtualBase::resetStatus() { m_pose= mrpt::math::TPose2D(.0,.0,.0); m_vel = mrpt::math::TTwist2D(.0,.0,.0); m_odometry = mrpt::math::TPose2D(.0,.0,.0); internal_clear(); } void CVehicleSimulVirtualBase::resetTime() { m_time = .0; } mrpt::math::TTwist2D CVehicleSimulVirtualBase::getCurrentGTVelLocal() const { mrpt::math::TTwist2D tl = this->m_vel; tl.rotate(-m_pose.phi); return tl; } <commit_msg>initialize m_use_odo_error to false<commit_after>/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2016, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #include "kinematics-precomp.h" // Precompiled header #include <mrpt/kinematics/CVehicleSimulVirtualBase.h> using namespace mrpt::kinematics; CVehicleSimulVirtualBase::CVehicleSimulVirtualBase() : m_firmware_control_period(500e-6), m_use_odo_error(false) { } CVehicleSimulVirtualBase::~CVehicleSimulVirtualBase() { } void CVehicleSimulVirtualBase::setCurrentGTPose(const mrpt::math::TPose2D &pose) { m_pose=pose; } void CVehicleSimulVirtualBase::simulateOneTimeStep(const double dt) { const double final_t = m_time + dt; while (m_time <= final_t) { this->internal_simulStep(m_firmware_control_period); m_time += m_firmware_control_period; // Move forward } } void CVehicleSimulVirtualBase::resetStatus() { m_pose= mrpt::math::TPose2D(.0,.0,.0); m_vel = mrpt::math::TTwist2D(.0,.0,.0); m_odometry = mrpt::math::TPose2D(.0,.0,.0); internal_clear(); } void CVehicleSimulVirtualBase::resetTime() { m_time = .0; } mrpt::math::TTwist2D CVehicleSimulVirtualBase::getCurrentGTVelLocal() const { mrpt::math::TTwist2D tl = this->m_vel; tl.rotate(-m_pose.phi); return tl; } <|endoftext|>
<commit_before>#include <iostream> #include "gdal_priv.h" #include "cpl_conv.h" // for CPLMalloc() #include "io.h" using namespace std; /** * @brief A short function description * * A more detailed function description */ int printRasterInfo(const char* pszFilename) { GDALDataset *poDataset; GDALAllRegister(); poDataset = (GDALDataset *) GDALOpen( pszFilename, GA_ReadOnly ); if( poDataset == NULL ) { std::cout << "Dataset " << pszFilename << " could not be opened." << std::endl; return -1; } else { std::cout << "Dataset: " << pszFilename << std::endl; double adfGeoTransform[6]; std::cout << " Driver: " << poDataset->GetDriver()->GetDescription() << "/" << poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) << std::endl; std::cout << " Size: " << poDataset->GetRasterXSize() << "x" << poDataset->GetRasterYSize() << "x" << poDataset->GetRasterCount() << std::endl; if( poDataset->GetProjectionRef() != NULL ) std::cout << " Projection: " << poDataset->GetProjectionRef() << std::endl; if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) { std::cout << " Origin: (" << adfGeoTransform[0] << ", " << adfGeoTransform[3] << ")" << std::endl; std::cout << " Pixel Size: (" << adfGeoTransform[1] << ", " << adfGeoTransform[5] << std::endl; } } return 0; } int readRaster(const char* pszFilename) { // Set config options for GDAL (needs >= 2.0). Setting GTIFF_VIRTUAL_MEM_IO to "YES" can cause things bleed to // swap if enough RAM is not available. Use "IF_ENOUGH_RAM" for safer performance if unsure. NOTE that faster // mem io only works with *uncompressed* GeoTIFFs. // New in GDAL 2.0, from https://2015.foss4g-na.org/sites/default/files/slides/GDAL%202.0%20overview.pdf // GeoTIFF driver (with i7-4700 HQ (8 vCPUs)):with i7-4700 HQ (8 vCPUs) // - Default: time ./testblockcache -ondisk: 7.5s // - GTIFF_DIRECT_IO=YES: short circuit the block cache&libtiff for most RasterIO() operations (restricted to // uncompressed stripped GeoTIFF). time ./testblockcache -ondisk: 2s // - GTIFF_VIRTUAL_MEM_IO=YES: same as above, with tiled GeoTIFF as well. Uses memory-mapped file access. Linux // only for now, 64bit recommended (could be extended to other platforms possible). // time ./testblockcache -ondisk: 0.3s // CPLSetConfigOption("GTIFF_VIRTUAL_MEM_IO", "YES" ); // Open the dataset GDALDataset *poDataset; GDALAllRegister(); poDataset = (GDALDataset *) GDALOpen( pszFilename, GA_ReadOnly ); if( poDataset == NULL ) { std::cout << "Dataset " << pszFilename << " could not be opened." << std::endl; return -1; } else { GDALRasterBand *poBand; int nBlockXSize, nBlockYSize; int bGotMin, bGotMax; double adfMinMax[2]; // Get raster band and its size poBand = poDataset->GetRasterBand(1); poBand->GetBlockSize( &nBlockXSize, &nBlockYSize); std::cout << "Dataset: " << pszFilename << std::endl; std::cout << "Block=" << nBlockXSize << "x" << nBlockYSize << " Type=" << GDALGetDataTypeName(poBand->GetRasterDataType()) << " ColorInterp=" << GDALGetColorInterpretationName(poBand->GetColorInterpretation()) << std::endl; // Calculate some stats adfMinMax[0] = poBand->GetMinimum(&bGotMin); adfMinMax[1] = poBand->GetMaximum(&bGotMax); if(!(bGotMin && bGotMax)) { GDALComputeRasterMinMax((GDALRasterBandH) poBand, TRUE, adfMinMax); } std::cout << "Min=" << adfMinMax[0] << " Max=" << adfMinMax[1] << std::endl; if(poBand->GetOverviewCount() > 0) { std::cout << "Band has " << poBand->GetOverviewCount() << " overviews." << std::endl; } if( poBand->GetColorTable() != NULL ) { std::cout << "Band has a color table with " << poBand->GetColorTable()->GetColorEntryCount() << " entries." << std::endl; } // Get the actual data float *pafScanline; int nXSize = poBand->GetXSize(); pafScanline = (float *) CPLMalloc(sizeof(float) * nXSize); // RasterIO has a new argument psExtraArg in GDAL > 2.0. NOTE: that GDALRasterBand::ReadBlock() probably has // better performance for reading the whole data at one go. #ifdef USE_GDAL_2 GDALRasterIOExtraArg* arg = NULL; poBand->RasterIO(GF_Read, 0, 0, nXSize, 1, pafScanline, nXSize, 1, GDT_Float3GDALRasterBand::ReadBlock 2, 0, 0, arg); #else poBand->RasterIO(GF_Read, 0, 0, nXSize, 1, pafScanline, nXSize, 1, GDT_Float32, 0, 0); #endif // ... do something with the data ... // Free resources CPLFree(pafScanline); GDALClose((GDALDatasetH) poDataset); std::cout << std::endl; } return 0; } <commit_msg>Add old docs<commit_after>#include <iostream> #include "gdal_priv.h" #include "cpl_conv.h" // for CPLMalloc() #include "io.h" using namespace std; /*! \file io.cpp With a little bit of a elaboration, should you feel it necessary. */ int printRasterInfo(const char* pszFilename) { /** An enum type. * The documentation block cannot be put after the enum! */ GDALDataset *poDataset; GDALAllRegister(); poDataset = (GDALDataset *) GDALOpen( pszFilename, GA_ReadOnly ); if( poDataset == NULL ) { std::cout << "Dataset " << pszFilename << " could not be opened." << std::endl; return -1; } else { std::cout << "Dataset: " << pszFilename << std::endl; double adfGeoTransform[6]; std::cout << " Driver: " << poDataset->GetDriver()->GetDescription() << "/" << poDataset->GetDriver()->GetMetadataItem( GDAL_DMD_LONGNAME ) << std::endl; std::cout << " Size: " << poDataset->GetRasterXSize() << "x" << poDataset->GetRasterYSize() << "x" << poDataset->GetRasterCount() << std::endl; if( poDataset->GetProjectionRef() != NULL ) std::cout << " Projection: " << poDataset->GetProjectionRef() << std::endl; if( poDataset->GetGeoTransform( adfGeoTransform ) == CE_None ) { std::cout << " Origin: (" << adfGeoTransform[0] << ", " << adfGeoTransform[3] << ")" << std::endl; std::cout << " Pixel Size: (" << adfGeoTransform[1] << ", " << adfGeoTransform[5] << std::endl; } } return 0; } int readRaster(const char* pszFilename) { // Set config options for GDAL (needs >= 2.0). Setting GTIFF_VIRTUAL_MEM_IO to "YES" can cause things bleed to // swap if enough RAM is not available. Use "IF_ENOUGH_RAM" for safer performance if unsure. NOTE that faster // mem io only works with *uncompressed* GeoTIFFs. // New in GDAL 2.0, from https://2015.foss4g-na.org/sites/default/files/slides/GDAL%202.0%20overview.pdf // GeoTIFF driver (with i7-4700 HQ (8 vCPUs)):with i7-4700 HQ (8 vCPUs) // - Default: time ./testblockcache -ondisk: 7.5s // - GTIFF_DIRECT_IO=YES: short circuit the block cache&libtiff for most RasterIO() operations (restricted to // uncompressed stripped GeoTIFF). time ./testblockcache -ondisk: 2s // - GTIFF_VIRTUAL_MEM_IO=YES: same as above, with tiled GeoTIFF as well. Uses memory-mapped file access. Linux // only for now, 64bit recommended (could be extended to other platforms possible). // time ./testblockcache -ondisk: 0.3s // CPLSetConfigOption("GTIFF_VIRTUAL_MEM_IO", "YES" ); // Open the dataset GDALDataset *poDataset; GDALAllRegister(); poDataset = (GDALDataset *) GDALOpen( pszFilename, GA_ReadOnly ); if( poDataset == NULL ) { std::cout << "Dataset " << pszFilename << " could not be opened." << std::endl; return -1; } else { GDALRasterBand *poBand; int nBlockXSize, nBlockYSize; int bGotMin, bGotMax; double adfMinMax[2]; // Get raster band and its size poBand = poDataset->GetRasterBand(1); poBand->GetBlockSize( &nBlockXSize, &nBlockYSize); std::cout << "Dataset: " << pszFilename << std::endl; std::cout << "Block=" << nBlockXSize << "x" << nBlockYSize << " Type=" << GDALGetDataTypeName(poBand->GetRasterDataType()) << " ColorInterp=" << GDALGetColorInterpretationName(poBand->GetColorInterpretation()) << std::endl; // Calculate some stats adfMinMax[0] = poBand->GetMinimum(&bGotMin); adfMinMax[1] = poBand->GetMaximum(&bGotMax); if(!(bGotMin && bGotMax)) { GDALComputeRasterMinMax((GDALRasterBandH) poBand, TRUE, adfMinMax); } std::cout << "Min=" << adfMinMax[0] << " Max=" << adfMinMax[1] << std::endl; if(poBand->GetOverviewCount() > 0) { std::cout << "Band has " << poBand->GetOverviewCount() << " overviews." << std::endl; } if( poBand->GetColorTable() != NULL ) { std::cout << "Band has a color table with " << poBand->GetColorTable()->GetColorEntryCount() << " entries." << std::endl; } // Get the actual data float *pafScanline; int nXSize = poBand->GetXSize(); pafScanline = (float *) CPLMalloc(sizeof(float) * nXSize); // RasterIO has a new argument psExtraArg in GDAL > 2.0. NOTE: that GDALRasterBand::ReadBlock() probably has // better performance for reading the whole data at one go. #ifdef USE_GDAL_2 GDALRasterIOExtraArg* arg = NULL; poBand->RasterIO(GF_Read, 0, 0, nXSize, 1, pafScanline, nXSize, 1, GDT_Float3GDALRasterBand::ReadBlock 2, 0, 0, arg); #else poBand->RasterIO(GF_Read, 0, 0, nXSize, 1, pafScanline, nXSize, 1, GDT_Float32, 0, 0); #endif // ... do something with the data ... // Free resources CPLFree(pafScanline); GDALClose((GDALDatasetH) poDataset); std::cout << std::endl; } return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Daniel Vrátil <dvratil@redhat.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "fakeakonadiserver.h" #include "fakeconnection.h" #include "fakedatastore.h" #include "fakesearchmanager.h" #include "fakeclient.h" #include <QSettings> #include <QCoreApplication> #include <QSqlQuery> #include <QDir> #include <QFileInfo> #include <QLocalServer> #include <QTest> #include <libs/xdgbasedirs_p.h> #include <imapparser_p.h> #include <shared/akstandarddirs.h> #include <akapplication.h> #include <storage/dbconfig.h> #include <storage/datastore.h> #include <preprocessormanager.h> #include <search/searchmanager.h> #include <utils.h> using namespace Akonadi; using namespace Akonadi::Server; FakeAkonadiServer::FakeAkonadiServer( QObject *parent ) : QLocalServer( parent ) , mDataStore(0) , mServerLoop(0) , mNotificationSpy(0) { mClient = new FakeClient; } FakeAkonadiServer::~FakeAkonadiServer() { close(); cleanup(); delete mClient; } QString FakeAkonadiServer::basePath() { return QString::fromLatin1("/tmp/akonadiserver-test-%1").arg(QCoreApplication::instance()->applicationPid()); } QString FakeAkonadiServer::socketFile() { return basePath() % QLatin1String("/local/share/akonadi/akonadiserver.socket"); } QString FakeAkonadiServer::instanceName() { return QString::fromLatin1("akonadiserver-test-%1").arg(QCoreApplication::instance()->applicationPid()); } QList<QByteArray> FakeAkonadiServer::loginScenario() { QList<QByteArray> scenario; // FIXME: Use real protocol version scenario << "S: * OK Akonadi Almost IMAP Server [PROTOCOL " + QByteArray::number(Connection::protocolVersion()) + "]"; scenario << "C: 0 LOGIN " + instanceName().toLatin1(); scenario << "S: 0 OK User logged in"; return scenario; } QList<QByteArray> FakeAkonadiServer::defaultScenario() { QList<QByteArray> caps; caps << "NOTIFY 2"; caps << "NOPAYLOADPATH"; caps << "AKAPPENDSTREAMING"; return customCapabilitiesScenario(caps); } QList<QByteArray> FakeAkonadiServer::customCapabilitiesScenario(const QList<QByteArray> &capabilities) { QList<QByteArray> scenario = loginScenario(); scenario << "C: 1 CAPABILITY (" + ImapParser::join(capabilities, " ") + ")"; scenario << "S: 1 OK CAPABILITY completed"; return scenario; } QList<QByteArray> FakeAkonadiServer::selectCollectionScenario(const QString &name) { QList<QByteArray> scenario; const Collection collection = Collection::retrieveByName(name); scenario << "C: 3 UID SELECT SILENT " + QByteArray::number(collection.id()); scenario << "S: 3 OK Completed"; return scenario; } QList<QByteArray> FakeAkonadiServer::selectResourceScenario(const QString &name) { QList<QByteArray> scenario; const Resource resource = Resource::retrieveByName(name); scenario << "C: 2 RESSELECT " + resource.name().toLatin1(); scenario << "S: 2 OK " + resource.name().toLatin1() + " selected"; return scenario; } bool FakeAkonadiServer::initialize() { qDebug() << "==== Fake Akonadi Server starting up ===="; qputenv("XDG_DATA_HOME", qPrintable(QString(basePath() + QLatin1String("/local")))); qputenv("XDG_CONFIG_HOME", qPrintable(QString(basePath() + QLatin1String("/config")))); qputenv("AKONADI_INSTANCE", qPrintable(instanceName())); QSettings settings(AkStandardDirs::serverConfigFile(XdgBaseDirs::WriteOnly), QSettings::IniFormat); settings.beginGroup(QLatin1String("General")); settings.setValue(QLatin1String("Driver"), QLatin1String("QSQLITE3")); settings.endGroup(); settings.beginGroup(QLatin1String("QSQLITE3")); settings.setValue(QLatin1String("Name"), QString(basePath() + QLatin1String("/local/share/akonadi/akonadi.db"))); settings.endGroup(); settings.sync(); DbConfig *dbConfig = DbConfig::configuredDatabase(); if (dbConfig->driverName() != QLatin1String("QSQLITE3")) { throw FakeAkonadiServerException(QLatin1String("Unexpected driver specified. Expected QSQLITE3, got ") + dbConfig->driverName()); } const QLatin1String initCon("initConnection"); QSqlDatabase db = QSqlDatabase::addDatabase(DbConfig::configuredDatabase()->driverName(), initCon); DbConfig::configuredDatabase()->apply(db); db.setDatabaseName(DbConfig::configuredDatabase()->databaseName()); if (!db.isDriverAvailable(DbConfig::configuredDatabase()->driverName())) { throw FakeAkonadiServerException(QString::fromLatin1("SQL driver %s not available").arg(db.driverName())); } if (!db.isValid()) { throw FakeAkonadiServerException("Got invalid database"); } if (db.open()) { qWarning() << "Database" << dbConfig->configuredDatabase()->databaseName() << "already exists, the test is not running in a clean environment!"; db.close(); } else { db.close(); db.setDatabaseName(QString()); if (db.open()) { { QSqlQuery query(db); if (!query.exec(QString::fromLatin1("CREATE DATABASE %1").arg(DbConfig::configuredDatabase()->databaseName()))) { throw FakeAkonadiServerException("Failed to create new database"); } } db.close(); } } QSqlDatabase::removeDatabase(initCon); dbConfig->setup(); mDataStore = static_cast<FakeDataStore*>(FakeDataStore::self()); if (!mDataStore->init()) { throw FakeAkonadiServerException("Failed to initialize datastore"); } PreprocessorManager::init(); PreprocessorManager::instance()->setEnabled(false); mSearchManager = new FakeSearchManager(); const QString socketFile = basePath() + QLatin1String("/local/share/akonadi/akonadiserver.socket"); qDebug() << "==== Fake Akonadi Server started ===="; return true; } bool FakeAkonadiServer::deleteDirectory(const QString &path) { // TODO: Qt 5: Use QDir::removeRecursively Q_ASSERT(path.startsWith(basePath())); QDir dir(path); dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot | QDir::Hidden); const QFileInfoList list = dir.entryInfoList(); for (int i = 0; i < list.size(); ++i) { if (list.at(i).isDir() && !list.at(i).isSymLink()) { deleteDirectory(list.at(i).absoluteFilePath()); const QDir tmpDir(list.at(i).absoluteDir()); tmpDir.rmdir(list.at(i).fileName()); } else { QFile::remove(list.at(i).absoluteFilePath()); } } dir.cdUp(); dir.rmdir(path); return true; } bool FakeAkonadiServer::cleanup() { qDebug() << "==== Fake Akonadi Server shutting down ===="; const boost::program_options::variables_map options = AkApplication::instance()->commandLineArguments(); if (!options.count("no-cleanup")) { deleteDirectory(basePath()); qDebug() << "Cleaned up" << basePath(); } else { qDebug() << "Skipping clean up of" << basePath(); } PreprocessorManager::done(); SearchManager::instance(); if (mDataStore) { mDataStore->close(); } qDebug() << "==== Fake Akonadi Server shut down ===="; return true; } void FakeAkonadiServer::setScenario(const QList<QByteArray> &scenario) { mClient->setScenario(scenario); } void FakeAkonadiServer::incomingConnection(quintptr socketDescriptor) { QThread *thread = new QThread(); FakeConnection *connection = new FakeConnection(socketDescriptor, thread); thread->start(); connect(connection, SIGNAL(disconnected()), thread, SLOT(quit())); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); connect(thread, SIGNAL(finished()), connection, SLOT(deleteLater())); mNotificationSpy = new QSignalSpy(connection->notificationCollector(), SIGNAL(notify(Akonadi::NotificationMessageV3::List))); } void FakeAkonadiServer::runTest() { QVERIFY(listen(socketFile())); mServerLoop = new QEventLoop(this); connect(mClient, SIGNAL(finished()), mServerLoop, SLOT(quit())); // Start the client: the client will connect to the server and will // start playing the scenario mClient->start(); // Wait until the client disconnects, i.e. until the scenario is completed. mServerLoop->exec(); mServerLoop->deleteLater(); mServerLoop = 0; close(); } FakeDataStore* FakeAkonadiServer::dataStore() const { Q_ASSERT_X(mDataStore, "FakeAkonadiServer::connection()", "You have to call FakeAkonadiServer::start() first"); return mDataStore; } QSignalSpy* FakeAkonadiServer::notificationSpy() const { return mNotificationSpy; } <commit_msg>FakeAkonadiServer: don't overwrite user's config in ~/.config/akonadi<commit_after>/* * Copyright (C) 2014 Daniel Vrátil <dvratil@redhat.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * */ #include "fakeakonadiserver.h" #include "fakeconnection.h" #include "fakedatastore.h" #include "fakesearchmanager.h" #include "fakeclient.h" #include <QSettings> #include <QCoreApplication> #include <QSqlQuery> #include <QDir> #include <QFileInfo> #include <QLocalServer> #include <QTest> #include <libs/xdgbasedirs_p.h> #include <imapparser_p.h> #include <shared/akstandarddirs.h> #include <akapplication.h> #include <storage/dbconfig.h> #include <storage/datastore.h> #include <preprocessormanager.h> #include <search/searchmanager.h> #include <utils.h> using namespace Akonadi; using namespace Akonadi::Server; FakeAkonadiServer::FakeAkonadiServer( QObject *parent ) : QLocalServer( parent ) , mDataStore(0) , mServerLoop(0) , mNotificationSpy(0) { mClient = new FakeClient; qputenv("XDG_DATA_HOME", qPrintable(QString(basePath() + QLatin1String("/local")))); qputenv("XDG_CONFIG_HOME", qPrintable(QString(basePath() + QLatin1String("/config")))); qputenv("AKONADI_INSTANCE", qPrintable(instanceName())); } FakeAkonadiServer::~FakeAkonadiServer() { close(); cleanup(); delete mClient; } QString FakeAkonadiServer::basePath() { return QString::fromLatin1("/tmp/akonadiserver-test-%1").arg(QCoreApplication::instance()->applicationPid()); } QString FakeAkonadiServer::socketFile() { return basePath() % QLatin1String("/local/share/akonadi/akonadiserver.socket"); } QString FakeAkonadiServer::instanceName() { return QString::fromLatin1("akonadiserver-test-%1").arg(QCoreApplication::instance()->applicationPid()); } QList<QByteArray> FakeAkonadiServer::loginScenario() { QList<QByteArray> scenario; // FIXME: Use real protocol version scenario << "S: * OK Akonadi Almost IMAP Server [PROTOCOL " + QByteArray::number(Connection::protocolVersion()) + "]"; scenario << "C: 0 LOGIN " + instanceName().toLatin1(); scenario << "S: 0 OK User logged in"; return scenario; } QList<QByteArray> FakeAkonadiServer::defaultScenario() { QList<QByteArray> caps; caps << "NOTIFY 2"; caps << "NOPAYLOADPATH"; caps << "AKAPPENDSTREAMING"; return customCapabilitiesScenario(caps); } QList<QByteArray> FakeAkonadiServer::customCapabilitiesScenario(const QList<QByteArray> &capabilities) { QList<QByteArray> scenario = loginScenario(); scenario << "C: 1 CAPABILITY (" + ImapParser::join(capabilities, " ") + ")"; scenario << "S: 1 OK CAPABILITY completed"; return scenario; } QList<QByteArray> FakeAkonadiServer::selectCollectionScenario(const QString &name) { QList<QByteArray> scenario; const Collection collection = Collection::retrieveByName(name); scenario << "C: 3 UID SELECT SILENT " + QByteArray::number(collection.id()); scenario << "S: 3 OK Completed"; return scenario; } QList<QByteArray> FakeAkonadiServer::selectResourceScenario(const QString &name) { QList<QByteArray> scenario; const Resource resource = Resource::retrieveByName(name); scenario << "C: 2 RESSELECT " + resource.name().toLatin1(); scenario << "S: 2 OK " + resource.name().toLatin1() + " selected"; return scenario; } bool FakeAkonadiServer::initialize() { qDebug() << "==== Fake Akonadi Server starting up ===="; qputenv("XDG_DATA_HOME", qPrintable(QString(basePath() + QLatin1String("/local")))); qputenv("XDG_CONFIG_HOME", qPrintable(QString(basePath() + QLatin1String("/config")))); qputenv("AKONADI_INSTANCE", qPrintable(instanceName())); QSettings settings(AkStandardDirs::serverConfigFile(XdgBaseDirs::WriteOnly), QSettings::IniFormat); settings.beginGroup(QLatin1String("General")); settings.setValue(QLatin1String("Driver"), QLatin1String("QSQLITE3")); settings.endGroup(); settings.beginGroup(QLatin1String("QSQLITE3")); settings.setValue(QLatin1String("Name"), QString(basePath() + QLatin1String("/local/share/akonadi/akonadi.db"))); settings.endGroup(); settings.sync(); DbConfig *dbConfig = DbConfig::configuredDatabase(); if (dbConfig->driverName() != QLatin1String("QSQLITE3")) { throw FakeAkonadiServerException(QLatin1String("Unexpected driver specified. Expected QSQLITE3, got ") + dbConfig->driverName()); } const QLatin1String initCon("initConnection"); QSqlDatabase db = QSqlDatabase::addDatabase(DbConfig::configuredDatabase()->driverName(), initCon); DbConfig::configuredDatabase()->apply(db); db.setDatabaseName(DbConfig::configuredDatabase()->databaseName()); if (!db.isDriverAvailable(DbConfig::configuredDatabase()->driverName())) { throw FakeAkonadiServerException(QString::fromLatin1("SQL driver %s not available").arg(db.driverName())); } if (!db.isValid()) { throw FakeAkonadiServerException("Got invalid database"); } if (db.open()) { qWarning() << "Database" << dbConfig->configuredDatabase()->databaseName() << "already exists, the test is not running in a clean environment!"; db.close(); } else { db.close(); db.setDatabaseName(QString()); if (db.open()) { { QSqlQuery query(db); if (!query.exec(QString::fromLatin1("CREATE DATABASE %1").arg(DbConfig::configuredDatabase()->databaseName()))) { throw FakeAkonadiServerException("Failed to create new database"); } } db.close(); } } QSqlDatabase::removeDatabase(initCon); dbConfig->setup(); mDataStore = static_cast<FakeDataStore*>(FakeDataStore::self()); if (!mDataStore->init()) { throw FakeAkonadiServerException("Failed to initialize datastore"); } PreprocessorManager::init(); PreprocessorManager::instance()->setEnabled(false); mSearchManager = new FakeSearchManager(); const QString socketFile = basePath() + QLatin1String("/local/share/akonadi/akonadiserver.socket"); qDebug() << "==== Fake Akonadi Server started ===="; return true; } bool FakeAkonadiServer::deleteDirectory(const QString &path) { // TODO: Qt 5: Use QDir::removeRecursively Q_ASSERT(path.startsWith(basePath())); QDir dir(path); dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot | QDir::Hidden); const QFileInfoList list = dir.entryInfoList(); for (int i = 0; i < list.size(); ++i) { if (list.at(i).isDir() && !list.at(i).isSymLink()) { deleteDirectory(list.at(i).absoluteFilePath()); const QDir tmpDir(list.at(i).absoluteDir()); tmpDir.rmdir(list.at(i).fileName()); } else { QFile::remove(list.at(i).absoluteFilePath()); } } dir.cdUp(); dir.rmdir(path); return true; } bool FakeAkonadiServer::cleanup() { qDebug() << "==== Fake Akonadi Server shutting down ===="; const boost::program_options::variables_map options = AkApplication::instance()->commandLineArguments(); if (!options.count("no-cleanup")) { deleteDirectory(basePath()); qDebug() << "Cleaned up" << basePath(); } else { qDebug() << "Skipping clean up of" << basePath(); } PreprocessorManager::done(); SearchManager::instance(); if (mDataStore) { mDataStore->close(); } qDebug() << "==== Fake Akonadi Server shut down ===="; return true; } void FakeAkonadiServer::setScenario(const QList<QByteArray> &scenario) { mClient->setScenario(scenario); } void FakeAkonadiServer::incomingConnection(quintptr socketDescriptor) { QThread *thread = new QThread(); FakeConnection *connection = new FakeConnection(socketDescriptor, thread); thread->start(); connect(connection, SIGNAL(disconnected()), thread, SLOT(quit())); connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); connect(thread, SIGNAL(finished()), connection, SLOT(deleteLater())); mNotificationSpy = new QSignalSpy(connection->notificationCollector(), SIGNAL(notify(Akonadi::NotificationMessageV3::List))); } void FakeAkonadiServer::runTest() { QVERIFY(listen(socketFile())); mServerLoop = new QEventLoop(this); connect(mClient, SIGNAL(finished()), mServerLoop, SLOT(quit())); // Start the client: the client will connect to the server and will // start playing the scenario mClient->start(); // Wait until the client disconnects, i.e. until the scenario is completed. mServerLoop->exec(); mServerLoop->deleteLater(); mServerLoop = 0; close(); } FakeDataStore* FakeAkonadiServer::dataStore() const { Q_ASSERT_X(mDataStore, "FakeAkonadiServer::connection()", "You have to call FakeAkonadiServer::start() first"); return mDataStore; } QSignalSpy* FakeAkonadiServer::notificationSpy() const { return mNotificationSpy; } <|endoftext|>
<commit_before>#include <tiramisu/tiramisu.h> using namespace tiramisu; void gen(std::string name, int size, int val0, int val1) { tiramisu::init(name); tiramisu::function *function0 = global::get_implicit_function(); tiramisu::constant N("N", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0, function0); tiramisu::var i("i", 0, N), j("j", 0, N); tiramisu::var i0("i0"), j0("j0"), i1("i1"), j1("j1"); tiramisu::computation S0(tiramisu::expr((uint8_t) (val0 + val1)), i, j); S0.tile(i, j, 2, 2, i0, j0, i1, j1); S0.tag_parallel_level(i); tiramisu::buffer buf0("buf0", {size, size}, tiramisu::p_uint8, a_output, function0); S0.store_in(&buf0, {i ,j}); function0->codegen({&buf0}, "build/generated_fct_test_115.o"); } int main(int argc, char **argv) { gen("func", 10, 3, 4); return 0; } <commit_msg>Fix test115<commit_after>#include <tiramisu/tiramisu.h> using namespace tiramisu; void gen(std::string name, int size, int val0, int val1) { tiramisu::init(name); tiramisu::function *function0 = global::get_implicit_function(); tiramisu::constant N("N", tiramisu::expr((int32_t) size), p_int32, true, NULL, 0, function0); tiramisu::var i("i", 0, 10), j("j", 0, N); tiramisu::var i0("i0"), j0("j0"), i1("i1"), j1("j1"); tiramisu::computation S0(tiramisu::expr((uint8_t) (val0 + val1)), i, j); S0.tile(i, j, 2, 2, i0, j0, i1, j1); S0.tag_parallel_level(i0); tiramisu::buffer buf0("buf0", {size, size}, tiramisu::p_uint8, a_output, function0); S0.store_in(&buf0, {i ,j}); function0->codegen({&buf0}, "build/generated_fct_test_115.o"); } int main(int argc, char **argv) { gen("func", 10, 3, 4); return 0; } <|endoftext|>
<commit_before> #include "QtApp.hpp" #include "QtMenu.hpp" #include "PythonHelpers.h" #include "PyThreading.hpp" #include <QAction> // Dummy vars for QApplication. // Note that the App construction is late at init. The Python code // has already parsed all args and warned about unknown ones, etc. // If we want to allow some Qt args, we should add some Python arg // like "--qtargs" and pass those here. static int dummy_argc = 1; static char* dummy_argv[] = {(char*)"musicplayer", NULL}; QtApp::QtApp() : QApplication(dummy_argc, dummy_argv) { { QByteArray normalizedSignature = QMetaObject::normalizedSignature("genericExec(boost::function<void(void)>)"); int methodIndex = this->metaObject()->indexOfSlot(normalizedSignature); assert(methodIndex >= 0); genericExec_method = this->metaObject()->method(methodIndex); } this->setOrganizationName("Albert Zeyer"); this->setApplicationName("MusicPlayer"); connect(this, SIGNAL(aboutToQuit()), this, SLOT(handleApplicationQuit())); } void QtApp::handleApplicationQuit() { PyScopedGIL gil; printf("about to quit ...\n"); PyObject* guiMod = getModule("gui"); // borrowed if(!guiMod) { printf("QtApp::handleApplicationQuit: gui module not found"); return; } PyObject* ret = PyObject_CallMethod(guiMod, (char*)"handleApplicationQuit", NULL); if(!ret && PyErr_Occurred()) PyErr_Print(); Py_XDECREF(ret); } void QtApp::openWindowViaMenu() { if(sender() == NULL) { printf("QtApp::openWindowViaMenu: no sender\n"); return; } QAction* act = qobject_cast<QAction*>(sender()); if(!act) { printf("QtApp::openWindowViaMenu: sender is not QAction\n"); return; } if(act->objectName().isEmpty()) { printf("QtApp::openWindowViaMenu: sender name is empty\n"); return; } openWindow(act->objectName().toStdString()); } void QtApp::openMainWindow() { openWindow("Main"); } void QtApp::openWindow(const std::string& name) { QWidget* win = new QWidget(); win->setWindowTitle(QString::fromStdString(name)); // ... } void QtApp::minimizeWindow() { QWidget* win = qApp->activeWindow(); if(win) win->showMinimized(); } void QtApp::closeWindow() { QWidget* win = qApp->activeWindow(); if(win) win->close(); } void QtApp::edit_cut() { QWidget* w = QApplication::focusWidget(); //... } void QtApp::edit_copy() { } void QtApp::edit_paste() { } void QtApp::edit_selectAll() { } void QtApp::handlePlayerUpdate() { updateControlMenu(); } void QtApp::playPause() { PyScopedGIL gil; PyObject* mod = getModule("State"); // borrowed if(!mod) return; PyObject* player = NULL; PyObject* playing = NULL; bool playingBool = false; player = attrChain(mod, "state.player"); if(!player) goto final; playing = PyObject_GetAttrString(player, "playing"); if(!playing) goto final; switch(PyObject_IsTrue(playing)) { case 1: playingBool = true; break; case 0: playingBool = false; break; default: goto final; } playingBool = !playingBool; PyObject_SetAttrString_retain(player, "playing", PyBool_FromLong(playingBool)); final: if(PyErr_Occurred()) PyErr_Print(); Py_XDECREF(player); Py_XDECREF(playing); } void QtApp::nextSong() { PyScopedGIL gil; PyObject* mod = getModule("State"); // borrowed if(!mod) return; PyObject* player = NULL; PyObject* ret = NULL; player = attrChain(mod, "state.player"); ret = PyObject_CallMethod(player, "nextSong", NULL); final: if(PyErr_Occurred()) PyErr_Print(); Py_XDECREF(player); Py_XDECREF(ret); } void QtApp::debug_resetPlayer() { } <commit_msg>qt win show<commit_after> #include "QtApp.hpp" #include "QtMenu.hpp" #include "PythonHelpers.h" #include "PyThreading.hpp" #include <QAction> // Dummy vars for QApplication. // Note that the App construction is late at init. The Python code // has already parsed all args and warned about unknown ones, etc. // If we want to allow some Qt args, we should add some Python arg // like "--qtargs" and pass those here. static int dummy_argc = 1; static char* dummy_argv[] = {(char*)"musicplayer", NULL}; QtApp::QtApp() : QApplication(dummy_argc, dummy_argv) { { QByteArray normalizedSignature = QMetaObject::normalizedSignature("genericExec(boost::function<void(void)>)"); int methodIndex = this->metaObject()->indexOfSlot(normalizedSignature); assert(methodIndex >= 0); genericExec_method = this->metaObject()->method(methodIndex); } this->setOrganizationName("Albert Zeyer"); this->setApplicationName("MusicPlayer"); connect(this, SIGNAL(aboutToQuit()), this, SLOT(handleApplicationQuit())); } void QtApp::handleApplicationQuit() { PyScopedGIL gil; printf("about to quit ...\n"); PyObject* guiMod = getModule("gui"); // borrowed if(!guiMod) { printf("QtApp::handleApplicationQuit: gui module not found"); return; } PyObject* ret = PyObject_CallMethod(guiMod, (char*)"handleApplicationQuit", NULL); if(!ret && PyErr_Occurred()) PyErr_Print(); Py_XDECREF(ret); } void QtApp::openWindowViaMenu() { if(sender() == NULL) { printf("QtApp::openWindowViaMenu: no sender\n"); return; } QAction* act = qobject_cast<QAction*>(sender()); if(!act) { printf("QtApp::openWindowViaMenu: sender is not QAction\n"); return; } if(act->objectName().isEmpty()) { printf("QtApp::openWindowViaMenu: sender name is empty\n"); return; } openWindow(act->objectName().toStdString()); } void QtApp::openMainWindow() { openWindow("Main"); } void QtApp::openWindow(const std::string& name) { QWidget* win = new QWidget(); win->setWindowTitle(QString::fromStdString(name)); // ... win->show(); } void QtApp::minimizeWindow() { QWidget* win = qApp->activeWindow(); if(win) win->showMinimized(); } void QtApp::closeWindow() { QWidget* win = qApp->activeWindow(); if(win) win->close(); } void QtApp::edit_cut() { QWidget* w = QApplication::focusWidget(); //... } void QtApp::edit_copy() { } void QtApp::edit_paste() { } void QtApp::edit_selectAll() { } void QtApp::handlePlayerUpdate() { updateControlMenu(); } void QtApp::playPause() { PyScopedGIL gil; PyObject* mod = getModule("State"); // borrowed if(!mod) return; PyObject* player = NULL; PyObject* playing = NULL; bool playingBool = false; player = attrChain(mod, "state.player"); if(!player) goto final; playing = PyObject_GetAttrString(player, "playing"); if(!playing) goto final; switch(PyObject_IsTrue(playing)) { case 1: playingBool = true; break; case 0: playingBool = false; break; default: goto final; } playingBool = !playingBool; PyObject_SetAttrString_retain(player, "playing", PyBool_FromLong(playingBool)); final: if(PyErr_Occurred()) PyErr_Print(); Py_XDECREF(player); Py_XDECREF(playing); } void QtApp::nextSong() { PyScopedGIL gil; PyObject* mod = getModule("State"); // borrowed if(!mod) return; PyObject* player = NULL; PyObject* ret = NULL; player = attrChain(mod, "state.player"); ret = PyObject_CallMethod(player, "nextSong", NULL); final: if(PyErr_Occurred()) PyErr_Print(); Py_XDECREF(player); Py_XDECREF(ret); } void QtApp::debug_resetPlayer() { } <|endoftext|>
<commit_before>#include <string> #include <stdio.h> #include <tag.h> #include <tstringlist.h> #include <tbytevectorlist.h> #include <tpropertymap.h> #include <oggfile.h> #include <vorbisfile.h> #include <oggpageheader.h> #include <cppunit/extensions/HelperMacros.h> #include "utils.h" using namespace std; using namespace TagLib; class TestOGG : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(TestOGG); CPPUNIT_TEST(testSimple); CPPUNIT_TEST(testSplitPackets); CPPUNIT_TEST(testDictInterface1); CPPUNIT_TEST(testDictInterface2); CPPUNIT_TEST_SUITE_END(); public: void testSimple() { ScopedFileCopy copy("empty", ".ogg"); string newname = copy.fileName(); Vorbis::File *f = new Vorbis::File(newname.c_str()); f->tag()->setArtist("The Artist"); f->save(); delete f; f = new Vorbis::File(newname.c_str()); CPPUNIT_ASSERT_EQUAL(String("The Artist"), f->tag()->artist()); delete f; } void testSplitPackets() { ScopedFileCopy copy("empty", ".ogg"); string newname = copy.fileName(); Vorbis::File *f = new Vorbis::File(newname.c_str()); f->tag()->addField("test", ByteVector(128 * 1024, 'x') + ByteVector(1, '\0')); f->save(); delete f; f = new Vorbis::File(newname.c_str()); CPPUNIT_ASSERT_EQUAL(19, f->lastPageHeader()->pageSequenceNumber()); delete f; } void testDictInterface1() { ScopedFileCopy copy("empty", ".ogg"); string newname = copy.fileName(); Vorbis::File *f = new Vorbis::File(newname.c_str()); CPPUNIT_ASSERT_EQUAL(TagLib::uint(0), f->tag()->properties().size()); PropertyMap newTags; StringList values("value 1"); values.append("value 2"); newTags["ARTIST"] = values; f->tag()->setProperties(newTags); PropertyMap map = f->tag()->properties(); CPPUNIT_ASSERT_EQUAL(TagLib::uint(1), map.size()); CPPUNIT_ASSERT_EQUAL(TagLib::uint(2), map["ARTIST"].size()); CPPUNIT_ASSERT_EQUAL(String("value 1"), map["ARTIST"][0]); delete f; } void testDictInterface2() { ScopedFileCopy copy("test", ".ogg"); string newname = copy.fileName(); Vorbis::File *f = new Vorbis::File(newname.c_str()); PropertyMap tags = f->tag()->properties(); CPPUNIT_ASSERT_EQUAL(TagLib::uint(2), tags["UNUSUALTAG"].size()); CPPUNIT_ASSERT_EQUAL(String("usual value"), tags["UNUSUALTAG"][0]); CPPUNIT_ASSERT_EQUAL(String("another value"), tags["UNUSUALTAG"][1]); CPPUNIT_ASSERT_EQUAL(String("öäüoΣø", String::UTF8), tags["UNICODETAG"][0]); tags["UNICODETAG"][0] = String("νεω ναλυε", String::UTF8); tags.erase("UNUSUALTAG"); f->tag()->setProperties(tags); CPPUNIT_ASSERT_EQUAL(String("νεω ναλυε", String::UTF8), f->tag()->properties()["UNICODETAG"][0]); CPPUNIT_ASSERT_EQUAL(false, f->tag()->properties().contains("UNUSUALTAG")); delete f; } }; CPPUNIT_TEST_SUITE_REGISTRATION(TestOGG); <commit_msg>Fixed a test to work with MSVC.<commit_after>#include <string> #include <stdio.h> #include <tag.h> #include <tstringlist.h> #include <tbytevectorlist.h> #include <tpropertymap.h> #include <oggfile.h> #include <vorbisfile.h> #include <oggpageheader.h> #include <cppunit/extensions/HelperMacros.h> #include "utils.h" using namespace std; using namespace TagLib; class TestOGG : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(TestOGG); CPPUNIT_TEST(testSimple); CPPUNIT_TEST(testSplitPackets); CPPUNIT_TEST(testDictInterface1); CPPUNIT_TEST(testDictInterface2); CPPUNIT_TEST_SUITE_END(); public: void testSimple() { ScopedFileCopy copy("empty", ".ogg"); string newname = copy.fileName(); Vorbis::File *f = new Vorbis::File(newname.c_str()); f->tag()->setArtist("The Artist"); f->save(); delete f; f = new Vorbis::File(newname.c_str()); CPPUNIT_ASSERT_EQUAL(String("The Artist"), f->tag()->artist()); delete f; } void testSplitPackets() { ScopedFileCopy copy("empty", ".ogg"); string newname = copy.fileName(); Vorbis::File *f = new Vorbis::File(newname.c_str()); f->tag()->addField("test", ByteVector(128 * 1024, 'x') + ByteVector(1, '\0')); f->save(); delete f; f = new Vorbis::File(newname.c_str()); CPPUNIT_ASSERT_EQUAL(19, f->lastPageHeader()->pageSequenceNumber()); delete f; } void testDictInterface1() { ScopedFileCopy copy("empty", ".ogg"); string newname = copy.fileName(); Vorbis::File *f = new Vorbis::File(newname.c_str()); CPPUNIT_ASSERT_EQUAL(TagLib::uint(0), f->tag()->properties().size()); PropertyMap newTags; StringList values("value 1"); values.append("value 2"); newTags["ARTIST"] = values; f->tag()->setProperties(newTags); PropertyMap map = f->tag()->properties(); CPPUNIT_ASSERT_EQUAL(TagLib::uint(1), map.size()); CPPUNIT_ASSERT_EQUAL(TagLib::uint(2), map["ARTIST"].size()); CPPUNIT_ASSERT_EQUAL(String("value 1"), map["ARTIST"][0]); delete f; } void testDictInterface2() { ScopedFileCopy copy("test", ".ogg"); string newname = copy.fileName(); Vorbis::File *f = new Vorbis::File(newname.c_str()); PropertyMap tags = f->tag()->properties(); CPPUNIT_ASSERT_EQUAL(TagLib::uint(2), tags["UNUSUALTAG"].size()); CPPUNIT_ASSERT_EQUAL(String("usual value"), tags["UNUSUALTAG"][0]); CPPUNIT_ASSERT_EQUAL(String("another value"), tags["UNUSUALTAG"][1]); CPPUNIT_ASSERT_EQUAL( String("\xC3\xB6\xC3\xA4\xC3\xBC\x6F\xCE\xA3\xC3\xB8", String::UTF8), tags["UNICODETAG"][0]); tags["UNICODETAG"][0] = String( "\xCE\xBD\xCE\xB5\xCF\x89\x20\xCE\xBD\xCE\xB1\xCE\xBB\xCF\x85\xCE\xB5", String::UTF8); tags.erase("UNUSUALTAG"); f->tag()->setProperties(tags); CPPUNIT_ASSERT_EQUAL( String("\xCE\xBD\xCE\xB5\xCF\x89\x20\xCE\xBD\xCE\xB1\xCE\xBB\xCF\x85\xCE\xB5", String::UTF8), f->tag()->properties()["UNICODETAG"][0]); CPPUNIT_ASSERT_EQUAL(false, f->tag()->properties().contains("UNUSUALTAG")); delete f; } }; CPPUNIT_TEST_SUITE_REGISTRATION(TestOGG); <|endoftext|>
<commit_before>//======================================================== // Hazi feladat keret. // A //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // sorokon beluli reszben celszeru garazdalkodni, mert // a tobbit ugyis toroljuk. // A Hazi feladat csak ebben a fajlban lehet // Tilos: // - mast "beincludolni", illetve mas konyvtarat hasznalni // - faljmuveleteket vegezni //======================================================== #include <math.h> #include <stdlib.h> #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) // MsWindows-on ez is kell #include <windows.h> #else // g++ nem fordit a stanard include-ok nelkul :-/ #include <string.h> #endif // Win32 platform #include <GL/gl.h> #include <GL/glu.h> // A GLUT-ot le kell tolteni: http://www.opengl.org/resources/libraries/glut/ #include <GL/glut.h> #include <stdio.h> //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Innentol modosithatod... //-------------------------------------------------------- // Nev: // Neptun: //-------------------------------------------------------- #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) class Vector { public: float x, y, z; Vector(float x0, float y0, float z0) { x = x0; y = y0; z = z0; } Vector operator+(const Vector& v) { return Vector(x + v.x, y + v.y, z + v.z); } Vector operator*(float f) { return Vector(x * f, y * f, z * f); } }; class Matrix { public: float m[4][4]; void Clear() { memset(&m[0][0], 0, sizeof(m)); } void LoadIdentify() { Clear(); m[0][0] = m[1][1] = m[2][2] = m[3][3] = 1; } Vector operator*(const Vector& v) { float Xh = m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3]; float Yh = m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3]; float Zh = m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3]; float h = m[3][0] * v.x + m[3][1] * v.y + m[3][2] * v.z + m[3][3]; return Vector(Xh/h, Yh/h, Zh/h); } }; enum { NOOP = 0, SCALE, ROTATE, SHIFT }; // csak mert math.ht nemszabad ;-/ # define M_PI 3.14159265358979323846 const Vector* points[2][7]; Matrix* transs[3]; int trans_state = ROTATE; void onInitialization( ) { points[0][0] = new Vector(10, 20, 0); points[0][1] = new Vector(100, 80, 0); points[0][2] = new Vector(120, 20, 0); points[0][3] = new Vector(210, 80, 0); points[0][4] = new Vector(230, 20, 0); points[0][5] = new Vector(320, 80, 0); points[0][6] = new Vector(340, 20, 0); points[1][0] = new Vector(10, 120, 0); points[1][1] = new Vector(100, 180, 0); points[1][2] = new Vector(120, 120, 0); points[1][3] = new Vector(210, 180, 0); points[1][4] = new Vector(230, 120, 0); points[1][5] = new Vector(320, 180, 0); points[1][6] = new Vector(340, 120, 0); /* * 1 0 0 0 * 0 1 0 0 * 0 0 1 0 * 0 0 0 1 */ transs[NOOP] = new Matrix(); transs[NOOP]->LoadIdentify(); /* * 0.5 0 0 0 * 0 0.5 0 0 * 0 0 0.5 0 * 0 0 0 1 */ transs[SCALE] = new Matrix(); transs[SCALE]->LoadIdentify(); transs[SCALE]->m[0][0] = 0.5; transs[SCALE]->m[1][1] = 0.5; transs[SCALE]->m[2][2] = 0.5; /* * cos sin 0 0 * -sin cos 0 0 * 0 0 1 0 * 0 0 0 1 */ float angle = M_PI/4; transs[ROTATE] = new Matrix(); transs[ROTATE]->LoadIdentify(); transs[ROTATE]->m[0][0] = cosf(angle); transs[ROTATE]->m[0][1] = -sinf(angle); transs[ROTATE]->m[1][0] = sinf(angle); transs[ROTATE]->m[1][1] = cosf(angle); gluOrtho2D(0., 500., 0., 500.); } void onDisplay( ) { glClearColor(0.1f, 0.2f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glColor4d(0.9f, 0.8f, 0.7f, 1.0f); for (int i = 0; i < ARRAY_SIZE(points); i++) { glBegin(GL_LINE_STRIP); for (int j = 0; j < ARRAY_SIZE(points[i]); j++) { Vector v = *transs[trans_state] * *points[i][j]; glVertex2d(v.x, v.y); } glEnd(); } // Buffercsere: rajzolas vege glFinish(); glutSwapBuffers(); } void onMouse(int button, int state, int x, int y) { // A GLUT_LEFT_BUTTON / GLUT_RIGHT_BUTTON // ill. a GLUT_DOWN / GLUT_UP makrokat hasznald. } void onIdle( ) { } void onKeyboard(unsigned char key, int x, int y) { } // ...Idaig modosithatod //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ int main(int argc, char **argv) { glutInit(&argc, argv); glutInitWindowSize(600, 600); glutInitWindowPosition(100, 100); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutCreateWindow("Grafika hazi feladat"); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); onInitialization(); glutDisplayFunc(onDisplay); glutMouseFunc(onMouse); glutIdleFunc(onIdle); glutKeyboardFunc(onKeyboard); glutMainLoop(); return 0; } <commit_msg>megy az eltolas is<commit_after>//======================================================== // Hazi feladat keret. // A //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // sorokon beluli reszben celszeru garazdalkodni, mert // a tobbit ugyis toroljuk. // A Hazi feladat csak ebben a fajlban lehet // Tilos: // - mast "beincludolni", illetve mas konyvtarat hasznalni // - faljmuveleteket vegezni //======================================================== #include <math.h> #include <stdlib.h> #if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) // MsWindows-on ez is kell #include <windows.h> #else // g++ nem fordit a stanard include-ok nelkul :-/ #include <string.h> #endif // Win32 platform #include <GL/gl.h> #include <GL/glu.h> // A GLUT-ot le kell tolteni: http://www.opengl.org/resources/libraries/glut/ #include <GL/glut.h> #include <stdio.h> //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Innentol modosithatod... //-------------------------------------------------------- // Nev: // Neptun: //-------------------------------------------------------- #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) class Vector { public: float x, y, z; Vector(float x0, float y0, float z0) { x = x0; y = y0; z = z0; } Vector operator+(const Vector& v) { return Vector(x + v.x, y + v.y, z + v.z); } Vector operator*(float f) { return Vector(x * f, y * f, z * f); } }; class Matrix { public: float m[4][4]; void Clear() { memset(&m[0][0], 0, sizeof(m)); } void LoadIdentify() { Clear(); m[0][0] = m[1][1] = m[2][2] = m[3][3] = 1; } Vector operator*(const Vector& v) { float Xh = m[0][0] * v.x + m[0][1] * v.y + m[0][2] * v.z + m[0][3]; float Yh = m[1][0] * v.x + m[1][1] * v.y + m[1][2] * v.z + m[1][3]; float Zh = m[2][0] * v.x + m[2][1] * v.y + m[2][2] * v.z + m[2][3]; float h = m[3][0] * v.x + m[3][1] * v.y + m[3][2] * v.z + m[3][3]; return Vector(Xh/h, Yh/h, Zh/h); } }; enum { NOOP = 0, SCALE, ROTATE, SHIFT }; int trans_state = SHIFT; // csak mert math.ht nemszabad ;-/ # define M_PI 3.14159265358979323846 const Vector* points[2][7]; Matrix* transs[4]; void onInitialization( ) { points[0][0] = new Vector(10, 20, 0); points[0][1] = new Vector(100, 80, 0); points[0][2] = new Vector(120, 20, 0); points[0][3] = new Vector(210, 80, 0); points[0][4] = new Vector(230, 20, 0); points[0][5] = new Vector(320, 80, 0); points[0][6] = new Vector(340, 20, 0); points[1][0] = new Vector(10, 120, 0); points[1][1] = new Vector(100, 180, 0); points[1][2] = new Vector(120, 120, 0); points[1][3] = new Vector(210, 180, 0); points[1][4] = new Vector(230, 120, 0); points[1][5] = new Vector(320, 180, 0); points[1][6] = new Vector(340, 120, 0); /* * 1 0 0 0 * 0 1 0 0 * 0 0 1 0 * 0 0 0 1 */ transs[NOOP] = new Matrix(); transs[NOOP]->LoadIdentify(); /* * 0.5 0 0 0 * 0 0.5 0 0 * 0 0 0.5 0 * 0 0 0 1 */ transs[SCALE] = new Matrix(); transs[SCALE]->LoadIdentify(); transs[SCALE]->m[0][0] = 0.5; transs[SCALE]->m[1][1] = 0.5; transs[SCALE]->m[2][2] = 0.5; /* * cos sin 0 0 * -sin cos 0 0 * 0 0 1 0 * 0 0 0 1 */ float angle = M_PI/4; transs[ROTATE] = new Matrix(); transs[ROTATE]->LoadIdentify(); transs[ROTATE]->m[0][0] = cosf(angle); transs[ROTATE]->m[0][1] = -sinf(angle); transs[ROTATE]->m[1][0] = sinf(angle); transs[ROTATE]->m[1][1] = cosf(angle); /* * 1 0 0 0 * 0 1 0 0 * 0 0 1 0 * px py pz 1 */ transs[SHIFT] = new Matrix(); transs[SHIFT]->LoadIdentify(); transs[SHIFT]->m[1][3] = 100; gluOrtho2D(0., 500., 0., 500.); } void onDisplay( ) { glClearColor(0.1f, 0.2f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glColor4d(0.9f, 0.8f, 0.7f, 1.0f); for (int i = 0; i < ARRAY_SIZE(points); i++) { glBegin(GL_LINE_STRIP); for (int j = 0; j < ARRAY_SIZE(points[i]); j++) { Vector v = *transs[trans_state] * *points[i][j]; glVertex2d(v.x, v.y); } glEnd(); } // Buffercsere: rajzolas vege glFinish(); glutSwapBuffers(); } void onMouse(int button, int state, int x, int y) { // A GLUT_LEFT_BUTTON / GLUT_RIGHT_BUTTON // ill. a GLUT_DOWN / GLUT_UP makrokat hasznald. } void onIdle( ) { } void onKeyboard(unsigned char key, int x, int y) { } // ...Idaig modosithatod //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ int main(int argc, char **argv) { glutInit(&argc, argv); glutInitWindowSize(600, 600); glutInitWindowPosition(100, 100); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutCreateWindow("Grafika hazi feladat"); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); onInitialization(); glutDisplayFunc(onDisplay); glutMouseFunc(onMouse); glutIdleFunc(onIdle); glutKeyboardFunc(onKeyboard); glutMainLoop(); return 0; } <|endoftext|>
<commit_before>#ifndef ALEPH_TOPOLOGY_IO_PLY_HH__ #define ALEPH_TOPOLOGY_IO_PLY_HH__ #include "filtrations/Data.hh" #include "utilities/String.hh" #include "topology/Simplex.hh" #include "topology/SimplicialComplex.hh" #include <cassert> #include <fstream> #include <limits> #include <map> #include <set> #include <stdexcept> #include <string> #include <utility> #include <vector> namespace aleph { namespace topology { namespace io { namespace detail { /* Maps PLY data types to their corresponding sizes in bytes. This is required for parsing binary files later on. */ std::map<std::string, unsigned short> TypeSizeMap = { { "double" , 8 }, { "float" , 4 }, { "int" , 4 }, { "int32" , 4 }, { "uint" , 4 }, { "uint32" , 4 }, { "short" , 2 }, { "ushort" , 2 }, { "char" , 1 }, { "uchar" , 1 }, { "uint8" , 1 } }; /* Reads a single value from a binary input stream, reversing the storage order if necessary. */ template <class T> void readValue( std::ifstream& stream, std::size_t bytes, bool reverse, T& target ) { if( !reverse || bytes == 1 ) stream.read( reinterpret_cast<char*>( &target ), static_cast<std::streamsize>( bytes ) ); else { char* buffer = new char[bytes]; char* reversedBuffer = new char[bytes]; stream.read( buffer, static_cast<std::streamsize>( bytes ) ); for( std::size_t i = 0; i < bytes; i++ ) reversedBuffer[i] = buffer[ bytes - 1 - i ]; std::copy( reversedBuffer, reversedBuffer + bytes, target ); // FIXME: Superfluous? #if 0 memcpy( reinterpret_cast<void*>( &target ), reinterpret_cast<void*>( reversedBuffer ), bytes ); #endif delete[] reversedBuffer; delete[] buffer; } } } // namespace detail /** @class PLYReader @brief Parses PLY files This is a simple reader class for files in PLY format. It supports reading PLY files with an arbitrary number of vertex properties. A user may specify which property to use in order to assign the data stored for each simplex. */ class PLYReader { public: // Contains all descriptors for a single PLY property. The number of // elements is somewhat superfluous when parsing ASCII files. struct PropertyDescriptor { std::string name; // Property name (or list name) unsigned index; // Offset of attribute for ASCII data unsigned bytesOffset; // Offset of attribute for binary data unsigned bytes; // Number of bytes // Only used for lists: Here, both the length parameter and the // entry parameter of a list usually have different lengths. unsigned bytesListSize; unsigned bytesListEntry; }; template <class SimplicialComplex> void operator()( const std::string& filename, SimplicialComplex& K ) { std::ifstream in( filename ); if( !in ) throw std::runtime_error( "Unable to read input file" ); this->operator()( in, K ); } template <class SimplicialComplex> void operator()( std::ifstream& in, SimplicialComplex& K ) { // Header ------------------------------------------------------------ // // The header needs to consist of the word "ply", followed by a "format" // description. std::size_t numVertices = 0; // Number of edges std::size_t vertexSizeInBytes = 0; // Only relevant for binary files std::size_t numFaces = 0; // Number of faces std::size_t faceSizeInBytes = 0; // Only relevant for binary files // Current line in file. This is required because I prefer reading the // file line by line via `std::getline`. std::string line; bool headerParsed = false; bool parseBinary = false; bool littleEndian = false; std::getline( in, line ); line = utilities::trim( line ); if( line != "ply" ) throw std::runtime_error( "Format error: Expecting \"ply\"" ); std::getline( in, line ); line = utilities::trim( line ); if( line.substr( 0, 6 ) != "format" ) throw std::runtime_error( "Format error: Expecting \"format\"" ); else { std::string format = line.substr( 6 ); format = utilities::trim( format ); if( format == "ascii 1.0" ) parseBinary = false; else if( format == "binary_little_endian 1.0" ) { parseBinary = true; littleEndian = true; } else if( format == "binary_big_endian 1.0" ) { parseBinary = true; littleEndian = false; } else throw std::runtime_error( "Format error: Expecting \"ascii 1.0\" or \"binary_little_endian 1.0\" or \"binary_big_endian 1.0\" " ); } // All properties stored in the PLY file in the order in which they // were discovered. The parse requires the existence of some of the // properties, e.g. "x", "y", and "z" in order to work correctly. std::vector<PropertyDescriptor> properties; unsigned propertyIndex = 0; // Offset for properties in ASCII files unsigned propertyOffset = 0; // Offset for properties in binary files bool readingVertexProperties = false; bool readingFaceProperties = false; // Parse the rest of the header, taking care to skip any comment lines. do { std::getline( in, line ); line = utilities::trim( line ); if( !in ) break; if( line.substr( 0, 7 ) == "comment" ) continue; else if( line.substr( 0, 7) == "element" ) { std::string element = line.substr( 7 ); element = utilities::trim( element ); std::istringstream converter( element ); std::string name; std::size_t numElements = 0; converter >> name >> numElements; if( !converter ) throw std::runtime_error( "Element conversion error: Expecting number of elements" ); name = utilities::trim( name ); if( name == "vertex" ) { numVertices = numElements; readingVertexProperties = true; } else if( name == "face" ) { numFaces = numElements; readingFaceProperties = true; } } else if( line.substr( 0, 8) == "property" ) { std::string property = line.substr( 8 ); property = utilities::trim( property ); std::istringstream converter( property ); std::string dataType; std::string name; converter >> dataType >> name; dataType = utilities::trim( dataType ); name = utilities::trim( name ); PropertyDescriptor descriptor; descriptor.index = propertyIndex; // List of properties require a special handling. The syntax is // "property list SIZE_TYPE ENTRY_TYPE NAME", e.g. "property // list uint float vertex_height". if( dataType == "list" ) { std::string sizeType = name; std::string entryType; std::string listName; converter >> entryType >> listName; utilities::trim( entryType ); utilities::trim( listName ); descriptor.bytesListSize = detail::TypeSizeMap.at( sizeType ); descriptor.bytesListEntry = detail::TypeSizeMap.at( entryType ); descriptor.name = listName; } else { descriptor.bytes = detail::TypeSizeMap.at( dataType ); descriptor.bytesOffset = propertyOffset; descriptor.name = name; } if( !converter ) throw std::runtime_error( "Property conversion error: Expecting data type and name of property" ); if( readingFaceProperties ) faceSizeInBytes += descriptor.bytes; else if( readingVertexProperties ) vertexSizeInBytes += descriptor.bytes; propertyOffset += descriptor.bytes; propertyIndex += 1; properties.push_back( descriptor ); } if( line == "end_header" ) { headerParsed = true; break; } } while( !headerParsed && in ); assert( numVertices > 0 ); assert( numFaces > 0 ); using Simplex = typename SimplicialComplex::ValueType; // Container for storing all simplices that are created while reading // the mesh data structure. std::vector<Simplex> simplices; if( parseBinary ) { } else simplices = this->parseASCII<Simplex>( in, numVertices, numFaces, properties ); in.close(); K = SimplicialComplex( simplices.begin(), simplices.end() ); K.recalculateWeights(); K.sort( filtrations::Data<Simplex>() ); } /* Sets the property to read for every simplex */ void setDataProperty( const std::string& property ) { _property = property; } private: template <class Simplex> std::vector<Simplex> parseASCII( std::ifstream& in, std::size_t numVertices, std::size_t numFaces, const std::vector<PropertyDescriptor>& properties ) { using DataType = typename Simplex::DataType; using VertexType = typename Simplex::VertexType; std::vector<Simplex> simplices; std::string line; auto getPropertyIndex = [&properties] ( const std::string& property ) { auto it = std::find_if( properties.begin(), properties.end(), [&property] ( const PropertyDescriptor& descriptor ) { return descriptor.name == property; } ); if( it != properties.end() ) return it->index; else return std::numeric_limits<unsigned>::max(); }; // Read vertices ----------------------------------------------------- for( std::size_t vertexIndex = 0; vertexIndex < numVertices; vertexIndex++ ) { std::vector<double> vertexCoordinates( 3 ); std::getline( in, line ); line = utilities::trim( line ); auto tokens = utilities::split( line ); auto ix = getPropertyIndex( "x" ); auto iy = getPropertyIndex( "y" ); auto iz = getPropertyIndex( "z" ); auto iw = getPropertyIndex( _property ); auto x = std::stod( tokens.at( ix ) ); auto y = std::stod( tokens.at( iy ) ); auto z = std::stod( tokens.at( iz ) ); _coordinates.push_back( {x,y,z} ); // No property for reading weights specified, or the specified // property could not be found; just use the default weight of // the simplex class. if( _property.empty() || iw == std::numeric_limits<unsigned>::max() ) simplices.push_back( { VertexType( vertexIndex ) } ); else { DataType w = aleph::utilities::convert<DataType>( tokens.at(iw) ); simplices.push_back( Simplex( VertexType( vertexIndex ), w ) ); } } // Read faces -------------------------------------------------------- // Keep track of all edges that are encountered. This ensures that the // simplicial complex is valid upon construction and does not have any // missing simplices. std::set< std::pair<VertexType, VertexType> > edges; for( std::size_t faceIndex = 0; faceIndex < numFaces; faceIndex++ ) { std::getline( in, line ); std::istringstream converter( line ); unsigned numEntries = 0; converter >> numEntries; if( !converter ) throw std::runtime_error( "Face conversion error: Expecting number of entries" ); // I can make a simplex out of a triangle, but every other shape would // get complicated. if( numEntries == 3 ) { VertexType i1 = 0; VertexType i2 = 0; VertexType i3 = 0; converter >> i1 >> i2 >> i3; if( !converter ) throw std::runtime_error( "Unable to parse vertex indices" ); Simplex triangle( {i1,i2,i3} ); // Create edges ---------------------------------------------- for( auto itEdge = triangle.begin_boundary(); itEdge != triangle.end_boundary(); ++itEdge ) { // As the boundary iterator works as a filtered iterator only, // I need this copy. // // Else, different calls to `begin()` and `end()` will result in // two different copies of the simplex. The copies, in turn, // will then not be usable as a source for vertices. Simplex edge = *itEdge; auto u = *( edge.begin() ); auto v = *( edge.begin() + 1 ); if( u < v ) std::swap( u, v ); auto pair = edges.insert( std::make_pair( u,v ) ); if( pair.second ) simplices.push_back( Simplex( edge.begin(), edge.end() ) ); } simplices.push_back( triangle ); } else throw std::runtime_error( "Format error: Expecting triangular faces only" ); } return simplices; } /** Data property to assign to new simplices */ std::string _property = "z"; /** Coordinates stored by the current run of the reader */ std::vector< std::vector<double> > _coordinates; }; } // namespace io } // namespace topology } // namespace aleph #endif <commit_msg>Reading vertices of binary PLY files<commit_after>#ifndef ALEPH_TOPOLOGY_IO_PLY_HH__ #define ALEPH_TOPOLOGY_IO_PLY_HH__ #include "filtrations/Data.hh" #include "utilities/String.hh" #include "topology/Simplex.hh" #include "topology/SimplicialComplex.hh" #include <cassert> #include <fstream> #include <limits> #include <map> #include <set> #include <stdexcept> #include <string> #include <utility> #include <vector> namespace aleph { namespace topology { namespace io { namespace detail { /* Maps PLY data types to their corresponding sizes in bytes. This is required for parsing binary files later on. */ std::map<std::string, unsigned short> TypeSizeMap = { { "double" , 8 }, { "float" , 4 }, { "int" , 4 }, { "int32" , 4 }, { "uint" , 4 }, { "uint32" , 4 }, { "short" , 2 }, { "ushort" , 2 }, { "char" , 1 }, { "uchar" , 1 }, { "uint8" , 1 } }; /* Maps PLY data types to their 'signedness'. This is required for parsing binary files later on. TODO: Use this to extend parse */ std::map<std::string, bool> TypeSignednessMap = { { "double" , true }, { "float" , true }, { "int" , true }, { "int32" , true }, { "uint" , false }, { "uint32" , false }, { "short" , true }, { "ushort" , false }, { "char" , true }, { "uchar" , false }, { "uint8" , false } }; /* Describes an arbitrary value of a PLY file */ union PLYValue { double d; float f; int i; short s; char c; unsigned u; unsigned short us; unsigned char uc; }; /* Reads a single value from a binary input stream, reversing the storage order if necessary. */ template <class T> void readValue( std::ifstream& stream, std::size_t bytes, bool littleEndian, T* target ) { if( !littleEndian || bytes == 1 ) stream.read( reinterpret_cast<char*>( target ), static_cast<std::streamsize>( bytes ) ); else { char* buffer = new char[bytes]; char* reversedBuffer = new char[bytes]; stream.read( buffer, static_cast<std::streamsize>( bytes ) ); for( std::size_t i = 0; i < bytes; i++ ) reversedBuffer[i] = buffer[ bytes - 1 - i ]; std::copy( reversedBuffer, reversedBuffer + bytes, target ); // FIXME: Superfluous? #if 0 memcpy( reinterpret_cast<void*>( &target ), reinterpret_cast<void*>( reversedBuffer ), bytes ); #endif delete[] reversedBuffer; delete[] buffer; } } } // namespace detail /** @class PLYReader @brief Parses PLY files This is a simple reader class for files in PLY format. It supports reading PLY files with an arbitrary number of vertex properties. A user may specify which property to use in order to assign the data stored for each simplex. */ class PLYReader { public: // Contains all descriptors for a single PLY property. The number of // elements is somewhat superfluous when parsing ASCII files. struct PropertyDescriptor { std::string name; // Property name (or list name) unsigned index; // Offset of attribute for ASCII data unsigned bytesOffset; // Offset of attribute for binary data unsigned bytes; // Number of bytes // Only used for lists: Here, both the length parameter and the // entry parameter of a list usually have different lengths. unsigned bytesListSize; unsigned bytesListEntry; }; template <class SimplicialComplex> void operator()( const std::string& filename, SimplicialComplex& K ) { std::ifstream in( filename ); if( !in ) throw std::runtime_error( "Unable to read input file" ); this->operator()( in, K ); } template <class SimplicialComplex> void operator()( std::ifstream& in, SimplicialComplex& K ) { // Header ------------------------------------------------------------ // // The header needs to consist of the word "ply", followed by a "format" // description. std::size_t numVertices = 0; // Number of edges std::size_t vertexSizeInBytes = 0; // Only relevant for binary files std::size_t numFaces = 0; // Number of faces std::size_t faceSizeInBytes = 0; // Only relevant for binary files // Current line in file. This is required because I prefer reading the // file line by line via `std::getline`. std::string line; bool headerParsed = false; bool parseBinary = false; bool littleEndian = false; std::getline( in, line ); line = utilities::trim( line ); if( line != "ply" ) throw std::runtime_error( "Format error: Expecting \"ply\"" ); std::getline( in, line ); line = utilities::trim( line ); if( line.substr( 0, 6 ) != "format" ) throw std::runtime_error( "Format error: Expecting \"format\"" ); else { std::string format = line.substr( 6 ); format = utilities::trim( format ); if( format == "ascii 1.0" ) parseBinary = false; else if( format == "binary_little_endian 1.0" ) { parseBinary = true; littleEndian = true; } else if( format == "binary_big_endian 1.0" ) { parseBinary = true; littleEndian = false; } else throw std::runtime_error( "Format error: Expecting \"ascii 1.0\" or \"binary_little_endian 1.0\" or \"binary_big_endian 1.0\" " ); } // All properties stored in the PLY file in the order in which they // were discovered. The parse requires the existence of some of the // properties, e.g. "x", "y", and "z" in order to work correctly. std::vector<PropertyDescriptor> properties; unsigned propertyIndex = 0; // Offset for properties in ASCII files unsigned propertyOffset = 0; // Offset for properties in binary files bool readingVertexProperties = false; bool readingFaceProperties = false; // Parse the rest of the header, taking care to skip any comment lines. do { std::getline( in, line ); line = utilities::trim( line ); if( !in ) break; if( line.substr( 0, 7 ) == "comment" ) continue; else if( line.substr( 0, 7) == "element" ) { std::string element = line.substr( 7 ); element = utilities::trim( element ); std::istringstream converter( element ); std::string name; std::size_t numElements = 0; converter >> name >> numElements; if( !converter ) throw std::runtime_error( "Element conversion error: Expecting number of elements" ); name = utilities::trim( name ); if( name == "vertex" ) { numVertices = numElements; readingVertexProperties = true; } else if( name == "face" ) { numFaces = numElements; readingFaceProperties = true; } } else if( line.substr( 0, 8) == "property" ) { std::string property = line.substr( 8 ); property = utilities::trim( property ); std::istringstream converter( property ); std::string dataType; std::string name; converter >> dataType >> name; dataType = utilities::trim( dataType ); name = utilities::trim( name ); PropertyDescriptor descriptor; descriptor.index = propertyIndex; // List of properties require a special handling. The syntax is // "property list SIZE_TYPE ENTRY_TYPE NAME", e.g. "property // list uint float vertex_height". if( dataType == "list" ) { std::string sizeType = name; std::string entryType; std::string listName; converter >> entryType >> listName; utilities::trim( entryType ); utilities::trim( listName ); descriptor.bytesListSize = detail::TypeSizeMap.at( sizeType ); descriptor.bytesListEntry = detail::TypeSizeMap.at( entryType ); descriptor.name = listName; } else { descriptor.bytes = detail::TypeSizeMap.at( dataType ); descriptor.bytesOffset = propertyOffset; descriptor.name = name; } if( !converter ) throw std::runtime_error( "Property conversion error: Expecting data type and name of property" ); if( readingFaceProperties ) faceSizeInBytes += descriptor.bytes; else if( readingVertexProperties ) vertexSizeInBytes += descriptor.bytes; propertyOffset += descriptor.bytes; propertyIndex += 1; properties.push_back( descriptor ); } if( line == "end_header" ) { headerParsed = true; break; } } while( !headerParsed && in ); assert( numVertices > 0 ); assert( numFaces > 0 ); using Simplex = typename SimplicialComplex::ValueType; // Container for storing all simplices that are created while reading // the mesh data structure. std::vector<Simplex> simplices; if( parseBinary ) { simplices = this->parseBinary<Simplex>( in, numVertices, numFaces, littleEndian, properties ); } else { simplices = this->parseASCII<Simplex>( in, numVertices, numFaces, properties ); } in.close(); K = SimplicialComplex( simplices.begin(), simplices.end() ); K.recalculateWeights(); K.sort( filtrations::Data<Simplex>() ); } /* Sets the property to read for every simplex */ void setDataProperty( const std::string& property ) { _property = property; } private: template <class Simplex> std::vector<Simplex> parseBinary( std::ifstream& in, std::size_t numVertices, std::size_t numFaces, bool littleEndian, const std::vector<PropertyDescriptor>& properties ) { using DataType = typename Simplex::DataType; using VertexType = typename Simplex::VertexType; DataType weight = DataType(); for( std::size_t vertexIndex = 0; vertexIndex < numVertices; vertexIndex++ ) { std::vector<double> coordinates; for( auto&& descriptor : properties ) { // Only faces may have lists for now... if( descriptor.bytesListSize + descriptor.bytesListEntry != 0 ) continue; detail::PLYValue pv; switch( descriptor.bytes ) { case 8: detail::readValue( in, descriptor.bytes, littleEndian, &pv.d ); break; case 4: detail::readValue( in, descriptor.bytes, littleEndian, &pv.f ); break; case 2: detail::readValue( in, descriptor.bytes, littleEndian, &pv.s ); break; case 1: detail::readValue( in, descriptor.bytes, littleEndian, &pv.c ); break; } // FIXME: Not sure whether this is legal... if( descriptor.name == "x" || descriptor.name == "y" || descriptor.name == "z" ) coordinates.push_back( pv.d ); } } for( std::size_t faceIndex = 0; faceIndex < numVertices; faceIndex++ ) { } } template <class Simplex> std::vector<Simplex> parseASCII( std::ifstream& in, std::size_t numVertices, std::size_t numFaces, const std::vector<PropertyDescriptor>& properties ) { using DataType = typename Simplex::DataType; using VertexType = typename Simplex::VertexType; std::vector<Simplex> simplices; std::string line; auto getPropertyIndex = [&properties] ( const std::string& property ) { auto it = std::find_if( properties.begin(), properties.end(), [&property] ( const PropertyDescriptor& descriptor ) { return descriptor.name == property; } ); if( it != properties.end() ) return it->index; else return std::numeric_limits<unsigned>::max(); }; // Read vertices ----------------------------------------------------- for( std::size_t vertexIndex = 0; vertexIndex < numVertices; vertexIndex++ ) { std::vector<double> vertexCoordinates( 3 ); std::getline( in, line ); line = utilities::trim( line ); auto tokens = utilities::split( line ); auto ix = getPropertyIndex( "x" ); auto iy = getPropertyIndex( "y" ); auto iz = getPropertyIndex( "z" ); auto iw = getPropertyIndex( _property ); auto x = std::stod( tokens.at( ix ) ); auto y = std::stod( tokens.at( iy ) ); auto z = std::stod( tokens.at( iz ) ); _coordinates.push_back( {x,y,z} ); // No property for reading weights specified, or the specified // property could not be found; just use the default weight of // the simplex class. if( _property.empty() || iw == std::numeric_limits<unsigned>::max() ) simplices.push_back( { VertexType( vertexIndex ) } ); else { DataType w = aleph::utilities::convert<DataType>( tokens.at(iw) ); simplices.push_back( Simplex( VertexType( vertexIndex ), w ) ); } } // Read faces -------------------------------------------------------- // Keep track of all edges that are encountered. This ensures that the // simplicial complex is valid upon construction and does not have any // missing simplices. std::set< std::pair<VertexType, VertexType> > edges; for( std::size_t faceIndex = 0; faceIndex < numFaces; faceIndex++ ) { std::getline( in, line ); std::istringstream converter( line ); unsigned numEntries = 0; converter >> numEntries; if( !converter ) throw std::runtime_error( "Face conversion error: Expecting number of entries" ); // I can make a simplex out of a triangle, but every other shape would // get complicated. if( numEntries == 3 ) { VertexType i1 = 0; VertexType i2 = 0; VertexType i3 = 0; converter >> i1 >> i2 >> i3; if( !converter ) throw std::runtime_error( "Unable to parse vertex indices" ); Simplex triangle( {i1,i2,i3} ); // Create edges ---------------------------------------------- for( auto itEdge = triangle.begin_boundary(); itEdge != triangle.end_boundary(); ++itEdge ) { // As the boundary iterator works as a filtered iterator only, // I need this copy. // // Else, different calls to `begin()` and `end()` will result in // two different copies of the simplex. The copies, in turn, // will then not be usable as a source for vertices. Simplex edge = *itEdge; auto u = *( edge.begin() ); auto v = *( edge.begin() + 1 ); if( u < v ) std::swap( u, v ); auto pair = edges.insert( std::make_pair( u,v ) ); if( pair.second ) simplices.push_back( Simplex( edge.begin(), edge.end() ) ); } simplices.push_back( triangle ); } else throw std::runtime_error( "Format error: Expecting triangular faces only" ); } return simplices; } /** Data property to assign to new simplices */ std::string _property = "z"; /** Coordinates stored by the current run of the reader */ std::vector< std::vector<double> > _coordinates; }; } // namespace io } // namespace topology } // namespace aleph #endif <|endoftext|>
<commit_before>#include "DXResourceContext.h" DXResourceContext::DXResourceContext() { mDevice = 0; mContext = 0; mSwapChain = 0; mPrimaryRT = 0; mPostProcessRT = 0; mBackBufferRT = 0; mPrimaryRTV = 0; mPostProcessRTV = 0; mBackBufferRTV = 0; mDepthStencilView = 0; } DXResourceContext::~DXResourceContext() { release(); } HRESULT DXResourceContext::createDevice() { // This will hold options for DirectX initialization unsigned int deviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) // If we're in debug mode in visual studio, we also // want to make a "Debug DirectX Device" to see some // errors and warnings in Visual Studio's output window // when things go wrong! deviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif HRESULT hr = D3D11CreateDevice( 0, // Video adapter (physical GPU) to use, or null for default D3D_DRIVER_TYPE_HARDWARE, // We want to use the hardware (GPU) 0, // Used when doing software rendering deviceFlags, // Any special options 0, // Optional array of possible verisons we want as fallbacks 0, // The number of fallbacks in the above param D3D11_SDK_VERSION, // Current version of the SDK &mDevice, &support.dxFeatureLevel, &mContext); return hr; } HRESULT DXResourceContext::checkMultiSampleSupport(UINT *sampleSize) { const UINT DXGI_FORMAT_MAX = 116; const UINT MAX_SAMPLES_CHECK = 128; //https://msdn.microsoft.com/en-us/library/windows/desktop/dn458384.aspx for (UINT i = 1; i < DXGI_FORMAT_MAX; i++) { //MS says this is supposed to be safe_cast, but couldn't find how to make it work DXGI_FORMAT inFormat = static_cast<DXGI_FORMAT>(i); UINT formatSupport = 0; HRESULT hr = mDevice->CheckFormatSupport(inFormat, &formatSupport); if ((formatSupport & D3D11_FORMAT_SUPPORT_MULTISAMPLE_RESOLVE) && (formatSupport & D3D11_FORMAT_SUPPORT_MULTISAMPLE_RENDERTARGET)) { //NOT IMPLEMENTED YET } } for (UINT sampleCount = 1; sampleCount <= D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT; sampleCount++) { UINT numQualityFlags = 0; HRESULT hr = mDevice->CheckMultisampleQualityLevels(support.format, sampleCount, &numQualityFlags); if (SUCCEEDED(hr) && numQualityFlags > 0) { (*sampleSize) = sampleCount; //mQualityFlags = numQualityFlags; } } return S_OK; } HRESULT DXResourceContext::checkDeviceSupport() { //Check what sample size the device supports, and store it return checkMultiSampleSupport(&support.sampleSize); } HRESULT DXResourceContext::createSwapChain(HWND hWnd) { // Create a description of how our swap // chain should work DXGI_SWAP_CHAIN_DESC swapDesc = {}; swapDesc.BufferCount = 1; swapDesc.BufferDesc.Width = dimensions.width; swapDesc.BufferDesc.Height = dimensions.height; swapDesc.BufferDesc.RefreshRate.Numerator = 60; swapDesc.BufferDesc.RefreshRate.Denominator = 1; swapDesc.BufferDesc.Format = support.format; swapDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; swapDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapDesc.Flags = 0; swapDesc.OutputWindow = hWnd; swapDesc.SampleDesc.Count = 1; swapDesc.SampleDesc.Quality = 0; swapDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; swapDesc.Windowed = true; //Get the DXGI Device from the D3D device IDXGIAdapter* dxgiDevice = 0; DX::ThrowIfFailed(mDevice->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&dxgiDevice))); //Get the representation of the graphics adapter IDXGIAdapter* dxgiAdapter = 0; DX::ThrowIfFailed(dxgiDevice->GetParent(__uuidof(IDXGIAdapter), reinterpret_cast<void**>(&dxgiAdapter))); //Retrieve the factory (that created the device) from the adapter IDXGIFactory* dxgiFactory = 0; DX::ThrowIfFailed(dxgiAdapter->GetParent(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&dxgiFactory))); //Create the Swap Chain DX::ThrowIfFailed(dxgiFactory->CreateSwapChain(mDevice, &swapDesc, &mSwapChain)); dxgiDevice->Release(); dxgiAdapter->Release(); dxgiFactory->Release(); return S_OK; } void DXResourceContext::setViewport(const UINT &width, const UINT &height) { dimensions.width = width; dimensions.height = height; // set up a viewport so we render into // to correct portion of the window D3D11_VIEWPORT viewport = {}; viewport.TopLeftX = 0; viewport.TopLeftY = 0; viewport.Width = (float)dimensions.width; viewport.Height = (float)dimensions.height; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; mContext->RSSetViewports(1, &viewport); // Resize the underlying swap chain buffers mSwapChain->ResizeBuffers( 1, dimensions.width, dimensions.height, support.format, 0); } HRESULT DXResourceContext::createRenderTargets() { // 1. -----PRIMARY RENDER TARGET-------- // First create the primary render target // All objects in the scene will first be drawn to this RT // This render target will configured with MSAA if it is supported D3D11_TEXTURE2D_DESC primaryBufferDesc = {}; ZeroMemory(&primaryBufferDesc, sizeof(D3D11_TEXTURE2D_DESC)); primaryBufferDesc.Width = dimensions.width; primaryBufferDesc.Height = dimensions.height; primaryBufferDesc.MipLevels = 1; primaryBufferDesc.ArraySize = 1; primaryBufferDesc.Format = support.format; primaryBufferDesc.BindFlags = D3D11_BIND_RENDER_TARGET; primaryBufferDesc.SampleDesc.Count = support.sampleSize; primaryBufferDesc.SampleDesc.Quality = support.qualityFlags; DX::ThrowIfFailed( mDevice->CreateTexture2D( &primaryBufferDesc, nullptr, &mPrimaryRT)); //Describe a multi-sample render target view CD3D11_RENDER_TARGET_VIEW_DESC primaryRTVDesc(D3D11_RTV_DIMENSION_TEXTURE2DMS); mDevice->CreateRenderTargetView( mPrimaryRT, &primaryRTVDesc, &mPrimaryRTV); // 2. -----POST PROCESS RENDER TARGETS-------- // Next create a single-sample render target for post process render passes D3D11_TEXTURE2D_DESC textureDesc = {}; ZeroMemory(&textureDesc, sizeof(D3D11_TEXTURE2D_DESC)); textureDesc.Width = dimensions.width; textureDesc.Height = dimensions.height; textureDesc.ArraySize = 1; textureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; textureDesc.CPUAccessFlags = 0; textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; textureDesc.MipLevels = 1; textureDesc.MiscFlags = 0; textureDesc.SampleDesc.Count = 1; textureDesc.SampleDesc.Quality = 0; textureDesc.Usage = D3D11_USAGE_DEFAULT; DX::ThrowIfFailed(mDevice->CreateTexture2D(&textureDesc, 0, &mPostProcessRT)); DX::ThrowIfFailed(mDevice->CreateTexture2D(&textureDesc, 0, &mBloomMapRT)); DX::ThrowIfFailed(mDevice->CreateTexture2D(&textureDesc, 0, &mTemporaryRT)); //Create Post Process Render Target Views D3D11_RENDER_TARGET_VIEW_DESC postProcessRTVDesc = {}; ZeroMemory(&postProcessRTVDesc, sizeof(D3D11_RENDER_TARGET_VIEW_DESC)); postProcessRTVDesc.Format = textureDesc.Format; postProcessRTVDesc.Texture2D.MipSlice = 0; postProcessRTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; DX::ThrowIfFailed(mDevice->CreateRenderTargetView(mPostProcessRT, &postProcessRTVDesc, &mPostProcessRTV)); DX::ThrowIfFailed(mDevice->CreateRenderTargetView(mBloomMapRT, &postProcessRTVDesc, &mBloomMapRTV)); DX::ThrowIfFailed(mDevice->CreateRenderTargetView(mTemporaryRT, &postProcessRTVDesc, &mTemporaryRTV)); //Create Shader Resource Views D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; ZeroMemory(&srvDesc, sizeof(D3D11_SHADER_RESOURCE_VIEW_DESC)); srvDesc.Format = support.format; srvDesc.Texture2D.MipLevels = 1; srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; DX::ThrowIfFailed(mDevice->CreateShaderResourceView(mPostProcessRT, &srvDesc, &mPostProcessSRV)); DX::ThrowIfFailed(mDevice->CreateShaderResourceView(mBloomMapRT, &srvDesc, &mBloomMapSRV)); DX::ThrowIfFailed(mDevice->CreateShaderResourceView(mTemporaryRT, &srvDesc, &mTemporarySRV)); // 3. -----BACK BUFFER RENDER TARGET-------- // Finally create the render target to the back buffer // - post processes will render into this // Get a reference to the currrent back buffer render target mSwapChain->GetBuffer( 0, __uuidof(ID3D11Texture2D), (void**)&mBackBufferRT); // Now that we have the texture, create a render target view // for the back buffer so we can render into it DX::ThrowIfFailed(mDevice->CreateRenderTargetView(mBackBufferRT, 0, &mBackBufferRTV)); return S_OK; } HRESULT DXResourceContext::createDepthBuffer() { // Set up the description of the texture to use for the depth buffer D3D11_TEXTURE2D_DESC depthStencilDesc; depthStencilDesc.Width = dimensions.width; depthStencilDesc.Height = dimensions.height; depthStencilDesc.MipLevels = 1; depthStencilDesc.ArraySize = 1; depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilDesc.Usage = D3D11_USAGE_DEFAULT; depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthStencilDesc.CPUAccessFlags = 0; depthStencilDesc.MiscFlags = 0; depthStencilDesc.SampleDesc.Count = support.sampleSize; depthStencilDesc.SampleDesc.Quality = support.qualityFlags; D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc = {}; ZeroMemory(&depthStencilViewDesc, sizeof(D3D11_DEPTH_STENCIL_VIEW_DESC)); depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS; depthStencilViewDesc.Texture2D.MipSlice = 0; // Create the depth buffer and its view, then // release our reference to the texture ID3D11Texture2D* depthBufferTexture; DX::ThrowIfFailed(mDevice->CreateTexture2D(&depthStencilDesc, 0, &depthBufferTexture)); DX::ThrowIfFailed(mDevice->CreateDepthStencilView(depthBufferTexture, 0, &mDepthStencilView)); depthBufferTexture->Release(); return S_OK; } void DXResourceContext::releaseSizeDependentResources() { if (mDepthStencilView) { mDepthStencilView->Release(); } if (mPostProcessSRV) { mPostProcessSRV->Release(); } if (mBloomMapSRV) { mBloomMapSRV->Release(); } if (mTemporarySRV) { mTemporarySRV->Release(); } if (mPrimaryRTV) { mPrimaryRTV->Release(); } if (mTemporaryRTV) { mTemporaryRTV->Release(); } if (mBloomMapRTV) { mBloomMapRTV->Release(); } if (mPostProcessRTV) { mPostProcessRTV->Release(); } if (mBackBufferRTV) { mBackBufferRTV->Release(); } if (mPrimaryRT) { mPrimaryRT->Release(); } if (mTemporaryRT) { mTemporaryRT->Release(); } if (mBloomMapRT) { mBloomMapRT->Release(); } if (mPostProcessRT) { mPostProcessRT->Release(); } if (mBackBufferRT) { mBackBufferRT->Release(); } } void DXResourceContext::release() { // Release all DirectX resources if (mDepthStencilView) { mDepthStencilView->Release(); } if (mPostProcessSRV) { mPostProcessSRV->Release(); } if (mBloomMapSRV) { mBloomMapSRV->Release(); } if (mTemporarySRV) { mTemporarySRV->Release(); } if (mPrimaryRTV) { mPrimaryRTV->Release(); } if (mTemporaryRTV) { mTemporaryRTV->Release(); } if (mBloomMapRTV) { mBloomMapRTV->Release(); } if (mPostProcessRTV) { mPostProcessRTV->Release(); } if (mBackBufferRTV) { mBackBufferRTV->Release(); } if (mPrimaryRT) { mPrimaryRT->Release(); } if (mTemporaryRT) { mTemporaryRT->Release(); } if (mBloomMapRT) { mBloomMapRT->Release(); } if (mPostProcessRT) { mPostProcessRT->Release(); } if (mBackBufferRT) { mBackBufferRT->Release(); } if (mSwapChain) { mSwapChain->Release(); } if (mContext) { mContext->Release(); } if (mDevice) { mDevice->Release(); } }<commit_msg>use helper function in DXRC release<commit_after>#include "DXResourceContext.h" DXResourceContext::DXResourceContext() { mDevice = 0; mContext = 0; mSwapChain = 0; mPrimaryRT = 0; mPostProcessRT = 0; mBackBufferRT = 0; mPrimaryRTV = 0; mPostProcessRTV = 0; mBackBufferRTV = 0; mDepthStencilView = 0; } DXResourceContext::~DXResourceContext() { release(); } HRESULT DXResourceContext::createDevice() { // This will hold options for DirectX initialization unsigned int deviceFlags = 0; #if defined(DEBUG) || defined(_DEBUG) // If we're in debug mode in visual studio, we also // want to make a "Debug DirectX Device" to see some // errors and warnings in Visual Studio's output window // when things go wrong! deviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif HRESULT hr = D3D11CreateDevice( 0, // Video adapter (physical GPU) to use, or null for default D3D_DRIVER_TYPE_HARDWARE, // We want to use the hardware (GPU) 0, // Used when doing software rendering deviceFlags, // Any special options 0, // Optional array of possible verisons we want as fallbacks 0, // The number of fallbacks in the above param D3D11_SDK_VERSION, // Current version of the SDK &mDevice, &support.dxFeatureLevel, &mContext); return hr; } HRESULT DXResourceContext::checkMultiSampleSupport(UINT *sampleSize) { const UINT DXGI_FORMAT_MAX = 116; const UINT MAX_SAMPLES_CHECK = 128; //https://msdn.microsoft.com/en-us/library/windows/desktop/dn458384.aspx for (UINT i = 1; i < DXGI_FORMAT_MAX; i++) { //MS says this is supposed to be safe_cast, but couldn't find how to make it work DXGI_FORMAT inFormat = static_cast<DXGI_FORMAT>(i); UINT formatSupport = 0; HRESULT hr = mDevice->CheckFormatSupport(inFormat, &formatSupport); if ((formatSupport & D3D11_FORMAT_SUPPORT_MULTISAMPLE_RESOLVE) && (formatSupport & D3D11_FORMAT_SUPPORT_MULTISAMPLE_RENDERTARGET)) { //NOT IMPLEMENTED YET } } for (UINT sampleCount = 1; sampleCount <= D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT; sampleCount++) { UINT numQualityFlags = 0; HRESULT hr = mDevice->CheckMultisampleQualityLevels(support.format, sampleCount, &numQualityFlags); if (SUCCEEDED(hr) && numQualityFlags > 0) { (*sampleSize) = sampleCount; //mQualityFlags = numQualityFlags; } } return S_OK; } HRESULT DXResourceContext::checkDeviceSupport() { //Check what sample size the device supports, and store it return checkMultiSampleSupport(&support.sampleSize); } HRESULT DXResourceContext::createSwapChain(HWND hWnd) { // Create a description of how our swap // chain should work DXGI_SWAP_CHAIN_DESC swapDesc = {}; swapDesc.BufferCount = 1; swapDesc.BufferDesc.Width = dimensions.width; swapDesc.BufferDesc.Height = dimensions.height; swapDesc.BufferDesc.RefreshRate.Numerator = 60; swapDesc.BufferDesc.RefreshRate.Denominator = 1; swapDesc.BufferDesc.Format = support.format; swapDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; swapDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; swapDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapDesc.Flags = 0; swapDesc.OutputWindow = hWnd; swapDesc.SampleDesc.Count = 1; swapDesc.SampleDesc.Quality = 0; swapDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; swapDesc.Windowed = true; //Get the DXGI Device from the D3D device IDXGIAdapter* dxgiDevice = 0; DX::ThrowIfFailed(mDevice->QueryInterface(__uuidof(IDXGIDevice), reinterpret_cast<void**>(&dxgiDevice))); //Get the representation of the graphics adapter IDXGIAdapter* dxgiAdapter = 0; DX::ThrowIfFailed(dxgiDevice->GetParent(__uuidof(IDXGIAdapter), reinterpret_cast<void**>(&dxgiAdapter))); //Retrieve the factory (that created the device) from the adapter IDXGIFactory* dxgiFactory = 0; DX::ThrowIfFailed(dxgiAdapter->GetParent(__uuidof(IDXGIFactory), reinterpret_cast<void**>(&dxgiFactory))); //Create the Swap Chain DX::ThrowIfFailed(dxgiFactory->CreateSwapChain(mDevice, &swapDesc, &mSwapChain)); dxgiDevice->Release(); dxgiAdapter->Release(); dxgiFactory->Release(); return S_OK; } void DXResourceContext::setViewport(const UINT &width, const UINT &height) { dimensions.width = width; dimensions.height = height; // set up a viewport so we render into // to correct portion of the window D3D11_VIEWPORT viewport = {}; viewport.TopLeftX = 0; viewport.TopLeftY = 0; viewport.Width = (float)dimensions.width; viewport.Height = (float)dimensions.height; viewport.MinDepth = 0.0f; viewport.MaxDepth = 1.0f; mContext->RSSetViewports(1, &viewport); // Resize the underlying swap chain buffers mSwapChain->ResizeBuffers( 1, dimensions.width, dimensions.height, support.format, 0); } HRESULT DXResourceContext::createRenderTargets() { // 1. -----PRIMARY RENDER TARGET-------- // First create the primary render target // All objects in the scene will first be drawn to this RT // This render target will configured with MSAA if it is supported D3D11_TEXTURE2D_DESC primaryBufferDesc = {}; ZeroMemory(&primaryBufferDesc, sizeof(D3D11_TEXTURE2D_DESC)); primaryBufferDesc.Width = dimensions.width; primaryBufferDesc.Height = dimensions.height; primaryBufferDesc.MipLevels = 1; primaryBufferDesc.ArraySize = 1; primaryBufferDesc.Format = support.format; primaryBufferDesc.BindFlags = D3D11_BIND_RENDER_TARGET; primaryBufferDesc.SampleDesc.Count = support.sampleSize; primaryBufferDesc.SampleDesc.Quality = support.qualityFlags; DX::ThrowIfFailed( mDevice->CreateTexture2D( &primaryBufferDesc, nullptr, &mPrimaryRT)); //Describe a multi-sample render target view CD3D11_RENDER_TARGET_VIEW_DESC primaryRTVDesc(D3D11_RTV_DIMENSION_TEXTURE2DMS); mDevice->CreateRenderTargetView( mPrimaryRT, &primaryRTVDesc, &mPrimaryRTV); // 2. -----POST PROCESS RENDER TARGETS-------- // Next create a single-sample render target for post process render passes D3D11_TEXTURE2D_DESC textureDesc = {}; ZeroMemory(&textureDesc, sizeof(D3D11_TEXTURE2D_DESC)); textureDesc.Width = dimensions.width; textureDesc.Height = dimensions.height; textureDesc.ArraySize = 1; textureDesc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; textureDesc.CPUAccessFlags = 0; textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; textureDesc.MipLevels = 1; textureDesc.MiscFlags = 0; textureDesc.SampleDesc.Count = 1; textureDesc.SampleDesc.Quality = 0; textureDesc.Usage = D3D11_USAGE_DEFAULT; DX::ThrowIfFailed(mDevice->CreateTexture2D(&textureDesc, 0, &mPostProcessRT)); DX::ThrowIfFailed(mDevice->CreateTexture2D(&textureDesc, 0, &mBloomMapRT)); DX::ThrowIfFailed(mDevice->CreateTexture2D(&textureDesc, 0, &mTemporaryRT)); //Create Post Process Render Target Views D3D11_RENDER_TARGET_VIEW_DESC postProcessRTVDesc = {}; ZeroMemory(&postProcessRTVDesc, sizeof(D3D11_RENDER_TARGET_VIEW_DESC)); postProcessRTVDesc.Format = textureDesc.Format; postProcessRTVDesc.Texture2D.MipSlice = 0; postProcessRTVDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; DX::ThrowIfFailed(mDevice->CreateRenderTargetView(mPostProcessRT, &postProcessRTVDesc, &mPostProcessRTV)); DX::ThrowIfFailed(mDevice->CreateRenderTargetView(mBloomMapRT, &postProcessRTVDesc, &mBloomMapRTV)); DX::ThrowIfFailed(mDevice->CreateRenderTargetView(mTemporaryRT, &postProcessRTVDesc, &mTemporaryRTV)); //Create Shader Resource Views D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; ZeroMemory(&srvDesc, sizeof(D3D11_SHADER_RESOURCE_VIEW_DESC)); srvDesc.Format = support.format; srvDesc.Texture2D.MipLevels = 1; srvDesc.Texture2D.MostDetailedMip = 0; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; DX::ThrowIfFailed(mDevice->CreateShaderResourceView(mPostProcessRT, &srvDesc, &mPostProcessSRV)); DX::ThrowIfFailed(mDevice->CreateShaderResourceView(mBloomMapRT, &srvDesc, &mBloomMapSRV)); DX::ThrowIfFailed(mDevice->CreateShaderResourceView(mTemporaryRT, &srvDesc, &mTemporarySRV)); // 3. -----BACK BUFFER RENDER TARGET-------- // Finally create the render target to the back buffer // - post processes will render into this // Get a reference to the currrent back buffer render target mSwapChain->GetBuffer( 0, __uuidof(ID3D11Texture2D), (void**)&mBackBufferRT); // Now that we have the texture, create a render target view // for the back buffer so we can render into it DX::ThrowIfFailed(mDevice->CreateRenderTargetView(mBackBufferRT, 0, &mBackBufferRTV)); return S_OK; } HRESULT DXResourceContext::createDepthBuffer() { // Set up the description of the texture to use for the depth buffer D3D11_TEXTURE2D_DESC depthStencilDesc; depthStencilDesc.Width = dimensions.width; depthStencilDesc.Height = dimensions.height; depthStencilDesc.MipLevels = 1; depthStencilDesc.ArraySize = 1; depthStencilDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilDesc.Usage = D3D11_USAGE_DEFAULT; depthStencilDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; depthStencilDesc.CPUAccessFlags = 0; depthStencilDesc.MiscFlags = 0; depthStencilDesc.SampleDesc.Count = support.sampleSize; depthStencilDesc.SampleDesc.Quality = support.qualityFlags; D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc = {}; ZeroMemory(&depthStencilViewDesc, sizeof(D3D11_DEPTH_STENCIL_VIEW_DESC)); depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT; depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2DMS; depthStencilViewDesc.Texture2D.MipSlice = 0; // Create the depth buffer and its view, then // release our reference to the texture ID3D11Texture2D* depthBufferTexture; DX::ThrowIfFailed(mDevice->CreateTexture2D(&depthStencilDesc, 0, &depthBufferTexture)); DX::ThrowIfFailed(mDevice->CreateDepthStencilView(depthBufferTexture, 0, &mDepthStencilView)); depthBufferTexture->Release(); return S_OK; } void DXResourceContext::releaseSizeDependentResources() { if (mDepthStencilView) { mDepthStencilView->Release(); } if (mPostProcessSRV) { mPostProcessSRV->Release(); } if (mBloomMapSRV) { mBloomMapSRV->Release(); } if (mTemporarySRV) { mTemporarySRV->Release(); } if (mPrimaryRTV) { mPrimaryRTV->Release(); } if (mTemporaryRTV) { mTemporaryRTV->Release(); } if (mBloomMapRTV) { mBloomMapRTV->Release(); } if (mPostProcessRTV) { mPostProcessRTV->Release(); } if (mBackBufferRTV) { mBackBufferRTV->Release(); } if (mPrimaryRT) { mPrimaryRT->Release(); } if (mTemporaryRT) { mTemporaryRT->Release(); } if (mBloomMapRT) { mBloomMapRT->Release(); } if (mPostProcessRT) { mPostProcessRT->Release(); } if (mBackBufferRT) { mBackBufferRT->Release(); } } void DXResourceContext::release() { // Release all DirectX resources releaseSizeDependentResources(); if (mSwapChain) { mSwapChain->Release(); } if (mContext) { mContext->Release(); } if (mDevice) { mDevice->Release(); } }<|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/resource_bundle.h" #include <atlbase.h> #include "base/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/resource_util.h" #include "base/string_piece.h" #include "base/win_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/l10n_util.h" namespace { // Returns the flags that should be passed to LoadLibraryEx. DWORD GetDataDllLoadFlags() { if (win_util::GetWinVersion() >= win_util::WINVERSION_VISTA) return LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE; return DONT_RESOLVE_DLL_REFERENCES; } } // end anonymous namespace ResourceBundle::~ResourceBundle() { FreeImages(); if (locale_resources_data_) { BOOL rv = FreeLibrary(locale_resources_data_); DCHECK(rv); } if (theme_data_) { BOOL rv = FreeLibrary(theme_data_); DCHECK(rv); } } void ResourceBundle::LoadResources(const std::wstring& pref_locale) { // As a convenience, set resources_data_ to the current module. resources_data_ = _AtlBaseModule.GetModuleInstance(); DCHECK(NULL == locale_resources_data_) << "locale dll already loaded"; const FilePath& locale_path = GetLocaleFilePath(pref_locale); if (locale_path.value().empty()) { // It's possible that there are no locale dlls found, in which case we just // return. NOTREACHED(); return; } // The dll should only have resources, not executable code. locale_resources_data_ = LoadLibraryEx(locale_path.value().c_str(), NULL, GetDataDllLoadFlags()); DCHECK(locale_resources_data_ != NULL) << "unable to load generated resources"; } FilePath ResourceBundle::GetLocaleFilePath(const std::wstring& pref_locale) { FilePath locale_path; PathService::Get(chrome::DIR_LOCALES, &locale_path); const std::wstring app_locale = l10n_util::GetApplicationLocale(pref_locale); if (app_locale.empty()) return FilePath(); return locale_path.Append(app_locale + L".dll"); } void ResourceBundle::LoadThemeResources() { DCHECK(NULL == theme_data_) << "theme dll already loaded"; std::wstring theme_data_path; PathService::Get(chrome::DIR_THEMES, &theme_data_path); file_util::AppendToPath(&theme_data_path, L"default.dll"); // The dll should only have resources, not executable code. theme_data_ = LoadLibraryEx(theme_data_path.c_str(), NULL, GetDataDllLoadFlags()); DCHECK(theme_data_ != NULL) << "unable to load " << theme_data_path; } /* static */ bool ResourceBundle::LoadResourceBytes( DataHandle module, int resource_id, std::vector<unsigned char>* bytes) { void* data_ptr; size_t data_size; if (base::GetDataResourceFromModule(module, resource_id, &data_ptr, &data_size)) { bytes->resize(data_size); memcpy(&(bytes->front()), data_ptr, data_size); return true; } else { return false; } } HICON ResourceBundle::LoadThemeIcon(int icon_id) { return ::LoadIcon(theme_data_, MAKEINTRESOURCE(icon_id)); } StringPiece ResourceBundle::GetRawDataResource(int resource_id) { void* data_ptr; size_t data_size; if (base::GetDataResourceFromModule(_AtlBaseModule.GetModuleInstance(), resource_id, &data_ptr, &data_size)) { return StringPiece(static_cast<const char*>(data_ptr), data_size); } else if (locale_resources_data_ && base::GetDataResourceFromModule(locale_resources_data_, resource_id, &data_ptr, &data_size)) { return StringPiece(static_cast<const char*>(data_ptr), data_size); } return StringPiece(); } // Loads and returns a cursor from the current module. HCURSOR ResourceBundle::LoadCursor(int cursor_id) { return ::LoadCursor(_AtlBaseModule.GetModuleInstance(), MAKEINTRESOURCE(cursor_id)); } string16 ResourceBundle::GetLocalizedString(int message_id) { // If for some reason we were unable to load a resource dll, return an empty // string (better than crashing). if (!locale_resources_data_) { LOG(WARNING) << "locale resources are not loaded"; return string16(); } DCHECK(IS_INTRESOURCE(message_id)); // Get a reference directly to the string resource. HINSTANCE hinstance = locale_resources_data_; const ATLSTRINGRESOURCEIMAGE* image = AtlGetStringResourceImage(hinstance, message_id); if (!image) { // Fall back on the current module (shouldn't be any strings here except // in unittests). image = AtlGetStringResourceImage(_AtlBaseModule.GetModuleInstance(), message_id); if (!image) { NOTREACHED() << "unable to find resource: " << message_id; return std::wstring(); } } // Copy into a string16 and return. return string16(image->achString, image->nLength); } <commit_msg>fix bustage - removed this include for some reason<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "app/resource_bundle.h" #include <atlbase.h> #include "base/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/resource_util.h" #include "base/string_piece.h" #include "base/win_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/gfx/chrome_font.h" #include "chrome/common/l10n_util.h" namespace { // Returns the flags that should be passed to LoadLibraryEx. DWORD GetDataDllLoadFlags() { if (win_util::GetWinVersion() >= win_util::WINVERSION_VISTA) return LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE | LOAD_LIBRARY_AS_IMAGE_RESOURCE; return DONT_RESOLVE_DLL_REFERENCES; } } // end anonymous namespace ResourceBundle::~ResourceBundle() { FreeImages(); if (locale_resources_data_) { BOOL rv = FreeLibrary(locale_resources_data_); DCHECK(rv); } if (theme_data_) { BOOL rv = FreeLibrary(theme_data_); DCHECK(rv); } } void ResourceBundle::LoadResources(const std::wstring& pref_locale) { // As a convenience, set resources_data_ to the current module. resources_data_ = _AtlBaseModule.GetModuleInstance(); DCHECK(NULL == locale_resources_data_) << "locale dll already loaded"; const FilePath& locale_path = GetLocaleFilePath(pref_locale); if (locale_path.value().empty()) { // It's possible that there are no locale dlls found, in which case we just // return. NOTREACHED(); return; } // The dll should only have resources, not executable code. locale_resources_data_ = LoadLibraryEx(locale_path.value().c_str(), NULL, GetDataDllLoadFlags()); DCHECK(locale_resources_data_ != NULL) << "unable to load generated resources"; } FilePath ResourceBundle::GetLocaleFilePath(const std::wstring& pref_locale) { FilePath locale_path; PathService::Get(chrome::DIR_LOCALES, &locale_path); const std::wstring app_locale = l10n_util::GetApplicationLocale(pref_locale); if (app_locale.empty()) return FilePath(); return locale_path.Append(app_locale + L".dll"); } void ResourceBundle::LoadThemeResources() { DCHECK(NULL == theme_data_) << "theme dll already loaded"; std::wstring theme_data_path; PathService::Get(chrome::DIR_THEMES, &theme_data_path); file_util::AppendToPath(&theme_data_path, L"default.dll"); // The dll should only have resources, not executable code. theme_data_ = LoadLibraryEx(theme_data_path.c_str(), NULL, GetDataDllLoadFlags()); DCHECK(theme_data_ != NULL) << "unable to load " << theme_data_path; } /* static */ bool ResourceBundle::LoadResourceBytes( DataHandle module, int resource_id, std::vector<unsigned char>* bytes) { void* data_ptr; size_t data_size; if (base::GetDataResourceFromModule(module, resource_id, &data_ptr, &data_size)) { bytes->resize(data_size); memcpy(&(bytes->front()), data_ptr, data_size); return true; } else { return false; } } HICON ResourceBundle::LoadThemeIcon(int icon_id) { return ::LoadIcon(theme_data_, MAKEINTRESOURCE(icon_id)); } StringPiece ResourceBundle::GetRawDataResource(int resource_id) { void* data_ptr; size_t data_size; if (base::GetDataResourceFromModule(_AtlBaseModule.GetModuleInstance(), resource_id, &data_ptr, &data_size)) { return StringPiece(static_cast<const char*>(data_ptr), data_size); } else if (locale_resources_data_ && base::GetDataResourceFromModule(locale_resources_data_, resource_id, &data_ptr, &data_size)) { return StringPiece(static_cast<const char*>(data_ptr), data_size); } return StringPiece(); } // Loads and returns a cursor from the current module. HCURSOR ResourceBundle::LoadCursor(int cursor_id) { return ::LoadCursor(_AtlBaseModule.GetModuleInstance(), MAKEINTRESOURCE(cursor_id)); } string16 ResourceBundle::GetLocalizedString(int message_id) { // If for some reason we were unable to load a resource dll, return an empty // string (better than crashing). if (!locale_resources_data_) { LOG(WARNING) << "locale resources are not loaded"; return string16(); } DCHECK(IS_INTRESOURCE(message_id)); // Get a reference directly to the string resource. HINSTANCE hinstance = locale_resources_data_; const ATLSTRINGRESOURCEIMAGE* image = AtlGetStringResourceImage(hinstance, message_id); if (!image) { // Fall back on the current module (shouldn't be any strings here except // in unittests). image = AtlGetStringResourceImage(_AtlBaseModule.GetModuleInstance(), message_id); if (!image) { NOTREACHED() << "unable to find resource: " << message_id; return std::wstring(); } } // Copy into a string16 and return. return string16(image->achString, image->nLength); } <|endoftext|>
<commit_before>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "SurgSim/Collision/DefaultContactCalculation.h" #include "SurgSim/Collision/CollisionPair.h" #include "SurgSim/Collision/Representation.h" #include "SurgSim/Framework/Log.h" #include "SurgSim/Math/Shape.h" namespace SurgSim { namespace Collision { DefaultContactCalculation::DefaultContactCalculation(bool doAssert) : m_doAssert(doAssert) { } DefaultContactCalculation::~DefaultContactCalculation() { } std::pair<int, int> DefaultContactCalculation::getShapeTypes() { return std::pair<int, int>(SurgSim::Math::SHAPE_TYPE_NONE, SurgSim::Math::SHAPE_TYPE_NONE); } void DefaultContactCalculation::doCalculateContact(std::shared_ptr<CollisionPair> pair) { SURGSIM_ASSERT(!m_doAssert) << "Contact calculation not implemented for pairs with types (" << pair->getFirst()->getShapeType() << ", " << pair->getSecond()->getShapeType() << ")."; SURGSIM_LOG_ONCE(SurgSim::Framework::Logger::getDefaultLogger(), WARNING) << "Contact calculation not implemented for pairs with types (" << pair->getFirst()->getShapeType() << ", " << pair->getSecond()->getShapeType() << ")."; } std::list<std::shared_ptr<Contact>> DefaultContactCalculation::doCalculateContact( const std::shared_ptr<Math::Shape>& shape1, const Math::RigidTransform3d& pose1, const std::shared_ptr<Math::Shape>& shape2, const Math::RigidTransform3d& pose2) { SURGSIM_ASSERT(!m_doAssert) << "Contact calculation not implemented for pairs with types (" << shape1->getType() << ", " << shape2->getType() << ")."; SURGSIM_LOG_ONCE(SurgSim::Framework::Logger::getDefaultLogger(), WARNING) << "Contact calculation not implemented for pairs with types (" << shape1->getType() << ", " << shape2->getType() << ")."; return std::list<std::shared_ptr<Contact>>(); } }; // namespace Collision }; // namespace SurgSim <commit_msg>Fix wording in error message<commit_after>// This file is a part of the OpenSurgSim project. // Copyright 2013, SimQuest Solutions Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "SurgSim/Collision/DefaultContactCalculation.h" #include "SurgSim/Collision/CollisionPair.h" #include "SurgSim/Collision/Representation.h" #include "SurgSim/Framework/Log.h" #include "SurgSim/Math/Shape.h" namespace SurgSim { namespace Collision { DefaultContactCalculation::DefaultContactCalculation(bool doAssert) : m_doAssert(doAssert) { } DefaultContactCalculation::~DefaultContactCalculation() { } std::pair<int, int> DefaultContactCalculation::getShapeTypes() { return std::pair<int, int>(SurgSim::Math::SHAPE_TYPE_NONE, SurgSim::Math::SHAPE_TYPE_NONE); } void DefaultContactCalculation::doCalculateContact(std::shared_ptr<CollisionPair> pair) { SURGSIM_ASSERT(!m_doAssert) << "Contact calculation not implemented for pairs with types (" << pair->getFirst()->getShapeType() << ", " << pair->getSecond()->getShapeType() << ")."; SURGSIM_LOG_ONCE(SurgSim::Framework::Logger::getDefaultLogger(), WARNING) << "Contact calculation not implemented for pairs with types (" << pair->getFirst()->getShapeType() << ", " << pair->getSecond()->getShapeType() << ")."; } std::list<std::shared_ptr<Contact>> DefaultContactCalculation::doCalculateContact( const std::shared_ptr<Math::Shape>& shape1, const Math::RigidTransform3d& pose1, const std::shared_ptr<Math::Shape>& shape2, const Math::RigidTransform3d& pose2) { SURGSIM_ASSERT(!m_doAssert) << "Contact calculation not implemented for shapes with types (" << shape1->getType() << ", " << shape2->getType() << ")."; SURGSIM_LOG_ONCE(SurgSim::Framework::Logger::getDefaultLogger(), WARNING) << "Contact calculation not implemented for pairs with types (" << shape1->getType() << ", " << shape2->getType() << ")."; return std::list<std::shared_ptr<Contact>>(); } }; // namespace Collision }; // namespace SurgSim <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkSimilarity2DTransformTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <iostream> #include "itkSimilarity2DTransform.h" #include "vnl/vnl_vector_fixed.h" #include "itkVector.h" int itkSimilarity2DTransformTest(int ,char *[] ) { std::cout << "==================================" << std::endl; std::cout << "Testing Similarity 2D Transform" << std::endl << std::endl; const double epsilon = 1e-10; const unsigned int N = 2; bool Ok = true; typedef itk::Similarity2DTransform<double> SimilarityTransformType; SimilarityTransformType::Pointer transform = SimilarityTransformType::New(); // 15 degrees in radians const double angle = 15.0 * atan( 1.0f ) / 45.0; const double sinth = sin( angle ); const double costh = cos( angle ); std::cout << "Testing Rotation:"; transform->SetAngle(angle); // Rotate an itk::Point SimilarityTransformType::InputPointType::ValueType pInit[2] = {10,10}; SimilarityTransformType::InputPointType p = pInit; SimilarityTransformType::InputPointType q; q[0] = p[0] * costh - p[1] * sinth; q[1] = p[0] * sinth + p[1] * costh; SimilarityTransformType::OutputPointType r; r = transform->TransformPoint( p ); for(unsigned int i=0; i<N; i++) { if( fabs( q[i]- r[i] ) > epsilon ) { Ok = false; break; } } if( !Ok ) { std::cerr << "Error rotating point : " << p << std::endl; std::cerr << "Result should be : " << q << std::endl; std::cerr << "Reported Result is : " << r << std::endl; return EXIT_FAILURE; } else { std::cout << " [ PASSED ] " << std::endl; } std::cout << "Testing Translation:"; transform->SetAngle(0); SimilarityTransformType::OffsetType::ValueType ioffsetInit[2] = {1,4}; SimilarityTransformType::OffsetType ioffset = ioffsetInit; transform->SetOffset( ioffset ); q = p + ioffset; r = transform->TransformPoint( p ); for(unsigned int i=0; i<N; i++) { if( fabs( q[i]- r[i] ) > epsilon ) { Ok = false; break; } } if( !Ok ) { std::cerr << "Error translating point: " << p << std::endl; std::cerr << "Result should be : " << q << std::endl; std::cerr << "Reported Result is : " << r << std::endl; return EXIT_FAILURE; } else { std::cout << " [ PASSED ] " << std::endl; } return EXIT_SUCCESS; } <commit_msg>ENH: improve coverage<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkSimilarity2DTransformTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <iostream> #include "itkSimilarity2DTransform.h" #include "vnl/vnl_vector_fixed.h" #include "itkVector.h" int itkSimilarity2DTransformTest(int ,char *[] ) { std::cout << "==================================" << std::endl; std::cout << "Testing Similarity 2D Transform" << std::endl << std::endl; const double epsilon = 1e-10; const unsigned int N = 2; bool Ok = true; typedef itk::Similarity2DTransform<double> SimilarityTransformType; SimilarityTransformType::Pointer transform = SimilarityTransformType::New(); // Test the identity transform std::cout << "Testing Identity:"; transform->SetIdentity(); SimilarityTransformType::InputPointType::ValueType pInit[2] = {10,10}; SimilarityTransformType::InputPointType p = pInit; SimilarityTransformType::OutputPointType r; r = transform->TransformPoint( p ); for(unsigned int i=0; i<N; i++) { if( fabs( p[i]- r[i] ) > epsilon ) { Ok = false; break; } } if( !Ok ) { std::cerr << "Error with Identity transform" << std::endl; return EXIT_FAILURE; } else { std::cout << " [ PASSED ] " << std::endl; } // Test the Set/Get Parameters std::cout << "Testing Set/GetParameters():"; SimilarityTransformType::ParametersType params; params.resize(6); for(unsigned int i=0;i<6;i++) { params[i]=i; } transform->SetParameters(params); SimilarityTransformType::ParametersType outputParams; outputParams = transform->GetParameters(); for(unsigned int i=0; i<N; i++) { if( fabs( outputParams[i]-params[i] ) > epsilon ) { Ok = false; break; } } if( !Ok ) { std::cerr << "Error with Set/GetParameters:" << std::endl; std::cerr << "Input:" << params << std::endl; std::cerr << "Output:" << outputParams << std::endl; return EXIT_FAILURE; } else { std::cout << " [ PASSED ] " << std::endl; } // 15 degrees in radians transform->SetIdentity(); const double angle = 15.0 * atan( 1.0f ) / 45.0; const double sinth = sin( angle ); const double costh = cos( angle ); std::cout << "Testing Rotation:"; transform->SetAngle(angle); // Rotate an itk::Point SimilarityTransformType::InputPointType q; p = pInit; q[0] = p[0] * costh - p[1] * sinth; q[1] = p[0] * sinth + p[1] * costh; r = transform->TransformPoint( p ); for(unsigned int i=0; i<N; i++) { if( fabs( q[i]- r[i] ) > epsilon ) { Ok = false; break; } } if( !Ok ) { std::cerr << "Error rotating point : " << p << std::endl; std::cerr << "Result should be : " << q << std::endl; std::cerr << "Reported Result is : " << r << std::endl; return EXIT_FAILURE; } else { std::cout << " [ PASSED ] " << std::endl; } std::cout << "Testing Translation:"; transform->SetAngle(0); SimilarityTransformType::OffsetType::ValueType ioffsetInit[2] = {1,4}; SimilarityTransformType::OffsetType ioffset = ioffsetInit; transform->SetOffset( ioffset ); q = p + ioffset; r = transform->TransformPoint( p ); for(unsigned int i=0; i<N; i++) { if( fabs( q[i]- r[i] ) > epsilon ) { Ok = false; break; } } if( !Ok ) { std::cerr << "Error translating point: " << p << std::endl; std::cerr << "Result should be : " << q << std::endl; std::cerr << "Reported Result is : " << r << std::endl; return EXIT_FAILURE; } else { std::cout << " [ PASSED ] " << std::endl; } // Testing the Jacobian std::cout << "Testing Jacobian:"; SimilarityTransformType::JacobianType jacobian = transform->GetJacobian(p); if( (jacobian[0][0] != 10) || (jacobian[0][1] != -10) || (jacobian[0][2] != 0) || (jacobian[0][3] != 0) || (jacobian[0][4] != 1) || (jacobian[0][5] != 0) || (jacobian[1][0] != 10) || (jacobian[1][1] != 10) || (jacobian[1][2] !=0 ) || (jacobian[1][3] != 0) || (jacobian[1][4] !=0) || (jacobian[1][5] != 1) ) { std::cerr << "Error with Jacobian: " << jacobian << std::endl; return EXIT_FAILURE; } else { std::cout << " [ PASSED ] " << std::endl; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ** This file is part of the Ovi services plugin for the Maps and ** Navigation API. The use of these services, whether by use of the ** plugin or by other means, is governed by the terms and conditions ** described by the file OVI_SERVICES_TERMS_AND_CONDITIONS.txt in ** this package, located in the directory containing the Ovi services ** plugin source code. ** ****************************************************************************/ #include "qgeotiledmapdata_nokia.h" #include "jsonparser.h" #include "qgeomappingmanagerengine_nokia.h" #include "qgeoboundingbox.h" #include "qgeocoordinate.h" #include <QNetworkAccessManager> #include <QNetworkProxy> QTM_USE_NAMESPACE /*! Constructs a new tiled map data object, which stores the map data required by \a geoMap and makes use of the functionality provided by \a engine. */ QGeoTiledMapDataNokia::QGeoTiledMapDataNokia(QGeoMappingManagerEngineNokia *engine) : QGeoTiledMapData(engine), watermark(":/images/watermark.png") { m_networkManager = new QNetworkAccessManager(this); connect(m_networkManager, SIGNAL(finished(QNetworkReply*)), SLOT(copyrightReplyFinished(QNetworkReply*))); m_networkManager->get(QNetworkRequest(QUrl("http://maptile.maps.svc.ovi.com/maptiler/v2/copyright/newest"))); } QGeoTiledMapDataNokia::~QGeoTiledMapDataNokia() { } static QGeoBoundingBox variantListToBoundingBox(const QVariantList & list) { if (list.size() < 4) return QGeoBoundingBox(); qreal latTop = list[0].toReal(); qreal latBottom = list[2].toReal(); if (latTop < latBottom) qSwap(latTop, latBottom); return QGeoBoundingBox(QGeoCoordinate(latTop, list[1].toReal()), QGeoCoordinate(latBottom, list[3].toReal())); } void QGeoTiledMapDataNokia::copyrightReplyFinished(QNetworkReply * reply) { JSONParser jp(reply->readAll()); QVariant root = jp.parse(); copyrights.clear(); QVariantHash rootHash = root.toHash(); foreach (QString key, rootHash.keys()) { QList<CopyrightDescriptor> copyrightDescriptorList; foreach (QVariant copyrightSource, rootHash[key].toList()) { QVariantHash copyrightSourceHash = copyrightSource.toHash(); CopyrightDescriptor copyrightDescriptor; copyrightDescriptor.minLevel = copyrightSourceHash["minLevel"].toReal(); copyrightDescriptor.maxLevel = copyrightSourceHash["maxLevel"].toReal(); copyrightDescriptor.label = copyrightSourceHash["label"].toString(); copyrightDescriptor.alt = copyrightSourceHash["alt"].toString(); foreach (QVariant box, copyrightSourceHash["boxes"].toList()) { copyrightDescriptor.boxes << variantListToBoundingBox(box.toList()); } copyrightDescriptorList << copyrightDescriptor; } copyrights[key] = copyrightDescriptorList; } } QString QGeoTiledMapDataNokia::getViewCopyright() { QGeoBoundingBox viewport = this->viewport(); QString terraintype; switch (mapType()) { case QGraphicsGeoMap::StreetMap: terraintype = "normal"; break; case QGraphicsGeoMap::SatelliteMapDay: case QGraphicsGeoMap::SatelliteMapNight: terraintype = "hybrid"; break; case QGraphicsGeoMap::TerrainMap: terraintype = "terrain"; break; default: terraintype = "normal"; } CopyrightDescriptor fallback; QStringList copyrightStrings; bool contained = false; foreach (CopyrightDescriptor copyrightDescriptor, copyrights[terraintype]) { if (zoomLevel() < copyrightDescriptor.minLevel) continue; if (zoomLevel() > copyrightDescriptor.maxLevel) continue; if (copyrightDescriptor.boxes.isEmpty()) { fallback = copyrightDescriptor; } else { foreach (QGeoBoundingBox box, copyrightDescriptor.boxes) { if (box.intersects(viewport)) { copyrightStrings << copyrightDescriptor.label; if (box.contains(viewport)) { contained = true; break; } // TODO: consider the case where the viewport is fully contained by the combined bounding boxes, but not by one individual bounding box } } } } if (copyrightStrings.isEmpty() || !contained) { if (!fallback.label.isEmpty()) copyrightStrings << fallback.label; } copyrightStrings.removeDuplicates(); QString ret = copyrightStrings.join(", "); return ret; } /*! \reimp */ void QGeoTiledMapDataNokia::paint(QPainter *painter, const QStyleOptionGraphicsItem *option) { QGeoTiledMapData::paint(painter, option); QRect viewport = painter->viewport(); painter->drawPixmap( viewport.bottomLeft()+QPoint(5,-5-watermark.height()), watermark ); QString copyrightText = getViewCopyright(); if (copyrightText != lastCopyrightText || lastViewport != viewport) { lastCopyrightText = copyrightText; lastViewport = viewport; QRect maxBoundingRect(QPoint(viewport.left()+10+watermark.width(), viewport.top()), QPoint(viewport.right()-5, viewport.bottom()-5)); QRect textBoundingRect = painter->boundingRect(maxBoundingRect, Qt::AlignLeft | Qt::AlignBottom | Qt::TextWordWrap, copyrightText); lastCopyrightRect = textBoundingRect.adjusted(-1, -1, 1, 1); lastCopyright = QPixmap(lastCopyrightRect.size()); lastCopyright.fill(QColor(Qt::transparent)); { QPainter painter2(&lastCopyright); painter2.drawText( QRect(QPoint(1, 2), textBoundingRect.size()), Qt::TextWordWrap, copyrightText ); painter2.drawPixmap(QRect(QPoint(-1, -1), lastCopyrightRect.size()), lastCopyright); painter2.drawPixmap(QRect(QPoint(1, -1), lastCopyrightRect.size()), lastCopyright); painter2.setPen(QColor(Qt::white)); painter2.drawText( QRect(QPoint(1, 1), textBoundingRect.size()), Qt::TextWordWrap, copyrightText ); } } painter->drawPixmap( lastCopyrightRect, lastCopyright ); } <commit_msg>Fix crash when making a QGraphicsGeoMap without network<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ** This file is part of the Ovi services plugin for the Maps and ** Navigation API. The use of these services, whether by use of the ** plugin or by other means, is governed by the terms and conditions ** described by the file OVI_SERVICES_TERMS_AND_CONDITIONS.txt in ** this package, located in the directory containing the Ovi services ** plugin source code. ** ****************************************************************************/ #include "qgeotiledmapdata_nokia.h" #include "jsonparser.h" #include "qgeomappingmanagerengine_nokia.h" #include "qgeoboundingbox.h" #include "qgeocoordinate.h" #include <QNetworkAccessManager> #include <QNetworkProxy> QTM_USE_NAMESPACE /*! Constructs a new tiled map data object, which stores the map data required by \a geoMap and makes use of the functionality provided by \a engine. */ QGeoTiledMapDataNokia::QGeoTiledMapDataNokia(QGeoMappingManagerEngineNokia *engine) : QGeoTiledMapData(engine), watermark(":/images/watermark.png") { m_networkManager = new QNetworkAccessManager(this); connect(m_networkManager, SIGNAL(finished(QNetworkReply*)), SLOT(copyrightReplyFinished(QNetworkReply*))); m_networkManager->get(QNetworkRequest(QUrl("http://maptile.maps.svc.ovi.com/maptiler/v2/copyright/newest"))); } QGeoTiledMapDataNokia::~QGeoTiledMapDataNokia() { } static QGeoBoundingBox variantListToBoundingBox(const QVariantList & list) { if (list.size() < 4) return QGeoBoundingBox(); qreal latTop = list[0].toReal(); qreal latBottom = list[2].toReal(); if (latTop < latBottom) qSwap(latTop, latBottom); return QGeoBoundingBox(QGeoCoordinate(latTop, list[1].toReal()), QGeoCoordinate(latBottom, list[3].toReal())); } void QGeoTiledMapDataNokia::copyrightReplyFinished(QNetworkReply * reply) { if (reply->error() != QNetworkReply::NoError) return; JSONParser jp(reply->readAll()); QVariant root = jp.parse(); copyrights.clear(); QVariantHash rootHash = root.toHash(); foreach (QString key, rootHash.keys()) { QList<CopyrightDescriptor> copyrightDescriptorList; foreach (QVariant copyrightSource, rootHash[key].toList()) { QVariantHash copyrightSourceHash = copyrightSource.toHash(); CopyrightDescriptor copyrightDescriptor; copyrightDescriptor.minLevel = copyrightSourceHash["minLevel"].toReal(); copyrightDescriptor.maxLevel = copyrightSourceHash["maxLevel"].toReal(); copyrightDescriptor.label = copyrightSourceHash["label"].toString(); copyrightDescriptor.alt = copyrightSourceHash["alt"].toString(); foreach (QVariant box, copyrightSourceHash["boxes"].toList()) { copyrightDescriptor.boxes << variantListToBoundingBox(box.toList()); } copyrightDescriptorList << copyrightDescriptor; } copyrights[key] = copyrightDescriptorList; } } QString QGeoTiledMapDataNokia::getViewCopyright() { QGeoBoundingBox viewport = this->viewport(); QString terraintype; switch (mapType()) { case QGraphicsGeoMap::StreetMap: terraintype = "normal"; break; case QGraphicsGeoMap::SatelliteMapDay: case QGraphicsGeoMap::SatelliteMapNight: terraintype = "hybrid"; break; case QGraphicsGeoMap::TerrainMap: terraintype = "terrain"; break; default: terraintype = "normal"; } CopyrightDescriptor fallback; QStringList copyrightStrings; bool contained = false; foreach (CopyrightDescriptor copyrightDescriptor, copyrights[terraintype]) { if (zoomLevel() < copyrightDescriptor.minLevel) continue; if (zoomLevel() > copyrightDescriptor.maxLevel) continue; if (copyrightDescriptor.boxes.isEmpty()) { fallback = copyrightDescriptor; } else { foreach (QGeoBoundingBox box, copyrightDescriptor.boxes) { if (box.intersects(viewport)) { copyrightStrings << copyrightDescriptor.label; if (box.contains(viewport)) { contained = true; break; } // TODO: consider the case where the viewport is fully contained by the combined bounding boxes, but not by one individual bounding box } } } } if (copyrightStrings.isEmpty() || !contained) { if (!fallback.label.isEmpty()) copyrightStrings << fallback.label; } copyrightStrings.removeDuplicates(); QString ret = copyrightStrings.join(", "); return ret; } /*! \reimp */ void QGeoTiledMapDataNokia::paint(QPainter *painter, const QStyleOptionGraphicsItem *option) { QGeoTiledMapData::paint(painter, option); QRect viewport = painter->viewport(); painter->drawPixmap( viewport.bottomLeft()+QPoint(5,-5-watermark.height()), watermark ); QString copyrightText = getViewCopyright(); if (copyrightText != lastCopyrightText || lastViewport != viewport) { lastCopyrightText = copyrightText; lastViewport = viewport; QRect maxBoundingRect(QPoint(viewport.left()+10+watermark.width(), viewport.top()), QPoint(viewport.right()-5, viewport.bottom()-5)); QRect textBoundingRect = painter->boundingRect(maxBoundingRect, Qt::AlignLeft | Qt::AlignBottom | Qt::TextWordWrap, copyrightText); lastCopyrightRect = textBoundingRect.adjusted(-1, -1, 1, 1); lastCopyright = QPixmap(lastCopyrightRect.size()); lastCopyright.fill(QColor(Qt::transparent)); { QPainter painter2(&lastCopyright); painter2.drawText( QRect(QPoint(1, 2), textBoundingRect.size()), Qt::TextWordWrap, copyrightText ); painter2.drawPixmap(QRect(QPoint(-1, -1), lastCopyrightRect.size()), lastCopyright); painter2.drawPixmap(QRect(QPoint(1, -1), lastCopyrightRect.size()), lastCopyright); painter2.setPen(QColor(Qt::white)); painter2.drawText( QRect(QPoint(1, 1), textBoundingRect.size()), Qt::TextWordWrap, copyrightText ); } } painter->drawPixmap( lastCopyrightRect, lastCopyright ); } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <vcl/outdev.hxx> #include <vcl/bitmapex.hxx> #include <vcl/alpha.hxx> #include <vcl/window.hxx> #include <vcl/bmpacc.hxx> #include <vcl/virdev.hxx> #include <vcl/image.hxx> #include <vcl/settings.hxx> #include <image.h> #include <boost/scoped_array.hpp> #define IMPSYSIMAGEITEM_MASK ( 0x01 ) #define IMPSYSIMAGEITEM_ALPHA ( 0x02 ) ImageAryData::ImageAryData( const ImageAryData& rData ) : maName( rData.maName ), mnId( rData.mnId ), maBitmapEx( rData.maBitmapEx ) { } ImageAryData::ImageAryData( const OUString &aName, sal_uInt16 nId, const BitmapEx &aBitmap ) : maName( aName ), mnId( nId ), maBitmapEx( aBitmap ) { } ImageAryData::~ImageAryData() { } ImageAryData& ImageAryData::operator=( const ImageAryData& rData ) { maName = rData.maName; mnId = rData.mnId; maBitmapEx = rData.maBitmapEx; return *this; } ImplImageList::ImplImageList() : mnRefCount(1) { } ImplImageList::ImplImageList( const ImplImageList &aSrc ) : maPrefix(aSrc.maPrefix) , maImageSize(aSrc.maImageSize) , mnRefCount(1) { maImages.reserve( aSrc.maImages.size() ); for ( ImageAryDataVec::const_iterator aIt = aSrc.maImages.begin(), aEnd = aSrc.maImages.end(); aIt != aEnd; ++aIt ) { ImageAryData* pAryData = new ImageAryData( **aIt ); maImages.push_back( pAryData ); if( !pAryData->maName.isEmpty() ) maNameHash [ pAryData->maName ] = pAryData; } } ImplImageList::~ImplImageList() { for ( ImageAryDataVec::iterator aIt = maImages.begin(), aEnd = maImages.end(); aIt != aEnd; ++aIt ) delete *aIt; } void ImplImageList::AddImage( const OUString &aName, sal_uInt16 nId, const BitmapEx &aBitmapEx ) { ImageAryData *pImg = new ImageAryData( aName, nId, aBitmapEx ); maImages.push_back( pImg ); if( !aName.isEmpty() ) maNameHash [ aName ] = pImg; } void ImplImageList::RemoveImage( sal_uInt16 nPos ) { ImageAryData *pImg = maImages[ nPos ]; if( !pImg->maName.isEmpty() ) maNameHash.erase( pImg->maName ); maImages.erase( maImages.begin() + nPos ); } ImplImageData::ImplImageData( const BitmapEx& rBmpEx ) : mpImageBitmap( NULL ), maBmpEx( rBmpEx ) { } ImplImageData::~ImplImageData() { delete mpImageBitmap; } bool ImplImageData::IsEqual( const ImplImageData& rData ) { return( maBmpEx == rData.maBmpEx ); } ImplImage::ImplImage() : mnRefCount(1) , mpData(NULL) , meType(IMAGETYPE_BITMAP) { } ImplImage::~ImplImage() { switch( meType ) { case IMAGETYPE_BITMAP: delete static_cast< Bitmap* >( mpData ); break; case IMAGETYPE_IMAGE: delete static_cast< ImplImageData* >( mpData ); break; } } ImplImageBmp::ImplImageBmp() : mpDisplayBmp( NULL ), mpInfoAry( NULL ), mnSize( 0 ) { } ImplImageBmp::~ImplImageBmp() { delete[] mpInfoAry; delete mpDisplayBmp; } void ImplImageBmp::Create( const BitmapEx& rBmpEx, long nItemWidth, long nItemHeight, sal_uInt16 nInitSize ) { maBmpEx = rBmpEx; maDisabledBmpEx.SetEmpty(); delete mpDisplayBmp; mpDisplayBmp = NULL; maSize = Size( nItemWidth, nItemHeight ); mnSize = nInitSize; delete[] mpInfoAry; mpInfoAry = new sal_uInt8[ mnSize ]; memset( mpInfoAry, rBmpEx.IsAlpha() ? IMPSYSIMAGEITEM_ALPHA : ( rBmpEx.IsTransparent() ? IMPSYSIMAGEITEM_MASK : 0 ), mnSize ); } void ImplImageBmp::Draw( sal_uInt16 nPos, OutputDevice* pOutDev, const Point& rPos, sal_uInt16 nStyle, const Size* pSize ) { if( pOutDev->IsDeviceOutputNecessary() ) { const Point aSrcPos( nPos * maSize.Width(), 0 ); Size aOutSize; aOutSize = ( pSize ? *pSize : pOutDev->PixelToLogic( maSize ) ); if( nStyle & IMAGE_DRAW_DISABLE ) { ImplUpdateDisabledBmpEx( nPos); pOutDev->DrawBitmapEx( rPos, aOutSize, aSrcPos, maSize, maDisabledBmpEx ); } else { if( nStyle & ( IMAGE_DRAW_COLORTRANSFORM | IMAGE_DRAW_HIGHLIGHT | IMAGE_DRAW_DEACTIVE | IMAGE_DRAW_SEMITRANSPARENT ) ) { BitmapEx aTmpBmpEx; const Rectangle aCropRect( aSrcPos, maSize ); if( mpInfoAry[ nPos ] & ( IMPSYSIMAGEITEM_MASK | IMPSYSIMAGEITEM_ALPHA ) ) aTmpBmpEx = maBmpEx; else aTmpBmpEx = maBmpEx.GetBitmap(); aTmpBmpEx.Crop( aCropRect ); Bitmap aTmpBmp( aTmpBmpEx.GetBitmap() ); if( nStyle & ( IMAGE_DRAW_HIGHLIGHT | IMAGE_DRAW_DEACTIVE ) ) { BitmapWriteAccess* pAcc = aTmpBmp.AcquireWriteAccess(); if( pAcc ) { const StyleSettings& rSettings = pOutDev->GetSettings().GetStyleSettings(); Color aColor; BitmapColor aCol; const long nW = pAcc->Width(); const long nH = pAcc->Height(); boost::scoped_array<sal_uInt8> pMapR(new sal_uInt8[ 256 ]); boost::scoped_array<sal_uInt8> pMapG(new sal_uInt8[ 256 ]); boost::scoped_array<sal_uInt8> pMapB(new sal_uInt8[ 256 ]); long nX, nY; if( nStyle & IMAGE_DRAW_HIGHLIGHT ) aColor = rSettings.GetHighlightColor(); else aColor = rSettings.GetDeactiveColor(); const sal_uInt8 cR = aColor.GetRed(); const sal_uInt8 cG = aColor.GetGreen(); const sal_uInt8 cB = aColor.GetBlue(); for( nX = 0L; nX < 256L; nX++ ) { pMapR[ nX ] = (sal_uInt8) ( ( ( nY = ( nX + cR ) >> 1 ) > 255 ) ? 255 : nY ); pMapG[ nX ] = (sal_uInt8) ( ( ( nY = ( nX + cG ) >> 1 ) > 255 ) ? 255 : nY ); pMapB[ nX ] = (sal_uInt8) ( ( ( nY = ( nX + cB ) >> 1 ) > 255 ) ? 255 : nY ); } if( pAcc->HasPalette() ) { for( sal_uInt16 i = 0, nCount = pAcc->GetPaletteEntryCount(); i < nCount; i++ ) { const BitmapColor& rCol = pAcc->GetPaletteColor( i ); aCol.SetRed( pMapR[ rCol.GetRed() ] ); aCol.SetGreen( pMapG[ rCol.GetGreen() ] ); aCol.SetBlue( pMapB[ rCol.GetBlue() ] ); pAcc->SetPaletteColor( i, aCol ); } } else if( pAcc->GetScanlineFormat() == BMP_FORMAT_24BIT_TC_BGR ) { for( nY = 0L; nY < nH; nY++ ) { Scanline pScan = pAcc->GetScanline( nY ); for( nX = 0L; nX < nW; nX++ ) { *pScan = pMapB[ *pScan ]; pScan++; *pScan = pMapG[ *pScan ]; pScan++; *pScan = pMapR[ *pScan ]; pScan++; } } } else { for( nY = 0L; nY < nH; nY++ ) { for( nX = 0L; nX < nW; nX++ ) { aCol = pAcc->GetPixel( nY, nX ); aCol.SetRed( pMapR[ aCol.GetRed() ] ); aCol.SetGreen( pMapG[ aCol.GetGreen() ] ); aCol.SetBlue( pMapB[ aCol.GetBlue() ] ); pAcc->SetPixel( nY, nX, aCol ); } } } aTmpBmp.ReleaseAccess( pAcc ); } } if( nStyle & IMAGE_DRAW_SEMITRANSPARENT ) { if( aTmpBmpEx.IsTransparent() ) { Bitmap aAlphaBmp( aTmpBmpEx.GetAlpha().GetBitmap() ); aAlphaBmp.Adjust( 50 ); aTmpBmpEx = BitmapEx( aTmpBmp, AlphaMask( aAlphaBmp ) ); } else { sal_uInt8 cErase = 128; aTmpBmpEx = BitmapEx( aTmpBmp, AlphaMask( aTmpBmp.GetSizePixel(), &cErase ) ); } } else { if( aTmpBmpEx.IsAlpha() ) aTmpBmpEx = BitmapEx( aTmpBmp, aTmpBmpEx.GetAlpha() ); else if( aTmpBmpEx.IsAlpha() ) aTmpBmpEx = BitmapEx( aTmpBmp, aTmpBmpEx.GetMask() ); } pOutDev->DrawBitmapEx( rPos, aOutSize, aTmpBmpEx ); } else { const BitmapEx* pOutputBmp; if( pOutDev->GetOutDevType() == OUTDEV_WINDOW ) { ImplUpdateDisplayBmp( pOutDev ); pOutputBmp = mpDisplayBmp; } else pOutputBmp = &maBmpEx; if( pOutputBmp ) pOutDev->DrawBitmapEx( rPos, aOutSize, aSrcPos, maSize, *pOutputBmp ); } } } } void ImplImageBmp::ImplUpdateDisplayBmp( OutputDevice* #if defined WNT pOutDev #endif ) { if( !mpDisplayBmp && !maBmpEx.IsEmpty() ) { #if defined WNT if( maBmpEx.IsAlpha() ) mpDisplayBmp = new BitmapEx( maBmpEx ); else { const Bitmap aBmp( maBmpEx.GetBitmap().CreateDisplayBitmap( pOutDev ) ); if( maBmpEx.IsTransparent() ) mpDisplayBmp = new BitmapEx( aBmp, maBmpEx.GetMask().CreateDisplayBitmap( pOutDev ) ); else mpDisplayBmp = new BitmapEx( aBmp ); } #else mpDisplayBmp = new BitmapEx( maBmpEx ); #endif } } void ImplImageBmp::ImplUpdateDisabledBmpEx( int nPos ) { const Size aTotalSize( maBmpEx.GetSizePixel() ); if( maDisabledBmpEx.IsEmpty() ) { Bitmap aGrey( aTotalSize, 8, &Bitmap::GetGreyPalette( 256 ) ); AlphaMask aGreyAlphaMask( aTotalSize ); maDisabledBmpEx = BitmapEx( aGrey, aGreyAlphaMask ); nPos = -1; } Bitmap aBmp( maBmpEx.GetBitmap() ); BitmapReadAccess* pBmp( aBmp.AcquireReadAccess() ); AlphaMask aBmpAlphaMask( maBmpEx.GetAlpha() ); BitmapReadAccess* pBmpAlphaMask( aBmpAlphaMask.AcquireReadAccess() ); Bitmap aGrey( maDisabledBmpEx.GetBitmap() ); BitmapWriteAccess* pGrey( aGrey.AcquireWriteAccess() ); AlphaMask aGreyAlphaMask( maDisabledBmpEx.GetAlpha() ); BitmapWriteAccess* pGreyAlphaMask( aGreyAlphaMask.AcquireWriteAccess() ); if( pBmp && pBmpAlphaMask && pGrey && pGreyAlphaMask ) { BitmapColor aGreyVal( 0 ); BitmapColor aGreyAlphaMaskVal( 0 ); const Point aPos( ( nPos < 0 ) ? 0 : ( nPos * maSize.Width() ), 0 ); const int nLeft = aPos.X(), nRight = nLeft + ( ( nPos < 0 ) ? aTotalSize.Width() : maSize.Width() ); const int nTop = aPos.Y(), nBottom = nTop + maSize.Height(); for( int nY = nTop; nY < nBottom; ++nY ) { for( int nX = nLeft; nX < nRight; ++nX ) { aGreyVal.SetIndex( pBmp->GetLuminance( nY, nX ) ); pGrey->SetPixel( nY, nX, aGreyVal ); const BitmapColor aBmpAlphaMaskVal( pBmpAlphaMask->GetPixel( nY, nX ) ); aGreyAlphaMaskVal.SetIndex( static_cast< sal_uInt8 >( ::std::min( aBmpAlphaMaskVal.GetIndex() + 178ul, 255ul ) ) ); pGreyAlphaMask->SetPixel( nY, nX, aGreyAlphaMaskVal ); } } } aBmp.ReleaseAccess( pBmp ); aBmpAlphaMask.ReleaseAccess( pBmpAlphaMask ); aGrey.ReleaseAccess( pGrey ); aGreyAlphaMask.ReleaseAccess( pGreyAlphaMask ); maDisabledBmpEx = BitmapEx( aGrey, aGreyAlphaMask ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>cppcheck: multiCondition<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <vcl/outdev.hxx> #include <vcl/bitmapex.hxx> #include <vcl/alpha.hxx> #include <vcl/window.hxx> #include <vcl/bmpacc.hxx> #include <vcl/virdev.hxx> #include <vcl/image.hxx> #include <vcl/settings.hxx> #include <image.h> #include <boost/scoped_array.hpp> #define IMPSYSIMAGEITEM_MASK ( 0x01 ) #define IMPSYSIMAGEITEM_ALPHA ( 0x02 ) ImageAryData::ImageAryData( const ImageAryData& rData ) : maName( rData.maName ), mnId( rData.mnId ), maBitmapEx( rData.maBitmapEx ) { } ImageAryData::ImageAryData( const OUString &aName, sal_uInt16 nId, const BitmapEx &aBitmap ) : maName( aName ), mnId( nId ), maBitmapEx( aBitmap ) { } ImageAryData::~ImageAryData() { } ImageAryData& ImageAryData::operator=( const ImageAryData& rData ) { maName = rData.maName; mnId = rData.mnId; maBitmapEx = rData.maBitmapEx; return *this; } ImplImageList::ImplImageList() : mnRefCount(1) { } ImplImageList::ImplImageList( const ImplImageList &aSrc ) : maPrefix(aSrc.maPrefix) , maImageSize(aSrc.maImageSize) , mnRefCount(1) { maImages.reserve( aSrc.maImages.size() ); for ( ImageAryDataVec::const_iterator aIt = aSrc.maImages.begin(), aEnd = aSrc.maImages.end(); aIt != aEnd; ++aIt ) { ImageAryData* pAryData = new ImageAryData( **aIt ); maImages.push_back( pAryData ); if( !pAryData->maName.isEmpty() ) maNameHash [ pAryData->maName ] = pAryData; } } ImplImageList::~ImplImageList() { for ( ImageAryDataVec::iterator aIt = maImages.begin(), aEnd = maImages.end(); aIt != aEnd; ++aIt ) delete *aIt; } void ImplImageList::AddImage( const OUString &aName, sal_uInt16 nId, const BitmapEx &aBitmapEx ) { ImageAryData *pImg = new ImageAryData( aName, nId, aBitmapEx ); maImages.push_back( pImg ); if( !aName.isEmpty() ) maNameHash [ aName ] = pImg; } void ImplImageList::RemoveImage( sal_uInt16 nPos ) { ImageAryData *pImg = maImages[ nPos ]; if( !pImg->maName.isEmpty() ) maNameHash.erase( pImg->maName ); maImages.erase( maImages.begin() + nPos ); } ImplImageData::ImplImageData( const BitmapEx& rBmpEx ) : mpImageBitmap( NULL ), maBmpEx( rBmpEx ) { } ImplImageData::~ImplImageData() { delete mpImageBitmap; } bool ImplImageData::IsEqual( const ImplImageData& rData ) { return( maBmpEx == rData.maBmpEx ); } ImplImage::ImplImage() : mnRefCount(1) , mpData(NULL) , meType(IMAGETYPE_BITMAP) { } ImplImage::~ImplImage() { switch( meType ) { case IMAGETYPE_BITMAP: delete static_cast< Bitmap* >( mpData ); break; case IMAGETYPE_IMAGE: delete static_cast< ImplImageData* >( mpData ); break; } } ImplImageBmp::ImplImageBmp() : mpDisplayBmp( NULL ), mpInfoAry( NULL ), mnSize( 0 ) { } ImplImageBmp::~ImplImageBmp() { delete[] mpInfoAry; delete mpDisplayBmp; } void ImplImageBmp::Create( const BitmapEx& rBmpEx, long nItemWidth, long nItemHeight, sal_uInt16 nInitSize ) { maBmpEx = rBmpEx; maDisabledBmpEx.SetEmpty(); delete mpDisplayBmp; mpDisplayBmp = NULL; maSize = Size( nItemWidth, nItemHeight ); mnSize = nInitSize; delete[] mpInfoAry; mpInfoAry = new sal_uInt8[ mnSize ]; memset( mpInfoAry, rBmpEx.IsAlpha() ? IMPSYSIMAGEITEM_ALPHA : ( rBmpEx.IsTransparent() ? IMPSYSIMAGEITEM_MASK : 0 ), mnSize ); } void ImplImageBmp::Draw( sal_uInt16 nPos, OutputDevice* pOutDev, const Point& rPos, sal_uInt16 nStyle, const Size* pSize ) { if( pOutDev->IsDeviceOutputNecessary() ) { const Point aSrcPos( nPos * maSize.Width(), 0 ); Size aOutSize; aOutSize = ( pSize ? *pSize : pOutDev->PixelToLogic( maSize ) ); if( nStyle & IMAGE_DRAW_DISABLE ) { ImplUpdateDisabledBmpEx( nPos); pOutDev->DrawBitmapEx( rPos, aOutSize, aSrcPos, maSize, maDisabledBmpEx ); } else { if( nStyle & ( IMAGE_DRAW_COLORTRANSFORM | IMAGE_DRAW_HIGHLIGHT | IMAGE_DRAW_DEACTIVE | IMAGE_DRAW_SEMITRANSPARENT ) ) { BitmapEx aTmpBmpEx; const Rectangle aCropRect( aSrcPos, maSize ); if( mpInfoAry[ nPos ] & ( IMPSYSIMAGEITEM_MASK | IMPSYSIMAGEITEM_ALPHA ) ) aTmpBmpEx = maBmpEx; else aTmpBmpEx = maBmpEx.GetBitmap(); aTmpBmpEx.Crop( aCropRect ); Bitmap aTmpBmp( aTmpBmpEx.GetBitmap() ); if( nStyle & ( IMAGE_DRAW_HIGHLIGHT | IMAGE_DRAW_DEACTIVE ) ) { BitmapWriteAccess* pAcc = aTmpBmp.AcquireWriteAccess(); if( pAcc ) { const StyleSettings& rSettings = pOutDev->GetSettings().GetStyleSettings(); Color aColor; BitmapColor aCol; const long nW = pAcc->Width(); const long nH = pAcc->Height(); boost::scoped_array<sal_uInt8> pMapR(new sal_uInt8[ 256 ]); boost::scoped_array<sal_uInt8> pMapG(new sal_uInt8[ 256 ]); boost::scoped_array<sal_uInt8> pMapB(new sal_uInt8[ 256 ]); long nX, nY; if( nStyle & IMAGE_DRAW_HIGHLIGHT ) aColor = rSettings.GetHighlightColor(); else aColor = rSettings.GetDeactiveColor(); const sal_uInt8 cR = aColor.GetRed(); const sal_uInt8 cG = aColor.GetGreen(); const sal_uInt8 cB = aColor.GetBlue(); for( nX = 0L; nX < 256L; nX++ ) { pMapR[ nX ] = (sal_uInt8) ( ( ( nY = ( nX + cR ) >> 1 ) > 255 ) ? 255 : nY ); pMapG[ nX ] = (sal_uInt8) ( ( ( nY = ( nX + cG ) >> 1 ) > 255 ) ? 255 : nY ); pMapB[ nX ] = (sal_uInt8) ( ( ( nY = ( nX + cB ) >> 1 ) > 255 ) ? 255 : nY ); } if( pAcc->HasPalette() ) { for( sal_uInt16 i = 0, nCount = pAcc->GetPaletteEntryCount(); i < nCount; i++ ) { const BitmapColor& rCol = pAcc->GetPaletteColor( i ); aCol.SetRed( pMapR[ rCol.GetRed() ] ); aCol.SetGreen( pMapG[ rCol.GetGreen() ] ); aCol.SetBlue( pMapB[ rCol.GetBlue() ] ); pAcc->SetPaletteColor( i, aCol ); } } else if( pAcc->GetScanlineFormat() == BMP_FORMAT_24BIT_TC_BGR ) { for( nY = 0L; nY < nH; nY++ ) { Scanline pScan = pAcc->GetScanline( nY ); for( nX = 0L; nX < nW; nX++ ) { *pScan = pMapB[ *pScan ]; pScan++; *pScan = pMapG[ *pScan ]; pScan++; *pScan = pMapR[ *pScan ]; pScan++; } } } else { for( nY = 0L; nY < nH; nY++ ) { for( nX = 0L; nX < nW; nX++ ) { aCol = pAcc->GetPixel( nY, nX ); aCol.SetRed( pMapR[ aCol.GetRed() ] ); aCol.SetGreen( pMapG[ aCol.GetGreen() ] ); aCol.SetBlue( pMapB[ aCol.GetBlue() ] ); pAcc->SetPixel( nY, nX, aCol ); } } } aTmpBmp.ReleaseAccess( pAcc ); } } if( nStyle & IMAGE_DRAW_SEMITRANSPARENT ) { if( aTmpBmpEx.IsTransparent() ) { Bitmap aAlphaBmp( aTmpBmpEx.GetAlpha().GetBitmap() ); aAlphaBmp.Adjust( 50 ); aTmpBmpEx = BitmapEx( aTmpBmp, AlphaMask( aAlphaBmp ) ); } else { sal_uInt8 cErase = 128; aTmpBmpEx = BitmapEx( aTmpBmp, AlphaMask( aTmpBmp.GetSizePixel(), &cErase ) ); } } else { if( aTmpBmpEx.IsAlpha() ) aTmpBmpEx = BitmapEx( aTmpBmp, aTmpBmpEx.GetAlpha() ); else if( aTmpBmpEx.IsTransparent() ) aTmpBmpEx = BitmapEx( aTmpBmp, aTmpBmpEx.GetMask() ); } pOutDev->DrawBitmapEx( rPos, aOutSize, aTmpBmpEx ); } else { const BitmapEx* pOutputBmp; if( pOutDev->GetOutDevType() == OUTDEV_WINDOW ) { ImplUpdateDisplayBmp( pOutDev ); pOutputBmp = mpDisplayBmp; } else pOutputBmp = &maBmpEx; if( pOutputBmp ) pOutDev->DrawBitmapEx( rPos, aOutSize, aSrcPos, maSize, *pOutputBmp ); } } } } void ImplImageBmp::ImplUpdateDisplayBmp( OutputDevice* #if defined WNT pOutDev #endif ) { if( !mpDisplayBmp && !maBmpEx.IsEmpty() ) { #if defined WNT if( maBmpEx.IsAlpha() ) mpDisplayBmp = new BitmapEx( maBmpEx ); else { const Bitmap aBmp( maBmpEx.GetBitmap().CreateDisplayBitmap( pOutDev ) ); if( maBmpEx.IsTransparent() ) mpDisplayBmp = new BitmapEx( aBmp, maBmpEx.GetMask().CreateDisplayBitmap( pOutDev ) ); else mpDisplayBmp = new BitmapEx( aBmp ); } #else mpDisplayBmp = new BitmapEx( maBmpEx ); #endif } } void ImplImageBmp::ImplUpdateDisabledBmpEx( int nPos ) { const Size aTotalSize( maBmpEx.GetSizePixel() ); if( maDisabledBmpEx.IsEmpty() ) { Bitmap aGrey( aTotalSize, 8, &Bitmap::GetGreyPalette( 256 ) ); AlphaMask aGreyAlphaMask( aTotalSize ); maDisabledBmpEx = BitmapEx( aGrey, aGreyAlphaMask ); nPos = -1; } Bitmap aBmp( maBmpEx.GetBitmap() ); BitmapReadAccess* pBmp( aBmp.AcquireReadAccess() ); AlphaMask aBmpAlphaMask( maBmpEx.GetAlpha() ); BitmapReadAccess* pBmpAlphaMask( aBmpAlphaMask.AcquireReadAccess() ); Bitmap aGrey( maDisabledBmpEx.GetBitmap() ); BitmapWriteAccess* pGrey( aGrey.AcquireWriteAccess() ); AlphaMask aGreyAlphaMask( maDisabledBmpEx.GetAlpha() ); BitmapWriteAccess* pGreyAlphaMask( aGreyAlphaMask.AcquireWriteAccess() ); if( pBmp && pBmpAlphaMask && pGrey && pGreyAlphaMask ) { BitmapColor aGreyVal( 0 ); BitmapColor aGreyAlphaMaskVal( 0 ); const Point aPos( ( nPos < 0 ) ? 0 : ( nPos * maSize.Width() ), 0 ); const int nLeft = aPos.X(), nRight = nLeft + ( ( nPos < 0 ) ? aTotalSize.Width() : maSize.Width() ); const int nTop = aPos.Y(), nBottom = nTop + maSize.Height(); for( int nY = nTop; nY < nBottom; ++nY ) { for( int nX = nLeft; nX < nRight; ++nX ) { aGreyVal.SetIndex( pBmp->GetLuminance( nY, nX ) ); pGrey->SetPixel( nY, nX, aGreyVal ); const BitmapColor aBmpAlphaMaskVal( pBmpAlphaMask->GetPixel( nY, nX ) ); aGreyAlphaMaskVal.SetIndex( static_cast< sal_uInt8 >( ::std::min( aBmpAlphaMaskVal.GetIndex() + 178ul, 255ul ) ) ); pGreyAlphaMask->SetPixel( nY, nX, aGreyAlphaMaskVal ); } } } aBmp.ReleaseAccess( pBmp ); aBmpAlphaMask.ReleaseAccess( pBmpAlphaMask ); aGrey.ReleaseAccess( pGrey ); aGreyAlphaMask.ReleaseAccess( pGreyAlphaMask ); maDisabledBmpEx = BitmapEx( aGrey, aGreyAlphaMask ); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include "MARCdata.hpp" void MARCdata::csvOutput(const std::string filename){ constructSubfields(); ogzstream table(filename.c_str()); table << "008lang|100a|100d|240n|245a|260a|260b|260c|300a|300c|650a|650y,651y|650z,651a,651z\n"; for (auto& book : books){ int langIdx = book["008"]['#'].length()-5; table << book["008"]['#'].substr(langIdx,3) << "|"; table << book["100"]['a'] << "|"; table << book["100"]['d'] << "|"; table << book["240"]['n'] << "|"; table << book["245"]['a'] << "|"; table << book["260"]['a'] << "|"; table << book["260"]['b'] << "|"; table << book["260"]['c'] << "|"; table << book["300"]['a'] << "|"; table << book["300"]['c'] << "|"; table << book["650"]['a'] << "|"; table << book["650"]['y'] << ";"; table << book["651"]['y'] << "|"; table << book["650"]['z'] << ";"; table << book["651"]['a'] << ";"; table << book["651"]['z'] << "\n"; } } int main() { MARCdata estc; estc.xmlInput("data/ESTChistory.xml"); estc.csvOutput("data/estc.csv.gz"); return 0; } <commit_msg>ESTC full OK<commit_after>#include "MARCdata.hpp" void MARCdata::csvOutput(const std::string filename){ constructSubfields(); ogzstream table(filename.c_str()); table << "008lang|100a|100d|240n|245a|260a|260b|260c|300a|300c|650a|650y,651y|650z,651a,651z\n"; for (auto& book : books){ int langIdx = book["008"]['#'].length()-5; table << book["008"]['#'].substr(langIdx,3) << "|"; table << book["100"]['a'] << "|"; table << book["100"]['d'] << "|"; table << book["240"]['n'] << "|"; table << book["245"]['a'] << "|"; table << book["260"]['a'] << "|"; table << book["260"]['b'] << "|"; table << book["260"]['c'] << "|"; table << book["300"]['a'] << "|"; table << book["300"]['c'] << "|"; table << book["650"]['a'] << "|"; table << book["650"]['y'] << ";"; table << book["651"]['y'] << "|"; table << book["650"]['z'] << ";"; table << book["651"]['a'] << ";"; table << book["651"]['z'] << "\n"; } } int main() { MARCdata estc; estc.xmlInput("data/estc.xml"); estc.csvOutput("data/estc.csv.gz"); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: unovirtualmachine.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2005-07-07 10:53:52 $ * * 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: 2005 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include "sal/config.h" #include "jvmaccess/unovirtualmachine.hxx" #include "osl/diagnose.h" #include "jvmaccess/virtualmachine.hxx" #if defined SOLAR_JAVA #include "jni.h" #endif namespace jvmaccess { UnoVirtualMachine::CreationException::CreationException() {} UnoVirtualMachine::CreationException::CreationException( CreationException const &) {} UnoVirtualMachine::CreationException::~CreationException() {} UnoVirtualMachine::CreationException & UnoVirtualMachine::CreationException::operator =(CreationException const &) { return *this; } UnoVirtualMachine::UnoVirtualMachine( rtl::Reference< jvmaccess::VirtualMachine > const & virtualMachine, void * classLoader): m_virtualMachine(virtualMachine), m_classLoader(0) { #if defined SOLAR_JAVA try { m_classLoader = jvmaccess::VirtualMachine::AttachGuard(m_virtualMachine). getEnvironment()->NewGlobalRef(static_cast< jobject >(classLoader)); } catch (jvmaccess::VirtualMachine::AttachGuard::CreationException &) {} #endif if (m_classLoader == 0) { throw CreationException(); } } rtl::Reference< jvmaccess::VirtualMachine > UnoVirtualMachine::getVirtualMachine() const { return m_virtualMachine; } void * UnoVirtualMachine::getClassLoader() const { return m_classLoader; } UnoVirtualMachine::~UnoVirtualMachine() { #if defined SOLAR_JAVA try { jvmaccess::VirtualMachine::AttachGuard(m_virtualMachine). getEnvironment()->DeleteGlobalRef( static_cast< jobject >(m_classLoader)); } catch (jvmaccess::VirtualMachine::AttachGuard::CreationException &) { OSL_TRACE( "jvmaccess::UnoVirtualMachine::~UnoVirtualMachine:" " jvmaccess::VirtualMachine::AttachGuard::CreationException" ); } #endif } } <commit_msg>INTEGRATION: CWS ooo19126 (1.3.4); FILE MERGED 2005/09/05 14:40:57 rt 1.3.4.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: unovirtualmachine.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-07 19:23:03 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "sal/config.h" #include "jvmaccess/unovirtualmachine.hxx" #include "osl/diagnose.h" #include "jvmaccess/virtualmachine.hxx" #if defined SOLAR_JAVA #include "jni.h" #endif namespace jvmaccess { UnoVirtualMachine::CreationException::CreationException() {} UnoVirtualMachine::CreationException::CreationException( CreationException const &) {} UnoVirtualMachine::CreationException::~CreationException() {} UnoVirtualMachine::CreationException & UnoVirtualMachine::CreationException::operator =(CreationException const &) { return *this; } UnoVirtualMachine::UnoVirtualMachine( rtl::Reference< jvmaccess::VirtualMachine > const & virtualMachine, void * classLoader): m_virtualMachine(virtualMachine), m_classLoader(0) { #if defined SOLAR_JAVA try { m_classLoader = jvmaccess::VirtualMachine::AttachGuard(m_virtualMachine). getEnvironment()->NewGlobalRef(static_cast< jobject >(classLoader)); } catch (jvmaccess::VirtualMachine::AttachGuard::CreationException &) {} #endif if (m_classLoader == 0) { throw CreationException(); } } rtl::Reference< jvmaccess::VirtualMachine > UnoVirtualMachine::getVirtualMachine() const { return m_virtualMachine; } void * UnoVirtualMachine::getClassLoader() const { return m_classLoader; } UnoVirtualMachine::~UnoVirtualMachine() { #if defined SOLAR_JAVA try { jvmaccess::VirtualMachine::AttachGuard(m_virtualMachine). getEnvironment()->DeleteGlobalRef( static_cast< jobject >(m_classLoader)); } catch (jvmaccess::VirtualMachine::AttachGuard::CreationException &) { OSL_TRACE( "jvmaccess::UnoVirtualMachine::~UnoVirtualMachine:" " jvmaccess::VirtualMachine::AttachGuard::CreationException" ); } #endif } } <|endoftext|>
<commit_before>/* This file is part of KAddressBook. Copyright (c) 2002 Mike Pilone <mpilone@slac.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "contactlistview.h" #include <QToolTip> #include <Qt3Support/Q3Header> #include <QtGui/QBrush> #include <QtGui/QDropEvent> #include <QtGui/QMouseEvent> #include <QtGui/QPainter> #include <QtGui/QPixmap> #include <k3listview.h> #include <kabc/addressbook.h> #include <kabc/addressee.h> #include <kapplication.h> #include <kcolorscheme.h> #include <kconfig.h> #include <kdebug.h> #include <kimproxy.h> #include <klocale.h> #include <kurl.h> #include "kaddressbooktableview.h" /////////////////////////// // ContactListViewItem Methods ContactListViewItem::ContactListViewItem(const KABC::Addressee &a, ContactListView *parent, KABC::AddressBook *doc, const KABC::Field::List &fields, KIMProxy *proxy ) : K3ListViewItem(parent), mAddressee(a), mFields( fields ), parentListView( parent ), mDocument(doc), mIMProxy( proxy ) { if ( mIMProxy ) mHasIM = mIMProxy->isPresent( mAddressee.uid() ); else mHasIM = false; refresh(); } QString ContactListViewItem::key(int column, bool ascending) const { // Preserve behaviour of QListViewItem::key(), otherwise we cause a crash if the column does not exist if ( column >= parentListView->columns() ) return QString(); Q_UNUSED( ascending ) if ( parentListView->showIM() ) { // in this case, one column is reserved for IM presence // so we have to process it differently if ( column == parentListView->imColumn() ) { // increment by one before converting to string so that -1 is not greater than 1 // create the sort key by taking the numeric status 0 low, 5 high, and subtracting it from 5 // so that the default ascending gives online before offline, etc. QString key = QString::number( 5 - ( mIMProxy->presenceNumeric( mAddressee.uid() ) + 1 ) ); return key; } else { return mFields[ column ]->sortKey( mAddressee ); } } else return mFields[ column ]->sortKey( mAddressee ); } void ContactListViewItem::paintCell(QPainter * p, const QColorGroup & cg, int column, int width, int align) { K3ListViewItem::paintCell(p, cg, column, width, align); if ( !p ) return; if (parentListView->singleLine()) { p->setPen( parentListView->alternateColor() ); p->drawLine( 0, height() - 1, width, height() - 1 ); } } ContactListView *ContactListViewItem::parent() { return parentListView; } void ContactListViewItem::refresh() { // Update our addressee, since it may have changed else were mAddressee = mDocument->findByUid(mAddressee.uid()); if (mAddressee.isEmpty()) return; int i = 0; // don't show unknown presence, it's not interesting if ( mHasIM ) { if ( mIMProxy->presenceNumeric( mAddressee.uid() ) > 0 ) setPixmap( parentListView->imColumn(), mIMProxy->presenceIcon( mAddressee.uid() ) ); else setPixmap( parentListView->imColumn(), QPixmap() ); } KABC::Field::List::ConstIterator it; for ( it = mFields.constBegin(); it != mFields.constEnd(); ++it ) { if ( (*it)->label() == KABC::Addressee::birthdayLabel() ) { QDate date = mAddressee.birthday().date(); if ( date.isValid() ) setText( i++, KGlobal::locale()->formatDate( date, KLocale::ShortDate ) ); else setText( i++, "" ); } else setText( i++, (*it)->value( mAddressee ) ); } } void ContactListViewItem::setHasIM( bool hasIM ) { mHasIM = hasIM; } /////////////////////////////// // ContactListView ContactListView::ContactListView(KAddressBookTableView *view, KABC::AddressBook* /* doc */, QWidget *parent, const char *name ) : K3ListView( parent ), pabWidget( view ), oldColumn( 0 ) { setObjectName(name); mABackground = true; mSingleLine = false; mToolTips = true; mShowIM = true; mAlternateColor = KColorScheme( QPalette::Active, KColorScheme::View ).background( KColorScheme::AlternateBackground ).color(); setAlternateBackgroundEnabled(mABackground); setAcceptDrops( true ); viewport()->setAcceptDrops( true ); setAllColumnsShowFocus( true ); setShowSortIndicator(true); setSelectionModeExt( K3ListView::Extended ); setDropVisualizer(false); connect(this, SIGNAL(dropped(QDropEvent*)), this, SLOT(itemDropped(QDropEvent*))); } bool ContactListView::event( QEvent *e ) { if( e->type() != QEvent::ToolTip ) return K3ListView::event( e ); if ( !tooltips() ) return true; QHelpEvent * he = static_cast< QHelpEvent * >( e ); QPoint pnt = viewport()->mapFromGlobal( mapToGlobal( he->pos() ) ); Q3ListViewItem * item = itemAt ( pnt ); if ( item ) { ContactListViewItem *plvi = static_cast<ContactListViewItem *>( item ); QString s; //kDebug(5720) <<"Tip rec:" << r.x() <<"," << r.y() <<"," << r.width() // << "," << r.height(); KABC::Addressee a = plvi->addressee(); if (a.isEmpty()) return true; s += i18nc("label: value", "%1: %2", a.formattedNameLabel(), a.formattedName()); s += '\n'; s += i18nc("label: value", "%1: %2", a.organizationLabel(), a.organization()); QString notes = a.note().trimmed(); if ( !notes.isEmpty() ) { notes += '\n'; s += '\n' + i18nc("label: value", "%1: \n", a.noteLabel()); QFontMetrics fm( font() ); // Begin word wrap code based on QMultiLineEdit code int i = 0; bool doBreak = false; int linew = 0; int lastSpace = -1; int a = 0; int lastw = 0; while ( i < int(notes.length()) ) { doBreak = false; if ( notes[i] != '\n' ) linew += fm.width( notes[i] ); if ( lastSpace >= a && notes[i] != '\n' ) if (linew >= parentWidget()->width()) { doBreak = true; if ( lastSpace > a ) { i = lastSpace; linew = lastw; } else i = qMax( a, i-1 ); } if ( notes[i] == '\n' || doBreak ) { s += notes.mid( a, i - a + (doBreak?1:0) ) +'\n'; a = i + 1; lastSpace = a; linew = 0; } if ( notes[i].isSpace() ) { lastSpace = i; lastw = linew; } if ( lastSpace <= a ) { lastw = linew; } ++i; } } if ( s.isEmpty() ) QToolTip::hideText(); else QToolTip::showText( he->globalPos(), s ); } return true; } void ContactListView::paintEmptyArea( QPainter * p, const QRect & rect ) { QBrush b = palette().brush(QPalette::Active, QPalette::Base); // Get the brush, which will have the background pixmap if there is one. if (!b.texture().isNull()) { p->drawTiledPixmap( rect.left(), rect.top(), rect.width(), rect.height(), b.texture(), rect.left() + contentsX(), rect.top() + contentsY() ); } else { // Do a normal paint K3ListView::paintEmptyArea(p, rect); } } void ContactListView::contentsMousePressEvent(QMouseEvent* e) { presspos = e->pos(); K3ListView::contentsMousePressEvent(e); } // To initiate a drag operation void ContactListView::contentsMouseMoveEvent( QMouseEvent *e ) { if ((e->buttons() & Qt::LeftButton) && (e->pos() - presspos).manhattanLength() > 4 ) { emit startAddresseeDrag(); } else K3ListView::contentsMouseMoveEvent( e ); } bool ContactListView::acceptDrag(QDropEvent *e) const { return e->mimeData()->hasText(); } void ContactListView::itemDropped(QDropEvent *e) { contentsDropEvent(e); } void ContactListView::contentsDropEvent( QDropEvent *e ) { emit addresseeDropped(e); } void ContactListView::setAlternateBackgroundEnabled(bool enabled) { mABackground = enabled; if (mABackground) { setAlternateBackground(mAlternateColor); } else { setAlternateBackground(QColor()); } } void ContactListView::setBackgroundPixmap(const QString &filename) { if (filename.isEmpty()) { setPalette( QPalette() ); } else { QPalette palette; palette.setBrush( backgroundRole(), QBrush(QPixmap(filename) )); setPalette( palette ); } } void ContactListView::setShowIM( bool enabled ) { mShowIM = enabled; } bool ContactListView::showIM() { return mShowIM; } void ContactListView::setIMColumn( int column ) { mInstantMsgColumn = column; } int ContactListView::imColumn() { return mInstantMsgColumn; } #include "contactlistview.moc" <commit_msg>backport SVN commit 992417 by winterz:<commit_after>/* This file is part of KAddressBook. Copyright (c) 2002 Mike Pilone <mpilone@slac.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, permission is given to link this program with any edition of Qt, and distribute the resulting executable, without including the source code for Qt in the source distribution. */ #include "contactlistview.h" #include <QToolTip> #include <Qt3Support/Q3Header> #include <QtGui/QBrush> #include <QtGui/QDropEvent> #include <QtGui/QMouseEvent> #include <QtGui/QPainter> #include <QtGui/QPixmap> #include <k3listview.h> #include <kabc/addressbook.h> #include <kabc/addressee.h> #include <kapplication.h> #include <kcolorscheme.h> #include <kconfig.h> #include <kdebug.h> #include <kimproxy.h> #include <klocale.h> #include <kurl.h> #include "kaddressbooktableview.h" /////////////////////////// // ContactListViewItem Methods ContactListViewItem::ContactListViewItem(const KABC::Addressee &a, ContactListView *parent, KABC::AddressBook *doc, const KABC::Field::List &fields, KIMProxy *proxy ) : K3ListViewItem(parent), mAddressee(a), mFields( fields ), parentListView( parent ), mDocument(doc), mIMProxy( proxy ) { if ( mIMProxy ) mHasIM = mIMProxy->isPresent( mAddressee.uid() ); else mHasIM = false; refresh(); } QString ContactListViewItem::key(int column, bool ascending) const { // Preserve behaviour of QListViewItem::key(), otherwise we cause a crash if the column does not exist if ( column >= parentListView->columns() ) return QString(); Q_UNUSED( ascending ) if ( parentListView->showIM() ) { // in this case, one column is reserved for IM presence // so we have to process it differently if ( column == parentListView->imColumn() ) { // increment by one before converting to string so that -1 is not greater than 1 // create the sort key by taking the numeric status 0 low, 5 high, and subtracting it from 5 // so that the default ascending gives online before offline, etc. QString key = QString::number( 5 - ( mIMProxy->presenceNumeric( mAddressee.uid() ) + 1 ) ); return key; } else { return mFields[ column ]->sortKey( mAddressee ); } } else return mFields[ column ]->sortKey( mAddressee ); } void ContactListViewItem::paintCell(QPainter * p, const QColorGroup & cg, int column, int width, int align) { K3ListViewItem::paintCell(p, cg, column, width, align); if ( !p ) return; if (parentListView->singleLine()) { p->setPen( parentListView->alternateColor() ); p->drawLine( 0, height() - 1, width, height() - 1 ); } } ContactListView *ContactListViewItem::parent() { return parentListView; } void ContactListViewItem::refresh() { if ( !mDocument ) { return; } // Update our addressee, since it may have changed else were mAddressee = mDocument->findByUid( mAddressee.uid() ); if ( mAddressee.isEmpty() ) { return; } int i = 0; // don't show unknown presence, it's not interesting if ( mHasIM ) { if ( mIMProxy->presenceNumeric( mAddressee.uid() ) > 0 ) setPixmap( parentListView->imColumn(), mIMProxy->presenceIcon( mAddressee.uid() ) ); else setPixmap( parentListView->imColumn(), QPixmap() ); } KABC::Field::List::ConstIterator it; for ( it = mFields.constBegin(); it != mFields.constEnd(); ++it ) { if ( (*it)->label() == KABC::Addressee::birthdayLabel() ) { QDate date = mAddressee.birthday().date(); if ( date.isValid() ) setText( i++, KGlobal::locale()->formatDate( date, KLocale::ShortDate ) ); else setText( i++, "" ); } else setText( i++, (*it)->value( mAddressee ) ); } } void ContactListViewItem::setHasIM( bool hasIM ) { mHasIM = hasIM; } /////////////////////////////// // ContactListView ContactListView::ContactListView(KAddressBookTableView *view, KABC::AddressBook* /* doc */, QWidget *parent, const char *name ) : K3ListView( parent ), pabWidget( view ), oldColumn( 0 ) { setObjectName(name); mABackground = true; mSingleLine = false; mToolTips = true; mShowIM = true; mAlternateColor = KColorScheme( QPalette::Active, KColorScheme::View ).background( KColorScheme::AlternateBackground ).color(); setAlternateBackgroundEnabled(mABackground); setAcceptDrops( true ); viewport()->setAcceptDrops( true ); setAllColumnsShowFocus( true ); setShowSortIndicator(true); setSelectionModeExt( K3ListView::Extended ); setDropVisualizer(false); connect(this, SIGNAL(dropped(QDropEvent*)), this, SLOT(itemDropped(QDropEvent*))); } bool ContactListView::event( QEvent *e ) { if( e->type() != QEvent::ToolTip ) return K3ListView::event( e ); if ( !tooltips() ) return true; QHelpEvent * he = static_cast< QHelpEvent * >( e ); QPoint pnt = viewport()->mapFromGlobal( mapToGlobal( he->pos() ) ); Q3ListViewItem * item = itemAt ( pnt ); if ( item ) { ContactListViewItem *plvi = static_cast<ContactListViewItem *>( item ); QString s; //kDebug(5720) <<"Tip rec:" << r.x() <<"," << r.y() <<"," << r.width() // << "," << r.height(); KABC::Addressee a = plvi->addressee(); if (a.isEmpty()) return true; s += i18nc("label: value", "%1: %2", a.formattedNameLabel(), a.formattedName()); s += '\n'; s += i18nc("label: value", "%1: %2", a.organizationLabel(), a.organization()); QString notes = a.note().trimmed(); if ( !notes.isEmpty() ) { notes += '\n'; s += '\n' + i18nc("label: value", "%1: \n", a.noteLabel()); QFontMetrics fm( font() ); // Begin word wrap code based on QMultiLineEdit code int i = 0; bool doBreak = false; int linew = 0; int lastSpace = -1; int a = 0; int lastw = 0; while ( i < int(notes.length()) ) { doBreak = false; if ( notes[i] != '\n' ) linew += fm.width( notes[i] ); if ( lastSpace >= a && notes[i] != '\n' ) if (linew >= parentWidget()->width()) { doBreak = true; if ( lastSpace > a ) { i = lastSpace; linew = lastw; } else i = qMax( a, i-1 ); } if ( notes[i] == '\n' || doBreak ) { s += notes.mid( a, i - a + (doBreak?1:0) ) +'\n'; a = i + 1; lastSpace = a; linew = 0; } if ( notes[i].isSpace() ) { lastSpace = i; lastw = linew; } if ( lastSpace <= a ) { lastw = linew; } ++i; } } if ( s.isEmpty() ) QToolTip::hideText(); else QToolTip::showText( he->globalPos(), s ); } return true; } void ContactListView::paintEmptyArea( QPainter * p, const QRect & rect ) { QBrush b = palette().brush(QPalette::Active, QPalette::Base); // Get the brush, which will have the background pixmap if there is one. if (!b.texture().isNull()) { p->drawTiledPixmap( rect.left(), rect.top(), rect.width(), rect.height(), b.texture(), rect.left() + contentsX(), rect.top() + contentsY() ); } else { // Do a normal paint K3ListView::paintEmptyArea(p, rect); } } void ContactListView::contentsMousePressEvent(QMouseEvent* e) { presspos = e->pos(); K3ListView::contentsMousePressEvent(e); } // To initiate a drag operation void ContactListView::contentsMouseMoveEvent( QMouseEvent *e ) { if ((e->buttons() & Qt::LeftButton) && (e->pos() - presspos).manhattanLength() > 4 ) { emit startAddresseeDrag(); } else K3ListView::contentsMouseMoveEvent( e ); } bool ContactListView::acceptDrag(QDropEvent *e) const { return e->mimeData()->hasText(); } void ContactListView::itemDropped(QDropEvent *e) { contentsDropEvent(e); } void ContactListView::contentsDropEvent( QDropEvent *e ) { emit addresseeDropped(e); } void ContactListView::setAlternateBackgroundEnabled(bool enabled) { mABackground = enabled; if (mABackground) { setAlternateBackground(mAlternateColor); } else { setAlternateBackground(QColor()); } } void ContactListView::setBackgroundPixmap(const QString &filename) { if (filename.isEmpty()) { setPalette( QPalette() ); } else { QPalette palette; palette.setBrush( backgroundRole(), QBrush(QPixmap(filename) )); setPalette( palette ); } } void ContactListView::setShowIM( bool enabled ) { mShowIM = enabled; } bool ContactListView::showIM() { return mShowIM; } void ContactListView::setIMColumn( int column ) { mInstantMsgColumn = column; } int ContactListView::imColumn() { return mInstantMsgColumn; } #include "contactlistview.moc" <|endoftext|>
<commit_before>//============================================================================== // CellML annotation view details widget //============================================================================== #include "cellmlannotationviewdetailswidget.h" #include "treeview.h" //============================================================================== #include "ui_cellmlannotationviewdetailswidget.h" //============================================================================== #include <QFormLayout> #include <QLabel> #include <QLineEdit> #include <QScrollBar> //============================================================================== namespace OpenCOR { namespace CellMLAnnotationView { //============================================================================== CellmlAnnotationViewDetailsWidget::CellmlAnnotationViewDetailsWidget(QWidget *pParent) : CellmlAnnotationViewDetailsWidget::CellmlAnnotationViewDetailsWidget(QWidget *pParent, CellMLSupport::CellmlFile *pCellmlFile) : QScrollArea(pParent), Core::CommonWidget(pParent), mGui(new Ui::CellmlAnnotationViewDetailsWidget), mCellmlFile(pCellmlFile), mCellmlItems(CellmlItems()), mRdfTriples(CellMLSupport::CellmlFileRdfTriples()), mCellmlWidget(0), mCellmlFormLayout(0), mCellmlCmetaIdValue(0), mMetadataWidget(0), mMetadataFormLayout(0), mMetadataTreeView(0), mMetadataDataModel(0) { // Set up the GUI mGui->setupUi(this); } //============================================================================== CellmlAnnotationViewDetailsWidget::~CellmlAnnotationViewDetailsWidget() { // Delete the GUI delete mGui; } //============================================================================== void CellmlAnnotationViewDetailsWidget::retranslateUi() { // Retranslate our GUI mGui->retranslateUi(this); // Update the GUI (since some widgets get reinitialised as a result of the // retranslation) delete takeWidget(); // This will force the GUI to be recreated from // scratch and everything to be retranslated updateGui(mCellmlItems, mRdfTriples); } //============================================================================== CellmlAnnotationViewDetailsWidget::CellmlItem CellmlAnnotationViewDetailsWidget::cellmlItem(const Type &pType, CellMLSupport::CellmlFileElement *pElement, const QString &pName) { // Return a formatted CellmlItem 'object' CellmlItem res; res.type = pType; res.element = pElement; res.name = pName; return res; } //============================================================================== void CellmlAnnotationViewDetailsWidget::updateGui(const CellmlItems &pCellmlItems, const CellMLSupport::CellmlFileRdfTriples &pRdfTriples) { // Hide ourselves (since we may potentially update ourselves quite a bit and // we want to avoid any flickering) // Note #1: one would normally use setUpdatesEnabled(), but it still results // in bad flickering on Mac OS X, so... // Note #2: it's surprising that setVisible() doesn't cause any flickering // on any of the platforms we are targetting, but let's not // complain... setVisible(false); // Keep track of the CellML items and metadata group name mCellmlItems = pCellmlItems; mRdfTriples = pRdfTriples; // Check whether we are dealing with some metadata or not if (pCellmlItems.count()) { // We are not dealing with some metadata, so enable the CellML side of // the GUI if (!widget() || (widget() != mCellmlWidget)) { mCellmlWidget = new QWidget(this); mCellmlFormLayout = new QFormLayout(mCellmlWidget); mCellmlWidget->setLayout(mCellmlFormLayout); setWidget(mCellmlWidget); } // Remove everything from our form layout for (int i = 0, iMax = mCellmlFormLayout->count(); i < iMax; ++i) { QLayoutItem *item = mCellmlFormLayout->takeAt(0); delete item->widget(); delete item; } mCellmlCmetaIdValue = 0; // Go through the different items which properties we want to add to the // GUI for (int i = 0, iLast = pCellmlItems.count()-1; i <= iLast; ++i) { CellmlItem cellmlItem = pCellmlItems.at(i); // Determine which widget should be shown/hidden bool showName = false; bool showXlinkHref = false; bool showUnitReference = false; bool showComponentReference = false; bool showUnit = false; bool showInitialValue = false; bool showPublicInterface = false; bool showPrivateInterface = false; bool showRelationship = false; bool showRelationshipNamespace = false; bool showComponent = false; bool showFirstComponent = false; bool showSecondComponent = false; bool showFirstVariable = false; bool showSecondVariable = false; switch (cellmlItem.type) { case Model: case Unit: case UnitElement: case Component: case Group: case Connection: showName = true; break; case Import: showXlinkHref = true; break; case ImportUnit: showName = true; showUnitReference = true; break; case ImportComponent: showName = true; showComponentReference = true; break; case Variable: showName = true; showUnit = true; showInitialValue = true; showPublicInterface = true; showPrivateInterface = true; break; case RelationshipReference: showRelationship = true; showRelationshipNamespace = true; break; case ComponentReference: showComponent = true; break; case ComponentMapping: showFirstComponent = true; showSecondComponent = true; break; case VariableMapping: showFirstVariable = true; showSecondVariable = true; break; }; // Add whatever we need // Note: as long as all of the widgets' parent is our scroll area's // widget, then they will get automatically deleted, so no need to // delete them in ~CellmlAnnotationViewDetailsWidget()... // Add a bold centered label as a header to let the user know what type // of item we are talking about QLabel *header = new QLabel(typeAsString(cellmlItem.type), mCellmlWidget); QFont headerFont = header->font(); headerFont.setBold(true); header->setAlignment(Qt::AlignCenter); header->setFont(headerFont); mCellmlFormLayout->addRow(header); // Show the item's cmeta:id, keeping in mind that we only want to // allow the editing of the cmeta:id of the very first item QString cmetaId = cellmlItem.element->cmetaId(); if (i == iLast) { // This is our 'main' current item, so we want to allow the user // to edit its cmeta:id mCellmlCmetaIdValue = new QLineEdit(cmetaId, mCellmlWidget); mCellmlFormLayout->addRow(new QLabel(tr("cmeta:id:"), mCellmlWidget), mCellmlCmetaIdValue); } else { // Not our 'main' current item, so just display its cmeta:id addRowToCellmlFormLayout(tr("cmeta:id:"), cmetaId.isEmpty()?"/":cmetaId); } // Show the item's remaining properties if (showName) { // Retrieve the name of the CellML element // Note: in the case of a group or a connection, there won't be a // name, so we use the item's name, hoping one was provided... QString name = ((cellmlItem.type == Group) || (cellmlItem.type == Connection))? cellmlItem.name.isEmpty()?"/":cellmlItem.name: static_cast<CellMLSupport::CellmlFileNamedElement *>(cellmlItem.element)->name(); addRowToCellmlFormLayout(tr("Name:"), name); } if (showXlinkHref) addRowToCellmlFormLayout(tr("xlink:href:"), static_cast<CellMLSupport::CellmlFileImport *>(cellmlItem.element)->xlinkHref()); if (showUnitReference) addRowToCellmlFormLayout(tr("Unit reference:"), static_cast<CellMLSupport::CellmlFileImportUnit *>(cellmlItem.element)->unitReference()); if (showComponentReference) addRowToCellmlFormLayout(tr("Component reference:"), static_cast<CellMLSupport::CellmlFileImportComponent *>(cellmlItem.element)->componentReference()); if (showUnit) addRowToCellmlFormLayout(tr("Unit:"), static_cast<CellMLSupport::CellmlFileVariable *>(cellmlItem.element)->unit()); if (showInitialValue) { QString initialValue = static_cast<CellMLSupport::CellmlFileVariable *>(cellmlItem.element)->initialValue(); addRowToCellmlFormLayout(tr("Initial value:"), initialValue.isEmpty()?"/":initialValue); } if (showPublicInterface) addRowToCellmlFormLayout(tr("Public interface:"), static_cast<CellMLSupport::CellmlFileVariable *>(cellmlItem.element)->publicInterfaceAsString()); if (showPrivateInterface) addRowToCellmlFormLayout(tr("Private interface:"), static_cast<CellMLSupport::CellmlFileVariable *>(cellmlItem.element)->privateInterfaceAsString()); if (showRelationship) addRowToCellmlFormLayout(tr("Relationship:"), static_cast<CellMLSupport::CellmlFileRelationshipReference *>(cellmlItem.element)->relationship()); if (showRelationshipNamespace) { QString relationshipNamespace = static_cast<CellMLSupport::CellmlFileRelationshipReference *>(cellmlItem.element)->relationshipNamespace(); addRowToCellmlFormLayout(tr("Relationship namespace:"), relationshipNamespace.isEmpty()?"/":relationshipNamespace); } if (showComponent) addRowToCellmlFormLayout(tr("Component:"), static_cast<CellMLSupport::CellmlFileComponentReference *>(cellmlItem.element)->component()); if (showFirstComponent) addRowToCellmlFormLayout(tr("First component:"), static_cast<CellMLSupport::CellmlFileMapComponents *>(cellmlItem.element)->firstComponent()); if (showSecondComponent) addRowToCellmlFormLayout(tr("Second component:"), static_cast<CellMLSupport::CellmlFileMapComponents *>(cellmlItem.element)->secondComponent()); if (showFirstVariable) addRowToCellmlFormLayout(tr("First variable:"), static_cast<CellMLSupport::CellmlFileMapVariablesItem *>(cellmlItem.element)->firstVariable()); if (showSecondVariable) addRowToCellmlFormLayout(tr("Second variable:"), static_cast<CellMLSupport::CellmlFileMapVariablesItem *>(cellmlItem.element)->secondVariable()); } } else { // We are dealing with some metadata, so enable the metadata ML side of // the GUI if (!widget() || (widget() != mMetadataWidget)) { mMetadataWidget = new QWidget(this); mMetadataFormLayout = new QVBoxLayout(mMetadataWidget); mMetadataFormLayout->setMargin(0); mMetadataWidget->setLayout(mMetadataFormLayout); mMetadataTreeView = new Core::TreeView(mMetadataWidget); mMetadataDataModel = new QStandardItemModel(mMetadataTreeView); mMetadataTreeView->setEditTriggers(QAbstractItemView::NoEditTriggers); mMetadataTreeView->setFrameShape(QFrame::NoFrame); mMetadataTreeView->setModel(mMetadataDataModel); mMetadataTreeView->setRootIsDecorated(false); mMetadataTreeView->setSelectionMode(QAbstractItemView::SingleSelection); mMetadataDataModel->setHorizontalHeaderLabels(QStringList() << tr("#") << tr("Subject") << tr("Predicate") << tr("Object")); mMetadataFormLayout->addWidget(mMetadataTreeView); setWidget(mMetadataWidget); } // Remove all previous triples from our tree view while (mMetadataDataModel->rowCount()) foreach (QStandardItem *item, mMetadataDataModel->takeRow(0)) delete item; // Add the 'new' triples to our tree view // Note: for the triple's subject, we try to remove the CellML file's // URI base, thus only leaving the equivalent of a CellML element // cmeta:id which will speak more to the user than a possible long // URI reference... QString uriBase = mCellmlFile->uriBase(); int rdfTripleCounter = 0; foreach (CellMLSupport::CellmlFileRdfTriple *rdfTriple, pRdfTriples) mMetadataDataModel->invisibleRootItem()->appendRow(QList<QStandardItem *>() << new QStandardItem(QString::number(++rdfTripleCounter)) << new QStandardItem(rdfTriple->subject()->asString().remove(QRegExp("^"+QRegExp::escape(uriBase)+"#?"))) << new QStandardItem(rdfTriple->predicate()->asString()) << new QStandardItem(rdfTriple->object()->asString())); // Make sure that all the columns have their contents fit mMetadataTreeView->resizeColumnToContents(0); mMetadataTreeView->resizeColumnToContents(1); mMetadataTreeView->resizeColumnToContents(2); mMetadataTreeView->resizeColumnToContents(3); } // Re-show ourselves setVisible(true); // Scroll down to the bottom of ourselves, just in case things don't fit // within the viewport // Note: for this, we need to be up-to-date, hence we make a call to // qApp->processEvents() and this can only be done when we are once // again visible... qApp->processEvents(); verticalScrollBar()->setValue(verticalScrollBar()->maximum()); // Give the focus to the cmeta:id value field // Note: indeed, to have the cmeta:id value field as a focus proxy widget // for CellmlAnnotationViewWidget isn't good enough to have it get the // focus after selecting a 'new' CellML element in // CellmlAnnotationViewWidget (while it's when we switch from one // CellML file to another), so... if ((widget() == mCellmlWidget) && mCellmlCmetaIdValue) mCellmlCmetaIdValue->setFocus(); } //============================================================================== void CellmlAnnotationViewDetailsWidget::updateGui(const CellmlItems &pCellmlItems) { // Call our generic updateGui() updateGui(pCellmlItems, CellMLSupport::CellmlFileRdfTriples()); } //============================================================================== void CellmlAnnotationViewDetailsWidget::updateGui(const CellMLSupport::CellmlFileRdfTriples &pRdfTriples) { // Call our generic updateGui() updateGui(CellmlItems(), pRdfTriples); } //============================================================================== void CellmlAnnotationViewDetailsWidget::addRowToCellmlFormLayout(const QString &pLabel, const QString &pValue) { // Add a row to our form layout mCellmlFormLayout->addRow(new QLabel(pLabel, mCellmlWidget), new QLabel(pValue, mCellmlWidget)); } //============================================================================== QString CellmlAnnotationViewDetailsWidget::typeAsString(const Type &pType) const { switch (pType) { case Import: return tr("Import"); case ImportUnit: return tr("Imported unit"); case ImportComponent: return tr("Imported component"); case Unit: return tr("Unit"); case UnitElement: return tr("Unit element"); case Component: return tr("Component"); case Variable: return tr("Variable"); case Group: return tr("Group"); case RelationshipReference: return tr("Relationshop reference"); case ComponentReference: return tr("Component reference"); case Connection: return tr("Connection"); case ComponentMapping: return tr("Component mapping"); case VariableMapping: return tr("Variable mapping"); default: // Model return tr("Model"); } } //============================================================================== QWidget * CellmlAnnotationViewDetailsWidget::focusProxyWidget() { // If anything, we want our cmeta:id value widget to be a focus proxy widget return (widget() == mCellmlWidget)?mCellmlCmetaIdValue:0; } //============================================================================== } // namespace CellMLAnnotationView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>TortoiseGit getting confused...<commit_after>//============================================================================== // CellML annotation view details widget //============================================================================== #include "cellmlannotationviewdetailswidget.h" #include "treeview.h" //============================================================================== #include "ui_cellmlannotationviewdetailswidget.h" //============================================================================== #include <QFormLayout> #include <QLabel> #include <QLineEdit> #include <QScrollBar> //============================================================================== namespace OpenCOR { namespace CellMLAnnotationView { //============================================================================== CellmlAnnotationViewDetailsWidget::CellmlAnnotationViewDetailsWidget(QWidget *pParent, CellMLSupport::CellmlFile *pCellmlFile) : QScrollArea(pParent), Core::CommonWidget(pParent), mGui(new Ui::CellmlAnnotationViewDetailsWidget), mCellmlFile(pCellmlFile), mCellmlItems(CellmlItems()), mRdfTriples(CellMLSupport::CellmlFileRdfTriples()), mCellmlWidget(0), mCellmlFormLayout(0), mCellmlCmetaIdValue(0), mMetadataWidget(0), mMetadataFormLayout(0), mMetadataTreeView(0), mMetadataDataModel(0) { // Set up the GUI mGui->setupUi(this); } //============================================================================== CellmlAnnotationViewDetailsWidget::~CellmlAnnotationViewDetailsWidget() { // Delete the GUI delete mGui; } //============================================================================== void CellmlAnnotationViewDetailsWidget::retranslateUi() { // Retranslate our GUI mGui->retranslateUi(this); // Update the GUI (since some widgets get reinitialised as a result of the // retranslation) delete takeWidget(); // This will force the GUI to be recreated from // scratch and everything to be retranslated updateGui(mCellmlItems, mRdfTriples); } //============================================================================== CellmlAnnotationViewDetailsWidget::CellmlItem CellmlAnnotationViewDetailsWidget::cellmlItem(const Type &pType, CellMLSupport::CellmlFileElement *pElement, const QString &pName) { // Return a formatted CellmlItem 'object' CellmlItem res; res.type = pType; res.element = pElement; res.name = pName; return res; } //============================================================================== void CellmlAnnotationViewDetailsWidget::updateGui(const CellmlItems &pCellmlItems, const CellMLSupport::CellmlFileRdfTriples &pRdfTriples) { // Hide ourselves (since we may potentially update ourselves quite a bit and // we want to avoid any flickering) // Note #1: one would normally use setUpdatesEnabled(), but it still results // in bad flickering on Mac OS X, so... // Note #2: it's surprising that setVisible() doesn't cause any flickering // on any of the platforms we are targetting, but let's not // complain... setVisible(false); // Keep track of the CellML items and metadata group name mCellmlItems = pCellmlItems; mRdfTriples = pRdfTriples; // Check whether we are dealing with some metadata or not if (pCellmlItems.count()) { // We are not dealing with some metadata, so enable the CellML side of // the GUI if (!widget() || (widget() != mCellmlWidget)) { mCellmlWidget = new QWidget(this); mCellmlFormLayout = new QFormLayout(mCellmlWidget); mCellmlWidget->setLayout(mCellmlFormLayout); setWidget(mCellmlWidget); } // Remove everything from our form layout for (int i = 0, iMax = mCellmlFormLayout->count(); i < iMax; ++i) { QLayoutItem *item = mCellmlFormLayout->takeAt(0); delete item->widget(); delete item; } mCellmlCmetaIdValue = 0; // Go through the different items which properties we want to add to the // GUI for (int i = 0, iLast = pCellmlItems.count()-1; i <= iLast; ++i) { CellmlItem cellmlItem = pCellmlItems.at(i); // Determine which widget should be shown/hidden bool showName = false; bool showXlinkHref = false; bool showUnitReference = false; bool showComponentReference = false; bool showUnit = false; bool showInitialValue = false; bool showPublicInterface = false; bool showPrivateInterface = false; bool showRelationship = false; bool showRelationshipNamespace = false; bool showComponent = false; bool showFirstComponent = false; bool showSecondComponent = false; bool showFirstVariable = false; bool showSecondVariable = false; switch (cellmlItem.type) { case Model: case Unit: case UnitElement: case Component: case Group: case Connection: showName = true; break; case Import: showXlinkHref = true; break; case ImportUnit: showName = true; showUnitReference = true; break; case ImportComponent: showName = true; showComponentReference = true; break; case Variable: showName = true; showUnit = true; showInitialValue = true; showPublicInterface = true; showPrivateInterface = true; break; case RelationshipReference: showRelationship = true; showRelationshipNamespace = true; break; case ComponentReference: showComponent = true; break; case ComponentMapping: showFirstComponent = true; showSecondComponent = true; break; case VariableMapping: showFirstVariable = true; showSecondVariable = true; break; }; // Add whatever we need // Note: as long as all of the widgets' parent is our scroll area's // widget, then they will get automatically deleted, so no need to // delete them in ~CellmlAnnotationViewDetailsWidget()... // Add a bold centered label as a header to let the user know what type // of item we are talking about QLabel *header = new QLabel(typeAsString(cellmlItem.type), mCellmlWidget); QFont headerFont = header->font(); headerFont.setBold(true); header->setAlignment(Qt::AlignCenter); header->setFont(headerFont); mCellmlFormLayout->addRow(header); // Show the item's cmeta:id, keeping in mind that we only want to // allow the editing of the cmeta:id of the very first item QString cmetaId = cellmlItem.element->cmetaId(); if (i == iLast) { // This is our 'main' current item, so we want to allow the user // to edit its cmeta:id mCellmlCmetaIdValue = new QLineEdit(cmetaId, mCellmlWidget); mCellmlFormLayout->addRow(new QLabel(tr("cmeta:id:"), mCellmlWidget), mCellmlCmetaIdValue); } else { // Not our 'main' current item, so just display its cmeta:id addRowToCellmlFormLayout(tr("cmeta:id:"), cmetaId.isEmpty()?"/":cmetaId); } // Show the item's remaining properties if (showName) { // Retrieve the name of the CellML element // Note: in the case of a group or a connection, there won't be a // name, so we use the item's name, hoping one was provided... QString name = ((cellmlItem.type == Group) || (cellmlItem.type == Connection))? cellmlItem.name.isEmpty()?"/":cellmlItem.name: static_cast<CellMLSupport::CellmlFileNamedElement *>(cellmlItem.element)->name(); addRowToCellmlFormLayout(tr("Name:"), name); } if (showXlinkHref) addRowToCellmlFormLayout(tr("xlink:href:"), static_cast<CellMLSupport::CellmlFileImport *>(cellmlItem.element)->xlinkHref()); if (showUnitReference) addRowToCellmlFormLayout(tr("Unit reference:"), static_cast<CellMLSupport::CellmlFileImportUnit *>(cellmlItem.element)->unitReference()); if (showComponentReference) addRowToCellmlFormLayout(tr("Component reference:"), static_cast<CellMLSupport::CellmlFileImportComponent *>(cellmlItem.element)->componentReference()); if (showUnit) addRowToCellmlFormLayout(tr("Unit:"), static_cast<CellMLSupport::CellmlFileVariable *>(cellmlItem.element)->unit()); if (showInitialValue) { QString initialValue = static_cast<CellMLSupport::CellmlFileVariable *>(cellmlItem.element)->initialValue(); addRowToCellmlFormLayout(tr("Initial value:"), initialValue.isEmpty()?"/":initialValue); } if (showPublicInterface) addRowToCellmlFormLayout(tr("Public interface:"), static_cast<CellMLSupport::CellmlFileVariable *>(cellmlItem.element)->publicInterfaceAsString()); if (showPrivateInterface) addRowToCellmlFormLayout(tr("Private interface:"), static_cast<CellMLSupport::CellmlFileVariable *>(cellmlItem.element)->privateInterfaceAsString()); if (showRelationship) addRowToCellmlFormLayout(tr("Relationship:"), static_cast<CellMLSupport::CellmlFileRelationshipReference *>(cellmlItem.element)->relationship()); if (showRelationshipNamespace) { QString relationshipNamespace = static_cast<CellMLSupport::CellmlFileRelationshipReference *>(cellmlItem.element)->relationshipNamespace(); addRowToCellmlFormLayout(tr("Relationship namespace:"), relationshipNamespace.isEmpty()?"/":relationshipNamespace); } if (showComponent) addRowToCellmlFormLayout(tr("Component:"), static_cast<CellMLSupport::CellmlFileComponentReference *>(cellmlItem.element)->component()); if (showFirstComponent) addRowToCellmlFormLayout(tr("First component:"), static_cast<CellMLSupport::CellmlFileMapComponents *>(cellmlItem.element)->firstComponent()); if (showSecondComponent) addRowToCellmlFormLayout(tr("Second component:"), static_cast<CellMLSupport::CellmlFileMapComponents *>(cellmlItem.element)->secondComponent()); if (showFirstVariable) addRowToCellmlFormLayout(tr("First variable:"), static_cast<CellMLSupport::CellmlFileMapVariablesItem *>(cellmlItem.element)->firstVariable()); if (showSecondVariable) addRowToCellmlFormLayout(tr("Second variable:"), static_cast<CellMLSupport::CellmlFileMapVariablesItem *>(cellmlItem.element)->secondVariable()); } } else { // We are dealing with some metadata, so enable the metadata ML side of // the GUI if (!widget() || (widget() != mMetadataWidget)) { mMetadataWidget = new QWidget(this); mMetadataFormLayout = new QVBoxLayout(mMetadataWidget); mMetadataFormLayout->setMargin(0); mMetadataWidget->setLayout(mMetadataFormLayout); mMetadataTreeView = new Core::TreeView(mMetadataWidget); mMetadataDataModel = new QStandardItemModel(mMetadataTreeView); mMetadataTreeView->setEditTriggers(QAbstractItemView::NoEditTriggers); mMetadataTreeView->setFrameShape(QFrame::NoFrame); mMetadataTreeView->setModel(mMetadataDataModel); mMetadataTreeView->setRootIsDecorated(false); mMetadataTreeView->setSelectionMode(QAbstractItemView::SingleSelection); mMetadataDataModel->setHorizontalHeaderLabels(QStringList() << tr("#") << tr("Subject") << tr("Predicate") << tr("Object")); mMetadataFormLayout->addWidget(mMetadataTreeView); setWidget(mMetadataWidget); } // Remove all previous triples from our tree view while (mMetadataDataModel->rowCount()) foreach (QStandardItem *item, mMetadataDataModel->takeRow(0)) delete item; // Add the 'new' triples to our tree view // Note: for the triple's subject, we try to remove the CellML file's // URI base, thus only leaving the equivalent of a CellML element // cmeta:id which will speak more to the user than a possible long // URI reference... QString uriBase = mCellmlFile->uriBase(); int rdfTripleCounter = 0; foreach (CellMLSupport::CellmlFileRdfTriple *rdfTriple, pRdfTriples) mMetadataDataModel->invisibleRootItem()->appendRow(QList<QStandardItem *>() << new QStandardItem(QString::number(++rdfTripleCounter)) << new QStandardItem(rdfTriple->subject()->asString().remove(QRegExp("^"+QRegExp::escape(uriBase)+"#?"))) << new QStandardItem(rdfTriple->predicate()->asString()) << new QStandardItem(rdfTriple->object()->asString())); // Make sure that all the columns have their contents fit mMetadataTreeView->resizeColumnToContents(0); mMetadataTreeView->resizeColumnToContents(1); mMetadataTreeView->resizeColumnToContents(2); mMetadataTreeView->resizeColumnToContents(3); } // Re-show ourselves setVisible(true); // Scroll down to the bottom of ourselves, just in case things don't fit // within the viewport // Note: for this, we need to be up-to-date, hence we make a call to // qApp->processEvents() and this can only be done when we are once // again visible... qApp->processEvents(); verticalScrollBar()->setValue(verticalScrollBar()->maximum()); // Give the focus to the cmeta:id value field // Note: indeed, to have the cmeta:id value field as a focus proxy widget // for CellmlAnnotationViewWidget isn't good enough to have it get the // focus after selecting a 'new' CellML element in // CellmlAnnotationViewWidget (while it's when we switch from one // CellML file to another), so... if ((widget() == mCellmlWidget) && mCellmlCmetaIdValue) mCellmlCmetaIdValue->setFocus(); } //============================================================================== void CellmlAnnotationViewDetailsWidget::updateGui(const CellmlItems &pCellmlItems) { // Call our generic updateGui() updateGui(pCellmlItems, CellMLSupport::CellmlFileRdfTriples()); } //============================================================================== void CellmlAnnotationViewDetailsWidget::updateGui(const CellMLSupport::CellmlFileRdfTriples &pRdfTriples) { // Call our generic updateGui() updateGui(CellmlItems(), pRdfTriples); } //============================================================================== void CellmlAnnotationViewDetailsWidget::addRowToCellmlFormLayout(const QString &pLabel, const QString &pValue) { // Add a row to our form layout mCellmlFormLayout->addRow(new QLabel(pLabel, mCellmlWidget), new QLabel(pValue, mCellmlWidget)); } //============================================================================== QString CellmlAnnotationViewDetailsWidget::typeAsString(const Type &pType) const { switch (pType) { case Import: return tr("Import"); case ImportUnit: return tr("Imported unit"); case ImportComponent: return tr("Imported component"); case Unit: return tr("Unit"); case UnitElement: return tr("Unit element"); case Component: return tr("Component"); case Variable: return tr("Variable"); case Group: return tr("Group"); case RelationshipReference: return tr("Relationshop reference"); case ComponentReference: return tr("Component reference"); case Connection: return tr("Connection"); case ComponentMapping: return tr("Component mapping"); case VariableMapping: return tr("Variable mapping"); default: // Model return tr("Model"); } } //============================================================================== QWidget * CellmlAnnotationViewDetailsWidget::focusProxyWidget() { // If anything, we want our cmeta:id value widget to be a focus proxy widget return (widget() == mCellmlWidget)?mCellmlCmetaIdValue:0; } //============================================================================== } // namespace CellMLAnnotationView } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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. ----------------------------------------------------------------------------- */ #include "OgreGLES2FrameBufferObject.h" #include "OgreGLES2HardwarePixelBuffer.h" #include "OgreGLES2FBORenderTexture.h" #include "OgreGLES2DepthBuffer.h" #include "OgreGLUtil.h" #include "OgreRoot.h" #include "OgreGLES2RenderSystem.h" #include "OgreGLES2Support.h" namespace Ogre { //----------------------------------------------------------------------------- GLES2FrameBufferObject::GLES2FrameBufferObject(GLES2FBOManager *manager, uint fsaa): mManager(manager), mNumSamples(fsaa) { GLES2Support* glSupport = getGLES2SupportRef(); // Generate framebuffer object OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mFB)); if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_DEBUG)) { OGRE_CHECK_GL_ERROR(glLabelObjectEXT(GL_BUFFER_OBJECT_EXT, mFB, 0, ("FBO #" + StringConverter::toString(mFB)).c_str())); } // Check multisampling if supported GLint maxSamples = 0; if(glSupport->hasMinGLVersion(3, 0)) { // Check samples supported OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mFB)); OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_SAMPLES_APPLE, &maxSamples)); OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 0)); } mNumSamples = std::min(mNumSamples, (GLsizei)maxSamples); // Will we need a second FBO to do multisampling? if (mNumSamples) { OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mMultisampleFB)); if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_DEBUG)) { OGRE_CHECK_GL_ERROR(glLabelObjectEXT(GL_BUFFER_OBJECT_EXT, mMultisampleFB, 0, ("MSAA FBO #" + StringConverter::toString(mMultisampleFB)).c_str())); } } else { mMultisampleFB = 0; } // Initialise state mDepth.buffer = 0; mStencil.buffer = 0; for(size_t x = 0; x < OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x) { mColour[x].buffer=0; } } GLES2FrameBufferObject::~GLES2FrameBufferObject() { mManager->releaseRenderBuffer(mDepth); mManager->releaseRenderBuffer(mStencil); mManager->releaseRenderBuffer(mMultisampleColourBuffer); // Delete framebuffer object OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mFB)); if (mMultisampleFB) OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mMultisampleFB)); } #if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN void GLES2FrameBufferObject::notifyOnContextLost() { mManager->releaseRenderBuffer(mDepth); mManager->releaseRenderBuffer(mStencil); mManager->releaseRenderBuffer(mMultisampleColourBuffer); OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mFB)); if (mMultisampleFB) OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mMultisampleFB)); } void GLES2FrameBufferObject::notifyOnContextReset(const GLES2SurfaceDesc &target) { // Generate framebuffer object OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mFB)); OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mFB)); // Bind target to surface 0 and initialise bindSurface(0, target); } #endif void GLES2FrameBufferObject::bindSurface(size_t attachment, const GLES2SurfaceDesc &target) { assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS); mColour[attachment] = target; // Re-initialise if(mColour[0].buffer) initialise(); } void GLES2FrameBufferObject::unbindSurface(size_t attachment) { assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS); mColour[attachment].buffer = 0; // Re-initialise if buffer 0 still bound if(mColour[0].buffer) initialise(); } void GLES2FrameBufferObject::initialise() { // Release depth and stencil, if they were bound mManager->releaseRenderBuffer(mDepth); mManager->releaseRenderBuffer(mStencil); mManager->releaseRenderBuffer(mMultisampleColourBuffer); // First buffer must be bound if(!mColour[0].buffer) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Attachment 0 must have surface attached", "GLES2FrameBufferObject::initialise"); } // If we're doing multisampling, then we need another FBO which contains a // renderbuffer which is set up to multisample, and we'll blit it to the final // FBO afterwards to perform the multisample resolve. In that case, the // mMultisampleFB is bound during rendering and is the one with a depth/stencil // Store basic stats uint32 width = mColour[0].buffer->getWidth(); uint32 height = mColour[0].buffer->getHeight(); GLuint format = mColour[0].buffer->getGLFormat(); ushort maxSupportedMRTs = Root::getSingleton().getRenderSystem()->getCapabilities()->getNumMultiRenderTargets(); // Bind simple buffer to add colour attachments OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mFB)); // Bind all attachment points to frame buffer for(unsigned int x = 0; x < maxSupportedMRTs; ++x) { if(mColour[x].buffer) { if(mColour[x].buffer->getWidth() != width || mColour[x].buffer->getHeight() != height) { StringStream ss; ss << "Attachment " << x << " has incompatible size "; ss << mColour[x].buffer->getWidth() << "x" << mColour[x].buffer->getHeight(); ss << ". It must be of the same as the size of surface 0, "; ss << width << "x" << height; ss << "."; OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLES2FrameBufferObject::initialise"); } if(mColour[x].buffer->getGLFormat() != format) { StringStream ss; ss << "Attachment " << x << " has incompatible format."; OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLES2FrameBufferObject::initialise"); } if(getFormat() == PF_DEPTH) mColour[x].buffer->bindToFramebuffer(GL_DEPTH_ATTACHMENT, mColour[x].zoffset); else mColour[x].buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0+x, mColour[x].zoffset); } else { // Detach OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, static_cast<GLenum>(GL_COLOR_ATTACHMENT0+x), GL_RENDERBUFFER, 0)); } } // Now deal with depth / stencil if (mMultisampleFB) { // Bind multisample buffer OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB)); // Create AA render buffer (colour) // note, this can be shared too because we blit it to the final FBO // right after the render is finished mMultisampleColourBuffer = mManager->requestRenderBuffer(format, width, height, mNumSamples); // Attach it, because we won't be attaching below and non-multisample has // actually been attached to other FBO mMultisampleColourBuffer.buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0, mMultisampleColourBuffer.zoffset); // depth & stencil will be dealt with below } // Depth buffer is not handled here anymore. // See GLES2FrameBufferObject::attachDepthBuffer() & RenderSystem::setDepthBufferFor() #if OGRE_NO_GLES3_SUPPORT == 0 GLenum bufs[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; GLsizei n=0; for(unsigned int x=0; x<maxSupportedMRTs; ++x) { // Fill attached colour buffers if(mColour[x].buffer) { if(getFormat() == PF_DEPTH) bufs[x] = GL_DEPTH_ATTACHMENT; else bufs[x] = GL_COLOR_ATTACHMENT0 + x; // Keep highest used buffer + 1 n = x+1; } else { bufs[x] = GL_NONE; } } // Drawbuffer extension supported, use it if(getFormat() != PF_DEPTH) OGRE_CHECK_GL_ERROR(glDrawBuffers(n, bufs)); if (mMultisampleFB) { // we need a read buffer because we'll be blitting to mFB OGRE_CHECK_GL_ERROR(glReadBuffer(bufs[0])); } else { // No read buffer, by default, if we want to read anyway we must not forget to set this. OGRE_CHECK_GL_ERROR(glReadBuffer(GL_NONE)); } #endif // Check status GLuint status; OGRE_CHECK_GL_ERROR(status = glCheckFramebufferStatus(GL_FRAMEBUFFER)); // Bind main buffer #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS // The screen buffer is 1 on iOS OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 1)); #else OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 0)); #endif switch(status) { case GL_FRAMEBUFFER_COMPLETE: // All is good break; case GL_FRAMEBUFFER_UNSUPPORTED: OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "All framebuffer formats with this texture internal format unsupported", "GLES2FrameBufferObject::initialise"); default: OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Framebuffer incomplete or other FBO status error", "GLES2FrameBufferObject::initialise"); } } void GLES2FrameBufferObject::bind() { // Bind it to FBO const GLuint fb = mMultisampleFB ? mMultisampleFB : mFB; OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, fb)); } void GLES2FrameBufferObject::swapBuffers() { if (mMultisampleFB) { #if OGRE_NO_GLES3_SUPPORT == 0 GLint oldfb = 0; OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldfb)); // Blit from multisample buffer to final buffer, triggers resolve uint32 width = mColour[0].buffer->getWidth(); uint32 height = mColour[0].buffer->getHeight(); OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_READ_FRAMEBUFFER, mMultisampleFB)); OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mFB)); OGRE_CHECK_GL_ERROR(glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST)); // Unbind OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, oldfb)); #endif } } void GLES2FrameBufferObject::attachDepthBuffer( DepthBuffer *depthBuffer ) { GLES2DepthBuffer *glDepthBuffer = static_cast<GLES2DepthBuffer*>(depthBuffer); OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB ? mMultisampleFB : mFB )); if( glDepthBuffer ) { GLES2RenderBuffer *depthBuf = glDepthBuffer->getDepthBuffer(); GLES2RenderBuffer *stencilBuf = glDepthBuffer->getStencilBuffer(); //Attach depth buffer, if it has one. if( depthBuf ) depthBuf->bindToFramebuffer( GL_DEPTH_ATTACHMENT, 0 ); //Attach stencil buffer, if it has one. if( stencilBuf ) stencilBuf->bindToFramebuffer( GL_STENCIL_ATTACHMENT, 0 ); } else { OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0)); OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0)); } } //----------------------------------------------------------------------------- void GLES2FrameBufferObject::detachDepthBuffer() { OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB ? mMultisampleFB : mFB )); OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0 )); OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0 )); } uint32 GLES2FrameBufferObject::getWidth() { assert(mColour[0].buffer); return mColour[0].buffer->getWidth(); } uint32 GLES2FrameBufferObject::getHeight() { assert(mColour[0].buffer); return mColour[0].buffer->getHeight(); } PixelFormat GLES2FrameBufferObject::getFormat() { assert(mColour[0].buffer); return mColour[0].buffer->getFormat(); } GLsizei GLES2FrameBufferObject::getFSAA() { return mNumSamples; } //----------------------------------------------------------------------------- } <commit_msg>GLES2: multi-sampled FBO requires GLES3 at compile time for now<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd 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. ----------------------------------------------------------------------------- */ #include "OgreGLES2FrameBufferObject.h" #include "OgreGLES2HardwarePixelBuffer.h" #include "OgreGLES2FBORenderTexture.h" #include "OgreGLES2DepthBuffer.h" #include "OgreGLUtil.h" #include "OgreRoot.h" #include "OgreGLES2RenderSystem.h" #include "OgreGLES2Support.h" namespace Ogre { //----------------------------------------------------------------------------- GLES2FrameBufferObject::GLES2FrameBufferObject(GLES2FBOManager *manager, uint fsaa): mManager(manager), mNumSamples(fsaa) { // Generate framebuffer object OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mFB)); if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_DEBUG)) { OGRE_CHECK_GL_ERROR(glLabelObjectEXT(GL_BUFFER_OBJECT_EXT, mFB, 0, ("FBO #" + StringConverter::toString(mFB)).c_str())); } // Check multisampling if supported GLint maxSamples = 0; if(!OGRE_NO_GLES3_SUPPORT) { // Check samples supported OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mFB)); OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_MAX_SAMPLES_APPLE, &maxSamples)); OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 0)); } mNumSamples = std::min(mNumSamples, (GLsizei)maxSamples); // Will we need a second FBO to do multisampling? if (mNumSamples) { OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mMultisampleFB)); if(Root::getSingleton().getRenderSystem()->getCapabilities()->hasCapability(RSC_DEBUG)) { OGRE_CHECK_GL_ERROR(glLabelObjectEXT(GL_BUFFER_OBJECT_EXT, mMultisampleFB, 0, ("MSAA FBO #" + StringConverter::toString(mMultisampleFB)).c_str())); } } else { mMultisampleFB = 0; } // Initialise state mDepth.buffer = 0; mStencil.buffer = 0; for(size_t x = 0; x < OGRE_MAX_MULTIPLE_RENDER_TARGETS; ++x) { mColour[x].buffer=0; } } GLES2FrameBufferObject::~GLES2FrameBufferObject() { mManager->releaseRenderBuffer(mDepth); mManager->releaseRenderBuffer(mStencil); mManager->releaseRenderBuffer(mMultisampleColourBuffer); // Delete framebuffer object OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mFB)); if (mMultisampleFB) OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mMultisampleFB)); } #if OGRE_PLATFORM == OGRE_PLATFORM_ANDROID || OGRE_PLATFORM == OGRE_PLATFORM_EMSCRIPTEN void GLES2FrameBufferObject::notifyOnContextLost() { mManager->releaseRenderBuffer(mDepth); mManager->releaseRenderBuffer(mStencil); mManager->releaseRenderBuffer(mMultisampleColourBuffer); OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mFB)); if (mMultisampleFB) OGRE_CHECK_GL_ERROR(glDeleteFramebuffers(1, &mMultisampleFB)); } void GLES2FrameBufferObject::notifyOnContextReset(const GLES2SurfaceDesc &target) { // Generate framebuffer object OGRE_CHECK_GL_ERROR(glGenFramebuffers(1, &mFB)); OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mFB)); // Bind target to surface 0 and initialise bindSurface(0, target); } #endif void GLES2FrameBufferObject::bindSurface(size_t attachment, const GLES2SurfaceDesc &target) { assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS); mColour[attachment] = target; // Re-initialise if(mColour[0].buffer) initialise(); } void GLES2FrameBufferObject::unbindSurface(size_t attachment) { assert(attachment < OGRE_MAX_MULTIPLE_RENDER_TARGETS); mColour[attachment].buffer = 0; // Re-initialise if buffer 0 still bound if(mColour[0].buffer) initialise(); } void GLES2FrameBufferObject::initialise() { // Release depth and stencil, if they were bound mManager->releaseRenderBuffer(mDepth); mManager->releaseRenderBuffer(mStencil); mManager->releaseRenderBuffer(mMultisampleColourBuffer); // First buffer must be bound if(!mColour[0].buffer) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Attachment 0 must have surface attached", "GLES2FrameBufferObject::initialise"); } // If we're doing multisampling, then we need another FBO which contains a // renderbuffer which is set up to multisample, and we'll blit it to the final // FBO afterwards to perform the multisample resolve. In that case, the // mMultisampleFB is bound during rendering and is the one with a depth/stencil // Store basic stats uint32 width = mColour[0].buffer->getWidth(); uint32 height = mColour[0].buffer->getHeight(); GLuint format = mColour[0].buffer->getGLFormat(); ushort maxSupportedMRTs = Root::getSingleton().getRenderSystem()->getCapabilities()->getNumMultiRenderTargets(); // Bind simple buffer to add colour attachments OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mFB)); // Bind all attachment points to frame buffer for(unsigned int x = 0; x < maxSupportedMRTs; ++x) { if(mColour[x].buffer) { if(mColour[x].buffer->getWidth() != width || mColour[x].buffer->getHeight() != height) { StringStream ss; ss << "Attachment " << x << " has incompatible size "; ss << mColour[x].buffer->getWidth() << "x" << mColour[x].buffer->getHeight(); ss << ". It must be of the same as the size of surface 0, "; ss << width << "x" << height; ss << "."; OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLES2FrameBufferObject::initialise"); } if(mColour[x].buffer->getGLFormat() != format) { StringStream ss; ss << "Attachment " << x << " has incompatible format."; OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, ss.str(), "GLES2FrameBufferObject::initialise"); } if(getFormat() == PF_DEPTH) mColour[x].buffer->bindToFramebuffer(GL_DEPTH_ATTACHMENT, mColour[x].zoffset); else mColour[x].buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0+x, mColour[x].zoffset); } else { // Detach OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer(GL_FRAMEBUFFER, static_cast<GLenum>(GL_COLOR_ATTACHMENT0+x), GL_RENDERBUFFER, 0)); } } // Now deal with depth / stencil if (mMultisampleFB) { // Bind multisample buffer OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB)); // Create AA render buffer (colour) // note, this can be shared too because we blit it to the final FBO // right after the render is finished mMultisampleColourBuffer = mManager->requestRenderBuffer(format, width, height, mNumSamples); // Attach it, because we won't be attaching below and non-multisample has // actually been attached to other FBO mMultisampleColourBuffer.buffer->bindToFramebuffer(GL_COLOR_ATTACHMENT0, mMultisampleColourBuffer.zoffset); // depth & stencil will be dealt with below } // Depth buffer is not handled here anymore. // See GLES2FrameBufferObject::attachDepthBuffer() & RenderSystem::setDepthBufferFor() #if OGRE_NO_GLES3_SUPPORT == 0 GLenum bufs[OGRE_MAX_MULTIPLE_RENDER_TARGETS]; GLsizei n=0; for(unsigned int x=0; x<maxSupportedMRTs; ++x) { // Fill attached colour buffers if(mColour[x].buffer) { if(getFormat() == PF_DEPTH) bufs[x] = GL_DEPTH_ATTACHMENT; else bufs[x] = GL_COLOR_ATTACHMENT0 + x; // Keep highest used buffer + 1 n = x+1; } else { bufs[x] = GL_NONE; } } // Drawbuffer extension supported, use it if(getFormat() != PF_DEPTH) OGRE_CHECK_GL_ERROR(glDrawBuffers(n, bufs)); if (mMultisampleFB) { // we need a read buffer because we'll be blitting to mFB OGRE_CHECK_GL_ERROR(glReadBuffer(bufs[0])); } else { // No read buffer, by default, if we want to read anyway we must not forget to set this. OGRE_CHECK_GL_ERROR(glReadBuffer(GL_NONE)); } #endif // Check status GLuint status; OGRE_CHECK_GL_ERROR(status = glCheckFramebufferStatus(GL_FRAMEBUFFER)); // Bind main buffer #if OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS // The screen buffer is 1 on iOS OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 1)); #else OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, 0)); #endif switch(status) { case GL_FRAMEBUFFER_COMPLETE: // All is good break; case GL_FRAMEBUFFER_UNSUPPORTED: OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "All framebuffer formats with this texture internal format unsupported", "GLES2FrameBufferObject::initialise"); default: OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Framebuffer incomplete or other FBO status error", "GLES2FrameBufferObject::initialise"); } } void GLES2FrameBufferObject::bind() { // Bind it to FBO const GLuint fb = mMultisampleFB ? mMultisampleFB : mFB; OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, fb)); } void GLES2FrameBufferObject::swapBuffers() { if (mMultisampleFB) { #if OGRE_NO_GLES3_SUPPORT == 0 GLint oldfb = 0; OGRE_CHECK_GL_ERROR(glGetIntegerv(GL_FRAMEBUFFER_BINDING, &oldfb)); // Blit from multisample buffer to final buffer, triggers resolve uint32 width = mColour[0].buffer->getWidth(); uint32 height = mColour[0].buffer->getHeight(); OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_READ_FRAMEBUFFER, mMultisampleFB)); OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, mFB)); OGRE_CHECK_GL_ERROR(glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST)); // Unbind OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, oldfb)); #endif } } void GLES2FrameBufferObject::attachDepthBuffer( DepthBuffer *depthBuffer ) { GLES2DepthBuffer *glDepthBuffer = static_cast<GLES2DepthBuffer*>(depthBuffer); OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB ? mMultisampleFB : mFB )); if( glDepthBuffer ) { GLES2RenderBuffer *depthBuf = glDepthBuffer->getDepthBuffer(); GLES2RenderBuffer *stencilBuf = glDepthBuffer->getStencilBuffer(); //Attach depth buffer, if it has one. if( depthBuf ) depthBuf->bindToFramebuffer( GL_DEPTH_ATTACHMENT, 0 ); //Attach stencil buffer, if it has one. if( stencilBuf ) stencilBuf->bindToFramebuffer( GL_STENCIL_ATTACHMENT, 0 ); } else { OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0)); OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0)); } } //----------------------------------------------------------------------------- void GLES2FrameBufferObject::detachDepthBuffer() { OGRE_CHECK_GL_ERROR(glBindFramebuffer(GL_FRAMEBUFFER, mMultisampleFB ? mMultisampleFB : mFB )); OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, 0 )); OGRE_CHECK_GL_ERROR(glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, 0 )); } uint32 GLES2FrameBufferObject::getWidth() { assert(mColour[0].buffer); return mColour[0].buffer->getWidth(); } uint32 GLES2FrameBufferObject::getHeight() { assert(mColour[0].buffer); return mColour[0].buffer->getHeight(); } PixelFormat GLES2FrameBufferObject::getFormat() { assert(mColour[0].buffer); return mColour[0].buffer->getFormat(); } GLsizei GLES2FrameBufferObject::getFSAA() { return mNumSamples; } //----------------------------------------------------------------------------- } <|endoftext|>
<commit_before>//============================================================================== // CellML Model Repository window //============================================================================== #include "cellmlmodelrepositorywindow.h" #include "cellmlmodelrepositorywidget.h" //============================================================================== #include "ui_cellmlmodelrepositorywindow.h" //============================================================================== #include <QClipboard> #include <QMenu> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> //============================================================================== #include <QJsonParser> //============================================================================== namespace OpenCOR { namespace CellMLModelRepository { //============================================================================== CellmlModelRepositoryWindow::CellmlModelRepositoryWindow(QWidget *pParent) : OrganisationWidget(pParent), mUi(new Ui::CellmlModelRepositoryWindow) { // Set up the UI mUi->setupUi(this); // Create and add the CellML Model Repository widget mCellmlModelRepositoryWidget = new CellmlModelRepositoryWidget("CellmlModelRepositoryWidget", this); mUi->dockWidgetContents->layout()->addWidget(mCellmlModelRepositoryWidget); // We want our own context menu for the help widget (indeed, we don't want // the default one which has the reload menu item and not the other actions // that we have in our toolbar, so...) mCellmlModelRepositoryWidget->setContextMenuPolicy(Qt::CustomContextMenu); connect(mCellmlModelRepositoryWidget, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(customContextMenu(const QPoint &))); // Retrieve the list of models in the CellML Model Repository as JSON code // from http://models.cellml.org/workspace/rest/contents.json mNetworkAccessManager = new QNetworkAccessManager(this); // Make sure that we get told when the download of our Internet file is // complete connect(mNetworkAccessManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(finished(QNetworkReply *)) ); // Get the list of CellML models on_refreshButton_clicked(); } //============================================================================== CellmlModelRepositoryWindow::~CellmlModelRepositoryWindow() { // Delete the UI delete mUi; } //============================================================================== void CellmlModelRepositoryWindow::retranslateUi() { // Retranslate the whole window mUi->retranslateUi(this); // Retranslate our list of models outputModelList(mModelList); } //============================================================================== void CellmlModelRepositoryWindow::outputModelList(const QStringList &pModelList) { // Output a given list of models mModelList = pModelList; QString contents = ""; const QString leadingSpaces = " "; if (mModelList.count()) { // We have models to list, so... if (mModelList.count() == 1) contents = tr("<strong>1</strong> CellML model was found:")+"\n"; else contents = tr("<strong>%1</strong> CellML models were found:").arg(mModelList.count())+"\n"; contents += leadingSpaces+"<ul>\n"; foreach (const QString &model, mModelList) contents += leadingSpaces+"<li><a href=\""+mModelUrls.at(mModelNames.indexOf(model))+"\">"+model+"</a></li>\n"; contents += leadingSpaces+"</ul>"; } else if (mModelNames.empty()) { if (mErrorMsg.size()) { // Something went wrong while trying to retrieve the list of models, // so... QString errorMsg = mErrorMsg.left(1).toLower()+mErrorMsg.right(mErrorMsg.size()-1); QString dots = (errorMsg.at(errorMsg.size()-1) == '.')?"..":"..."; contents = leadingSpaces+"Error: "+errorMsg+dots; } else { // The list is still being loaded, so... contents = leadingSpaces+tr("Please wait while the list of CellML models is being loaded..."); } } else { // No model could be found, so... contents = leadingSpaces+tr("No CellML model matches your criteria"); } // Output the list matching the search criteria, or a message telling the // user what went wrong, if anything mCellmlModelRepositoryWidget->output(contents); } //============================================================================== void CellmlModelRepositoryWindow::on_nameValue_textChanged(const QString &text) { // Generate a Web page that contains all the models which match our search // criteria outputModelList(mModelNames.filter(QRegExp(text, Qt::CaseInsensitive, QRegExp::RegExp2))); } //============================================================================== void CellmlModelRepositoryWindow::on_actionCopy_triggered() { // Copy the current slection to the clipboard QApplication::clipboard()->setText(mCellmlModelRepositoryWidget->selectedText()); } //============================================================================== void CellmlModelRepositoryWindow::on_refreshButton_clicked() { // Output the message telling the user that the list is being downloaded // Note: to clear mModelNames ensures that we get the correct message from // outputModelList... mModelNames.clear(); outputModelList(QStringList()); // Disable the GUI side, so that the user doesn't get confused and ask to // refresh over and over again while he should just be patient setEnabled(false); // Get the list of CellML models mNetworkAccessManager->get(QNetworkRequest(QUrl("http://models.cellml.org/workspace/rest/contents.json"))); } //============================================================================== void CellmlModelRepositoryWindow::finished(QNetworkReply *pNetworkReply) { // Clear some properties mModelNames.clear(); mModelUrls.clear(); mErrorMsg.clear(); // Output the list of models, should we have retrieved it without any // problem if (pNetworkReply->error() == QNetworkReply::NoError) { // Parse the JSON code QJson::Parser jsonParser; bool parsingOk; QVariantMap res = jsonParser.parse (pNetworkReply->readAll(), &parsingOk).toMap(); if (parsingOk) { // Retrieve the name of the keys QStringList keys; foreach (const QVariant &keyVariant, res["keys"].toList()) keys << keyVariant.toString(); // Retrieve the list of models itself foreach(const QVariant &modelVariant, res["values"].toList()) { QVariantList modelDetailsVariant = modelVariant.toList(); mModelNames << modelDetailsVariant.at(0).toString(); mModelUrls << modelDetailsVariant.at(1).toString(); } } } else { // Something went wrong, so... mErrorMsg = pNetworkReply->errorString(); } // Initialise the output using whatever search criteria is present on_nameValue_textChanged(mUi->nameValue->text()); // Re-enable the GUI side setEnabled(true); // Give, within the window, the focus to the nameValue widget, but then set // the focus to whoever had it before, if needed QWidget *focusedWidget = QApplication::focusWidget(); mUi->nameValue->setFocus(); if (focusedWidget && (QApplication::focusWidget()->parentWidget() != focusedWidget->parentWidget())) focusedWidget->setFocus(); } //============================================================================== void CellmlModelRepositoryWindow::customContextMenu(const QPoint &) const { // Create a custom context menu for our CellML Models Repository widget QMenu menu; menu.addAction(mUi->actionCopy); menu.exec(QCursor::pos()); } //============================================================================== } // namespace CellMLModelRepository } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <commit_msg>Fixed, once and for all (still need to check on Mac OS X), the focusing issue upon starting OpenCOR. The focus was always on the CellMLModelRepository plugin.<commit_after>//============================================================================== // CellML Model Repository window //============================================================================== #include "cellmlmodelrepositorywindow.h" #include "cellmlmodelrepositorywidget.h" //============================================================================== #include "ui_cellmlmodelrepositorywindow.h" //============================================================================== #include <QClipboard> #include <QMenu> #include <QNetworkAccessManager> #include <QNetworkReply> #include <QNetworkRequest> //============================================================================== #include <QJsonParser> //============================================================================== namespace OpenCOR { namespace CellMLModelRepository { //============================================================================== CellmlModelRepositoryWindow::CellmlModelRepositoryWindow(QWidget *pParent) : OrganisationWidget(pParent), mUi(new Ui::CellmlModelRepositoryWindow) { // Set up the UI mUi->setupUi(this); // Create and add the CellML Model Repository widget mCellmlModelRepositoryWidget = new CellmlModelRepositoryWidget("CellmlModelRepositoryWidget", this); mUi->dockWidgetContents->layout()->addWidget(mCellmlModelRepositoryWidget); // We want our own context menu for the help widget (indeed, we don't want // the default one which has the reload menu item and not the other actions // that we have in our toolbar, so...) mCellmlModelRepositoryWidget->setContextMenuPolicy(Qt::CustomContextMenu); connect(mCellmlModelRepositoryWidget, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(customContextMenu(const QPoint &))); // Retrieve the list of models in the CellML Model Repository as JSON code // from http://models.cellml.org/workspace/rest/contents.json mNetworkAccessManager = new QNetworkAccessManager(this); // Make sure that we get told when the download of our Internet file is // complete connect(mNetworkAccessManager, SIGNAL(finished(QNetworkReply *)), this, SLOT(finished(QNetworkReply *)) ); // Get the list of CellML models on_refreshButton_clicked(); } //============================================================================== CellmlModelRepositoryWindow::~CellmlModelRepositoryWindow() { // Delete the UI delete mUi; } //============================================================================== void CellmlModelRepositoryWindow::retranslateUi() { // Retranslate the whole window mUi->retranslateUi(this); // Retranslate our list of models outputModelList(mModelList); } //============================================================================== void CellmlModelRepositoryWindow::outputModelList(const QStringList &pModelList) { // Output a given list of models mModelList = pModelList; QString contents = ""; const QString leadingSpaces = " "; if (mModelList.count()) { // We have models to list, so... if (mModelList.count() == 1) contents = tr("<strong>1</strong> CellML model was found:")+"\n"; else contents = tr("<strong>%1</strong> CellML models were found:").arg(mModelList.count())+"\n"; contents += leadingSpaces+"<ul>\n"; foreach (const QString &model, mModelList) contents += leadingSpaces+"<li><a href=\""+mModelUrls.at(mModelNames.indexOf(model))+"\">"+model+"</a></li>\n"; contents += leadingSpaces+"</ul>"; } else if (mModelNames.empty()) { if (mErrorMsg.size()) { // Something went wrong while trying to retrieve the list of models, // so... QString errorMsg = mErrorMsg.left(1).toLower()+mErrorMsg.right(mErrorMsg.size()-1); QString dots = (errorMsg.at(errorMsg.size()-1) == '.')?"..":"..."; contents = leadingSpaces+"Error: "+errorMsg+dots; } else { // The list is still being loaded, so... contents = leadingSpaces+tr("Please wait while the list of CellML models is being loaded..."); } } else { // No model could be found, so... contents = leadingSpaces+tr("No CellML model matches your criteria"); } // Output the list matching the search criteria, or a message telling the // user what went wrong, if anything mCellmlModelRepositoryWidget->output(contents); } //============================================================================== void CellmlModelRepositoryWindow::on_nameValue_textChanged(const QString &text) { // Generate a Web page that contains all the models which match our search // criteria outputModelList(mModelNames.filter(QRegExp(text, Qt::CaseInsensitive, QRegExp::RegExp2))); } //============================================================================== void CellmlModelRepositoryWindow::on_actionCopy_triggered() { // Copy the current slection to the clipboard QApplication::clipboard()->setText(mCellmlModelRepositoryWidget->selectedText()); } //============================================================================== void CellmlModelRepositoryWindow::on_refreshButton_clicked() { // Output the message telling the user that the list is being downloaded // Note: to clear mModelNames ensures that we get the correct message from // outputModelList... mModelNames.clear(); outputModelList(QStringList()); // Disable the GUI side, so that the user doesn't get confused and ask to // refresh over and over again while he should just be patient setEnabled(false); // Get the list of CellML models mNetworkAccessManager->get(QNetworkRequest(QUrl("http://models.cellml.org/workspace/rest/contents.json"))); } //============================================================================== void CellmlModelRepositoryWindow::finished(QNetworkReply *pNetworkReply) { // Clear some properties mModelNames.clear(); mModelUrls.clear(); mErrorMsg.clear(); // Output the list of models, should we have retrieved it without any // problem if (pNetworkReply->error() == QNetworkReply::NoError) { // Parse the JSON code QJson::Parser jsonParser; bool parsingOk; QVariantMap res = jsonParser.parse (pNetworkReply->readAll(), &parsingOk).toMap(); if (parsingOk) { // Retrieve the name of the keys QStringList keys; foreach (const QVariant &keyVariant, res["keys"].toList()) keys << keyVariant.toString(); // Retrieve the list of models itself foreach(const QVariant &modelVariant, res["values"].toList()) { QVariantList modelDetailsVariant = modelVariant.toList(); mModelNames << modelDetailsVariant.at(0).toString(); mModelUrls << modelDetailsVariant.at(1).toString(); } } } else { // Something went wrong, so... mErrorMsg = pNetworkReply->errorString(); } // Initialise the output using whatever search criteria is present on_nameValue_textChanged(mUi->nameValue->text()); // Re-enable the GUI side setEnabled(true); // Give, within the window, the focus to the nameValue widget, but then set // the focus to whoever had it before, if needed QWidget *focusedWidget = ((QWidget *) parent())->focusWidget(); // Note: the parent of this window is OpenCOR's main window, so that allows // us to 'safely' retrieve OpenCOR's currently focused widget... mUi->nameValue->setFocus(); if (focusedWidget && (parentWidget() != focusedWidget->parentWidget())) focusedWidget->setFocus(); } //============================================================================== void CellmlModelRepositoryWindow::customContextMenu(const QPoint &) const { // Create a custom context menu for our CellML Models Repository widget QMenu menu; menu.addAction(mUi->actionCopy); menu.exec(QCursor::pos()); } //============================================================================== } // namespace CellMLModelRepository } // namespace OpenCOR //============================================================================== // End of file //============================================================================== <|endoftext|>
<commit_before>#include <unistd.h> #include <errno.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <vector> #include <queue> #include <poll.h> #include <fcntl.h> #include <sys/mman.h> using namespace std; #include "DRAMRequest.h" #include "dramDefs.h" #include "channel.h" Channel *cmdChannel = NULL; Channel *respChannel = NULL; int sendResp(dramCmd *cmd) { dramCmd resp; resp.id = cmd->id; resp.cmd = cmd->cmd; resp.size = cmd->size; switch (cmd->cmd) { case DRAM_READY: resp.size = 0; break; default: EPRINTF("[SIM] Command %d not supported!\n", cmd->cmd); exit(-1); } respChannel->send(&resp); return cmd->id; } int numCycles = 0; std::queue<DRAMRequest*> dramRequestQ; void recvDRAMRequest( uint64_t addr, uint64_t tag, bool isWr, uint32_t *wdata ) { DRAMRequest *req = new DRAMRequest(addr, tag, isWr, wdata); dramRequestQ.push(req); req->print(); } void checkDRAMResponse() { if (dramRequestQ.size() > 0) { DRAMRequest *req = dramRequestQ.front(); req->elapsed++; if(req->elapsed == req->delay) { dramRequestQ.pop(); uint32_t rdata[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; if (req->isWr) { // Write request: Update 1 burst-length bytes at *addr uint32_t *waddr = (uint32_t*) req->addr; for (int i=0; i<16; i++) { waddr[i] = req->wdata[i]; } } else { // Read request: Read burst-length bytes at *addr uint32_t *raddr = (uint32_t*) req->addr; for (int i=0; i<16; i++) { rdata[i] = raddr[i]; } } } } } // Function is called every clock cycle int tick() { bool exitTick = false; int finishSim = 0; numCycles++; // Check for DRAM response and send it to design checkDRAMResponse(); // Handle new incoming operations while (!exitTick) { dramCmd *cmd = (dramCmd*) cmdChannel->recv(); dramCmd readResp; switch (cmd->cmd) { case DRAM_MALLOC: { size_t size = *(size_t*)cmd->data; int fd = open("/dev/zero", O_RDWR); void *ptr = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0); close(fd); dramCmd resp; resp.id = cmd->id; resp.cmd = cmd->cmd; *(uint64_t*)resp.data = (uint64_t)ptr; resp.size = sizeof(size_t); EPRINTF("[SIM] MALLOC(%lu), returning %p\n", size, (void*)ptr); respChannel->send(&resp); break; } case DRAM_FREE: { void *ptr = (void*)(*(uint64_t*)cmd->data); ASSERT(ptr != NULL, "Attempting to call free on null pointer\n"); EPRINTF("[SIM] FREE(%p)\n", ptr); break; } case DRAM_MEMCPY_H2D: { uint64_t *data = (uint64_t*)cmd->data; void *dst = (void*)data[0]; size_t size = data[1]; EPRINTF("[SIM] Received memcpy request to %p, size %lu\n", (void*)dst, size); // Now to receive 'size' bytes from the cmd stream cmdChannel->recvFixedBytes(dst, size); // Send ack back indicating end of memcpy dramCmd resp; resp.id = cmd->id; resp.cmd = cmd->cmd; resp.size = 0; respChannel->send(&resp); break; } case DRAM_MEMCPY_D2H: { // Transfer 'size' bytes from src uint64_t *data = (uint64_t*)cmd->data; void *src = (void*)data[0]; size_t size = data[1]; // Now to receive 'size' bytes from the cmd stream respChannel->sendFixedBytes(src, size); break; } case DRAM_STEP: exitTick = true; break; case DRAM_FIN: finishSim = 1; exitTick = true; break; default: break; } } return finishSim; } void dramLoop() { while (!tick()); } // Called before simulation begins int main(int argc, char **argv) { EPRINTF("[SIM] DRAM process started!\n"); // 0. Create Channel structures cmdChannel = new Channel(DRAM_CMD_FD, -1, sizeof(dramCmd)); respChannel = new Channel(-1, DRAM_RESP_FD, sizeof(dramCmd)); // 1. Read command dramCmd *cmd = (dramCmd*) cmdChannel->recv(); // 2. Send response sendResp(cmd); // 3. Go into the DRAM loop dramLoop(); EPRINTF("[DRAM] Quitting DRAM simulator\n"); return 0; } <commit_msg>Minor update to starting print<commit_after>#include <unistd.h> #include <errno.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <vector> #include <queue> #include <poll.h> #include <fcntl.h> #include <sys/mman.h> using namespace std; #include "DRAMRequest.h" #include "dramDefs.h" #include "channel.h" Channel *cmdChannel = NULL; Channel *respChannel = NULL; int sendResp(dramCmd *cmd) { dramCmd resp; resp.id = cmd->id; resp.cmd = cmd->cmd; resp.size = cmd->size; switch (cmd->cmd) { case DRAM_READY: resp.size = 0; break; default: EPRINTF("[SIM] Command %d not supported!\n", cmd->cmd); exit(-1); } respChannel->send(&resp); return cmd->id; } int numCycles = 0; std::queue<DRAMRequest*> dramRequestQ; void recvDRAMRequest( uint64_t addr, uint64_t tag, bool isWr, uint32_t *wdata ) { DRAMRequest *req = new DRAMRequest(addr, tag, isWr, wdata); dramRequestQ.push(req); req->print(); } void checkDRAMResponse() { if (dramRequestQ.size() > 0) { DRAMRequest *req = dramRequestQ.front(); req->elapsed++; if(req->elapsed == req->delay) { dramRequestQ.pop(); uint32_t rdata[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; if (req->isWr) { // Write request: Update 1 burst-length bytes at *addr uint32_t *waddr = (uint32_t*) req->addr; for (int i=0; i<16; i++) { waddr[i] = req->wdata[i]; } } else { // Read request: Read burst-length bytes at *addr uint32_t *raddr = (uint32_t*) req->addr; for (int i=0; i<16; i++) { rdata[i] = raddr[i]; } } } } } // Function is called every clock cycle int tick() { bool exitTick = false; int finishSim = 0; numCycles++; // Check for DRAM response and send it to design checkDRAMResponse(); // Handle new incoming operations while (!exitTick) { dramCmd *cmd = (dramCmd*) cmdChannel->recv(); dramCmd readResp; switch (cmd->cmd) { case DRAM_MALLOC: { size_t size = *(size_t*)cmd->data; int fd = open("/dev/zero", O_RDWR); void *ptr = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0); close(fd); dramCmd resp; resp.id = cmd->id; resp.cmd = cmd->cmd; *(uint64_t*)resp.data = (uint64_t)ptr; resp.size = sizeof(size_t); EPRINTF("[SIM] MALLOC(%lu), returning %p\n", size, (void*)ptr); respChannel->send(&resp); break; } case DRAM_FREE: { void *ptr = (void*)(*(uint64_t*)cmd->data); ASSERT(ptr != NULL, "Attempting to call free on null pointer\n"); EPRINTF("[SIM] FREE(%p)\n", ptr); break; } case DRAM_MEMCPY_H2D: { uint64_t *data = (uint64_t*)cmd->data; void *dst = (void*)data[0]; size_t size = data[1]; EPRINTF("[SIM] Received memcpy request to %p, size %lu\n", (void*)dst, size); // Now to receive 'size' bytes from the cmd stream cmdChannel->recvFixedBytes(dst, size); // Send ack back indicating end of memcpy dramCmd resp; resp.id = cmd->id; resp.cmd = cmd->cmd; resp.size = 0; respChannel->send(&resp); break; } case DRAM_MEMCPY_D2H: { // Transfer 'size' bytes from src uint64_t *data = (uint64_t*)cmd->data; void *src = (void*)data[0]; size_t size = data[1]; // Now to receive 'size' bytes from the cmd stream respChannel->sendFixedBytes(src, size); break; } case DRAM_STEP: exitTick = true; break; case DRAM_FIN: finishSim = 1; exitTick = true; break; default: break; } } return finishSim; } void dramLoop() { while (!tick()); } // Called before simulation begins int main(int argc, char **argv) { EPRINTF("[DRAM] DRAM process started!\n"); // 0. Create Channel structures cmdChannel = new Channel(DRAM_CMD_FD, -1, sizeof(dramCmd)); respChannel = new Channel(-1, DRAM_RESP_FD, sizeof(dramCmd)); // 1. Read command dramCmd *cmd = (dramCmd*) cmdChannel->recv(); // 2. Send response sendResp(cmd); // 3. Go into the DRAM loop dramLoop(); EPRINTF("[DRAM] Quitting DRAM simulator\n"); return 0; } <|endoftext|>
<commit_before>/* -*- mode: c++; c-basic-offset:4 -*- uiserver/keyselectionjob.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2007 Klarälvdalens Datakonsult AB Kleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kleopatra 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "keyselectionjob.h" #include "keyselectiondialog.h" #include "kleo-assuan.h" #include "assuancommand.h" // for AssuanCommand::makeError() #include <kleo/keylistjob.h> #include <KLocale> #include <QDebug> #include <QList> #include <QPointer> #include <QStringList> #include <gpgme++/error.h> #include <gpgme++/key.h> #include <gpgme++/keylistresult.h> using namespace Kleo; class KeySelectionJob::Private { public: Private( KeySelectionJob* qq ) : q( qq ), m_secretKeysOnly( false ), m_keyListings( 0 ), m_started( false ) {} ~Private(); void startKeyListing(); bool startKeyListingForProtocol( const char* protocol ); void showKeySelectionDialog(); std::vector<GpgME::Key> m_keys; QStringList m_patterns; bool m_secretKeysOnly; QPointer<KeySelectionDialog> m_keySelector; int m_keyListings; GpgME::KeyListResult m_listResult; bool m_started; void nextKey( const GpgME::Key& key ); void keyListingDone( const GpgME::KeyListResult& result ); void keySelectionDialogClosed(); private: void emitError( int error, const GpgME::KeyListResult& result ); void emitResult( const std::vector<GpgME::Key>& keys ); private: KeySelectionJob* q; }; KeySelectionJob::Private::~Private() { delete m_keySelector; } void KeySelectionJob::Private::emitError( int error, const GpgME::KeyListResult& result ) { emit q->error( GpgME::Error( AssuanCommand::makeError( error ) ), result ); q->deleteLater(); } void KeySelectionJob::Private::emitResult( const std::vector<GpgME::Key>& keys ) { emit q->result( keys ); q->deleteLater(); } void KeySelectionJob::Private::keyListingDone( const GpgME::KeyListResult& result ) { m_listResult = result; if ( result.error() ) { emitError( result.error(), result ); return; } --m_keyListings; assert( m_keyListings >= 0 ); if ( m_keyListings == 0 ) { showKeySelectionDialog(); } } void KeySelectionJob::Private::nextKey( const GpgME::Key& key ) { m_keys.push_back( key ); } KeySelectionJob::KeySelectionJob( QObject* parent ) : QObject( parent ), d( new Private( this ) ) { } void KeySelectionJob::Private::keySelectionDialogClosed() { if ( m_keySelector->result() == QDialog::Rejected ) { emitError( GPG_ERR_CANCELED, m_listResult ); } else { emitResult( m_keySelector->selectedKeys() ); } } bool KeySelectionJob::Private::startKeyListingForProtocol( const char* protocol ) { if ( !CryptoBackendFactory::instance()->protocol( protocol ) ) return false; KeyListJob *keylisting = CryptoBackendFactory::instance()->protocol( protocol )->keyListJob(); QObject::connect( keylisting, SIGNAL( result( GpgME::KeyListResult ) ), q, SLOT( keyListingDone( GpgME::KeyListResult ) ) ); QObject::connect( keylisting, SIGNAL( nextKey( GpgME::Key ) ), q, SLOT( nextKey( GpgME::Key ) ) ); if ( const GpgME::Error err = keylisting->start( m_patterns, m_secretKeysOnly ) ) { q->deleteLater(); throw assuan_exception( err, i18n( "Unable to start keylisting for protocol %1", protocol ) ); } return true; } void KeySelectionJob::Private::startKeyListing() { m_keyListings = 0; QStringList protocols; protocols << "openpgp" << "smime"; Q_FOREACH ( const QString i, protocols ) { try { if ( startKeyListingForProtocol( i.toAscii().constData() ) ) ++m_keyListings; } catch ( const assuan_exception& exp ) { qDebug() << QString::fromStdString( exp.message() ); } } if ( m_keyListings == 0 ) { throw assuan_exception( AssuanCommand::makeError( GPG_ERR_GENERAL ), i18n( "Unable to start keylisting for any backend/no backends available" ) ); } } void KeySelectionJob::Private::showKeySelectionDialog() { assert( !m_keySelector ); m_keySelector = new KeySelectionDialog(); QObject::connect( m_keySelector, SIGNAL( accepted() ), q, SLOT( keySelectionDialogClosed() ) ); QObject::connect( m_keySelector, SIGNAL( rejected() ), q, SLOT( keySelectionDialogClosed() ) ); m_keySelector->addKeys( m_keys ); m_keySelector->show(); } void KeySelectionJob::start() { assert( !d->m_started ); if ( d->m_started ) return; d->m_started = true; d->startKeyListing(); } void KeySelectionJob::setPatterns( const QStringList& patterns ) { d->m_patterns = patterns; } QStringList KeySelectionJob::patterns() const { return d->m_patterns; } void KeySelectionJob::setSecretKeysOnly( bool secretOnly ) { d->m_secretKeysOnly = secretOnly; } bool KeySelectionJob::secretKeysOnly() const { return d->m_secretKeysOnly; } #include "keyselectionjob.moc" <commit_msg>oups, revert that<commit_after>/* -*- mode: c++; c-basic-offset:4 -*- uiserver/keyselectionjob.cpp This file is part of Kleopatra, the KDE keymanager Copyright (c) 2007 Klarälvdalens Datakonsult AB Kleopatra is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Kleopatra 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #include "keyselectionjob.h" #include "keyselectiondialog.h" #include "kleo-assuan.h" #include "assuancommand.h" // for AssuanCommand::makeError() #include <kleo/keylistjob.h> #include <QPointer> #include <QStringList> #include <gpgme++/error.h> #include <gpgme++/key.h> #include <gpgme++/keylistresult.h> using namespace Kleo; class KeySelectionJob::Private { public: Private( KeySelectionJob* qq ) : q( qq ), m_secretKeysOnly( false ), m_keyListings( 0 ), m_started( false ) {} ~Private(); void startKeyListing(); void showKeySelectionDialog(); std::vector<GpgME::Key> m_keys; QStringList m_patterns; bool m_secretKeysOnly; QPointer<KeySelectionDialog> m_keySelector; int m_keyListings; GpgME::KeyListResult m_listResult; bool m_started; void nextKey( const GpgME::Key& key ); void keyListingDone( const GpgME::KeyListResult& result ); void keySelectionDialogClosed(); private: void emitError( int error, const GpgME::KeyListResult& result ); void emitResult( const std::vector<GpgME::Key>& keys ); private: KeySelectionJob* q; }; KeySelectionJob::Private::~Private() { delete m_keySelector; } void KeySelectionJob::Private::emitError( int error, const GpgME::KeyListResult& result ) { emit q->error( GpgME::Error( AssuanCommand::makeError( error ) ), result ); q->deleteLater(); } void KeySelectionJob::Private::emitResult( const std::vector<GpgME::Key>& keys ) { emit q->result( keys ); q->deleteLater(); } void KeySelectionJob::Private::keyListingDone( const GpgME::KeyListResult& result ) { m_listResult = result; if ( result.error() ) { emitError( result.error(), result ); return; } --m_keyListings; assert( m_keyListings >= 0 ); if ( m_keyListings == 0 ) { showKeySelectionDialog(); } } void KeySelectionJob::Private::nextKey( const GpgME::Key& key ) { m_keys.push_back( key ); } KeySelectionJob::KeySelectionJob( QObject* parent ) : QObject( parent ), d( new Private( this ) ) { } void KeySelectionJob::Private::keySelectionDialogClosed() { if ( m_keySelector->result() == QDialog::Rejected ) { emitError( GPG_ERR_CANCELED, m_listResult ); } else { emitResult( m_keySelector->selectedKeys() ); } } void KeySelectionJob::Private::startKeyListing() { m_keyListings = 2; // openpgp and cms KeyListJob *keylisting = CryptoBackendFactory::instance()->protocol( "openpgp" )->keyListJob(); QObject::connect( keylisting, SIGNAL( result( GpgME::KeyListResult ) ), q, SLOT( keyListingDone( GpgME::KeyListResult ) ) ); QObject::connect( keylisting, SIGNAL( nextKey( GpgME::Key ) ), q, SLOT( nextKey( GpgME::Key ) ) ); if ( const GpgME::Error err = keylisting->start( m_patterns, m_secretKeysOnly ) ) { q->deleteLater(); throw assuan_exception( err, "Unable to start keylisting" ); } keylisting = Kleo::CryptoBackendFactory::instance()->protocol( "smime" )->keyListJob(); QObject::connect( keylisting, SIGNAL( result( GpgME::KeyListResult ) ), q, SLOT( keyListingDone( GpgME::KeyListResult ) ) ); QObject::connect( keylisting, SIGNAL( nextKey( GpgME::Key ) ), q, SLOT( nextKey( GpgME::Key ) ) ); if ( const GpgME::Error err = keylisting->start( m_patterns, m_secretKeysOnly ) ) { q->deleteLater(); throw assuan_exception( err, "Unable to start keylisting" ); } } void KeySelectionJob::Private::showKeySelectionDialog() { assert( !m_keySelector ); m_keySelector = new KeySelectionDialog(); QObject::connect( m_keySelector, SIGNAL( accepted() ), q, SLOT( keySelectionDialogClosed() ) ); QObject::connect( m_keySelector, SIGNAL( rejected() ), q, SLOT( keySelectionDialogClosed() ) ); m_keySelector->addKeys( m_keys ); m_keySelector->show(); } void KeySelectionJob::start() { assert( !d->m_started ); if ( d->m_started ) return; d->m_started = true; d->startKeyListing(); } void KeySelectionJob::setPatterns( const QStringList& patterns ) { d->m_patterns = patterns; } QStringList KeySelectionJob::patterns() const { return d->m_patterns; } void KeySelectionJob::setSecretKeysOnly( bool secretOnly ) { d->m_secretKeysOnly = secretOnly; } bool KeySelectionJob::secretKeysOnly() const { return d->m_secretKeysOnly; } #include "keyselectionjob.moc" <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // UNSUPPORTED: libcpp-has-no-threads // <thread> // class thread // template <class F, class ...Args> thread(F&& f, Args&&... args); // UNSUPPORTED: sanitizer-new-delete #include <thread> #include <new> #include <atomic> #include <cstdlib> #include <cassert> #include "test_macros.h" std::atomic<unsigned> throw_one(0xFFFF); std::atomic<unsigned> outstanding_new(0); void* operator new(std::size_t s) TEST_THROW_SPEC(std::bad_alloc) { if (throw_one == 0) TEST_THROW(std::bad_alloc()); --throw_one; ++outstanding_new; void* ret = std::malloc(s); if (!ret) std::abort(); // placate MSVC's unchecked malloc warning return ret; } void operator delete(void* p) TEST_NOEXCEPT { --outstanding_new; std::free(p); } bool f_run = false; void f() { f_run = true; } class G { int alive_; public: static int n_alive; static bool op_run; G() : alive_(1) {++n_alive;} G(const G& g) : alive_(g.alive_) {++n_alive;} ~G() {alive_ = 0; --n_alive;} void operator()() { assert(alive_ == 1); assert(n_alive >= 1); op_run = true; } void operator()(int i, double j) { assert(alive_ == 1); assert(n_alive >= 1); assert(i == 5); assert(j == 5.5); op_run = true; } }; int G::n_alive = 0; bool G::op_run = false; #if TEST_STD_VER >= 11 class MoveOnly { MoveOnly(const MoveOnly&); public: MoveOnly() {} MoveOnly(MoveOnly&&) {} void operator()(MoveOnly&&) { } }; #endif // Test throwing std::bad_alloc //----------------------------- // Concerns: // A Each allocation performed during thread construction should be performed // in the parent thread so that std::terminate is not called if // std::bad_alloc is thrown by new. // B std::thread's constructor should properly handle exceptions and not leak // memory. // Plan: // 1 Create a thread and count the number of allocations, 'N', it performs. // 2 For each allocation performed run a test where that allocation throws. // 2.1 check that the exception can be caught in the parent thread. // 2.2 Check that the functor has not been called. // 2.3 Check that no memory allocated by the creation of the thread is leaked. // 3 Finally check that a thread runs successfully if we throw after 'N+1' // allocations. void test_throwing_new_during_thread_creation() { #ifndef TEST_HAS_NO_EXCEPTIONS throw_one = 0xFFF; { std::thread t(f); t.join(); } const int numAllocs = 0xFFF - throw_one; // i <= numAllocs means the last iteration is expected not to throw. for (int i=0; i <= numAllocs; ++i) { throw_one = i; f_run = false; unsigned old_outstanding = outstanding_new; try { std::thread t(f); assert(i == numAllocs); // Only final iteration will not throw. t.join(); assert(f_run); } catch (std::bad_alloc const&) { assert(i < numAllocs); assert(!f_run); // (2.2) } assert(old_outstanding == outstanding_new); // (2.3) } f_run = false; throw_one = 0xFFF; #endif } int main(int, char**) { test_throwing_new_during_thread_creation(); { std::thread t(f); t.join(); assert(f_run == true); } { assert(G::n_alive == 0); assert(!G::op_run); { G g; std::thread t(g); t.join(); } assert(G::n_alive == 0); assert(G::op_run); } G::op_run = false; #ifndef TEST_HAS_NO_EXCEPTIONS { try { throw_one = 0; assert(G::n_alive == 0); assert(!G::op_run); std::thread t((G())); assert(false); } catch (...) { throw_one = 0xFFFF; assert(G::n_alive == 0); assert(!G::op_run); } } #endif #if TEST_STD_VER >= 11 { assert(G::n_alive == 0); assert(!G::op_run); { G g; std::thread t(g, 5, 5.5); t.join(); } assert(G::n_alive == 0); assert(G::op_run); } { std::thread t = std::thread(MoveOnly(), MoveOnly()); t.join(); } #endif return 0; } <commit_msg>[libc++][test] Remove non-portable assumption that thread's constructor allocates with ::new<commit_after>//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // UNSUPPORTED: libcpp-has-no-threads // <thread> // class thread // template <class F, class ...Args> thread(F&& f, Args&&... args); // UNSUPPORTED: sanitizer-new-delete #include <thread> #include <new> #include <atomic> #include <cstdlib> #include <cassert> #include "test_macros.h" std::atomic<unsigned> throw_one(0xFFFF); std::atomic<unsigned> outstanding_new(0); void* operator new(std::size_t s) TEST_THROW_SPEC(std::bad_alloc) { unsigned expected = throw_one; do { if (expected == 0) TEST_THROW(std::bad_alloc()); } while (!throw_one.compare_exchange_weak(expected, expected - 1)); ++outstanding_new; void* ret = std::malloc(s); if (!ret) std::abort(); // placate MSVC's unchecked malloc warning return ret; } void operator delete(void* p) TEST_NOEXCEPT { if (!p) return; --outstanding_new; std::free(p); } bool f_run = false; void f() { f_run = true; } class G { int alive_; public: static int n_alive; static bool op_run; G() : alive_(1) {++n_alive;} G(const G& g) : alive_(g.alive_) {++n_alive;} ~G() {alive_ = 0; --n_alive;} void operator()() { assert(alive_ == 1); assert(n_alive >= 1); op_run = true; } void operator()(int i, double j) { assert(alive_ == 1); assert(n_alive >= 1); assert(i == 5); assert(j == 5.5); op_run = true; } }; int G::n_alive = 0; bool G::op_run = false; #if TEST_STD_VER >= 11 class MoveOnly { MoveOnly(const MoveOnly&); public: MoveOnly() {} MoveOnly(MoveOnly&&) {} void operator()(MoveOnly&&) { } }; #endif // Test throwing std::bad_alloc //----------------------------- // Concerns: // A Each allocation performed during thread construction should be performed // in the parent thread so that std::terminate is not called if // std::bad_alloc is thrown by new. // B std::thread's constructor should properly handle exceptions and not leak // memory. // Plan: // 1 Create a thread and count the number of allocations, 'numAllocs', it // performs. // 2 For each allocation performed run a test where that allocation throws. // 2.1 check that the exception can be caught in the parent thread. // 2.2 Check that the functor has not been called. // 2.3 Check that no memory allocated by the creation of the thread is leaked. // 3 Finally check that a thread runs successfully if we throw after // 'numAllocs + 1' allocations. int numAllocs; void test_throwing_new_during_thread_creation() { #ifndef TEST_HAS_NO_EXCEPTIONS throw_one = 0xFFF; { std::thread t(f); t.join(); } numAllocs = 0xFFF - throw_one; // i <= numAllocs means the last iteration is expected not to throw. for (int i=0; i <= numAllocs; ++i) { throw_one = i; f_run = false; unsigned old_outstanding = outstanding_new; try { std::thread t(f); assert(i == numAllocs); // Only final iteration will not throw. t.join(); assert(f_run); } catch (std::bad_alloc const&) { assert(i < numAllocs); assert(!f_run); // (2.2) } assert(old_outstanding == outstanding_new); // (2.3) } f_run = false; throw_one = 0xFFF; #endif } int main(int, char**) { test_throwing_new_during_thread_creation(); { std::thread t(f); t.join(); assert(f_run == true); } { assert(G::n_alive == 0); assert(!G::op_run); { G g; std::thread t(g); t.join(); } assert(G::n_alive == 0); assert(G::op_run); } G::op_run = false; #ifndef TEST_HAS_NO_EXCEPTIONS // The test below expects `std::thread` to call `new`, which may not be the // case for all implementations. LIBCPP_ASSERT(numAllocs > 0); // libc++ should call new. if (numAllocs > 0) { try { throw_one = 0; assert(G::n_alive == 0); assert(!G::op_run); std::thread t((G())); assert(false); } catch (std::bad_alloc const&) { throw_one = 0xFFFF; assert(G::n_alive == 0); assert(!G::op_run); } } #endif #if TEST_STD_VER >= 11 { assert(G::n_alive == 0); assert(!G::op_run); { G g; std::thread t(g, 5, 5.5); t.join(); } assert(G::n_alive == 0); assert(G::op_run); } { std::thread t = std::thread(MoveOnly(), MoveOnly()); t.join(); } #endif return 0; } <|endoftext|>
<commit_before>//@HEADER // *************************************************** // // HPCG: High Performance Conjugate Gradient Benchmark // // Contact: // Michael A. Heroux ( maherou@sandia.gov) // Jack Dongarra (dongarra@eecs.utk.edu) // Piotr Luszczek (luszczek@eecs.utk.edu) // // modified by Dominic Meiser, Tech-X corporation // // *************************************************** //@HEADER #ifndef EXCHANGEHALO_HPP #define EXCHANGEHALO_HPP #include "SparseMatrix.hpp" #include "Vector.hpp" struct DataTransfer_; typedef struct DataTransfer_* DataTransfer; /*! Initiates communication of data that is at the border of the part of the domain assigned to this processor. Data is not guaranteed to be received until EndExchangeHalo finishes. @param[in] A The known system matrix @param[inout] x On entry: the local vector entries followed by entries to be communicated. It is save to modify the local data after BeginExchangeHalo returns. It is assumed that the GPU data in x is up to date. @return A handle to internal data transfer information needed for completing the halo exchange by means of EndExchangeHalo. @sa EndExchangeHalo */ DataTransfer BeginExchangeHalo(const SparseMatrix & A, Vector & x); /** Finalizes halo data exchange. @param[in] A The known system matrix @param[inout] x On exit: the local vector entries followed by entries received from other processes. Only the data on the GPU is updated. @param[in] transfer Handle to data transfer data obtained by call to BeginExchangeHalo. @sa BeginExchangeHalo */ void EndExchangeHalo(const SparseMatrix & A, Vector & x, DataTransfer transfer); #endif // EXCHANGEHALO_HPP <commit_msg>Add declaration of legacy ExchangeHalo to ExchangeHalo.hpp.<commit_after>//@HEADER // *************************************************** // // HPCG: High Performance Conjugate Gradient Benchmark // // Contact: // Michael A. Heroux ( maherou@sandia.gov) // Jack Dongarra (dongarra@eecs.utk.edu) // Piotr Luszczek (luszczek@eecs.utk.edu) // // modified by Dominic Meiser, Tech-X corporation // // *************************************************** //@HEADER #ifndef EXCHANGEHALO_HPP #define EXCHANGEHALO_HPP #include "SparseMatrix.hpp" #include "Vector.hpp" struct DataTransfer_; typedef struct DataTransfer_* DataTransfer; /*! Initiates communication of data that is at the border of the part of the domain assigned to this processor. Data is not guaranteed to be received until EndExchangeHalo finishes. @param[in] A The known system matrix @param[inout] x On entry: the local vector entries followed by entries to be communicated. It is save to modify the local data after BeginExchangeHalo returns. It is assumed that the GPU data in x is up to date. @return A handle to internal data transfer information needed for completing the halo exchange by means of EndExchangeHalo. @sa EndExchangeHalo */ DataTransfer BeginExchangeHalo(const SparseMatrix & A, Vector & x); /** Finalizes halo data exchange. @param[in] A The known system matrix @param[inout] x On exit: the local vector entries followed by entries received from other processes. Only the data on the GPU is updated. @param[in] transfer Handle to data transfer data obtained by call to BeginExchangeHalo. @sa BeginExchangeHalo */ void EndExchangeHalo(const SparseMatrix & A, Vector & x, DataTransfer transfer); /** * For convenience we provide a declaration of the original ExchangeHalo * */ void ExchangeHalo(const SparseMatrix& A, Vector& x); #endif // EXCHANGEHALO_HPP <|endoftext|>
<commit_before>#ifndef ARRAY_HPP #define ARRAY_HPP #include <ace-vm/Value.hpp> namespace ace { namespace vm { class Array { public: Array(int size = 0); Array(const Array &other); ~Array(); Array &operator=(const Array &other); inline bool operator==(const Array &other) const { return this == &other; } inline int GetSize() const { return m_size; } inline Value &AtIndex(int index) { return m_buffer[index]; } inline const Value &AtIndex(int index) const { return m_buffer[index]; } void Push(const Value &value); void Pop(); private: int m_size; int m_capacity; Value *m_buffer; }; } // namespace vm } // namespace ace #endif<commit_msg>Delete array.hpp<commit_after><|endoftext|>
<commit_before>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Bohrium 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 General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <vector> #include <iostream> #include <boost/functional/hash.hpp> #include <jitk/kernel.hpp> #include "engine_opencl.hpp" using namespace std; namespace { #define CL_DEVICE_AUTO 1024 // More than maximum in the bitmask map<const string, cl_device_type> device_map = { {"auto", CL_DEVICE_AUTO}, {"gpu", CL_DEVICE_TYPE_GPU}, {"accelerator", CL_DEVICE_TYPE_ACCELERATOR}, {"default", CL_DEVICE_TYPE_DEFAULT}, {"cpu", CL_DEVICE_TYPE_CPU} }; // Get the OpenCL device (search order: GPU, ACCELERATOR, DEFAULT, and CPU) cl::Device getDevice(const cl::Platform &platform, const string &default_device_type) { vector<cl::Device> device_list; platform.getDevices(CL_DEVICE_TYPE_ALL, &device_list); if(device_list.size() == 0){ throw runtime_error("No OpenCL device found"); } if (!util::exist(device_map, default_device_type)) { stringstream ss; ss << "'" << default_device_type << "' is not a OpenCL device type. " \ << "Must be one of 'auto', 'gpu', 'accelerator', 'cpu', or 'default'"; throw runtime_error(ss.str()); } else if (device_map[default_device_type] != CL_DEVICE_AUTO) { for (auto &device: device_list) { if ((device.getInfo<CL_DEVICE_TYPE>() & device_map[default_device_type]) == device_map[default_device_type]) { return device; } } stringstream ss; ss << "Could not find selected OpenCL device type ('" \ << default_device_type << "') on default platform"; throw runtime_error(ss.str()); } // Type was 'auto' for (auto &device_type: device_map) { for (auto &device: device_list) { if ((device.getInfo<CL_DEVICE_TYPE>() & device_type.second) == device_type.second) { return device; } } } throw runtime_error("No OpenCL device of usable type found"); } } namespace bohrium { static boost::hash<string> hasher; EngineOpenCL::EngineOpenCL(const ConfigParser &config, jitk::Statistics &stat) : compile_flg(config.defaultGet<string>("compiler_flg", "")), default_device_type(config.defaultGet<string>("device_type", "auto")), verbose(config.defaultGet<bool>("verbose", false)), stat(stat) { vector<cl::Platform> platforms; cl::Platform::get(&platforms); if(platforms.size() == 0) { throw runtime_error("No OpenCL platforms found"); } cl::Platform default_platform=platforms[0]; if(verbose) { cout << "Using platform: " << default_platform.getInfo<CL_PLATFORM_NAME>() << endl; } //get the device of the default platform device = getDevice(default_platform, default_device_type); if(verbose) { cout << "Using device: " << device.getInfo<CL_DEVICE_NAME>() \ << " ("<< device.getInfo<CL_DEVICE_OPENCL_C_VERSION>() << ")" << endl; } vector<cl::Device> dev_list = {device}; context = cl::Context(dev_list); queue = cl::CommandQueue(context, device); } pair<cl::NDRange, cl::NDRange> EngineOpenCL::NDRanges(const vector<const jitk::LoopB*> &threaded_blocks) const { const auto &b = threaded_blocks; switch (b.size()) { case 1: { const cl_ulong lsize = work_group_size_1dx; const cl_ulong rem = b[0]->size % lsize; const cl_ulong gsize = b[0]->size + (rem==0?0:(lsize-rem)); return make_pair(cl::NDRange(gsize), cl::NDRange(lsize)); } case 2: { const cl_ulong lsize_x = work_group_size_2dx; const cl_ulong lsize_y = work_group_size_2dy; const cl_ulong rem_x = b[0]->size % lsize_x; const cl_ulong rem_y = b[1]->size % lsize_y; const cl_ulong gsize_x = b[0]->size + (rem_x==0?0:(lsize_x-rem_x)); const cl_ulong gsize_y = b[1]->size + (rem_y==0?0:(lsize_y-rem_y)); return make_pair(cl::NDRange(gsize_x, gsize_y), cl::NDRange(lsize_x, lsize_y)); } case 3: { const cl_ulong lsize_x = work_group_size_3dx; const cl_ulong lsize_y = work_group_size_3dy; const cl_ulong lsize_z = work_group_size_3dz; const cl_ulong rem_x = b[0]->size % lsize_x; const cl_ulong rem_y = b[1]->size % lsize_y; const cl_ulong rem_z = b[2]->size % lsize_z; const cl_ulong gsize_x = b[0]->size + (rem_x==0?0:(lsize_x-rem_x)); const cl_ulong gsize_y = b[1]->size + (rem_y==0?0:(lsize_y-rem_y)); const cl_ulong gsize_z = b[2]->size + (rem_z==0?0:(lsize_z-rem_z)); return make_pair(cl::NDRange(gsize_x, gsize_y, gsize_z), cl::NDRange(lsize_x, lsize_y, lsize_z)); } default: throw runtime_error("NDRanges: maximum of three dimensions!"); } } void EngineOpenCL::execute(const std::string &source, const jitk::Kernel &kernel, const vector<const jitk::LoopB*> &threaded_blocks, const vector<const bh_view*> &offset_strides) { size_t hash = hasher(source); ++stat.kernel_cache_lookups; cl::Program program; auto tcompile = chrono::steady_clock::now(); // Do we have the program already? if (_programs.find(hash) != _programs.end()) { program = _programs.at(hash); } else { // Or do we have to compile it ++stat.kernel_cache_misses; program = cl::Program(context, source); try { program.build({device}, compile_flg.c_str()); if (verbose) { cout << "********** Compile Flags **********" << endl \ << compile_flg.c_str() << endl \ << "************ Flags END ************" << endl << endl; cout << "************ Build Log ************" << endl \ << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device) \ << "^^^^^^^^^^^^^ Log END ^^^^^^^^^^^^^" << endl << endl; } } catch (cl::Error e) { cerr << "Error building: " << endl << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device) << endl; throw; } _programs[hash] = program; } stat.time_compile += chrono::steady_clock::now() - tcompile; // Let's execute the OpenCL kernel cl::Kernel opencl_kernel = cl::Kernel(program, "execute"); { cl_uint i = 0; for (bh_base *base: kernel.getNonTemps()) { // NB: the iteration order matters! opencl_kernel.setArg(i++, *buffers.at(base)); } for (const bh_view *view: offset_strides) { uint64_t t1 = (uint64_t) view->start; opencl_kernel.setArg(i++, t1); for (int j=0; j<view->ndim; ++j) { uint64_t t2 = (uint64_t) view->stride[j]; opencl_kernel.setArg(i++, t2); } } } const auto ranges = NDRanges(threaded_blocks); auto texec = chrono::steady_clock::now(); queue.enqueueNDRangeKernel(opencl_kernel, cl::NullRange, ranges.first, ranges.second); queue.finish(); stat.time_exec += chrono::steady_clock::now() - texec; } } // bohrium <commit_msg>Print verbose flags out before compiling with OpenCL<commit_after>/* This file is part of Bohrium and copyright (c) 2012 the Bohrium team <http://www.bh107.org>. Bohrium is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Bohrium 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 General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Bohrium. If not, see <http://www.gnu.org/licenses/>. */ #include <vector> #include <iostream> #include <boost/functional/hash.hpp> #include <jitk/kernel.hpp> #include "engine_opencl.hpp" using namespace std; namespace { #define CL_DEVICE_AUTO 1024 // More than maximum in the bitmask map<const string, cl_device_type> device_map = { {"auto", CL_DEVICE_AUTO}, {"gpu", CL_DEVICE_TYPE_GPU}, {"accelerator", CL_DEVICE_TYPE_ACCELERATOR}, {"default", CL_DEVICE_TYPE_DEFAULT}, {"cpu", CL_DEVICE_TYPE_CPU} }; // Get the OpenCL device (search order: GPU, ACCELERATOR, DEFAULT, and CPU) cl::Device getDevice(const cl::Platform &platform, const string &default_device_type) { vector<cl::Device> device_list; platform.getDevices(CL_DEVICE_TYPE_ALL, &device_list); if(device_list.size() == 0){ throw runtime_error("No OpenCL device found"); } if (!util::exist(device_map, default_device_type)) { stringstream ss; ss << "'" << default_device_type << "' is not a OpenCL device type. " \ << "Must be one of 'auto', 'gpu', 'accelerator', 'cpu', or 'default'"; throw runtime_error(ss.str()); } else if (device_map[default_device_type] != CL_DEVICE_AUTO) { for (auto &device: device_list) { if ((device.getInfo<CL_DEVICE_TYPE>() & device_map[default_device_type]) == device_map[default_device_type]) { return device; } } stringstream ss; ss << "Could not find selected OpenCL device type ('" \ << default_device_type << "') on default platform"; throw runtime_error(ss.str()); } // Type was 'auto' for (auto &device_type: device_map) { for (auto &device: device_list) { if ((device.getInfo<CL_DEVICE_TYPE>() & device_type.second) == device_type.second) { return device; } } } throw runtime_error("No OpenCL device of usable type found"); } } namespace bohrium { static boost::hash<string> hasher; EngineOpenCL::EngineOpenCL(const ConfigParser &config, jitk::Statistics &stat) : compile_flg(config.defaultGet<string>("compiler_flg", "")), default_device_type(config.defaultGet<string>("device_type", "auto")), verbose(config.defaultGet<bool>("verbose", false)), stat(stat) { vector<cl::Platform> platforms; cl::Platform::get(&platforms); if(platforms.size() == 0) { throw runtime_error("No OpenCL platforms found"); } cl::Platform default_platform=platforms[0]; if(verbose) { cout << "Using platform: " << default_platform.getInfo<CL_PLATFORM_NAME>() << endl; } //get the device of the default platform device = getDevice(default_platform, default_device_type); if(verbose) { cout << "Using device: " << device.getInfo<CL_DEVICE_NAME>() \ << " ("<< device.getInfo<CL_DEVICE_OPENCL_C_VERSION>() << ")" << endl; } vector<cl::Device> dev_list = {device}; context = cl::Context(dev_list); queue = cl::CommandQueue(context, device); } pair<cl::NDRange, cl::NDRange> EngineOpenCL::NDRanges(const vector<const jitk::LoopB*> &threaded_blocks) const { const auto &b = threaded_blocks; switch (b.size()) { case 1: { const cl_ulong lsize = work_group_size_1dx; const cl_ulong rem = b[0]->size % lsize; const cl_ulong gsize = b[0]->size + (rem==0?0:(lsize-rem)); return make_pair(cl::NDRange(gsize), cl::NDRange(lsize)); } case 2: { const cl_ulong lsize_x = work_group_size_2dx; const cl_ulong lsize_y = work_group_size_2dy; const cl_ulong rem_x = b[0]->size % lsize_x; const cl_ulong rem_y = b[1]->size % lsize_y; const cl_ulong gsize_x = b[0]->size + (rem_x==0?0:(lsize_x-rem_x)); const cl_ulong gsize_y = b[1]->size + (rem_y==0?0:(lsize_y-rem_y)); return make_pair(cl::NDRange(gsize_x, gsize_y), cl::NDRange(lsize_x, lsize_y)); } case 3: { const cl_ulong lsize_x = work_group_size_3dx; const cl_ulong lsize_y = work_group_size_3dy; const cl_ulong lsize_z = work_group_size_3dz; const cl_ulong rem_x = b[0]->size % lsize_x; const cl_ulong rem_y = b[1]->size % lsize_y; const cl_ulong rem_z = b[2]->size % lsize_z; const cl_ulong gsize_x = b[0]->size + (rem_x==0?0:(lsize_x-rem_x)); const cl_ulong gsize_y = b[1]->size + (rem_y==0?0:(lsize_y-rem_y)); const cl_ulong gsize_z = b[2]->size + (rem_z==0?0:(lsize_z-rem_z)); return make_pair(cl::NDRange(gsize_x, gsize_y, gsize_z), cl::NDRange(lsize_x, lsize_y, lsize_z)); } default: throw runtime_error("NDRanges: maximum of three dimensions!"); } } void EngineOpenCL::execute(const std::string &source, const jitk::Kernel &kernel, const vector<const jitk::LoopB*> &threaded_blocks, const vector<const bh_view*> &offset_strides) { size_t hash = hasher(source); ++stat.kernel_cache_lookups; cl::Program program; auto tcompile = chrono::steady_clock::now(); // Do we have the program already? if (_programs.find(hash) != _programs.end()) { program = _programs.at(hash); } else { // Or do we have to compile it ++stat.kernel_cache_misses; program = cl::Program(context, source); try { if (verbose) { cout << "********** Compile Flags **********" << endl \ << compile_flg.c_str() << endl \ << "************ Flags END ************" << endl << endl; cout << "************ Build Log ************" << endl \ << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device) \ << "^^^^^^^^^^^^^ Log END ^^^^^^^^^^^^^" << endl << endl; } program.build({device}, compile_flg.c_str()); } catch (cl::Error e) { cerr << "Error building: " << endl << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device) << endl; throw; } _programs[hash] = program; } stat.time_compile += chrono::steady_clock::now() - tcompile; // Let's execute the OpenCL kernel cl::Kernel opencl_kernel = cl::Kernel(program, "execute"); { cl_uint i = 0; for (bh_base *base: kernel.getNonTemps()) { // NB: the iteration order matters! opencl_kernel.setArg(i++, *buffers.at(base)); } for (const bh_view *view: offset_strides) { uint64_t t1 = (uint64_t) view->start; opencl_kernel.setArg(i++, t1); for (int j=0; j<view->ndim; ++j) { uint64_t t2 = (uint64_t) view->stride[j]; opencl_kernel.setArg(i++, t2); } } } const auto ranges = NDRanges(threaded_blocks); auto texec = chrono::steady_clock::now(); queue.enqueueNDRangeKernel(opencl_kernel, cl::NullRange, ranges.first, ranges.second); queue.finish(); stat.time_exec += chrono::steady_clock::now() - texec; } } // bohrium <|endoftext|>
<commit_before>// Copyright 2018 Global Phasing Ltd. // // Selections. #ifndef GEMMI_SELECT_HPP_ #define GEMMI_SELECT_HPP_ #include <string> #include <cstdlib> // for strtol #include <cctype> // for isalpha #include <climits> // for INT_MIN, INT_MAX #include "fail.hpp" // for fail #include "model.hpp" // for Model, Chain, etc #include "iterator.hpp" // for FilterProxy namespace gemmi { // from http://www.ccp4.ac.uk/html/pdbcur.html // Specification of the selection sets: // either // /mdl/chn/s1.i1-s2.i2/at[el]:aloc // or // /mdl/chn/*(res).ic/at[el]:aloc // struct Selection { struct List { bool all = true; bool inverted = false; std::string list; // comma-separated std::string str() const { if (all) return "*"; return inverted ? "!" + list : list; } }; struct SequenceId { int seqnum; char icode; std::string str() const { std::string s; if (seqnum != INT_MIN && seqnum != INT_MAX) s = std::to_string(seqnum); if (icode != '*') { s += '.'; if (icode != ' ') s += icode; } return s; } int compare(const SeqId& seqid) const { if (seqnum != *seqid.num) return seqnum < *seqid.num ? -1 : 1; if (icode != '*' && icode != seqid.icode) return icode < seqid.icode ? -1 : 1; return 0; } }; int mdl = 0; // 0 = all List chain_ids; SequenceId from_seqid = {INT_MIN, '*'}; SequenceId to_seqid = {INT_MAX, '*'}; List residue_names; List atom_names; List elements; List altlocs; std::string to_cid() const { std::string cid(1, '/'); if (mdl != 0) cid += std::to_string(mdl); cid += '/'; cid += chain_ids.str(); cid += '/'; cid += from_seqid.str(); if (!residue_names.all) { cid += residue_names.str(); } else { cid += '-'; cid += to_seqid.str(); } cid += '/'; cid += atom_names.str(); if (!elements.all) cid += "[" + elements.str() + "]"; if (!altlocs.all) cid += ":" + altlocs.str(); return cid; } bool matches(const gemmi::Model& model) const { return mdl == 0 || std::to_string(mdl) == model.name; } bool matches(const gemmi::Chain& chain) const { return chain_ids.all || find_in_list(chain.name, chain_ids); } bool matches(const gemmi::Residue& res) const { return (residue_names.all || find_in_list(res.name, residue_names)) && from_seqid.compare(res.seqid) <= 0 && to_seqid.compare(res.seqid) >= 0; } bool matches(const gemmi::Atom& a) const { return (atom_names.all || find_in_list(a.name, atom_names)) && (elements.all || find_in_list(a.element.uname(), elements)) && (altlocs.all || find_in_list(std::string(a.altloc ? 0 : 1, a.altloc), altlocs)); } bool matches(const gemmi::CRA& cra) const { return (cra.chain == nullptr || matches(*cra.chain)) && (cra.residue == nullptr || matches(*cra.residue)) && (cra.atom == nullptr || matches(*cra.atom)); } FilterProxy<Selection, Model> models(Structure& st) const { return {*this, st.models}; } FilterProxy<Selection, Chain> chains(Model& model) const { return {*this, model.chains}; } FilterProxy<Selection, Residue> residues(Chain& chain) const { return {*this, chain.residues}; } FilterProxy<Selection, Atom> atoms(Residue& residue) const { return {*this, residue.atoms}; } CRA first_in_model(Model& model) const { if (matches(model)) for (Chain& chain : model.chains) { if (matches(chain)) for (Residue& res : chain.residues) { if (matches(res)) for (Atom& atom : res.atoms) { if (matches(atom)) return {&chain, &res, &atom}; } } } return {nullptr, nullptr, nullptr}; } std::pair<Model*, CRA> first(Structure& st) const { for (Model& model : st.models) { CRA cra = first_in_model(model); if (cra.chain) return {&model, cra}; } return {nullptr, {nullptr, nullptr, nullptr}}; } static Structure copy_empty(const Structure& orig) { Structure st(orig); st.models.clear(); // it may be inefficient return st; } static Model copy_empty(const Model& orig) { return Model(orig.name); } static Chain copy_empty(const Chain& orig) { return Chain(orig.name); } static Residue copy_empty(const Residue& orig) { Residue res((ResidueId&)orig); res.subchain = orig.subchain; res.label_seq = orig.label_seq; res.entity_type = orig.entity_type; res.het_flag = orig.het_flag; res.is_cis = orig.is_cis; res.flag = orig.flag; return res; } static Atom copy_empty(const Atom& orig) { return Atom(orig); } template<typename T> void add_matching_children(const T& orig, T& target) { for (const auto& orig_child : orig.children()) if (matches(orig_child)) { target.children().push_back(copy_empty(orig_child)); add_matching_children(orig_child, target.children().back()); } } void add_matching_children(const Atom&, Atom&) {} template<typename T> T copy_subset(const T& orig) { T copied = copy_empty(orig); add_matching_children(orig, copied); return copied; } private: static bool find_in_comma_separated_string(const std::string& name, const std::string& str) { if (name.length() >= str.length()) return name == str; for (size_t start=0, end=0; end != std::string::npos; start=end+1) { end = str.find(',', start); if (str.compare(start, end - start, name) == 0) return true; } return false; } // assumes that list.all is checked before this function is called static bool find_in_list(const std::string& name, const List& list) { bool found = find_in_comma_separated_string(name, list.list); return list.inverted ? !found : found; } }; namespace impl { int determine_omitted_cid_fields(const std::string& cid) { if (cid[0] == '/') return 0; // model if (std::isdigit(cid[0]) || cid[0] == '.' || cid[0] == '(' || cid[0] == '-') return 2; // residue size_t sep = cid.find_first_of("/(:["); if (sep == std::string::npos || cid[sep] == '/') return 1; // chain if (cid[sep] == '(') return 2; // residue return 3; // atom } Selection::List make_cid_list(const std::string& cid, size_t pos, size_t end) { Selection::List list; list.all = (cid[pos] == '*'); if (cid[pos] == '!') { list.inverted = true; ++pos; } list.list = cid.substr(pos, end - pos); return list; } Selection::SequenceId parse_cid_seqid(const std::string& cid, size_t& pos, int default_seqnum) { size_t initial_pos = pos; int seqnum = default_seqnum; char icode = ' '; if (cid[pos] == '*') { ++pos; icode = '*'; } else if (std::isdigit(cid[pos])) { char* endptr; seqnum = std::strtol(&cid[pos], &endptr, 10); pos = endptr - &cid[0]; } if (cid[pos] == '.') ++pos; if (initial_pos != pos && (std::isalpha(cid[pos]) || cid[pos] == '*')) icode = cid[pos++]; return {seqnum, icode}; } } // namespace impl inline Selection parse_cid(const std::string& cid) { Selection sel; if (cid.empty() || (cid.size() == 1 && cid[0] == '*')) return sel; int omit = impl::determine_omitted_cid_fields(cid); size_t sep = 0; // model if (omit == 0) { sep = cid.find('/', 1); if (sep != 1 && cid[1] != '*') { char* endptr; sel.mdl = std::strtol(&cid[1], &endptr, 10); size_t end_pos = endptr - &cid[0]; if (end_pos != sep && end_pos != cid.length()) fail("Expected model number first: " + cid); } } // chain if (omit <= 1 && sep != std::string::npos) { size_t pos = (sep == 0 ? 0 : sep + 1); sep = cid.find('/', pos); sel.chain_ids = impl::make_cid_list(cid, pos, sep); } // residue; MMDB CID syntax: s1.i1-s2.i2 or *(res).ic // In gemmi both 14.a and 14a are accepted. // *(ALA). and *(ALA) and (ALA). can be used instead of (ALA) for // compatibility with MMDB. if (omit <= 2 && sep != std::string::npos) { size_t pos = (sep == 0 ? 0 : sep + 1); if (cid[pos] != '(') sel.from_seqid = impl::parse_cid_seqid(cid, pos, INT_MIN); if (cid[pos] == '(') { ++pos; size_t right_br = cid.find(')', pos); sel.residue_names = impl::make_cid_list(cid, pos, right_br); pos = right_br + 1; } // allow "(RES)." and "(RES).*" and "(RES)*" if (cid[pos] == '.') ++pos; if (cid[pos] == '*') ++pos; if (cid[pos] == '-') { ++pos; sel.to_seqid = impl::parse_cid_seqid(cid, pos, INT_MAX); } sep = pos; } // atom; at[el]:aloc if (sep < cid.size()) { if (sep != 0 && cid[sep] != '/') fail("Invalid selection syntax: " + cid); size_t pos = (sep == 0 ? 0 : sep + 1); size_t end = cid.find_first_of("[:", pos); if (end != pos) sel.atom_names = impl::make_cid_list(cid, pos, end); if (end != std::string::npos) { if (cid[end] == '[') { pos = end + 1; end = cid.find(']', pos); sel.elements = impl::make_cid_list(cid, pos, end); sel.elements.list = to_upper(sel.elements.list); ++end; } if (cid[end] == ':') sel.altlocs = impl::make_cid_list(cid, end + 1, std::string::npos); else if (end < cid.length()) fail("Invalid selection syntax (after ']'): " + cid); } } return sel; } } // namespace gemmi #endif <commit_msg>refactor Selection<commit_after>// Copyright 2018 Global Phasing Ltd. // // Selections. #ifndef GEMMI_SELECT_HPP_ #define GEMMI_SELECT_HPP_ #include <string> #include <cstdlib> // for strtol #include <cctype> // for isalpha #include <climits> // for INT_MIN, INT_MAX #include "fail.hpp" // for fail #include "model.hpp" // for Model, Chain, etc #include "iterator.hpp" // for FilterProxy namespace gemmi { // from http://www.ccp4.ac.uk/html/pdbcur.html // Specification of the selection sets: // either // /mdl/chn/s1.i1-s2.i2/at[el]:aloc // or // /mdl/chn/*(res).ic/at[el]:aloc // struct Selection { struct List { bool all = true; bool inverted = false; std::string list; // comma-separated std::string str() const { if (all) return "*"; return inverted ? "!" + list : list; } // assumes that list.all is checked before this function is called bool has(const std::string& name) const { if (all) return true; bool found = is_in_list(name); return inverted ? !found : found; } private: // list is a comma separated string bool is_in_list(const std::string& name) const { if (name.length() >= list.length()) return name == list; for (size_t start=0, end=0; end != std::string::npos; start=end+1) { end = list.find(',', start); if (list.compare(start, end - start, name) == 0) return true; } return false; } }; struct SequenceId { int seqnum; char icode; std::string str() const { std::string s; if (seqnum != INT_MIN && seqnum != INT_MAX) s = std::to_string(seqnum); if (icode != '*') { s += '.'; if (icode != ' ') s += icode; } return s; } int compare(const SeqId& seqid) const { if (seqnum != *seqid.num) return seqnum < *seqid.num ? -1 : 1; if (icode != '*' && icode != seqid.icode) return icode < seqid.icode ? -1 : 1; return 0; } }; int mdl = 0; // 0 = all List chain_ids; SequenceId from_seqid = {INT_MIN, '*'}; SequenceId to_seqid = {INT_MAX, '*'}; List residue_names; List atom_names; List elements; List altlocs; std::string to_cid() const { std::string cid(1, '/'); if (mdl != 0) cid += std::to_string(mdl); cid += '/'; cid += chain_ids.str(); cid += '/'; cid += from_seqid.str(); if (!residue_names.all) { cid += residue_names.str(); } else { cid += '-'; cid += to_seqid.str(); } cid += '/'; cid += atom_names.str(); if (!elements.all) cid += "[" + elements.str() + "]"; if (!altlocs.all) cid += ":" + altlocs.str(); return cid; } bool matches(const gemmi::Model& model) const { return mdl == 0 || std::to_string(mdl) == model.name; } bool matches(const gemmi::Chain& chain) const { return chain_ids.has(chain.name); } bool matches(const gemmi::Residue& res) const { return residue_names.has(res.name) && from_seqid.compare(res.seqid) <= 0 && to_seqid.compare(res.seqid) >= 0; } bool matches(const gemmi::Atom& a) const { return atom_names.has(a.name) && elements.has(a.element.uname()) && altlocs.has(std::string(a.altloc ? 0 : 1, a.altloc)); } bool matches(const gemmi::CRA& cra) const { return (cra.chain == nullptr || matches(*cra.chain)) && (cra.residue == nullptr || matches(*cra.residue)) && (cra.atom == nullptr || matches(*cra.atom)); } FilterProxy<Selection, Model> models(Structure& st) const { return {*this, st.models}; } FilterProxy<Selection, Chain> chains(Model& model) const { return {*this, model.chains}; } FilterProxy<Selection, Residue> residues(Chain& chain) const { return {*this, chain.residues}; } FilterProxy<Selection, Atom> atoms(Residue& residue) const { return {*this, residue.atoms}; } CRA first_in_model(Model& model) const { if (matches(model)) for (Chain& chain : model.chains) { if (matches(chain)) for (Residue& res : chain.residues) { if (matches(res)) for (Atom& atom : res.atoms) { if (matches(atom)) return {&chain, &res, &atom}; } } } return {nullptr, nullptr, nullptr}; } std::pair<Model*, CRA> first(Structure& st) const { for (Model& model : st.models) { CRA cra = first_in_model(model); if (cra.chain) return {&model, cra}; } return {nullptr, {nullptr, nullptr, nullptr}}; } static Structure copy_empty(const Structure& orig) { Structure st(orig); st.models.clear(); // it may be inefficient return st; } static Model copy_empty(const Model& orig) { return Model(orig.name); } static Chain copy_empty(const Chain& orig) { return Chain(orig.name); } static Residue copy_empty(const Residue& orig) { Residue res((ResidueId&)orig); res.subchain = orig.subchain; res.label_seq = orig.label_seq; res.entity_type = orig.entity_type; res.het_flag = orig.het_flag; res.is_cis = orig.is_cis; res.flag = orig.flag; return res; } static Atom copy_empty(const Atom& orig) { return Atom(orig); } template<typename T> void add_matching_children(const T& orig, T& target) { for (const auto& orig_child : orig.children()) if (matches(orig_child)) { target.children().push_back(copy_empty(orig_child)); add_matching_children(orig_child, target.children().back()); } } void add_matching_children(const Atom&, Atom&) {} template<typename T> T copy_subset(const T& orig) { T copied = copy_empty(orig); add_matching_children(orig, copied); return copied; } }; namespace impl { int determine_omitted_cid_fields(const std::string& cid) { if (cid[0] == '/') return 0; // model if (std::isdigit(cid[0]) || cid[0] == '.' || cid[0] == '(' || cid[0] == '-') return 2; // residue size_t sep = cid.find_first_of("/(:["); if (sep == std::string::npos || cid[sep] == '/') return 1; // chain if (cid[sep] == '(') return 2; // residue return 3; // atom } Selection::List make_cid_list(const std::string& cid, size_t pos, size_t end) { Selection::List list; list.all = (cid[pos] == '*'); if (cid[pos] == '!') { list.inverted = true; ++pos; } list.list = cid.substr(pos, end - pos); return list; } Selection::SequenceId parse_cid_seqid(const std::string& cid, size_t& pos, int default_seqnum) { size_t initial_pos = pos; int seqnum = default_seqnum; char icode = ' '; if (cid[pos] == '*') { ++pos; icode = '*'; } else if (std::isdigit(cid[pos])) { char* endptr; seqnum = std::strtol(&cid[pos], &endptr, 10); pos = endptr - &cid[0]; } if (cid[pos] == '.') ++pos; if (initial_pos != pos && (std::isalpha(cid[pos]) || cid[pos] == '*')) icode = cid[pos++]; return {seqnum, icode}; } } // namespace impl inline Selection parse_cid(const std::string& cid) { Selection sel; if (cid.empty() || (cid.size() == 1 && cid[0] == '*')) return sel; int omit = impl::determine_omitted_cid_fields(cid); size_t sep = 0; // model if (omit == 0) { sep = cid.find('/', 1); if (sep != 1 && cid[1] != '*') { char* endptr; sel.mdl = std::strtol(&cid[1], &endptr, 10); size_t end_pos = endptr - &cid[0]; if (end_pos != sep && end_pos != cid.length()) fail("Expected model number first: " + cid); } } // chain if (omit <= 1 && sep != std::string::npos) { size_t pos = (sep == 0 ? 0 : sep + 1); sep = cid.find('/', pos); sel.chain_ids = impl::make_cid_list(cid, pos, sep); } // residue; MMDB CID syntax: s1.i1-s2.i2 or *(res).ic // In gemmi both 14.a and 14a are accepted. // *(ALA). and *(ALA) and (ALA). can be used instead of (ALA) for // compatibility with MMDB. if (omit <= 2 && sep != std::string::npos) { size_t pos = (sep == 0 ? 0 : sep + 1); if (cid[pos] != '(') sel.from_seqid = impl::parse_cid_seqid(cid, pos, INT_MIN); if (cid[pos] == '(') { ++pos; size_t right_br = cid.find(')', pos); sel.residue_names = impl::make_cid_list(cid, pos, right_br); pos = right_br + 1; } // allow "(RES)." and "(RES).*" and "(RES)*" if (cid[pos] == '.') ++pos; if (cid[pos] == '*') ++pos; if (cid[pos] == '-') { ++pos; sel.to_seqid = impl::parse_cid_seqid(cid, pos, INT_MAX); } sep = pos; } // atom; at[el]:aloc if (sep < cid.size()) { if (sep != 0 && cid[sep] != '/') fail("Invalid selection syntax: " + cid); size_t pos = (sep == 0 ? 0 : sep + 1); size_t end = cid.find_first_of("[:", pos); if (end != pos) sel.atom_names = impl::make_cid_list(cid, pos, end); if (end != std::string::npos) { if (cid[end] == '[') { pos = end + 1; end = cid.find(']', pos); sel.elements = impl::make_cid_list(cid, pos, end); sel.elements.list = to_upper(sel.elements.list); ++end; } if (cid[end] == ':') sel.altlocs = impl::make_cid_list(cid, end + 1, std::string::npos); else if (end < cid.length()) fail("Invalid selection syntax (after ']'): " + cid); } } return sel; } } // namespace gemmi #endif <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkPContingencyStatistics.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2011 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #if defined(_MSC_VER) #pragma warning (disable:4503) #endif #include "vtkToolkits.h" #include "vtkPOrderStatistics.h" #include "vtkCommunicator.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkMultiBlockDataSet.h" #include "vtkObjectFactory.h" #include "vtkMath.h" #include "vtkMultiProcessController.h" #include "vtkStringArray.h" #include "vtkTable.h" #include "vtkVariantArray.h" #include <vtkstd/map> #include <vtkstd/set> #include <vtkstd/vector> vtkStandardNewMacro(vtkPOrderStatistics); vtkCxxSetObjectMacro(vtkPOrderStatistics, Controller, vtkMultiProcessController); //----------------------------------------------------------------------------- vtkPOrderStatistics::vtkPOrderStatistics() { this->Controller = 0; this->SetController( vtkMultiProcessController::GetGlobalController() ); } //----------------------------------------------------------------------------- vtkPOrderStatistics::~vtkPOrderStatistics() { this->SetController( 0 ); } //----------------------------------------------------------------------------- void vtkPOrderStatistics::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Controller: " << this->Controller << endl; } //----------------------------------------------------------------------------- static void PackValues( const vtkstd::vector<vtkStdString>& values, vtkStdString& buffer ) { buffer.clear(); for( vtkstd::vector<vtkStdString>::const_iterator it = values.begin(); it != values.end(); ++ it ) { buffer.append( *it ); buffer.push_back( 0 ); } } //----------------------------------------------------------------------------- static void UnpackValues( const vtkStdString& buffer, vtkstd::vector<vtkStdString>& values ) { values.clear(); const char* const bufferEnd = &buffer[0] + buffer.size(); for( const char* start = &buffer[0]; start != bufferEnd; ++ start ) { for( const char* finish = start; finish != bufferEnd; ++ finish ) { if( ! *finish ) { values.push_back( vtkStdString( start ) ); start = finish; break; } } } } // ---------------------------------------------------------------------- void vtkPOrderStatistics::Learn( vtkTable* inData, vtkTable* inParameters, vtkMultiBlockDataSet* outMeta ) { if ( ! outMeta ) { return; } // First calculate order statistics on local data set this->Superclass::Learn( inData, inParameters, outMeta ); if ( ! outMeta || outMeta->GetNumberOfBlocks() < 1 ) { // No statistics were calculated. return; } // Make sure that parallel updates are needed, otherwise leave it at that. int np = this->Controller->GetNumberOfProcesses(); if ( np < 2 ) { return; } // Get ready for parallel calculations vtkCommunicator* com = this->Controller->GetCommunicator(); if ( ! com ) { vtkErrorMacro("No parallel communicator."); } // Figure local process id vtkIdType myRank = com->GetLocalProcessId(); // NB: Use process 0 as sole reducer for now vtkIdType rProc = 0; // Iterate over primary tables unsigned int nBlocks = outMeta->GetNumberOfBlocks(); for ( unsigned int b = 0; b < nBlocks; ++ b ) { // Fetch histogram table vtkTable* histoTab = vtkTable::SafeDownCast( outMeta->GetBlock( b ) ); if ( ! histoTab ) { continue; } // Downcast columns to typed arrays for efficient data access vtkAbstractArray* vals = histoTab->GetColumnByName( "Value" ); vtkIdTypeArray* card = vtkIdTypeArray::SafeDownCast( histoTab->GetColumnByName( "Cardinality" ) ); if ( ! vals || ! card ) { vtkErrorMacro("Column fetching error on process " << myRank << "."); return; } // Create new table for global histogram vtkTable* histoTab_g = vtkTable::New(); // Create column for global histogram cardinalities vtkIdTypeArray* card_g = vtkIdTypeArray::New(); card_g->SetName( "Cardinality" ); // Gather all histogram cardinalities on process rProc // NB: GatherV because the arrays have variable lengths if ( ! com->GatherV( card, card_g, rProc ) ) { vtkErrorMacro("Process " << com->GetLocalProcessId() << " could not gather histogram cardinalities."); return; } // Gather all histogram values on rProc and perform reduction of the global histogram table if ( vals->IsA("vtkDataArray") ) { // Downcast column to data array for subsequent typed message passing vtkDataArray* dVals = vtkDataArray::SafeDownCast( vals ); // Create column for global histogram values of the same type as the values vtkDataArray* dVals_g = vtkDataArray::CreateDataArray( dVals->GetDataType() ); dVals_g->SetName( "Value" ); // Gather all histogram values on process rProc // NB: GatherV because the arrays have variable lengths if ( ! com->GatherV( dVals, dVals_g, rProc ) ) { vtkErrorMacro("Process " << com->GetLocalProcessId() << " could not gather histogram values."); return; } // Reduce to global histogram table on process rProc if ( myRank == rProc ) { if ( this->Reduce( card_g, dVals_g ) ) { return; } } // if ( myRank == rProc ) // Finally broadcast reduced histogram values if ( ! com->Broadcast( dVals_g, rProc ) ) { vtkErrorMacro("Process " << com->GetLocalProcessId() << " could not broadcast reduced histogram values."); return; } // Add column of data values to histogram table histoTab_g->AddColumn( dVals_g ); // Clean up dVals_g->Delete(); // Finally broadcast reduced histogram cardinalities if ( ! com->Broadcast( card_g, rProc ) ) { vtkErrorMacro("Process " << com->GetLocalProcessId() << " could not broadcast reduced histogram cardinalities."); return; } } // if ( vals->IsA("vtkDataArray") ) else if ( vals->IsA("vtkStringArray") ) { // Downcast column to string array for subsequent typed message passing vtkStringArray* sVals = vtkStringArray::SafeDownCast( vals ); // Packing step: concatenate all string values vtkStdString sPack_l; if ( this->Pack( sVals, sPack_l ) ) { vtkErrorMacro("Packing error on process " << myRank << "."); return; } // (All) gather all string sizes vtkIdType nc_l = sPack_l.size(); vtkIdType* nc_g = new vtkIdType[np]; com->AllGather( &nc_l, nc_g, 1 ); // Calculate total size and displacement arrays vtkIdType* offsets = new vtkIdType[np]; vtkIdType ncTotal = 0; for ( vtkIdType i = 0; i < np; ++ i ) { offsets[i] = ncTotal; ncTotal += nc_g[i]; } // Allocate receive buffer on reducer process, based on the global size obtained above char* sPack_g = 0; if ( myRank == rProc ) { sPack_g = new char[ncTotal]; } // Create column for global histogram values of the same type as the values vtkStringArray* sVals_g = vtkStringArray::New(); sVals_g->SetName( "Value" ); // Gather all sPack on process rProc // NB: GatherV because the packets have variable lengths if ( ! com->GatherV( &(*sPack_l.begin()), sPack_g, nc_l, nc_g, offsets, rProc ) ) { vtkErrorMacro("Process " << myRank << "could not gather string values."); return; } // Reduce to global histogram on process rProc vtkstd::map<vtkStdString,vtkIdType> histogram; if ( myRank == rProc ) { if ( this->Reduce( card_g, ncTotal, sPack_g, histogram ) ) { return; } } // if ( myRank == rProc ) // Finally broadcast reduced histogram if ( this->Broadcast( histogram, card_g, sVals_g, rProc ) ) { vtkErrorMacro("Process " << com->GetLocalProcessId() << " could not broadcast reduced histogram values."); return; } // Add column of string values to histogram table histoTab_g->AddColumn( sVals_g ); // Clean up sVals_g->Delete(); } // else if ( vals->IsA("vtkStringArray") ) else if ( vals->IsA("vtkVariantArray") ) { vtkErrorMacro( "Unsupported data type (variant array) for column " << vals->GetName() << ". Ignoring it." ); return; } else { vtkErrorMacro( "Unsupported data type for column " << vals->GetName() << ". Ignoring it." ); return; } // Add column of cardinalities to histogram table histoTab_g->AddColumn( card_g ); if ( myRank == 1 ) { histoTab_g->Dump(); } // Replace local histogram table with globally reduced one outMeta->SetBlock( b, histoTab_g ); // Clean up card_g->Delete(); histoTab_g->Delete(); } // for ( unsigned int b = 0; b < nBlocks; ++ b ) } // ---------------------------------------------------------------------- bool vtkPOrderStatistics::Pack( vtkStringArray* sVals, vtkStdString& sPack ) { vtkstd::vector<vtkStdString> sVect; // consecutive strings vtkIdType nv = sVals->GetNumberOfValues(); for ( vtkIdType i = 0; i < nv; ++ i ) { // Push back current string value sVect.push_back( sVals->GetValue( i ) ); } // Concatenate vector of strings into single string PackValues( sVect, sPack ); return false; } //----------------------------------------------------------------------------- bool vtkPOrderStatistics::Reduce( vtkIdTypeArray* card_g, vtkDataArray* dVals_g ) { // Check consistency: we must have as many values as cardinality entries vtkIdType nRow_g = card_g->GetNumberOfTuples(); if ( dVals_g->GetNumberOfTuples() != nRow_g ) { vtkErrorMacro("Gathering error on process " << this->Controller->GetCommunicator()->GetLocalProcessId() << ": inconsistent number of values and cardinality entries: " << dVals_g->GetNumberOfTuples() << " <> " << nRow_g << "."); return true; } // Reduce to the global histogram table vtkstd::map<double,vtkIdType> histogram; double x; vtkIdType c; for ( vtkIdType r = 0; r < nRow_g; ++ r ) { // First, fetch value x = dVals_g->GetTuple1( r ); // Then, retrieve corresponding cardinality c = card_g->GetValue( r ); // Last, update histogram count for corresponding value histogram[x] += c; } // Now resize global histogram arrays to reduced size nRow_g = static_cast<vtkIdType>( histogram.size() ); dVals_g->SetNumberOfTuples( nRow_g ); card_g->SetNumberOfTuples( nRow_g ); // Then store reduced histogram into array vtkstd::map<double,vtkIdType>::iterator hit = histogram.begin(); for ( vtkIdType r = 0; r < nRow_g; ++ r, ++ hit ) { dVals_g->SetTuple1( r, hit->first ); card_g->SetValue( r, hit->second ); } return false; } //----------------------------------------------------------------------------- bool vtkPOrderStatistics::Reduce( vtkIdTypeArray* card_g, vtkIdType& ncTotal, char* sPack_g, vtkstd::map<vtkStdString,vtkIdType>& histogram ) { // First, unpack the packet of strings vtkstd::vector<vtkStdString> sVect_g; UnpackValues( vtkStdString ( sPack_g, ncTotal ), sVect_g ); // Second, check consistency: we must have as many values as cardinality entries vtkIdType nRow_g = card_g->GetNumberOfTuples(); if ( vtkIdType( sVect_g.size() ) != nRow_g ) { vtkErrorMacro("Gathering error on process " << this->Controller->GetCommunicator()->GetLocalProcessId() << ": inconsistent number of values and cardinality entries: " << sVect_g.size() << " <> " << nRow_g << "."); return true; } // Third, reduce to the global histogram vtkIdType c; vtkIdType i = 0; for ( vtkstd::vector<vtkStdString>::iterator vit = sVect_g.begin(); vit != sVect_g.end(); ++ vit , ++ i ) { // First, retrieve cardinality c = card_g->GetValue( i ); // Then, update histogram count for corresponding value histogram[*vit] += c; } return false; } // ---------------------------------------------------------------------- bool vtkPOrderStatistics::Broadcast( vtkstd::map<vtkStdString,vtkIdType>& histogram, vtkIdTypeArray* card, vtkStringArray* sVals, vtkIdType rProc ) { vtkCommunicator* com = this->Controller->GetCommunicator(); // Packing step: concatenate array of strings vtkStdString sPack; if ( this->Pack( sVals, sPack ) ) { vtkErrorMacro("Packing error on process " << com->GetLocalProcessId() << "."); return true; } // Broadcast size of string buffer vtkIdType nc = sPack.size(); if ( ! com->Broadcast( &nc, 1, rProc ) ) { vtkErrorMacro("Process " << com->GetLocalProcessId() << " could not broadcast size of string buffer."); return true; } // Resize string it can receive the broadcasted string buffer sPack.resize( nc ); // Broadcast histogram values if ( ! com->Broadcast( &(*sPack.begin()), nc, rProc ) ) { vtkErrorMacro("Process " << com->GetLocalProcessId() << " could not broadcast histogram string values."); return true; } // Unpack the packet of strings vtkstd::vector<vtkStdString> sVect; UnpackValues( sPack, sVect ); // Broadcast histogram cardinalities if ( ! com->Broadcast( card, rProc ) ) { vtkErrorMacro("Process " << com->GetLocalProcessId() << " could not broadcast histogram cardinalities."); return true; } // Now resize global histogram arrays to reduced size vtkIdType nRow = static_cast<vtkIdType>( histogram.size() ); sVals->SetNumberOfValues( nRow ); card->SetNumberOfTuples( nRow ); // Then store reduced histogram into array vtkstd::map<vtkStdString,vtkIdType>::iterator hit = histogram.begin(); for ( vtkIdType r = 0; r < nRow; ++ r, ++ hit ) { sVals->SetValue( r, hit->first ); card->SetValue( r, hit->second ); } return false; } <commit_msg>Fixed conceptual error resulting in subtle bug.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkPContingencyStatistics.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /*------------------------------------------------------------------------- Copyright 2011 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. -------------------------------------------------------------------------*/ #if defined(_MSC_VER) #pragma warning (disable:4503) #endif #include "vtkToolkits.h" #include "vtkPOrderStatistics.h" #include "vtkCommunicator.h" #include "vtkIdTypeArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkMultiBlockDataSet.h" #include "vtkObjectFactory.h" #include "vtkMath.h" #include "vtkMultiProcessController.h" #include "vtkStringArray.h" #include "vtkTable.h" #include "vtkVariantArray.h" #include <vtkstd/map> #include <vtkstd/set> #include <vtkstd/vector> vtkStandardNewMacro(vtkPOrderStatistics); vtkCxxSetObjectMacro(vtkPOrderStatistics, Controller, vtkMultiProcessController); //----------------------------------------------------------------------------- vtkPOrderStatistics::vtkPOrderStatistics() { this->Controller = 0; this->SetController( vtkMultiProcessController::GetGlobalController() ); } //----------------------------------------------------------------------------- vtkPOrderStatistics::~vtkPOrderStatistics() { this->SetController( 0 ); } //----------------------------------------------------------------------------- void vtkPOrderStatistics::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Controller: " << this->Controller << endl; } //----------------------------------------------------------------------------- static void PackStringVector( const vtkstd::vector<vtkStdString>& strings, vtkStdString& buffer ) { buffer.clear(); for( vtkstd::vector<vtkStdString>::const_iterator it = strings.begin(); it != strings.end(); ++ it ) { buffer.append( *it ); buffer.push_back( 0 ); } } //----------------------------------------------------------------------------- static void PackStringMap( const vtkstd::map<vtkStdString,vtkIdType>& strings, vtkStdString& buffer ) { buffer.clear(); for( vtkstd::map<vtkStdString,vtkIdType>::const_iterator it = strings.begin(); it != strings.end(); ++ it ) { buffer.append( it->first ); buffer.push_back( 0 ); } } //----------------------------------------------------------------------------- static void UnpackStringBuffer( const vtkStdString& buffer, vtkstd::vector<vtkStdString>& strings ) { strings.clear(); const char* const bufferEnd = &buffer[0] + buffer.size(); for( const char* start = &buffer[0]; start != bufferEnd; ++ start ) { for( const char* finish = start; finish != bufferEnd; ++ finish ) { if( ! *finish ) { strings.push_back( vtkStdString( start ) ); start = finish; break; } } } } // ---------------------------------------------------------------------- void vtkPOrderStatistics::Learn( vtkTable* inData, vtkTable* inParameters, vtkMultiBlockDataSet* outMeta ) { if ( ! outMeta ) { return; } // First calculate order statistics on local data set this->Superclass::Learn( inData, inParameters, outMeta ); if ( ! outMeta || outMeta->GetNumberOfBlocks() < 1 ) { // No statistics were calculated. return; } // Make sure that parallel updates are needed, otherwise leave it at that. int np = this->Controller->GetNumberOfProcesses(); if ( np < 2 ) { return; } // Get ready for parallel calculations vtkCommunicator* com = this->Controller->GetCommunicator(); if ( ! com ) { vtkErrorMacro("No parallel communicator."); } // Figure local process id vtkIdType myRank = com->GetLocalProcessId(); // NB: Use process 0 as sole reducer for now vtkIdType rProc = 0; // Iterate over primary tables unsigned int nBlocks = outMeta->GetNumberOfBlocks(); for ( unsigned int b = 0; b < nBlocks; ++ b ) { // Fetch histogram table vtkTable* histoTab = vtkTable::SafeDownCast( outMeta->GetBlock( b ) ); if ( ! histoTab ) { continue; } // Downcast columns to typed arrays for efficient data access vtkAbstractArray* vals = histoTab->GetColumnByName( "Value" ); vtkIdTypeArray* card = vtkIdTypeArray::SafeDownCast( histoTab->GetColumnByName( "Cardinality" ) ); if ( ! vals || ! card ) { vtkErrorMacro("Column fetching error on process " << myRank << "."); return; } // Create new table for global histogram vtkTable* histoTab_g = vtkTable::New(); // Create column for global histogram cardinalities vtkIdTypeArray* card_g = vtkIdTypeArray::New(); card_g->SetName( "Cardinality" ); // Gather all histogram cardinalities on process rProc // NB: GatherV because the arrays have variable lengths if ( ! com->GatherV( card, card_g, rProc ) ) { vtkErrorMacro("Process " << com->GetLocalProcessId() << " could not gather histogram cardinalities."); return; } // Gather all histogram values on rProc and perform reduction of the global histogram table if ( vals->IsA("vtkDataArray") ) { // Downcast column to data array for subsequent typed message passing vtkDataArray* dVals = vtkDataArray::SafeDownCast( vals ); // Create column for global histogram values of the same type as the values vtkDataArray* dVals_g = vtkDataArray::CreateDataArray( dVals->GetDataType() ); dVals_g->SetName( "Value" ); // Gather all histogram values on process rProc // NB: GatherV because the arrays have variable lengths if ( ! com->GatherV( dVals, dVals_g, rProc ) ) { vtkErrorMacro("Process " << com->GetLocalProcessId() << " could not gather histogram values."); return; } // Reduce to global histogram table on process rProc if ( myRank == rProc ) { if ( this->Reduce( card_g, dVals_g ) ) { return; } } // if ( myRank == rProc ) // Finally broadcast reduced histogram values if ( ! com->Broadcast( dVals_g, rProc ) ) { vtkErrorMacro("Process " << com->GetLocalProcessId() << " could not broadcast reduced histogram values."); return; } // Add column of data values to histogram table histoTab_g->AddColumn( dVals_g ); // Clean up dVals_g->Delete(); // Finally broadcast reduced histogram cardinalities if ( ! com->Broadcast( card_g, rProc ) ) { vtkErrorMacro("Process " << com->GetLocalProcessId() << " could not broadcast reduced histogram cardinalities."); return; } } // if ( vals->IsA("vtkDataArray") ) else if ( vals->IsA("vtkStringArray") ) { // Downcast column to string array for subsequent typed message passing vtkStringArray* sVals = vtkStringArray::SafeDownCast( vals ); // Packing step: concatenate all string values vtkStdString sPack_l; if ( this->Pack( sVals, sPack_l ) ) { vtkErrorMacro("Packing error on process " << myRank << "."); return; } // (All) gather all string sizes vtkIdType nc_l = sPack_l.size(); vtkIdType* nc_g = new vtkIdType[np]; com->AllGather( &nc_l, nc_g, 1 ); // Calculate total size and displacement arrays vtkIdType* offsets = new vtkIdType[np]; vtkIdType ncTotal = 0; for ( vtkIdType i = 0; i < np; ++ i ) { offsets[i] = ncTotal; ncTotal += nc_g[i]; } // Allocate receive buffer on reducer process, based on the global size obtained above char* sPack_g = 0; if ( myRank == rProc ) { sPack_g = new char[ncTotal]; } // Gather all sPack on process rProc // NB: GatherV because the packets have variable lengths if ( ! com->GatherV( &(*sPack_l.begin()), sPack_g, nc_l, nc_g, offsets, rProc ) ) { vtkErrorMacro("Process " << myRank << "could not gather string values."); return; } // Reduce to global histogram on process rProc vtkstd::map<vtkStdString,vtkIdType> histogram; if ( myRank == rProc ) { if ( this->Reduce( card_g, ncTotal, sPack_g, histogram ) ) { return; } } // if ( myRank == rProc ) // Create column for global histogram values of the same type as the values vtkStringArray* sVals_g = vtkStringArray::New(); sVals_g->SetName( "Value" ); // Finally broadcast reduced histogram if ( this->Broadcast( histogram, card_g, sVals_g, rProc ) ) { vtkErrorMacro("Process " << com->GetLocalProcessId() << " could not broadcast reduced histogram values."); return; } // Add column of string values to histogram table histoTab_g->AddColumn( sVals_g ); // Clean up sVals_g->Delete(); } // else if ( vals->IsA("vtkStringArray") ) else if ( vals->IsA("vtkVariantArray") ) { vtkErrorMacro( "Unsupported data type (variant array) for column " << vals->GetName() << ". Ignoring it." ); return; } else { vtkErrorMacro( "Unsupported data type for column " << vals->GetName() << ". Ignoring it." ); return; } // Add column of cardinalities to histogram table histoTab_g->AddColumn( card_g ); if ( myRank == 0 ) { histoTab_g->Dump(); } // Replace local histogram table with globally reduced one outMeta->SetBlock( b, histoTab_g ); // Clean up card_g->Delete(); histoTab_g->Delete(); } // for ( unsigned int b = 0; b < nBlocks; ++ b ) } // ---------------------------------------------------------------------- bool vtkPOrderStatistics::Pack( vtkStringArray* sVals, vtkStdString& sPack ) { vtkstd::vector<vtkStdString> sVect; // consecutive strings vtkIdType nv = sVals->GetNumberOfValues(); for ( vtkIdType i = 0; i < nv; ++ i ) { // Push back current string value sVect.push_back( sVals->GetValue( i ) ); } // Concatenate vector of strings into single string PackStringVector( sVect, sPack ); return false; } //----------------------------------------------------------------------------- bool vtkPOrderStatistics::Reduce( vtkIdTypeArray* card_g, vtkDataArray* dVals_g ) { // Check consistency: we must have as many values as cardinality entries vtkIdType nRow_g = card_g->GetNumberOfTuples(); if ( dVals_g->GetNumberOfTuples() != nRow_g ) { vtkErrorMacro("Gathering error on process " << this->Controller->GetCommunicator()->GetLocalProcessId() << ": inconsistent number of values and cardinality entries: " << dVals_g->GetNumberOfTuples() << " <> " << nRow_g << "."); return true; } // Reduce to the global histogram table vtkstd::map<double,vtkIdType> histogram; double x; vtkIdType c; for ( vtkIdType r = 0; r < nRow_g; ++ r ) { // First, fetch value x = dVals_g->GetTuple1( r ); // Then, retrieve corresponding cardinality c = card_g->GetValue( r ); // Last, update histogram count for corresponding value histogram[x] += c; } // Now resize global histogram arrays to reduced size nRow_g = static_cast<vtkIdType>( histogram.size() ); dVals_g->SetNumberOfTuples( nRow_g ); card_g->SetNumberOfTuples( nRow_g ); // Then store reduced histogram into array vtkstd::map<double,vtkIdType>::iterator hit = histogram.begin(); for ( vtkIdType r = 0; r < nRow_g; ++ r, ++ hit ) { dVals_g->SetTuple1( r, hit->first ); card_g->SetValue( r, hit->second ); } return false; } //----------------------------------------------------------------------------- bool vtkPOrderStatistics::Reduce( vtkIdTypeArray* card_g, vtkIdType& ncTotal, char* sPack_g, vtkstd::map<vtkStdString,vtkIdType>& histogram ) { // First, unpack the packet of strings vtkstd::vector<vtkStdString> sVect_g; UnpackStringBuffer( vtkStdString ( sPack_g, ncTotal ), sVect_g ); // Second, check consistency: we must have as many values as cardinality entries vtkIdType nRow_g = card_g->GetNumberOfTuples(); if ( vtkIdType( sVect_g.size() ) != nRow_g ) { vtkErrorMacro("Gathering error on process " << this->Controller->GetCommunicator()->GetLocalProcessId() << ": inconsistent number of values and cardinality entries: " << sVect_g.size() << " <> " << nRow_g << "."); return true; } // Third, reduce to the global histogram vtkIdType c; vtkIdType i = 0; for ( vtkstd::vector<vtkStdString>::iterator vit = sVect_g.begin(); vit != sVect_g.end(); ++ vit , ++ i ) { // First, retrieve cardinality c = card_g->GetValue( i ); // Then, update histogram count for corresponding value histogram[*vit] += c; } return false; } // ---------------------------------------------------------------------- bool vtkPOrderStatistics::Broadcast( vtkstd::map<vtkStdString,vtkIdType>& histogram, vtkIdTypeArray* card, vtkStringArray* sVals, vtkIdType rProc ) { vtkCommunicator* com = this->Controller->GetCommunicator(); // Concatenate string keys of histogram into single string vtkStdString sPack; PackStringMap( histogram, sPack ); // Broadcast size of string buffer vtkIdType nc = sPack.size(); if ( ! com->Broadcast( &nc, 1, rProc ) ) { vtkErrorMacro("Process " << com->GetLocalProcessId() << " could not broadcast size of string buffer."); return true; } // Resize string so it can receive the broadcasted string buffer sPack.resize( nc ); // Broadcast histogram values if ( ! com->Broadcast( &(*sPack.begin()), nc, rProc ) ) { vtkErrorMacro("Process " << com->GetLocalProcessId() << " could not broadcast histogram string values."); return true; } // Unpack the packet of strings vtkstd::vector<vtkStdString> sVect; UnpackStringBuffer( sPack, sVect ); // Broadcast histogram cardinalities if ( ! com->Broadcast( card, rProc ) ) { vtkErrorMacro("Process " << com->GetLocalProcessId() << " could not broadcast histogram cardinalities."); return true; } // Now resize global histogram arrays to reduced size vtkIdType nRow = static_cast<vtkIdType>( sVect.size() ); sVals->SetNumberOfValues( nRow ); card->SetNumberOfTuples( nRow ); // Then store reduced histogram into array vtkstd::vector<vtkStdString>::iterator vit = sVect.begin(); for ( vtkIdType r = 0; r < nRow; ++ r, ++ vit ) { sVals->SetValue( r, *vit ); } return false; } <|endoftext|>
<commit_before>// // Copyright (C) 2016 University of Amsterdam // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // #include "csvimporter_test.h" #include "csviterator.h" void CSVImporterTest::initTestCase() { } void CSVImporterTest::cleanupTestCase() { } void CSVImporterTest::init() { fe = new FileEvent(); dsp = new DataSetPackage(); asl = new AsyncLoader(); } void CSVImporterTest::cleanup() { // destroy all the objects created and delete the dataSet from the shared memory SharedMemory::deleteDataSet(dsp->dataSet); fe->~FileEvent(); dsp->~DataSetPackage(); asl->~AsyncLoader(); } void CSVImporterTest::csvTester_data() { QTest::addColumn<QString>("filename"); int count = 0; boost::filesystem::path p("test_files"); for (auto i = boost::filesystem::directory_iterator(p); i != boost::filesystem::directory_iterator(); i++) { if (!boost::filesystem::is_directory(i->path())) //we eliminate directories { QTest::newRow("csv file test") << QString::fromStdString(i->path().filename().string()); count++; } } } void CSVImporterTest::csvTester() { QFETCH(QString, filename); qDebug() << "filename: " << filename; QString full_path = QString("test_files/").append(filename); fe->setOperation(FileEvent::FileOpen); fe->setPath(full_path); asl->loadTask(fe, dsp); asl->_thread.quit(); columnIsNumeric.resize(dsp->dataSet->columnCount()); //set default column type as numeric for(int i=0; i<dsp->dataSet->columnCount(); ++i) { columnIsNumeric[i] = true; } struct fileContent fc; int error = readDataFromCSV(full_path, &fc); if(error == 1) //file could not be opened { QVERIFY(false); } bool ans = checkIfEqual(&fc); QVERIFY(ans); } /* checks if data read from file is same as the data stored in the shared memory */ bool CSVImporterTest::checkIfEqual(struct fileContent *fc) { if(fc->columns != dsp->dataSet->columnCount()) { qDebug() << "Column size mismatch"; return false; } if(fc->rows != dsp->dataSet->rowCount()) { qDebug() << "Row size mismatch" << QString::number(fc->rows) << " " << QString::number(dsp->dataSet->rowCount()); return false; } for(int i=0; i<fc->columns; ++i) { if(fc->headers[i] != dsp->dataSet->column(i).name()) { qDebug() << "Header name mismatch"; return false; } for(int j=0; j<fc->rows; ++j) { std::string currentWord = fc->data[j][i]; if(columnIsNumeric[i] && currentWord!= ".") { double temp = ::atof(currentWord.c_str()); currentWord = roundTo6Digits(temp, 6); } if(currentWord != dsp->dataSet->column(i)[j]) { qDebug() << "Data mismatch"; return false; } } } return true; } /* read data from the file specified from path and store it in the struct fileContent */ int CSVImporterTest::readDataFromCSV(QString path, struct fileContent *fc) { std::regex numeric_rgx("-?[0-9]+([.][0-9]+)?"); //regular expression for a numeric std::ifstream input(path.toStdString().c_str()); std::vector< std::vector<std::string> > fileRows; std::string currentWord; if(input.is_open()) { for(CSVIterator csvIter(input); csvIter != CSVIterator(); ++csvIter) { std::vector<std::string> tempRow; //has one row if((*csvIter).size() <=0) { continue; } for(int i=0; i<(*csvIter).size(); ++i) { currentWord = (*csvIter)[i]; if(currentWord == "") { currentWord = "."; } else { if(!fileRows.empty()) { if(columnIsNumeric[i]) { if(!(std::regex_match(currentWord, numeric_rgx))) //check if the currentWord is numeric { columnIsNumeric[i] = false; } } } } tempRow.push_back(currentWord); } fileRows.push_back(tempRow); tempRow.clear(); } fc->rows = fileRows.size() - 1; fc->columns = fileRows[0].size(); fc->headers = fileRows[0]; fileRows.erase(fileRows.begin()); fc->data = fileRows; return 0; } else { qDebug() << "Unable to open file"; return 1; } } std::string CSVImporterTest::roundTo6Digits(double x, int n) { char buff[32]; sprintf(buff, "%.*g", n, x); std::string cppString(buff); return cppString; } <commit_msg>minor changes<commit_after>// // Copyright (C) 2016 University of Amsterdam // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // (at your option) any later version. // // This program 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // #include "csvimporter_test.h" #include "csviterator.h" void CSVImporterTest::initTestCase() { } void CSVImporterTest::cleanupTestCase() { } void CSVImporterTest::init() { fe = new FileEvent(); dsp = new DataSetPackage(); asl = new AsyncLoader(); } void CSVImporterTest::cleanup() { // destroy all the objects created and delete the dataSet from the shared memory SharedMemory::deleteDataSet(dsp->dataSet); fe->~FileEvent(); dsp->~DataSetPackage(); asl->~AsyncLoader(); } void CSVImporterTest::csvTester_data() { QTest::addColumn<QString>("filename"); int count = 0; boost::filesystem::path p("test_files"); //add files to be tested in a folder "test_files" for (auto i = boost::filesystem::directory_iterator(p); i != boost::filesystem::directory_iterator(); i++) { if (!boost::filesystem::is_directory(i->path())) //we eliminate directories { QTest::newRow("csv file test") << QString::fromStdString(i->path().filename().string()); count++; } } } void CSVImporterTest::csvTester() { QFETCH(QString, filename); qDebug() << "filename: " << filename; QString full_path = QString("test_files/").append(filename); fe->setOperation(FileEvent::FileOpen); fe->setPath(full_path); asl->loadTask(fe, dsp); asl->_thread.quit(); columnIsNumeric.resize(dsp->dataSet->columnCount()); //set default column type as numeric for(int i=0; i<dsp->dataSet->columnCount(); ++i) { columnIsNumeric[i] = true; } struct fileContent fc; int error = readDataFromCSV(full_path, &fc); if(error == 1) //file could not be opened { QVERIFY(false); } else { bool ans = checkIfEqual(&fc); QVERIFY(ans); } } /* checks if data read from file is same as the data stored in the shared memory */ bool CSVImporterTest::checkIfEqual(struct fileContent *fc) { if(fc->columns != dsp->dataSet->columnCount()) { qDebug() << "Column size mismatch"; return false; } if(fc->rows != dsp->dataSet->rowCount()) { qDebug() << "Row size mismatch" << QString::number(fc->rows) << " " << QString::number(dsp->dataSet->rowCount()); return false; } for(int i=0; i<fc->columns; ++i) { if(fc->headers[i] != dsp->dataSet->column(i).name()) { qDebug() << "Header name mismatch"; return false; } for(int j=0; j<fc->rows; ++j) { std::string currentWord = fc->data[j][i]; if(columnIsNumeric[i] && currentWord!= ".") { double temp = ::atof(currentWord.c_str()); currentWord = roundTo6Digits(temp, 6); } if(currentWord != dsp->dataSet->column(i)[j]) { qDebug() << "Data mismatch"; return false; } } } return true; } /* read data from the file specified from path and store it in the struct fileContent */ int CSVImporterTest::readDataFromCSV(QString path, struct fileContent *fc) { std::regex numeric_rgx("-?[0-9]+([.][0-9]+)?"); //regular expression for a numeric std::ifstream input(path.toStdString().c_str()); std::vector< std::vector<std::string> > fileRows; std::string currentWord; if(input.is_open()) { for(CSVIterator csvIter(input); csvIter != CSVIterator(); ++csvIter) { std::vector<std::string> tempRow; //has one row if((*csvIter).size() <=0) { continue; } for(int i=0; i<(*csvIter).size(); ++i) { currentWord = (*csvIter)[i]; if(currentWord == "") { currentWord = "."; } else { if(!fileRows.empty()) { if(columnIsNumeric[i])//check if the column has strings that are non-nueric { if(!(std::regex_match(currentWord, numeric_rgx))) //check if the currentWord is numeric { columnIsNumeric[i] = false; } } } } tempRow.push_back(currentWord); } fileRows.push_back(tempRow); tempRow.clear(); } fc->rows = fileRows.size() - 1; fc->columns = fileRows[0].size(); fc->headers = fileRows[0]; fileRows.erase(fileRows.begin()); fc->data = fileRows; return 0; } else { qDebug() << "Unable to open file"; return 1; } } std::string CSVImporterTest::roundTo6Digits(double x, int n) { char buff[32]; sprintf(buff, "%.*g", n, x); std::string cppString(buff); return cppString; } <|endoftext|>
<commit_before> #include "../Flare.h" #include "FlareGameUserSettings.h" #include "FlareGame.h" #include "../Player/FlarePlayerController.h" /*---------------------------------------------------- Constructor ----------------------------------------------------*/ UFlareGameUserSettings::UFlareGameUserSettings(const class FObjectInitializer& PCIP) : Super(PCIP) { } void UFlareGameUserSettings::SetToDefaults() { Super::SetToDefaults(); // Graphics ScreenPercentage = 100; #if LINUX UseTemporalAA = false; #else UseTemporalAA = true; #endif UseMotionBlur = true; // Gameplay UseCockpit = true; UseAnticollision = false; PauseGameInMenus = false; MaxShipsInSector = 50; // Sound MusicVolume = 8; MasterVolume = 10; } void UFlareGameUserSettings::ApplySettings(bool bCheckForCommandLineOverrides) { FLOG("UFlareGameUserSettings::ApplySettings"); Super::ApplySettings(bCheckForCommandLineOverrides); SetUseTemporalAA(UseTemporalAA); SetScreenPercentage(ScreenPercentage); } void UFlareGameUserSettings::SetUseTemporalAA(bool NewSetting) { FLOGV("UFlareGameUserSettings::SetUseTemporalAA %d", NewSetting); UseTemporalAA = NewSetting; auto TemporalAACVar = IConsoleManager::Get().FindConsoleVariable(TEXT("r.DefaultFeature.AntiAliasing")); TemporalAACVar->Set(UseTemporalAA ? AAM_TemporalAA : AAM_FXAA, ECVF_SetByConsole); } void UFlareGameUserSettings::SetScreenPercentage(int32 NewScreenPercentage) { FLOGV("UFlareGameUserSettings::SetScreenPercentage %d", NewScreenPercentage); ScreenPercentage = NewScreenPercentage; auto ScreenPercentageCVar = IConsoleManager::Get().FindConsoleVariable(TEXT("r.ScreenPercentage")); ScreenPercentageCVar->Set(ScreenPercentage, ECVF_SetByConsole); } <commit_msg>Lowered default settings<commit_after> #include "../Flare.h" #include "FlareGameUserSettings.h" #include "FlareGame.h" #include "../Player/FlarePlayerController.h" /*---------------------------------------------------- Constructor ----------------------------------------------------*/ UFlareGameUserSettings::UFlareGameUserSettings(const class FObjectInitializer& PCIP) : Super(PCIP) { } void UFlareGameUserSettings::SetToDefaults() { Super::SetToDefaults(); // Graphics ScreenPercentage = 100; #if LINUX UseTemporalAA = false; #else UseTemporalAA = true; #endif UseMotionBlur = true; // Gameplay UseCockpit = true; UseAnticollision = false; PauseGameInMenus = false; MaxShipsInSector = 20; // Sound MusicVolume = 8; MasterVolume = 10; } void UFlareGameUserSettings::ApplySettings(bool bCheckForCommandLineOverrides) { FLOG("UFlareGameUserSettings::ApplySettings"); Super::ApplySettings(bCheckForCommandLineOverrides); SetUseTemporalAA(UseTemporalAA); SetScreenPercentage(ScreenPercentage); } void UFlareGameUserSettings::SetUseTemporalAA(bool NewSetting) { FLOGV("UFlareGameUserSettings::SetUseTemporalAA %d", NewSetting); UseTemporalAA = NewSetting; auto TemporalAACVar = IConsoleManager::Get().FindConsoleVariable(TEXT("r.DefaultFeature.AntiAliasing")); TemporalAACVar->Set(UseTemporalAA ? AAM_TemporalAA : AAM_FXAA, ECVF_SetByConsole); } void UFlareGameUserSettings::SetScreenPercentage(int32 NewScreenPercentage) { FLOGV("UFlareGameUserSettings::SetScreenPercentage %d", NewScreenPercentage); ScreenPercentage = NewScreenPercentage; auto ScreenPercentageCVar = IConsoleManager::Get().FindConsoleVariable(TEXT("r.ScreenPercentage")); ScreenPercentageCVar->Set(ScreenPercentage, ECVF_SetByConsole); } <|endoftext|>
<commit_before>#include "j1UIScene.h" #include "j1App.h" #include "j1Fonts.h" #include "UI_element.h" #include "UI_Button.h" #include "j1Input.h" #include "j1Render.h" j1UIScene::j1UIScene() { pausable = false; } j1UIScene::~j1UIScene() { } bool j1UIScene::Awake() { return true; } bool j1UIScene::Start() { _TTF_Font* text_font = App->font->Load("fonts/BMYEONSUNG.ttf", 50); SDL_Color text_color = { 229, 168, 61, 255 }; menu* mainMenu = new menu(INGAME_MENU); { UI_element* pause = App->gui->createButton(100, 100, NULL, { 0,148,281,111 }, { 281,148,281,111 }, { 562,148,281,111 }, this); pause->function = PAUSE; pause->dragable = true; UI_element* text = App->gui->createText("PAUSE", 200, 200, text_font, text_color); text->setOutlined(true); pause->appendChildAtCenter(text); text = App->gui->createText("IN GAME", 0, 0, text_font, text_color); text->setOutlined(true); mainMenu->elements.add(pause); mainMenu->elements.add(text); menus.add(mainMenu); } menu* testMenu = new menu(PAUSE_MENU); { UI_element* button = App->gui->createButton(300, 300, NULL, { 0,148,281,111 }, { 281,148,281,111 }, { 562,148,281,111 }, this); button->dragable = true; button->function = PAUSE; UI_element* test = App->gui->createText("RESUME", 200, 200, text_font, { 229, 168, 61, 255 }, this); test->setOutlined(true); button->appendChildAtCenter(test); test = App->gui->createText("PAUSE MENU", 0, 0, text_font, text_color); test->setOutlined(true); testMenu->elements.add(button); testMenu->elements.add(test); menus.add(testMenu); } current_menu = mainMenu; return true; } bool j1UIScene::PreUpdate() { return true; } bool j1UIScene::Update(float dt) { if (App->input->GetKey(SDL_SCANCODE_T) == KEY_DOWN) LoadMenu(PAUSE_MENU); return true; } bool j1UIScene::PostUpdate(float dt) { return true; } bool j1UIScene::OnUIEvent(UI_element* element, event_type event_type) { bool ret = true; if (event_type == MOUSE_ENTER) { element->state = MOUSEOVER; } else if (event_type == MOUSE_LEAVE) { element->state = STANDBY; } else if (event_type == MOUSE_LEFT_CLICK) { element->state = CLICKED; switch (element->function) { case NEW_GAME: break; case CONTINUE: break; case SETTINGS: LoadMenu(SETTINGS_MENU); break; case CREDITS: LoadMenu(CREDITS_MENU); break; case QUIT: ret = false; break; case PAUSE: if (App->paused) { App->paused = false; LoadMenu(INGAME_MENU); } else { App->paused = true; LoadMenu(PAUSE_MENU); } break; case RESTART: break; } } else if (event_type == MOUSE_LEFT_RELEASE) { if (element->state == CLICKED) element->state = MOUSEOVER; } else if (event_type == MOUSE_RIGHT_CLICK) { } else if (event_type == MOUSE_RIGHT_RELEASE) { } return ret; } bool j1UIScene::CleanUp() { p2List_item<menu*>* item; item = menus.start; while (item) { delete item->data; item = item->next; } menus.clear(); current_menu = nullptr; return true; } bool j1UIScene::LoadMenu(menu_id id) { bool ret = false; for (p2List_item<menu*>* item = menus.start; item; item = item->next) { if (item->data->id == id) { current_menu = item->data; ret = true; break; } } return ret; } <commit_msg>Added pause menu and main menu with all elements<commit_after>#include "j1UIScene.h" #include "j1App.h" #include "j1Fonts.h" #include "UI_element.h" #include "UI_Button.h" #include "UI_Image.h" #include "j1Input.h" #include "j1Render.h" j1UIScene::j1UIScene() { pausable = false; } j1UIScene::~j1UIScene() { } bool j1UIScene::Awake() { return true; } bool j1UIScene::Start() { _TTF_Font* big_buttons_font = App->font->Load("fonts/BMYEONSUNG.ttf", 50); SDL_Color big_buttons_color = { 229, 168, 61, 255 }; _TTF_Font* mid_buttons_font = App->font->Load("fonts/BMYEONSUNG.ttf", 30); SDL_Color mid_buttons_color = { 229, 168, 61, 255 }; menu* mainMenu = new menu(INGAME_MENU); { //TITLE UI_element* title_img = App->gui->createImageFromAtlas(179 * App->gui->UI_scale, 92 * App->gui->UI_scale, { 0, 0, 664,147 }, this); //NEW GAME UI_element* new_game = App->gui->createButton(372 * App->gui->UI_scale, 341 * App->gui->UI_scale, NULL, { 0,148,281,111 }, { 281,148,281,111 }, { 562,148,281,111 }, this); new_game->function = PAUSE; new_game->dragable = true; UI_element* new_text = App->gui->createText("NEW GAME", 200, 200, big_buttons_font, big_buttons_color); new_text->setOutlined(true); new_game->appendChildAtCenter(new_text); //CONTINUE GAME UI_element* continue_game = App->gui->createButton(372 * App->gui->UI_scale, 469 * App->gui->UI_scale, NULL, { 0,148,281,111 }, { 281,148,281,111 }, { 562,148,281,111 }, this); continue_game->dragable = true; UI_element* continue_text = App->gui->createText("CONTINUE", 200, 200, big_buttons_font, big_buttons_color); continue_text->setOutlined(true); continue_game->appendChildAtCenter(continue_text); //EXIT GAME UI_element* exit_game = App->gui->createButton(372 * App->gui->UI_scale, 595 * App->gui->UI_scale, NULL, { 0,148,281,111 }, { 281,148,281,111 }, { 562,148,281,111 }, this); exit_game->dragable = true; UI_element* exit_text = App->gui->createText("EXIT", 200, 200, big_buttons_font, big_buttons_color); exit_text->setOutlined(true); exit_game->appendChildAtCenter(exit_text); //CREDITS UI_element* credits = App->gui->createButton(31 * App->gui->UI_scale, 647 * App->gui->UI_scale, NULL, { 666,0,168,66 }, { 666,67,168,66 }, { 835,0,168,66 }, this); credits->dragable = true; UI_element* credits_text = App->gui->createText("CREDITS", 200, 200, mid_buttons_font, mid_buttons_color); credits_text->setOutlined(true); credits->appendChildAtCenter(credits_text); //SETTINGS UI_element* settings = App->gui->createButton(823 * App->gui->UI_scale, 647 * App->gui->UI_scale, NULL, { 666,0,168,66 }, { 666,67,168,66 }, { 835,0,168,66 }, this); settings->dragable = true; UI_element* settings_text = App->gui->createText("SETTINGS", 200, 200, mid_buttons_font, mid_buttons_color); settings_text->setOutlined(true); settings->appendChildAtCenter(settings_text); /*new_text = App->gui->createText("IN GAME", 0, 0, big_buttons_font, big_buttons_color); new_text->setOutlined(true);*/ mainMenu->elements.add(title_img); mainMenu->elements.add(new_game); mainMenu->elements.add(new_text); mainMenu->elements.add(continue_game); mainMenu->elements.add(continue_text); mainMenu->elements.add(exit_game); mainMenu->elements.add(exit_text); mainMenu->elements.add(credits); mainMenu->elements.add(credits_text); mainMenu->elements.add(settings); mainMenu->elements.add(settings_text); menus.add(mainMenu); } menu* pauseMenu = new menu(PAUSE_MENU); { //PAUSE BUTTON UI_element* pause_button = App->gui->createButton(947 * App->gui->UI_scale, 12 * App->gui->UI_scale, NULL, { 665,266,61,65 }, { 725,266,61,65 }, { 785,148,61,65 }, this); pause_button->dragable = true; pause_button->function = PAUSE; //WINDOW SDL_Texture* mid_window_tex = App->tex->Load("gui/medium_parchment.png"); UI_element* pause_window = App->gui->createImage(208 * App->gui->UI_scale, 182 * App->gui->UI_scale, mid_window_tex, this); pause_window->dragable = true; //SETTING CIRCLE BUTTON UI_element* settings_button = App->gui->createButton(275 * App->gui->UI_scale, 414 * App->gui->UI_scale, NULL, { 876,341,120,123 }, { 876,465,120,123 }, { 876,589,120,123 }, this); settings_button->dragable = true; pause_window->appendChild(275 * App->gui->UI_scale, 414 * App->gui->UI_scale, settings_button); //PLAY CIRCLE BUTTON UI_element* play_button = App->gui->createButton(439 * App->gui->UI_scale, 414 * App->gui->UI_scale, NULL, { 638,341,120,123 }, { 638,465,120,123 }, { 638,589,120,123 }, this); play_button->dragable = true; pause_window->appendChild(439 * App->gui->UI_scale, 414 * App->gui->UI_scale, play_button); //RESTART CIRCLE BUTTON UI_element* restart_button = App->gui->createButton(606 * App->gui->UI_scale, 414 * App->gui->UI_scale, NULL, { 757,341,120,123 }, { 757,465,120,123 }, { 757,589,120,123 }, this); restart_button->dragable = true; pause_window->appendChild(606 * App->gui->UI_scale, 414 * App->gui->UI_scale, restart_button); //SLIDER UI_element* slider = App->gui->createImageFromAtlas(248 * App->gui->UI_scale, 310 * App->gui->UI_scale, { 0, 321, 504, 53 }, this); slider->dragable = true; //test = App->gui->createText("PAUSE MENU", 0, 0, big_buttons_font, big_buttons_color); //test->setOutlined(true); pauseMenu->elements.add(pause_button); pauseMenu->elements.add(pause_window); pauseMenu->elements.add(settings_button); pauseMenu->elements.add(restart_button); pauseMenu->elements.add(play_button); pauseMenu->elements.add(slider); menus.add(pauseMenu); } current_menu = mainMenu; return true; } bool j1UIScene::PreUpdate() { return true; } bool j1UIScene::Update(float dt) { if (App->input->GetKey(SDL_SCANCODE_T) == KEY_DOWN) LoadMenu(PAUSE_MENU); return true; } bool j1UIScene::PostUpdate(float dt) { return true; } bool j1UIScene::OnUIEvent(UI_element* element, event_type event_type) { bool ret = true; if (event_type == MOUSE_ENTER) { element->state = MOUSEOVER; } else if (event_type == MOUSE_LEAVE) { element->state = STANDBY; } else if (event_type == MOUSE_LEFT_CLICK) { element->state = CLICKED; switch (element->function) { case NEW_GAME: break; case CONTINUE: break; case SETTINGS: LoadMenu(SETTINGS_MENU); break; case CREDITS: LoadMenu(CREDITS_MENU); break; case QUIT: ret = false; break; case PAUSE: if (App->paused) { App->paused = false; LoadMenu(INGAME_MENU); } else { App->paused = true; LoadMenu(PAUSE_MENU); } break; case RESTART: break; } } else if (event_type == MOUSE_LEFT_RELEASE) { if (element->state == CLICKED) element->state = MOUSEOVER; } else if (event_type == MOUSE_RIGHT_CLICK) { } else if (event_type == MOUSE_RIGHT_RELEASE) { } return ret; } bool j1UIScene::CleanUp() { p2List_item<menu*>* item; item = menus.start; while (item) { delete item->data; item = item->next; } menus.clear(); current_menu = nullptr; return true; } bool j1UIScene::LoadMenu(menu_id id) { bool ret = false; for (p2List_item<menu*>* item = menus.start; item; item = item->next) { if (item->data->id == id) { current_menu = item->data; ret = true; break; } } return ret; } <|endoftext|>
<commit_before>/* * Copyright (C) 2013 * Alessio Sclocco <a.sclocco@vu.nl> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <iostream> #include <string> #include <vector> #include <exception> #include <fstream> #include <iomanip> #include <limits> #include <cmath> using std::cout; using std::cerr; using std::endl; using std::string; using std::vector; using std::exception; using std::ofstream; using std::fixed; using std::setprecision; using std::numeric_limits; #include <ArgumentList.hpp> #include <Observation.hpp> #include <InitializeOpenCL.hpp> #include <CLData.hpp> #include <utils.hpp> #include <Folding.hpp> #include <Timer.hpp> using isa::utils::ArgumentList; using isa::utils::toStringValue; using isa::utils::Timer; using AstroData::Observation; using isa::OpenCL::initializeOpenCL; using isa::OpenCL::CLData; using PulsarSearch::Folding; typedef float dataType; const string typeName("float"); const unsigned int maxThreadsPerBlock = 1024; const unsigned int maxThreadsMultiplier = 512; const unsigned int maxItemsPerThread = 256; const unsigned int maxItemsMultiplier = 256; const unsigned int padding = 32; // Common parameters const unsigned int nrBeams = 1; const unsigned int nrStations = 64; // LOFAR /*const float minFreq = 138.965f; const float channelBandwidth = 0.195f; const unsigned int nrSamplesPerSecond = 200000; const unsigned int nrChannels = 32;*/ // Apertif const float minFreq = 1425.0f; const float channelBandwidth = 0.2929f; const unsigned int nrSamplesPerSecond = 20000; const unsigned int nrChannels = 1024; // Periods const unsigned int nrBins = 256; int main(int argc, char * argv[]) { unsigned int nrDMs = 0; unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; Observation< dataType > observation("FoldingTuning", typeName); CLData< dataType > * dedispersedData = new CLData< dataType >("DedispersedData", true); CLData< dataType > * foldedData = new CLData<dataType >("FoldedData", true); CLData< unsigned int > * counterData = new CLData< unsigned int >("CounterData", true); try { ArgumentList args(argc, argv); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); nrDMs = args.getSwitchArgument< unsigned int >("-dms"); } catch ( exception & err ) { cerr << err.what() << endl; return 1; } // Setup of the observation observation.setPadding(padding); observation.setNrSamplesPerSecond(nrSamplesPerSecond); observation.setNrDMs(nrDMs); observation.setFirstPeriod(nrBins); observation.setPeriodStep(nrBins); observation.setNrBins(nrBins); cl::Context * clContext = new cl::Context(); vector< cl::Platform > * clPlatforms = new vector< cl::Platform >(); vector< cl::Device > * clDevices = new vector< cl::Device >(); vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >(); initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); cout << fixed << endl; cout << "# nrDMs nrPeriods nrDMsPerBlock nrPeriodsPerBlock nrBinsPerBlock nrDMsPerThread nrPeriodsPerThread nrBinsPerThread GFLOP/s err time err" << endl << endl; for ( unsigned int nrPeriods = 2; nrPeriods <= 1024; nrPeriods *= 2 ) { observation.setNrPeriods(nrPeriods); // Allocate memory dedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs()); foldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods()); foldedData->blankHostData(); counterData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods()); counterData->blankHostData(); dedispersedData->setCLContext(clContext); dedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); foldedData->setCLContext(clContext); foldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); counterData->setCLContext(clContext); counterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); try { dedispersedData->allocateDeviceData(); foldedData->allocateDeviceData(); foldedData->copyHostToDevice(); counterData->allocateDeviceData(); counterData->copyHostToDevice(); } catch ( OpenCLError err ) { cerr << err.what() << endl; } // Find the parameters vector< unsigned int > DMsPerBlock; for ( unsigned int DMs = 2; DMs <= maxThreadsPerBlock; DMs++ ) { if ( (observation.getNrDMs() % DMs) == 0 ) { DMsPerBlock.push_back(DMs); } } for ( vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); DMs++ ) { for (unsigned int periodsPerBlock = 1; periodsPerBlock <= maxThreadsMultiplier; periodsPerBlock++ ) { if ( (*DMs * periodsPerBlock) > maxThreadsPerBlock ) { break; } else if ( (observation.getNrPeriods() % periodsPerBlock) != 0 ) { continue; } for ( unsigned int binsPerBlock = 1; binsPerBlock <= maxThreadsMultiplier; binsPerBlock++ ) { if ( (*DMs * periodsPerBlock * binsPerBlock) > maxThreadsPerBlock ) { break; } else if ( (observation.getNrBins() % binsPerBlock) != 0 ) { continue; } for ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItemsPerThread; DMsPerThread++ ) { if ( (observation.getNrDMs() % (*DMs * DMsPerThread)) != 0 ) { continue; } for ( unsigned int periodsPerThread = 1; periodsPerThread <= maxItemsPerThread; periodsPerThread++ ) { if ( (DMsPerThread * periodsPerThread) > maxItemsPerThread ) { break; } else if ( (observation.getNrPeriods() % (periodsPerBlock * periodsPerThread)) != 0 ) { continue; } for ( unsigned int binsPerThread = 1; binsPerThread <= maxItemsPerThread; binsPerThread++ ) { if ( (DMsPerThread * periodsPerThread * binsPerThread) > maxItemsPerThread ) { break; } else if ( (observation.getNrBins() % (binsPerBlock * binsPerThread)) != 0 ) { continue; } double Acur = 0.0; double Aold = 0.0; double Vcur = 0.0; double Vold = 0.0; try { // Generate kernel Folding< dataType > clFold("clFold", typeName); clFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0))); clFold.setObservation(&observation); clFold.setNrDMsPerBlock(*DMs); clFold.setNrPeriodsPerBlock(periodsPerBlock); clFold.setNrBinsPerBlock(binsPerBlock); clFold.setNrDMsPerThread(DMsPerThread); clFold.setNrPeriodsPerThread(periodsPerThread); clFold.setNrBinsPerThread(binsPerThread); clFold.generateCode(); clFold(dedispersedData, foldedData, counterData); (clFold.getTimer()).reset(); for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { clFold(dedispersedData, foldedData, counterData); if ( iteration == 0 ) { Acur = clFold.getGFLOP() / clFold.getTimer().getLastRunTime(); } else { Aold = Acur; Vold = Vcur; Acur = Aold + (((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Aold) / (iteration + 1)); Vcur = Vold + (((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Aold) * ((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Acur)); } } Vcur = sqrt(Vcur / nrIterations); cout << nrDMs << " " << nrPeriods << " " << *DMs << " " << periodsPerBlock << " " << binsPerBlock << " " << DMsPerThread << " " << periodsPerThread << " " << binsPerThread << " " << setprecision(3) << Acur << " " << Vcur << " " << setprecision(6) << clFold.getTimer().getAverageTime() << " " << clFold.getTimer().getStdDev() << endl; } catch ( OpenCLError err ) { cerr << err.what() << endl; continue; } } } } } } } cout << endl << endl; } cout << endl; return 0; } <commit_msg>It is possible to select the lower number of threads to start with during tuning.<commit_after>/* * Copyright (C) 2013 * Alessio Sclocco <a.sclocco@vu.nl> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include <iostream> #include <string> #include <vector> #include <exception> #include <fstream> #include <iomanip> #include <limits> #include <cmath> using std::cout; using std::cerr; using std::endl; using std::string; using std::vector; using std::exception; using std::ofstream; using std::fixed; using std::setprecision; using std::numeric_limits; #include <ArgumentList.hpp> #include <Observation.hpp> #include <InitializeOpenCL.hpp> #include <CLData.hpp> #include <utils.hpp> #include <Folding.hpp> #include <Timer.hpp> using isa::utils::ArgumentList; using isa::utils::toStringValue; using isa::utils::Timer; using AstroData::Observation; using isa::OpenCL::initializeOpenCL; using isa::OpenCL::CLData; using PulsarSearch::Folding; typedef float dataType; const string typeName("float"); const unsigned int maxThreadsPerBlock = 1024; const unsigned int maxThreadsMultiplier = 512; const unsigned int maxItemsPerThread = 256; const unsigned int maxItemsMultiplier = 256; const unsigned int padding = 32; // Common parameters const unsigned int nrBeams = 1; const unsigned int nrStations = 64; // LOFAR /*const float minFreq = 138.965f; const float channelBandwidth = 0.195f; const unsigned int nrSamplesPerSecond = 200000; const unsigned int nrChannels = 32;*/ // Apertif const float minFreq = 1425.0f; const float channelBandwidth = 0.2929f; const unsigned int nrSamplesPerSecond = 20000; const unsigned int nrChannels = 1024; // Periods const unsigned int nrBins = 256; int main(int argc, char * argv[]) { unsigned int nrDMs = 0; unsigned int lowerNrThreads = 0; unsigned int nrIterations = 0; unsigned int clPlatformID = 0; unsigned int clDeviceID = 0; Observation< dataType > observation("FoldingTuning", typeName); CLData< dataType > * dedispersedData = new CLData< dataType >("DedispersedData", true); CLData< dataType > * foldedData = new CLData<dataType >("FoldedData", true); CLData< unsigned int > * counterData = new CLData< unsigned int >("CounterData", true); try { ArgumentList args(argc, argv); clPlatformID = args.getSwitchArgument< unsigned int >("-opencl_platform"); clDeviceID = args.getSwitchArgument< unsigned int >("-opencl_device"); nrIterations = args.getSwitchArgument< unsigned int >("-iterations"); nrDMs = args.getSwitchArgument< unsigned int >("-dms"); lowerNrThreads = args.getSwitchArgument< unsigned int >("-lnt"); } catch ( exception & err ) { cerr << err.what() << endl; return 1; } // Setup of the observation observation.setPadding(padding); observation.setNrSamplesPerSecond(nrSamplesPerSecond); observation.setNrDMs(nrDMs); observation.setFirstPeriod(nrBins); observation.setPeriodStep(nrBins); observation.setNrBins(nrBins); cl::Context * clContext = new cl::Context(); vector< cl::Platform > * clPlatforms = new vector< cl::Platform >(); vector< cl::Device > * clDevices = new vector< cl::Device >(); vector< vector< cl::CommandQueue > > * clQueues = new vector< vector < cl::CommandQueue > >(); initializeOpenCL(clPlatformID, 1, clPlatforms, clContext, clDevices, clQueues); cout << fixed << endl; cout << "# nrDMs nrPeriods nrDMsPerBlock nrPeriodsPerBlock nrBinsPerBlock nrDMsPerThread nrPeriodsPerThread nrBinsPerThread GFLOP/s err time err" << endl << endl; for ( unsigned int nrPeriods = 2; nrPeriods <= 1024; nrPeriods *= 2 ) { observation.setNrPeriods(nrPeriods); // Allocate memory dedispersedData->allocateHostData(observation.getNrSamplesPerSecond() * observation.getNrPaddedDMs()); foldedData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods()); foldedData->blankHostData(); counterData->allocateHostData(observation.getNrPaddedDMs() * observation.getNrBins() * observation.getNrPeriods()); counterData->blankHostData(); dedispersedData->setCLContext(clContext); dedispersedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); foldedData->setCLContext(clContext); foldedData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); counterData->setCLContext(clContext); counterData->setCLQueue(&((clQueues->at(clDeviceID)).at(0))); try { dedispersedData->allocateDeviceData(); foldedData->allocateDeviceData(); foldedData->copyHostToDevice(); counterData->allocateDeviceData(); counterData->copyHostToDevice(); } catch ( OpenCLError err ) { cerr << err.what() << endl; } // Find the parameters vector< unsigned int > DMsPerBlock; for ( unsigned int DMs = lowerNrThreads; DMs <= maxThreadsPerBlock; DMs++ ) { if ( (observation.getNrDMs() % DMs) == 0 ) { DMsPerBlock.push_back(DMs); } } for ( vector< unsigned int >::iterator DMs = DMsPerBlock.begin(); DMs != DMsPerBlock.end(); DMs++ ) { for (unsigned int periodsPerBlock = 1; periodsPerBlock <= maxThreadsMultiplier; periodsPerBlock++ ) { if ( (*DMs * periodsPerBlock) > maxThreadsPerBlock ) { break; } else if ( (observation.getNrPeriods() % periodsPerBlock) != 0 ) { continue; } for ( unsigned int binsPerBlock = 1; binsPerBlock <= maxThreadsMultiplier; binsPerBlock++ ) { if ( (*DMs * periodsPerBlock * binsPerBlock) > maxThreadsPerBlock ) { break; } else if ( (observation.getNrBins() % binsPerBlock) != 0 ) { continue; } for ( unsigned int DMsPerThread = 1; DMsPerThread <= maxItemsPerThread; DMsPerThread++ ) { if ( (observation.getNrDMs() % (*DMs * DMsPerThread)) != 0 ) { continue; } for ( unsigned int periodsPerThread = 1; periodsPerThread <= maxItemsPerThread; periodsPerThread++ ) { if ( (DMsPerThread * periodsPerThread) > maxItemsPerThread ) { break; } else if ( (observation.getNrPeriods() % (periodsPerBlock * periodsPerThread)) != 0 ) { continue; } for ( unsigned int binsPerThread = 1; binsPerThread <= maxItemsPerThread; binsPerThread++ ) { if ( (DMsPerThread * periodsPerThread * binsPerThread) > maxItemsPerThread ) { break; } else if ( (observation.getNrBins() % (binsPerBlock * binsPerThread)) != 0 ) { continue; } double Acur = 0.0; double Aold = 0.0; double Vcur = 0.0; double Vold = 0.0; try { // Generate kernel Folding< dataType > clFold("clFold", typeName); clFold.bindOpenCL(clContext, &(clDevices->at(clDeviceID)), &((clQueues->at(clDeviceID)).at(0))); clFold.setObservation(&observation); clFold.setNrDMsPerBlock(*DMs); clFold.setNrPeriodsPerBlock(periodsPerBlock); clFold.setNrBinsPerBlock(binsPerBlock); clFold.setNrDMsPerThread(DMsPerThread); clFold.setNrPeriodsPerThread(periodsPerThread); clFold.setNrBinsPerThread(binsPerThread); clFold.generateCode(); clFold(dedispersedData, foldedData, counterData); (clFold.getTimer()).reset(); for ( unsigned int iteration = 0; iteration < nrIterations; iteration++ ) { clFold(dedispersedData, foldedData, counterData); if ( iteration == 0 ) { Acur = clFold.getGFLOP() / clFold.getTimer().getLastRunTime(); } else { Aold = Acur; Vold = Vcur; Acur = Aold + (((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Aold) / (iteration + 1)); Vcur = Vold + (((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Aold) * ((clFold.getGFLOP() / clFold.getTimer().getLastRunTime()) - Acur)); } } Vcur = sqrt(Vcur / nrIterations); cout << nrDMs << " " << nrPeriods << " " << *DMs << " " << periodsPerBlock << " " << binsPerBlock << " " << DMsPerThread << " " << periodsPerThread << " " << binsPerThread << " " << setprecision(3) << Acur << " " << Vcur << " " << setprecision(6) << clFold.getTimer().getAverageTime() << " " << clFold.getTimer().getStdDev() << endl; } catch ( OpenCLError err ) { cerr << err.what() << endl; continue; } } } } } } } cout << endl << endl; } cout << endl; return 0; } <|endoftext|>
<commit_before>/** String conversion definitions. * * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/stringconv instead. * * Copyright (c) 2000-2019, Jeroen T. Vermeulen. * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this mistake, * or contact the author. */ #ifndef PQXX_H_STRINGCONV #define PQXX_H_STRINGCONV #include "pqxx/compiler-public.hxx" #include <limits> #include <sstream> #include <stdexcept> namespace pqxx { /** * @defgroup stringconversion String conversion * * The PostgreSQL server accepts and represents data in string form. It has * its own formats for various data types. The string conversions define how * various C++ types translate to and from their respective PostgreSQL text * representations. * * Each conversion is defined by a specialisation of the @c string_traits * template. This template implements some basic functions to support the * conversion, ideally in both directions. * * If you need to convert a type which is not supported out of the box, define * your own @c string_traits specialisation for that type, similar to the ones * defined here. Any conversion code which "sees" your specialisation will now * support your conversion. In particular, you'll be able to read result * fields into a variable of the new type. * * There is a macro to help you define conversions for individual enumeration * types. The conversion will represent enumeration values as numeric strings. */ //@{ /// Traits class for use in string conversions /** Specialize this template for a type that you wish to add to_string and * from_string support for. */ template<typename T, typename = void> struct string_traits; namespace internal { /// Throw exception for attempt to convert null to given type. [[noreturn]] PQXX_LIBEXPORT void throw_null_conversion( const std::string &type); /// Give a human-readable name for a type, at compile time. /** Each instantiation contains a static member called @c value which is the * type's name, as a string. * * This template should not be around for long. C++14's variable templates * make it easier (eliminating the cumbersome struct) and C++20's introspection * should obviate it completely. */ template<typename TYPE> struct type_name; #define PQXX_DECLARE_TYPE_NAME(TYPE) \ template<> struct type_name<TYPE> \ { static constexpr const char *value = #TYPE; } PQXX_DECLARE_TYPE_NAME(bool); PQXX_DECLARE_TYPE_NAME(short); PQXX_DECLARE_TYPE_NAME(unsigned short); PQXX_DECLARE_TYPE_NAME(int); PQXX_DECLARE_TYPE_NAME(unsigned int); PQXX_DECLARE_TYPE_NAME(long); PQXX_DECLARE_TYPE_NAME(unsigned long); PQXX_DECLARE_TYPE_NAME(long long); PQXX_DECLARE_TYPE_NAME(unsigned long long); PQXX_DECLARE_TYPE_NAME(float); PQXX_DECLARE_TYPE_NAME(double); PQXX_DECLARE_TYPE_NAME(long double); PQXX_DECLARE_TYPE_NAME(char *); PQXX_DECLARE_TYPE_NAME(const char *); PQXX_DECLARE_TYPE_NAME(std::string); PQXX_DECLARE_TYPE_NAME(const std::string); PQXX_DECLARE_TYPE_NAME(std::stringstream); PQXX_DECLARE_TYPE_NAME(std::nullptr_t); #undef PQXX_DECLARE_TYPE_NAME template<size_t N> struct type_name<char[N]> { static constexpr const char *value = "char[]"; }; /// Helper: string traits implementation for built-in types. /** These types all look much alike, so they can share much of their traits * classes (though templatised, of course). * * The actual `to_string` and `from_string` are implemented in the library, * but the rest is defined inline. */ template<typename TYPE> struct PQXX_LIBEXPORT builtin_traits { static constexpr const char *name() noexcept { return internal::type_name<TYPE>::value; } static constexpr bool has_null() noexcept { return false; } static bool is_null(TYPE) { return false; } [[noreturn]] static TYPE null() { throw_null_conversion(name()); } static void from_string(const char Str[], TYPE &Obj); static std::string to_string(TYPE Obj); }; } // namespace pqxx::internal /// Helper: declare a string_traits specialisation for a builtin type. #define PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(TYPE) \ template<> struct PQXX_LIBEXPORT string_traits<TYPE> : \ internal::builtin_traits<TYPE> {}; PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(bool) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(short) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(unsigned short) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(int) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(unsigned int) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(long) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(unsigned long) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(long long) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(unsigned long long) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(float) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(double) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(long double) #undef PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION /// Helper class for defining enum conversions. /** The conversion will convert enum values to numeric strings, and vice versa. * * To define a string conversion for an enum type, derive a @c string_traits * specialisation for the enum from this struct. * * There's usually an easier way though: the @c PQXX_DECLARE_ENUM_CONVERSION * macro. Use @c enum_traits manually only if you need to customise your * traits type in more detail, e.g. if your enum has a "null" value built in. */ template<typename ENUM> struct enum_traits { using underlying_type = typename std::underlying_type<ENUM>::type; using underlying_traits = string_traits<underlying_type>; static constexpr bool has_null() noexcept { return false; } [[noreturn]] static ENUM null() { internal::throw_null_conversion("enum type"); } static void from_string(const char Str[], ENUM &Obj) { underlying_type tmp; underlying_traits::from_string(Str, tmp); Obj = ENUM(tmp); } static std::string to_string(ENUM Obj) { return underlying_traits::to_string(underlying_type(Obj)); } }; /// Macro: Define a string conversion for an enum type. /** This specialises the @c pqxx::string_traits template, so use it in the * @c ::pqxx namespace. * * For example: * * #include <iostream> * #include <pqxx/strconv> * enum X { xa, xb }; * namespace pqxx { PQXX_DECLARE_ENUM_CONVERSION(x); } * int main() { std::cout << to_string(xa) << std::endl; } */ #define PQXX_DECLARE_ENUM_CONVERSION(ENUM) \ template<> \ struct string_traits<ENUM> : pqxx::enum_traits<ENUM> \ { \ static constexpr const char *name() noexcept { return #ENUM; } \ [[noreturn]] static ENUM null() \ { internal::throw_null_conversion(name()); } \ } /// String traits for C-style string ("pointer to const char") template<> struct PQXX_LIBEXPORT string_traits<const char *> { static constexpr const char *name() noexcept { return "const char *"; } static constexpr bool has_null() noexcept { return true; } static bool is_null(const char *t) { return t == nullptr; } static const char *null() { return nullptr; } static void from_string(const char Str[], const char *&Obj) { Obj = Str; } static std::string to_string(const char *Obj) { return Obj; } }; /// String traits for non-const C-style string ("pointer to char") template<> struct PQXX_LIBEXPORT string_traits<char *> { static constexpr const char *name() noexcept { return "char *"; } static constexpr bool has_null() noexcept { return true; } static bool is_null(const char *t) { return t == nullptr; } static const char *null() { return nullptr; } // Don't allow this conversion since it breaks const-safety. // static void from_string(const char Str[], char *&Obj); static std::string to_string(char *Obj) { return Obj; } }; /// String traits for C-style string constant ("array of char") template<size_t N> struct PQXX_LIBEXPORT string_traits<char[N]> { static constexpr const char *name() noexcept { return "char[]"; } static constexpr bool has_null() noexcept { return true; } static bool is_null(const char t[]) { return t == nullptr; } static const char *null() { return nullptr; } static std::string to_string(const char Obj[]) { return Obj; } }; template<> struct PQXX_LIBEXPORT string_traits<std::string> { static constexpr const char *name() noexcept { return "string"; } static constexpr bool has_null() noexcept { return false; } static bool is_null(const std::string &) { return false; } [[noreturn]] static std::string null() { internal::throw_null_conversion(name()); } static void from_string(const char Str[], std::string &Obj) { Obj=Str; } static std::string to_string(const std::string &Obj) { return Obj; } }; template<> struct PQXX_LIBEXPORT string_traits<const std::string> { static constexpr const char *name() noexcept { return "const string"; } static constexpr bool has_null() noexcept { return false; } static bool is_null(const std::string &) { return false; } [[noreturn]] static const std::string null() { internal::throw_null_conversion(name()); } static const std::string to_string(const std::string &Obj) { return Obj; } }; template<> struct PQXX_LIBEXPORT string_traits<std::stringstream> { static constexpr const char *name() noexcept { return "stringstream"; } static constexpr bool has_null() noexcept { return false; } static bool is_null(const std::stringstream &) { return false; } [[noreturn]] static std::stringstream null() { internal::throw_null_conversion(name()); } static void from_string(const char Str[], std::stringstream &Obj) { Obj.clear(); Obj << Str; } static std::string to_string(const std::stringstream &Obj) { return Obj.str(); } }; /// Weird case: nullptr_t. We don't fully support it. template<> struct PQXX_LIBEXPORT string_traits<std::nullptr_t> { static constexpr const char *name() noexcept { return "nullptr_t"; } static constexpr bool has_null() noexcept { return true; } static std::nullptr_t null() { return nullptr; } static std::string to_string(const nullptr_t &) { return "null"; } }; // TODO: Implement date conversions. /// Attempt to convert postgres-generated string to given built-in type /** If the form of the value found in the string does not match the expected * type, e.g. if a decimal point is found when converting to an integer type, * the conversion fails. Overflows (e.g. converting "9999999999" to a 16-bit * C++ type) are also treated as errors. If in some cases this behaviour should * be inappropriate, convert to something bigger such as @c long @c int first * and then truncate the resulting value. * * Only the simplest possible conversions are supported. No fancy features * such as hexadecimal or octal, spurious signs, or exponent notation will work. * No whitespace is stripped away. Only the kinds of strings that come out of * PostgreSQL and out of to_string() can be converted. */ template<typename T> inline void from_string(const char Str[], T &Obj) { if (Str == nullptr) throw std::runtime_error{"Attempt to read null string."}; string_traits<T>::from_string(Str, Obj); } /// Conversion with known string length (for strings that may contain nuls) /** This is only used for strings, where embedded nul bytes should not determine * the end of the string. * * For all other types, this just uses the regular, nul-terminated version of * from_string(). */ template<typename T> inline void from_string(const char Str[], T &Obj, size_t) { return from_string(Str, Obj); } template<> inline void from_string<std::string>( //[t00] const char Str[], std::string &Obj, size_t len) { if (Str == nullptr) throw std::runtime_error{"Attempt to read null string."}; Obj.assign(Str, len); } template<typename T> inline void from_string(const std::string &Str, T &Obj) //[t45] { from_string(Str.c_str(), Obj); } template<typename T> inline void from_string(const std::stringstream &Str, T &Obj) //[t00] { from_string(Str.str(), Obj); } template<> inline void from_string(const std::string &Str, std::string &Obj) //[t46] { Obj = Str; } namespace internal { /// Compute numeric value of given textual digit (assuming that it is a digit) constexpr int digit_to_number(char c) noexcept { return c-'0'; } constexpr char number_to_digit(int i) noexcept { return static_cast<char>(i+'0'); } } // namespace pqxx::internal /// Convert built-in type to a readable string that PostgreSQL will understand /** No special formatting is done, and any locale settings are ignored. The * resulting string will be human-readable and in a format suitable for use in * SQL queries. */ template<typename T> inline std::string to_string(const T &Obj) { return string_traits<T>::to_string(Obj); } //@} } // namespace pqxx #endif <commit_msg>Compile fix.<commit_after>/** String conversion definitions. * * DO NOT INCLUDE THIS FILE DIRECTLY; include pqxx/stringconv instead. * * Copyright (c) 2000-2019, Jeroen T. Vermeulen. * * See COPYING for copyright license. If you did not receive a file called * COPYING with this source code, please notify the distributor of this mistake, * or contact the author. */ #ifndef PQXX_H_STRINGCONV #define PQXX_H_STRINGCONV #include "pqxx/compiler-public.hxx" #include <limits> #include <sstream> #include <stdexcept> namespace pqxx { /** * @defgroup stringconversion String conversion * * The PostgreSQL server accepts and represents data in string form. It has * its own formats for various data types. The string conversions define how * various C++ types translate to and from their respective PostgreSQL text * representations. * * Each conversion is defined by a specialisation of the @c string_traits * template. This template implements some basic functions to support the * conversion, ideally in both directions. * * If you need to convert a type which is not supported out of the box, define * your own @c string_traits specialisation for that type, similar to the ones * defined here. Any conversion code which "sees" your specialisation will now * support your conversion. In particular, you'll be able to read result * fields into a variable of the new type. * * There is a macro to help you define conversions for individual enumeration * types. The conversion will represent enumeration values as numeric strings. */ //@{ /// Traits class for use in string conversions /** Specialize this template for a type that you wish to add to_string and * from_string support for. */ template<typename T, typename = void> struct string_traits; namespace internal { /// Throw exception for attempt to convert null to given type. [[noreturn]] PQXX_LIBEXPORT void throw_null_conversion( const std::string &type); /// Give a human-readable name for a type, at compile time. /** Each instantiation contains a static member called @c value which is the * type's name, as a string. * * This template should not be around for long. C++14's variable templates * make it easier (eliminating the cumbersome struct) and C++20's introspection * should obviate it completely. */ template<typename TYPE> struct type_name; #define PQXX_DECLARE_TYPE_NAME(TYPE) \ template<> struct type_name<TYPE> \ { static constexpr const char *value = #TYPE; } PQXX_DECLARE_TYPE_NAME(bool); PQXX_DECLARE_TYPE_NAME(short); PQXX_DECLARE_TYPE_NAME(unsigned short); PQXX_DECLARE_TYPE_NAME(int); PQXX_DECLARE_TYPE_NAME(unsigned int); PQXX_DECLARE_TYPE_NAME(long); PQXX_DECLARE_TYPE_NAME(unsigned long); PQXX_DECLARE_TYPE_NAME(long long); PQXX_DECLARE_TYPE_NAME(unsigned long long); PQXX_DECLARE_TYPE_NAME(float); PQXX_DECLARE_TYPE_NAME(double); PQXX_DECLARE_TYPE_NAME(long double); PQXX_DECLARE_TYPE_NAME(char *); PQXX_DECLARE_TYPE_NAME(const char *); PQXX_DECLARE_TYPE_NAME(std::string); PQXX_DECLARE_TYPE_NAME(const std::string); PQXX_DECLARE_TYPE_NAME(std::stringstream); PQXX_DECLARE_TYPE_NAME(std::nullptr_t); #undef PQXX_DECLARE_TYPE_NAME template<size_t N> struct type_name<char[N]> { static constexpr const char *value = "char[]"; }; /// Helper: string traits implementation for built-in types. /** These types all look much alike, so they can share much of their traits * classes (though templatised, of course). * * The actual `to_string` and `from_string` are implemented in the library, * but the rest is defined inline. */ template<typename TYPE> struct PQXX_LIBEXPORT builtin_traits { static constexpr const char *name() noexcept { return internal::type_name<TYPE>::value; } static constexpr bool has_null() noexcept { return false; } static bool is_null(TYPE) { return false; } [[noreturn]] static TYPE null() { throw_null_conversion(name()); } static void from_string(const char Str[], TYPE &Obj); static std::string to_string(TYPE Obj); }; } // namespace pqxx::internal /// Helper: declare a string_traits specialisation for a builtin type. #define PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(TYPE) \ template<> struct PQXX_LIBEXPORT string_traits<TYPE> : \ internal::builtin_traits<TYPE> {}; PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(bool) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(short) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(unsigned short) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(int) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(unsigned int) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(long) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(unsigned long) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(long long) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(unsigned long long) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(float) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(double) PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION(long double) #undef PQXX_DECLARE_STRING_TRAITS_SPECIALIZATION /// Helper class for defining enum conversions. /** The conversion will convert enum values to numeric strings, and vice versa. * * To define a string conversion for an enum type, derive a @c string_traits * specialisation for the enum from this struct. * * There's usually an easier way though: the @c PQXX_DECLARE_ENUM_CONVERSION * macro. Use @c enum_traits manually only if you need to customise your * traits type in more detail, e.g. if your enum has a "null" value built in. */ template<typename ENUM> struct enum_traits { using underlying_type = typename std::underlying_type<ENUM>::type; using underlying_traits = string_traits<underlying_type>; static constexpr bool has_null() noexcept { return false; } [[noreturn]] static ENUM null() { internal::throw_null_conversion("enum type"); } static void from_string(const char Str[], ENUM &Obj) { underlying_type tmp; underlying_traits::from_string(Str, tmp); Obj = ENUM(tmp); } static std::string to_string(ENUM Obj) { return underlying_traits::to_string(underlying_type(Obj)); } }; /// Macro: Define a string conversion for an enum type. /** This specialises the @c pqxx::string_traits template, so use it in the * @c ::pqxx namespace. * * For example: * * #include <iostream> * #include <pqxx/strconv> * enum X { xa, xb }; * namespace pqxx { PQXX_DECLARE_ENUM_CONVERSION(x); } * int main() { std::cout << to_string(xa) << std::endl; } */ #define PQXX_DECLARE_ENUM_CONVERSION(ENUM) \ template<> \ struct string_traits<ENUM> : pqxx::enum_traits<ENUM> \ { \ static constexpr const char *name() noexcept { return #ENUM; } \ [[noreturn]] static ENUM null() \ { internal::throw_null_conversion(name()); } \ } /// String traits for C-style string ("pointer to const char") template<> struct PQXX_LIBEXPORT string_traits<const char *> { static constexpr const char *name() noexcept { return "const char *"; } static constexpr bool has_null() noexcept { return true; } static bool is_null(const char *t) { return t == nullptr; } static const char *null() { return nullptr; } static void from_string(const char Str[], const char *&Obj) { Obj = Str; } static std::string to_string(const char *Obj) { return Obj; } }; /// String traits for non-const C-style string ("pointer to char") template<> struct PQXX_LIBEXPORT string_traits<char *> { static constexpr const char *name() noexcept { return "char *"; } static constexpr bool has_null() noexcept { return true; } static bool is_null(const char *t) { return t == nullptr; } static const char *null() { return nullptr; } // Don't allow this conversion since it breaks const-safety. // static void from_string(const char Str[], char *&Obj); static std::string to_string(char *Obj) { return Obj; } }; /// String traits for C-style string constant ("array of char") template<size_t N> struct PQXX_LIBEXPORT string_traits<char[N]> { static constexpr const char *name() noexcept { return "char[]"; } static constexpr bool has_null() noexcept { return true; } static bool is_null(const char t[]) { return t == nullptr; } static const char *null() { return nullptr; } static std::string to_string(const char Obj[]) { return Obj; } }; template<> struct PQXX_LIBEXPORT string_traits<std::string> { static constexpr const char *name() noexcept { return "string"; } static constexpr bool has_null() noexcept { return false; } static bool is_null(const std::string &) { return false; } [[noreturn]] static std::string null() { internal::throw_null_conversion(name()); } static void from_string(const char Str[], std::string &Obj) { Obj=Str; } static std::string to_string(const std::string &Obj) { return Obj; } }; template<> struct PQXX_LIBEXPORT string_traits<const std::string> { static constexpr const char *name() noexcept { return "const string"; } static constexpr bool has_null() noexcept { return false; } static bool is_null(const std::string &) { return false; } [[noreturn]] static const std::string null() { internal::throw_null_conversion(name()); } static const std::string to_string(const std::string &Obj) { return Obj; } }; template<> struct PQXX_LIBEXPORT string_traits<std::stringstream> { static constexpr const char *name() noexcept { return "stringstream"; } static constexpr bool has_null() noexcept { return false; } static bool is_null(const std::stringstream &) { return false; } [[noreturn]] static std::stringstream null() { internal::throw_null_conversion(name()); } static void from_string(const char Str[], std::stringstream &Obj) { Obj.clear(); Obj << Str; } static std::string to_string(const std::stringstream &Obj) { return Obj.str(); } }; /// Weird case: nullptr_t. We don't fully support it. template<> struct PQXX_LIBEXPORT string_traits<std::nullptr_t> { static constexpr const char *name() noexcept { return "nullptr_t"; } static constexpr bool has_null() noexcept { return true; } static std::nullptr_t null() { return nullptr; } static std::string to_string(const std::nullptr_t &) { return "null"; } }; // TODO: Implement date conversions. /// Attempt to convert postgres-generated string to given built-in type /** If the form of the value found in the string does not match the expected * type, e.g. if a decimal point is found when converting to an integer type, * the conversion fails. Overflows (e.g. converting "9999999999" to a 16-bit * C++ type) are also treated as errors. If in some cases this behaviour should * be inappropriate, convert to something bigger such as @c long @c int first * and then truncate the resulting value. * * Only the simplest possible conversions are supported. No fancy features * such as hexadecimal or octal, spurious signs, or exponent notation will work. * No whitespace is stripped away. Only the kinds of strings that come out of * PostgreSQL and out of to_string() can be converted. */ template<typename T> inline void from_string(const char Str[], T &Obj) { if (Str == nullptr) throw std::runtime_error{"Attempt to read null string."}; string_traits<T>::from_string(Str, Obj); } /// Conversion with known string length (for strings that may contain nuls) /** This is only used for strings, where embedded nul bytes should not determine * the end of the string. * * For all other types, this just uses the regular, nul-terminated version of * from_string(). */ template<typename T> inline void from_string(const char Str[], T &Obj, size_t) { return from_string(Str, Obj); } template<> inline void from_string<std::string>( //[t00] const char Str[], std::string &Obj, size_t len) { if (Str == nullptr) throw std::runtime_error{"Attempt to read null string."}; Obj.assign(Str, len); } template<typename T> inline void from_string(const std::string &Str, T &Obj) //[t45] { from_string(Str.c_str(), Obj); } template<typename T> inline void from_string(const std::stringstream &Str, T &Obj) //[t00] { from_string(Str.str(), Obj); } template<> inline void from_string(const std::string &Str, std::string &Obj) //[t46] { Obj = Str; } namespace internal { /// Compute numeric value of given textual digit (assuming that it is a digit) constexpr int digit_to_number(char c) noexcept { return c-'0'; } constexpr char number_to_digit(int i) noexcept { return static_cast<char>(i+'0'); } } // namespace pqxx::internal /// Convert built-in type to a readable string that PostgreSQL will understand /** No special formatting is done, and any locale settings are ignored. The * resulting string will be human-readable and in a format suitable for use in * SQL queries. */ template<typename T> inline std::string to_string(const T &Obj) { return string_traits<T>::to_string(Obj); } //@} } // namespace pqxx #endif <|endoftext|>
<commit_before>#ifndef SIGMA_ENTITY_HPP #define SIGMA_ENTITY_HPP #include <sigma/config.hpp> #include <cinttypes> #include <functional> namespace sigma { struct SIGMA_API entity { entity() noexcept; entity(std::uint32_t index, std::uint32_t version) noexcept; bool operator==(entity o) const noexcept; bool operator!=(entity o) const noexcept; bool is_valid() const noexcept; std::uint32_t index; std::uint32_t version; }; } namespace std { template <> struct SIGMA_API hash<sigma::entity> { size_t operator()(const sigma::entity& e) const; }; } #endif // SIGMA_ENTITY_HPP <commit_msg>Added entity serialization.<commit_after>#ifndef SIGMA_ENTITY_HPP #define SIGMA_ENTITY_HPP #include <sigma/config.hpp> #include <cinttypes> #include <functional> namespace sigma { struct SIGMA_API entity { entity() noexcept; entity(std::uint32_t index, std::uint32_t version) noexcept; bool operator==(entity o) const noexcept; bool operator!=(entity o) const noexcept; bool is_valid() const noexcept; std::uint32_t index; std::uint32_t version; template <class Archive> void serialize(Archive& ar, const unsigned int version) { ar& index; ar& version; } }; } namespace std { template <> struct SIGMA_API hash<sigma::entity> { size_t operator()(const sigma::entity& e) const; }; } #endif // SIGMA_ENTITY_HPP <|endoftext|>
<commit_before>//===- LinalgTensorCodegenDriver.cpp - Linalg transformation driver--------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "PassDetail.h" #include "Passes.h" #include "Transforms.h" #include "mlir/Conversion/AffineToStandard/AffineToStandard.h" #include "mlir/Conversion/LinalgToLLVM/LinalgToLLVM.h" #include "mlir/Conversion/MemRefToLLVM/MemRefToLLVM.h" #include "mlir/Conversion/Passes.h" #include "mlir/Conversion/VectorToLLVM/ConvertVectorToLLVM.h" #include "mlir/Conversion/VectorToSCF/VectorToSCF.h" #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" #include "mlir/Dialect/Linalg/ComprehensiveBufferize/ComprehensiveBufferize.h" #include "mlir/Dialect/Linalg/IR/LinalgOps.h" #include "mlir/Dialect/Linalg/Passes.h" #include "mlir/Dialect/Linalg/Transforms/CodegenStrategy.h" #include "mlir/Dialect/Linalg/Transforms/Hoisting.h" #include "mlir/Dialect/Linalg/Transforms/Transforms.h" #include "mlir/Dialect/Linalg/Utils/Utils.h" #include "mlir/Dialect/MemRef/IR/MemRef.h" #include "mlir/Dialect/MemRef/Transforms/Passes.h" #include "mlir/Dialect/SCF/SCF.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/Dialect/Tensor/IR/Tensor.h" #include "mlir/Dialect/Vector/VectorTransforms.h" #include "mlir/IR/PatternMatch.h" #include "mlir/Pass/PassManager.h" #include "mlir/Transforms/GreedyPatternRewriteDriver.h" #include "mlir/Transforms/LoopUtils.h" #include "mlir/Transforms/Passes.h" using namespace mlir; using namespace mlir::linalg; namespace { struct LinalgTensorCodegenDriverPass : public LinalgTensorCodegenDriverBase<LinalgTensorCodegenDriverPass> { LinalgTensorCodegenDriverPass() = default; LinalgTensorCodegenDriverPass(const LinalgTensorCodegenDriverPass &pass) {} /// Function pass entry point. void runOnOperation() override; private: void fuseOutputIntoReduction(FuncOp funcOp); void fuseAll(FuncOp funcOp); void runOpAnchoredStrategy(FuncOp funcOp); void runComprehensiveBufferization(); void runVectorLowering(); void runLowerToLLVM(); void getDependentDialects(DialectRegistry &registry) const override; }; } // namespace void LinalgTensorCodegenDriverPass::runLowerToLLVM() { OpPassManager dynamicPM("builtin.module"); OpPassManager &nestedFuncOpPM = dynamicPM.nest<FuncOp>(); // This is a failsafe catchall, if it does something performance opportunities // have been missed previously. nestedFuncOpPM.addPass(createConvertVectorToSCFPass()); nestedFuncOpPM.addPass(createConvertLinalgToLoopsPass()); dynamicPM.addPass(createCanonicalizerPass()); dynamicPM.addPass(createLowerAffinePass()); dynamicPM.addPass(createLowerToCFGPass()); dynamicPM.addPass(createConvertLinalgToLLVMPass()); dynamicPM.addPass(createConvertVectorToLLVMPass( // clang-format off LowerVectorToLLVMOptions() .enableReassociateFPReductions(reassociateFPReductions) .enableIndexOptimizations(indexOptimizations) .enableArmNeon(armNeon) .enableArmSVE(armSVE) .enableAMX(amx) .enableX86Vector(x86Vector))); // clang-format on dynamicPM.addPass(createMemRefToLLVMPass()); dynamicPM.addPass(createLowerToLLVMPass()); dynamicPM.addPass(createCanonicalizerPass()); dynamicPM.addPass(createCSEPass()); if (failed(runPipeline(dynamicPM, getOperation()))) return signalPassFailure(); } /// Return the neutral element as a new Value. /// For now, just assume it is the zero of type. /// In the future, it should be the zero of type + op. static Value getNeutralOfLinalgOp(OpBuilder &b, OpOperand &op) { auto t = getElementTypeOrSelf(op.get().getType()); return b.create<ConstantOp>(op.getOwner()->getLoc(), t, b.getZeroAttr(t)); } /// Collect all Linalg ops, they must all have tensor semantics. /// For now this just fuses everything. // TODO: finer control. void LinalgTensorCodegenDriverPass::fuseAll(FuncOp funcOp) { SmallVector<LinalgOp> linalgOps; auto walkResult = funcOp.walk([&](LinalgOp op) { if (!op.hasTensorSemantics()) return WalkResult::interrupt(); linalgOps.push_back(op); return WalkResult::advance(); }); if (walkResult.wasInterrupted()) return signalPassFailure(); // Compute the tile sizes and the interchange. LinalgOp rootOp = linalgOps.back(); assert(tileSizes.size() >= rootOp.getNumLoops() && "expect one tile sizes per root op loop dimension"); assert(tileInterchange.empty() || tileInterchange.size() == tileSizes.size() && "expect the number of tile sizes and interchange dims to match"); SmallVector<int64_t> rootTileSizes(tileSizes.begin(), tileSizes.begin() + rootOp.getNumLoops()); SmallVector<int64_t> rootInterchange = tileInterchange.empty() ? llvm::to_vector<6>(llvm::seq<int64_t>(0, rootOp.getNumLoops())) : SmallVector<int64_t>( tileInterchange.begin(), tileInterchange.begin() + rootOp.getNumLoops()); // Tile the root operation and fuse it with its producers. OpBuilder b(funcOp.getContext()); FailureOr<TileLoopNest> tileLoopNest = tileConsumerAndFuseProducers(b, rootOp, rootTileSizes, rootInterchange); if (failed(tileLoopNest)) return signalPassFailure(); rootOp->replaceAllUsesWith(tileLoopNest->getRootOpReplacementResults()); } void LinalgTensorCodegenDriverPass::fuseOutputIntoReduction(FuncOp funcOp) { LinalgTilingOptions tiling_options; tiling_options.setTileSizes(tileSizes); auto *context = funcOp.getContext(); auto patterns = mlir::linalg::getLinalgTilingCanonicalizationPatterns(context); mlir::memref::populateResolveRankedShapeTypeResultDimsPatterns(patterns); populateFuseFillIntoReductionPatterns(patterns, tiling_options); (void)mlir::applyPatternsAndFoldGreedily(funcOp, std::move(patterns)); // Ensure we drop the marker in the end. funcOp.walk([](mlir::linalg::LinalgOp op) { op->removeAttr(mlir::linalg::LinalgTransforms::kLinalgTransformMarker); }); } void LinalgTensorCodegenDriverPass::runOpAnchoredStrategy(FuncOp funcOp) { if (anchorOpName.empty()) return; if (fuse) return fuseAll(funcOp); if (fuseFillIntoReduction) return fuseOutputIntoReduction(funcOp); // Set up tiling and vectorization options. LinalgTilingOptions tilingOptions; if (!tileSizes.empty()) tilingOptions = tilingOptions.setTileSizes(tileSizes); if (!tileInterchange.empty()) tilingOptions = tilingOptions.setInterchange( SmallVector<unsigned>(tileInterchange.begin(), tileInterchange.end())); if (scalarizeDynamicDims) tilingOptions = tilingOptions.scalarizeDynamicDims(); tilingOptions = tilingOptions.setPeeledLoops(peeledLoops); // Set up padding options. // TODO: Replace the lambdas by either functions defined in MLIR core or even // adapt the LinalgPaddingOptions to take the `hoistPaddings` and // `packPaddings` arrays directly. auto packFunc = [&](OpOperand &opOperand) { return opOperand.getOperandNumber() < packPaddings.size() ? packPaddings[opOperand.getOperandNumber()] : false; }; auto hoistingFunc = [&](OpOperand &opOperand) { return opOperand.getOperandNumber() < hoistPaddings.size() ? hoistPaddings[opOperand.getOperandNumber()] : 0; }; LinalgPaddingOptions paddingOptions; paddingOptions.setPaddingValueComputationFunction(getNeutralOfLinalgOp); paddingOptions.setPaddingNoFoldComputationFunction(packFunc); paddingOptions.setPaddingHoistComputationFunction(hoistingFunc); CodegenStrategy strategy; StringRef genericOpName = GenericOp::getOperationName(); strategy .tileIf(!tileSizes.empty() || scalarizeDynamicDims, anchorOpName, tilingOptions) .padIf(pad, anchorOpName, paddingOptions) .generalizeIf(generalize, anchorOpName) .interchangeIf(!iteratorInterchange.empty(), iteratorInterchange) .vectorizeIf(vectorize, generalize ? genericOpName : anchorOpName); // Created a nested OpPassManager and run. OpPassManager dynamicPM("builtin.func"); strategy.configurePassPipeline(dynamicPM, funcOp.getContext()); if (failed(runPipeline(dynamicPM, funcOp))) return signalPassFailure(); } void LinalgTensorCodegenDriverPass::runComprehensiveBufferization() { OpPassManager dynamicPM("builtin.module"); dynamicPM.addPass(createCanonicalizerPass()); dynamicPM.addPass(createCSEPass()); dynamicPM.addPass(createLinalgComprehensiveModuleBufferizePass()); if (failed(runPipeline(dynamicPM, getOperation()))) return signalPassFailure(); } void LinalgTensorCodegenDriverPass::runVectorLowering() { vector::VectorTransposeLowering vectorTransposeLowering = llvm::StringSwitch<vector::VectorTransposeLowering>( lowerVectorTransposeTo.getValue()) .Case("eltwise", vector::VectorTransposeLowering::EltWise) .Case("flat_transpose", vector::VectorTransposeLowering::Flat) .Case("shuffle", vector::VectorTransposeLowering::Shuffle) .Default(vector::VectorTransposeLowering::EltWise); vector::VectorMultiReductionLowering vectorMultiReductionLowering = llvm::StringSwitch<vector::VectorMultiReductionLowering>( lowerVectorMultiReductionTo.getValue()) .Case("innerreduction", vector::VectorMultiReductionLowering::InnerReduction) .Default(vector::VectorMultiReductionLowering::InnerParallel); vector::VectorContractLowering vectorContractLowering = llvm::StringSwitch<vector::VectorContractLowering>( lowerVectorContractionTo.getValue()) .Case("matrixintrinsics", vector::VectorContractLowering::Matmul) .Case("dot", vector::VectorContractLowering::Dot) .Case("outerproduct", vector::VectorContractLowering::OuterProduct) .Default(vector::VectorContractLowering::OuterProduct); vector::VectorTransferSplit vectorTransferSplit = llvm::StringSwitch<vector::VectorTransferSplit>( splitVectorTransfersTo.getValue()) .Case("none", vector::VectorTransferSplit::None) .Case("linalg-copy", vector::VectorTransferSplit::LinalgCopy) .Case("vector-transfers", vector::VectorTransferSplit::VectorTransfer) .Default(vector::VectorTransferSplit::None); // Per-function lowering pipeline. getOperation().walk([&](FuncOp funcOp) { CodegenStrategy strategy; strategy.vectorLowering( LinalgVectorLoweringOptions() // Lowering of vector contractions. .enableContractionLowering(vectorLoweringStage >= 0) // Lowering of vector multi_reduction. .enableMultiReductionLowering(vectorLoweringStage >= 1) // Whether to split full/partial vector.transfer ops. .enableTransferPartialRewrite(vectorLoweringStage >= 2 && vectorTransferSplit != vector::VectorTransferSplit::None) // Set the maximum vector load / store rank. .setMaxTransferRank(maxTransferRank) // Lower vector.transfer to vector.transfer of max rank. .enableTransferLowering(vectorLoweringStage >= 3) // Conversion to scf. .enableTransferToSCFConversion(vectorLoweringStage >= 4) .setVectorTransferToSCFOptions( VectorTransferToSCFOptions() .enableFullUnroll(unrollVectorTransfers) .enableLowerPermutationMaps()) // Lowering of vector.shape_cast. .enableShapeCastLowering(vectorLoweringStage >= 5) // Lowering of vector.transpose. .enableVectorTransposeLowering(vectorLoweringStage >= 6) .setVectorTransformsOptions( vector::VectorTransformsOptions() .setVectorTransposeLowering(vectorTransposeLowering) .setVectorTransformsOptions(vectorContractLowering) .setVectorMultiReductionLowering( vectorMultiReductionLowering) .setVectorTransferSplit(vectorTransferSplit))); // Created a nested OpPassManager and run. OpPassManager dynamicPM("builtin.func"); strategy.configurePassPipeline(dynamicPM, funcOp.getContext()); if (failed(runPipeline(dynamicPM, funcOp))) return signalPassFailure(); }); } void LinalgTensorCodegenDriverPass::runOnOperation() { if (!anchorFuncOpName.empty()) { getOperation().walk([&](FuncOp funcOp) { if (funcOp.getName() != anchorFuncOpName) return; // Run transforms that require anchoring on a particular op. This only // applies if !anchorOpName.empty(). runOpAnchoredStrategy(funcOp); if (vectorizePadding) { OwningRewritePatternList extraVectorizationPatterns( funcOp.getContext()); populatePadTensorOpVectorizationPatterns(extraVectorizationPatterns); (void)applyPatternsAndFoldGreedily( funcOp, std::move(extraVectorizationPatterns)); } }); } if (bufferize) { runComprehensiveBufferization(); // Perform buffer-level hoistings. getOperation().walk( [&](FuncOp funcOp) { hoistRedundantVectorTransfers(funcOp); }); } if (vectorLowering) runVectorLowering(); if (llvmLowering) runLowerToLLVM(); } /// Return the dialect that must be loaded in the context before this pass. void LinalgTensorCodegenDriverPass::getDependentDialects( DialectRegistry &registry) const { registry.insert<arith::ArithmeticDialect>(); registry.insert<AffineDialect>(); registry.insert<linalg::LinalgDialect>(); registry.insert<memref::MemRefDialect>(); registry.insert<scf::SCFDialect>(); registry.insert<StandardOpsDialect>(); registry.insert<tensor::TensorDialect>(); registry.insert<vector::VectorDialect>(); registerBufferizableOpInterfaceExternalModels(registry); } std::unique_ptr<OperationPass<ModuleOp>> mlir::createLinalgTensorCodegenDriverPass() { return std::make_unique<LinalgTensorCodegenDriverPass>(); } <commit_msg>Integrate LLVM at llvm/llvm-project@161755770a44<commit_after>//===- LinalgTensorCodegenDriver.cpp - Linalg transformation driver--------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "PassDetail.h" #include "Passes.h" #include "Transforms.h" #include "mlir/Conversion/AffineToStandard/AffineToStandard.h" #include "mlir/Conversion/LinalgToLLVM/LinalgToLLVM.h" #include "mlir/Conversion/MemRefToLLVM/MemRefToLLVM.h" #include "mlir/Conversion/Passes.h" #include "mlir/Conversion/VectorToLLVM/ConvertVectorToLLVM.h" #include "mlir/Conversion/VectorToSCF/VectorToSCF.h" #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" #include "mlir/Dialect/Linalg/ComprehensiveBufferize/ComprehensiveBufferize.h" #include "mlir/Dialect/Linalg/IR/LinalgOps.h" #include "mlir/Dialect/Linalg/Passes.h" #include "mlir/Dialect/Linalg/Transforms/CodegenStrategy.h" #include "mlir/Dialect/Linalg/Transforms/Hoisting.h" #include "mlir/Dialect/Linalg/Transforms/Transforms.h" #include "mlir/Dialect/Linalg/Utils/Utils.h" #include "mlir/Dialect/MemRef/IR/MemRef.h" #include "mlir/Dialect/MemRef/Transforms/Passes.h" #include "mlir/Dialect/SCF/SCF.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/Dialect/Tensor/IR/Tensor.h" #include "mlir/Dialect/Vector/VectorTransforms.h" #include "mlir/IR/PatternMatch.h" #include "mlir/Pass/PassManager.h" #include "mlir/Transforms/GreedyPatternRewriteDriver.h" #include "mlir/Transforms/LoopUtils.h" #include "mlir/Transforms/Passes.h" using namespace mlir; using namespace mlir::linalg; namespace { struct LinalgTensorCodegenDriverPass : public LinalgTensorCodegenDriverBase<LinalgTensorCodegenDriverPass> { LinalgTensorCodegenDriverPass() = default; LinalgTensorCodegenDriverPass(const LinalgTensorCodegenDriverPass &pass) {} /// Function pass entry point. void runOnOperation() override; private: void fuseOutputIntoReduction(FuncOp funcOp); void fuseAll(FuncOp funcOp); void runOpAnchoredStrategy(FuncOp funcOp); void runComprehensiveBufferization(); void runVectorLowering(); void runLowerToLLVM(); void getDependentDialects(DialectRegistry &registry) const override; }; } // namespace void LinalgTensorCodegenDriverPass::runLowerToLLVM() { OpPassManager dynamicPM("builtin.module"); OpPassManager &nestedFuncOpPM = dynamicPM.nest<FuncOp>(); // This is a failsafe catchall, if it does something performance opportunities // have been missed previously. nestedFuncOpPM.addPass(createConvertVectorToSCFPass()); nestedFuncOpPM.addPass(createConvertLinalgToLoopsPass()); dynamicPM.addPass(createCanonicalizerPass()); dynamicPM.addPass(createLowerAffinePass()); dynamicPM.addPass(createLowerToCFGPass()); dynamicPM.addPass(createConvertLinalgToLLVMPass()); dynamicPM.addPass(createConvertVectorToLLVMPass( // clang-format off LowerVectorToLLVMOptions() .enableReassociateFPReductions(reassociateFPReductions) .enableIndexOptimizations(indexOptimizations) .enableArmNeon(armNeon) .enableArmSVE(armSVE) .enableAMX(amx) .enableX86Vector(x86Vector))); // clang-format on dynamicPM.addPass(createMemRefToLLVMPass()); dynamicPM.addPass(createLowerToLLVMPass()); dynamicPM.addPass(createCanonicalizerPass()); dynamicPM.addPass(createCSEPass()); if (failed(runPipeline(dynamicPM, getOperation()))) return signalPassFailure(); } /// Return the neutral element as a new Value. /// For now, just assume it is the zero of type. /// In the future, it should be the zero of type + op. static Value getNeutralOfLinalgOp(OpBuilder &b, OpOperand &op) { auto t = getElementTypeOrSelf(op.get().getType()); return b.create<ConstantOp>(op.getOwner()->getLoc(), t, b.getZeroAttr(t)); } /// Collect all Linalg ops, they must all have tensor semantics. /// For now this just fuses everything. // TODO: finer control. void LinalgTensorCodegenDriverPass::fuseAll(FuncOp funcOp) { SmallVector<LinalgOp> linalgOps; auto walkResult = funcOp.walk([&](LinalgOp op) { if (!op.hasTensorSemantics()) return WalkResult::interrupt(); linalgOps.push_back(op); return WalkResult::advance(); }); if (walkResult.wasInterrupted()) return signalPassFailure(); // Compute the tile sizes and the interchange. LinalgOp rootOp = linalgOps.back(); assert(tileSizes.size() >= rootOp.getNumLoops() && "expect one tile sizes per root op loop dimension"); assert(tileInterchange.empty() || tileInterchange.size() == tileSizes.size() && "expect the number of tile sizes and interchange dims to match"); SmallVector<int64_t> rootTileSizes(tileSizes.begin(), tileSizes.begin() + rootOp.getNumLoops()); SmallVector<int64_t> rootInterchange = tileInterchange.empty() ? llvm::to_vector<6>(llvm::seq<int64_t>(0, rootOp.getNumLoops())) : SmallVector<int64_t>( tileInterchange.begin(), tileInterchange.begin() + rootOp.getNumLoops()); // Tile the root operation and fuse it with its producers. OpBuilder b(funcOp.getContext()); FailureOr<TileLoopNest> tileLoopNest = tileConsumerAndFuseProducers(b, rootOp, rootTileSizes, rootInterchange); if (failed(tileLoopNest)) return signalPassFailure(); rootOp->replaceAllUsesWith(tileLoopNest->getRootOpReplacementResults()); } void LinalgTensorCodegenDriverPass::fuseOutputIntoReduction(FuncOp funcOp) { LinalgTilingOptions tiling_options; tiling_options.setTileSizes(tileSizes); auto *context = funcOp.getContext(); auto patterns = mlir::linalg::getLinalgTilingCanonicalizationPatterns(context); mlir::memref::populateResolveRankedShapeTypeResultDimsPatterns(patterns); populateFuseFillIntoReductionPatterns(patterns, tiling_options); (void)mlir::applyPatternsAndFoldGreedily(funcOp, std::move(patterns)); // Ensure we drop the marker in the end. funcOp.walk([](mlir::linalg::LinalgOp op) { op->removeAttr(mlir::linalg::LinalgTransforms::kLinalgTransformMarker); }); } void LinalgTensorCodegenDriverPass::runOpAnchoredStrategy(FuncOp funcOp) { if (anchorOpName.empty()) return; if (fuse) return fuseAll(funcOp); if (fuseFillIntoReduction) return fuseOutputIntoReduction(funcOp); // Set up tiling and vectorization options. LinalgTilingOptions tilingOptions; if (!tileSizes.empty()) tilingOptions = tilingOptions.setTileSizes(tileSizes); if (!tileInterchange.empty()) tilingOptions = tilingOptions.setInterchange( SmallVector<unsigned>(tileInterchange.begin(), tileInterchange.end())); if (scalarizeDynamicDims) tilingOptions = tilingOptions.scalarizeDynamicDims(); tilingOptions = tilingOptions.setPeeledLoops(peeledLoops); // Set up padding options. // TODO: Replace the lambdas by either functions defined in MLIR core or even // adapt the LinalgPaddingOptions to take the `hoistPaddings` and // `packPaddings` arrays directly. auto packFunc = [&](OpOperand &opOperand) { return opOperand.getOperandNumber() < packPaddings.size() ? packPaddings[opOperand.getOperandNumber()] : false; }; auto hoistingFunc = [&](OpOperand &opOperand) { return opOperand.getOperandNumber() < hoistPaddings.size() ? hoistPaddings[opOperand.getOperandNumber()] : 0; }; LinalgPaddingOptions paddingOptions; paddingOptions.setPaddingValueComputationFunction(getNeutralOfLinalgOp); paddingOptions.setPaddingNoFoldComputationFunction(packFunc); paddingOptions.setPaddingHoistComputationFunction(hoistingFunc); CodegenStrategy strategy; StringRef genericOpName = GenericOp::getOperationName(); strategy .tileIf(!tileSizes.empty() || scalarizeDynamicDims, anchorOpName, tilingOptions) .padIf(pad, anchorOpName, paddingOptions) .generalizeIf(generalize, anchorOpName) .interchangeIf(!iteratorInterchange.empty(), iteratorInterchange) .vectorizeIf(vectorize, generalize ? genericOpName : anchorOpName); // Created a nested OpPassManager and run. OpPassManager dynamicPM("builtin.func"); strategy.configurePassPipeline(dynamicPM, funcOp.getContext()); if (failed(runPipeline(dynamicPM, funcOp))) return signalPassFailure(); } void LinalgTensorCodegenDriverPass::runComprehensiveBufferization() { OpPassManager dynamicPM("builtin.module"); dynamicPM.addPass(createCanonicalizerPass()); dynamicPM.addPass(createCSEPass()); dynamicPM.addPass(createLinalgComprehensiveModuleBufferizePass()); if (failed(runPipeline(dynamicPM, getOperation()))) return signalPassFailure(); } void LinalgTensorCodegenDriverPass::runVectorLowering() { vector::VectorTransposeLowering vectorTransposeLowering = llvm::StringSwitch<vector::VectorTransposeLowering>( lowerVectorTransposeTo.getValue()) .Case("eltwise", vector::VectorTransposeLowering::EltWise) .Case("flat_transpose", vector::VectorTransposeLowering::Flat) .Case("shuffle", vector::VectorTransposeLowering::Shuffle) .Default(vector::VectorTransposeLowering::EltWise); vector::VectorMultiReductionLowering vectorMultiReductionLowering = llvm::StringSwitch<vector::VectorMultiReductionLowering>( lowerVectorMultiReductionTo.getValue()) .Case("innerreduction", vector::VectorMultiReductionLowering::InnerReduction) .Default(vector::VectorMultiReductionLowering::InnerParallel); vector::VectorContractLowering vectorContractLowering = llvm::StringSwitch<vector::VectorContractLowering>( lowerVectorContractionTo.getValue()) .Case("matrixintrinsics", vector::VectorContractLowering::Matmul) .Case("dot", vector::VectorContractLowering::Dot) .Case("outerproduct", vector::VectorContractLowering::OuterProduct) .Default(vector::VectorContractLowering::OuterProduct); vector::VectorTransferSplit vectorTransferSplit = llvm::StringSwitch<vector::VectorTransferSplit>( splitVectorTransfersTo.getValue()) .Case("none", vector::VectorTransferSplit::None) .Case("linalg-copy", vector::VectorTransferSplit::LinalgCopy) .Case("vector-transfers", vector::VectorTransferSplit::VectorTransfer) .Default(vector::VectorTransferSplit::None); // Per-function lowering pipeline. getOperation().walk([&](FuncOp funcOp) { CodegenStrategy strategy; strategy.vectorLowering( LinalgVectorLoweringOptions() // Lowering of vector contractions. .enableContractionLowering(vectorLoweringStage >= 0) // Lowering of vector multi_reduction. .enableMultiReductionLowering(vectorLoweringStage >= 1) // Whether to split full/partial vector.transfer ops. .enableTransferPartialRewrite(vectorLoweringStage >= 2 && vectorTransferSplit != vector::VectorTransferSplit::None) // Set the maximum vector load / store rank. .setMaxTransferRank(maxTransferRank) // Lower vector.transfer to vector.transfer of max rank. .enableTransferLowering(vectorLoweringStage >= 3) // Conversion to scf. .enableTransferToSCFConversion(vectorLoweringStage >= 4) .setVectorTransferToSCFOptions( VectorTransferToSCFOptions() .enableFullUnroll(unrollVectorTransfers) .enableLowerPermutationMaps()) // Lowering of vector.shape_cast. .enableShapeCastLowering(vectorLoweringStage >= 5) // Lowering of vector.transpose. .enableVectorTransposeLowering(vectorLoweringStage >= 6) .setVectorTransformsOptions( vector::VectorTransformsOptions() .setVectorTransposeLowering(vectorTransposeLowering) .setVectorTransformsOptions(vectorContractLowering) .setVectorMultiReductionLowering( vectorMultiReductionLowering) .setVectorTransferSplit(vectorTransferSplit))); // Created a nested OpPassManager and run. OpPassManager dynamicPM("builtin.func"); strategy.configurePassPipeline(dynamicPM, funcOp.getContext()); if (failed(runPipeline(dynamicPM, funcOp))) return signalPassFailure(); }); } void LinalgTensorCodegenDriverPass::runOnOperation() { if (!anchorFuncOpName.empty()) { getOperation().walk([&](FuncOp funcOp) { if (funcOp.getName() != anchorFuncOpName) return; // Run transforms that require anchoring on a particular op. This only // applies if !anchorOpName.empty(). runOpAnchoredStrategy(funcOp); if (vectorizePadding) { OwningRewritePatternList extraVectorizationPatterns( funcOp.getContext()); populatePadTensorOpVectorizationPatterns(extraVectorizationPatterns); (void)applyPatternsAndFoldGreedily( funcOp, std::move(extraVectorizationPatterns)); } }); } if (bufferize) { runComprehensiveBufferization(); // Perform buffer-level hoistings. getOperation().walk( [&](FuncOp funcOp) { hoistRedundantVectorTransfers(funcOp); }); } if (vectorLowering) runVectorLowering(); if (llvmLowering) runLowerToLLVM(); } /// Return the dialect that must be loaded in the context before this pass. void LinalgTensorCodegenDriverPass::getDependentDialects( DialectRegistry &registry) const { registry.insert<arith::ArithmeticDialect>(); registry.insert<AffineDialect>(); registry.insert<linalg::LinalgDialect>(); registry.insert<memref::MemRefDialect>(); registry.insert<scf::SCFDialect>(); registry.insert<StandardOpsDialect>(); registry.insert<tensor::TensorDialect>(); registry.insert<vector::VectorDialect>(); linalg::comprehensive_bufferize:: registerBufferizableOpInterfaceExternalModels(registry); } std::unique_ptr<OperationPass<ModuleOp>> mlir::createLinalgTensorCodegenDriverPass() { return std::make_unique<LinalgTensorCodegenDriverPass>(); } <|endoftext|>
<commit_before>//===--- AllocBoxToStack.cpp - Promote alloc_box to alloc_stack -----------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "allocbox-to-stack" #include "swift/SILPasses/Passes.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/Dominance.h" #include "swift/SILPasses/Utils/Local.h" #include "llvm/ADT/Statistic.h" #include "llvm/Support/Debug.h" using namespace swift; STATISTIC(NumStackPromoted, "Number of alloc_box's promoted to the stack"); STATISTIC(NumEntryCycleBB, "Number of alloc_box's promotion disrupted due to " "entry cycle"); //===----------------------------------------------------------------------===// // alloc_box Promotion //===----------------------------------------------------------------------===// /// We are currently checking for domination/post-domination but not control /// equivalence, a necessary condition for a single entry/single-exit /// region. This function ensures that we do not run into the issue by making /// sure that the allocbox is not reachable from itself. static bool checkForEntryCycles(SILInstruction *ABI, SILInstruction *SRI) { llvm::SmallVector<SILBasicBlock *, 16> Worklist; llvm::SmallPtrSet<SILBasicBlock *, 16> VisitedBBSet; auto *AllocBoxBB = ABI->getParent(); auto *ReleaseBB = SRI->getParent(); // Add the alloc box bb to the worklist. Worklist.push_back(AllocBoxBB); // For each BB in the worklist... while (!Worklist.empty()) { auto *BB = Worklist.pop_back_val(); // Otherwise, add the successors of the BB to the worklist... for (auto &Succ : BB->getSuccs()) { auto *BB = Succ.getBB(); // We found an entry cycle, we can not promote this alloc box. if (BB == AllocBoxBB) { ++NumEntryCycleBB; return true; } // Prune the search at the SRI's BB. if (BB == ReleaseBB) continue; // Only visit a BB once. if (VisitedBBSet.insert(BB)) Worklist.push_back(BB); } } // The allocbox's BB is not reachable from itself, we are safe. return false; } /// getLastRelease - Determine if there is a single ReleaseInst or /// DeallocBoxInst that post-dominates all of the uses of the specified /// AllocBox. If so, return it. If not, return null. static SILInstruction *getLastRelease(AllocBoxInst *ABI, SmallVectorImpl<SILInstruction*> &Users, SmallVectorImpl<SILInstruction*> &Releases, llvm::OwningPtr<PostDominanceInfo> &PDI) { // If there are no releases, then the box is leaked. Don't transform it. This // can only happen in hand-written SIL code, not compiler generated code. if (Releases.empty()) return nullptr; // If there is a single release, it must be the last release. The calling // conventions used in SIL (at least in the case where the ABI doesn't escape) // are such that the value is live until it is explicitly released: there are // no calls in this case that pass ownership and release for us. if (Releases.size() == 1) return Releases.back(); // If there are multiple releases of the value, we only support the case where // there is a single ultimate release that post-dominates all of the rest of // them. // Determine the most-post-dominating release by doing a linear scan over all // of the releases to find one that post-dominates them all. Because we don't // want to do multiple scans of the block (which could be large) just keep // track of whether there are multiple releases in the ultimate block we find. bool MultipleReleasesInBlock = false; SILInstruction *LastRelease = Releases[0]; for (unsigned i = 1, e = Releases.size(); i != e; ++i) { SILInstruction *RI = Releases[i]; // If this release is in the same block as our candidate, keep track of the // multiple release nature of that block, but don't try to determine an // ordering between them yet. if (RI->getParent() == LastRelease->getParent()) { MultipleReleasesInBlock = true; continue; } // Otherwise, we need to order them. Make sure we've computed PDI. if (!PDI.isValid()) PDI.reset(new PostDominanceInfo(ABI->getParent()->getParent())); if (PDI->properlyDominates(RI->getParent(), LastRelease->getParent())) { // RI post-dom's LastRelease, so it is our new LastRelease. LastRelease = RI; MultipleReleasesInBlock = false; } } // Okay, we found the most-post-dominating release. Make sure that the entry // basic block is not apart of any cycles originating inside the region. This // is to prevent self-cycle issues. if (checkForEntryCycles(ABI, LastRelease)) return nullptr; // Make sure that the most-post-dominating release we have found postdom all // of our uses. If the release does not postdom a use, it would be unsafe to // perform the use. for (auto *User : Users) { if (User->getParent() == LastRelease->getParent()) continue; // Make sure we've computed PDI. if (!PDI.isValid()) PDI.reset(new PostDominanceInfo(ABI->getParent()->getParent())); if (!PDI->properlyDominates(LastRelease->getParent(), User->getParent())) return nullptr; } // Okay, the LastRelease block postdoms all users. If there are multiple // releases in the block, make sure we're looking at the last one. if (MultipleReleasesInBlock) { for (auto MBBI = --LastRelease->getParent()->end(); ; --MBBI) { auto *RI = dyn_cast<StrongReleaseInst>(MBBI); if (RI == nullptr || RI->getOperand() != SILValue(ABI, 0)) { assert(MBBI != LastRelease->getParent()->begin() && "Didn't find any release in this block?"); continue; } LastRelease = RI; break; } } return LastRelease; } /// checkAllocBoxUses - Scan all of the uses (recursively) of the specified /// alloc_box, validating that they don't allow the ABI to escape. static bool checkAllocBoxUses(AllocBoxInst *ABI, SILValue V, SmallVectorImpl<SILInstruction*> &Users) { for (auto UI : V.getUses()) { auto *User = UI->getUser(); // These instructions do not cause the box's address to escape. if (isa<CopyAddrInst>(User) || isa<LoadInst>(User) || isa<ProtocolMethodInst>(User) || (isa<StoreInst>(User) && UI->getOperandNumber() == 1) || (isa<AssignInst>(User) && UI->getOperandNumber() == 1)) { Users.push_back(User); continue; } // These instructions only cause the alloc_box to escape if they are used in // a way that escapes. Recursively check that the uses of the instruction // don't escape and collect all of the uses of the value. if (isa<StructElementAddrInst>(User) || isa<TupleElementAddrInst>(User) || isa<ProjectExistentialInst>(User) || isa<MarkUninitializedInst>(User)) { Users.push_back(User); if (checkAllocBoxUses(ABI, User, Users)) return true; continue; } // apply and partial_apply instructions do not capture the pointer when // it is passed through @inout arguments or for indirect returns. if (auto apply = dyn_cast<ApplyInst>(User)) { if (apply->getSubstCalleeType() ->getInterfaceParameters()[UI->getOperandNumber()-1].isIndirect()) continue; } if (auto partialApply = dyn_cast<PartialApplyInst>(User)) { if (partialApply->getSubstCalleeType() ->getInterfaceParameters()[UI->getOperandNumber()-1].isIndirect()) continue; } // Otherwise, this looks like it escapes. DEBUG(llvm::dbgs() << "*** Failed to promote alloc_box in @" << ABI->getFunction()->getName() << ": " << *ABI << " Due to user: " << *User << "\n"); return true; } return false; } /// optimizeAllocBox - Try to promote an alloc_box instruction to an /// alloc_stack. On success, this updates the IR and returns true, but does not /// remove the alloc_box itself. static bool optimizeAllocBox(AllocBoxInst *ABI, llvm::OwningPtr<PostDominanceInfo> &PDI) { // Scan all of the uses of the alloc_box to see if any of them cause the // allocated memory to escape. If so, we can't promote it to the stack. If // not, we can turn it into an alloc_stack. SmallVector<SILInstruction*, 32> Users; if (checkAllocBoxUses(ABI, SILValue(ABI, 1), Users)) return false; // Scan all of the uses of the retain count value, collecting all the releases // and validating that we don't have an unexpected user. SmallVector<SILInstruction*, 4> Releases; for (auto UI : SILValue(ABI, 0).getUses()) { auto *User = UI->getUser(); if (isa<StrongRetainInst>(User)) continue; // Release doesn't either, but we want to keep track of where this value // gets released. if (isa<StrongReleaseInst>(User) || isa<DeallocBoxInst>(User)) { Releases.push_back(User); Users.push_back(User); continue; } // Otherwise, this looks like it escapes. DEBUG(llvm::dbgs() << "*** Failed to promote alloc_box in @" << ABI->getFunction()->getName() << ": " << *ABI << " Due to user: " << *User << "\n"); return false; } // Okay, the value doesn't escape. Determine where the last release is. This // code only handles the case where there is a single "last release". This // should work for us, because we don't expect code duplication that can // introduce different releases for different codepaths. If this ends up // mattering in the future, this can be generalized. SILInstruction *LastRelease = getLastRelease(ABI, Users, Releases, PDI); // FIXME: If there's no last release, we can't balance the alloc_stack. if (!LastRelease) return false; auto &lowering = ABI->getModule().Types.getTypeLowering(ABI->getElementType()); if (LastRelease == nullptr && !lowering.isTrivial()) { // If we can't tell where the last release is, we don't know where to insert // the destroy_addr for this box. DEBUG(llvm::dbgs() << "*** Failed to promote alloc_box: " << *ABI << " Cannot determine location of the last release!\n" << *ABI->getParent()->getParent() << "\n"); return false; } DEBUG(llvm::dbgs() << "*** Promoting alloc_box to stack: " << *ABI); // Okay, it looks like this value doesn't escape. Promote it to an // alloc_stack. Start by inserting the alloc stack after the alloc_box. SILBuilder B1(ABI->getParent(), ++SILBasicBlock::iterator(ABI)); auto *ASI = B1.createAllocStack(ABI->getLoc(), ABI->getElementType()); ASI->setDebugScope(ABI->getDebugScope()); // Replace all uses of the pointer operand with the spiffy new AllocStack. SILValue(ABI, 1).replaceAllUsesWith(ASI->getAddressResult()); // If we found a 'last release', insert a dealloc_stack instruction and a // destroy_addr if its type is non-trivial. if (LastRelease) { SILBuilder B2(LastRelease); if (!lowering.isTrivial() && !isa<DeallocBoxInst>(LastRelease)) B2.emitDestroyAddr(CleanupLocation::getCleanupLocation(ABI->getLoc()), ASI->getAddressResult()); // Reset the insertion point in case the destroy address expanded to // multiple blocks. B2.setInsertionPoint(LastRelease); B2.createDeallocStack(LastRelease->getLoc(), ASI->getContainerResult()); } // Remove any retain and release instructions. Since all uses of result #1 // are gone, this only walks through uses of result #0 (the retain count // pointer). while (!ABI->use_empty()) { auto *User = (*ABI->use_begin())->getUser(); assert(isa<StrongReleaseInst>(User) || isa<StrongRetainInst>(User) || isa<DeallocBoxInst>(User)); User->eraseFromParent(); } return true; } //===----------------------------------------------------------------------===// // Top Level Driver //===----------------------------------------------------------------------===// void swift::performSILAllocBoxToStackPromotion(SILModule *M) { for (auto &Fn : *M) { // PostDomInfo - This is the post dominance information for the specified // function. It is lazily generated only if needed. llvm::OwningPtr<PostDominanceInfo> PostDomInfo; for (auto &BB : Fn) { auto I = BB.begin(), E = BB.end(); while (I != E) { if (auto *ABI = dyn_cast<AllocBoxInst>(I)) if (optimizeAllocBox(ABI, PostDomInfo)) { ++NumStackPromoted; // Carefully move iterator to avoid invalidation problems. ++I; ABI->eraseFromParent(); continue; } ++I; } } } } <commit_msg>[allocbox-to-stack] Improve comments. NFC.<commit_after>//===--- AllocBoxToStack.cpp - Promote alloc_box to alloc_stack -----------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "allocbox-to-stack" #include "swift/SILPasses/Passes.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/Dominance.h" #include "swift/SILPasses/Utils/Local.h" #include "llvm/ADT/Statistic.h" #include "llvm/Support/Debug.h" using namespace swift; STATISTIC(NumStackPromoted, "Number of alloc_box's promoted to the stack"); STATISTIC(NumEntryCycleBB, "Number of alloc_box's promotion disrupted due to " "entry cycle"); //===----------------------------------------------------------------------===// // alloc_box Promotion //===----------------------------------------------------------------------===// /// We are currently checking for domination/post-domination but not control /// equivalence, a necessary condition for a single entry/single-exit /// region. This function ensures that we do not run into the issue by making /// sure that the allocbox is not reachable from itself. static bool checkForEntryCycles(SILInstruction *ABI, SILInstruction *SRI) { llvm::SmallVector<SILBasicBlock *, 16> Worklist; llvm::SmallPtrSet<SILBasicBlock *, 16> VisitedBBSet; auto *AllocBoxBB = ABI->getParent(); auto *ReleaseBB = SRI->getParent(); // Add the alloc box bb to the worklist. Worklist.push_back(AllocBoxBB); // For each BB in the worklist... while (!Worklist.empty()) { auto *BB = Worklist.pop_back_val(); // Add the successors of the BB to the worklist... for (auto &Succ : BB->getSuccs()) { auto *BB = Succ.getBB(); // If one of those successors is AllocBoxBB, we have an entry cycle // implying that we can not promote this alloc box. if (BB == AllocBoxBB) { ++NumEntryCycleBB; return true; } // If the successor is the ReleaseBB, skip it since ReleaseBB // post-dominates Prune the search at the SRI's BB. if (BB == ReleaseBB) continue; // Otherwise, if we have not visited the BB yet, add it to the worklist // for processing. if (VisitedBBSet.insert(BB)) Worklist.push_back(BB); } } // The allocbox's BB is not reachable from itself, we are safe. return false; } /// getLastRelease - Determine if there is a single ReleaseInst or /// DeallocBoxInst that post-dominates all of the uses of the specified /// AllocBox. If so, return it. If not, return null. static SILInstruction *getLastRelease(AllocBoxInst *ABI, SmallVectorImpl<SILInstruction*> &Users, SmallVectorImpl<SILInstruction*> &Releases, llvm::OwningPtr<PostDominanceInfo> &PDI) { // If there are no releases, then the box is leaked. Don't transform it. This // can only happen in hand-written SIL code, not compiler generated code. if (Releases.empty()) return nullptr; // If there is a single release, it must be the last release. The calling // conventions used in SIL (at least in the case where the ABI doesn't escape) // are such that the value is live until it is explicitly released: there are // no calls in this case that pass ownership and release for us. if (Releases.size() == 1) return Releases.back(); // If there are multiple releases of the value, we only support the case where // there is a single ultimate release that post-dominates all of the rest of // them. // Determine the most-post-dominating release by doing a linear scan over all // of the releases to find one that post-dominates them all. Because we don't // want to do multiple scans of the block (which could be large) just keep // track of whether there are multiple releases in the ultimate block we find. bool MultipleReleasesInBlock = false; SILInstruction *LastRelease = Releases[0]; for (unsigned i = 1, e = Releases.size(); i != e; ++i) { SILInstruction *RI = Releases[i]; // If this release is in the same block as our candidate, keep track of the // multiple release nature of that block, but don't try to determine an // ordering between them yet. if (RI->getParent() == LastRelease->getParent()) { MultipleReleasesInBlock = true; continue; } // Otherwise, we need to order them. Make sure we've computed PDI. if (!PDI.isValid()) PDI.reset(new PostDominanceInfo(ABI->getParent()->getParent())); if (PDI->properlyDominates(RI->getParent(), LastRelease->getParent())) { // RI post-dom's LastRelease, so it is our new LastRelease. LastRelease = RI; MultipleReleasesInBlock = false; } } // Okay, we found the most-post-dominating release. Make sure that the entry // basic block is not apart of any cycles originating inside the region. This // is to prevent self-cycle issues. if (checkForEntryCycles(ABI, LastRelease)) return nullptr; // Make sure that the most-post-dominating release we have found postdom all // of our uses. If the release does not postdom a use, it would be unsafe to // perform the use. for (auto *User : Users) { if (User->getParent() == LastRelease->getParent()) continue; // Make sure we've computed PDI. if (!PDI.isValid()) PDI.reset(new PostDominanceInfo(ABI->getParent()->getParent())); if (!PDI->properlyDominates(LastRelease->getParent(), User->getParent())) return nullptr; } // Okay, the LastRelease block postdoms all users. If there are multiple // releases in the block, make sure we're looking at the last one. if (MultipleReleasesInBlock) { for (auto MBBI = --LastRelease->getParent()->end(); ; --MBBI) { auto *RI = dyn_cast<StrongReleaseInst>(MBBI); if (RI == nullptr || RI->getOperand() != SILValue(ABI, 0)) { assert(MBBI != LastRelease->getParent()->begin() && "Didn't find any release in this block?"); continue; } LastRelease = RI; break; } } return LastRelease; } /// checkAllocBoxUses - Scan all of the uses (recursively) of the specified /// alloc_box, validating that they don't allow the ABI to escape. static bool checkAllocBoxUses(AllocBoxInst *ABI, SILValue V, SmallVectorImpl<SILInstruction*> &Users) { for (auto UI : V.getUses()) { auto *User = UI->getUser(); // These instructions do not cause the box's address to escape. if (isa<CopyAddrInst>(User) || isa<LoadInst>(User) || isa<ProtocolMethodInst>(User) || (isa<StoreInst>(User) && UI->getOperandNumber() == 1) || (isa<AssignInst>(User) && UI->getOperandNumber() == 1)) { Users.push_back(User); continue; } // These instructions only cause the alloc_box to escape if they are used in // a way that escapes. Recursively check that the uses of the instruction // don't escape and collect all of the uses of the value. if (isa<StructElementAddrInst>(User) || isa<TupleElementAddrInst>(User) || isa<ProjectExistentialInst>(User) || isa<MarkUninitializedInst>(User)) { Users.push_back(User); if (checkAllocBoxUses(ABI, User, Users)) return true; continue; } // apply and partial_apply instructions do not capture the pointer when // it is passed through @inout arguments or for indirect returns. if (auto apply = dyn_cast<ApplyInst>(User)) { if (apply->getSubstCalleeType() ->getInterfaceParameters()[UI->getOperandNumber()-1].isIndirect()) continue; } if (auto partialApply = dyn_cast<PartialApplyInst>(User)) { if (partialApply->getSubstCalleeType() ->getInterfaceParameters()[UI->getOperandNumber()-1].isIndirect()) continue; } // Otherwise, this looks like it escapes. DEBUG(llvm::dbgs() << "*** Failed to promote alloc_box in @" << ABI->getFunction()->getName() << ": " << *ABI << " Due to user: " << *User << "\n"); return true; } return false; } /// optimizeAllocBox - Try to promote an alloc_box instruction to an /// alloc_stack. On success, this updates the IR and returns true, but does not /// remove the alloc_box itself. static bool optimizeAllocBox(AllocBoxInst *ABI, llvm::OwningPtr<PostDominanceInfo> &PDI) { // Scan all of the uses of the alloc_box to see if any of them cause the // allocated memory to escape. If so, we can't promote it to the stack. If // not, we can turn it into an alloc_stack. SmallVector<SILInstruction*, 32> Users; if (checkAllocBoxUses(ABI, SILValue(ABI, 1), Users)) return false; // Scan all of the uses of the retain count value, collecting all the releases // and validating that we don't have an unexpected user. SmallVector<SILInstruction*, 4> Releases; for (auto UI : SILValue(ABI, 0).getUses()) { auto *User = UI->getUser(); if (isa<StrongRetainInst>(User)) continue; // Release doesn't either, but we want to keep track of where this value // gets released. if (isa<StrongReleaseInst>(User) || isa<DeallocBoxInst>(User)) { Releases.push_back(User); Users.push_back(User); continue; } // Otherwise, this looks like it escapes. DEBUG(llvm::dbgs() << "*** Failed to promote alloc_box in @" << ABI->getFunction()->getName() << ": " << *ABI << " Due to user: " << *User << "\n"); return false; } // Okay, the value doesn't escape. Determine where the last release is. This // code only handles the case where there is a single "last release". This // should work for us, because we don't expect code duplication that can // introduce different releases for different codepaths. If this ends up // mattering in the future, this can be generalized. SILInstruction *LastRelease = getLastRelease(ABI, Users, Releases, PDI); // FIXME: If there's no last release, we can't balance the alloc_stack. if (!LastRelease) return false; auto &lowering = ABI->getModule().Types.getTypeLowering(ABI->getElementType()); if (LastRelease == nullptr && !lowering.isTrivial()) { // If we can't tell where the last release is, we don't know where to insert // the destroy_addr for this box. DEBUG(llvm::dbgs() << "*** Failed to promote alloc_box: " << *ABI << " Cannot determine location of the last release!\n" << *ABI->getParent()->getParent() << "\n"); return false; } DEBUG(llvm::dbgs() << "*** Promoting alloc_box to stack: " << *ABI); // Okay, it looks like this value doesn't escape. Promote it to an // alloc_stack. Start by inserting the alloc stack after the alloc_box. SILBuilder B1(ABI->getParent(), ++SILBasicBlock::iterator(ABI)); auto *ASI = B1.createAllocStack(ABI->getLoc(), ABI->getElementType()); ASI->setDebugScope(ABI->getDebugScope()); // Replace all uses of the pointer operand with the spiffy new AllocStack. SILValue(ABI, 1).replaceAllUsesWith(ASI->getAddressResult()); // If we found a 'last release', insert a dealloc_stack instruction and a // destroy_addr if its type is non-trivial. if (LastRelease) { SILBuilder B2(LastRelease); if (!lowering.isTrivial() && !isa<DeallocBoxInst>(LastRelease)) B2.emitDestroyAddr(CleanupLocation::getCleanupLocation(ABI->getLoc()), ASI->getAddressResult()); // Reset the insertion point in case the destroy address expanded to // multiple blocks. B2.setInsertionPoint(LastRelease); B2.createDeallocStack(LastRelease->getLoc(), ASI->getContainerResult()); } // Remove any retain and release instructions. Since all uses of result #1 // are gone, this only walks through uses of result #0 (the retain count // pointer). while (!ABI->use_empty()) { auto *User = (*ABI->use_begin())->getUser(); assert(isa<StrongReleaseInst>(User) || isa<StrongRetainInst>(User) || isa<DeallocBoxInst>(User)); User->eraseFromParent(); } return true; } //===----------------------------------------------------------------------===// // Top Level Driver //===----------------------------------------------------------------------===// void swift::performSILAllocBoxToStackPromotion(SILModule *M) { for (auto &Fn : *M) { // PostDomInfo - This is the post dominance information for the specified // function. It is lazily generated only if needed. llvm::OwningPtr<PostDominanceInfo> PostDomInfo; for (auto &BB : Fn) { auto I = BB.begin(), E = BB.end(); while (I != E) { if (auto *ABI = dyn_cast<AllocBoxInst>(I)) if (optimizeAllocBox(ABI, PostDomInfo)) { ++NumStackPromoted; // Carefully move iterator to avoid invalidation problems. ++I; ABI->eraseFromParent(); continue; } ++I; } } } } <|endoftext|>
<commit_before>#include<LiquidCrystal.h> LiquidCrystal lcd(8,9,10,11,12,13); int R=5; // REED SWITCH int P=7; // POWER --not needed int X=6; // PIR int T=A3; // TEMPERATURE - A2 has already been defined as Analog Pin 2 in int H=A5; //HUMIDITY int L=A4; //LIGHT int M1=3; //MOTOR PIN #1 int M2=4; //MOTOR PIN #2 int BUZ=2; int ctr=0; char buffer[10]; float CELSIUS, HUM, LIGHT; String sensordata [6]; void setup() { Serial.begin(9600); lcd.begin(16,2); pinMode(P, INPUT); pinMode(R, INPUT); pinMode(X, INPUT); pinMode(T, INPUT); pinMode(H, INPUT); pinMode(L, INPUT); pinMode(M1, OUTPUT); pinMode(M2, OUTPUT); pinMode(BUZ, OUTPUT); digitalWrite(BUZ, LOW); digitalWrite(M1, LOW); digitalWrite(M2, LOW); displayName(); } // A Function to locate a given search string in a given base string boolean find_string(String base, String search) { int len = search.length(); // find the length of the base string for(int m = 0; m<((base.length()-len)+1);m++)// Iterate from the beginning of the base string till the end minus length of the substring { if(base.substring(m,(m+len))==search) // Check if the extracted Substring Matches the Search String { return true; // if it matches exit the function with a true value } } return false; // if the above loop did not find any matches, control would come here and return a false value } // A Function to locate a given search character in a given base string and return its position boolean find_char_loc(String base, char search) { for(int m = 0; m < base.length();m++)// Iterate from the beginning of the base string till the end minus length of the substring { if(base[m]==search) // Check if the character Matches the Search character { return m; // if it matches exit the function with the current location value } } } //////////***TEMPERATURE***/////////// void TEMPERATURE() { const int len1 = 5; // no of times for the loop to run float samples[len1], tempc=0.0, tempf = 0.0; Serial.print("Getting Temp\t"); lcd.clear(); // for taking mean value of len1 readings for(int i = 0;i<len1;i++){ samples[i] = ( 5.0 * analogRead(T) * 100.0) / 1024.0; tempc = tempc + samples[i]; delay(2000/len1); } CELSIUS=tempc/len1; // setting mean value here tempf = (CELSIUS * 9)/ 5 + 32; // converting to farheniet (if needed) lcd.setCursor(0,0); lcd.print("T:"); lcd.print(CELSIUS); Serial.print("T:\t"); Serial.print(CELSIUS); Serial.print("\t"); // dtostrf(floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, charBuf); // converting float to string and setting in sensordata array sensordata[0] = dtostrf(CELSIUS, 5, 2, buffer); } //////////***HUMIDITY***/////////// void HUMIDITY() { Serial.print("Getting Hum "); float valb = analogRead(H); // humidity calculation delay(10); float prehum = (valb/5); float humconst = (0.16/0.0062); float humi = prehum - humconst; float pretruehumconst = 0.00216*CELSIUS; float pretruehum = 1.0546-pretruehumconst; float truehum = humi/pretruehum ; HUM = truehum; lcd.setCursor(9,0); lcd.print("H:"); lcd.print(HUM); Serial.print("H: "); Serial.print(HUM); Serial.print("\t"); //sensordata[1] = String(HUM); sensordata[1] = dtostrf(HUM, 5, 2, buffer); } //////////***LIGHT***/////////// void LIG() { Serial.print("Getting Lig "); int value_lig=analogRead(L); delay(10); LIGHT=value_lig; lcd.setCursor(0,1); lcd.print("L:"); lcd.print(LIGHT); Serial.print("L: "); Serial.print(LIGHT);Serial.println("\t"); //sensordata[2] = String(LIGHT); sensordata[2] = dtostrf(LIGHT, 5, 2, buffer); delay(2000); lcd.clear(); } //////////***POWER***/////////// void POWER() { Serial.print("PWR STATUS\t"); /*if(digitalRead(P)==LOW) { lcd.setCursor(0,0); lcd.print("P:OFF"); Serial.print("P:OFF");Serial.print("\t"); sensordata[3] = "OFF"; } else { lcd.setCursor(0,0); lcd.print("P:ON"); Serial.print("P:ON");Serial.print("\t"); sensordata[3] = "ON"; }*/ lcd.setCursor(0,0); lcd.print("P:ON"); Serial.print("P:ON");Serial.print("\t"); sensordata[3] = "ON"; } //////////***REED SWITCH***/////////// void REED() { Serial.print(" REED STATUS "); if(digitalRead(R)==LOW) { lcd.setCursor(6,0); lcd.print("R:OPEN"); Serial.print("R:OPEN");Serial.print("\t"); sensordata[4] = "OPEN"; lcd.clear(); lcd.print("WARNING!!"); lcd.setCursor(0,1); lcd.print("DOOR BREACHED!!!"); delay(200); digitalWrite(BUZ,HIGH); delay(10000); lcd.clear(); digitalWrite(BUZ,LOW); } else { lcd.setCursor(6,0); lcd.print("R:CLOSE"); Serial.print("R:CLOSE");Serial.print("\t"); sensordata[4] = "CLOSE"; } } //////////***PIR SENSOR***/////////// void PIR() { Serial.print("PIR STATUS "); if(digitalRead(X)==HIGH) { lcd.setCursor(0,1); lcd.print("X:YES"); Serial.print("X:YES");Serial.println("\t"); sensordata[5] = "YES"; digitalWrite(M1,HIGH); for(k=0; k<3; k++) { lcd.clear(); lcd.print("WARNING!!"); lcd.setCursor(0,1); lcd.print("MOTION"); delay(1000); lcd.clear(); lcd.print("WARNING!!"); lcd.setCursor(0,1); lcd.print("DETECTED!!"); delay(1000); } lcd.clear(); digitalWrite(M1,LOW); } else { lcd.setCursor(0,1); lcd.print("X:NO "); Serial.print("X:NO");Serial.println("\t"); sensordata[5] = "NO"; } delay(2000); } /////***LCD TEST FUNCTION***//////// void lcd_test(int msg_no) { lcd.clear(); lcd.setCursor(0,0); lcd.print("TEST MSG "); lcd.print(msg_no); delay(1000); lcd.clear(); } void lcd_test(String msg) { lcd.clear(); lcd.setCursor(0,0); lcd.print("TEST MSG "); lcd.print(msg); delay(1000); lcd.clear(); } //////////***MAIN LOOP***/////////// void loop() { //lcd_test(0); TEMPERATURE(); HUMIDITY(); LIG(); POWER(); REED(); PIR(); Serial.println(); if(ctr == 5){ displayName(); ctr = 0; } ctr++; } void displayName() { lcd.clear(); lcd.setCursor(0,0); lcd.print("Sidhi's "); delay(1000); lcd.setCursor(0,1); lcd.print("SMART TRACKER"); delay(1000); lcd.clear(); } <commit_msg>code updated<commit_after>#include<LiquidCrystal.h> LiquidCrystal lcd(8,9,10,11,12,13); int R=5; // REED SWITCH int P=7; // POWER --not needed int X=6; // PIR int T=A3; // TEMPERATURE - A2 has already been defined as Analog Pin 2 in int H=A5; //HUMIDITY int L=A4; //LIGHT int M1=3; //MOTOR PIN #1 int M2=4; //MOTOR PIN #2 int BUZ=2; int ctr=0; char buffer[10]; float CELSIUS, HUM; int LIGHT; String sensordata [6]; void setup() { Serial.begin(9600); lcd.begin(16,2); pinMode(P, INPUT); pinMode(R, INPUT); pinMode(X, INPUT); pinMode(T, INPUT); pinMode(H, INPUT); pinMode(L, INPUT); pinMode(M1, OUTPUT); pinMode(M2, OUTPUT); pinMode(BUZ, OUTPUT); digitalWrite(BUZ, LOW); digitalWrite(M1, LOW); digitalWrite(M2, LOW); displayName(); } // A Function to locate a given search string in a given base string boolean find_string(String base, String search) { int len = search.length(); // find the length of the base string for(int m = 0; m<((base.length()-len)+1);m++)// Iterate from the beginning of the base string till the end minus length of the substring { if(base.substring(m,(m+len))==search) // Check if the extracted Substring Matches the Search String { return true; // if it matches exit the function with a true value } } return false; // if the above loop did not find any matches, control would come here and return a false value } // A Function to locate a given search character in a given base string and return its position boolean find_char_loc(String base, char search) { for(int m = 0; m < base.length();m++)// Iterate from the beginning of the base string till the end minus length of the substring { if(base[m]==search) // Check if the character Matches the Search character { return m; // if it matches exit the function with the current location value } } } //////////***TEMPERATURE***/////////// void TEMPERATURE() { const int len1 = 5; // no of times for the loop to run float samples[len1], tempc=0.0, tempf = 0.0; Serial.print("Getting Temp\t"); lcd.clear(); // for taking mean value of len1 readings for(int i = 0;i<len1;i++){ samples[i] = ( 5.0 * analogRead(T) * 100.0) / 1024.0; tempc = tempc + samples[i]; delay(2000/len1); } CELSIUS=tempc/len1; // setting mean value here tempf = (CELSIUS * 9)/ 5 + 32; // converting to farheniet (if needed) lcd.setCursor(0,0); lcd.print("T:"); lcd.print(CELSIUS); Serial.print("T:\t"); Serial.print(CELSIUS); Serial.print("\t"); // dtostrf(floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, charBuf); // converting float to string and setting in sensordata array sensordata[0] = dtostrf(CELSIUS, 5, 2, buffer); } //////////***HUMIDITY***/////////// void HUMIDITY() { Serial.print("Getting Hum "); float valb = analogRead(H); // humidity calculation delay(10); float prehum = (valb/5); float humconst = (0.16/0.0062); float humi = prehum - humconst; float pretruehumconst = 0.00216*CELSIUS; float pretruehum = 1.0546-pretruehumconst; float truehum = humi/pretruehum ; HUM = truehum; lcd.setCursor(9,0); lcd.print("H:"); lcd.print(HUM); Serial.print("H: "); Serial.print(HUM); Serial.print("\t"); //sensordata[1] = String(HUM); sensordata[1] = dtostrf(HUM, 5, 2, buffer); } //////////***LIGHT***/////////// void LIG() { Serial.print("Getting Lig "); int value_lig=analogRead(L); delay(10); LIGHT=value_lig; lcd.setCursor(0,1); lcd.print("L:"); lcd.print(LIGHT); Serial.print("L: "); Serial.print(LIGHT);Serial.println("\t"); //sensordata[2] = String(LIGHT); sensordata[2] = String(LIGHT); delay(2000); lcd.clear(); } //////////***POWER***/////////// void POWER() { Serial.print("PWR STATUS\t"); /*if(digitalRead(P)==LOW) { lcd.setCursor(0,0); lcd.print("P:OFF"); Serial.print("P:OFF");Serial.print("\t"); sensordata[3] = "OFF"; } else { lcd.setCursor(0,0); lcd.print("P:ON"); Serial.print("P:ON");Serial.print("\t"); sensordata[3] = "ON"; }*/ lcd.setCursor(0,0); lcd.print("P:ON"); Serial.print("P:ON");Serial.print("\t"); sensordata[3] = "ON"; } //////////***REED SWITCH***/////////// void REED() { Serial.print(" REED STATUS "); if(digitalRead(R)==LOW) { lcd.setCursor(6,0); lcd.print("R:OPEN"); Serial.print("R:OPEN");Serial.print("\t"); sensordata[4] = "OPEN"; lcd.clear(); lcd.print("WARNING!!"); lcd.setCursor(0,1); lcd.print("DOOR BREACHED!!!"); delay(200); digitalWrite(BUZ,HIGH); delay(10000); lcd.clear(); digitalWrite(BUZ,LOW); } else { lcd.setCursor(6,0); lcd.print("R:CLOSE"); Serial.print("R:CLOSE");Serial.print("\t"); sensordata[4] = "CLOSE"; } } //////////***PIR SENSOR***/////////// void PIR() { Serial.print("PIR STATUS "); if(digitalRead(X)==HIGH) { lcd.setCursor(0,1); lcd.print("X:YES"); Serial.print("X:YES");Serial.println("\t"); sensordata[5] = "YES"; digitalWrite(M1,HIGH); for(int k=0; k<3; k++) { lcd.clear(); lcd.print("WARNING!!"); lcd.setCursor(0,1); lcd.print("MOTION"); delay(1000); lcd.clear(); lcd.print("WARNING!!"); lcd.setCursor(0,1); lcd.print("DETECTED!!"); delay(1000); } lcd.clear(); digitalWrite(M1,LOW); } else { lcd.setCursor(0,1); lcd.print("X:NO "); Serial.print("X:NO");Serial.println("\t"); sensordata[5] = "NO"; } delay(2000); } /////***LCD TEST FUNCTION***//////// void lcd_test(int msg_no) { lcd.clear(); lcd.setCursor(0,0); lcd.print("TEST MSG "); lcd.print(msg_no); delay(1000); lcd.clear(); } void lcd_test(String msg) { lcd.clear(); lcd.setCursor(0,0); lcd.print("TEST MSG "); lcd.print(msg); delay(1000); lcd.clear(); } //////////***MAIN LOOP***/////////// void loop() { //lcd_test(0); TEMPERATURE(); HUMIDITY(); LIG(); POWER(); REED(); PIR(); Serial.println(); if(ctr == 5){ printResult(); displayName(); ctr = 0; } ctr++; } void displayName() { lcd.clear(); lcd.setCursor(0,0); lcd.print("Sidhi's "); delay(1000); lcd.setCursor(0,1); lcd.print("SMART TRACKER"); delay(1000); lcd.clear(); } void printResult() { Serial.println(""); Serial.print("RESULT "); Serial.print("T:"); Serial.print(sensordata[0]); Serial.print(","); Serial.print("H:"); Serial.print(sensordata[1]); Serial.print(","); Serial.print("L:"); Serial.print(sensordata[2]); Serial.print(","); Serial.print("P:"); Serial.print(sensordata[3]); Serial.print(","); Serial.print("R:"); Serial.print(sensordata[4]); Serial.print(","); Serial.print("X:"); Serial.print(sensordata[5]); Serial.println("END"); } <|endoftext|>
<commit_before>#include <cassert> #include <string> #include <vector> #include <utility> #include <algorithm> #include <map> #include <cmath> #include "common.h" #define WARN printf namespace { // this is the same as read_u64_le, but uses uint64_t as in/out uint64_t ReverseBytes(uint64_t x) { return ((x & 0xff00000000000000ull) >> 56) | ((x & 0x00ff000000000000ull) >> 40) | ((x & 0x0000ff0000000000ull) >> 24) | ((x & 0x000000ff00000000ull) >> 8) | ((x & 0x00000000ff000000ull) << 8) | ((x & 0x0000000000ff0000ull) << 24) | ((x & 0x000000000000ff00ull) << 40) | ((x & 0x00000000000000ffull) << 56); } uint64_t set_value(uint64_t ret, Signal sig, int64_t ival){ int shift = sig.is_little_endian? sig.b1 : sig.bo; uint64_t mask = ((1ULL << sig.b2)-1) << shift; uint64_t dat = (ival & ((1ULL << sig.b2)-1)) << shift; if (sig.is_little_endian) { dat = ReverseBytes(dat); } ret &= ~mask; ret |= dat; return ret; } class CANPacker { public: CANPacker(const std::string& dbc_name) { dbc = dbc_lookup(dbc_name); assert(dbc); for (int i=0; i<dbc->num_msgs; i++) { const Msg* msg = &dbc->msgs[i]; message_lookup[msg->address] = *msg; for (int j=0; j<msg->num_sigs; j++) { const Signal* sig = &msg->sigs[j]; signal_lookup[std::make_pair(msg->address, std::string(sig->name))] = *sig; } } } uint64_t pack(uint32_t address, const std::vector<SignalPackValue> &signals, int counter) { uint64_t ret = 0; for (const auto& sigval : signals) { std::string name = std::string(sigval.name); double value = sigval.value; auto sig_it = signal_lookup.find(std::make_pair(address, name)); if (sig_it == signal_lookup.end()) { WARN("undefined signal %s - %d\n", name.c_str(), address); continue; } auto sig = sig_it->second; int64_t ival = (int64_t)(round((value - sig.offset) / sig.factor)); if (ival < 0) { ival = (1ULL << sig.b2) + ival; } ret = set_value(ret, sig, ival); } if (counter >= 0){ auto sig_it = signal_lookup.find(std::make_pair(address, "COUNTER")); if (sig_it == signal_lookup.end()) { WARN("COUNTER not defined\n"); return ret; } auto sig = sig_it->second; if (sig.type != SignalType::HONDA_COUNTER){ WARN("COUNTER signal type not valid\n"); } ret = set_value(ret, sig, counter); } auto sig_it = signal_lookup.find(std::make_pair(address, "CHECKSUM")); if (sig_it != signal_lookup.end()) { auto sig = sig_it->second; if (sig.type == SignalType::HONDA_CHECKSUM){ unsigned int chksm = honda_checksum(address, ret, message_lookup[address].size); ret = set_value(ret, sig, chksm); } else if (sig.type == SignalType::TOYOTA_CHECKSUM){ unsigned int chksm = toyota_checksum(address, ret, message_lookup[address].size); ret = set_value(ret, sig, chksm); } else { WARN("CHECKSUM signal type not valid\n"); } } return ret; } private: const DBC *dbc = NULL; std::map<std::pair<uint32_t, std::string>, Signal> signal_lookup; std::map<uint32_t, Msg> message_lookup; }; } extern "C" { void* canpack_init(const char* dbc_name) { CANPacker *ret = new CANPacker(std::string(dbc_name)); return (void*)ret; } uint64_t canpack_pack(void* inst, uint32_t address, size_t num_vals, const SignalPackValue *vals, int counter, bool checksum) { CANPacker *cp = (CANPacker*)inst; return cp->pack(address, std::vector<SignalPackValue>(vals, vals+num_vals), counter); } } <commit_msg>little endian mask fix (#330)<commit_after>#include <cassert> #include <string> #include <vector> #include <utility> #include <algorithm> #include <map> #include <cmath> #include "common.h" #define WARN printf namespace { // this is the same as read_u64_le, but uses uint64_t as in/out uint64_t ReverseBytes(uint64_t x) { return ((x & 0xff00000000000000ull) >> 56) | ((x & 0x00ff000000000000ull) >> 40) | ((x & 0x0000ff0000000000ull) >> 24) | ((x & 0x000000ff00000000ull) >> 8) | ((x & 0x00000000ff000000ull) << 8) | ((x & 0x0000000000ff0000ull) << 24) | ((x & 0x000000000000ff00ull) << 40) | ((x & 0x00000000000000ffull) << 56); } uint64_t set_value(uint64_t ret, Signal sig, int64_t ival){ int shift = sig.is_little_endian? sig.b1 : sig.bo; uint64_t mask = ((1ULL << sig.b2)-1) << shift; uint64_t dat = (ival & ((1ULL << sig.b2)-1)) << shift; if (sig.is_little_endian) { dat = ReverseBytes(dat); mask = ReverseBytes(mask); } ret &= ~mask; ret |= dat; return ret; } class CANPacker { public: CANPacker(const std::string& dbc_name) { dbc = dbc_lookup(dbc_name); assert(dbc); for (int i=0; i<dbc->num_msgs; i++) { const Msg* msg = &dbc->msgs[i]; message_lookup[msg->address] = *msg; for (int j=0; j<msg->num_sigs; j++) { const Signal* sig = &msg->sigs[j]; signal_lookup[std::make_pair(msg->address, std::string(sig->name))] = *sig; } } } uint64_t pack(uint32_t address, const std::vector<SignalPackValue> &signals, int counter) { uint64_t ret = 0; for (const auto& sigval : signals) { std::string name = std::string(sigval.name); double value = sigval.value; auto sig_it = signal_lookup.find(std::make_pair(address, name)); if (sig_it == signal_lookup.end()) { WARN("undefined signal %s - %d\n", name.c_str(), address); continue; } auto sig = sig_it->second; int64_t ival = (int64_t)(round((value - sig.offset) / sig.factor)); if (ival < 0) { ival = (1ULL << sig.b2) + ival; } ret = set_value(ret, sig, ival); } if (counter >= 0){ auto sig_it = signal_lookup.find(std::make_pair(address, "COUNTER")); if (sig_it == signal_lookup.end()) { WARN("COUNTER not defined\n"); return ret; } auto sig = sig_it->second; if (sig.type != SignalType::HONDA_COUNTER){ WARN("COUNTER signal type not valid\n"); } ret = set_value(ret, sig, counter); } auto sig_it = signal_lookup.find(std::make_pair(address, "CHECKSUM")); if (sig_it != signal_lookup.end()) { auto sig = sig_it->second; if (sig.type == SignalType::HONDA_CHECKSUM){ unsigned int chksm = honda_checksum(address, ret, message_lookup[address].size); ret = set_value(ret, sig, chksm); } else if (sig.type == SignalType::TOYOTA_CHECKSUM){ unsigned int chksm = toyota_checksum(address, ret, message_lookup[address].size); ret = set_value(ret, sig, chksm); } else { WARN("CHECKSUM signal type not valid\n"); } } return ret; } private: const DBC *dbc = NULL; std::map<std::pair<uint32_t, std::string>, Signal> signal_lookup; std::map<uint32_t, Msg> message_lookup; }; } extern "C" { void* canpack_init(const char* dbc_name) { CANPacker *ret = new CANPacker(std::string(dbc_name)); return (void*)ret; } uint64_t canpack_pack(void* inst, uint32_t address, size_t num_vals, const SignalPackValue *vals, int counter, bool checksum) { CANPacker *cp = (CANPacker*)inst; return cp->pack(address, std::vector<SignalPackValue>(vals, vals+num_vals), counter); } } <|endoftext|>
<commit_before>/** * @file stringUtils.cpp * */ // Copyright 2001 California Institute of Technology #ifdef WIN32 #pragma warning(disable:4786) #pragma warning(disable:4503) #endif #include "ct_defs.h" #include "ctexceptions.h" #include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> namespace Cantera { /** * Convert a floating point number to a string using sprintf. */ string fp2str(double x, string fmt) { char buf[30]; sprintf(buf, fmt.c_str(), x); return string(buf); } /** * Convert an integer number to a string using sprintf. */ string int2str(int n, string fmt) { char buf[30]; sprintf(buf, fmt.c_str(), n); return string(buf); } string lowercase(string s) { int n = static_cast<int>(s.size()); string lc(s); for (int i = 0; i < n; i++) lc[i] = tolower(s[i]); return lc; } /** * Strip white space. */ string stripws(string s) { int i; bool sempty = true; int n = static_cast<int>(s.size()); string ss = ""; for (i = 0; i < n; i++) { if (s[i] != ' ' && isprint(s[i])) { ss += s[i]; sempty = false; } else if (!sempty) break; } return ss; } /** * Strip non-printing characters. */ string stripnonprint(string s) { int i; int n = static_cast<int>(s.size()); string ss = ""; for (i = 0; i < n; i++) { if (isprint(s[i])) { ss += s[i]; } } return ss; } /** * Parse a composition string. */ void parseCompString(const string ss, compositionMap& x) { string s = ss; string::size_type icolon, ibegin, iend; string name, num, nm; do { ibegin = s.find_first_not_of(", ;\n\t"); if (ibegin != string::npos) { s = s.substr(ibegin,s.size()); icolon = s.find(':'); iend = s.find_first_of(", ;\n\t"); //icomma = s.find(','); if (icolon != string::npos) { name = s.substr(0, icolon); if (iend != string::npos) { num = s.substr(icolon+1, iend-icolon); s = s.substr(iend+1, s.size()); } else { num = s.substr(icolon+1, s.size()); s = ""; } nm = stripws(name); if (x.find(nm) == x.end()) { //if (x[nm] == 0.0) { throw CanteraError("parseCompString", "unknown species " + nm); } x[nm] = atof(num.c_str()); } else s = ""; } } while (s != ""); } int fillArrayFromString(const string& str, doublereal* a, char delim) { string::size_type iloc; int count = 0; string num, s; s = str; while (s.size() > 0) { iloc = s.find(delim); if (iloc > 0) { num = s.substr(0, iloc); s = s.substr(iloc+1,s.size()); } else { num = s; s = ""; } a[count] = atof(num.c_str()); count++; } return count; } /** * Get the file name without the path or extension */ string getFileName(const string& path) { string file; size_t idot = path.find_last_of('.'); size_t islash = path.find_last_of('/'); if (idot > 0 && idot < path.size()) { if (islash > 0 && islash < idot) { file = path.substr(islash+1, idot-islash-1); } else { file = path.substr(0,idot); } } else { file = path; } return file; } /** * Generate a logfile name based on an input file name */ string logfileName(const string& infile) { string logfile; size_t idot = infile.find_last_of('.'); size_t islash = infile.find_last_of('/'); if (idot > 0 && idot < infile.size()) { if (islash > 0 && islash < idot) { logfile = infile.substr(islash+1, idot-islash-1) + ".log"; } else { logfile = infile.substr(0,idot) + ".log"; } } else { logfile = infile + ".log"; } return logfile; } string wrapString(const string& s, int len) { int nc = s.size(); int n, count=0; string r; for (n = 0; n < nc; n++) { if (s[n] == '\n') count = 0; else count++; if (count > len && s[n] == ' ') { r += "\n "; count = 0; } r += s[n]; } return r; } /* * This routine strips off blanks and tabs (only leading and trailing * characters) in 'str'. On return, it returns the number of * characters still included in the string (excluding the null character). * * Comments are excluded -> All instances of the comment character, '!', * are replaced by '\0' thereby terminating * the string * * Parameter list: * * str == On output 'str' contains the same characters as on * input except the leading and trailing white space and * comments have been removed. */ int stripLTWScstring(char str[]) { int i = 0, j = 0; char ch; const char COM_CHAR='\0'; /* * Quick Returns */ if ((str == 0) || (str[0] == '\0')) return (0); /* Find first non-space character character */ while(((ch = str[i]) != '\0') && isspace(ch)) i++; /* * Move real part of str to the front by copying the string * - Comments are handled here, by terminating the copy at the * first comment indicator, and inserting the null character at * that point. */ while ( (ch = str[j+i]) != '\0' && (ch != COM_CHAR)) { str[j] = ch; j++; } str[j] = '\0'; j--; /* Remove trailing white space by inserting a null character */ while( (j != -1 ) && isspace(str[j])) j--; j++; str[j] = '\0'; return (j); } /* * atofCheck is a wrapper around the C stdlib routine atof(). * It does quite a bit more error checking than atof() or * strtod(), and is quite a bit more restrictive. * * First it interprets both E, e, d, and D as exponents. * atof() only interprets e or E as an exponent character. * * It only accepts a string as well formed if it consists as a * single token. Multiple words will produce an error message * * It will produce an error for NAN and inf entries as well, * in contrast to atof() or strtod(). * The user needs to know that a serious numerical issue * has occurred. * * It does not accept hexadecimal numbers. * * On any error, it will throw a CanteraError signal. */ double atofCheck(const char *dptr) { if (!dptr) { throw CanteraError("atofCheck", "null pointer to string"); } char *eptr = (char *) malloc(strlen(dptr)+1); strcpy(eptr, dptr); int ll = stripLTWScstring(eptr); if (ll == 0) { throw CanteraError("atofCheck", "string has zero length"); } int numDot = 0; int numExp = 0; char ch; int istart = 0; ch = eptr[0]; if (ch == '+' || ch == '-') { istart = 1; } for (int i = istart; i < ll; i++) { ch = eptr[i]; if (isdigit(ch)) { } else if (ch == '.') { numDot++; if (numDot > 1) { free(eptr); throw CanteraError("atofCheck", "string has more than one ."); } } else if (ch == 'e' || ch == 'E' || ch == 'd' || ch == 'D') { numExp++; eptr[i] = 'E'; if (numExp > 1) { free(eptr); throw CanteraError("atofCheck", "string has more than one exp char"); } ch = eptr[i+1]; if (ch == '+' || ch == '-') { i++; } } else { string hh(dptr); free(eptr); throw CanteraError("aotofCheck", "Trouble processing string, " + hh); } } double rval = atof(eptr); free(eptr); return rval; } } <commit_msg>changed stripws to allow spaces in the middle of strings<commit_after>/** * @file stringUtils.cpp * */ // Copyright 2001 California Institute of Technology #ifdef WIN32 #pragma warning(disable:4786) #pragma warning(disable:4503) #endif #include "ct_defs.h" #include "ctexceptions.h" #include <stdio.h> #include <ctype.h> #include <string.h> #include <stdlib.h> namespace Cantera { /** * Convert a floating point number to a string using sprintf. */ string fp2str(double x, string fmt) { char buf[30]; sprintf(buf, fmt.c_str(), x); return string(buf); } /** * Convert an integer number to a string using sprintf. */ string int2str(int n, string fmt) { char buf[30]; sprintf(buf, fmt.c_str(), n); return string(buf); } string lowercase(string s) { int n = static_cast<int>(s.size()); string lc(s); for (int i = 0; i < n; i++) lc[i] = tolower(s[i]); return lc; } static int firstChar(string s) { int i; int n = static_cast<int>(s.size()); for (i = 0; i < n; i++) if (s[i] != ' ' && isprint(s[i])) break; return i; } static int lastChar(string s) { int i; int n = static_cast<int>(s.size()); for (i = n-1; i >= 0; i--) if (s[i] != ' ' && isprint(s[i])) break; return i; } /** * Strip leading and trailing white space. */ string stripws(string s) { int ifirst = firstChar(s); int ilast = lastChar(s); return s.substr(ifirst, ilast - ifirst + 1); } /** * Strip non-printing characters. */ string stripnonprint(string s) { int i; int n = static_cast<int>(s.size()); string ss = ""; for (i = 0; i < n; i++) { if (isprint(s[i])) { ss += s[i]; } } return ss; } /** * Parse a composition string. */ void parseCompString(const string ss, compositionMap& x) { string s = ss; string::size_type icolon, ibegin, iend; string name, num, nm; do { ibegin = s.find_first_not_of(", ;\n\t"); if (ibegin != string::npos) { s = s.substr(ibegin,s.size()); icolon = s.find(':'); iend = s.find_first_of(", ;\n\t"); //icomma = s.find(','); if (icolon != string::npos) { name = s.substr(0, icolon); if (iend != string::npos) { num = s.substr(icolon+1, iend-icolon); s = s.substr(iend+1, s.size()); } else { num = s.substr(icolon+1, s.size()); s = ""; } nm = stripws(name); if (x.find(nm) == x.end()) { //if (x[nm] == 0.0) { throw CanteraError("parseCompString", "unknown species " + nm); } x[nm] = atof(num.c_str()); } else s = ""; } } while (s != ""); } int fillArrayFromString(const string& str, doublereal* a, char delim) { string::size_type iloc; int count = 0; string num, s; s = str; while (s.size() > 0) { iloc = s.find(delim); if (iloc > 0) { num = s.substr(0, iloc); s = s.substr(iloc+1,s.size()); } else { num = s; s = ""; } a[count] = atof(num.c_str()); count++; } return count; } /** * Get the file name without the path or extension */ string getFileName(const string& path) { string file; size_t idot = path.find_last_of('.'); size_t islash = path.find_last_of('/'); if (idot > 0 && idot < path.size()) { if (islash > 0 && islash < idot) { file = path.substr(islash+1, idot-islash-1); } else { file = path.substr(0,idot); } } else { file = path; } return file; } /** * Generate a logfile name based on an input file name */ string logfileName(const string& infile) { string logfile; size_t idot = infile.find_last_of('.'); size_t islash = infile.find_last_of('/'); if (idot > 0 && idot < infile.size()) { if (islash > 0 && islash < idot) { logfile = infile.substr(islash+1, idot-islash-1) + ".log"; } else { logfile = infile.substr(0,idot) + ".log"; } } else { logfile = infile + ".log"; } return logfile; } string wrapString(const string& s, int len) { int nc = s.size(); int n, count=0; string r; for (n = 0; n < nc; n++) { if (s[n] == '\n') count = 0; else count++; if (count > len && s[n] == ' ') { r += "\n "; count = 0; } r += s[n]; } return r; } /* * This routine strips off blanks and tabs (only leading and trailing * characters) in 'str'. On return, it returns the number of * characters still included in the string (excluding the null character). * * Comments are excluded -> All instances of the comment character, '!', * are replaced by '\0' thereby terminating * the string * * Parameter list: * * str == On output 'str' contains the same characters as on * input except the leading and trailing white space and * comments have been removed. */ int stripLTWScstring(char str[]) { int i = 0, j = 0; char ch; const char COM_CHAR='\0'; /* * Quick Returns */ if ((str == 0) || (str[0] == '\0')) return (0); /* Find first non-space character character */ while(((ch = str[i]) != '\0') && isspace(ch)) i++; /* * Move real part of str to the front by copying the string * - Comments are handled here, by terminating the copy at the * first comment indicator, and inserting the null character at * that point. */ while ( (ch = str[j+i]) != '\0' && (ch != COM_CHAR)) { str[j] = ch; j++; } str[j] = '\0'; j--; /* Remove trailing white space by inserting a null character */ while( (j != -1 ) && isspace(str[j])) j--; j++; str[j] = '\0'; return (j); } /* * atofCheck is a wrapper around the C stdlib routine atof(). * It does quite a bit more error checking than atof() or * strtod(), and is quite a bit more restrictive. * * First it interprets both E, e, d, and D as exponents. * atof() only interprets e or E as an exponent character. * * It only accepts a string as well formed if it consists as a * single token. Multiple words will produce an error message * * It will produce an error for NAN and inf entries as well, * in contrast to atof() or strtod(). * The user needs to know that a serious numerical issue * has occurred. * * It does not accept hexadecimal numbers. * * On any error, it will throw a CanteraError signal. */ double atofCheck(const char *dptr) { if (!dptr) { throw CanteraError("atofCheck", "null pointer to string"); } char *eptr = (char *) malloc(strlen(dptr)+1); strcpy(eptr, dptr); int ll = stripLTWScstring(eptr); if (ll == 0) { throw CanteraError("atofCheck", "string has zero length"); } int numDot = 0; int numExp = 0; char ch; int istart = 0; ch = eptr[0]; if (ch == '+' || ch == '-') { istart = 1; } for (int i = istart; i < ll; i++) { ch = eptr[i]; if (isdigit(ch)) { } else if (ch == '.') { numDot++; if (numDot > 1) { free(eptr); throw CanteraError("atofCheck", "string has more than one ."); } } else if (ch == 'e' || ch == 'E' || ch == 'd' || ch == 'D') { numExp++; eptr[i] = 'E'; if (numExp > 1) { free(eptr); throw CanteraError("atofCheck", "string has more than one exp char"); } ch = eptr[i+1]; if (ch == '+' || ch == '-') { i++; } } else { string hh(dptr); free(eptr); throw CanteraError("aotofCheck", "Trouble processing string, " + hh); } } double rval = atof(eptr); free(eptr); return rval; } } <|endoftext|>
<commit_before>#pragma ident "$Id: $" #include <iostream> #include "Exception.hpp" #include "DayTime.hpp" #include "CommandOptionParser.hpp" #include "StringUtils.hpp" #include "ValarrayUtils.hpp" #include "ObsArray.hpp" #include "SparseBinnedStats.hpp" void dumpRaw(std::ostream& ostr, const gpstk::ObsArray& oa, bool numeric); void writeStats(std::ostream& ostr, const gpstk::SparseBinnedStats<double>& sbs, bool numeric, bool elevation=true); using namespace std; using namespace gpstk; using namespace ValarrayUtils; int main(int argc, char *argv[]) { try { // Default difference that isolates multipath std::string mp_formula="P1-wl1*L1+2/(1-gamma)*(wl1*L1-wl2*L2)"; // Default minimum length for a pass for use solution double minPassLength = 300; double angInterval = 15; CommandOptionNoArg helpOption('h',"help","Display argument list.",false); CommandOptionNoArg verboseOption('v',"verbose", "Verbose display of processing status.",false); CommandOptionNoArg rawOption('r',"raw", "Output raw combinations not statistics",false); CommandOptionNoArg numericOption('n',"numeric", "Format the output for numerical packages",false); CommandOptionNoArg azimuthOption('a',"azimuth", "Compute statistics binned by azimuth instead of elevation",false); CommandOptionWithAnyArg obsFileOption('o',"obs","RINEX observation file",true); CommandOptionWithAnyArg navFileOption('e',"nav", "RINEX navigation (ephemeris) file",true); CommandOptionWithAnyArg binOption('b',"bin", "Defines a bin. Eliminates the default bins. Repeated use of this option defines additional bins. Value is min,max. Ex.: -b 10,90",false); CommandOptionWithAnyArg mpOption('m',"multipath", "Dual frequency multipath combination to use. Default is " + mp_formula,false); mpOption.setMaxCount(1); CommandOptionWithNumberArg lengthOption('l',"length",string("Minimum length in seconds for an ")+ string("overhead pass to be used. Default value is ") + StringUtils::asString(minPassLength, 1) + string(" seconds."), false); lengthOption.setMaxCount(1); CommandOptionWithNumberArg angWidthOption('w',"width",string("Width of angular bins to use.")+ string("If used, defines regular, nonoverlapping bins of ") + string("azimuth and/or elevation. Default value is ") + StringUtils::asString(angInterval, 2) + string(" degrees."), false); angWidthOption.setMaxCount(1); CommandOptionParser cop("GPSTk Multipath Environment Evaluator. Computes statistical model of a dual frequency multipath combination. The model is a function of azimuth and/or elevation. By default the model presented is second order statistics (std. deviation), sorted into bins of elevation."); cop.parseOptions(argc, argv); if (cop.hasErrors()) { cop.dumpErrors(cout); cop.displayUsage(cout); return 1; } if(helpOption.getCount()) { cop.displayUsage(cout); return 0; } bool verbose=(verboseOption.getCount()>0); bool numeric=(numericOption.getCount()>0); DayTime now; if (!numeric) { cout << "Multipath Environment Evaluation Tool, a GPSTk utility" << endl << endl; } if ( (verbose) && (!numeric)) { cout << "Loading obs and nav files." << obsFileOption.getValue() << endl; cout << "Loading nav files: " << navFileOption.getValue() << endl; } ObsArray oa; if (mpOption.getCount()>0) mp_formula = mpOption.getValue()[0]; oa.add(mp_formula); oa.load(obsFileOption.getValue(),navFileOption.getValue()); size_t originalLength = oa.getNumSatEpochs(); if ((!numeric)&& (verbose)) cout << "Editing points with loss of lock indication and pass with short lengths." << endl; std::valarray<bool> removePts = oa.lli; if (lengthOption.getCount()>0) minPassLength = StringUtils::asDouble(lengthOption.getValue()[0]); set<long> allpasses = unique(oa.pass); for (set<long>::iterator i=allpasses.begin(); i!=allpasses.end(); i++) { if (oa.getPassLength(*i)<minPassLength) { removePts = removePts || (oa.pass==*i); } } oa.edit(removePts); size_t editedLength = oa.getNumSatEpochs(); if (!numeric) { cout << "Edited " << (originalLength-editedLength) << " points ("; cout << setprecision(2) << 100.*(originalLength-editedLength)/originalLength; cout << "%)." << endl; } if (!numeric) { cout << "Removing mean of each pass." << endl; for (set<long>::iterator iPass=allpasses.begin(); iPass!=allpasses.end() ; iPass++) { valarray<bool> passMask = (oa.pass==*iPass); valarray<double> mpVals = oa.observation[passMask]; valarray<double> binVals(mpVals.size()); double mean = mpVals.sum() / mpVals.size(); mpVals -= mean; oa.observation[passMask]=mpVals; } } allpasses = unique(oa.pass); if (!numeric) { if (verbose) { cout <<"Using this combination for multipath: " <<mp_formula<<endl; cout << "Data collection interval is " << setprecision(3) << oa.interval << " seconds"; if (oa.intervalInferred) cout << ", inferred from data"; else cout << ", read from file headers"; cout << "." <<endl; } cout << "Overhead passes used: "; cout << allpasses.size() << endl; } if (rawOption.getCount()>0) { dumpRaw(cout, oa, numeric); } else { bool byAzimuth = (azimuthOption.getCount()>0); angInterval = StringUtils::asDouble(angWidthOption.getValue()[0]); bool regularIntervals = (byAzimuth || (angWidthOption.getCount()>0)); SparseBinnedStats<double> sbs; if (binOption.getCount()==0) { if (!byAzimuth) { if (!regularIntervals) { sbs.addBin(0,90); sbs.addBin(10,30); sbs.addBin(20,40); sbs.addBin(40,90); sbs.addBin(10,90); } else { for (double d=0; d<90; d+=angInterval) sbs.addBin(d,d+angInterval); } } else { for (double d=0; d<359; d+=angInterval) sbs.addBin(d,d+angInterval); } } else { for (int k=0; k<binOption.getValue().size(); k++) { string temp = binOption.getValue()[k]; string lowerWord = StringUtils::word(temp,0,','); string upperWord = StringUtils::word(temp,1,','); sbs.addBin(StringUtils::asDouble(lowerWord), StringUtils::asDouble(upperWord)); } } for (set<long>::iterator iPass=allpasses.begin(); iPass!=allpasses.end() ; iPass++) { valarray<bool> passMask = (oa.pass==*iPass); valarray<double> mpVals = oa.observation[passMask]; valarray<double> binVals(mpVals.size()); if (!byAzimuth) binVals = oa.elevation[passMask]; else binVals = oa.azimuth[passMask]; sbs.addData(mpVals, binVals); } writeStats(cout, sbs, numeric, !byAzimuth); } DayTime then; if ( (verbose) && (!numeric)) cout << "Processing complete in " << then - now << " seconds." << endl; } catch (Exception& e) { cerr << e << endl; } return 0; } void dumpRaw(std::ostream& ostr, const ObsArray& oa, bool numeric) { if (numeric) { ostr << "# GPS Week, Seconds of week, Sat. id, Sat. system, Pass, "; ostr << "Multipath value, LLI indicator, Azimuth, Elevation " << endl; } for (size_t i=0; i<oa.observation.size(); i++) { if (!numeric) { ostr << oa.epoch[i] << " " << oa.satellite[i] << " "; ostr << "Pass " << oa.pass[i] << " "; ostr << setprecision(12) << oa.observation[i]; if (oa.validAzEl[i]) { ostr << setprecision(5); ostr << " Az " << oa.azimuth[i]; ostr << " El " << oa.elevation[i]; } if (oa.lli[i]) ostr << " <- Loss of lock"; ostr << std::endl; } else { ostr << oa.epoch[i].GPSfullweek() << " "; ostr << oa.epoch[i].GPSsow() << " "; ostr << oa.satellite[i].id << " "; ostr << (int) oa.satellite[i].system << " "; ostr << oa.pass[i] << " "; ostr << setprecision(12) << oa.observation[i] << " "; ostr << (int) oa.lli[i]; if (oa.validAzEl[i]) { ostr << setprecision(5); ostr << " " << oa.azimuth[i]; ostr << " " << oa.elevation[i]; } ostr << std::endl; } } } void writeStats(std::ostream& ostr, const SparseBinnedStats<double>& mstats, bool numeric, bool elevation) { std::string angDesc = "elevation"; if (!elevation) angDesc = "azimuth"; if(!numeric) { ostr << endl; ostr << "Standard deviation of bins sorted by " << angDesc << "." << endl << endl; for (int i=0; i<mstats.stats.size(); i++) { ostr << "From " << setw(3) << mstats.bins[i].lowerBound; ostr << " to " << setw(3) << mstats.bins[i].upperBound; ostr << ": " << setprecision(3) << mstats.stats[i].StdDev() << endl; } ostr << endl; ostr << "Total points used: " << mstats.usedCount << endl; ostr << " rejected: " << mstats.rejectedCount << endl; } else { ostr << "# Bins of " << angDesc << " -- columns are min, max, standard deviation " << endl; for (int i=0; i<mstats.stats.size(); i++) { ostr << setw(3) << mstats.bins[i].lowerBound << " "; ostr << setw(3) << mstats.bins[i].upperBound << " "; ostr << setprecision(3) << mstats.stats[i].StdDev() << endl; } } } <commit_msg>Correct logic error introduced by last submission.<commit_after>#pragma ident "$Id: $" #include <iostream> #include "Exception.hpp" #include "DayTime.hpp" #include "CommandOptionParser.hpp" #include "StringUtils.hpp" #include "ValarrayUtils.hpp" #include "ObsArray.hpp" #include "SparseBinnedStats.hpp" void dumpRaw(std::ostream& ostr, const gpstk::ObsArray& oa, bool numeric); void writeStats(std::ostream& ostr, const gpstk::SparseBinnedStats<double>& sbs, bool numeric, bool elevation=true); using namespace std; using namespace gpstk; using namespace ValarrayUtils; int main(int argc, char *argv[]) { try { // Default difference that isolates multipath std::string mp_formula="P1-wl1*L1+2/(1-gamma)*(wl1*L1-wl2*L2)"; // Default minimum length for a pass for use solution double minPassLength = 300; double angInterval = 15; CommandOptionNoArg helpOption('h',"help","Display argument list.",false); CommandOptionNoArg verboseOption('v',"verbose", "Verbose display of processing status.",false); CommandOptionNoArg rawOption('r',"raw", "Output raw combinations not statistics",false); CommandOptionNoArg numericOption('n',"numeric", "Format the output for numerical packages",false); CommandOptionNoArg azimuthOption('a',"azimuth", "Compute statistics binned by azimuth instead of elevation",false); CommandOptionWithAnyArg obsFileOption('o',"obs","RINEX observation file",true); CommandOptionWithAnyArg navFileOption('e',"nav", "RINEX navigation (ephemeris) file",true); CommandOptionWithAnyArg binOption('b',"bin", "Defines a bin. Eliminates the default bins. Repeated use of this option defines additional bins. Value is min,max. Ex.: -b 10,90",false); CommandOptionWithAnyArg mpOption('m',"multipath", "Dual frequency multipath combination to use. Default is " + mp_formula,false); mpOption.setMaxCount(1); CommandOptionWithNumberArg lengthOption('l',"length",string("Minimum length in seconds for an ")+ string("overhead pass to be used. Default value is ") + StringUtils::asString(minPassLength, 1) + string(" seconds."), false); lengthOption.setMaxCount(1); CommandOptionWithNumberArg angWidthOption('w',"width",string("Width of angular bins to use.")+ string("If used, defines regular, nonoverlapping bins of ") + string("azimuth and/or elevation. Default value is ") + StringUtils::asString(angInterval, 2) + string(" degrees."), false); angWidthOption.setMaxCount(1); CommandOptionParser cop("GPSTk Multipath Environment Evaluator. Computes statistical model of a dual frequency multipath combination. The model is a function of azimuth and/or elevation. By default the model presented is second order statistics (std. deviation), sorted into bins of elevation."); cop.parseOptions(argc, argv); if (cop.hasErrors()) { cop.dumpErrors(cout); cop.displayUsage(cout); return 1; } if(helpOption.getCount()) { cop.displayUsage(cout); return 0; } bool verbose=(verboseOption.getCount()>0); bool numeric=(numericOption.getCount()>0); DayTime now; if (!numeric) { cout << "Multipath Environment Evaluation Tool, a GPSTk utility" << endl << endl; } if ( (verbose) && (!numeric)) { cout << "Loading obs and nav files." << obsFileOption.getValue() << endl; cout << "Loading nav files: " << navFileOption.getValue() << endl; } ObsArray oa; if (mpOption.getCount()>0) mp_formula = mpOption.getValue()[0]; oa.add(mp_formula); oa.load(obsFileOption.getValue(),navFileOption.getValue()); size_t originalLength = oa.getNumSatEpochs(); if ((!numeric)&& (verbose)) cout << "Editing points with loss of lock indication and pass with short lengths." << endl; std::valarray<bool> removePts = oa.lli; if (lengthOption.getCount()>0) minPassLength = StringUtils::asDouble(lengthOption.getValue()[0]); set<long> allpasses = unique(oa.pass); for (set<long>::iterator i=allpasses.begin(); i!=allpasses.end(); i++) { if (oa.getPassLength(*i)<minPassLength) { removePts = removePts || (oa.pass==*i); } } oa.edit(removePts); size_t editedLength = oa.getNumSatEpochs(); if (!numeric) { cout << "Edited " << (originalLength-editedLength) << " points ("; cout << setprecision(2) << 100.*(originalLength-editedLength)/originalLength; cout << "%)." << endl; } if (!numeric) { cout << "Removing mean of each pass." << endl; } for (set<long>::iterator iPass=allpasses.begin(); iPass!=allpasses.end() ; iPass++) { valarray<bool> passMask = (oa.pass==*iPass); valarray<double> mpVals = oa.observation[passMask]; valarray<double> binVals(mpVals.size()); double mean = mpVals.sum() / mpVals.size(); mpVals -= mean; oa.observation[passMask]=mpVals; } allpasses = unique(oa.pass); if (!numeric) { if (verbose) { cout <<"Using this combination for multipath: " <<mp_formula<<endl; cout << "Data collection interval is " << setprecision(3) << oa.interval << " seconds"; if (oa.intervalInferred) cout << ", inferred from data"; else cout << ", read from file headers"; cout << "." <<endl; } cout << "Overhead passes used: "; cout << allpasses.size() << endl; } if (rawOption.getCount()>0) { dumpRaw(cout, oa, numeric); } else { bool byAzimuth = (azimuthOption.getCount()>0); angInterval = StringUtils::asDouble(angWidthOption.getValue()[0]); bool regularIntervals = (byAzimuth || (angWidthOption.getCount()>0)); SparseBinnedStats<double> sbs; if (binOption.getCount()==0) { if (!byAzimuth) { if (!regularIntervals) { sbs.addBin(0,90); sbs.addBin(10,30); sbs.addBin(20,40); sbs.addBin(40,90); sbs.addBin(10,90); } else { for (double d=0; d<90; d+=angInterval) sbs.addBin(d,d+angInterval); } } else { for (double d=0; d<359; d+=angInterval) sbs.addBin(d,d+angInterval); } } else { for (int k=0; k<binOption.getValue().size(); k++) { string temp = binOption.getValue()[k]; string lowerWord = StringUtils::word(temp,0,','); string upperWord = StringUtils::word(temp,1,','); sbs.addBin(StringUtils::asDouble(lowerWord), StringUtils::asDouble(upperWord)); } } for (set<long>::iterator iPass=allpasses.begin(); iPass!=allpasses.end() ; iPass++) { valarray<bool> passMask = (oa.pass==*iPass); valarray<double> mpVals = oa.observation[passMask]; valarray<double> binVals(mpVals.size()); if (!byAzimuth) binVals = oa.elevation[passMask]; else binVals = oa.azimuth[passMask]; sbs.addData(mpVals, binVals); } writeStats(cout, sbs, numeric, !byAzimuth); } DayTime then; if ( (verbose) && (!numeric)) cout << "Processing complete in " << then - now << " seconds." << endl; } catch (Exception& e) { cerr << e << endl; } return 0; } void dumpRaw(std::ostream& ostr, const ObsArray& oa, bool numeric) { if (numeric) { ostr << "# GPS Week, Seconds of week, Sat. id, Sat. system, Pass, "; ostr << "Multipath value, LLI indicator, Azimuth, Elevation " << endl; } for (size_t i=0; i<oa.observation.size(); i++) { if (!numeric) { ostr << oa.epoch[i] << " " << oa.satellite[i] << " "; ostr << "Pass " << oa.pass[i] << " "; ostr << setprecision(12) << oa.observation[i]; if (oa.validAzEl[i]) { ostr << setprecision(5); ostr << " Az " << oa.azimuth[i]; ostr << " El " << oa.elevation[i]; } if (oa.lli[i]) ostr << " <- Loss of lock"; ostr << std::endl; } else { ostr << setprecision(4) << oa.epoch[i].GPSfullweek() << " "; ostr << setprecision(6) << oa.epoch[i].GPSsow() << " "; ostr << oa.satellite[i].id << " "; ostr << (int) oa.satellite[i].system << " "; ostr << oa.pass[i] << " "; ostr << setprecision(12) << oa.observation[i] << " "; ostr << (int) oa.lli[i]; if (oa.validAzEl[i]) { ostr << setprecision(5); ostr << " " << oa.azimuth[i]; ostr << " " << oa.elevation[i]; } ostr << std::endl; } } } void writeStats(std::ostream& ostr, const SparseBinnedStats<double>& mstats, bool numeric, bool elevation) { std::string angDesc = "elevation"; if (!elevation) angDesc = "azimuth"; if(!numeric) { ostr << endl; ostr << "Standard deviation of bins sorted by " << angDesc << "." << endl << endl; for (int i=0; i<mstats.stats.size(); i++) { ostr << "From " << setw(3) << mstats.bins[i].lowerBound; ostr << " to " << setw(3) << mstats.bins[i].upperBound; ostr << ": " << setprecision(3) << mstats.stats[i].StdDev() << endl; } ostr << endl; ostr << "Total points used: " << mstats.usedCount << endl; ostr << " rejected: " << mstats.rejectedCount << endl; } else { ostr << "# Bins of " << angDesc << " -- columns are min, max, standard deviation " << endl; for (int i=0; i<mstats.stats.size(); i++) { ostr << setw(3) << mstats.bins[i].lowerBound << " "; ostr << setw(3) << mstats.bins[i].upperBound << " "; ostr << setprecision(3) << mstats.stats[i].StdDev() << endl; } } } <|endoftext|>
<commit_before>#pragma once #include <iterator> #include <stdexcept> #include <limits> #include <functional> #include <numeric> #include "acmacs-base/throw.hh" #include "acmacs-base/stream.hh" // ---------------------------------------------------------------------- namespace acmacs { namespace internal { template <typename T, typename Increment> class input_iterator : public std::iterator<std::input_iterator_tag, T> { public: constexpr static const T End{std::numeric_limits<T>::max()}; inline input_iterator() : current(End) {} inline input_iterator(T aFirst, const Increment& aIncrement) : current(aFirst), increment(aIncrement) { increment.find_valid(current); } inline input_iterator(T aFirst, Increment&& aIncrement) : current(aFirst), increment(std::move(aIncrement)) { increment.find_valid(current); } inline input_iterator& operator++() { increment(current); return *this;} // inline input_iterator operator++(int) { input_iterator result = *this; ++(*this); return result; } inline bool operator==(const input_iterator& other) const { return current == other.current; } inline bool operator!=(const input_iterator& other) const { return !(*this == other); } inline const T& operator*() const { return current; } inline T& operator*() { return current; } private: T current; Increment increment; }; // input_iterator<> } // namespace internal // ---------------------------------------------------------------------- // template <typename T> class Range // { // private: // class increment // { // public: // inline increment() {} // inline increment(T aStep, T aLast) : step(aStep), last(aLast) { if (step == T{0}) THROW_OR_VOID(std::runtime_error("Invalid range with step 0")); } // inline void operator()(T& current) // { // if (current != internal::input_iterator<T, increment>::End) { // current += step; // if (step > 0) { // if (current >= last) // current = internal::input_iterator<T, increment>::End; // } // else { // if (current <= last) // current = internal::input_iterator<T, increment>::End; // } // } // } // inline void find_valid(T&) {} // private: // T step; // T last; // }; // class iterator : public internal::input_iterator<T, increment> // { // public: // inline iterator() : internal::input_iterator<T, increment>() {} // inline iterator(T aFirst, T aLast, T aStep) : internal::input_iterator<T, increment>(aFirst, {aStep, aLast}) {} // }; // public: // static inline iterator begin(T first, T last, T step = T{1}) // { // return {first, last, step}; // } // static inline iterator begin(T last) // { // return {T{0}, last, T{1}}; // } // static inline iterator end() // { // return {}; // } // }; // class Range // ---------------------------------------------------------------------- class IndexGenerator { public: using Validator = std::function<bool (size_t)>; private: class increment { public: inline increment() {} inline increment(size_t aLast, Validator aValidator) : last(aLast), valid(aValidator) {} inline bool end(size_t current) const { return current == internal::input_iterator<size_t, increment>::End; } inline size_t end() const { return internal::input_iterator<size_t, increment>::End; } inline void operator()(size_t& current) { if (!end(current)) { ++current; while (current < last && !valid(current)) ++current; if (current >= last) current = end(); } } inline void find_valid(size_t& current) { while (!end(current) && !valid(current)) operator()(current); } size_t last; Validator valid; }; public: inline IndexGenerator(size_t aFirst, size_t aLast, Validator aValidator) : mFirst(aFirst), mIncrement(aLast, aValidator) {} inline IndexGenerator(size_t aLast, Validator aValidator) : mFirst(0), mIncrement(aLast, aValidator) {} using iterator = internal::input_iterator<size_t, IndexGenerator::increment>; inline iterator begin() const { return {mFirst, mIncrement}; } inline iterator end() const { return {}; } private: size_t mFirst; increment mIncrement; }; // class IndexGenerator // ---------------------------------------------------------------------- template <typename Index> class index_iterator { public: using difference_type = long; using value_type = Index; using pointer = Index*; using reference = Index&; using iterator_category = std::random_access_iterator_tag; inline index_iterator(value_type aValue) : value(aValue) {} inline index_iterator& operator++() { ++value; return *this;} //inline index_iterator operator++(int) { iterator retval = *this; ++(*this); return retval;} inline bool operator==(const index_iterator<Index>& other) const { return value == other.value; } inline bool operator!=(const index_iterator<Index>& other) const { return !(*this == other); } inline value_type operator*() const { return value; } inline difference_type operator-(const index_iterator<Index>& other) const { return static_cast<difference_type>(value) - static_cast<difference_type>(other.value); } private: value_type value; }; // class index_iterator<> index_iterator(size_t) -> index_iterator<size_t>; index_iterator(int) -> index_iterator<int>; template <typename Index> class incrementer { public: inline incrementer(Index aBegin, Index aEnd) : mBegin{aBegin}, mEnd{aEnd} { if (mEnd < mBegin) throw std::runtime_error("acmacs::incrementer: end < begin"); } inline index_iterator<Index> begin() { return mBegin; } inline index_iterator<Index> end() { return mEnd; } private: Index mBegin, mEnd; }; // class incrementer<> incrementer(size_t, size_t) -> incrementer<size_t>; incrementer(int, int) -> incrementer<int>; // ---------------------------------------------------------------------- template <typename Index> inline void fill_with_indexes(std::vector<Index>& aToFill, Index aBegin, Index aEnd) { aToFill.resize(aEnd - aBegin); std::iota(aToFill.begin(), aToFill.end(), aBegin); } template <typename Index> inline void fill_with_indexes(std::vector<Index>& aToFill, Index aSize) { aToFill.resize(aSize); std::iota(aToFill.begin(), aToFill.end(), 0); } template <typename Index> inline std::vector<Index> filled_with_indexes(Index aSize) { std::vector<Index> result(aSize); std::iota(result.begin(), result.end(), 0); return result; } // ---------------------------------------------------------------------- } // namespace acmacs // ---------------------------------------------------------------------- #ifdef ACMACS_TARGET_OS inline std::ostream& operator << (std::ostream& out, const acmacs::IndexGenerator& aGen) { return stream_internal::write_to_stream(out, aGen, "<", ">", ", "); } #endif // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>acmacs:incrementer renamed to acmacs::range<commit_after>#pragma once #include <iterator> #include <stdexcept> #include <limits> #include <functional> #include <numeric> #include "acmacs-base/throw.hh" #include "acmacs-base/stream.hh" // ---------------------------------------------------------------------- namespace acmacs { namespace internal { template <typename T, typename Increment> class input_iterator : public std::iterator<std::input_iterator_tag, T> { public: constexpr static const T End{std::numeric_limits<T>::max()}; inline input_iterator() : current(End) {} inline input_iterator(T aFirst, const Increment& aIncrement) : current(aFirst), increment(aIncrement) { increment.find_valid(current); } inline input_iterator(T aFirst, Increment&& aIncrement) : current(aFirst), increment(std::move(aIncrement)) { increment.find_valid(current); } inline input_iterator& operator++() { increment(current); return *this;} // inline input_iterator operator++(int) { input_iterator result = *this; ++(*this); return result; } inline bool operator==(const input_iterator& other) const { return current == other.current; } inline bool operator!=(const input_iterator& other) const { return !(*this == other); } inline const T& operator*() const { return current; } inline T& operator*() { return current; } private: T current; Increment increment; }; // input_iterator<> } // namespace internal // ---------------------------------------------------------------------- // template <typename T> class Range // { // private: // class increment // { // public: // inline increment() {} // inline increment(T aStep, T aLast) : step(aStep), last(aLast) { if (step == T{0}) THROW_OR_VOID(std::runtime_error("Invalid range with step 0")); } // inline void operator()(T& current) // { // if (current != internal::input_iterator<T, increment>::End) { // current += step; // if (step > 0) { // if (current >= last) // current = internal::input_iterator<T, increment>::End; // } // else { // if (current <= last) // current = internal::input_iterator<T, increment>::End; // } // } // } // inline void find_valid(T&) {} // private: // T step; // T last; // }; // class iterator : public internal::input_iterator<T, increment> // { // public: // inline iterator() : internal::input_iterator<T, increment>() {} // inline iterator(T aFirst, T aLast, T aStep) : internal::input_iterator<T, increment>(aFirst, {aStep, aLast}) {} // }; // public: // static inline iterator begin(T first, T last, T step = T{1}) // { // return {first, last, step}; // } // static inline iterator begin(T last) // { // return {T{0}, last, T{1}}; // } // static inline iterator end() // { // return {}; // } // }; // class Range // ---------------------------------------------------------------------- class IndexGenerator { public: using Validator = std::function<bool (size_t)>; private: class increment { public: inline increment() {} inline increment(size_t aLast, Validator aValidator) : last(aLast), valid(aValidator) {} inline bool end(size_t current) const { return current == internal::input_iterator<size_t, increment>::End; } inline size_t end() const { return internal::input_iterator<size_t, increment>::End; } inline void operator()(size_t& current) { if (!end(current)) { ++current; while (current < last && !valid(current)) ++current; if (current >= last) current = end(); } } inline void find_valid(size_t& current) { while (!end(current) && !valid(current)) operator()(current); } size_t last; Validator valid; }; public: inline IndexGenerator(size_t aFirst, size_t aLast, Validator aValidator) : mFirst(aFirst), mIncrement(aLast, aValidator) {} inline IndexGenerator(size_t aLast, Validator aValidator) : mFirst(0), mIncrement(aLast, aValidator) {} using iterator = internal::input_iterator<size_t, IndexGenerator::increment>; inline iterator begin() const { return {mFirst, mIncrement}; } inline iterator end() const { return {}; } private: size_t mFirst; increment mIncrement; }; // class IndexGenerator // ---------------------------------------------------------------------- template <typename Index> class index_iterator { public: using difference_type = long; using value_type = Index; using pointer = Index*; using reference = Index&; using iterator_category = std::random_access_iterator_tag; inline index_iterator(value_type aValue) : value(aValue) {} inline index_iterator& operator++() { ++value; return *this;} //inline index_iterator operator++(int) { iterator retval = *this; ++(*this); return retval;} inline bool operator==(const index_iterator<Index>& other) const { return value == other.value; } inline bool operator!=(const index_iterator<Index>& other) const { return !(*this == other); } inline value_type operator*() const { return value; } inline difference_type operator-(const index_iterator<Index>& other) const { return static_cast<difference_type>(value) - static_cast<difference_type>(other.value); } private: value_type value; }; // class index_iterator<> index_iterator(size_t) -> index_iterator<size_t>; index_iterator(int) -> index_iterator<int>; template <typename Index> class range { public: inline range(Index aBegin, Index aEnd) : mBegin{aBegin}, mEnd{aEnd} { if (mEnd < mBegin) throw std::runtime_error("acmacs::range: end < begin"); } inline index_iterator<Index> begin() { return mBegin; } inline index_iterator<Index> end() { return mEnd; } private: Index mBegin, mEnd; }; // class range<> range(size_t, size_t) -> range<size_t>; range(int, int) -> range<int>; // ---------------------------------------------------------------------- template <typename Index> inline void fill_with_indexes(std::vector<Index>& aToFill, Index aBegin, Index aEnd) { aToFill.resize(aEnd - aBegin); std::iota(aToFill.begin(), aToFill.end(), aBegin); } template <typename Index> inline void fill_with_indexes(std::vector<Index>& aToFill, Index aSize) { aToFill.resize(aSize); std::iota(aToFill.begin(), aToFill.end(), 0); } template <typename Index> inline std::vector<Index> filled_with_indexes(Index aSize) { std::vector<Index> result(aSize); std::iota(result.begin(), result.end(), 0); return result; } // ---------------------------------------------------------------------- } // namespace acmacs // ---------------------------------------------------------------------- #ifdef ACMACS_TARGET_OS inline std::ostream& operator << (std::ostream& out, const acmacs::IndexGenerator& aGen) { return stream_internal::write_to_stream(out, aGen, "<", ">", ", "); } #endif // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>