text
stringlengths
54
60.6k
<commit_before>#include "test_services.hpp" #define BOOST_TEST_MODULE #include <boost/test/included/unit_test.hpp> #include <iterator> BOOST_AUTO_TEST_CASE( service_without_any_characteristic_results_in_one_attribute ) { const auto number = empty_service::number_of_attributes; BOOST_CHECK_EQUAL( 1u, number ); } BOOST_AUTO_TEST_CASE( first_attribute_is_the_primary_service ) { const auto attr = empty_service::attribute_at< 0 >( 0 ); BOOST_CHECK_EQUAL( 0x2800, attr.uuid ); } static const std::uint8_t global_temperature_service_uuid[ 16 ] = { 0x2A, 0xD9, 0x91, 0x11, 0xAB, 0x5B, 0x58, 0xB0, 0x3B, 0x4F, 0x50, 0x44, 0x52, 0x6E, 0x42, 0xF0 }; static void check_service_uuid( const bluetoe::details::attribute_access_arguments& args, std::size_t size = sizeof( global_temperature_service_uuid ) ) { BOOST_CHECK_EQUAL_COLLECTIONS( std::begin( global_temperature_service_uuid ), std::begin( global_temperature_service_uuid ) + size, args.buffer, args.buffer + args.buffer_size ); } BOOST_AUTO_TEST_CASE( first_attribute_is_the_primary_service_and_can_be_read ) { const auto attr = empty_service::attribute_at< 0 >( 0 ); BOOST_REQUIRE( attr.access ); std::uint8_t buffer[ 16 ]; auto read = bluetoe::details::attribute_access_arguments::read( buffer, 0 ); const auto access_result = attr.access( read, 1 ); BOOST_CHECK( access_result == bluetoe::details::attribute_access_result::success ); check_service_uuid( read ); } BOOST_AUTO_TEST_CASE( first_attribute_is_the_primary_service_and_can_be_read_buffer_larger ) { const auto attr = empty_service::attribute_at< 0 >( 0 ); std::uint8_t buffer[ 20 ]; auto read = bluetoe::details::attribute_access_arguments::read( buffer, 0 ); const auto access_result = attr.access( read, 1 ); BOOST_CHECK( access_result == bluetoe::details::attribute_access_result::success ); check_service_uuid( read ); } BOOST_AUTO_TEST_CASE( first_attribute_is_the_primary_service_and_can_be_read_buffer_larger_with_offset ) { const auto attr = empty_service::attribute_at< 0 >( 0 ); std::uint8_t buffer[ 20 ]; auto read = bluetoe::details::attribute_access_arguments::read( buffer, 4 ); const auto access_result = attr.access( read, 1 ); BOOST_CHECK( access_result == bluetoe::details::attribute_access_result::success ); BOOST_CHECK_EQUAL_COLLECTIONS( std::begin( global_temperature_service_uuid ) + 4, std::end( global_temperature_service_uuid ), &read.buffer[ 0 ], &read.buffer[ read.buffer_size ]); } BOOST_AUTO_TEST_CASE( first_attribute_is_the_primary_service_and_can_be_read_buffer_larger_with_offset_16 ) { const auto attr = empty_service::attribute_at< 0 >( 0 ); std::uint8_t buffer[ 20 ]; auto read = bluetoe::details::attribute_access_arguments::read( buffer, 16 ); const auto access_result = attr.access( read, 1 ); BOOST_CHECK( access_result == bluetoe::details::attribute_access_result::success ); BOOST_CHECK_EQUAL( 0, read.buffer_size ); } BOOST_AUTO_TEST_CASE( first_attribute_is_the_primary_service_and_can_be_read_buffer_to_small ) { const auto attr = empty_service::attribute_at< 0 >( 0 ); std::uint8_t buffer[ 15 ]; auto read = bluetoe::details::attribute_access_arguments::read( buffer, 0 ); const auto access_result = attr.access( read, 1 ); BOOST_CHECK( access_result == bluetoe::details::attribute_access_result::read_truncated ); check_service_uuid( read, sizeof( buffer ) ); } BOOST_AUTO_TEST_CASE( write_to_primary_service ) { const auto attr = empty_service::attribute_at< 0 >( 0 ); std::uint8_t buffer[] = { 1, 2, 3 }; auto write = bluetoe::details::attribute_access_arguments::write( buffer ); const auto access_result = attr.access( write, 1 ); BOOST_CHECK( access_result == bluetoe::details::attribute_access_result::write_not_permitted ); } BOOST_FIXTURE_TEST_CASE( accessing_all_attributes, service_with_3_characteristics ) { static constexpr std::size_t expected_number_of_attributes = 7u; BOOST_REQUIRE_EQUAL( unsigned( number_of_attributes ), expected_number_of_attributes ); BOOST_CHECK_EQUAL( 0x2800, attribute_at< 0 >( 0 ).uuid ); BOOST_CHECK_EQUAL( 0x2803, attribute_at< 0 >( 1 ).uuid ); BOOST_CHECK_EQUAL( 0x0001, attribute_at< 0 >( 2 ).uuid ); BOOST_CHECK_EQUAL( 0x2803, attribute_at< 0 >( 3 ).uuid ); BOOST_CHECK_EQUAL( 0x0001, attribute_at< 0 >( 4 ).uuid ); BOOST_CHECK_EQUAL( 0x2803, attribute_at< 0 >( 5 ).uuid ); BOOST_CHECK_EQUAL( 0x0815, attribute_at< 0 >( 6 ).uuid ); } BOOST_FIXTURE_TEST_CASE( read_by_group_type_response, service_with_3_characteristics ) { std::uint8_t buffer[ 100 ]; std::uint8_t* const end = read_primary_service_response( std::begin( buffer ), std::end( buffer ), 12, true ); BOOST_CHECK_EQUAL( end - std::begin( buffer ), 20u ); static const std::uint8_t expected_result[] = { 0x0c, 0x00, // Starting Handle 0x12, 0x00, // Ending Handle 0xA9, 0x3C, 0xC7, 0x5B, // Attribute Value == 128 bit UUID 0xED, 0x4E, 0x8A, 0xA2, 0x9F, 0x49, 0xE2, 0x0D, 0x94, 0x40, 0x8B, 0x8C }; BOOST_CHECK_EQUAL_COLLECTIONS( std::begin( buffer ), end, std::begin( expected_result ), std::end( expected_result ) ); } BOOST_FIXTURE_TEST_CASE( read_by_group_type_response_buffer_to_small, service_with_3_characteristics ) { std::uint8_t buffer[ 19 ]; std::uint16_t index = 1; std::uint8_t* const end = read_primary_service_response( std::begin( buffer ), std::end( buffer ), index, true ); BOOST_CHECK( end == std::begin( buffer ) ); } BOOST_FIXTURE_TEST_CASE( read_by_group_type_response_for_16bit_uuid, cycling_speed_and_cadence_service ) { std::uint8_t buffer[ 100 ]; std::uint8_t* const end = read_primary_service_response( std::begin( buffer ), std::end( buffer ), 1, false ); BOOST_CHECK_EQUAL( end - std::begin( buffer ), 6u ); static const std::uint8_t expected_result[] = { 0x01, 0x00, // Starting Handle 0x05, 0x00, // Ending Handle 0x16, 0x18 // Attribute Value == 16 bit UUID }; BOOST_CHECK_EQUAL_COLLECTIONS( std::begin( buffer ), end, std::begin( expected_result ), std::end( expected_result ) ); } BOOST_FIXTURE_TEST_CASE( primary_service_value_compare_128bit, global_temperature_service ) { auto compare = bluetoe::details::attribute_access_arguments::compare_value( &global_temperature_service_uuid[ 0 ], &global_temperature_service_uuid[ sizeof global_temperature_service_uuid ]); BOOST_CHECK( attribute_at< 0 >( 0 ).access( compare, 1 ) == bluetoe::details::attribute_access_result::value_equal ); } BOOST_AUTO_TEST_SUITE( number_of_client_configs ) BOOST_AUTO_TEST_CASE( without_notifications_there_is_no_demand_for_client_configurations ) { BOOST_CHECK_EQUAL( 0, int( service_with_3_characteristics::number_of_client_configs ) ); } char v1, v2, v3; typedef bluetoe::service< bluetoe::service_uuid16< 0x8C8B4 >, bluetoe::characteristic< bluetoe::characteristic_uuid16< 0x8C8B4 >, bluetoe::bind_characteristic_value< decltype( v1 ), &v1 >, bluetoe::notify >, bluetoe::characteristic< bluetoe::characteristic_uuid16< 0x8C8B5 >, bluetoe::bind_characteristic_value< decltype( v2 ), &v2 > >, bluetoe::characteristic< bluetoe::characteristic_uuid16< 0x8C8B6 >, bluetoe::bind_characteristic_value< decltype( v2 ), &v3 >, bluetoe::notify > > service_with_2_notifications; BOOST_AUTO_TEST_CASE( service_with_2_notifications_has_2_client_configurations ) { BOOST_CHECK_EQUAL( 2, int( service_with_2_notifications::number_of_client_configs ) ); } BOOST_AUTO_TEST_SUITE_END() <commit_msg>search the attribute for the notificated value<commit_after>#include <iostream> #include "test_services.hpp" #define BOOST_TEST_MODULE #include <boost/test/included/unit_test.hpp> #include <iterator> BOOST_AUTO_TEST_CASE( service_without_any_characteristic_results_in_one_attribute ) { const auto number = empty_service::number_of_attributes; BOOST_CHECK_EQUAL( 1u, number ); } BOOST_AUTO_TEST_CASE( first_attribute_is_the_primary_service ) { const auto attr = empty_service::attribute_at< 0 >( 0 ); BOOST_CHECK_EQUAL( 0x2800, attr.uuid ); } static const std::uint8_t global_temperature_service_uuid[ 16 ] = { 0x2A, 0xD9, 0x91, 0x11, 0xAB, 0x5B, 0x58, 0xB0, 0x3B, 0x4F, 0x50, 0x44, 0x52, 0x6E, 0x42, 0xF0 }; static void check_service_uuid( const bluetoe::details::attribute_access_arguments& args, std::size_t size = sizeof( global_temperature_service_uuid ) ) { BOOST_CHECK_EQUAL_COLLECTIONS( std::begin( global_temperature_service_uuid ), std::begin( global_temperature_service_uuid ) + size, args.buffer, args.buffer + args.buffer_size ); } BOOST_AUTO_TEST_CASE( first_attribute_is_the_primary_service_and_can_be_read ) { const auto attr = empty_service::attribute_at< 0 >( 0 ); BOOST_REQUIRE( attr.access ); std::uint8_t buffer[ 16 ]; auto read = bluetoe::details::attribute_access_arguments::read( buffer, 0 ); const auto access_result = attr.access( read, 1 ); BOOST_CHECK( access_result == bluetoe::details::attribute_access_result::success ); check_service_uuid( read ); } BOOST_AUTO_TEST_CASE( first_attribute_is_the_primary_service_and_can_be_read_buffer_larger ) { const auto attr = empty_service::attribute_at< 0 >( 0 ); std::uint8_t buffer[ 20 ]; auto read = bluetoe::details::attribute_access_arguments::read( buffer, 0 ); const auto access_result = attr.access( read, 1 ); BOOST_CHECK( access_result == bluetoe::details::attribute_access_result::success ); check_service_uuid( read ); } BOOST_AUTO_TEST_CASE( first_attribute_is_the_primary_service_and_can_be_read_buffer_larger_with_offset ) { const auto attr = empty_service::attribute_at< 0 >( 0 ); std::uint8_t buffer[ 20 ]; auto read = bluetoe::details::attribute_access_arguments::read( buffer, 4 ); const auto access_result = attr.access( read, 1 ); BOOST_CHECK( access_result == bluetoe::details::attribute_access_result::success ); BOOST_CHECK_EQUAL_COLLECTIONS( std::begin( global_temperature_service_uuid ) + 4, std::end( global_temperature_service_uuid ), &read.buffer[ 0 ], &read.buffer[ read.buffer_size ]); } BOOST_AUTO_TEST_CASE( first_attribute_is_the_primary_service_and_can_be_read_buffer_larger_with_offset_16 ) { const auto attr = empty_service::attribute_at< 0 >( 0 ); std::uint8_t buffer[ 20 ]; auto read = bluetoe::details::attribute_access_arguments::read( buffer, 16 ); const auto access_result = attr.access( read, 1 ); BOOST_CHECK( access_result == bluetoe::details::attribute_access_result::success ); BOOST_CHECK_EQUAL( 0, read.buffer_size ); } BOOST_AUTO_TEST_CASE( first_attribute_is_the_primary_service_and_can_be_read_buffer_to_small ) { const auto attr = empty_service::attribute_at< 0 >( 0 ); std::uint8_t buffer[ 15 ]; auto read = bluetoe::details::attribute_access_arguments::read( buffer, 0 ); const auto access_result = attr.access( read, 1 ); BOOST_CHECK( access_result == bluetoe::details::attribute_access_result::read_truncated ); check_service_uuid( read, sizeof( buffer ) ); } BOOST_AUTO_TEST_CASE( write_to_primary_service ) { const auto attr = empty_service::attribute_at< 0 >( 0 ); std::uint8_t buffer[] = { 1, 2, 3 }; auto write = bluetoe::details::attribute_access_arguments::write( buffer ); const auto access_result = attr.access( write, 1 ); BOOST_CHECK( access_result == bluetoe::details::attribute_access_result::write_not_permitted ); } BOOST_FIXTURE_TEST_CASE( accessing_all_attributes, service_with_3_characteristics ) { static constexpr std::size_t expected_number_of_attributes = 7u; BOOST_REQUIRE_EQUAL( unsigned( number_of_attributes ), expected_number_of_attributes ); BOOST_CHECK_EQUAL( 0x2800, attribute_at< 0 >( 0 ).uuid ); BOOST_CHECK_EQUAL( 0x2803, attribute_at< 0 >( 1 ).uuid ); BOOST_CHECK_EQUAL( 0x0001, attribute_at< 0 >( 2 ).uuid ); BOOST_CHECK_EQUAL( 0x2803, attribute_at< 0 >( 3 ).uuid ); BOOST_CHECK_EQUAL( 0x0001, attribute_at< 0 >( 4 ).uuid ); BOOST_CHECK_EQUAL( 0x2803, attribute_at< 0 >( 5 ).uuid ); BOOST_CHECK_EQUAL( 0x0815, attribute_at< 0 >( 6 ).uuid ); } BOOST_FIXTURE_TEST_CASE( read_by_group_type_response, service_with_3_characteristics ) { std::uint8_t buffer[ 100 ]; std::uint8_t* const end = read_primary_service_response( std::begin( buffer ), std::end( buffer ), 12, true ); BOOST_CHECK_EQUAL( end - std::begin( buffer ), 20u ); static const std::uint8_t expected_result[] = { 0x0c, 0x00, // Starting Handle 0x12, 0x00, // Ending Handle 0xA9, 0x3C, 0xC7, 0x5B, // Attribute Value == 128 bit UUID 0xED, 0x4E, 0x8A, 0xA2, 0x9F, 0x49, 0xE2, 0x0D, 0x94, 0x40, 0x8B, 0x8C }; BOOST_CHECK_EQUAL_COLLECTIONS( std::begin( buffer ), end, std::begin( expected_result ), std::end( expected_result ) ); } BOOST_FIXTURE_TEST_CASE( read_by_group_type_response_buffer_to_small, service_with_3_characteristics ) { std::uint8_t buffer[ 19 ]; std::uint16_t index = 1; std::uint8_t* const end = read_primary_service_response( std::begin( buffer ), std::end( buffer ), index, true ); BOOST_CHECK( end == std::begin( buffer ) ); } BOOST_FIXTURE_TEST_CASE( read_by_group_type_response_for_16bit_uuid, cycling_speed_and_cadence_service ) { std::uint8_t buffer[ 100 ]; std::uint8_t* const end = read_primary_service_response( std::begin( buffer ), std::end( buffer ), 1, false ); BOOST_CHECK_EQUAL( end - std::begin( buffer ), 6u ); static const std::uint8_t expected_result[] = { 0x01, 0x00, // Starting Handle 0x05, 0x00, // Ending Handle 0x16, 0x18 // Attribute Value == 16 bit UUID }; BOOST_CHECK_EQUAL_COLLECTIONS( std::begin( buffer ), end, std::begin( expected_result ), std::end( expected_result ) ); } BOOST_FIXTURE_TEST_CASE( primary_service_value_compare_128bit, global_temperature_service ) { auto compare = bluetoe::details::attribute_access_arguments::compare_value( &global_temperature_service_uuid[ 0 ], &global_temperature_service_uuid[ sizeof global_temperature_service_uuid ]); BOOST_CHECK( attribute_at< 0 >( 0 ).access( compare, 1 ) == bluetoe::details::attribute_access_result::value_equal ); } BOOST_AUTO_TEST_SUITE( number_of_client_configs ) BOOST_AUTO_TEST_CASE( without_notifications_there_is_no_demand_for_client_configurations ) { BOOST_CHECK_EQUAL( 0, int( service_with_3_characteristics::number_of_client_configs ) ); } char v1, v2, v3; typedef bluetoe::service< bluetoe::service_uuid16< 0x8C8B >, bluetoe::characteristic< bluetoe::characteristic_uuid16< 0x8C8B >, bluetoe::bind_characteristic_value< decltype( v1 ), &v1 >, bluetoe::notify >, bluetoe::characteristic< bluetoe::characteristic_uuid16< 0x8C8C >, bluetoe::bind_characteristic_value< decltype( v2 ), &v2 > >, bluetoe::characteristic< bluetoe::characteristic_uuid16< 0x8C8D >, bluetoe::bind_characteristic_value< decltype( v3 ), &v3 >, bluetoe::notify > > service_with_2_notifications; BOOST_AUTO_TEST_CASE( service_with_2_notifications_has_2_client_configurations ) { BOOST_CHECK_EQUAL( 2, int( service_with_2_notifications::number_of_client_configs ) ); } // just to be sure BOOST_FIXTURE_TEST_CASE( check_service_with_2_notifications_attribute_layout, service_with_2_notifications ) { BOOST_CHECK_EQUAL( 0x2800, attribute_at< 0 >( 0 ).uuid ); BOOST_CHECK_EQUAL( 0x2803, attribute_at< 0 >( 1 ).uuid ); BOOST_CHECK_EQUAL( 0x8C8B, attribute_at< 0 >( 2 ).uuid ); BOOST_CHECK_EQUAL( 0x2902, attribute_at< 0 >( 3 ).uuid ); BOOST_CHECK_EQUAL( 0x2803, attribute_at< 0 >( 4 ).uuid ); BOOST_CHECK_EQUAL( 0x8C8C, attribute_at< 0 >( 5 ).uuid ); BOOST_CHECK_EQUAL( 0x2803, attribute_at< 0 >( 6 ).uuid ); BOOST_CHECK_EQUAL( 0x8C8D, attribute_at< 0 >( 7 ).uuid ); BOOST_CHECK_EQUAL( 0x2902, attribute_at< 0 >( 8 ).uuid ); } BOOST_FIXTURE_TEST_CASE( notification_value_not_found, service_with_2_notifications ) { BOOST_CHECK_EQUAL( find_characteristic_value_declaration< 1 >( nullptr ).first, 0 ); } BOOST_FIXTURE_TEST_CASE( notification_value_found, service_with_2_notifications ) { std::pair< std::uint16_t, bluetoe::details::attribute > result1 = find_characteristic_value_declaration< 1 >( &v1 ); std::pair< std::uint16_t, bluetoe::details::attribute > result2 = find_characteristic_value_declaration< 1 >( &v3 ); BOOST_CHECK_EQUAL( result1.first, 3 ); BOOST_CHECK_EQUAL( result2.first, 8 ); } BOOST_AUTO_TEST_SUITE_END() <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2012-2020 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name PX4 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "LoadMon.hpp" // if free stack space falls below this, print a warning #if defined(CONFIG_ARMV7M_STACKCHECK) static constexpr unsigned STACK_LOW_WARNING_THRESHOLD = 100; #else static constexpr unsigned STACK_LOW_WARNING_THRESHOLD = 300; #endif static constexpr unsigned FDS_LOW_WARNING_THRESHOLD = 2; ///< if free file descriptors fall below this, print a warning using namespace time_literals; namespace load_mon { LoadMon::LoadMon() : ModuleParams(nullptr), ScheduledWorkItem(MODULE_NAME, px4::wq_configurations::lp_default) { } LoadMon::~LoadMon() { ScheduleClear(); perf_free(_cycle_perf); } int LoadMon::task_spawn(int argc, char *argv[]) { LoadMon *obj = new LoadMon(); if (!obj) { PX4_ERR("alloc failed"); return -1; } _object.store(obj); _task_id = task_id_is_work_queue; /* Schedule a cycle to start things. */ obj->start(); return 0; } void LoadMon::start() { ScheduleOnInterval(300_ms); } void LoadMon::Run() { perf_begin(_cycle_perf); cpuload(); if (_param_sys_stck_en.get()) { stack_usage(); } if (should_exit()) { ScheduleClear(); exit_and_cleanup(); } perf_end(_cycle_perf); } void LoadMon::cpuload() { if (_last_idle_time == 0) { // Just get the time in the first iteration */ _last_idle_time = system_load.tasks[0].total_runtime; _last_idle_time_sample = hrt_absolute_time(); return; } irqstate_t irqstate = enter_critical_section(); const hrt_abstime now = hrt_absolute_time(); const hrt_abstime total_runtime = system_load.tasks[0].total_runtime; leave_critical_section(irqstate); // compute system load const float interval = now - _last_idle_time_sample; const float interval_idletime = total_runtime - _last_idle_time; // get ram usage struct mallinfo mem = mallinfo(); float ram_usage = (float)mem.uordblks / mem.arena; cpuload_s cpuload{}; cpuload.load = 1.f - interval_idletime / interval; cpuload.ram_usage = ram_usage; cpuload.timestamp = hrt_absolute_time(); _cpuload_pub.publish(cpuload); // store for next iteration _last_idle_time = total_runtime; _last_idle_time_sample = now; } void LoadMon::stack_usage() { unsigned stack_free = 0; unsigned fds_free = FDS_LOW_WARNING_THRESHOLD + 1; bool checked_task = false; task_stack_info_s task_stack_info{}; static_assert(sizeof(task_stack_info.task_name) == CONFIG_TASK_NAME_SIZE, "task_stack_info.task_name must match NuttX CONFIG_TASK_NAME_SIZE"); sched_lock(); if (system_load.tasks[_stack_task_index].valid && (system_load.tasks[_stack_task_index].tcb->pid > 0)) { stack_free = up_check_tcbstack_remain(system_load.tasks[_stack_task_index].tcb); strncpy((char *)task_stack_info.task_name, system_load.tasks[_stack_task_index].tcb->name, CONFIG_TASK_NAME_SIZE - 1); task_stack_info.task_name[CONFIG_TASK_NAME_SIZE - 1] = '\0'; checked_task = true; #if CONFIG_NFILE_DESCRIPTORS > 0 FAR struct task_group_s *group = system_load.tasks[_stack_task_index].tcb->group; unsigned tcb_num_used_fds = 0; if (group) { for (int fd_index = 0; fd_index < CONFIG_NFILE_DESCRIPTORS; ++fd_index) { if (group->tg_filelist.fl_files[fd_index].f_inode) { ++tcb_num_used_fds; } } fds_free = CONFIG_NFILE_DESCRIPTORS - tcb_num_used_fds; } #endif // CONFIG_NFILE_DESCRIPTORS } sched_unlock(); if (checked_task) { task_stack_info.stack_free = stack_free; task_stack_info.timestamp = hrt_absolute_time(); _task_stack_info_pub.publish(task_stack_info); // Found task low on stack, report and exit. Continue here in next cycle. if (stack_free < STACK_LOW_WARNING_THRESHOLD) { PX4_WARN("%s low on stack! (%i bytes left)", task_stack_info.task_name, stack_free); } // Found task low on file descriptors, report and exit. Continue here in next cycle. if (fds_free < FDS_LOW_WARNING_THRESHOLD) { PX4_WARN("%s low on FDs! (%i FDs left)", task_stack_info.task_name, fds_free); } } // Continue after last checked task next cycle _stack_task_index = (_stack_task_index + 1) % CONFIG_MAX_TASKS; } int LoadMon::print_usage(const char *reason) { if (reason) { PX4_ERR("%s\n", reason); } PRINT_MODULE_DESCRIPTION( R"DESCR_STR( ### Description Background process running periodically with 1 Hz on the low priority work queue to calculate the CPU load and RAM usage and publish the `cpuload` topic. On NuttX it also checks the stack usage of each process and if it falls below 300 bytes, a warning is output, which will also appear in the log file. )DESCR_STR"); PRINT_MODULE_USAGE_NAME("load_mon", "system"); PRINT_MODULE_USAGE_COMMAND_DESCR("start", "Start the background task"); PRINT_MODULE_USAGE_DEFAULT_COMMANDS(); return 0; } extern "C" __EXPORT int load_mon_main(int argc, char *argv[]) { return LoadMon::main(argc, argv); } } // namespace load_mon <commit_msg>load_mon: remove obsolete rate comment in description<commit_after>/**************************************************************************** * * Copyright (c) 2012-2020 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name PX4 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ #include "LoadMon.hpp" // if free stack space falls below this, print a warning #if defined(CONFIG_ARMV7M_STACKCHECK) static constexpr unsigned STACK_LOW_WARNING_THRESHOLD = 100; #else static constexpr unsigned STACK_LOW_WARNING_THRESHOLD = 300; #endif static constexpr unsigned FDS_LOW_WARNING_THRESHOLD = 2; ///< if free file descriptors fall below this, print a warning using namespace time_literals; namespace load_mon { LoadMon::LoadMon() : ModuleParams(nullptr), ScheduledWorkItem(MODULE_NAME, px4::wq_configurations::lp_default) { } LoadMon::~LoadMon() { ScheduleClear(); perf_free(_cycle_perf); } int LoadMon::task_spawn(int argc, char *argv[]) { LoadMon *obj = new LoadMon(); if (!obj) { PX4_ERR("alloc failed"); return -1; } _object.store(obj); _task_id = task_id_is_work_queue; /* Schedule a cycle to start things. */ obj->start(); return 0; } void LoadMon::start() { ScheduleOnInterval(300_ms); } void LoadMon::Run() { perf_begin(_cycle_perf); cpuload(); if (_param_sys_stck_en.get()) { stack_usage(); } if (should_exit()) { ScheduleClear(); exit_and_cleanup(); } perf_end(_cycle_perf); } void LoadMon::cpuload() { if (_last_idle_time == 0) { // Just get the time in the first iteration */ _last_idle_time = system_load.tasks[0].total_runtime; _last_idle_time_sample = hrt_absolute_time(); return; } irqstate_t irqstate = enter_critical_section(); const hrt_abstime now = hrt_absolute_time(); const hrt_abstime total_runtime = system_load.tasks[0].total_runtime; leave_critical_section(irqstate); // compute system load const float interval = now - _last_idle_time_sample; const float interval_idletime = total_runtime - _last_idle_time; // get ram usage struct mallinfo mem = mallinfo(); float ram_usage = (float)mem.uordblks / mem.arena; cpuload_s cpuload{}; cpuload.load = 1.f - interval_idletime / interval; cpuload.ram_usage = ram_usage; cpuload.timestamp = hrt_absolute_time(); _cpuload_pub.publish(cpuload); // store for next iteration _last_idle_time = total_runtime; _last_idle_time_sample = now; } void LoadMon::stack_usage() { unsigned stack_free = 0; unsigned fds_free = FDS_LOW_WARNING_THRESHOLD + 1; bool checked_task = false; task_stack_info_s task_stack_info{}; static_assert(sizeof(task_stack_info.task_name) == CONFIG_TASK_NAME_SIZE, "task_stack_info.task_name must match NuttX CONFIG_TASK_NAME_SIZE"); sched_lock(); if (system_load.tasks[_stack_task_index].valid && (system_load.tasks[_stack_task_index].tcb->pid > 0)) { stack_free = up_check_tcbstack_remain(system_load.tasks[_stack_task_index].tcb); strncpy((char *)task_stack_info.task_name, system_load.tasks[_stack_task_index].tcb->name, CONFIG_TASK_NAME_SIZE - 1); task_stack_info.task_name[CONFIG_TASK_NAME_SIZE - 1] = '\0'; checked_task = true; #if CONFIG_NFILE_DESCRIPTORS > 0 FAR struct task_group_s *group = system_load.tasks[_stack_task_index].tcb->group; unsigned tcb_num_used_fds = 0; if (group) { for (int fd_index = 0; fd_index < CONFIG_NFILE_DESCRIPTORS; ++fd_index) { if (group->tg_filelist.fl_files[fd_index].f_inode) { ++tcb_num_used_fds; } } fds_free = CONFIG_NFILE_DESCRIPTORS - tcb_num_used_fds; } #endif // CONFIG_NFILE_DESCRIPTORS } sched_unlock(); if (checked_task) { task_stack_info.stack_free = stack_free; task_stack_info.timestamp = hrt_absolute_time(); _task_stack_info_pub.publish(task_stack_info); // Found task low on stack, report and exit. Continue here in next cycle. if (stack_free < STACK_LOW_WARNING_THRESHOLD) { PX4_WARN("%s low on stack! (%i bytes left)", task_stack_info.task_name, stack_free); } // Found task low on file descriptors, report and exit. Continue here in next cycle. if (fds_free < FDS_LOW_WARNING_THRESHOLD) { PX4_WARN("%s low on FDs! (%i FDs left)", task_stack_info.task_name, fds_free); } } // Continue after last checked task next cycle _stack_task_index = (_stack_task_index + 1) % CONFIG_MAX_TASKS; } int LoadMon::print_usage(const char *reason) { if (reason) { PX4_ERR("%s\n", reason); } PRINT_MODULE_DESCRIPTION( R"DESCR_STR( ### Description Background process running periodically on the low priority work queue to calculate the CPU load and RAM usage and publish the `cpuload` topic. On NuttX it also checks the stack usage of each process and if it falls below 300 bytes, a warning is output, which will also appear in the log file. )DESCR_STR"); PRINT_MODULE_USAGE_NAME("load_mon", "system"); PRINT_MODULE_USAGE_COMMAND_DESCR("start", "Start the background task"); PRINT_MODULE_USAGE_DEFAULT_COMMANDS(); return 0; } extern "C" __EXPORT int load_mon_main(int argc, char *argv[]) { return LoadMon::main(argc, argv); } } // namespace load_mon <|endoftext|>
<commit_before>#pragma once #include <cstdint> #include <vector> #include <string> namespace rtp { /// Max packet size. This is limited by the CC1201 buffer size. static const unsigned int MAX_DATA_SZ = 120; const uint8_t BROADCAST_ADDRESS = 0; const uint8_t BASE_STATION_ADDRESS = 1; const uint8_t LOOPBACK_ADDRESS = 2; /** * @brief Port enumerations for different communication protocols. */ enum port { SINK = 0, LINK, CONTROL, LEGACY, PING }; struct header_data { enum Type { Control, Tuning, FirmwareUpdate, Misc }; header_data(uint8_t p = SINK) : address(0), port(p), type(Control){}; uint8_t address; unsigned int port : 4; Type type : 4; /// "packed" size (in bytes) of header data size_t size() const { return 2; } void pack(std::vector<uint8_t>* buf) const { buf->push_back(address); buf->push_back(port << 4 | type); } void unpack(const std::vector<uint8_t>& buf) { unpack(buf.data()); } void unpack(const uint8_t* buf) { address = buf[1]; port = buf[2] >> 4; type = (Type)(buf[2] & 0x0F); } }; /** * @brief Real-Time packet definition */ class packet { public: rtp::header_data header; std::vector<uint8_t> payload; packet(){}; packet(const std::string& s, uint8_t p = SINK) : header(p) { for (char c : s) payload.push_back(c); payload.push_back('\0'); } template <class T> packet(const std::vector<T>& v, uint8_t p = SINK) : header(p) { for (T val : v) payload.push_back(val); } size_t size() const { return payload.size() + header.size(); } int port() const { return static_cast<int>(header.port); } template <class T> void port(T p) { header.port = static_cast<unsigned int>(p); } int address() { return header.address; } void address(int a) { header.address = static_cast<unsigned int>(a); } template <class T> void recv(const std::vector<T>& v) { recv(v.data(), v.size()); } void recv(const uint8_t* buffer, size_t size) { // note: header ignores the first byte since it's the size byte header.unpack(buffer); // Everything after the header is payload data payload.clear(); for (size_t i = header.size() + 1; i < size; i++) { payload.push_back(buffer[i]); } } void pack(std::vector<uint8_t>* buffer) const { // first byte is total size (excluding the size byte) const uint8_t total_size = payload.size() + header.size(); buffer->reserve(total_size + 1); buffer->push_back(total_size); header.pack(buffer); // payload buffer->insert(buffer->end(), payload.begin(), payload.end()); } }; } <commit_msg>assigned values to port enum<commit_after>#pragma once #include <cstdint> #include <vector> #include <string> namespace rtp { /// Max packet size. This is limited by the CC1201 buffer size. static const unsigned int MAX_DATA_SZ = 120; const uint8_t BROADCAST_ADDRESS = 0; const uint8_t BASE_STATION_ADDRESS = 1; const uint8_t LOOPBACK_ADDRESS = 2; /** * @brief Port enumerations for different communication protocols. */ enum port { SINK = 0, LINK = 1, CONTROL = 2, LEGACY = 3, PING = 4 }; struct header_data { enum Type { Control, Tuning, FirmwareUpdate, Misc }; header_data(uint8_t p = SINK) : address(0), port(p), type(Control){}; uint8_t address; unsigned int port : 4; Type type : 4; /// "packed" size (in bytes) of header data size_t size() const { return 2; } void pack(std::vector<uint8_t>* buf) const { buf->push_back(address); buf->push_back(port << 4 | type); } void unpack(const std::vector<uint8_t>& buf) { unpack(buf.data()); } void unpack(const uint8_t* buf) { address = buf[1]; port = buf[2] >> 4; type = (Type)(buf[2] & 0x0F); } }; /** * @brief Real-Time packet definition */ class packet { public: rtp::header_data header; std::vector<uint8_t> payload; packet(){}; packet(const std::string& s, uint8_t p = SINK) : header(p) { for (char c : s) payload.push_back(c); payload.push_back('\0'); } template <class T> packet(const std::vector<T>& v, uint8_t p = SINK) : header(p) { for (T val : v) payload.push_back(val); } size_t size() const { return payload.size() + header.size(); } int port() const { return static_cast<int>(header.port); } template <class T> void port(T p) { header.port = static_cast<unsigned int>(p); } int address() { return header.address; } void address(int a) { header.address = static_cast<unsigned int>(a); } template <class T> void recv(const std::vector<T>& v) { recv(v.data(), v.size()); } void recv(const uint8_t* buffer, size_t size) { // note: header ignores the first byte since it's the size byte header.unpack(buffer); // Everything after the header is payload data payload.clear(); for (size_t i = header.size() + 1; i < size; i++) { payload.push_back(buffer[i]); } } void pack(std::vector<uint8_t>* buffer) const { // first byte is total size (excluding the size byte) const uint8_t total_size = payload.size() + header.size(); buffer->reserve(total_size + 1); buffer->push_back(total_size); header.pack(buffer); // payload buffer->insert(buffer->end(), payload.begin(), payload.end()); } }; } <|endoftext|>
<commit_before>/* * GameKeeper Framework * * Copyright (C) 2013 Karol Herbst <gamekeeper@karolherbst.de> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "runtime.h" #include <gamekeeper/core/common.h> #include <cstdlib> #include <gamekeeper/core/logger.h> #include <gamekeeper/core/loggerStream.h> #include <gamekeeper/client/gamekeeper.h> #include <gamekeeper/client/hypodermic.h> #include <boost/program_options/options_description.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include <Hypodermic/ContainerBuilder.h> #include <Hypodermic/Helpers.h> #include <gamekeeper/core/curlfiledownloader.h> #ifdef GAMEKEEPER_OS_IS_WINDOWS #include <gamekeeper/core/windowsinformation.h> #define OSINFORMATIONCLASS WindowsInformation #else #include <gamekeeper/core/linuxinformation.h> #define OSINFORMATIONCLASS LinuxInformation #endif #include <gamekeeper/core/log4cpploggerFactory.h> #include <gamekeeper/core/xdgpaths.h> namespace po = boost::program_options; GAMEKEEPER_NAMESPACE_START(client) static std::shared_ptr<Hypodermic::IContainer> localContainer; static std::shared_ptr<Hypodermic::IContainer> container; GameKeeperRuntime::GameKeeperRuntime() { using namespace gamekeeper::core; Hypodermic::ContainerBuilder containerBuilder; // set up IoC container containerBuilder.registerType<Log4cppLoggerFactory>()-> as<LoggerFactory>()-> singleInstance(); localContainer = containerBuilder.build(); } GameKeeperRuntime::~GameKeeperRuntime() { delete this->gameKeeperUI; } gamekeeper::core::Logger& GameKeeperRuntime::getUILogger() { return localContainer->resolve<gamekeeper::core::LoggerFactory>()->getComponentLogger("UI.client"); } static void fillProperties(po::options_description & cmd, po::options_description & file) { po::options_description descGlobalCmd("Global options"); descGlobalCmd.add_options() ("help,h", "produce help message"); cmd.add(descGlobalCmd); } int GameKeeperRuntime::main(int argc, const char* argv[], GameKeeperUI * gameKeeperUI) { this->gameKeeperUI = gameKeeperUI; po::options_description descCmd; po::options_description descFile; fillProperties(descCmd, descFile); po::options_description cmdClient("Client options"); po::options_description fileClient; po::options_description bothClient; po::options_description_easy_init cmdClientEasy = cmdClient.add_options(); po::options_description_easy_init fileClientEasy = fileClient.add_options(); po::options_description_easy_init bothClientEasy = bothClient.add_options(); this->gameKeeperUI->addOptions(cmdClientEasy, fileClientEasy, bothClientEasy); if(!bothClient.options().empty()) { cmdClient.add(bothClient); fileClient.add(bothClient); } if(!cmdClient.options().empty()) { descCmd.add(cmdClient); } if(!fileClient.options().empty()) { descFile.add(fileClient); } po::variables_map vm; po::store(po::parse_command_line(argc, argv, descCmd), vm); //po::store(po::parse_config_file("", descFile), vm); if(vm.count("help") > 0) { std::cout << descCmd << std::endl; return EXIT_SUCCESS; } po::notify(vm); Hypodermic::ContainerBuilder containerBuilder; { using namespace gamekeeper::core; // set up IoC container containerBuilder.registerInstance<LoggerFactory>( localContainer->resolve<gamekeeper::core::LoggerFactory>())-> as<LoggerFactory>()-> singleInstance(); containerBuilder.registerType<OSINFORMATIONCLASS>()-> as<OSInformation>()-> singleInstance(); containerBuilder.registerType<XDGPaths>(CREATE(new XDGPaths(INJECT(OSInformation))))-> as<OSPaths>()-> singleInstance(); containerBuilder.registerType<CurlFileDownloader>(CREATE(new CurlFileDownloader(INJECT(LoggerFactory))))-> as<FileDownloader>()-> as<HttpFileDownloader>()-> singleInstance(); } container = containerBuilder.build(); std::shared_ptr<gamekeeper::core::LoggerFactory> loggerFactory = container->resolve<gamekeeper::core::LoggerFactory>(); loggerFactory->getComponentLogger("main") << gamekeeper::core::LogLevel::Debug << "firing up GameKeeper" << gamekeeper::core::endl; this->gameKeeperUI->init(vm); this->gameKeeperUI->startEventLoop(); this->gameKeeperUI->onShutdown(); return EXIT_SUCCESS; } Hypodermic::IContainer& HypodermicUtil::getContainer() { return *container; } GAMEKEEPER_NAMESPACE_END(client) <commit_msg>client/runtime: add PropertyResolver<commit_after>/* * GameKeeper Framework * * Copyright (C) 2013 Karol Herbst <gamekeeper@karolherbst.de> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "runtime.h" #include <gamekeeper/core/common.h> #include <cstdlib> #include <gamekeeper/core/logger.h> #include <gamekeeper/core/loggerStream.h> #include <gamekeeper/client/gamekeeper.h> #include <gamekeeper/client/hypodermic.h> #include <boost/program_options/options_description.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/variables_map.hpp> #include <Hypodermic/ContainerBuilder.h> #include <Hypodermic/Helpers.h> #include <gamekeeper/core/boostpopropertyresolver.h> #include <gamekeeper/core/curlfiledownloader.h> #ifdef GAMEKEEPER_OS_IS_WINDOWS #include <gamekeeper/core/windowsinformation.h> #define OSINFORMATIONCLASS WindowsInformation #else #include <gamekeeper/core/linuxinformation.h> #define OSINFORMATIONCLASS LinuxInformation #endif #include <gamekeeper/core/log4cpploggerFactory.h> #include <gamekeeper/core/xdgpaths.h> namespace po = boost::program_options; GAMEKEEPER_NAMESPACE_START(client) static std::shared_ptr<Hypodermic::IContainer> localContainer; static std::shared_ptr<Hypodermic::IContainer> container; GameKeeperRuntime::GameKeeperRuntime() { using namespace gamekeeper::core; Hypodermic::ContainerBuilder containerBuilder; // set up IoC container containerBuilder.registerType<Log4cppLoggerFactory>()-> as<LoggerFactory>()-> singleInstance(); localContainer = containerBuilder.build(); } GameKeeperRuntime::~GameKeeperRuntime() { delete this->gameKeeperUI; } gamekeeper::core::Logger& GameKeeperRuntime::getUILogger() { return localContainer->resolve<gamekeeper::core::LoggerFactory>()->getComponentLogger("UI.client"); } static void fillProperties(po::options_description & cmd, po::options_description & file) { po::options_description descGlobalCmd("Global options"); descGlobalCmd.add_options() ("help,h", "produce help message"); cmd.add(descGlobalCmd); } int GameKeeperRuntime::main(int argc, const char* argv[], GameKeeperUI * gameKeeperUI) { this->gameKeeperUI = gameKeeperUI; po::options_description descCmd; po::options_description descFile; fillProperties(descCmd, descFile); po::options_description cmdClient("Client options"); po::options_description fileClient; po::options_description bothClient; po::options_description_easy_init cmdClientEasy = cmdClient.add_options(); po::options_description_easy_init fileClientEasy = fileClient.add_options(); po::options_description_easy_init bothClientEasy = bothClient.add_options(); this->gameKeeperUI->addOptions(cmdClientEasy, fileClientEasy, bothClientEasy); if(!bothClient.options().empty()) { cmdClient.add(bothClient); fileClient.add(bothClient); } if(!cmdClient.options().empty()) { descCmd.add(cmdClient); } if(!fileClient.options().empty()) { descFile.add(fileClient); } po::variables_map vm; po::store(po::parse_command_line(argc, argv, descCmd), vm); //po::store(po::parse_config_file("", descFile), vm); if(vm.count("help") > 0) { std::cout << descCmd << std::endl; return EXIT_SUCCESS; } po::notify(vm); Hypodermic::ContainerBuilder containerBuilder; { using namespace gamekeeper::core; // set up IoC container containerBuilder.registerInstance<LoggerFactory>( localContainer->resolve<gamekeeper::core::LoggerFactory>())-> as<LoggerFactory>()-> singleInstance(); containerBuilder.registerType<BoostPOPropertyResolver>(CREATE_CAPTURED([&vm], new BoostPOPropertyResolver(vm)))-> as<PropertyResolver>()-> singleInstance(); containerBuilder.registerType<OSINFORMATIONCLASS>()-> as<OSInformation>()-> singleInstance(); containerBuilder.registerType<XDGPaths>(CREATE(new XDGPaths(INJECT(OSInformation))))-> as<OSPaths>()-> singleInstance(); containerBuilder.registerType<CurlFileDownloader>(CREATE(new CurlFileDownloader(INJECT(LoggerFactory))))-> as<FileDownloader>()-> as<HttpFileDownloader>()-> singleInstance(); } container = containerBuilder.build(); std::shared_ptr<gamekeeper::core::LoggerFactory> loggerFactory = container->resolve<gamekeeper::core::LoggerFactory>(); loggerFactory->getComponentLogger("main") << gamekeeper::core::LogLevel::Debug << "firing up GameKeeper" << gamekeeper::core::endl; this->gameKeeperUI->init(vm); this->gameKeeperUI->startEventLoop(); this->gameKeeperUI->onShutdown(); return EXIT_SUCCESS; } Hypodermic::IContainer& HypodermicUtil::getContainer() { return *container; } GAMEKEEPER_NAMESPACE_END(client) <|endoftext|>
<commit_before>/** * @file logging.cpp * @brief Logging class * * (c) 2013-2014 by Mega Limited, Auckland, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. * * This file is also distributed under the terms of the GNU General * Public License, see http://www.gnu.org/copyleft/gpl.txt for details. */ #if defined(WINDOWS_PHONE) && !defined(__STDC_LIMIT_MACROS) #define __STDC_LIMIT_MACROS #endif #include "mega/logging.h" #include <ctime> #if defined(WINDOWS_PHONE) #include <stdint.h> #endif namespace mega { Logger *SimpleLogger::logger = nullptr; // by the default, display logs with level equal or less than logInfo enum LogLevel SimpleLogger::logCurrentLevel = logInfo; long long SimpleLogger::maxPayloadLogSize = 10240; #ifdef ENABLE_LOG_PERFORMANCE #ifdef WIN32 thread_local std::array<char, LOGGER_CHUNKS_SIZE> SimpleLogger::mBuffer; #else __thread std::array<char, LOGGER_CHUNKS_SIZE> SimpleLogger::mBuffer; #endif #else // static member initialization std::mutex SimpleLogger::outputs_mutex; OutputMap SimpleLogger::outputs; std::string SimpleLogger::getTime() { char ts[50]; time_t t = std::time(NULL); struct tm tp; if (gmtime_r(&t, &tp) && std::strftime(ts, sizeof(ts), "%H:%M:%S", &tp)) return ts; return {}; } void SimpleLogger::flush() { for (auto& o : outputs) { OutputStreams::iterator iter; OutputStreams vec; { std::lock_guard<std::mutex> guard(outputs_mutex); vec = o; } for (iter = vec.begin(); iter != vec.end(); iter++) { std::ostream *os = *iter; os->flush(); } } } OutputStreams SimpleLogger::getOutput(enum LogLevel ll) { assert(unsigned(ll) < outputs.size()); std::lock_guard<std::mutex> guard(outputs_mutex); return outputs[ll]; } void SimpleLogger::addOutput(enum LogLevel ll, std::ostream *os) { assert(unsigned(ll) < outputs.size()); std::lock_guard<std::mutex> guard(outputs_mutex); outputs[ll].push_back(os); } void SimpleLogger::setAllOutputs(std::ostream *os) { std::lock_guard<std::mutex> guard(outputs_mutex); for (auto& o : outputs) { o.push_back(os); } } #endif } // namespace <commit_msg>use gmtime_s on win<commit_after>/** * @file logging.cpp * @brief Logging class * * (c) 2013-2014 by Mega Limited, Auckland, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. * * This file is also distributed under the terms of the GNU General * Public License, see http://www.gnu.org/copyleft/gpl.txt for details. */ #if defined(WINDOWS_PHONE) && !defined(__STDC_LIMIT_MACROS) #define __STDC_LIMIT_MACROS #endif #include "mega/logging.h" #include <ctime> #if defined(WINDOWS_PHONE) #include <stdint.h> #endif namespace mega { Logger *SimpleLogger::logger = nullptr; // by the default, display logs with level equal or less than logInfo enum LogLevel SimpleLogger::logCurrentLevel = logInfo; long long SimpleLogger::maxPayloadLogSize = 10240; #ifdef ENABLE_LOG_PERFORMANCE #ifdef WIN32 thread_local std::array<char, LOGGER_CHUNKS_SIZE> SimpleLogger::mBuffer; #else __thread std::array<char, LOGGER_CHUNKS_SIZE> SimpleLogger::mBuffer; #endif #else // static member initialization std::mutex SimpleLogger::outputs_mutex; OutputMap SimpleLogger::outputs; std::string SimpleLogger::getTime() { char ts[50]; time_t t = std::time(NULL); std::tm tm{}; #ifdef WIN32 gmtime_s(&tm, &t); #else gmtime_r(&t, &tm); #endif if (std::strftime(ts, sizeof(ts), "%H:%M:%S", &tm)) return ts; return {}; } void SimpleLogger::flush() { for (auto& o : outputs) { OutputStreams::iterator iter; OutputStreams vec; { std::lock_guard<std::mutex> guard(outputs_mutex); vec = o; } for (iter = vec.begin(); iter != vec.end(); iter++) { std::ostream *os = *iter; os->flush(); } } } OutputStreams SimpleLogger::getOutput(enum LogLevel ll) { assert(unsigned(ll) < outputs.size()); std::lock_guard<std::mutex> guard(outputs_mutex); return outputs[ll]; } void SimpleLogger::addOutput(enum LogLevel ll, std::ostream *os) { assert(unsigned(ll) < outputs.size()); std::lock_guard<std::mutex> guard(outputs_mutex); outputs[ll].push_back(os); } void SimpleLogger::setAllOutputs(std::ostream *os) { std::lock_guard<std::mutex> guard(outputs_mutex); for (auto& o : outputs) { o.push_back(os); } } #endif } // namespace <|endoftext|>
<commit_before>/* * Copyright © 2010 Intel Corporation * * 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 (including the next * paragraph) 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 "glsl_symbol_table.h" #include "ast.h" #include "glsl_types.h" #include "ir.h" static ir_instruction * match_function_by_name(exec_list *instructions, const char *name, YYLTYPE *loc, simple_node *parameters, struct _mesa_glsl_parse_state *state) { ir_function *f = state->symbols->get_function(name); if (f == NULL) { _mesa_glsl_error(loc, state, "function `%s' undeclared", name); return ir_call::get_error_instruction(); } /* Once we've determined that the function being called might exist, * process the parameters. */ exec_list actual_parameters; simple_node *const first = parameters; if (first != NULL) { simple_node *ptr = first; do { ir_instruction *const result = ((ast_node *) ptr)->hir(instructions, state); ptr = ptr->next; actual_parameters.push_tail(result); } while (ptr != first); } /* After processing the function's actual parameters, try to find an * overload of the function that matches. */ const ir_function_signature *sig = f->matching_signature(& actual_parameters); if (sig != NULL) { /* FINISHME: The list of actual parameters needs to be modified to * FINISHME: include any necessary conversions. */ return new ir_call(sig, & actual_parameters); } else { /* FINISHME: Log a better error message here. G++ will show the types * FINISHME: of the actual parameters and the set of candidate * FINISHME: functions. A different error should also be logged when * FINISHME: multiple functions match. */ _mesa_glsl_error(loc, state, "no matching function for call to `%s'", name); return ir_call::get_error_instruction(); } } ir_instruction * ast_function_expression::hir(exec_list *instructions, struct _mesa_glsl_parse_state *state) { /* There are three sorts of function calls. * * 1. contstructors - The first subexpression is an ast_type_specifier. * 2. methods - Only the .length() method of array types. * 3. functions - Calls to regular old functions. * * There are two kinds of constructor call. Constructors for built-in * language types, such as mat4 and vec2, are free form. The only * requirement is that the parameters must provide enough values of the * correct scalar type. Constructors for arrays and structures must have * the exact number of parameters with matching types in the correct order. * These constructors follow essentially the same type matching rules as * functions. * * Method calls are actually detected when the ast_field_selection * expression is handled. */ if (is_constructor()) { return ir_call::get_error_instruction(); } else { const ast_expression *id = subexpressions[0]; YYLTYPE loc = id->get_location(); return match_function_by_name(instructions, id->primary_expression.identifier, & loc, subexpressions[1], state); } return ir_call::get_error_instruction(); } <commit_msg>Begin processing constructors<commit_after>/* * Copyright © 2010 Intel Corporation * * 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 (including the next * paragraph) 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 "glsl_symbol_table.h" #include "ast.h" #include "glsl_types.h" #include "ir.h" static ir_instruction * match_function_by_name(exec_list *instructions, const char *name, YYLTYPE *loc, simple_node *parameters, struct _mesa_glsl_parse_state *state) { ir_function *f = state->symbols->get_function(name); if (f == NULL) { _mesa_glsl_error(loc, state, "function `%s' undeclared", name); return ir_call::get_error_instruction(); } /* Once we've determined that the function being called might exist, * process the parameters. */ exec_list actual_parameters; simple_node *const first = parameters; if (first != NULL) { simple_node *ptr = first; do { ir_instruction *const result = ((ast_node *) ptr)->hir(instructions, state); ptr = ptr->next; actual_parameters.push_tail(result); } while (ptr != first); } /* After processing the function's actual parameters, try to find an * overload of the function that matches. */ const ir_function_signature *sig = f->matching_signature(& actual_parameters); if (sig != NULL) { /* FINISHME: The list of actual parameters needs to be modified to * FINISHME: include any necessary conversions. */ return new ir_call(sig, & actual_parameters); } else { /* FINISHME: Log a better error message here. G++ will show the types * FINISHME: of the actual parameters and the set of candidate * FINISHME: functions. A different error should also be logged when * FINISHME: multiple functions match. */ _mesa_glsl_error(loc, state, "no matching function for call to `%s'", name); return ir_call::get_error_instruction(); } } ir_instruction * ast_function_expression::hir(exec_list *instructions, struct _mesa_glsl_parse_state *state) { /* There are three sorts of function calls. * * 1. contstructors - The first subexpression is an ast_type_specifier. * 2. methods - Only the .length() method of array types. * 3. functions - Calls to regular old functions. * * Method calls are actually detected when the ast_field_selection * expression is handled. */ if (is_constructor()) { const ast_type_specifier *type = (ast_type_specifier *) subexpressions[0]; YYLTYPE loc = type->get_location(); const glsl_type *const constructor_type = state->symbols->get_type(type->type_name); /* Constructors for samplers are illegal. */ if (constructor_type->is_sampler()) { _mesa_glsl_error(& loc, state, "cannot construct sampler type `%s'", constructor_type->name); return ir_call::get_error_instruction(); } /* There are two kinds of constructor call. Constructors for built-in * language types, such as mat4 and vec2, are free form. The only * requirement is that the parameters must provide enough values of the * correct scalar type. Constructors for arrays and structures must * have the exact number of parameters with matching types in the * correct order. These constructors follow essentially the same type * matching rules as functions. */ return ir_call::get_error_instruction(); } else { const ast_expression *id = subexpressions[0]; YYLTYPE loc = id->get_location(); return match_function_by_name(instructions, id->primary_expression.identifier, & loc, subexpressions[1], state); } return ir_call::get_error_instruction(); } <|endoftext|>
<commit_before>// NOTE/NUANCE: When including WITHIN a library, no sub-dir prefix is needed. #include "uber-library-example.h" // Constructor UberLibraryExample::Pin::Pin(int _number) { number = _number; state = LOW; } // Initializers that should be called in the `setup()` function void UberLibraryExample::Pin::beginInPinMode(PinMode _pinMode) { pinMode(number, _pinMode); } // Main API functions that the library provides // typically called in `loop()` or `setup()` functions void UberLibraryExample::Pin::modulateAtFrequency(int _ms) { setHigh(); delay(_ms); setLow(); delay(_ms); } // Getters int UberLibraryExample::Pin::getNumber() { return number; } bool UberLibraryExample::Pin::getState() { return state; } bool UberLibraryExample::Pin::getMode() { return mode; } bool UberLibraryExample::Pin::isHigh() { return state == HIGH ? true : false; } // Setters void UberLibraryExample::Pin::setHigh() { state = HIGH; setActualPinState(); } void UberLibraryExample::Pin::setLow() { state = LOW; setActualPinState(); } void UberLibraryExample::Pin::setActualPinState() { digitalWrite(number, state); } <commit_msg>Delete uber-library-example.cpp<commit_after><|endoftext|>
<commit_before><?hh /* include('b/blackhole.hh'); include('p/log.hh'); require('p/header.hh'); require('p/forms.hh'); require('p/footer.hh'); require('p/aws.hh'); require('p/aws_constants.hh'); */ function get_num_links(): string{ $dyclient = mk_aws()->get('DynamoDb'); $result = $dyclient->describeTable( array( 'TableName' => aws_config::LINK_TABLE)); return $result['Table']['ItemCount']; } function is_meta(): string{ if( ( isset($_SERVER['HTTP_REFERER']) && preg_match("/(https?:\/\/)?(cdn\.)?jump\.wtf(\/.*)?/", $_SERVER['HTTP_REFERER'])) || ( isset($_ENV['HTTP_REFERER']) && preg_match("/(https?:\/\/)?(cdn\.)?jump\.wtf(\/.*)?/", $_ENV['HTTP_REFERER'])) ) return "This is so meta."; else return ""; } function i_main(): void{ echo gen_html_tag(); echo gen_head(); $body = <body></body>; $body->appendChild(gen_nav()); $body->appendChild( <div class="jumbotron"> <div class="container centered"> <h1>Link Shortening / File Hosting Service</h1> <p> An experiment with AWS resources.<br/> By submitting a link or file, you are agreeing to this site's <a href="t.txt">Terms of Service and Privacy Policy</a>. <br /><br /> A total of {get_num_links()} links have been generated. <br /><br /> {is_meta()} </p> </div> </div> ); $body->appendChild(gen_form()); $body->appendChild(gen_footer()); foreach( gen_footer_scripts() as $script ) $body->appendChild($script); echo $body; echo "</html>"; } //i_main(); <commit_msg>Another type error<commit_after><?hh /* include('b/blackhole.hh'); include('p/log.hh'); require('p/header.hh'); require('p/forms.hh'); require('p/footer.hh'); require('p/aws.hh'); require('p/aws_constants.hh'); */ function get_num_links(): string{ $dyclient = mk_aws()->get('DynamoDb'); $result = $dyclient->describeTable( array( 'TableName' => aws_config::LINK_TABLE)); return (string) $result['Table']['ItemCount']; } function is_meta(): string{ if( ( isset($_SERVER['HTTP_REFERER']) && preg_match("/(https?:\/\/)?(cdn\.)?jump\.wtf(\/.*)?/", $_SERVER['HTTP_REFERER'])) || ( isset($_ENV['HTTP_REFERER']) && preg_match("/(https?:\/\/)?(cdn\.)?jump\.wtf(\/.*)?/", $_ENV['HTTP_REFERER'])) ) return "This is so meta."; else return ""; } function i_main(): void{ echo gen_html_tag(); echo gen_head(); $body = <body></body>; $body->appendChild(gen_nav()); $body->appendChild( <div class="jumbotron"> <div class="container centered"> <h1>Link Shortening / File Hosting Service</h1> <p> An experiment with AWS resources.<br/> By submitting a link or file, you are agreeing to this site's <a href="t.txt">Terms of Service and Privacy Policy</a>. <br /><br /> A total of {get_num_links()} links have been generated. <br /><br /> {is_meta()} </p> </div> </div> ); $body->appendChild(gen_form()); $body->appendChild(gen_footer()); foreach( gen_footer_scripts() as $script ) $body->appendChild($script); echo $body; echo "</html>"; } //i_main(); <|endoftext|>
<commit_before>/* Copyright (C) 2005-2008, Thorvald Natvig <thorvald@natvig.com> Copyright (C) 2007, Sebastian Schlingmann <mit_service@users.sourceforge.net> 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 Mumble Developers 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 FOUNDATION 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. */ /* need the undef or else the include would not work it would help to include the header before QT, but that might mess with QT */ #undef qDebug #include "ApplicationServices/ApplicationServices.h" #undef check #include "Global.h" #include "TextToSpeech.h" static QMutex qmLock; static Fixed fVolume; static QList<QByteArray> qlMessages; static bool bRunning; static bool bEnabled; static void process_speech(); static void speech_done_cb(SpeechChannel scChannel, long, void **, unsigned long *, long *) { DisposeSpeechChannel(scChannel); if (qlMessages.isEmpty()) bRunning = false; else process_speech(); } static void process_speech() { SpeechChannel scChannel; QByteArray ba; qmLock.lock(); ba = qlMessages.takeFirst(); qmLock.unlock(); NewSpeechChannel(NULL, &scChannel); SetSpeechInfo(scChannel, soVolume, &fVolume); SetSpeechInfo(scChannel, soSpeechDoneCallBack, reinterpret_cast<void *>(speech_done_cb)); SpeakText(scChannel, ba.constData(), ba.size()); } TextToSpeech::TextToSpeech(QObject *) { bEnabled = true; } TextToSpeech::~TextToSpeech() { } void TextToSpeech::say(const QString &text) { if (!bEnabled) return; QTextCodec *codec = QTextCodec::codecForName("Apple Roman"); Q_ASSERT(codec != NULL); qmLock.lock(); qlMessages.append(codec->fromUnicode(text)); qmLock.unlock(); if (!bRunning) { process_speech(); bRunning = true; } } void TextToSpeech::setEnabled(bool e) { bEnabled = e; } void TextToSpeech::setVolume(int volume) { fVolume = FixRatio(volume, 100); } bool TextToSpeech::isEnabled() const { return bEnabled; } <commit_msg>TextToSpeechMac: Fix the parameters for our SpeechDone callback. I confused it with another function. This doesn't change any code, as we were only using the first parameter anyway.<commit_after>/* Copyright (C) 2005-2008, Thorvald Natvig <thorvald@natvig.com> Copyright (C) 2007, Sebastian Schlingmann <mit_service@users.sourceforge.net> 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 Mumble Developers 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 FOUNDATION 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. */ /* need the undef or else the include would not work it would help to include the header before QT, but that might mess with QT */ #undef qDebug #include "ApplicationServices/ApplicationServices.h" #undef check #include "Global.h" #include "TextToSpeech.h" static QMutex qmLock; static Fixed fVolume; static QList<QByteArray> qlMessages; static bool bRunning; static bool bEnabled; static void process_speech(); static void speech_done_cb(SpeechChannel scChannel, long) { DisposeSpeechChannel(scChannel); if (qlMessages.isEmpty()) bRunning = false; else process_speech(); } static void process_speech() { SpeechChannel scChannel; QByteArray ba; qmLock.lock(); ba = qlMessages.takeFirst(); qmLock.unlock(); NewSpeechChannel(NULL, &scChannel); SetSpeechInfo(scChannel, soVolume, &fVolume); SetSpeechInfo(scChannel, soSpeechDoneCallBack, reinterpret_cast<void *>(speech_done_cb)); SpeakText(scChannel, ba.constData(), ba.size()); } TextToSpeech::TextToSpeech(QObject *) { bEnabled = true; } TextToSpeech::~TextToSpeech() { } void TextToSpeech::say(const QString &text) { if (!bEnabled) return; QTextCodec *codec = QTextCodec::codecForName("Apple Roman"); Q_ASSERT(codec != NULL); qmLock.lock(); qlMessages.append(codec->fromUnicode(text)); qmLock.unlock(); if (!bRunning) { process_speech(); bRunning = true; } } void TextToSpeech::setEnabled(bool e) { bEnabled = e; } void TextToSpeech::setVolume(int volume) { fVolume = FixRatio(volume, 100); } bool TextToSpeech::isEnabled() const { return bEnabled; } <|endoftext|>
<commit_before>#include "Halide.h" #include <stdio.h> #include "clock.h" using namespace Halide; // 32-bit windows defines powf as a macro, which won't work for us. #ifdef WIN32 extern "C" __declspec(dllexport) float pow_ref(float x, float y) { return pow(x, y); } #else extern "C" float pow_ref(float x, float y) { return powf(x, y); } #endif HalideExtern_2(float, pow_ref, float, float); int main(int argc, char **argv) { Func f, g, h; Var x, y; f(x, y) = pow_ref((x+1)/512.0f, (y+1)/512.0f); g(x, y) = pow((x+1)/512.0f, (y+1)/512.0f); h(x, y) = fast_pow((x+1)/512.0f, (y+1)/512.0f); f.vectorize(x, 8); g.vectorize(x, 8); h.vectorize(x, 8); f.compile_jit(); g.compile_jit(); h.compile_jit(); Image<float> correct_result(2048, 768); Image<float> fast_result(2048, 768); Image<float> faster_result(2048, 768); const int iterations = 20; double t1 = current_time(); for (int i = 0; i < iterations; i++) { f.realize(correct_result); } double t2 = current_time(); for (int i = 0; i < iterations; i++) { g.realize(fast_result); } double t3 = current_time(); for (int i = 0; i < iterations; i++) { h.realize(faster_result); } double t4 = current_time(); RDom r(correct_result); Func fast_error, faster_error; Expr fast_delta = correct_result(r.x, r.y) - fast_result(r.x, r.y); Expr faster_delta = correct_result(r.x, r.y) - faster_result(r.x, r.y); fast_error() += cast<double>(fast_delta * fast_delta); faster_error() += cast<double>(faster_delta * faster_delta); Image<double> fast_err = fast_error.realize(); Image<double> faster_err = faster_error.realize(); int N = correct_result.width() * correct_result.height() * iterations; fast_err(0) = sqrt(fast_err(0)/N); faster_err(0) = sqrt(faster_err(0)/N); printf("powf: %f ns per pixel\n" "Halide's pow: %f ns per pixel (rms error = %0.10f)\n" "Halide's fast_pow: %f ns per pixel (rms error = %0.10f)\n", 1000000*(t2-t1) / N, 1000000*(t3-t2) / N, fast_err(0), 1000000*(t4-t3) / N, faster_err(0)); if (fast_err(0) > 0.000001) { printf("Error for pow too large\n"); return -1; } if (faster_err(0) > 0.0001) { printf("Error for fast_pow too large\n"); return -1; } if (t2-t1 < t3-t2) { printf("powf is faster than Halide's pow\n"); return -1; } if (t3-t2 < t4-t3) { printf("pow is faster than fast_pow\n"); return -1; } printf("Success!\n"); return 0; } <commit_msg>Made fast_pow timing test more reliable<commit_after>#include "Halide.h" #include <stdio.h> #include "clock.h" using namespace Halide; // 32-bit windows defines powf as a macro, which won't work for us. #ifdef WIN32 extern "C" __declspec(dllexport) float pow_ref(float x, float y) { return pow(x, y); } #else extern "C" float pow_ref(float x, float y) { return powf(x, y); } #endif HalideExtern_2(float, pow_ref, float, float); int main(int argc, char **argv) { Func f, g, h; Var x, y; f(x, y) = pow_ref((x+1)/512.0f, (y+1)/512.0f); g(x, y) = pow((x+1)/512.0f, (y+1)/512.0f); h(x, y) = fast_pow((x+1)/512.0f, (y+1)/512.0f); f.vectorize(x, 8); g.vectorize(x, 8); h.vectorize(x, 8); Image<float> correct_result(2048, 768); Image<float> fast_result(2048, 768); Image<float> faster_result(2048, 768); f.realize(correct_result); g.realize(fast_result); h.realize(faster_result); const int trials = 5; const int iterations = 5; double t1 = 1e10; double t2 = 1e10; double t3 = 1e10; // All profiling runs are done into the same buffer, to avoid // cache weirdness. Image<float> timing_scratch(400, 400); for (int i = 0; i < trials; i++) { double start = current_time(); for (int j = 0; j < iterations; j++) { f.realize(timing_scratch); } double end = current_time(); t1 = std::min(end - start, t1); start = current_time(); for (int j = 0; j < iterations; j++) { g.realize(timing_scratch); } end = current_time(); t2 = std::min(end - start, t2); start = current_time(); for (int j = 0; j < iterations; j++) { h.realize(timing_scratch); } end = current_time(); t3 = std::min(end - start, t3); } RDom r(correct_result); Func fast_error, faster_error; Expr fast_delta = correct_result(r.x, r.y) - fast_result(r.x, r.y); Expr faster_delta = correct_result(r.x, r.y) - faster_result(r.x, r.y); fast_error() += cast<double>(fast_delta * fast_delta); faster_error() += cast<double>(faster_delta * faster_delta); Image<double> fast_err = fast_error.realize(); Image<double> faster_err = faster_error.realize(); int timing_N = timing_scratch.width() * timing_scratch.height() * iterations; int correctness_N = fast_result.width() * fast_result.height() * iterations; fast_err(0) = sqrt(fast_err(0)/correctness_N); faster_err(0) = sqrt(faster_err(0)/correctness_N); printf("powf: %f ns per pixel\n" "Halide's pow: %f ns per pixel (rms error = %0.10f)\n" "Halide's fast_pow: %f ns per pixel (rms error = %0.10f)\n", 1000000*t1 / timing_N, 1000000*t2 / timing_N, fast_err(0), 1000000*t3 / timing_N, faster_err(0)); if (fast_err(0) > 0.000001) { printf("Error for pow too large\n"); return -1; } if (faster_err(0) > 0.0001) { printf("Error for fast_pow too large\n"); return -1; } if (t1 < t2) { printf("powf is faster than Halide's pow\n"); return -1; } if (t2 < t3) { printf("pow is faster than fast_pow\n"); return -1; } printf("Success!\n"); return 0; } <|endoftext|>
<commit_before> #include <iostream> #include <cstdlib> #include <fstream> #include <sstream> #include <cmath> #include <cassert> #include <iomanip> #include <cstdio> #include <utility> #include <algorithm> #include <ios> #include <limits> #include <stdint.h> #include <vector> #include <string> #include <cstring> #include <list> #include <map> #include <set> //#include <unordered_map> using namespace std; //One Dimension void print_vector_of_ints(const string& message, const vector<int>& vector_of_ints); void print_vector_of_chars(const string& message, const vector<char>& vector_of_chars); void print_vector_of_strings(const string& message, const vector<string>& vector_of_strings); void print_vector_of_floats(const string& message, const vector<float>& vector_of_floats); void print_vector_of_doubles(const string& message, const vector<double>& vector_of_doubles); void print_list_of_ints(const string& message, const list<int>& list_of_ints); void print_list_of_chars(const string& message, const list<char>& list_of_chars); void print_list_of_strings(const string& message, const list<string>& list_of_strings); void print_list_of_floats(const string& message, const list<float>& list_of_floats); void print_list_of_doubles(const string& message, const list<double>& list_of_doubles); void print_set_of_ints(const string& message, const set<int>& set_of_ints); void print_set_of_chars(const string& message, const set<char>& set_of_chars); void print_set_of_strings(const string& message, const set<string> &set_of_strings); void print_set_of_floats(const string& message, const set<float>& set_of_floats); void print_set_of_doubles(const string& message, const set<double>& set_of_doubles); //Two Dimensions void print_vector_of_vectors_of_strings(const string& message, const vector<vector<string> >& vector_of_vectors_of_strings); int main(int argc, char* argv[]){ vector<int> vector_of_ints; vector<char> vector_of_chars; vector<string> vector_of_strings; vector<float> vector_of_floats; vector<double> vector_of_doubles; list<int> list_of_ints; list<char> list_of_chars; list<string> list_of_strings; list<float> list_of_floats; list<double> list_of_doubles; set<int> set_of_ints; set<char> set_of_chars; set<string> set_of_strings; set<float> set_of_floats; set<double> set_of_doubles; vector_of_ints = {1, 2, 3}; print_vector_of_ints("vertor of ints initialized by {}", vector_of_ints); vector_of_strings = {"cat", "meow", "kitty"}; print_vector_of_strings("vertor of ints initialized by {}", vector_of_strings); vector_of_doubles = {1.0, 2.0, 3.0}; print_vector_of_doubles("vertor of ints initialized by {}", vector_of_doubles); vector_of_floats = {12.0, 22.0, 32.0}; print_vector_of_floats("vertor of ints initialized by {}", vector_of_floats); list_of_ints.push_back(2); list_of_ints.push_back(3); list_of_ints.push_back(4); list_of_ints.push_back(5); print_list_of_ints("testing function", list_of_ints); list_of_chars.push_back('a'); list_of_chars.push_back('b'); list_of_chars.push_back('c'); list_of_chars.push_back('d'); print_list_of_chars("testing function", list_of_chars); list_of_strings.push_back("hi"); list_of_strings.push_back("there"); list_of_strings.push_back("cout"); list_of_strings.push_back("statement"); print_list_of_strings("testing function", list_of_strings); list_of_floats.push_back(1.0); list_of_floats.push_back(2.0); list_of_floats.push_back(3.0); list_of_floats.push_back(4.0); print_list_of_floats("testing function", list_of_floats); list_of_doubles.push_back(11.0); list_of_doubles.push_back(21.0); list_of_doubles.push_back(31.0); list_of_doubles.push_back(41.0); print_list_of_doubles("testing function", list_of_doubles); //print_vector_of_ints("vector initialized given number and filler", vector_of_ints); return 0; } //=================================VECTORS=============================================== void print_vector_of_ints(const string& message, const vector<int>& vector_of_ints){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; for(unsigned int v = 0; v < vector_of_ints.size() -1; v++){ cout << vector_of_ints[v] << ", "; } cout << vector_of_ints[vector_of_ints.size()-1] << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } void print_vector_of_chars(const string& message, const vector<char>& vector_of_chars){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; for(unsigned int v = 0; v < vector_of_chars.size() -1; v++){ cout << vector_of_chars[v] << ", "; } cout << vector_of_chars[vector_of_chars.size()-1] << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } void print_vector_of_strings(const string& message, const vector<string>& vector_of_strings){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; for(unsigned int v = 0; v < vector_of_strings.size() -1; v++){ cout << vector_of_strings[v] << ", "; } cout << vector_of_strings[vector_of_strings.size()-1] << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } void print_vector_of_floats(const string& message, const vector<float>& vector_of_floats){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; for(unsigned int v = 0; v < vector_of_floats.size() -1; v++){ cout << vector_of_floats[v] << ", "; } cout << vector_of_floats[vector_of_floats.size()-1] << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } void print_vector_of_doubles(const string& message, const vector<double>& vector_of_doubles){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; for(unsigned int v = 0; v < vector_of_doubles.size() -1; v++){ cout << vector_of_doubles[v] << ", "; } cout << vector_of_doubles[vector_of_doubles.size()-1] << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } //=================================LISTS================================================ void print_list_of_ints(const string& message, const list<int>& list_of_ints){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; list<int>::const_iterator last_item_itr = list_of_ints.end(); last_item_itr--; for(list<int>::const_iterator l = list_of_ints.begin(); l != last_item_itr; l++){ cout << *l << ", "; } cout << *last_item_itr << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } void print_list_of_chars(const string& message, const list<char>& list_of_chars){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; list<char>::const_iterator last_item_itr = list_of_chars.end(); last_item_itr--; for(list<char>::const_iterator l = list_of_chars.begin(); l != last_item_itr; l++){ cout << *l << ", "; } cout << *last_item_itr << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } void print_list_of_strings(const string& message, const list<string>& list_of_strings){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; list<string>::const_iterator last_item_itr = list_of_strings.end(); last_item_itr--; for(list<string>::const_iterator l = list_of_strings.begin(); l != last_item_itr; l++){ cout << *l << ", "; } cout << *last_item_itr << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } void print_list_of_floats(const string& message, const list<float>& list_of_floats){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; list<float>::const_iterator last_item_itr = list_of_floats.end(); last_item_itr--; for(list<float>::const_iterator l = list_of_floats.begin(); l != last_item_itr; l++){ cout << *l << ", "; } cout << *last_item_itr << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } void print_list_of_doubles(const string& message, const list<double>& list_of_doubles){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; list<double>::const_iterator last_item_itr = list_of_doubles.end(); last_item_itr--; for(list<double>::const_iterator l = list_of_doubles.begin(); l != last_item_itr; l++){ cout << *l << ", "; } cout << *last_item_itr << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } //==================================SETS================================================ void print_set_of_ints(const string& message, const set<int>& set_of_ints){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; set<int>::const_iterator last_item_itr = set_of_ints.end(); last_item_itr--; for(set<int>::const_iterator l = set_of_ints.begin(); l != last_item_itr; l++){ cout << *l << ", "; } cout << *last_item_itr << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } void print_set_of_chars(const string& message, const set<char>& set_of_chars){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; set<char>::const_iterator last_item_itr = set_of_chars.end(); last_item_itr--; for(set<char>::const_iterator l = set_of_chars.begin(); l != last_item_itr; l++){ cout << *l << ", "; } cout << *last_item_itr << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } void print_set_of_strings(const string& message, const set<string>& set_of_strings){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; set<string>::const_iterator last_item_itr = set_of_strings.end(); last_item_itr--; for(set<string>::const_iterator l = set_of_strings.begin(); l != last_item_itr; l++){ cout << *l << ", "; } cout << *last_item_itr << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } //=================================VECTORS OF VECTORS=================================== void print_vector_of_vectors_of_strings(const string& message, const vector<vector<string> >& vector_of_vectors_of_strings){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl; //find maximum length row (maximum number of colunms) unsigned int maximum_length_row = 0; for(unsigned int r = 0; r < vector_of_vectors_of_strings.size(); r++){ if(vector_of_vectors_of_strings[r].size() > maximum_length_row){ maximum_length_row = vector_of_vectors_of_strings[r].size(); } } //find the largest string in each column to use as the column width for that column vector<unsigned int> maximum_length_per_col(maximum_length_row, 0); for(unsigned int r = 0; r < vector_of_vectors_of_strings.size(); r++){ for(unsigned int c = 0; c < vector_of_vectors_of_strings[r].size(); c++){ if(vector_of_vectors_of_strings[r][c].size() > maximum_length_per_col[c]){ maximum_length_per_col[c] = vector_of_vectors_of_strings[r][c].size(); } } } //print things according to column widths (left alligned and 1 extra spaces for padding between colums) //TODO: change from right aligned to left aligned. Try std::left, but if not, 2 prints where padding is (length you want - length you have) before regular print //TODO: also, change the way you are printing to not put an etxra space even at the edges (like before with the "last one" that you did in list/set/1D vector) for(unsigned int r = 0; r < vector_of_vectors_of_strings.size(); r++){ for(unsigned int c = 0; c < vector_of_vectors_of_strings[r].size(); c++){ std::cout << std::setfill (' ') << std::setw (maximum_length_per_col[c] + 1); std::cout << vector_of_vectors_of_strings[r][c] << std::endl; } } cout << "-----------------------------------------------------------------" << endl; }<commit_msg>vector of vector of strings print is working -> tested<commit_after> #include <iostream> #include <cstdlib> #include <fstream> #include <sstream> #include <cmath> #include <cassert> #include <iomanip> #include <cstdio> #include <utility> #include <algorithm> #include <ios> #include <limits> #include <stdint.h> #include <vector> #include <string> #include <cstring> #include <list> #include <map> #include <set> //#include <unordered_map> using namespace std; //One Dimension void print_vector_of_ints(const string& message, const vector<int>& vector_of_ints); void print_vector_of_chars(const string& message, const vector<char>& vector_of_chars); void print_vector_of_strings(const string& message, const vector<string>& vector_of_strings); void print_vector_of_floats(const string& message, const vector<float>& vector_of_floats); void print_vector_of_doubles(const string& message, const vector<double>& vector_of_doubles); void print_list_of_ints(const string& message, const list<int>& list_of_ints); void print_list_of_chars(const string& message, const list<char>& list_of_chars); void print_list_of_strings(const string& message, const list<string>& list_of_strings); void print_list_of_floats(const string& message, const list<float>& list_of_floats); void print_list_of_doubles(const string& message, const list<double>& list_of_doubles); void print_set_of_ints(const string& message, const set<int>& set_of_ints); void print_set_of_chars(const string& message, const set<char>& set_of_chars); void print_set_of_strings(const string& message, const set<string> &set_of_strings); void print_set_of_floats(const string& message, const set<float>& set_of_floats); void print_set_of_doubles(const string& message, const set<double>& set_of_doubles); //Two Dimensions void print_vector_of_vectors_of_strings(const string& message, const vector<vector<string> >& vector_of_vectors_of_strings); int main(int argc, char* argv[]){ vector<int> vector_of_ints; vector<char> vector_of_chars; vector<string> vector_of_strings; vector<float> vector_of_floats; vector<double> vector_of_doubles; list<int> list_of_ints; list<char> list_of_chars; list<string> list_of_strings; list<float> list_of_floats; list<double> list_of_doubles; set<int> set_of_ints; set<char> set_of_chars; set<string> set_of_strings; set<float> set_of_floats; set<double> set_of_doubles; vector_of_ints = {1, 2, 3}; print_vector_of_ints("vertor of ints initialized by {}", vector_of_ints); vector_of_strings = {"cat", "meow", "kitty"}; print_vector_of_strings("vertor of ints initialized by {}", vector_of_strings); vector_of_doubles = {1.0, 2.0, 3.0}; print_vector_of_doubles("vertor of ints initialized by {}", vector_of_doubles); vector_of_floats = {12.0, 22.0, 32.0}; print_vector_of_floats("vertor of ints initialized by {}", vector_of_floats); list_of_ints.push_back(2); list_of_ints.push_back(3); list_of_ints.push_back(4); list_of_ints.push_back(5); print_list_of_ints("testing function", list_of_ints); list_of_chars.push_back('a'); list_of_chars.push_back('b'); list_of_chars.push_back('c'); list_of_chars.push_back('d'); print_list_of_chars("testing function", list_of_chars); list_of_strings.push_back("hi"); list_of_strings.push_back("there"); list_of_strings.push_back("cout"); list_of_strings.push_back("statement"); print_list_of_strings("testing function", list_of_strings); list_of_floats.push_back(1.0); list_of_floats.push_back(2.0); list_of_floats.push_back(3.0); list_of_floats.push_back(4.0); print_list_of_floats("testing function", list_of_floats); list_of_doubles.push_back(11.0); list_of_doubles.push_back(21.0); list_of_doubles.push_back(31.0); list_of_doubles.push_back(41.0); print_list_of_doubles("testing function", list_of_doubles); vector<vector<string> > vector_of_vectors_of_strings; vector<string> vec1 = {"cat", "dog", "puppy", "buscuit"}; vector<string> vec2 = {"one", "two", "three", "four", "five", "six"}; vector<string> vec3 = {"oh", "hai", "thar"}; vector<string> vec4 = {"do", "you", "want", "to", "build", "a", "snowman?"}; vector_of_vectors_of_strings.push_back(vec1); vector_of_vectors_of_strings.push_back(vec2); vector_of_vectors_of_strings.push_back(vec3); vector_of_vectors_of_strings.push_back(vec4); print_vector_of_vectors_of_strings("testing vector of vector of strings", vector_of_vectors_of_strings); //print_vector_of_ints("vector initialized given number and filler", vector_of_ints); return 0; } //=================================VECTORS=============================================== void print_vector_of_ints(const string& message, const vector<int>& vector_of_ints){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; for(unsigned int v = 0; v < vector_of_ints.size() -1; v++){ cout << vector_of_ints[v] << ", "; } cout << vector_of_ints[vector_of_ints.size()-1] << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } void print_vector_of_chars(const string& message, const vector<char>& vector_of_chars){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; for(unsigned int v = 0; v < vector_of_chars.size() -1; v++){ cout << vector_of_chars[v] << ", "; } cout << vector_of_chars[vector_of_chars.size()-1] << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } void print_vector_of_strings(const string& message, const vector<string>& vector_of_strings){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; for(unsigned int v = 0; v < vector_of_strings.size() -1; v++){ cout << vector_of_strings[v] << ", "; } cout << vector_of_strings[vector_of_strings.size()-1] << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } void print_vector_of_floats(const string& message, const vector<float>& vector_of_floats){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; for(unsigned int v = 0; v < vector_of_floats.size() -1; v++){ cout << vector_of_floats[v] << ", "; } cout << vector_of_floats[vector_of_floats.size()-1] << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } void print_vector_of_doubles(const string& message, const vector<double>& vector_of_doubles){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; for(unsigned int v = 0; v < vector_of_doubles.size() -1; v++){ cout << vector_of_doubles[v] << ", "; } cout << vector_of_doubles[vector_of_doubles.size()-1] << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } //=================================LISTS================================================ void print_list_of_ints(const string& message, const list<int>& list_of_ints){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; list<int>::const_iterator last_item_itr = list_of_ints.end(); last_item_itr--; for(list<int>::const_iterator l = list_of_ints.begin(); l != last_item_itr; l++){ cout << *l << ", "; } cout << *last_item_itr << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } void print_list_of_chars(const string& message, const list<char>& list_of_chars){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; list<char>::const_iterator last_item_itr = list_of_chars.end(); last_item_itr--; for(list<char>::const_iterator l = list_of_chars.begin(); l != last_item_itr; l++){ cout << *l << ", "; } cout << *last_item_itr << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } void print_list_of_strings(const string& message, const list<string>& list_of_strings){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; list<string>::const_iterator last_item_itr = list_of_strings.end(); last_item_itr--; for(list<string>::const_iterator l = list_of_strings.begin(); l != last_item_itr; l++){ cout << *l << ", "; } cout << *last_item_itr << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } void print_list_of_floats(const string& message, const list<float>& list_of_floats){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; list<float>::const_iterator last_item_itr = list_of_floats.end(); last_item_itr--; for(list<float>::const_iterator l = list_of_floats.begin(); l != last_item_itr; l++){ cout << *l << ", "; } cout << *last_item_itr << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } void print_list_of_doubles(const string& message, const list<double>& list_of_doubles){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; list<double>::const_iterator last_item_itr = list_of_doubles.end(); last_item_itr--; for(list<double>::const_iterator l = list_of_doubles.begin(); l != last_item_itr; l++){ cout << *l << ", "; } cout << *last_item_itr << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } //==================================SETS================================================ void print_set_of_ints(const string& message, const set<int>& set_of_ints){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; set<int>::const_iterator last_item_itr = set_of_ints.end(); last_item_itr--; for(set<int>::const_iterator l = set_of_ints.begin(); l != last_item_itr; l++){ cout << *l << ", "; } cout << *last_item_itr << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } void print_set_of_chars(const string& message, const set<char>& set_of_chars){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; set<char>::const_iterator last_item_itr = set_of_chars.end(); last_item_itr--; for(set<char>::const_iterator l = set_of_chars.begin(); l != last_item_itr; l++){ cout << *l << ", "; } cout << *last_item_itr << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } void print_set_of_strings(const string& message, const set<string>& set_of_strings){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl << "["; set<string>::const_iterator last_item_itr = set_of_strings.end(); last_item_itr--; for(set<string>::const_iterator l = set_of_strings.begin(); l != last_item_itr; l++){ cout << *l << ", "; } cout << *last_item_itr << "]" << endl; cout << "-----------------------------------------------------------------" << endl; } //=================================VECTORS OF VECTORS=================================== void print_vector_of_vectors_of_strings(const string& message, const vector<vector<string> >& vector_of_vectors_of_strings){ cout << "-----------------------------------------------------------------" << endl; cout << message << endl; //find maximum length row (maximum number of colunms) unsigned int maximum_length_row = 0; for(unsigned int r = 0; r < vector_of_vectors_of_strings.size(); r++){ if(vector_of_vectors_of_strings[r].size() > maximum_length_row){ maximum_length_row = vector_of_vectors_of_strings[r].size(); } } //find the largest string in each column to use as the column width for that column vector<unsigned int> maximum_length_per_col(maximum_length_row, 0); for(unsigned int r = 0; r < vector_of_vectors_of_strings.size(); r++){ for(unsigned int c = 0; c < vector_of_vectors_of_strings[r].size(); c++){ if(vector_of_vectors_of_strings[r][c].size() > maximum_length_per_col[c]){ maximum_length_per_col[c] = vector_of_vectors_of_strings[r][c].size(); } } } //print things according to column widths (left alligned and 1 extra spaces for padding between colums) //TODO: change from right aligned to left aligned. Try std::left, but if not, 2 prints where padding is (length you want - length you have) before regular print //TODO: also, change the way you are printing to not put an etxra space even at the edges (like before with the "last one" that you did in list/set/1D vector) for(unsigned int r = 0; r < vector_of_vectors_of_strings.size(); r++){ for(unsigned int c = 0; c < vector_of_vectors_of_strings[r].size(); c++){ std::cout << std::left << std::setw (maximum_length_per_col[c] + 1) << std::setfill (' ') << vector_of_vectors_of_strings[r][c]; } std::cout << std::endl; } cout << "-----------------------------------------------------------------" << endl; }<|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2013-2014 RAD Game Tools and Valve Software * All Rights Reserved. * * 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. * **************************************************************************/ // File: vogl_trace.cpp #include "vogl_trace.h" #include "vogl_command_line_params.h" #include "vogl_colorized_console.h" #include <signal.h> #include "vogl_port.h" #if VOGL_PLATFORM_SUPPORTS_BTRACE #include "btrace.h" #endif #if defined(PLATFORM_LINUX) #include <execinfo.h> #include <linux/unistd.h> #endif #if defined(COMPILER_MSVC) // As long as we include windows.h, we will get different dll linkage for this. However, we will "win" in here // so we get the results we are looking for. #pragma warning( disable : 4273 ) #endif //---------------------------------------------------------------------------------------------------------------------- // Has exception hooks, dlopen() interception, super low-level global init. Be super careful what you // do in some of these funcs (particularly vogl_shared_object_constructor_func() or any of the funcs // it calls). I've found it's possible to do shit here that will work fine in primitive apps (like // vogltest) but kill tracing in some real apps. //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- // globals //---------------------------------------------------------------------------------------------------------------------- void *g_vogl_actual_libgl_module_handle = NULL; bool g_vogl_initializing_flag = false; //---------------------------------------------------------------------------------------------------------------------- // dlopen interceptor //---------------------------------------------------------------------------------------------------------------------- #if defined(PLATFORM_LINUX) // Console initialization. bool vogl_console_init(bool doinit); typedef void *(*dlopen_func_ptr_t)(const char *pFile, int mode); VOGL_API_EXPORT void *dlopen(const char *pFile, int mode) { static dlopen_func_ptr_t s_pActual_dlopen = (dlopen_func_ptr_t)dlsym(RTLD_NEXT, "dlopen"); if (!s_pActual_dlopen) return NULL; // Check to see if the vogl_console has been initialized. Only use the vogl console APIs if so. bool ret = vogl_console_init(false); if (ret) { vogl_verbose_printf("dlopen: %s %i\n", pFile ? pFile : "(nullptr)", mode); } // Only redirect libGL.so when it comes from the app, NOT the driver or one of its associated helpers. // This is definitely fragile as all fuck. if (!g_vogl_initializing_flag) { if (pFile && (strstr(pFile, "libGL.so") != NULL)) { const char *calling_module = btrace_get_calling_module(); bool should_redirect = !strstr(calling_module, "fglrx"); if (should_redirect) { pFile = btrace_get_current_module(); if (ret) { vogl_verbose_printf("redirecting dlopen to %s\n", pFile); vogl_verbose_printf("------------\n"); } } else if (ret) { vogl_verbose_printf("NOT redirecting dlopen to %s, this dlopen() call appears to be coming from the driver\n", pFile); vogl_verbose_printf("------------\n"); } } } // Check if this module is already loaded. void *is_loaded = (*s_pActual_dlopen)(pFile, RTLD_NOLOAD); // Call the real dlopen(). void *dlopen_ret = (*s_pActual_dlopen)(pFile, mode); // Only call btrace routines after vogl has been initialized. Otherwise we get // called before memory routines have been set up, etc. and possibly crash. if (g_vogl_has_been_initialized) { // If this file hadn't been loaded before, notify btrace. if (!is_loaded && dlopen_ret) btrace_dlopen_notify(pFile); } return dlopen_ret; } //---------------------------------------------------------------------------------------------------------------------- // Intercept _exit() so we get a final chance to flush our trace/log files //---------------------------------------------------------------------------------------------------------------------- typedef void (*exit_func_ptr_t)(int status); VOGL_API_EXPORT VOGL_NORETURN void _exit(int status) { static exit_func_ptr_t s_pActual_exit = (exit_func_ptr_t)dlsym(RTLD_NEXT, "_exit"); vogl_deinit(); if (s_pActual_exit) (*s_pActual_exit)(status); raise(SIGKILL); // to shut up compiler about this func marked as noreturn for (;;) ; } //---------------------------------------------------------------------------------------------------------------------- // Intercept _exit() so we get a final chance to flush our trace/log files //---------------------------------------------------------------------------------------------------------------------- typedef void (*Exit_func_ptr_t)(int status); VOGL_API_EXPORT VOGL_NORETURN void _Exit(int status) { static Exit_func_ptr_t s_pActual_Exit = (Exit_func_ptr_t)dlsym(RTLD_NEXT, "_Exit"); vogl_deinit(); if (s_pActual_Exit) (*s_pActual_Exit)(status); raise(SIGKILL); // to shut up compiler about this func marked as noreturn for (;;) ; } #endif // defined(PLATFORM_LINUX) //---------------------------------------------------------------------------------------------------------------------- // vogl_glInternalTraceCommandRAD_dummy_func //---------------------------------------------------------------------------------------------------------------------- static void vogl_glInternalTraceCommandRAD_dummy_func(GLuint cmd, GLuint size, const GLubyte *data) { // Nothing to do, this is an internal command used for serialization purposes that only we understand. VOGL_NOTE_UNUSED(cmd); VOGL_NOTE_UNUSED(size); VOGL_NOTE_UNUSED(data); } //---------------------------------------------------------------------------------------------------------------------- // vogl_get_proc_address_helper_return_actual //---------------------------------------------------------------------------------------------------------------------- vogl_void_func_ptr_t vogl_get_proc_address_helper_return_actual(const char *pName) { if (!strcmp(pName, "glInternalTraceCommandRAD")) return reinterpret_cast<vogl_void_func_ptr_t>(vogl_glInternalTraceCommandRAD_dummy_func); vogl_void_func_ptr_t pFunc = reinterpret_cast<vogl_void_func_ptr_t>(plat_dlsym(g_vogl_actual_libgl_module_handle ? g_vogl_actual_libgl_module_handle : PLAT_RTLD_NEXT, pName)); #if (VOGL_PLATFORM_HAS_GLX) if ((!pFunc) && (g_vogl_actual_gl_entrypoints.m_glXGetProcAddress)) pFunc = reinterpret_cast<vogl_void_func_ptr_t>(g_vogl_actual_gl_entrypoints.m_glXGetProcAddress(reinterpret_cast<const GLubyte *>(pName))); #elif (VOGL_PLATFORM_HAS_WGL) if ((!pFunc) && (g_vogl_actual_gl_entrypoints.m_wglGetProcAddress)) pFunc = reinterpret_cast<vogl_void_func_ptr_t>(g_vogl_actual_gl_entrypoints.m_wglGetProcAddress(pName)); #else #error "impl get_proc_address functions in g_vogl_actual_gl_entrypoints for this platform" #endif return pFunc; } //---------------------------------------------------------------------------------------------------------------------- // global constructor init // Note: Be VERY careful what you do in here! It's called very early during init (long before main, during c++ init) //---------------------------------------------------------------------------------------------------------------------- #if defined(PLATFORM_LINUX) #include "vogl_file_utils.h" VOGL_CONSTRUCTOR_FUNCTION(vogl_shared_object_constructor_func); static void vogl_shared_object_constructor_func() { // We really don't want to be hooking terminals running shell scripts to launch the games, and it // only causes problems when we do wind up in those processes. // So check if we're one of the fairly well known shells and bail if so. static const char *s_notrace[] = { "bash", "dash", "sh", "tcsh", "xterm", "zsh", "zsh5", "cgdb", "gdb", "strace", "desktop-launcher", "glxinfo", "kmod", "python", "python2.7", "python3", "python3.4", "dpkg-query", "grep", "egrep", "head", "free", "lsusb", "uname", "minidump_stackwalk" }; char exec_filename[PATH_MAX]; vogl::file_utils::get_exec_filename(exec_filename, sizeof(exec_filename)); const char *fname = strrchr(exec_filename, '/'); fname = fname ? (fname + 1) : exec_filename; for (size_t i = 0; i < sizeof(s_notrace) / sizeof(s_notrace[0]); i++) { if (vogl::vogl_strncasecmp(fname, s_notrace[i], sizeof(exec_filename)) == 0) return; } vogl_init(); } __attribute__((destructor)) static void vogl_shared_object_destructor_func() { if (vogl_is_capturing()) { // This shouldn't ever happen hopefully. Ie, our atexit() handler or exit() hooks should call vogl_deinit() // well before this destructor is called. vogl_warning_printf_once("ERROR: Called with open trace file. Somehow vogl_deinit() hasn't been called?"); // Try to do vogl_deinit(). vogl_deinit(); } } #elif defined(PLATFORM_WINDOWS) BOOL WINAPI DllMain(_In_ HINSTANCE hinstDLL, _In_ DWORD fdwReason, _In_ LPVOID lpvReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: vogl_init(); break; case DLL_PROCESS_DETACH: vogl_deinit(); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: // Nothing to do for this case. break; default: VOGL_ASSERT(!"Unexpected fdwReason passed to DllMain."); break; }; return TRUE; } VOGL_API_EXPORT void VOGL_API_CALLCONV GlmfBeginGlsBlock(DWORD _d1) { } VOGL_API_EXPORT void VOGL_API_CALLCONV GlmfCloseMetaFile(DWORD _d1) { } VOGL_API_EXPORT void VOGL_API_CALLCONV GlmfEndGlsBlock(DWORD _d1) { } VOGL_API_EXPORT void VOGL_API_CALLCONV GlmfEndPlayback(DWORD _d1) { } VOGL_API_EXPORT void VOGL_API_CALLCONV GlmfInitPlayback(DWORD _d1, DWORD _d2, DWORD _d3) { } VOGL_API_EXPORT void VOGL_API_CALLCONV GlmfPlayGlsRecord(DWORD _d1, DWORD _d2, DWORD _d3, DWORD _d4) { } VOGL_API_EXPORT void VOGL_API_CALLCONV glDebugEntry(DWORD _d1, DWORD _d2) { } VOGL_API_EXPORT DWORD VOGL_API_CALLCONV wglSwapMultipleBuffers(UINT, CONST WGLSWAP *) { return 0; } VOGL_API_EXPORT BOOL VOGL_API_CALLCONV wglUseFontOutlinesA(HDC hdc, DWORD first, DWORD count, DWORD listBase, FLOAT deviation, FLOAT extrusion, int format, LPGLYPHMETRICSFLOAT lpgmf) { return FALSE; } VOGL_API_EXPORT BOOL VOGL_API_CALLCONV wglUseFontOutlinesW(HDC hdc, DWORD first, DWORD count, DWORD listBase, FLOAT deviation, FLOAT extrusion, int format, LPGLYPHMETRICSFLOAT lpgmf) { return FALSE; } #else #error "Need a way to call vogl_init and vogl_deinit for this platform." #endif <commit_msg>Add check for mesa libGL to no-redirect block.<commit_after>/************************************************************************** * * Copyright 2013-2014 RAD Game Tools and Valve Software * All Rights Reserved. * * 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. * **************************************************************************/ // File: vogl_trace.cpp #include "vogl_trace.h" #include "vogl_command_line_params.h" #include "vogl_colorized_console.h" #include <signal.h> #include "vogl_port.h" #if VOGL_PLATFORM_SUPPORTS_BTRACE #include "btrace.h" #endif #if defined(PLATFORM_LINUX) #include <execinfo.h> #include <linux/unistd.h> #endif #if defined(COMPILER_MSVC) // As long as we include windows.h, we will get different dll linkage for this. However, we will "win" in here // so we get the results we are looking for. #pragma warning( disable : 4273 ) #endif //---------------------------------------------------------------------------------------------------------------------- // Has exception hooks, dlopen() interception, super low-level global init. Be super careful what you // do in some of these funcs (particularly vogl_shared_object_constructor_func() or any of the funcs // it calls). I've found it's possible to do shit here that will work fine in primitive apps (like // vogltest) but kill tracing in some real apps. //---------------------------------------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------------------------------------- // globals //---------------------------------------------------------------------------------------------------------------------- void *g_vogl_actual_libgl_module_handle = NULL; bool g_vogl_initializing_flag = false; //---------------------------------------------------------------------------------------------------------------------- // dlopen interceptor //---------------------------------------------------------------------------------------------------------------------- #if defined(PLATFORM_LINUX) // Console initialization. bool vogl_console_init(bool doinit); typedef void *(*dlopen_func_ptr_t)(const char *pFile, int mode); VOGL_API_EXPORT void *dlopen(const char *pFile, int mode) { static dlopen_func_ptr_t s_pActual_dlopen = (dlopen_func_ptr_t)dlsym(RTLD_NEXT, "dlopen"); if (!s_pActual_dlopen) return NULL; // Check to see if the vogl_console has been initialized. Only use the vogl console APIs if so. bool ret = vogl_console_init(false); if (ret) { vogl_verbose_printf("dlopen: %s %i\n", pFile ? pFile : "(nullptr)", mode); } // Only redirect libGL.so when it comes from the app, NOT the driver or one of its associated helpers. // This is definitely fragile as all fuck. if (!g_vogl_initializing_flag) { if (pFile && (strstr(pFile, "libGL.so") != NULL)) { // When the AMD or Intel driver tries to dlopen libGL.so, we need to return the real libGL.so handle. const char *calling_module = btrace_get_calling_module(); bool should_redirect = !strstr(calling_module, "fglrx") && !strstr(calling_module, "mesa/lib/libGL.so.1"); if (should_redirect) { pFile = btrace_get_current_module(); } if (ret) { vogl_verbose_printf("%sRedirecting dlopen to: %s.\n", (should_redirect ? "" : " NOT"), pFile); vogl_verbose_printf(" Calling module: %s.\n", calling_module); } } } // Check if this module is already loaded. void *is_loaded = (*s_pActual_dlopen)(pFile, RTLD_NOLOAD); // Call the real dlopen(). void *dlopen_ret = (*s_pActual_dlopen)(pFile, mode); // Only call btrace routines after vogl has been initialized. Otherwise we get // called before memory routines have been set up, etc. and possibly crash. if (g_vogl_has_been_initialized) { // If this file hadn't been loaded before, notify btrace. if (!is_loaded && dlopen_ret) btrace_dlopen_notify(pFile); } return dlopen_ret; } //---------------------------------------------------------------------------------------------------------------------- // Intercept _exit() so we get a final chance to flush our trace/log files //---------------------------------------------------------------------------------------------------------------------- typedef void (*exit_func_ptr_t)(int status); VOGL_API_EXPORT VOGL_NORETURN void _exit(int status) { static exit_func_ptr_t s_pActual_exit = (exit_func_ptr_t)dlsym(RTLD_NEXT, "_exit"); vogl_deinit(); if (s_pActual_exit) (*s_pActual_exit)(status); raise(SIGKILL); // to shut up compiler about this func marked as noreturn for (;;) ; } //---------------------------------------------------------------------------------------------------------------------- // Intercept _exit() so we get a final chance to flush our trace/log files //---------------------------------------------------------------------------------------------------------------------- typedef void (*Exit_func_ptr_t)(int status); VOGL_API_EXPORT VOGL_NORETURN void _Exit(int status) { static Exit_func_ptr_t s_pActual_Exit = (Exit_func_ptr_t)dlsym(RTLD_NEXT, "_Exit"); vogl_deinit(); if (s_pActual_Exit) (*s_pActual_Exit)(status); raise(SIGKILL); // to shut up compiler about this func marked as noreturn for (;;) ; } #endif // defined(PLATFORM_LINUX) //---------------------------------------------------------------------------------------------------------------------- // vogl_glInternalTraceCommandRAD_dummy_func //---------------------------------------------------------------------------------------------------------------------- static void vogl_glInternalTraceCommandRAD_dummy_func(GLuint cmd, GLuint size, const GLubyte *data) { // Nothing to do, this is an internal command used for serialization purposes that only we understand. VOGL_NOTE_UNUSED(cmd); VOGL_NOTE_UNUSED(size); VOGL_NOTE_UNUSED(data); } //---------------------------------------------------------------------------------------------------------------------- // vogl_get_proc_address_helper_return_actual //---------------------------------------------------------------------------------------------------------------------- vogl_void_func_ptr_t vogl_get_proc_address_helper_return_actual(const char *pName) { if (!strcmp(pName, "glInternalTraceCommandRAD")) return reinterpret_cast<vogl_void_func_ptr_t>(vogl_glInternalTraceCommandRAD_dummy_func); vogl_void_func_ptr_t pFunc = reinterpret_cast<vogl_void_func_ptr_t>(plat_dlsym(g_vogl_actual_libgl_module_handle ? g_vogl_actual_libgl_module_handle : PLAT_RTLD_NEXT, pName)); #if (VOGL_PLATFORM_HAS_GLX) if ((!pFunc) && (g_vogl_actual_gl_entrypoints.m_glXGetProcAddress)) pFunc = reinterpret_cast<vogl_void_func_ptr_t>(g_vogl_actual_gl_entrypoints.m_glXGetProcAddress(reinterpret_cast<const GLubyte *>(pName))); #elif (VOGL_PLATFORM_HAS_WGL) if ((!pFunc) && (g_vogl_actual_gl_entrypoints.m_wglGetProcAddress)) pFunc = reinterpret_cast<vogl_void_func_ptr_t>(g_vogl_actual_gl_entrypoints.m_wglGetProcAddress(pName)); #else #error "impl get_proc_address functions in g_vogl_actual_gl_entrypoints for this platform" #endif return pFunc; } //---------------------------------------------------------------------------------------------------------------------- // global constructor init // Note: Be VERY careful what you do in here! It's called very early during init (long before main, during c++ init) //---------------------------------------------------------------------------------------------------------------------- #if defined(PLATFORM_LINUX) #include "vogl_file_utils.h" VOGL_CONSTRUCTOR_FUNCTION(vogl_shared_object_constructor_func); static void vogl_shared_object_constructor_func() { // We really don't want to be hooking terminals running shell scripts to launch the games, and it // only causes problems when we do wind up in those processes. // So check if we're one of the fairly well known shells and bail if so. static const char *s_notrace[] = { "bash", "dash", "sh", "tcsh", "xterm", "zsh", "zsh5", "cgdb", "gdb", "strace", "desktop-launcher", "glxinfo", "kmod", "python", "python2.7", "python3", "python3.4", "dpkg-query", "grep", "egrep", "head", "free", "lsusb", "uname", "minidump_stackwalk" }; char exec_filename[PATH_MAX]; vogl::file_utils::get_exec_filename(exec_filename, sizeof(exec_filename)); const char *fname = strrchr(exec_filename, '/'); fname = fname ? (fname + 1) : exec_filename; for (size_t i = 0; i < sizeof(s_notrace) / sizeof(s_notrace[0]); i++) { if (vogl::vogl_strncasecmp(fname, s_notrace[i], sizeof(exec_filename)) == 0) return; } vogl_init(); } __attribute__((destructor)) static void vogl_shared_object_destructor_func() { if (vogl_is_capturing()) { // This shouldn't ever happen hopefully. Ie, our atexit() handler or exit() hooks should call vogl_deinit() // well before this destructor is called. vogl_warning_printf_once("ERROR: Called with open trace file. Somehow vogl_deinit() hasn't been called?"); // Try to do vogl_deinit(). vogl_deinit(); } } #elif defined(PLATFORM_WINDOWS) BOOL WINAPI DllMain(_In_ HINSTANCE hinstDLL, _In_ DWORD fdwReason, _In_ LPVOID lpvReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: vogl_init(); break; case DLL_PROCESS_DETACH: vogl_deinit(); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: // Nothing to do for this case. break; default: VOGL_ASSERT(!"Unexpected fdwReason passed to DllMain."); break; }; return TRUE; } VOGL_API_EXPORT void VOGL_API_CALLCONV GlmfBeginGlsBlock(DWORD _d1) { } VOGL_API_EXPORT void VOGL_API_CALLCONV GlmfCloseMetaFile(DWORD _d1) { } VOGL_API_EXPORT void VOGL_API_CALLCONV GlmfEndGlsBlock(DWORD _d1) { } VOGL_API_EXPORT void VOGL_API_CALLCONV GlmfEndPlayback(DWORD _d1) { } VOGL_API_EXPORT void VOGL_API_CALLCONV GlmfInitPlayback(DWORD _d1, DWORD _d2, DWORD _d3) { } VOGL_API_EXPORT void VOGL_API_CALLCONV GlmfPlayGlsRecord(DWORD _d1, DWORD _d2, DWORD _d3, DWORD _d4) { } VOGL_API_EXPORT void VOGL_API_CALLCONV glDebugEntry(DWORD _d1, DWORD _d2) { } VOGL_API_EXPORT DWORD VOGL_API_CALLCONV wglSwapMultipleBuffers(UINT, CONST WGLSWAP *) { return 0; } VOGL_API_EXPORT BOOL VOGL_API_CALLCONV wglUseFontOutlinesA(HDC hdc, DWORD first, DWORD count, DWORD listBase, FLOAT deviation, FLOAT extrusion, int format, LPGLYPHMETRICSFLOAT lpgmf) { return FALSE; } VOGL_API_EXPORT BOOL VOGL_API_CALLCONV wglUseFontOutlinesW(HDC hdc, DWORD first, DWORD count, DWORD listBase, FLOAT deviation, FLOAT extrusion, int format, LPGLYPHMETRICSFLOAT lpgmf) { return FALSE; } #else #error "Need a way to call vogl_init and vogl_deinit for this platform." #endif <|endoftext|>
<commit_before><commit_msg>Fixing scaling problems with karts<commit_after><|endoftext|>
<commit_before>// commodconverter.cc // Implements the CommodConverter class #include "commodconverter.h" namespace commodconverter { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CommodConverter::CommodConverter(cyclus::Context* ctx) : cyclus::Facility(ctx) { cyclus::Warn<cyclus::EXPERIMENTAL_WARNING>("the CommodConverter is experimental."); }; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // pragmas #pragma cyclus def schema commodconverter::CommodConverter #pragma cyclus def annotations commodconverter::CommodConverter #pragma cyclus def initinv commodconverter::CommodConverter #pragma cyclus def snapshotinv commodconverter::CommodConverter #pragma cyclus def infiletodb commodconverter::CommodConverter #pragma cyclus def snapshot commodconverter::CommodConverter #pragma cyclus def clone commodconverter::CommodConverter //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::InitFrom(CommodConverter* m) { #pragma cyclus impl initfromcopy commodconverter::CommodConverter cyclus::toolkit::CommodityProducer::Copy(m); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::InitFrom(cyclus::QueryableBackend* b){ #pragma cyclus impl initfromdb commodconverter::CommodConverter using cyclus::toolkit::Commodity; Commodity commod = Commodity(out_commod); cyclus::toolkit::CommodityProducer::Add(commod); cyclus::toolkit::CommodityProducer::SetCapacity(commod, capacity); cyclus::toolkit::CommodityProducer::SetCost(commod, cost); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::EnterNotify() { Facility::EnterNotify(); using cyclus::toolkit::Commodity; Commodity commod = Commodity(out_commod); cyclus::toolkit::CommodityProducer::Add(commod); cyclus::toolkit::CommodityProducer::SetCapacity(commod, capacity); cyclus::toolkit::CommodityProducer::SetCost(commod, cost); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - std::string CommodConverter::str() { std::stringstream ss; std::string ans; if (cyclus::toolkit::CommodityProducer:: Produces(cyclus::toolkit::Commodity(out_commod_()))){ ans = "yes"; } else { ans = "no"; } ss << cyclus::Facility::str(); ss << " has facility parameters {" << "\n" << " Input Commodity = " << in_commod_() << ",\n" << " Output Commodity = " << out_commod_() << ",\n" << " Process Time = " << process_time_() << ",\n" << " Capacity = " << capacity_() << ",\n" << " commod producer members: " << " produces " << out_commod << "?:" << ans << " capacity: " << cyclus::toolkit::CommodityProducer::Capacity(out_commod_()) << " cost: " << cyclus::toolkit::CommodityProducer::Cost(out_commod_()) << "'}"; return ss.str(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::Tick() { LOG(cyclus::LEV_INFO3, "ComCnv") << prototype() << " is ticking {"; if (current_capacity() > cyclus::eps()) { LOG(cyclus::LEV_INFO4, "ComCnv") << " has capacity for " << current_capacity() << " kg of " << in_commod << " recipe: " << in_recipe << "."; } LOG(cyclus::LEV_INFO3, "ComCnv") << "}"; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::Tock() { LOG(cyclus::LEV_INFO3, "ComCnv") << prototype() << " is tocking {"; BeginProcessing_(); // place unprocessed inventory into processing if( ready() >= 0 || process_time_() == 0 ) { Convert_(capacity_()); // place processing into stocks } LOG(cyclus::LEV_INFO3, "ComCnv") << "}"; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - std::set<cyclus::RequestPortfolio<cyclus::Material>::Ptr> CommodConverter::GetMatlRequests() { using cyclus::CapacityConstraint; using cyclus::Material; using cyclus::RequestPortfolio; using cyclus::Request; std::set<RequestPortfolio<Material>::Ptr> ports; RequestPortfolio<Material>::Ptr port(new RequestPortfolio<Material>()); Material::Ptr mat = Request_(); double amt = mat->quantity(); if (amt > cyclus::eps()) { //CapacityConstraint<Material> cc(amt); //port->AddConstraint(cc); port->AddRequest(mat, this, in_commod_()); ports.insert(port); } return ports; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::AcceptMatlTrades( const std::vector< std::pair<cyclus::Trade<cyclus::Material>, cyclus::Material::Ptr> >& responses) { std::vector< std::pair<cyclus::Trade<cyclus::Material>, cyclus::Material::Ptr> >::const_iterator it; for (it = responses.begin(); it != responses.end(); ++it) { AddMat_(it->second); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - std::set<cyclus::BidPortfolio<cyclus::Material>::Ptr> CommodConverter::GetMatlBids(cyclus::CommodMap<cyclus::Material>::type& commod_requests) { using cyclus::BidPortfolio; using cyclus::Material; std::set<BidPortfolio<Material>::Ptr> ports; std::set<std::string>::const_iterator it; BidPortfolio<Material>::Ptr port = GetBids_(commod_requests, out_commod, &stocks); if (!port->bids().empty()) { ports.insert(port); } return ports; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::GetMatlTrades( const std::vector< cyclus::Trade<cyclus::Material> >& trades, std::vector<std::pair<cyclus::Trade<cyclus::Material>, cyclus::Material::Ptr> >& responses) { using cyclus::Material; using cyclus::Trade; // for each trade, respond std::vector< Trade<Material> >::const_iterator it; for (it = trades.begin(); it != trades.end(); ++it) { std::string commodity = it->request->commodity(); //double qty = it->amt; double qty = stocks.quantity(); // create a material pointer representing what you can offer Material::Ptr response = TradeResponse_(qty, &stocks); responses.push_back(std::make_pair(*it, response)); LOG(cyclus::LEV_INFO5, "ComCnv") << prototype() << " just received an order" << " for " << it->amt << " of " << commodity; } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::AddMat_(cyclus::Material::Ptr mat) { // Here we do not check that the recipe matches the input recipe. LOG(cyclus::LEV_INFO5, "ComCnv") << prototype() << " is initially holding " << inventory.quantity() << " total."; try { inventory.Push(mat); } catch (cyclus::Error& e) { e.msg(Agent::InformErrorMsg(e.msg())); throw e; } LOG(cyclus::LEV_INFO5, "ComCnv") << prototype() << " added " << mat->quantity() << " of " << in_commod_() << " to its inventory, which is holding " << inventory.quantity() << " total."; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cyclus::Material::Ptr CommodConverter::Request_() { double qty = std::max(0.0, current_capacity()); LOG(cyclus::LEV_INFO5, "ComCnv") << prototype() << " just requested " << current_capacity() << " of commodity: " << in_commod << " with recipe: " << in_recipe; return cyclus::Material::CreateUntracked(qty, context()->GetRecipe(in_recipe)); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cyclus::BidPortfolio<cyclus::Material>::Ptr CommodConverter::GetBids_( cyclus::CommodMap<cyclus::Material>::type& commod_requests, std::string commod, cyclus::toolkit::ResourceBuff* buffer) { using cyclus::Bid; using cyclus::BidPortfolio; using cyclus::CapacityConstraint; using cyclus::Composition; using cyclus::Converter; using cyclus::Material; using cyclus::Request; using cyclus::ResCast; using cyclus::toolkit::ResourceBuff; BidPortfolio<Material>::Ptr port(new BidPortfolio<Material>()); if (commod_requests.count(commod) > 0 && buffer->quantity() > 0) { std::vector<Request<Material>*>& requests = commod_requests.at(commod); // get offer composition Material::Ptr back = ResCast<Material>(buffer->Pop(ResourceBuff::BACK)); Composition::Ptr comp = back->comp(); buffer->Push(back); std::vector<Request<Material>*>::iterator it; for (it = requests.begin(); it != requests.end(); ++it) { Request<Material>* req = *it; double qty = std::min(req->target()->quantity(), buffer->quantity()); Material::Ptr offer = Material::CreateUntracked(qty, comp); port->AddBid(req, offer, this); } //CapacityConstraint<Material> cc(buffer->quantity()); //port->AddConstraint(cc); } return port; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cyclus::Material::Ptr CommodConverter::TradeResponse_( double qty, cyclus::toolkit::ResourceBuff* buffer) { using cyclus::Material; using cyclus::ResCast; std::vector<Material::Ptr> manifest; try { // pop amount from inventory and blob it into one material manifest = ResCast<Material>(buffer->PopQty(qty)); } catch(cyclus::Error& e) { e.msg(Agent::InformErrorMsg(e.msg())); throw e; } Material::Ptr response = manifest[0]; for (int i = 1; i < manifest.size(); i++) { response->Absorb(manifest[i]); } return response; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::BeginProcessing_(){ if( inventory.count() > 0 ){ try { processing[context()->time()].Push(inventory.Pop()); LOG(cyclus::LEV_DEBUG2, "ComCnv") << "CommodConverter " << prototype() << " added resources to processing at t= " << context()->time(); } catch (cyclus::Error& e) { e.msg(Agent::InformErrorMsg(e.msg())); throw e; } } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::Convert_(double cap){ using cyclus::Material; using cyclus::ResCast; using cyclus::toolkit::ResourceBuff; using cyclus::toolkit::Manifest; int t = ready(); if ( ProcessingAmt_(t) > 0 ){ try { double to_pop = std::min(cap, processing[t].quantity()); // pop appropriate amount of material from processing std::vector<Material::Ptr> to_conv = ResCast<Material>(processing[t].PopQty(to_pop)); // if an out_recipe was provided, transmute it std::vector<Material::Ptr>::iterator mat; if( out_recipe == "" ){ // if no out recipe, then no transmute needed stocks.PushAll(to_conv); } else { // transmute each mat for(mat=to_conv.begin(); mat!=to_conv.end(); ++mat) { (*mat)->Transmute(context()->GetRecipe(out_recipe)); // put it in the stocks stocks.Push(*mat); } } AdvanceUnconverted_(t); LOG(cyclus::LEV_INFO1, "ComCnv") << "CommodConverter " << prototype() << " converted quantity : " << to_pop << " from " << in_commod << " to " << out_commod; } catch (cyclus::Error& e) { e.msg(Agent::InformErrorMsg(e.msg())); throw e; } } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double CommodConverter::ProcessingAmt_(int time) { using cyclus::toolkit::ResourceBuff; double to_ret = 0; std::map<int, ResourceBuff>::iterator proc = processing.find(time); if ( proc!=processing.end() && proc->second.quantity() > 0 ) { to_ret = proc->second.quantity(); } return to_ret; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::AdvanceUnconverted_(int time){ using cyclus::Material; using cyclus::ResCast; double to_pop = ProcessingAmt_(time); if ( to_pop > 0 ) { try { std::vector<Material::Ptr> to_advance = ResCast<Material>(processing[time].PopQty(to_pop)); processing[time+1].PushAll(to_advance); } catch (cyclus::Error& e) { e.msg(Agent::InformErrorMsg(e.msg())); throw e; } } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - extern "C" cyclus::Agent* ConstructCommodConverter(cyclus::Context* ctx) { return new CommodConverter(ctx); } } // namespace commodconverter <commit_msg>fixed popqty seg fault when qty = 0<commit_after>// commodconverter.cc // Implements the CommodConverter class #include "commodconverter.h" namespace commodconverter { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - CommodConverter::CommodConverter(cyclus::Context* ctx) : cyclus::Facility(ctx) { cyclus::Warn<cyclus::EXPERIMENTAL_WARNING>("the CommodConverter is experimental."); }; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // pragmas #pragma cyclus def schema commodconverter::CommodConverter #pragma cyclus def annotations commodconverter::CommodConverter #pragma cyclus def initinv commodconverter::CommodConverter #pragma cyclus def snapshotinv commodconverter::CommodConverter #pragma cyclus def infiletodb commodconverter::CommodConverter #pragma cyclus def snapshot commodconverter::CommodConverter #pragma cyclus def clone commodconverter::CommodConverter //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::InitFrom(CommodConverter* m) { #pragma cyclus impl initfromcopy commodconverter::CommodConverter cyclus::toolkit::CommodityProducer::Copy(m); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::InitFrom(cyclus::QueryableBackend* b){ #pragma cyclus impl initfromdb commodconverter::CommodConverter using cyclus::toolkit::Commodity; Commodity commod = Commodity(out_commod); cyclus::toolkit::CommodityProducer::Add(commod); cyclus::toolkit::CommodityProducer::SetCapacity(commod, capacity); cyclus::toolkit::CommodityProducer::SetCost(commod, cost); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::EnterNotify() { Facility::EnterNotify(); using cyclus::toolkit::Commodity; Commodity commod = Commodity(out_commod); cyclus::toolkit::CommodityProducer::Add(commod); cyclus::toolkit::CommodityProducer::SetCapacity(commod, capacity); cyclus::toolkit::CommodityProducer::SetCost(commod, cost); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - std::string CommodConverter::str() { std::stringstream ss; std::string ans; if (cyclus::toolkit::CommodityProducer:: Produces(cyclus::toolkit::Commodity(out_commod_()))){ ans = "yes"; } else { ans = "no"; } ss << cyclus::Facility::str(); ss << " has facility parameters {" << "\n" << " Input Commodity = " << in_commod_() << ",\n" << " Output Commodity = " << out_commod_() << ",\n" << " Process Time = " << process_time_() << ",\n" << " Capacity = " << capacity_() << ",\n" << " commod producer members: " << " produces " << out_commod << "?:" << ans << " capacity: " << cyclus::toolkit::CommodityProducer::Capacity(out_commod_()) << " cost: " << cyclus::toolkit::CommodityProducer::Cost(out_commod_()) << "'}"; return ss.str(); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::Tick() { LOG(cyclus::LEV_INFO3, "ComCnv") << prototype() << " is ticking {"; if (current_capacity() > cyclus::eps()) { LOG(cyclus::LEV_INFO4, "ComCnv") << " has capacity for " << current_capacity() << " kg of " << in_commod << " recipe: " << in_recipe << "."; } LOG(cyclus::LEV_INFO3, "ComCnv") << "}"; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::Tock() { LOG(cyclus::LEV_INFO3, "ComCnv") << prototype() << " is tocking {"; BeginProcessing_(); // place unprocessed inventory into processing if( ready() >= 0 || process_time_() == 0 ) { Convert_(capacity_()); // place processing into stocks } LOG(cyclus::LEV_INFO3, "ComCnv") << "}"; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - std::set<cyclus::RequestPortfolio<cyclus::Material>::Ptr> CommodConverter::GetMatlRequests() { using cyclus::CapacityConstraint; using cyclus::Material; using cyclus::RequestPortfolio; using cyclus::Request; std::set<RequestPortfolio<Material>::Ptr> ports; RequestPortfolio<Material>::Ptr port(new RequestPortfolio<Material>()); Material::Ptr mat = Request_(); double amt = mat->quantity(); if (amt > cyclus::eps()) { //CapacityConstraint<Material> cc(amt); //port->AddConstraint(cc); port->AddRequest(mat, this, in_commod_()); ports.insert(port); } return ports; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::AcceptMatlTrades( const std::vector< std::pair<cyclus::Trade<cyclus::Material>, cyclus::Material::Ptr> >& responses) { std::vector< std::pair<cyclus::Trade<cyclus::Material>, cyclus::Material::Ptr> >::const_iterator it; for (it = responses.begin(); it != responses.end(); ++it) { AddMat_(it->second); } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - std::set<cyclus::BidPortfolio<cyclus::Material>::Ptr> CommodConverter::GetMatlBids(cyclus::CommodMap<cyclus::Material>::type& commod_requests) { using cyclus::BidPortfolio; using cyclus::Material; std::set<BidPortfolio<Material>::Ptr> ports; std::set<std::string>::const_iterator it; BidPortfolio<Material>::Ptr port = GetBids_(commod_requests, out_commod, &stocks); if (!port->bids().empty()) { ports.insert(port); } return ports; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::GetMatlTrades( const std::vector< cyclus::Trade<cyclus::Material> >& trades, std::vector<std::pair<cyclus::Trade<cyclus::Material>, cyclus::Material::Ptr> >& responses) { using cyclus::Material; using cyclus::Trade; // for each trade, respond std::vector< Trade<Material> >::const_iterator it; for (it = trades.begin(); it != trades.end(); ++it) { std::string commodity = it->request->commodity(); //double qty = it->amt; double qty = stocks.quantity(); // create a material pointer representing what you can offer if ( qty > 0 ) { Material::Ptr response = TradeResponse_(qty, &stocks); responses.push_back(std::make_pair(*it, response)); } LOG(cyclus::LEV_INFO5, "ComCnv") << prototype() << " just received an order" << " for " << it->amt << " of " << commodity; } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::AddMat_(cyclus::Material::Ptr mat) { // Here we do not check that the recipe matches the input recipe. LOG(cyclus::LEV_INFO5, "ComCnv") << prototype() << " is initially holding " << inventory.quantity() << " total."; try { inventory.Push(mat); } catch (cyclus::Error& e) { e.msg(Agent::InformErrorMsg(e.msg())); throw e; } LOG(cyclus::LEV_INFO5, "ComCnv") << prototype() << " added " << mat->quantity() << " of " << in_commod_() << " to its inventory, which is holding " << inventory.quantity() << " total."; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cyclus::Material::Ptr CommodConverter::Request_() { double qty = std::max(0.0, current_capacity()); LOG(cyclus::LEV_INFO5, "ComCnv") << prototype() << " just requested " << current_capacity() << " of commodity: " << in_commod << " with recipe: " << in_recipe; return cyclus::Material::CreateUntracked(qty, context()->GetRecipe(in_recipe)); } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cyclus::BidPortfolio<cyclus::Material>::Ptr CommodConverter::GetBids_( cyclus::CommodMap<cyclus::Material>::type& commod_requests, std::string commod, cyclus::toolkit::ResourceBuff* buffer) { using cyclus::Bid; using cyclus::BidPortfolio; using cyclus::CapacityConstraint; using cyclus::Composition; using cyclus::Converter; using cyclus::Material; using cyclus::Request; using cyclus::ResCast; using cyclus::toolkit::ResourceBuff; BidPortfolio<Material>::Ptr port(new BidPortfolio<Material>()); if (commod_requests.count(commod) > 0 && buffer->quantity() > 0) { std::vector<Request<Material>*>& requests = commod_requests.at(commod); // get offer composition Material::Ptr back = ResCast<Material>(buffer->Pop(ResourceBuff::BACK)); Composition::Ptr comp = back->comp(); buffer->Push(back); std::vector<Request<Material>*>::iterator it; for (it = requests.begin(); it != requests.end(); ++it) { Request<Material>* req = *it; double qty = std::min(req->target()->quantity(), buffer->quantity()); Material::Ptr offer = Material::CreateUntracked(qty, comp); port->AddBid(req, offer, this); } //CapacityConstraint<Material> cc(buffer->quantity()); //port->AddConstraint(cc); } return port; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - cyclus::Material::Ptr CommodConverter::TradeResponse_( double qty, cyclus::toolkit::ResourceBuff* buffer) { using cyclus::Material; using cyclus::ResCast; std::vector<Material::Ptr> manifest; try { // pop amount from inventory and blob it into one material manifest = ResCast<Material>(buffer->PopQty(qty)); Material::Ptr response = manifest[0]; for (int i = 1; i < manifest.size(); i++) { response->Absorb(manifest[i]); } return response; } catch(cyclus::Error& e) { e.msg(Agent::InformErrorMsg(e.msg())); throw e; } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::BeginProcessing_(){ if( inventory.count() > 0 ){ try { processing[context()->time()].Push(inventory.Pop()); LOG(cyclus::LEV_DEBUG2, "ComCnv") << "CommodConverter " << prototype() << " added resources to processing at t= " << context()->time(); } catch (cyclus::Error& e) { e.msg(Agent::InformErrorMsg(e.msg())); throw e; } } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::Convert_(double cap){ using cyclus::Material; using cyclus::ResCast; using cyclus::toolkit::ResourceBuff; using cyclus::toolkit::Manifest; int t = ready(); if ( ProcessingAmt_(t) > 0 ){ try { double to_pop = std::min(cap, processing[t].quantity()); // pop appropriate amount of material from processing std::vector<Material::Ptr> to_conv = ResCast<Material>(processing[t].PopQty(to_pop)); // if an out_recipe was provided, transmute it std::vector<Material::Ptr>::iterator mat; if( out_recipe == "" ){ // if no out recipe, then no transmute needed stocks.PushAll(to_conv); } else { // transmute each mat for(mat=to_conv.begin(); mat!=to_conv.end(); ++mat) { (*mat)->Transmute(context()->GetRecipe(out_recipe)); // put it in the stocks stocks.Push(*mat); } } AdvanceUnconverted_(t); LOG(cyclus::LEV_INFO1, "ComCnv") << "CommodConverter " << prototype() << " converted quantity : " << to_pop << " from " << in_commod << " to " << out_commod << " at t= " << context()->time(); } catch (cyclus::Error& e) { e.msg(Agent::InformErrorMsg(e.msg())); throw e; } } } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - double CommodConverter::ProcessingAmt_(int time) { using cyclus::toolkit::ResourceBuff; double to_ret = 0; std::map<int, ResourceBuff>::iterator proc = processing.find(time); if ( proc!=processing.end() && proc->second.quantity() > 0 ) { to_ret = proc->second.quantity(); } return to_ret; } //- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void CommodConverter::AdvanceUnconverted_(int time){ using cyclus::Material; using cyclus::ResCast; double to_pop = ProcessingAmt_(time); if ( to_pop > 0 ) { try { std::vector<Material::Ptr> to_advance = ResCast<Material>(processing[time].PopQty(to_pop)); processing[time+1].PushAll(to_advance); } catch (cyclus::Error& e) { e.msg(Agent::InformErrorMsg(e.msg())); throw e; } } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - extern "C" cyclus::Agent* ConstructCommodConverter(cyclus::Context* ctx) { return new CommodConverter(ctx); } } // namespace commodconverter <|endoftext|>
<commit_before>/* * karm * This file only: Copyright (C) 1999 Espen Sand, espensa@online.no * Modifications (see CVS log) Copyright (C) 2000 Klarlvdalens * Datakonsult AB <kalle@dalheimer.de>, Jesper Pedersen <blackie@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. * * $Id$ */ #include <qlabel.h> #include <qlineedit.h> #include <qlayout.h> #include <qregexp.h> #include <qhbox.h> #include <kapplication.h> #include <klocale.h> #include <qcombobox.h> #include <kdebug.h> #include <qradiobutton.h> #include <qbuttongroup.h> #include <qpixmap.h> #include <kiconloader.h> #include <qwhatsthis.h> #include "adddlg.h" #include "karm.h" #include "ktimewidget.h" #include <qpushbutton.h> AddTaskDialog::AddTaskDialog(QString caption, bool editDlg) :KDialogBase(0, "AddTaskDialog", true, caption, Ok|Cancel, Ok, true ) { QWidget *page = new QWidget( this ); setMainWidget(page); QVBoxLayout *lay1 = new QVBoxLayout(page); QHBoxLayout *lay2 = new QHBoxLayout(); lay1->addLayout(lay2); // The name of the widget QLabel *label = new QLabel( i18n("Task name:"), page, "name" ); lay2->addWidget( label ); lay2->addSpacing(5); _name = new QLineEdit( page, "lineedit" ); _name->setMinimumWidth(fontMetrics().maxWidth()*15); lay2->addWidget( _name ); // The "Edit Absolut" radio button lay1->addSpacing(10);lay1->addStretch(1); _absoluteRB = new QRadioButton( i18n( "Edit absolute" ), page, "_absoluteRB" ); lay1->addWidget( _absoluteRB ); connect( _absoluteRB, SIGNAL( clicked() ), this, SLOT(slotAbsolutePressed()) ); // Absolute times QHBoxLayout *lay5 = new QHBoxLayout(); lay1->addLayout(lay5); lay5->addSpacing(20); QGridLayout *lay3 = new QGridLayout( 2, 2, -1, "lay3" ); lay5->addLayout(lay3); // Total Time _totalLA = new QLabel( i18n("Total:"), page, "time" ); lay3->addWidget( _totalLA, 0, 0 ); _totalTW = new KTimeWidget( page, "_totalTW" ); lay3->addWidget( _totalTW, 0, 1 ); // Session _sessionLA = new QLabel( i18n("Session time:"), page, "session time" ); lay3->addWidget( _sessionLA, 1, 0 ); _sessionTW = new KTimeWidget( page, "_sessionTW" ); lay3->addWidget( _sessionTW, 1, 1 ); // The "Edit relative" radio button lay1->addSpacing(10);lay1->addStretch(1); _relativeRB = new QRadioButton( i18n( "Edit relative (Apply to both session and total)" ), page, "_relativeRB" ); lay1->addWidget( _relativeRB ); connect( _relativeRB, SIGNAL( clicked() ), this, SLOT(slotRelativePressed()) ); // The relative times QHBoxLayout *lay4 = new QHBoxLayout(); lay1->addLayout( lay4 ); lay4->addSpacing(20); _operator = new QComboBox(page); _operator->insertItem( QString::fromLatin1( "+" ) ); _operator->insertItem( QString::fromLatin1( "-" ) ); lay4->addWidget( _operator ); lay4->addSpacing(5); _diffTW = new KTimeWidget( page, "_sessionAddTW" ); lay4->addWidget( _diffTW ); KIconLoader loader; QPixmap whatsThisIM = loader.loadIcon(QString::fromLatin1("contexthelp"), KIcon::Toolbar); QPushButton* whatsThisBU = new QPushButton(page, "whatsThisLA"); whatsThisBU->setFocusPolicy(NoFocus); connect(whatsThisBU, SIGNAL(clicked()), this, SLOT(enterWhatsThis())); whatsThisBU->setPixmap( whatsThisIM ); lay4->addWidget(whatsThisBU); lay1->addStretch(1); if ( editDlg ) { // This is an edit dialog. _operator->setFocus(); } else { // This is an initial dialog _name->setFocus(); } origTotal = 0; origSession = 0; slotRelativePressed(); // Whats this help. QWhatsThis::add(_name, i18n("Enter the name of the task here. This name is for your eyes only.")); QWhatsThis::add(_absoluteRB, i18n("If you select this radio button, you specify that you want " "to enter the time as absolute values. For example: " "total for this task is 20 hours and 15 minutes.\n\n" "The time is specified for the session time and for the total time " "separately.")); QWhatsThis::add(_relativeRB, i18n("If you select this radio button, you specify that you want " "to add or subtract time for the task. For example: I've worked 2 hours " "and 20 minutes more on this task (without having the timer " "running.)\n\n" "This time will be added or subtracted for both the " "session time and the total time.")); QWhatsThis::add(_totalTW, i18n("This is the overall time this task has been running.")); QWhatsThis::add(_sessionTW, i18n("This is the time the task has been running this session.")); QWhatsThis::add(_diffTW, i18n("Specify how much time to add or subtract to the overall and " "session time")); } void AddTaskDialog::enterWhatsThis() { QWhatsThis::enterWhatsThisMode (); } void AddTaskDialog::slotAbsolutePressed() { _relativeRB->setChecked( false ); _absoluteRB->setChecked( true ); _operator->setEnabled( false ); _diffTW->setEnabled( false ); _totalLA->setEnabled( true ); _sessionLA->setEnabled( true ); _totalTW->setEnabled( true ); _sessionTW->setEnabled( true ); } void AddTaskDialog::slotRelativePressed() { _relativeRB->setChecked( true ); _absoluteRB->setChecked( false ); _operator->setEnabled( true ); _diffTW->setEnabled( true ); _totalLA->setEnabled( false ); _sessionLA->setEnabled( false ); _totalTW->setEnabled( false ); _sessionTW->setEnabled( false ); } void AddTaskDialog::setTask( const QString &name, long total, long session ) { _name->setText( name ); _totalTW->setTime( total / 60, total % 60 ); _sessionTW->setTime( session / 60, session % 60 ); origTotal = total; origSession = session; } QString AddTaskDialog::taskName( void ) const { return( _name->text() ); } void AddTaskDialog::status( long *total, long *totalDiff, long *session, long *sessionDiff ) const { if ( _absoluteRB->isChecked() ) { *total = _totalTW->time(); *session = _sessionTW->time(); } else { int diff = _diffTW->time(); if ( _operator->currentItem() == 1) { diff = -diff; } *total = origTotal + diff; *session = origSession + diff; } *totalDiff = *total - origTotal; *sessionDiff = *session - origSession; } #include "adddlg.moc" <commit_msg>GUI: accels and buddies for the "add/edit task" dialog<commit_after>/* * karm * This file only: Copyright (C) 1999 Espen Sand, espensa@online.no * Modifications (see CVS log) Copyright (C) 2000 Klarlvdalens * Datakonsult AB <kalle@dalheimer.de>, Jesper Pedersen <blackie@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. * * $Id$ */ #include <qlabel.h> #include <qlineedit.h> #include <qlayout.h> #include <qregexp.h> #include <qhbox.h> #include <kapplication.h> #include <klocale.h> #include <qcombobox.h> #include <kdebug.h> #include <qradiobutton.h> #include <qbuttongroup.h> #include <qpixmap.h> #include <kiconloader.h> #include <qwhatsthis.h> #include "adddlg.h" #include "karm.h" #include "ktimewidget.h" #include <qpushbutton.h> AddTaskDialog::AddTaskDialog(QString caption, bool editDlg) :KDialogBase(0, "AddTaskDialog", true, caption, Ok|Cancel, Ok, true ) { QWidget *page = new QWidget( this ); setMainWidget(page); QVBoxLayout *lay1 = new QVBoxLayout(page); QHBoxLayout *lay2 = new QHBoxLayout(); lay1->addLayout(lay2); // The name of the widget QLabel *label = new QLabel( i18n("Task &name:"), page, "name" ); lay2->addWidget( label ); lay2->addSpacing(5); _name = new QLineEdit( page, "lineedit" ); _name->setMinimumWidth(fontMetrics().maxWidth()*15); lay2->addWidget( _name ); label->setBuddy( _name ); // The "Edit Absolut" radio button lay1->addSpacing(10);lay1->addStretch(1); _absoluteRB = new QRadioButton( i18n( "Edit &absolute" ), page, "_absoluteRB" ); lay1->addWidget( _absoluteRB ); connect( _absoluteRB, SIGNAL( clicked() ), this, SLOT(slotAbsolutePressed()) ); // Absolute times QHBoxLayout *lay5 = new QHBoxLayout(); lay1->addLayout(lay5); lay5->addSpacing(20); QGridLayout *lay3 = new QGridLayout( 2, 2, -1, "lay3" ); lay5->addLayout(lay3); // Total Time _totalLA = new QLabel( i18n("&Total:"), page, "time" ); lay3->addWidget( _totalLA, 0, 0 ); _totalTW = new KTimeWidget( page, "_totalTW" ); lay3->addWidget( _totalTW, 0, 1 ); _totalLA->setBuddy( _totalTW ); // Session _sessionLA = new QLabel( i18n("&Session time:"), page, "session time" ); lay3->addWidget( _sessionLA, 1, 0 ); _sessionTW = new KTimeWidget( page, "_sessionTW" ); lay3->addWidget( _sessionTW, 1, 1 ); _sessionLA->setBuddy( _sessionTW ); // The "Edit relative" radio button lay1->addSpacing(10);lay1->addStretch(1); _relativeRB = new QRadioButton( i18n( "Edit &relative (Apply to both session and total)" ), page, "_relativeRB" ); lay1->addWidget( _relativeRB ); connect( _relativeRB, SIGNAL( clicked() ), this, SLOT(slotRelativePressed()) ); // The relative times QHBoxLayout *lay4 = new QHBoxLayout(); lay1->addLayout( lay4 ); lay4->addSpacing(20); _operator = new QComboBox(page); _operator->insertItem( QString::fromLatin1( "+" ) ); _operator->insertItem( QString::fromLatin1( "-" ) ); lay4->addWidget( _operator ); lay4->addSpacing(5); _diffTW = new KTimeWidget( page, "_sessionAddTW" ); lay4->addWidget( _diffTW ); KIconLoader loader; QPixmap whatsThisIM = loader.loadIcon(QString::fromLatin1("contexthelp"), KIcon::Toolbar); QPushButton* whatsThisBU = new QPushButton(page, "whatsThisLA"); whatsThisBU->setFocusPolicy(NoFocus); connect(whatsThisBU, SIGNAL(clicked()), this, SLOT(enterWhatsThis())); whatsThisBU->setPixmap( whatsThisIM ); lay4->addWidget(whatsThisBU); lay1->addStretch(1); if ( editDlg ) { // This is an edit dialog. _operator->setFocus(); } else { // This is an initial dialog _name->setFocus(); } origTotal = 0; origSession = 0; slotRelativePressed(); // Whats this help. QWhatsThis::add(_name, i18n("Enter the name of the task here. This name is for your eyes only.")); QWhatsThis::add(_absoluteRB, i18n("If you select this radio button, you specify that you want " "to enter the time as absolute values. For example: " "total for this task is 20 hours and 15 minutes.\n\n" "The time is specified for the session time and for the total time " "separately.")); QWhatsThis::add(_relativeRB, i18n("If you select this radio button, you specify that you want " "to add or subtract time for the task. For example: I've worked 2 hours " "and 20 minutes more on this task (without having the timer " "running.)\n\n" "This time will be added or subtracted for both the " "session time and the total time.")); QWhatsThis::add(_totalTW, i18n("This is the overall time this task has been running.")); QWhatsThis::add(_sessionTW, i18n("This is the time the task has been running this session.")); QWhatsThis::add(_diffTW, i18n("Specify how much time to add or subtract to the overall and " "session time")); } void AddTaskDialog::enterWhatsThis() { QWhatsThis::enterWhatsThisMode (); } void AddTaskDialog::slotAbsolutePressed() { _relativeRB->setChecked( false ); _absoluteRB->setChecked( true ); _operator->setEnabled( false ); _diffTW->setEnabled( false ); _totalLA->setEnabled( true ); _sessionLA->setEnabled( true ); _totalTW->setEnabled( true ); _sessionTW->setEnabled( true ); } void AddTaskDialog::slotRelativePressed() { _relativeRB->setChecked( true ); _absoluteRB->setChecked( false ); _operator->setEnabled( true ); _diffTW->setEnabled( true ); _totalLA->setEnabled( false ); _sessionLA->setEnabled( false ); _totalTW->setEnabled( false ); _sessionTW->setEnabled( false ); } void AddTaskDialog::setTask( const QString &name, long total, long session ) { _name->setText( name ); _totalTW->setTime( total / 60, total % 60 ); _sessionTW->setTime( session / 60, session % 60 ); origTotal = total; origSession = session; } QString AddTaskDialog::taskName( void ) const { return( _name->text() ); } void AddTaskDialog::status( long *total, long *totalDiff, long *session, long *sessionDiff ) const { if ( _absoluteRB->isChecked() ) { *total = _totalTW->time(); *session = _sessionTW->time(); } else { int diff = _diffTW->time(); if ( _operator->currentItem() == 1) { diff = -diff; } *total = origTotal + diff; *session = origSession + diff; } *totalDiff = *total - origTotal; *sessionDiff = *session - origSession; } #include "adddlg.moc" <|endoftext|>
<commit_before>#pragma once #include <QString> #include <QtGlobal> #define CHATTERINO_VERSION "2.2.3-beta2" #if defined(Q_OS_WIN) # define CHATTERINO_OS "win" #elif defined(Q_OS_MACOS) # define CHATTERINO_OS "macos" #elif defined(Q_OS_LINUX) # define CHATTERINO_OS "linux" #elif defined(Q_OS_FREEBSD) # define CHATTERINO_OS "freebsd" #else # define CHATTERINO_OS "unknown" #endif namespace chatterino { class Version { public: static const Version &instance(); const QString &version() const; const QString &commitHash() const; const QString &dateOfBuild() const; const QString &fullVersion() const; const bool &isSupportedOS() const; private: Version(); QString version_; QString commitHash_; QString dateOfBuild_; QString fullVersion_; bool isSupportedOS_; }; }; // namespace chatterino <commit_msg>bumped version<commit_after>#pragma once #include <QString> #include <QtGlobal> #define CHATTERINO_VERSION "2.3" #if defined(Q_OS_WIN) # define CHATTERINO_OS "win" #elif defined(Q_OS_MACOS) # define CHATTERINO_OS "macos" #elif defined(Q_OS_LINUX) # define CHATTERINO_OS "linux" #elif defined(Q_OS_FREEBSD) # define CHATTERINO_OS "freebsd" #else # define CHATTERINO_OS "unknown" #endif namespace chatterino { class Version { public: static const Version &instance(); const QString &version() const; const QString &commitHash() const; const QString &dateOfBuild() const; const QString &fullVersion() const; const bool &isSupportedOS() const; private: Version(); QString version_; QString commitHash_; QString dateOfBuild_; QString fullVersion_; bool isSupportedOS_; }; }; // namespace chatterino <|endoftext|>
<commit_before>#pragma once #include <http_parser.h> // #include <iostream> // TODO: remove #include <stdexcept> #include <string> #include <map> #include <sstream> #include <deque> #include <type_traits> #include <functional> #include <iterator> #include <cassert> namespace http { class Request; using Headers = std::map<std::string, std::string>; using RequestConsumer = std::function<void(Request&&)>; namespace detail { template<typename ParserT> struct Callbacks { static int onMessageBegin(http_parser* p) { return ((ParserT*) p->data)->onMessageBegin(); } static int onUrl(http_parser* p, const char *data, size_t length) { return ((ParserT*) p->data)->onUrl(data, length); } static int onStatus(http_parser* p, const char *data, size_t length) { return ((ParserT*) p->data)->onStatus(data, length); } static int onHeaderField(http_parser* p, const char *data, size_t length) { return ((ParserT*) p->data)->onHeaderField(data, length); } static int onHeaderValue(http_parser* p, const char *data, size_t length) { return ((ParserT*) p->data)->onHeaderValue(data, length); } static int onHeadersComplete(http_parser* p) { return ((ParserT*) p->data)->onHeadersComplete(); } static int onMessageComplete(http_parser* p) { return ((ParserT*) p->data)->onMessageComplete(); } static int onBody(http_parser* p, const char *data, size_t length) { return ((ParserT*) p->data)->onBody(data, length); } static int onChunkHeader(http_parser* p) { return ((ParserT*) p->data)->onChunkHeader(); } static int onChunkComplete(http_parser* p) { return ((ParserT*) p->data)->onChunkComplete(); } }; template<typename ParserT> struct ParserSettings { http_parser_settings s; public: static ParserSettings& get() { static ParserSettings instance; return instance; } ParserSettings(const ParserSettings&) = delete; ParserSettings(ParserSettings&&) = delete; private: ParserSettings() { http_parser_settings_init(&s); s.on_message_begin = &Callbacks<ParserT>::onMessageBegin; s.on_url = &Callbacks<ParserT>::onUrl; s.on_status = &Callbacks<ParserT>::onStatus; s.on_header_field = &Callbacks<ParserT>::onHeaderField; s.on_header_value = &Callbacks<ParserT>::onHeaderValue; s.on_headers_complete = &Callbacks<ParserT>::onHeadersComplete; s.on_body = &Callbacks<ParserT>::onBody; s.on_message_complete = &Callbacks<ParserT>::onMessageComplete; s.on_chunk_header = &Callbacks<ParserT>::onChunkHeader; s.on_chunk_complete = &Callbacks<ParserT>::onChunkComplete; } }; class HeaderAssembler { Headers &headers; std::string currentHeaderField; std::string currentHeaderValue; bool currentHeaderFieldComplete = false; public: HeaderAssembler(Headers &headers): headers(headers) {} HeaderAssembler(const HeaderAssembler&) = delete; HeaderAssembler(HeaderAssembler&&) = delete; HeaderAssembler& operator=(const HeaderAssembler&) = delete; HeaderAssembler& operator=(HeaderAssembler&&) = delete; void reset() { currentHeaderField.clear(); currentHeaderValue.clear(); currentHeaderFieldComplete = false; } void onHeaderField(const char *data, std::size_t length) { if (currentHeaderFieldComplete) { onSingleHeaderComplete(); } currentHeaderField.append(data, length); } void onHeaderValue(const char *data, std::size_t length) { currentHeaderValue.append(data, length); currentHeaderFieldComplete = true; } void onHeadersComplete() { onSingleHeaderComplete(); } private: void onSingleHeaderComplete() { std::string& headerValue = headers[currentHeaderField]; if (headerValue.empty()) { headerValue = std::move(currentHeaderValue); } else if (!currentHeaderValue.empty()) { headerValue.reserve(1 + currentHeaderValue.size()); headerValue.append(","); headerValue.append(currentHeaderValue); } currentHeaderField.clear(); currentHeaderValue.clear(); currentHeaderFieldComplete = false; } }; } /* namespace detail */ class ParseError: public std::runtime_error { public: ParseError(const std::string& msg): std::runtime_error(msg) {} }; template <typename IterT> struct IsContiguousMemoryForwardIterator: std::is_pointer<IterT> {}; template <> struct IsContiguousMemoryForwardIterator <typename std::vector<char>::iterator>: std::true_type {}; template <> struct IsContiguousMemoryForwardIterator <typename std::vector<char>::const_iterator>: std::true_type {}; #ifdef HTTP_PARSER_CPP_IS_CONTIGUOUS_MEMORY_FORWARD_ITERATOR_EXTRA_SPECIALIZATIONS HTTP_PARSER_CPP_IS_CONTIGUOUS_MEMORY_FORWARD_ITERATOR_EXTRA_SPECIALIZATIONS #endif struct Request { using Type = enum http_method; public: Type type = HTTP_HEAD; std::string url; std::string body; Headers headers; public: Request() = default; Request(const Request&) = default; Request(Request&&) = default; Request& operator=(const Request&) = default; Request& operator=(Request&&) = default; }; class Parser { protected: http_parser p; http_parser_settings &parserSettings; std::size_t totalConsumedLength; Parser(http_parser_type parserType, http_parser_settings &parserSettings) : parserSettings(parserSettings), totalConsumedLength(0) { http_parser_init(&p, parserType); p.data = this; } virtual ~Parser() {} public: Parser(const Parser&) = delete; Parser& operator=(const Parser&) = delete; void feed(const char *input, std::size_t inputLength) { std::size_t consumedLength = http_parser_execute( &p, &parserSettings, input, inputLength); totalConsumedLength += consumedLength; if (consumedLength != inputLength) { std::ostringstream errMsg; errMsg << "HTTP Parse error on character " << totalConsumedLength << " (character " << p.nread << " in current request)"; throw ParseError(errMsg.str().c_str()); } } template<typename IterT> typename std::enable_if<std::is_same< typename std::iterator_traits<IterT>::value_type, char>::value>::type feed(IterT begin, IterT end) { feedIter(begin, end); } void feedEof() { (void) feed(nullptr, 0); } private: template<typename IterT> typename std::enable_if<!IsContiguousMemoryForwardIterator<IterT>::value>::type feedIter(IterT begin, IterT end) { for (IterT it = begin; it != end; ++it) { char c = *it; feed(&c, 1); } } template<typename IterT> typename std::enable_if<IsContiguousMemoryForwardIterator<IterT>::value>::type feedIter(IterT begin, IterT end) { const char *buf = &(*begin); const std::size_t len = end - begin; feed(buf, len); } }; class RequestParser: public Parser { Request currentRequest; detail::HeaderAssembler headerAssembler; RequestConsumer requestConsumer; public: std::deque<Request> parsedRequests; public: RequestParser() : Parser(HTTP_REQUEST, detail::ParserSettings<RequestParser>::get().s), headerAssembler(currentRequest.headers) {} RequestParser(RequestConsumer requestConsumer) : Parser(HTTP_REQUEST, detail::ParserSettings<RequestParser>::get().s), headerAssembler(currentRequest.headers), requestConsumer(requestConsumer) {} private: friend struct detail::Callbacks<RequestParser>; int onMessageBegin() { //std::cout << __FUNCTION__ << std::endl; currentRequest = Request(); headerAssembler.reset(); return 0; } int onUrl(const char *data, std::size_t length) { //std::cout << __FUNCTION__ << " (" << std::string(data, length) << ")" << std::endl; currentRequest.url.append(data, length); return 0; } int onStatus(const char *data, std::size_t length) { //std::cout << __FUNCTION__ << " (" << std::string(data, length) << ")" << std::endl; assert(false); // not reached return 0; } int onHeaderField(const char *data, std::size_t length) { //std::cout << __FUNCTION__ << " (" << std::string(data, length) << ")" << std::endl; headerAssembler.onHeaderField(data, length); return 0; } int onHeaderValue(const char *data, std::size_t length) { // std::cout << __FUNCTION__ << " (" << std::string(data, length) << ")" << std::endl; headerAssembler.onHeaderValue(data, length); return 0; } int onHeadersComplete() { // std::cout << __FUNCTION__ << std::endl; headerAssembler.onHeadersComplete(); return 0; } int onBody(const char *data, std::size_t length) { //std::cout << __FUNCTION__ << " (" << std::string(data, length) << ")" << std::endl; currentRequest.body.append(data, length); return 0; } int onMessageComplete() { //std::cout << __FUNCTION__ << std::endl; currentRequest.type = static_cast<Request::Type>(p.method); if (requestConsumer) { requestConsumer(std::move(currentRequest)); } else { parsedRequests.push_back(std::move(currentRequest)); } return 0; } int onChunkHeader() { // std::cout << __FUNCTION__ << " (" << p.content_length << ")" << std::endl; // TODO return 0; } int onChunkComplete() { // std::cout << __FUNCTION__ << std::endl; // TODO return 0; } }; } /* namespace http */ template<typename StreamT> StreamT& operator<<(StreamT& stream, http::Request::Type reqType) { stream << http_method_str(reqType); return stream; } template<typename StreamT> StreamT& operator<<(StreamT& stream, const http::Request& req) { stream << "HTTP " << req.type << " request\n" << "\turl: '" << req.url << "'\n" << "\theaders:\n"; for (const auto& fvPair: req.headers) { stream << "\t\t'" << fvPair.first << "': '" << fvPair.second << "'\n"; } stream << "\tbody is " << req.body.size() << " bytes long."; return stream; } <commit_msg>Fixed some formatting inconsistencies<commit_after>#pragma once #include <http_parser.h> // #include <iostream> // TODO: remove #include <stdexcept> #include <string> #include <map> #include <sstream> #include <deque> #include <type_traits> #include <functional> #include <iterator> #include <cassert> namespace http { class Request; using Headers = std::map<std::string, std::string>; using RequestConsumer = std::function<void(Request&&)>; namespace detail { template<typename ParserT> struct Callbacks { static int onMessageBegin(http_parser* p) { return ((ParserT*) p->data)->onMessageBegin(); } static int onUrl(http_parser* p, const char* data, size_t length) { return ((ParserT*) p->data)->onUrl(data, length); } static int onStatus(http_parser* p, const char* data, size_t length) { return ((ParserT*) p->data)->onStatus(data, length); } static int onHeaderField(http_parser* p, const char* data, size_t length) { return ((ParserT*) p->data)->onHeaderField(data, length); } static int onHeaderValue(http_parser* p, const char* data, size_t length) { return ((ParserT*) p->data)->onHeaderValue(data, length); } static int onHeadersComplete(http_parser* p) { return ((ParserT*) p->data)->onHeadersComplete(); } static int onMessageComplete(http_parser* p) { return ((ParserT*) p->data)->onMessageComplete(); } static int onBody(http_parser* p, const char* data, size_t length) { return ((ParserT*) p->data)->onBody(data, length); } static int onChunkHeader(http_parser* p) { return ((ParserT*) p->data)->onChunkHeader(); } static int onChunkComplete(http_parser* p) { return ((ParserT*) p->data)->onChunkComplete(); } }; template<typename ParserT> struct ParserSettings { http_parser_settings s; public: static ParserSettings& get() { static ParserSettings instance; return instance; } ParserSettings(const ParserSettings&) = delete; ParserSettings(ParserSettings&&) = delete; private: ParserSettings() { http_parser_settings_init(&s); s.on_message_begin = &Callbacks<ParserT>::onMessageBegin; s.on_url = &Callbacks<ParserT>::onUrl; s.on_status = &Callbacks<ParserT>::onStatus; s.on_header_field = &Callbacks<ParserT>::onHeaderField; s.on_header_value = &Callbacks<ParserT>::onHeaderValue; s.on_headers_complete = &Callbacks<ParserT>::onHeadersComplete; s.on_body = &Callbacks<ParserT>::onBody; s.on_message_complete = &Callbacks<ParserT>::onMessageComplete; s.on_chunk_header = &Callbacks<ParserT>::onChunkHeader; s.on_chunk_complete = &Callbacks<ParserT>::onChunkComplete; } }; class HeaderAssembler { Headers& headers; std::string currentHeaderField; std::string currentHeaderValue; bool currentHeaderFieldComplete = false; public: HeaderAssembler(Headers& headers): headers(headers) {} HeaderAssembler(const HeaderAssembler&) = delete; HeaderAssembler(HeaderAssembler&&) = delete; HeaderAssembler& operator=(const HeaderAssembler&) = delete; HeaderAssembler& operator=(HeaderAssembler&&) = delete; void reset() { currentHeaderField.clear(); currentHeaderValue.clear(); currentHeaderFieldComplete = false; } void onHeaderField(const char* data, std::size_t length) { if (currentHeaderFieldComplete) { onSingleHeaderComplete(); } currentHeaderField.append(data, length); } void onHeaderValue(const char* data, std::size_t length) { currentHeaderValue.append(data, length); currentHeaderFieldComplete = true; } void onHeadersComplete() { onSingleHeaderComplete(); } private: void onSingleHeaderComplete() { std::string& headerValue = headers[currentHeaderField]; if (headerValue.empty()) { headerValue = std::move(currentHeaderValue); } else if (!currentHeaderValue.empty()) { headerValue.reserve(1 + currentHeaderValue.size()); headerValue.append(","); headerValue.append(currentHeaderValue); } currentHeaderField.clear(); currentHeaderValue.clear(); currentHeaderFieldComplete = false; } }; } /* namespace detail */ class ParseError: public std::runtime_error { public: ParseError(const std::string& msg): std::runtime_error(msg) {} }; template <typename IterT> struct IsContiguousMemoryForwardIterator: std::is_pointer<IterT> {}; template <> struct IsContiguousMemoryForwardIterator <typename std::vector<char>::iterator>: std::true_type {}; template <> struct IsContiguousMemoryForwardIterator <typename std::vector<char>::const_iterator>: std::true_type {}; #ifdef HTTP_PARSER_CPP_IS_CONTIGUOUS_MEMORY_FORWARD_ITERATOR_EXTRA_SPECIALIZATIONS HTTP_PARSER_CPP_IS_CONTIGUOUS_MEMORY_FORWARD_ITERATOR_EXTRA_SPECIALIZATIONS #endif struct Request { using Type = enum http_method; public: Type type = HTTP_HEAD; std::string url; std::string body; Headers headers; public: Request() = default; Request(const Request&) = default; Request(Request&&) = default; Request& operator=(const Request&) = default; Request& operator=(Request&&) = default; }; class Parser { protected: http_parser p; http_parser_settings& parserSettings; std::size_t totalConsumedLength; Parser(http_parser_type parserType, http_parser_settings& parserSettings) : parserSettings(parserSettings), totalConsumedLength(0) { http_parser_init(&p, parserType); p.data = this; } virtual ~Parser() {} public: Parser(const Parser&) = delete; Parser& operator=(const Parser&) = delete; void feed(const char* input, std::size_t inputLength) { std::size_t consumedLength = http_parser_execute( &p, &parserSettings, input, inputLength); totalConsumedLength += consumedLength; if (consumedLength != inputLength) { std::ostringstream errMsg; errMsg << "HTTP Parse error on character " << totalConsumedLength << " (character " << p.nread << " in current request)"; throw ParseError(errMsg.str().c_str()); } } template<typename IterT> typename std::enable_if<std::is_same< typename std::iterator_traits<IterT>::value_type, char>::value>::type feed(IterT begin, IterT end) { feedIter(begin, end); } void feedEof() { (void) feed(nullptr, 0); } private: template<typename IterT> typename std::enable_if<!IsContiguousMemoryForwardIterator<IterT>::value>::type feedIter(IterT begin, IterT end) { for (IterT it = begin; it != end; ++it) { char c = *it; feed(&c, 1); } } template<typename IterT> typename std::enable_if<IsContiguousMemoryForwardIterator<IterT>::value>::type feedIter(IterT begin, IterT end) { const char *buf = &(*begin); const std::size_t len = end - begin; feed(buf, len); } }; class RequestParser: public Parser { Request currentRequest; detail::HeaderAssembler headerAssembler; RequestConsumer requestConsumer; public: std::deque<Request> parsedRequests; public: RequestParser() : Parser(HTTP_REQUEST, detail::ParserSettings<RequestParser>::get().s), headerAssembler(currentRequest.headers) {} RequestParser(RequestConsumer requestConsumer) : Parser(HTTP_REQUEST, detail::ParserSettings<RequestParser>::get().s), headerAssembler(currentRequest.headers), requestConsumer(requestConsumer) {} private: friend struct detail::Callbacks<RequestParser>; int onMessageBegin() { //std::cout << __FUNCTION__ << std::endl; currentRequest = Request(); headerAssembler.reset(); return 0; } int onUrl(const char* data, std::size_t length) { //std::cout << __FUNCTION__ << " (" << std::string(data, length) << ")" << std::endl; currentRequest.url.append(data, length); return 0; } int onStatus(const char* data, std::size_t length) { //std::cout << __FUNCTION__ << " (" << std::string(data, length) << ")" << std::endl; assert(false); // not reached return 0; } int onHeaderField(const char* data, std::size_t length) { //std::cout << __FUNCTION__ << " (" << std::string(data, length) << ")" << std::endl; headerAssembler.onHeaderField(data, length); return 0; } int onHeaderValue(const char* data, std::size_t length) { // std::cout << __FUNCTION__ << " (" << std::string(data, length) << ")" << std::endl; headerAssembler.onHeaderValue(data, length); return 0; } int onHeadersComplete() { // std::cout << __FUNCTION__ << std::endl; headerAssembler.onHeadersComplete(); return 0; } int onBody(const char* data, std::size_t length) { //std::cout << __FUNCTION__ << " (" << std::string(data, length) << ")" << std::endl; currentRequest.body.append(data, length); return 0; } int onMessageComplete() { //std::cout << __FUNCTION__ << std::endl; currentRequest.type = static_cast<Request::Type>(p.method); if (requestConsumer) { requestConsumer(std::move(currentRequest)); } else { parsedRequests.push_back(std::move(currentRequest)); } return 0; } int onChunkHeader() { // std::cout << __FUNCTION__ << " (" << p.content_length << ")" << std::endl; // TODO return 0; } int onChunkComplete() { // std::cout << __FUNCTION__ << std::endl; // TODO return 0; } }; } /* namespace http */ template<typename StreamT> StreamT& operator<<(StreamT& stream, http::Request::Type reqType) { stream << http_method_str(reqType); return stream; } template<typename StreamT> StreamT& operator<<(StreamT& stream, const http::Request& req) { stream << "HTTP " << req.type << " request\n" << "\turl: '" << req.url << "'\n" << "\theaders:\n"; for (const auto& fvPair: req.headers) { stream << "\t\t'" << fvPair.first << "': '" << fvPair.second << "'\n"; } stream << "\tbody is " << req.body.size() << " bytes long."; return stream; } <|endoftext|>
<commit_before>#include <dropwhile.hpp> #include <vector> #include <iostream> using iter::dropwhile; int main() { std::vector<int> ivec{1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4}; for (auto i : dropwhile([] (int i) {return i < 5;}, ivec)) { std::cout << i << '\n'; } return 0; } <commit_msg>Adds test with temporary<commit_after>#include <dropwhile.hpp> #include <range.hpp> #include <vector> #include <iostream> using iter::dropwhile; using iter::range; int main() { std::vector<int> ivec{1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4}; for (auto i : dropwhile([] (int i) {return i < 5;}, ivec)) { std::cout << i << '\n'; } for (auto i : dropwhile([] (int i) {return i < 5;}, range(10))) { std::cout << i << '\n'; } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2010 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 "base/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/shared_memory.h" #include "base/string16.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/service_process_util.h" #include "chrome/installer/util/version.h" #if defined(OS_WIN) #include "base/object_watcher.h" #include "base/scoped_handle_win.h" #endif // TODO(hclam): Split this file for different platforms. namespace { // This should be more than enough to hold a version string assuming each part // of the version string is an int64. const uint32 kMaxVersionStringLength = 256; // The structure that gets written to shared memory. struct ServiceProcessSharedData { char service_process_version[kMaxVersionStringLength]; base::ProcessId service_process_pid; }; // Return a name that is scoped to this instance of the service process. We // use the user-data-dir as a scoping prefix. std::string GetServiceProcessScopedName(const std::string& append_str) { FilePath user_data_dir; PathService::Get(chrome::DIR_USER_DATA, &user_data_dir); #if defined(OS_WIN) std::string scoped_name = WideToUTF8(user_data_dir.value()); #elif defined(OS_POSIX) std::string scoped_name = user_data_dir.value(); #endif // defined(OS_WIN) std::replace(scoped_name.begin(), scoped_name.end(), '\\', '!'); scoped_name.append(append_str); return scoped_name; } // Return a name that is scoped to this instance of the service process. We // use the user-data-dir and the version as a scoping prefix. std::string GetServiceProcessScopedVersionedName( const std::string& append_str) { std::string versioned_str; chrome::VersionInfo version_info; DCHECK(version_info.is_valid()); versioned_str.append(version_info.Version()); versioned_str.append(append_str); return GetServiceProcessScopedName(versioned_str); } // Gets the name of the shared memory used by the service process to write its // version. The name is not versioned. std::string GetServiceProcessSharedMemName() { return GetServiceProcessScopedName("_service_shmem"); } // Reads the named shared memory to get the shared data. Returns false if no // matching shared memory was found. bool GetServiceProcessSharedData(std::string* version, base::ProcessId* pid) { scoped_ptr<base::SharedMemory> shared_mem_service_data; shared_mem_service_data.reset(new base::SharedMemory()); ServiceProcessSharedData* service_data = NULL; if (shared_mem_service_data.get() && shared_mem_service_data->Open(GetServiceProcessSharedMemName(), true) && shared_mem_service_data->Map(sizeof(ServiceProcessSharedData))) { service_data = reinterpret_cast<ServiceProcessSharedData*>( shared_mem_service_data->memory()); // Make sure the version in shared memory is null-terminated. If it is not, // treat it as invalid. if (version && memchr(service_data->service_process_version, '\0', sizeof(service_data->service_process_version))) *version = service_data->service_process_version; if (pid) *pid = service_data->service_process_pid; return true; } return false; } enum ServiceProcessRunningState { SERVICE_NOT_RUNNING, SERVICE_OLDER_VERSION_RUNNING, SERVICE_SAME_VERSION_RUNNING, SERVICE_NEWER_VERSION_RUNNING, }; ServiceProcessRunningState GetServiceProcessRunningState( std::string* service_version_out) { std::string version; GetServiceProcessSharedData(&version, NULL); if (version.empty()) return SERVICE_NOT_RUNNING; // At this time we have a version string. Set the out param if it exists. if (service_version_out) *service_version_out = version; scoped_ptr<installer::Version> service_version; service_version.reset( installer::Version::GetVersionFromString(ASCIIToUTF16(version))); // If the version string is invalid, treat it like an older version. if (!service_version.get()) return SERVICE_OLDER_VERSION_RUNNING; // Get the version of the currently *running* instance of Chrome. chrome::VersionInfo version_info; if (!version_info.is_valid()) { NOTREACHED() << "Failed to get current file version"; // Our own version is invalid. This is an error case. Pretend that we // are out of date. return SERVICE_NEWER_VERSION_RUNNING; } scoped_ptr<installer::Version> running_version( installer::Version::GetVersionFromString( ASCIIToUTF16(version_info.Version()))); if (!running_version.get()) { NOTREACHED() << "Failed to parse version info"; // Our own version is invalid. This is an error case. Pretend that we // are out of date. return SERVICE_NEWER_VERSION_RUNNING; } if (running_version->IsHigherThan(service_version.get())) { return SERVICE_OLDER_VERSION_RUNNING; } else if (service_version->IsHigherThan(running_version.get())) { return SERVICE_NEWER_VERSION_RUNNING; } return SERVICE_SAME_VERSION_RUNNING; } #if defined(OS_WIN) string16 GetServiceProcessReadyEventName() { return UTF8ToWide( GetServiceProcessScopedVersionedName("_service_ready")); } string16 GetServiceProcessShutdownEventName() { return UTF8ToWide( GetServiceProcessScopedVersionedName("_service_shutdown_evt")); } class ServiceProcessShutdownMonitor : public base::ObjectWatcher::Delegate { public: explicit ServiceProcessShutdownMonitor(Task* shutdown_task) : shutdown_task_(shutdown_task) { } void Start() { string16 event_name = GetServiceProcessShutdownEventName(); CHECK(event_name.length() <= MAX_PATH); shutdown_event_.Set(CreateEvent(NULL, TRUE, FALSE, event_name.c_str())); watcher_.StartWatching(shutdown_event_.Get(), this); } // base::ObjectWatcher::Delegate implementation. virtual void OnObjectSignaled(HANDLE object) { shutdown_task_->Run(); shutdown_task_.reset(); } private: ScopedHandle shutdown_event_; base::ObjectWatcher watcher_; scoped_ptr<Task> shutdown_task_; }; #else // defined(OS_WIN) // Gets the name of the lock file for service process. Used on non-Windows OSes. FilePath GetServiceProcessLockFilePath() { FilePath user_data_dir; PathService::Get(chrome::DIR_USER_DATA, &user_data_dir); chrome::VersionInfo version_info; std::string lock_file_name = version_info.Version() + "Service Process Lock"; return user_data_dir.Append(lock_file_name); } #endif // defined(OS_WIN) struct ServiceProcessGlobalState { scoped_ptr<base::SharedMemory> shared_mem_service_data; #if defined(OS_WIN) // An event that is signaled when a service process is ready. ScopedHandle ready_event; scoped_ptr<ServiceProcessShutdownMonitor> shutdown_monitor; #endif // defined(OS_WIN) }; // TODO(sanjeevr): Remove this ugly global pointer and move all methods and // data members used by the service process into one singleton class which // could be owned by the service process. ServiceProcessGlobalState* g_service_globals = NULL; } // namespace // Gets the name of the service process IPC channel. std::string GetServiceProcessChannelName() { return GetServiceProcessScopedVersionedName("_service_ipc"); } std::string GetServiceProcessAutoRunKey() { return GetServiceProcessScopedName("_service_run"); } bool TakeServiceProcessSingletonLock() { DCHECK(g_service_globals == NULL); std::string running_version; ServiceProcessRunningState state = GetServiceProcessRunningState(&running_version); switch (state) { case SERVICE_SAME_VERSION_RUNNING: case SERVICE_NEWER_VERSION_RUNNING: return false; case SERVICE_OLDER_VERSION_RUNNING: // If an older version is running, kill it. ForceServiceProcessShutdown(running_version); break; case SERVICE_NOT_RUNNING: break; } g_service_globals = new ServiceProcessGlobalState; // TODO(sanjeevr): We can probably use the shared mem as the sole singleton // mechanism. For that the shared mem class needs to return whether it created // new instance or opened an existing one. #if defined(OS_WIN) string16 event_name = GetServiceProcessReadyEventName(); CHECK(event_name.length() <= MAX_PATH); ScopedHandle service_process_ready_event; service_process_ready_event.Set( CreateEvent(NULL, TRUE, FALSE, event_name.c_str())); DWORD error = GetLastError(); if ((error == ERROR_ALREADY_EXISTS) || (error == ERROR_ACCESS_DENIED)) { delete g_service_globals; g_service_globals = NULL; return false; } DCHECK(service_process_ready_event.IsValid()); g_service_globals->ready_event.Set(service_process_ready_event.Take()); #else // TODO(sanjeevr): Implement singleton mechanism for other platforms. NOTIMPLEMENTED(); #endif // Now that we have the singleton, let is also write the version we are using // to shared memory. This can be used by a newer service to signal us to exit. chrome::VersionInfo version_info; if (!version_info.is_valid()) { NOTREACHED() << "Failed to get current file version"; return false; } if (version_info.Version().length() >= kMaxVersionStringLength) { NOTREACHED() << "Version string length is << " << version_info.Version().length() << "which is longer than" << kMaxVersionStringLength; return false; } scoped_ptr<base::SharedMemory> shared_mem_service_data; shared_mem_service_data.reset(new base::SharedMemory()); if (!shared_mem_service_data.get()) return false; uint32 alloc_size = sizeof(ServiceProcessSharedData); if (!shared_mem_service_data->Create(GetServiceProcessSharedMemName(), false, true, alloc_size)) return false; if (!shared_mem_service_data->Map(alloc_size)) return false; memset(shared_mem_service_data->memory(), 0, alloc_size); ServiceProcessSharedData* shared_data = reinterpret_cast<ServiceProcessSharedData*>( shared_mem_service_data->memory()); memcpy(shared_data->service_process_version, version_info.Version().c_str(), version_info.Version().length()); shared_data->service_process_pid = base::GetCurrentProcId(); g_service_globals->shared_mem_service_data.reset( shared_mem_service_data.release()); return true; } void SignalServiceProcessReady(Task* shutdown_task) { #if defined(OS_WIN) DCHECK(g_service_globals != NULL); DCHECK(g_service_globals->ready_event.IsValid()); SetEvent(g_service_globals->ready_event.Get()); g_service_globals->shutdown_monitor.reset( new ServiceProcessShutdownMonitor(shutdown_task)); g_service_globals->shutdown_monitor->Start(); #else // TODO(hclam): Implement better mechanism for these platform. // Also we need to save shutdown task. For now we just delete the shutdown // task because we have not way to listen for shutdown requests. delete shutdown_task; const FilePath path = GetServiceProcessLockFilePath(); FILE* file = file_util::OpenFile(path, "wb+"); if (!file) return; LOG(INFO) << "Created Service Process lock file: " << path.value(); file_util::TruncateFile(file) && file_util::CloseFile(file); #endif } void SignalServiceProcessStopped() { delete g_service_globals; g_service_globals = NULL; #if !defined(OS_WIN) // TODO(hclam): Implement better mechanism for these platform. const FilePath path = GetServiceProcessLockFilePath(); file_util::Delete(path, false); #endif } bool ForceServiceProcessShutdown(const std::string& version) { #if defined(OS_WIN) ScopedHandle shutdown_event; std::string versioned_name = version; versioned_name.append("_service_shutdown_evt"); string16 event_name = UTF8ToWide(GetServiceProcessScopedName(versioned_name)); shutdown_event.Set(OpenEvent(EVENT_MODIFY_STATE, FALSE, event_name.c_str())); if (!shutdown_event.IsValid()) return false; SetEvent(shutdown_event.Get()); return true; #else // defined(OS_WIN) NOTIMPLEMENTED(); return false; #endif // defined(OS_WIN) } bool CheckServiceProcessReady() { #if defined(OS_WIN) string16 event_name = GetServiceProcessReadyEventName(); ScopedHandle event( OpenEvent(SYNCHRONIZE | READ_CONTROL, false, event_name.c_str())); if (!event.IsValid()) return false; // Check if the event is signaled. return WaitForSingleObject(event, 0) == WAIT_OBJECT_0; #else // TODO(hclam): Implement better mechanism for these platform. const FilePath path = GetServiceProcessLockFilePath(); return file_util::PathExists(path); #endif } base::ProcessId GetServiceProcessPid() { base::ProcessId pid = 0; GetServiceProcessSharedData(NULL, &pid); return pid; } <commit_msg>Fix service for CUPS CP proxy.<commit_after>// Copyright (c) 2010 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 "base/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/shared_memory.h" #include "base/string16.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/service_process_util.h" #include "chrome/installer/util/version.h" #if defined(OS_WIN) #include "base/object_watcher.h" #include "base/scoped_handle_win.h" #endif // TODO(hclam): Split this file for different platforms. namespace { // This should be more than enough to hold a version string assuming each part // of the version string is an int64. const uint32 kMaxVersionStringLength = 256; // The structure that gets written to shared memory. struct ServiceProcessSharedData { char service_process_version[kMaxVersionStringLength]; base::ProcessId service_process_pid; }; // Return a name that is scoped to this instance of the service process. We // use the user-data-dir as a scoping prefix. std::string GetServiceProcessScopedName(const std::string& append_str) { FilePath user_data_dir; PathService::Get(chrome::DIR_USER_DATA, &user_data_dir); #if defined(OS_WIN) std::string scoped_name = WideToUTF8(user_data_dir.value()); #elif defined(OS_POSIX) std::string scoped_name = user_data_dir.value(); #endif // defined(OS_WIN) std::replace(scoped_name.begin(), scoped_name.end(), '\\', '!'); std::replace(scoped_name.begin(), scoped_name.end(), '/', '!'); scoped_name.append(append_str); return scoped_name; } // Return a name that is scoped to this instance of the service process. We // use the user-data-dir and the version as a scoping prefix. std::string GetServiceProcessScopedVersionedName( const std::string& append_str) { std::string versioned_str; chrome::VersionInfo version_info; DCHECK(version_info.is_valid()); versioned_str.append(version_info.Version()); versioned_str.append(append_str); return GetServiceProcessScopedName(versioned_str); } // Gets the name of the shared memory used by the service process to write its // version. The name is not versioned. std::string GetServiceProcessSharedMemName() { return GetServiceProcessScopedName("_service_shmem"); } // Reads the named shared memory to get the shared data. Returns false if no // matching shared memory was found. bool GetServiceProcessSharedData(std::string* version, base::ProcessId* pid) { scoped_ptr<base::SharedMemory> shared_mem_service_data; shared_mem_service_data.reset(new base::SharedMemory()); ServiceProcessSharedData* service_data = NULL; if (shared_mem_service_data.get() && shared_mem_service_data->Open(GetServiceProcessSharedMemName(), true) && shared_mem_service_data->Map(sizeof(ServiceProcessSharedData))) { service_data = reinterpret_cast<ServiceProcessSharedData*>( shared_mem_service_data->memory()); // Make sure the version in shared memory is null-terminated. If it is not, // treat it as invalid. if (version && memchr(service_data->service_process_version, '\0', sizeof(service_data->service_process_version))) *version = service_data->service_process_version; if (pid) *pid = service_data->service_process_pid; return true; } return false; } enum ServiceProcessRunningState { SERVICE_NOT_RUNNING, SERVICE_OLDER_VERSION_RUNNING, SERVICE_SAME_VERSION_RUNNING, SERVICE_NEWER_VERSION_RUNNING, }; ServiceProcessRunningState GetServiceProcessRunningState( std::string* service_version_out) { std::string version; GetServiceProcessSharedData(&version, NULL); if (version.empty()) return SERVICE_NOT_RUNNING; // At this time we have a version string. Set the out param if it exists. if (service_version_out) *service_version_out = version; scoped_ptr<installer::Version> service_version; service_version.reset( installer::Version::GetVersionFromString(ASCIIToUTF16(version))); // If the version string is invalid, treat it like an older version. if (!service_version.get()) return SERVICE_OLDER_VERSION_RUNNING; // Get the version of the currently *running* instance of Chrome. chrome::VersionInfo version_info; if (!version_info.is_valid()) { NOTREACHED() << "Failed to get current file version"; // Our own version is invalid. This is an error case. Pretend that we // are out of date. return SERVICE_NEWER_VERSION_RUNNING; } scoped_ptr<installer::Version> running_version( installer::Version::GetVersionFromString( ASCIIToUTF16(version_info.Version()))); if (!running_version.get()) { NOTREACHED() << "Failed to parse version info"; // Our own version is invalid. This is an error case. Pretend that we // are out of date. return SERVICE_NEWER_VERSION_RUNNING; } if (running_version->IsHigherThan(service_version.get())) { return SERVICE_OLDER_VERSION_RUNNING; } else if (service_version->IsHigherThan(running_version.get())) { return SERVICE_NEWER_VERSION_RUNNING; } return SERVICE_SAME_VERSION_RUNNING; } #if defined(OS_WIN) string16 GetServiceProcessReadyEventName() { return UTF8ToWide( GetServiceProcessScopedVersionedName("_service_ready")); } string16 GetServiceProcessShutdownEventName() { return UTF8ToWide( GetServiceProcessScopedVersionedName("_service_shutdown_evt")); } class ServiceProcessShutdownMonitor : public base::ObjectWatcher::Delegate { public: explicit ServiceProcessShutdownMonitor(Task* shutdown_task) : shutdown_task_(shutdown_task) { } void Start() { string16 event_name = GetServiceProcessShutdownEventName(); CHECK(event_name.length() <= MAX_PATH); shutdown_event_.Set(CreateEvent(NULL, TRUE, FALSE, event_name.c_str())); watcher_.StartWatching(shutdown_event_.Get(), this); } // base::ObjectWatcher::Delegate implementation. virtual void OnObjectSignaled(HANDLE object) { shutdown_task_->Run(); shutdown_task_.reset(); } private: ScopedHandle shutdown_event_; base::ObjectWatcher watcher_; scoped_ptr<Task> shutdown_task_; }; #else // defined(OS_WIN) // Gets the name of the lock file for service process. Used on non-Windows OSes. FilePath GetServiceProcessLockFilePath() { FilePath user_data_dir; PathService::Get(chrome::DIR_USER_DATA, &user_data_dir); chrome::VersionInfo version_info; std::string lock_file_name = version_info.Version() + "Service Process Lock"; return user_data_dir.Append(lock_file_name); } #endif // defined(OS_WIN) struct ServiceProcessGlobalState { scoped_ptr<base::SharedMemory> shared_mem_service_data; #if defined(OS_WIN) // An event that is signaled when a service process is ready. ScopedHandle ready_event; scoped_ptr<ServiceProcessShutdownMonitor> shutdown_monitor; #endif // defined(OS_WIN) }; // TODO(sanjeevr): Remove this ugly global pointer and move all methods and // data members used by the service process into one singleton class which // could be owned by the service process. ServiceProcessGlobalState* g_service_globals = NULL; } // namespace // Gets the name of the service process IPC channel. std::string GetServiceProcessChannelName() { return GetServiceProcessScopedVersionedName("_service_ipc"); } std::string GetServiceProcessAutoRunKey() { return GetServiceProcessScopedName("_service_run"); } bool TakeServiceProcessSingletonLock() { DCHECK(g_service_globals == NULL); // On Linux shared menory is implemented using file. In case of incorrect // shutdown or process kill memshared file stay on the disk and prevents // next instance of service from starting. So, on Linux we have to disable // check for another running instance of the service. #if defined(OS_WIN) std::string running_version; ServiceProcessRunningState state = GetServiceProcessRunningState(&running_version); switch (state) { case SERVICE_SAME_VERSION_RUNNING: case SERVICE_NEWER_VERSION_RUNNING: return false; case SERVICE_OLDER_VERSION_RUNNING: // If an older version is running, kill it. ForceServiceProcessShutdown(running_version); break; case SERVICE_NOT_RUNNING: break; } #endif g_service_globals = new ServiceProcessGlobalState; // TODO(sanjeevr): We can probably use the shared mem as the sole singleton // mechanism. For that the shared mem class needs to return whether it created // new instance or opened an existing one. #if defined(OS_WIN) string16 event_name = GetServiceProcessReadyEventName(); CHECK(event_name.length() <= MAX_PATH); ScopedHandle service_process_ready_event; service_process_ready_event.Set( CreateEvent(NULL, TRUE, FALSE, event_name.c_str())); DWORD error = GetLastError(); if ((error == ERROR_ALREADY_EXISTS) || (error == ERROR_ACCESS_DENIED)) { delete g_service_globals; g_service_globals = NULL; return false; } DCHECK(service_process_ready_event.IsValid()); g_service_globals->ready_event.Set(service_process_ready_event.Take()); #else // TODO(sanjeevr): Implement singleton mechanism for other platforms. NOTIMPLEMENTED(); #endif // Now that we have the singleton, let is also write the version we are using // to shared memory. This can be used by a newer service to signal us to exit. chrome::VersionInfo version_info; if (!version_info.is_valid()) { NOTREACHED() << "Failed to get current file version"; return false; } if (version_info.Version().length() >= kMaxVersionStringLength) { NOTREACHED() << "Version string length is << " << version_info.Version().length() << "which is longer than" << kMaxVersionStringLength; return false; } scoped_ptr<base::SharedMemory> shared_mem_service_data; shared_mem_service_data.reset(new base::SharedMemory()); if (!shared_mem_service_data.get()) return false; uint32 alloc_size = sizeof(ServiceProcessSharedData); if (!shared_mem_service_data->Create(GetServiceProcessSharedMemName(), false, true, alloc_size)) return false; if (!shared_mem_service_data->Map(alloc_size)) return false; memset(shared_mem_service_data->memory(), 0, alloc_size); ServiceProcessSharedData* shared_data = reinterpret_cast<ServiceProcessSharedData*>( shared_mem_service_data->memory()); memcpy(shared_data->service_process_version, version_info.Version().c_str(), version_info.Version().length()); shared_data->service_process_pid = base::GetCurrentProcId(); g_service_globals->shared_mem_service_data.reset( shared_mem_service_data.release()); return true; } void SignalServiceProcessReady(Task* shutdown_task) { #if defined(OS_WIN) DCHECK(g_service_globals != NULL); DCHECK(g_service_globals->ready_event.IsValid()); SetEvent(g_service_globals->ready_event.Get()); g_service_globals->shutdown_monitor.reset( new ServiceProcessShutdownMonitor(shutdown_task)); g_service_globals->shutdown_monitor->Start(); #else // TODO(hclam): Implement better mechanism for these platform. // Also we need to save shutdown task. For now we just delete the shutdown // task because we have not way to listen for shutdown requests. delete shutdown_task; const FilePath path = GetServiceProcessLockFilePath(); FILE* file = file_util::OpenFile(path, "wb+"); if (!file) return; LOG(INFO) << "Created Service Process lock file: " << path.value(); file_util::TruncateFile(file) && file_util::CloseFile(file); #endif } void SignalServiceProcessStopped() { delete g_service_globals; g_service_globals = NULL; #if !defined(OS_WIN) // TODO(hclam): Implement better mechanism for these platform. const FilePath path = GetServiceProcessLockFilePath(); file_util::Delete(path, false); #endif } bool ForceServiceProcessShutdown(const std::string& version) { #if defined(OS_WIN) ScopedHandle shutdown_event; std::string versioned_name = version; versioned_name.append("_service_shutdown_evt"); string16 event_name = UTF8ToWide(GetServiceProcessScopedName(versioned_name)); shutdown_event.Set(OpenEvent(EVENT_MODIFY_STATE, FALSE, event_name.c_str())); if (!shutdown_event.IsValid()) return false; SetEvent(shutdown_event.Get()); return true; #else // defined(OS_WIN) NOTIMPLEMENTED(); return false; #endif // defined(OS_WIN) } bool CheckServiceProcessReady() { #if defined(OS_WIN) string16 event_name = GetServiceProcessReadyEventName(); ScopedHandle event( OpenEvent(SYNCHRONIZE | READ_CONTROL, false, event_name.c_str())); if (!event.IsValid()) return false; // Check if the event is signaled. return WaitForSingleObject(event, 0) == WAIT_OBJECT_0; #else // TODO(hclam): Implement better mechanism for these platform. const FilePath path = GetServiceProcessLockFilePath(); return file_util::PathExists(path); #endif } base::ProcessId GetServiceProcessPid() { base::ProcessId pid = 0; GetServiceProcessSharedData(NULL, &pid); return pid; } <|endoftext|>
<commit_before>#include "coldstakingpage.h" #include "bitcoinunits.h" #include "coldstakinglistfilterproxy.h" #include "coldstakinglistitemdelegate.h" #include "coldstakingmodel.h" #include "guiconstants.h" #include "guiutil.h" #include "main.h" #include "newstakedelegationdialog.h" #include "optionsmodel.h" #include "qt/coldstakingmodel.h" #include "transactiontablemodel.h" #include "wallet.h" #include "walletmodel.h" #include <QAction> #include <QClipboard> #include <QDesktopServices> #include <QKeyEvent> #include <QMenu> #include <QUrl> #include "txdb.h" #define LOAD_MIN_TIME_INTERVAL 15 const QString ColdStakingPage::copyOwnerAddressText = "Copy owner address"; const QString ColdStakingPage::copyStakerAddressText = "Copy staker address"; const QString ColdStakingPage::copyAmountText = "Copy amount"; const QString ColdStakingPage::enableStakingText = "Enable staking for this address"; const QString ColdStakingPage::disableStakingText = "Disable staking for this address"; const QString ColdStakingPage::cantStakeText = "Cannot stake an address you delegated"; ColdStakingPage::ColdStakingPage(QWidget* parent) : QWidget(parent), ui(new Ui_ColdStaking), model(new ColdStakingModel), itemDelegate(new ColdStakingListItemDelegate) { ui->setupUi(this); ui->listColdStakingView->setItemDelegate(itemDelegate); ui->listColdStakingView->setIconSize(QSize(ColdStakingListItemDelegate::DECORATION_SIZE, ColdStakingListItemDelegate::DECORATION_SIZE)); ui->listColdStakingView->setMinimumHeight(ColdStakingListItemDelegate::NUM_ITEMS * (ColdStakingListItemDelegate::DECORATION_SIZE + 2)); ui->listColdStakingView->setAttribute(Qt::WA_MacShowFocusRect, false); connect(ui->listColdStakingView, &ColdStakingListView::clicked, this, &ColdStakingPage::handleElementClicked); setupContextMenu(); filter = new ColdStakingListFilterProxy(ui->filter_lineEdit, this); filter->setDynamicSortFilter(true); setModel(model); refreshData(); newStakeDelegationDialog = new NewStakeDelegationDialog(this); // connect(ui->delegateStakeButton, &QPushButton::clicked, newStakeDelegationDialog, // &NewStakeDelegationDialog::open); connect(ui->delegateStakeButton, &QPushButton::clicked, this, &ColdStakingPage::slot_messageColdStakeNotReady); connect(ui->filter_lineEdit, &QLineEdit::textChanged, filter, &ColdStakingListFilterProxy::setFilterWildcard); } void ColdStakingPage::handleElementClicked(const QModelIndex& index) { if (filter) emit tokenClicked(filter->mapToSource(index)); } void ColdStakingPage::keyPressEvent(QKeyEvent* event) { if (event->key() == Qt::Key_F && (event->modifiers() & Qt::ControlModifier)) { ui->filter_lineEdit->setFocus(); } } void ColdStakingPage::setupContextMenu() { ui->listColdStakingView->setContextMenuPolicy(Qt::CustomContextMenu); contextMenu = new QMenu(this); copyOwnerAddrAction = new QAction(copyOwnerAddressText, this); copyStakerAddrAction = new QAction(copyStakerAddressText, this); copyAmountAction = new QAction(copyAmountText, this); toggleStakingAction = new QAction(enableStakingText, this); contextMenu->addAction(copyOwnerAddrAction); contextMenu->addAction(copyStakerAddrAction); contextMenu->addAction(copyAmountAction); contextMenu->addSeparator(); contextMenu->addAction(toggleStakingAction); connect(ui->listColdStakingView, &ColdStakingListView::customContextMenuRequested, this, &ColdStakingPage::slot_contextMenuRequested); connect(copyOwnerAddrAction, &QAction::triggered, this, &ColdStakingPage::slot_copyOwnerAddr); connect(copyStakerAddrAction, &QAction::triggered, this, &ColdStakingPage::slot_copyStakerAddr); connect(copyAmountAction, &QAction::triggered, this, &ColdStakingPage::slot_copyAmount); } void ColdStakingPage::slot_copyOwnerAddr() { copyField(ColdStakingModel::ColumnIndex::OWNER_ADDRESS, "owner address"); } void ColdStakingPage::slot_copyStakerAddr() { copyField(ColdStakingModel::ColumnIndex::STAKING_ADDRESS, "staker address"); } void ColdStakingPage::slot_copyAmount() { copyField(ColdStakingModel::ColumnIndex::TOTAL_STACKEABLE_AMOUNT_STR, "amount"); } void ColdStakingPage::slot_enableStaking(const QModelIndex& idx) { model->whitelist(idx); } void ColdStakingPage::slot_disableStaking(const QModelIndex& idx) { model->blacklist(idx); } void ColdStakingPage::slot_messageColdStakeNotReady() { QMessageBox::information(this, "No cold-staking yet", "Cold-staking is still not enabled in neblio"); } ColdStakingPage::~ColdStakingPage() { notifyWalletConnection.disconnect(); delete ui; } ColdStakingModel* ColdStakingPage::getTokenListModel() const { return model; } void ColdStakingPage::setModel(ColdStakingModel* model) { if (model) { filter->setSourceModel(model); ui->listColdStakingView->setModel(filter); } } void ColdStakingPage::setWalletModel(WalletModel* wModel) { model->setWalletModel(wModel); connect(model->getTransactionTableModel(), &TransactionTableModel::txArrived, this, &ColdStakingPage::onTxArrived); newStakeDelegationDialog->setWalletModel(model->getWalletModel()); notifyWalletConnection = model->getWalletModel()->getWallet()->NotifyAddressBookChanged.connect( [this](CWallet* /*wallet*/, const CTxDestination& /*address*/, const std::string& /*label*/, bool /*isMine*/, const std::string& /*purpose*/, ChangeType /*status*/) { refreshData(); }); } void ColdStakingPage::slot_contextMenuRequested(QPoint pos) { QModelIndexList selected = ui->listColdStakingView->selectedIndexesP(); if (selected.size() == 1) { contextMenu->popup(ui->listColdStakingView->viewport()->mapToGlobal(pos)); configureToggleStakingAction(selected.front()); } } void ColdStakingPage::onTxArrived(const QString& /*hash*/) { tryRefreshData(); } void ColdStakingPage::tryRefreshData() { // Check for min update time to not reload the UI so often if the node is syncing. int64_t now = GetTime(); if (lastRefreshTime + LOAD_MIN_TIME_INTERVAL < now) { lastRefreshTime = now; refreshData(); } } void ColdStakingPage::refreshData() { model->updateCSList(); } void ColdStakingPage::copyField(ColdStakingModel::ColumnIndex column, const QString& columnName) { const QModelIndexList selected = ui->listColdStakingView->selectedIndexesP(); std::set<int> rows; for (long i = 0; i < selected.size(); i++) { QModelIndex index = selected.at(i); int row = index.row(); rows.insert(row); } if (rows.size() != 1) { QMessageBox::warning(this, "Failed to copy", "Failed to copy " + columnName + "; selected items size is not equal to one"); return; } const QModelIndex idx = ui->listColdStakingView->model()->index(*rows.begin(), 0); QString resultStr = ui->listColdStakingView->model()->data(idx, column).toString(); if (!resultStr.isEmpty()) { QClipboard* clipboard = QGuiApplication::clipboard(); clipboard->setText(resultStr); } else { QMessageBox::warning(this, "Failed to copy", "No information to include in the clipboard"); } } void ColdStakingPage::configureToggleStakingAction(const QModelIndex& idx) { bool isWhitelisted = ui->listColdStakingView->model() ->data(idx, ColdStakingModel::ColumnIndex::IS_WHITELISTED) .toBool(); bool isStaker = ui->listColdStakingView->model() ->data(idx, ColdStakingModel::ColumnIndex::IS_RECEIVED_DELEGATION) .toBool(); // disconnect everything and reconnect it below toggleStakingAction->disconnect(); if (!isStaker) { if (isWhitelisted) { toggleStakingAction->setText(disableStakingText); connect(toggleStakingAction, &QAction::triggered, this, [=]() { slot_disableStaking(idx); }); } else { toggleStakingAction->setText(enableStakingText); connect(toggleStakingAction, &QAction::triggered, this, [=]() { slot_enableStaking(idx); }); } toggleStakingAction->setEnabled(true); } else { toggleStakingAction->setText(cantStakeText); toggleStakingAction->setEnabled(false); } } <commit_msg>Update coldstakingpage.cpp<commit_after>#include "coldstakingpage.h" #include "bitcoinunits.h" #include "coldstakinglistfilterproxy.h" #include "coldstakinglistitemdelegate.h" #include "coldstakingmodel.h" #include "guiconstants.h" #include "guiutil.h" #include "main.h" #include "newstakedelegationdialog.h" #include "optionsmodel.h" #include "qt/coldstakingmodel.h" #include "transactiontablemodel.h" #include "wallet.h" #include "walletmodel.h" #include <QAction> #include <QClipboard> #include <QDesktopServices> #include <QKeyEvent> #include <QMenu> #include <QUrl> #include "txdb.h" #define LOAD_MIN_TIME_INTERVAL 15 const QString ColdStakingPage::copyOwnerAddressText = "Copy owner address"; const QString ColdStakingPage::copyStakerAddressText = "Copy staker address"; const QString ColdStakingPage::copyAmountText = "Copy amount"; const QString ColdStakingPage::enableStakingText = "Enable staking for this address"; const QString ColdStakingPage::disableStakingText = "Disable staking for this address"; const QString ColdStakingPage::cantStakeText = "Cannot stake an address you delegated"; ColdStakingPage::ColdStakingPage(QWidget* parent) : QWidget(parent), ui(new Ui_ColdStaking), model(new ColdStakingModel), itemDelegate(new ColdStakingListItemDelegate) { ui->setupUi(this); ui->listColdStakingView->setItemDelegate(itemDelegate); ui->listColdStakingView->setIconSize(QSize(ColdStakingListItemDelegate::DECORATION_SIZE, ColdStakingListItemDelegate::DECORATION_SIZE)); ui->listColdStakingView->setMinimumHeight(ColdStakingListItemDelegate::NUM_ITEMS * (ColdStakingListItemDelegate::DECORATION_SIZE + 2)); ui->listColdStakingView->setAttribute(Qt::WA_MacShowFocusRect, false); connect(ui->listColdStakingView, &ColdStakingListView::clicked, this, &ColdStakingPage::handleElementClicked); setupContextMenu(); filter = new ColdStakingListFilterProxy(ui->filter_lineEdit, this); filter->setDynamicSortFilter(true); setModel(model); refreshData(); newStakeDelegationDialog = new NewStakeDelegationDialog(this); // connect(ui->delegateStakeButton, &QPushButton::clicked, newStakeDelegationDialog, // &NewStakeDelegationDialog::open); connect(ui->delegateStakeButton, &QPushButton::clicked, this, &ColdStakingPage::slot_messageColdStakeNotReady); connect(ui->filter_lineEdit, &QLineEdit::textChanged, filter, &ColdStakingListFilterProxy::setFilterWildcard); } void ColdStakingPage::handleElementClicked(const QModelIndex& index) { if (filter) emit tokenClicked(filter->mapToSource(index)); } void ColdStakingPage::keyPressEvent(QKeyEvent* event) { if (event->key() == Qt::Key_F && (event->modifiers() & Qt::ControlModifier)) { ui->filter_lineEdit->setFocus(); } } void ColdStakingPage::setupContextMenu() { ui->listColdStakingView->setContextMenuPolicy(Qt::CustomContextMenu); contextMenu = new QMenu(this); copyOwnerAddrAction = new QAction(copyOwnerAddressText, this); copyStakerAddrAction = new QAction(copyStakerAddressText, this); copyAmountAction = new QAction(copyAmountText, this); toggleStakingAction = new QAction(enableStakingText, this); contextMenu->addAction(copyOwnerAddrAction); contextMenu->addAction(copyStakerAddrAction); contextMenu->addAction(copyAmountAction); contextMenu->addSeparator(); contextMenu->addAction(toggleStakingAction); connect(ui->listColdStakingView, &ColdStakingListView::customContextMenuRequested, this, &ColdStakingPage::slot_contextMenuRequested); connect(copyOwnerAddrAction, &QAction::triggered, this, &ColdStakingPage::slot_copyOwnerAddr); connect(copyStakerAddrAction, &QAction::triggered, this, &ColdStakingPage::slot_copyStakerAddr); connect(copyAmountAction, &QAction::triggered, this, &ColdStakingPage::slot_copyAmount); } void ColdStakingPage::slot_copyOwnerAddr() { copyField(ColdStakingModel::ColumnIndex::OWNER_ADDRESS, "owner address"); } void ColdStakingPage::slot_copyStakerAddr() { copyField(ColdStakingModel::ColumnIndex::STAKING_ADDRESS, "staker address"); } void ColdStakingPage::slot_copyAmount() { copyField(ColdStakingModel::ColumnIndex::TOTAL_STACKEABLE_AMOUNT_STR, "amount"); } void ColdStakingPage::slot_enableStaking(const QModelIndex& idx) { model->whitelist(idx); } void ColdStakingPage::slot_disableStaking(const QModelIndex& idx) { model->blacklist(idx); } void ColdStakingPage::slot_messageColdStakeNotReady() { QMessageBox::information(this, "Cold Staking is Testnet-Only", "Neblio Cold Staking is not yet enabled on Mainnet."); } ColdStakingPage::~ColdStakingPage() { notifyWalletConnection.disconnect(); delete ui; } ColdStakingModel* ColdStakingPage::getTokenListModel() const { return model; } void ColdStakingPage::setModel(ColdStakingModel* model) { if (model) { filter->setSourceModel(model); ui->listColdStakingView->setModel(filter); } } void ColdStakingPage::setWalletModel(WalletModel* wModel) { model->setWalletModel(wModel); connect(model->getTransactionTableModel(), &TransactionTableModel::txArrived, this, &ColdStakingPage::onTxArrived); newStakeDelegationDialog->setWalletModel(model->getWalletModel()); notifyWalletConnection = model->getWalletModel()->getWallet()->NotifyAddressBookChanged.connect( [this](CWallet* /*wallet*/, const CTxDestination& /*address*/, const std::string& /*label*/, bool /*isMine*/, const std::string& /*purpose*/, ChangeType /*status*/) { refreshData(); }); } void ColdStakingPage::slot_contextMenuRequested(QPoint pos) { QModelIndexList selected = ui->listColdStakingView->selectedIndexesP(); if (selected.size() == 1) { contextMenu->popup(ui->listColdStakingView->viewport()->mapToGlobal(pos)); configureToggleStakingAction(selected.front()); } } void ColdStakingPage::onTxArrived(const QString& /*hash*/) { tryRefreshData(); } void ColdStakingPage::tryRefreshData() { // Check for min update time to not reload the UI so often if the node is syncing. int64_t now = GetTime(); if (lastRefreshTime + LOAD_MIN_TIME_INTERVAL < now) { lastRefreshTime = now; refreshData(); } } void ColdStakingPage::refreshData() { model->updateCSList(); } void ColdStakingPage::copyField(ColdStakingModel::ColumnIndex column, const QString& columnName) { const QModelIndexList selected = ui->listColdStakingView->selectedIndexesP(); std::set<int> rows; for (long i = 0; i < selected.size(); i++) { QModelIndex index = selected.at(i); int row = index.row(); rows.insert(row); } if (rows.size() != 1) { QMessageBox::warning(this, "Failed to copy", "Failed to copy " + columnName + "; selected items size is not equal to one"); return; } const QModelIndex idx = ui->listColdStakingView->model()->index(*rows.begin(), 0); QString resultStr = ui->listColdStakingView->model()->data(idx, column).toString(); if (!resultStr.isEmpty()) { QClipboard* clipboard = QGuiApplication::clipboard(); clipboard->setText(resultStr); } else { QMessageBox::warning(this, "Failed to copy", "No information to include in the clipboard"); } } void ColdStakingPage::configureToggleStakingAction(const QModelIndex& idx) { bool isWhitelisted = ui->listColdStakingView->model() ->data(idx, ColdStakingModel::ColumnIndex::IS_WHITELISTED) .toBool(); bool isStaker = ui->listColdStakingView->model() ->data(idx, ColdStakingModel::ColumnIndex::IS_RECEIVED_DELEGATION) .toBool(); // disconnect everything and reconnect it below toggleStakingAction->disconnect(); if (!isStaker) { if (isWhitelisted) { toggleStakingAction->setText(disableStakingText); connect(toggleStakingAction, &QAction::triggered, this, [=]() { slot_disableStaking(idx); }); } else { toggleStakingAction->setText(enableStakingText); connect(toggleStakingAction, &QAction::triggered, this, [=]() { slot_enableStaking(idx); }); } toggleStakingAction->setEnabled(true); } else { toggleStakingAction->setText(cantStakeText); toggleStakingAction->setEnabled(false); } } <|endoftext|>
<commit_before>/// \file ROOT/TDrawingOptsBase.hxx /// \ingroup Gpad ROOT7 /// \author Axel Naumann <axel@cern.ch> /// \date 2017-09-26 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_TDrawingOptsBase #define ROOT7_TDrawingOptsBase #include <ROOT/TColor.hxx> #include <ROOT/TDrawingAttrs.hxx> #include <ROOT/TStyle.hxx> #include <RStringView.h> #include <map> #include <string> #include <vector> namespace ROOT { namespace Experimental { class TCanvas; class TPadBase; /** \class ROOT::Experimental::TDrawingOptsBase Base class for drawing options. Implements access to the default and the default's initialization from a config file. Drawing options are made up of three kinds of primitives: - TColor - integer (long long) - floating point (double) They register the primitives with their `TCanvas`, and then refer to the registered primitives. Upon destruction, the `TDrawingOptsBase` deregisters the use of its primitives with the `TCanvas`, which empties the respective slots in the tables of the `TCanvas`, unless other options reference the same primitives (through `SameAs()`), and until the last use has deregistered. In derived classes (e.g. drawing options for the class `MyFancyBox`), declare attribute members as TDrawingAttrRef<TColor> fLineColor{*this, "MyFancyBoxLineColor"}; The attribute's value will be taken from the will be initialized */ class TDrawingOptsBaseNoDefault { public: template <class PRIMITIVE> class OptsAttrRefArr { /// Indexes of the `TCanvas`'s attribute table entries used by the options object. std::vector<TDrawingAttrRef<PRIMITIVE>> fRefArray; public: ~OptsAttrRefArr(); /// Register an attribute. ///\returns the index of the new attribute. TDrawingAttrRef<PRIMITIVE> Register(TCanvas &canv, const PRIMITIVE &val); /// Re-use an existing attribute. ///\returns the index of the attribute (i.e. valRef). TDrawingAttrRef<PRIMITIVE> SameAs(TCanvas &canv, TDrawingAttrRef<PRIMITIVE> idx); /// Re-use an existing attribute. ///\returns the index of the attribute, might be `IsInvalid()` if `val` could not be found. TDrawingAttrRef<PRIMITIVE> SameAs(TCanvas &canv, const PRIMITIVE &val); /// Update the attribute at index `idx` to the value `val`. void Update(TCanvas &canv, TDrawingAttrRef<PRIMITIVE> idx, const PRIMITIVE &val); /// Clear all attribute references, removing their uses in `TCanvas`. void Release(TCanvas &canv); /// Once copied, elements of a OptsAttrRefArr need to increase their use count. void RegisterCopy(TCanvas &canv); /// Access to attribute (const version). const PRIMITIVE &Get(TCanvas &canv, TDrawingAttrRef<PRIMITIVE> idx) const; /// Access to attribute (non-const version). PRIMITIVE &Get(TCanvas &canv, TDrawingAttrRef<PRIMITIVE> idx); }; private: /// The `TCanvas` holding the `TDrawable` (or its `TPad`). TCanvas *fCanvas = nullptr; /// Name of these drawing options, e.g. "1D"; will cause a member `TLineAttr{*this, "Line"}` to /// look for a style setting called "1D.Line.Color". std::string fName; /// Indexes of the `TCanvas`'s color table entries used by this options object. OptsAttrRefArr<TColor> fColorIdx; /// Indexes of the `TCanvas`'s integer table entries used by this options object. OptsAttrRefArr<long long> fIntIdx; /// Indexes of the `TCanvas`'s floating point table entries used by this options object. OptsAttrRefArr<double> fFPIdx; /// Access to the attribute tables (non-const version). OptsAttrRefArr<TColor> &GetAttrsRefArr(TColor *) { return fColorIdx; } OptsAttrRefArr<long long> &GetAttrsRefArr(long long *) { return fIntIdx; } OptsAttrRefArr<double> &GetAttrsRefArr(double *) { return fFPIdx; } /// Access to the attribute tables (const version). const OptsAttrRefArr<TColor> &GetAttrsRefArr(TColor *) const { return fColorIdx; } const OptsAttrRefArr<long long> &GetAttrsRefArr(long long *) const { return fIntIdx; } const OptsAttrRefArr<double> &GetAttrsRefArr(double *) const { return fFPIdx; } protected: /// Construct from the pad that holds our `TDrawable`. TDrawingOptsBaseNoDefault(TPadBase &pad, std::string_view name); /// Default attributes need to register their values in a pad - they will take this pad /// for default attributes of a style, as identified by the style's name. static TPadBase &GetDefaultCanvas(const TStyle &style); /// Whether the canvas is one of the canvases used to store attribute defaults. static bool IsDefaultCanvas(const TPadBase &canv); /// Get the (style config) name of this option set. const std::string &GetName() const { return fName; } /// The `TCanvas` holding the `TDrawable` (or its `TPad`) (non-const version). TCanvas &GetCanvas() { return *fCanvas; } /// The `TCanvas` holding the `TDrawable` (or its `TPad`) (const version). const TCanvas &GetCanvas() const { return *fCanvas; } template <class PRIMITIVE> TDrawingAttrRef<PRIMITIVE> Register(const PRIMITIVE &val) { return GetAttrsRefArr((PRIMITIVE *)nullptr).Register(GetCanvas(), val); } template <class PRIMITIVE> void Update(TDrawingAttrRef<PRIMITIVE> idx, const PRIMITIVE &val) { GetAttrsRefArr((PRIMITIVE *)nullptr).Update(GetCanvas(), idx, val); } template <class PRIMITIVE> TDrawingAttrRef<PRIMITIVE> SameAs(TDrawingAttrRef<PRIMITIVE> idx) { return GetAttrsRefArr((PRIMITIVE *)nullptr).SameAs(GetCanvas(), idx); } template <class PRIMITIVE> TDrawingAttrRef<PRIMITIVE> SameAs(const PRIMITIVE &val) { return GetAttrsRefArr((PRIMITIVE *)nullptr).SameAs(GetCanvas(), val); } template <class PRIMITIVE> friend class TDrawingAttrRef; public: TDrawingOptsBaseNoDefault() = default; ~TDrawingOptsBaseNoDefault(); TDrawingOptsBaseNoDefault(const TDrawingOptsBaseNoDefault &other); TDrawingOptsBaseNoDefault(TDrawingOptsBaseNoDefault &&other) = default; /// Access to the attribute (non-const version). template <class PRIMITIVE> PRIMITIVE &Get(TDrawingAttrRef<PRIMITIVE> ref) { return GetAttrsRefArr((PRIMITIVE*)nullptr).Get(GetCanvas(), ref); } /// Access to the attribute (const version). template <class PRIMITIVE> const PRIMITIVE &Get(TDrawingAttrRef<PRIMITIVE> ref) const { return GetAttrsRefArr((PRIMITIVE*)nullptr).Get(GetCanvas(), ref); } }; extern template class TDrawingOptsBaseNoDefault::OptsAttrRefArr<TColor>; extern template class TDrawingOptsBaseNoDefault::OptsAttrRefArr<long long>; extern template class TDrawingOptsBaseNoDefault::OptsAttrRefArr<double>; template <class DERIVED> class TDrawingOptsBase: public TDrawingOptsBaseNoDefault { public: TDrawingOptsBase() = default; /// Construct from the pad that holds our `TDrawable`. TDrawingOptsBase(TPadBase &pad, std::string_view name): TDrawingOptsBaseNoDefault(pad, name) { if (!IsDefaultCanvas(pad)) Default(); } /// Apply the given options to this option set. void Apply(const DERIVED& other) { static_cast<DERIVED&>(*this) = other; } /// Retrieve the default drawing options for the given style. static DERIVED GetDefaultForStyle(const TStyle& style) { return DERIVED(GetDefaultCanvas(style)); } /// Retrieve the default drawing options for `DERIVED`. Can be used to query and adjust the /// default options. static DERIVED &Default() { static DERIVED defaultOpts = GetDefaultForStyle(TStyle::GetCurrent()); return defaultOpts; } }; } // namespace Experimental } // namespace ROOT #endif <commit_msg>Fix doc.<commit_after>/// \file ROOT/TDrawingOptsBase.hxx /// \ingroup Gpad ROOT7 /// \author Axel Naumann <axel@cern.ch> /// \date 2017-09-26 /// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback /// is welcome! /************************************************************************* * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT7_TDrawingOptsBase #define ROOT7_TDrawingOptsBase #include <ROOT/TColor.hxx> #include <ROOT/TDrawingAttrs.hxx> #include <ROOT/TStyle.hxx> #include <RStringView.h> #include <map> #include <string> #include <vector> namespace ROOT { namespace Experimental { class TCanvas; class TPadBase; /** \class ROOT::Experimental::TDrawingOptsBase Base class for drawing options. Implements access to the default and the default's initialization from a config file. Drawing options are made up of three kinds of primitives: - TColor - integer (long long) - floating point (double) They register the primitives with their `TCanvas`, and then refer to the registered primitives. Upon destruction, the `TDrawingOptsBase` deregisters the use of its primitives with the `TCanvas`, which empties the respective slots in the tables of the `TCanvas`, unless other options reference the same primitives (through `SameAs()`), and until the last use has deregistered. In derived classes (e.g. drawing options for the class `MyFancyBox`), declare attribute members as TDrawingAttrRef<TColor> fLineColor{*this, "MyFancyBoxLineColor", kRed}; The attribute's initial value will be taken from the current style or, if that has no setting for the attribute, from the argument passed to the constructor (`kRed` in the example above). */ class TDrawingOptsBaseNoDefault { public: template <class PRIMITIVE> class OptsAttrRefArr { /// Indexes of the `TCanvas`'s attribute table entries used by the options object. std::vector<TDrawingAttrRef<PRIMITIVE>> fRefArray; public: ~OptsAttrRefArr(); /// Register an attribute. ///\returns the index of the new attribute. TDrawingAttrRef<PRIMITIVE> Register(TCanvas &canv, const PRIMITIVE &val); /// Re-use an existing attribute. ///\returns the index of the attribute (i.e. valRef). TDrawingAttrRef<PRIMITIVE> SameAs(TCanvas &canv, TDrawingAttrRef<PRIMITIVE> idx); /// Re-use an existing attribute. ///\returns the index of the attribute, might be `IsInvalid()` if `val` could not be found. TDrawingAttrRef<PRIMITIVE> SameAs(TCanvas &canv, const PRIMITIVE &val); /// Update the attribute at index `idx` to the value `val`. void Update(TCanvas &canv, TDrawingAttrRef<PRIMITIVE> idx, const PRIMITIVE &val); /// Clear all attribute references, removing their uses in `TCanvas`. void Release(TCanvas &canv); /// Once copied, elements of a OptsAttrRefArr need to increase their use count. void RegisterCopy(TCanvas &canv); /// Access to attribute (const version). const PRIMITIVE &Get(TCanvas &canv, TDrawingAttrRef<PRIMITIVE> idx) const; /// Access to attribute (non-const version). PRIMITIVE &Get(TCanvas &canv, TDrawingAttrRef<PRIMITIVE> idx); }; private: /// The `TCanvas` holding the `TDrawable` (or its `TPad`). TCanvas *fCanvas = nullptr; /// Name of these drawing options, e.g. "1D"; will cause a member `TLineAttr{*this, "Line"}` to /// look for a style setting called "1D.Line.Color". std::string fName; /// Indexes of the `TCanvas`'s color table entries used by this options object. OptsAttrRefArr<TColor> fColorIdx; /// Indexes of the `TCanvas`'s integer table entries used by this options object. OptsAttrRefArr<long long> fIntIdx; /// Indexes of the `TCanvas`'s floating point table entries used by this options object. OptsAttrRefArr<double> fFPIdx; /// Access to the attribute tables (non-const version). OptsAttrRefArr<TColor> &GetAttrsRefArr(TColor *) { return fColorIdx; } OptsAttrRefArr<long long> &GetAttrsRefArr(long long *) { return fIntIdx; } OptsAttrRefArr<double> &GetAttrsRefArr(double *) { return fFPIdx; } /// Access to the attribute tables (const version). const OptsAttrRefArr<TColor> &GetAttrsRefArr(TColor *) const { return fColorIdx; } const OptsAttrRefArr<long long> &GetAttrsRefArr(long long *) const { return fIntIdx; } const OptsAttrRefArr<double> &GetAttrsRefArr(double *) const { return fFPIdx; } protected: /// Construct from the pad that holds our `TDrawable`. TDrawingOptsBaseNoDefault(TPadBase &pad, std::string_view name); /// Default attributes need to register their values in a pad - they will take this pad /// for default attributes of a style, as identified by the style's name. static TPadBase &GetDefaultCanvas(const TStyle &style); /// Whether the canvas is one of the canvases used to store attribute defaults. static bool IsDefaultCanvas(const TPadBase &canv); /// Get the (style config) name of this option set. const std::string &GetName() const { return fName; } /// The `TCanvas` holding the `TDrawable` (or its `TPad`) (non-const version). TCanvas &GetCanvas() { return *fCanvas; } /// The `TCanvas` holding the `TDrawable` (or its `TPad`) (const version). const TCanvas &GetCanvas() const { return *fCanvas; } template <class PRIMITIVE> TDrawingAttrRef<PRIMITIVE> Register(const PRIMITIVE &val) { return GetAttrsRefArr((PRIMITIVE *)nullptr).Register(GetCanvas(), val); } template <class PRIMITIVE> void Update(TDrawingAttrRef<PRIMITIVE> idx, const PRIMITIVE &val) { GetAttrsRefArr((PRIMITIVE *)nullptr).Update(GetCanvas(), idx, val); } template <class PRIMITIVE> TDrawingAttrRef<PRIMITIVE> SameAs(TDrawingAttrRef<PRIMITIVE> idx) { return GetAttrsRefArr((PRIMITIVE *)nullptr).SameAs(GetCanvas(), idx); } template <class PRIMITIVE> TDrawingAttrRef<PRIMITIVE> SameAs(const PRIMITIVE &val) { return GetAttrsRefArr((PRIMITIVE *)nullptr).SameAs(GetCanvas(), val); } template <class PRIMITIVE> friend class TDrawingAttrRef; public: TDrawingOptsBaseNoDefault() = default; ~TDrawingOptsBaseNoDefault(); TDrawingOptsBaseNoDefault(const TDrawingOptsBaseNoDefault &other); TDrawingOptsBaseNoDefault(TDrawingOptsBaseNoDefault &&other) = default; /// Access to the attribute (non-const version). template <class PRIMITIVE> PRIMITIVE &Get(TDrawingAttrRef<PRIMITIVE> ref) { return GetAttrsRefArr((PRIMITIVE*)nullptr).Get(GetCanvas(), ref); } /// Access to the attribute (const version). template <class PRIMITIVE> const PRIMITIVE &Get(TDrawingAttrRef<PRIMITIVE> ref) const { return GetAttrsRefArr((PRIMITIVE*)nullptr).Get(GetCanvas(), ref); } }; extern template class TDrawingOptsBaseNoDefault::OptsAttrRefArr<TColor>; extern template class TDrawingOptsBaseNoDefault::OptsAttrRefArr<long long>; extern template class TDrawingOptsBaseNoDefault::OptsAttrRefArr<double>; template <class DERIVED> class TDrawingOptsBase: public TDrawingOptsBaseNoDefault { public: TDrawingOptsBase() = default; /// Construct from the pad that holds our `TDrawable`. TDrawingOptsBase(TPadBase &pad, std::string_view name): TDrawingOptsBaseNoDefault(pad, name) { if (!IsDefaultCanvas(pad)) Default(); } /// Apply the given options to this option set. void Apply(const DERIVED& other) { static_cast<DERIVED&>(*this) = other; } /// Retrieve the default drawing options for the given style. static DERIVED GetDefaultForStyle(const TStyle& style) { return DERIVED(GetDefaultCanvas(style)); } /// Retrieve the default drawing options for `DERIVED`. Can be used to query and adjust the /// default options. static DERIVED &Default() { static DERIVED defaultOpts = GetDefaultForStyle(TStyle::GetCurrent()); return defaultOpts; } }; } // namespace Experimental } // namespace ROOT #endif <|endoftext|>
<commit_before> // Copyright (c) 2012, 2013 Pierre MOULON. // 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/. #ifndef OPENMVG_FEATURES_FEATURE_HPP #define OPENMVG_FEATURES_FEATURE_HPP #include "openMVG/numeric/numeric.h" #include <iostream> #include <iterator> #include <fstream> #include <string> #include <vector> namespace openMVG { namespace features { /** * Base class for Point features. * Store position of the feature point. */ class PointFeature { friend std::ostream& operator<<(std::ostream& out, const PointFeature& obj); friend std::istream& operator>>(std::istream& in, PointFeature& obj); public: PointFeature(float x=0.0f, float y=0.0f) : _coords(x, y) {} float x() const { return _coords(0); } float y() const { return _coords(1); } const Vec2f & coords() const { return _coords;} float& x() { return _coords(0); } float& y() { return _coords(1); } Vec2f& coords() { return _coords;} template<class Archive> void serialize(Archive & ar) { ar (_coords(0), _coords(1)); } protected: Vec2f _coords; // (x, y). }; typedef std::vector<PointFeature> PointFeatures; //with overloaded operators: inline std::ostream& operator<<(std::ostream& out, const PointFeature& obj) { return out << obj._coords(0) << " " << obj._coords(1); } inline std::istream& operator>>(std::istream& in, PointFeature& obj) { return in >> obj._coords(0) >> obj._coords(1); } /** * Base class for ScaleInvariant Oriented Point features. * Add scale and orientation description to basis PointFeature. */ class SIOPointFeature : public PointFeature { friend std::ostream& operator<<(std::ostream& out, const SIOPointFeature& obj); friend std::istream& operator>>(std::istream& in, SIOPointFeature& obj); public: SIOPointFeature(float x=0.0f, float y=0.0f, float scale=0.0f, float orient=0.0f) : PointFeature(x,y) , _scale(scale) , _orientation(orient) {} float scale() const { return _scale; } float& scale() { return _scale; } float orientation() const { return _orientation; } float& orientation() { return _orientation; } bool operator ==(const SIOPointFeature& b) const { return (_scale == b.scale()) && (_orientation == b.orientation()) && (x() == b.x()) && (y() == b.y()) ; }; bool operator !=(const SIOPointFeature& b) const { return !((*this)==b); }; template<class Archive> void serialize(Archive & ar) { ar ( _coords(0), _coords(1), _scale, _orientation); } protected: float _scale; // In pixels. float _orientation; // In radians. }; // inline std::ostream& operator<<(std::ostream& out, const SIOPointFeature& obj) { const PointFeature *pf = static_cast<const PointFeature*>(&obj); return out << *pf << " " << obj._scale << " " << obj._orientation; } inline std::istream& operator>>(std::istream& in, SIOPointFeature& obj) { PointFeature *pf = static_cast<PointFeature*>(&obj); return in >> *pf >> obj._scale >> obj._orientation; } /// Read feats from file template<typename FeaturesT > static bool loadFeatsFromFile( const std::string & sfileNameFeats, FeaturesT & vec_feat) { vec_feat.clear(); std::ifstream fileIn(sfileNameFeats.c_str()); if (!fileIn.is_open()) return false; std::copy( std::istream_iterator<typename FeaturesT::value_type >(fileIn), std::istream_iterator<typename FeaturesT::value_type >(), std::back_inserter(vec_feat)); const bool bOk = !fileIn.bad(); fileIn.close(); return bOk; } /// Write feats to file template<typename FeaturesT > static bool saveFeatsToFile( const std::string & sfileNameFeats, FeaturesT & vec_feat) { std::ofstream file(sfileNameFeats.c_str()); if (!file.is_open()) return false; std::copy(vec_feat.begin(), vec_feat.end(), std::ostream_iterator<typename FeaturesT::value_type >(file,"\n")); bool bOk = file.good(); file.close(); return bOk; } /// Export point feature based vector to a matrix [(x,y)'T, (x,y)'T] template< typename FeaturesT, typename MatT > void PointsToMat( const FeaturesT & vec_feats, MatT & m) { m.resize(2, vec_feats.size()); typedef typename FeaturesT::value_type ValueT; // Container type size_t i = 0; for( typename FeaturesT::const_iterator iter = vec_feats.begin(); iter != vec_feats.end(); ++iter, ++i) { const ValueT & feat = *iter; m.col(i) << feat.x(), feat.y(); } } } // namespace features } // namespace openMVG #endif // OPENMVG_FEATURES_FEATURE_HPP <commit_msg>forgot a const. #454<commit_after> // Copyright (c) 2012, 2013 Pierre MOULON. // 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/. #ifndef OPENMVG_FEATURES_FEATURE_HPP #define OPENMVG_FEATURES_FEATURE_HPP #include "openMVG/numeric/numeric.h" #include <iostream> #include <iterator> #include <fstream> #include <string> #include <vector> namespace openMVG { namespace features { /** * Base class for Point features. * Store position of a feature point. */ class PointFeature { friend std::ostream& operator<<(std::ostream& out, const PointFeature& obj); friend std::istream& operator>>(std::istream& in, PointFeature& obj); public: PointFeature(float x=0.0f, float y=0.0f) : _coords(x, y) {} float x() const { return _coords(0); } float y() const { return _coords(1); } const Vec2f & coords() const { return _coords;} float& x() { return _coords(0); } float& y() { return _coords(1); } Vec2f& coords() { return _coords;} template<class Archive> void serialize(Archive & ar) { ar (_coords(0), _coords(1)); } protected: Vec2f _coords; // (x, y). }; typedef std::vector<PointFeature> PointFeatures; //with overloaded operators: inline std::ostream& operator<<(std::ostream& out, const PointFeature& obj) { return out << obj._coords(0) << " " << obj._coords(1); } inline std::istream& operator>>(std::istream& in, PointFeature& obj) { return in >> obj._coords(0) >> obj._coords(1); } /** * Base class for ScaleInvariant Oriented Point features. * Add scale and orientation description to basis PointFeature. */ class SIOPointFeature : public PointFeature { friend std::ostream& operator<<(std::ostream& out, const SIOPointFeature& obj); friend std::istream& operator>>(std::istream& in, SIOPointFeature& obj); public: SIOPointFeature(float x=0.0f, float y=0.0f, float scale=0.0f, float orient=0.0f) : PointFeature(x,y) , _scale(scale) , _orientation(orient) {} float scale() const { return _scale; } float& scale() { return _scale; } float orientation() const { return _orientation; } float& orientation() { return _orientation; } bool operator ==(const SIOPointFeature& b) const { return (_scale == b.scale()) && (_orientation == b.orientation()) && (x() == b.x()) && (y() == b.y()) ; }; bool operator !=(const SIOPointFeature& b) const { return !((*this)==b); }; template<class Archive> void serialize(Archive & ar) { ar ( _coords(0), _coords(1), _scale, _orientation); } protected: float _scale; // In pixels. float _orientation; // In radians. }; // inline std::ostream& operator<<(std::ostream& out, const SIOPointFeature& obj) { const PointFeature *pf = static_cast<const PointFeature*>(&obj); return out << *pf << " " << obj._scale << " " << obj._orientation; } inline std::istream& operator>>(std::istream& in, SIOPointFeature& obj) { PointFeature *pf = static_cast<PointFeature*>(&obj); return in >> *pf >> obj._scale >> obj._orientation; } /// Read feats from file template<typename FeaturesT > static bool loadFeatsFromFile( const std::string & sfileNameFeats, FeaturesT & vec_feat) { vec_feat.clear(); std::ifstream fileIn(sfileNameFeats.c_str()); if (!fileIn.is_open()) return false; std::copy( std::istream_iterator<typename FeaturesT::value_type >(fileIn), std::istream_iterator<typename FeaturesT::value_type >(), std::back_inserter(vec_feat)); const bool bOk = !fileIn.bad(); fileIn.close(); return bOk; } /// Write feats to file template<typename FeaturesT > static bool saveFeatsToFile( const std::string & sfileNameFeats, FeaturesT & vec_feat) { std::ofstream file(sfileNameFeats.c_str()); if (!file.is_open()) return false; std::copy(vec_feat.begin(), vec_feat.end(), std::ostream_iterator<typename FeaturesT::value_type >(file,"\n")); const bool bOk = file.good(); file.close(); return bOk; } /// Export point feature based vector to a matrix [(x,y)'T, (x,y)'T] template< typename FeaturesT, typename MatT > void PointsToMat( const FeaturesT & vec_feats, MatT & m) { m.resize(2, vec_feats.size()); typedef typename FeaturesT::value_type ValueT; // Container type size_t i = 0; for( typename FeaturesT::const_iterator iter = vec_feats.begin(); iter != vec_feats.end(); ++iter, ++i) { const ValueT & feat = *iter; m.col(i) << feat.x(), feat.y(); } } } // namespace features } // namespace openMVG #endif // OPENMVG_FEATURES_FEATURE_HPP <|endoftext|>
<commit_before>#include <mjolnir/input/read_input_file.hpp> int main(int argc, char** argv) { if(argc != 2) { std::cerr << "Usage: " << argv[0] << " <input.toml>" << std::endl; return 1; } auto simulator = mjolnir::read_input_file(std::string(argv[1])); simulator->initialize(); const auto start = std::chrono::system_clock::now(); std::cerr << "start running simulation" << std::endl; while(simulator->step()){/* do nothing */;} const auto stop = std::chrono::system_clock::now(); std::cout << "elapsed time: " << std::chrono::duration_cast<std::chrono::milliseconds>( stop - start).count() << " [msec]" << std::endl; simulator->finalize(); return 0; } <commit_msg>add some messages to main function<commit_after>#include <mjolnir/input/read_input_file.hpp> int main(int argc, char** argv) { if(argc != 2) { std::cerr << "Usage: " << argv[0] << " <input.toml>" << std::endl; return 1; } std::cerr << "reading input file..."; auto simulator = mjolnir::read_input_file(std::string(argv[1])); std::cerr << " done." << std::endl; std::cerr << "initializing simulator..."; simulator->initialize(); std::cerr << " done." << std::endl; const auto start = std::chrono::system_clock::now(); std::cerr << "start running simulation" << std::endl; while(simulator->step()){/* do nothing */;} const auto stop = std::chrono::system_clock::now(); std::cout << "elapsed time: " << std::chrono::duration_cast<std::chrono::milliseconds>( stop - start).count() << " [msec]" << std::endl; simulator->finalize(); return 0; } <|endoftext|>
<commit_before>// bdlma_guardingallocator.cpp -*-C++-*- #include <bdlma_guardingallocator.h> #include <bsls_ident.h> BSLS_IDENT_RCSID(bdlma_guardingallocator_cpp,"$Id$ $CSID$") #include <bsls_alignmentutil.h> #include <bsls_assert.h> #include <bsls_atomic.h> #include <bsls_exceptionutil.h> // 'BSLS_THROW' #include <bsls_performancehint.h> #include <bsls_platform.h> #include <bsls_types.h> #include <bsl_cstddef.h> // 'bsl::size_t' #include <bsl_new.h> // 'bsl::bad_alloc' #ifdef BSLS_PLATFORM_OS_WINDOWS #include <windows.h> // 'GetSystemInfo', 'VirtualAlloc', 'VirtualFree', // 'VirtualProtect' #else #include <stdlib.h> // 'valloc' #include <sys/mman.h> // 'mprotect' #include <unistd.h> // 'sysconf' #endif #ifdef BSLS_PLATFORM_OS_DARWIN #include <sys/mman.h> // 'mmap', 'munmap' #endif namespace BloombergLP { namespace { // HELPER FUNCTIONS // Define the offset (in bytes) from the address returned to the user in which // to stash reference addresses ('e_AFTER_USER_BLOCK' only). const bslma::Allocator::size_type OFFSET = bsls::AlignmentUtil::BSLS_MAX_ALIGNMENT; int getSystemPageSize() // Return the size (in bytes) of a system memory page. { static bsls::AtomicInt pageSize(0); if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(0 == pageSize.loadRelaxed())) { BSLS_PERFORMANCEHINT_UNLIKELY_HINT; #ifdef BSLS_PLATFORM_OS_WINDOWS SYSTEM_INFO info; GetSystemInfo(&info); pageSize = static_cast<int>(info.dwPageSize); #else pageSize = static_cast<int>(sysconf(_SC_PAGESIZE)); #endif } return pageSize.loadRelaxed(); } void *systemAlloc(bsl::size_t size) // Allocate a page-aligned block of memory of the specified 'size' (in // bytes), and return the address of the allocated block. The behavior is // undefined unless 'size > 0'. { BSLS_ASSERT(size > 0); #ifdef BSLS_PLATFORM_OS_WINDOWS return VirtualAlloc(0, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); #elif defined(BSLS_PLATFORM_OS_DARWIN) return mmap(0, size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, 0, 0); #else return valloc(size); #endif } void systemFree(void *address, size_t size) // Return the memory block at the specified 'address' back to its // allocator. The behavior is undefined unless 'address' was returned by // 'systemAlloc' and has not already been freed. { BSLS_ASSERT(address); #ifdef BSLS_PLATFORM_OS_WINDOWS VirtualFree(address, 0, MEM_RELEASE); (void) size; #elif defined(BSLS_PLATFORM_OS_DARWIN) munmap(address, size); #else free(address); (void) size; #endif } int systemProtect(void *address, int pageSize) // Protect from read/write access the page of memory at the specified // 'address' having the specified 'pageSize' (in bytes). The behavior is // undefined unless 'pageSize == getSystemPageSize()'. { BSLS_ASSERT(address); BSLS_ASSERT_SAFE(pageSize == getSystemPageSize()); #ifdef BSLS_PLATFORM_OS_WINDOWS DWORD oldProtect; return !VirtualProtect(address, pageSize, PAGE_NOACCESS, &oldProtect); #else return mprotect(static_cast<char *>(address), pageSize, PROT_NONE); #endif } int systemUnprotect(void *address, int pageSize) // Unprotect from read/write access the page of memory at the specified // 'address' having the specified 'pageSize' (in bytes). The behavior is // undefined unless 'pageSize == getSystemPageSize()'. { BSLS_ASSERT(address); BSLS_ASSERT_SAFE(pageSize == getSystemPageSize()); #ifdef BSLS_PLATFORM_OS_WINDOWS DWORD oldProtect; return !VirtualProtect(address, pageSize, PAGE_READWRITE, &oldProtect); #else return mprotect(static_cast<char *>(address), pageSize, PROT_READ | PROT_WRITE); #endif } } // close unnamed namespace namespace bdlma { // ----------------------- // class GuardingAllocator // ----------------------- // CREATORS GuardingAllocator::~GuardingAllocator() { } // MANIPULATORS void *GuardingAllocator::allocate(size_type size) { if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(0 == size)) { BSLS_PERFORMANCEHINT_UNLIKELY_HINT; return 0; // RETURN } const size_type paddedSize = bsls::AlignmentUtil::roundUpToMaximalAlignment(size); // Adjust for additional memory needed to stash reference addresses when // 'e_AFTER_USER_BLOCK' is in use. const int adjustedSize = e_AFTER_USER_BLOCK == d_guardPageLocation ? paddedSize + OFFSET * 2 : paddedSize; // Calculate the number of pages to allocate, *not* counting the guard // page. const int pageSize = getSystemPageSize(); const int numPages = (adjustedSize + pageSize - 1) / pageSize; const size_type totalSize = (numPages + 1) * pageSize; // add 1 for guard void *firstPage = systemAlloc(totalSize); if (!firstPage) { #ifdef BDE_BUILD_TARGET_EXC BSLS_THROW(bsl::bad_alloc()); #else return 0; // RETURN #endif } void *userAddress; // address to return to the caller void *guardPage; // address of the guard page for this allocation if (e_BEFORE_USER_BLOCK == d_guardPageLocation) { // Protect the memory page before the block returned to the user. guardPage = firstPage; userAddress = static_cast<char *>(firstPage) + pageSize; } else { // Protect the memory page after the block returned to the user. guardPage = static_cast<char *>(firstPage) + (numPages * pageSize); userAddress = static_cast<char *>(guardPage) - paddedSize; // Stash the reference addresses required by 'deallocate'. *(void **)(static_cast<char *>(userAddress) - OFFSET) = firstPage; *(void **)(static_cast<char *>(userAddress) - OFFSET * 2) = guardPage; } // Protect the guard page from read/write access. *(int *)(guardPage) = totalSize; if (0 != systemProtect(guardPage, pageSize)) { systemFree(firstPage, totalSize); #ifdef BDE_BUILD_TARGET_EXC BSLS_THROW(bsl::bad_alloc()); #else return 0; // RETURN #endif } return userAddress; } void GuardingAllocator::deallocate(void *address) { if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(0 == address)) { BSLS_PERFORMANCEHINT_UNLIKELY_HINT; return; // RETURN } const int pageSize = getSystemPageSize(); void *firstPage; // address of the first page of the allocation void *guardPage; // address of the guard page if (e_BEFORE_USER_BLOCK == d_guardPageLocation) { // The memory page before the block returned to the user is protected. firstPage = static_cast<char *>(address) - pageSize; guardPage = firstPage; } else { // The memory page after the block returned to the user is protected. firstPage = *(void **)(static_cast<char *>(address) - OFFSET); guardPage = *(void **)(static_cast<char *>(address) - OFFSET * 2); } // Unprotect the guard page and free the memory. const int rc = systemUnprotect(guardPage, pageSize); (void)rc; size_t totalSize = *(int *)(guardPage); BSLS_ASSERT_OPT(0 == rc); systemFree(firstPage, totalSize); } } // close package namespace } // close enterprise namespace // ---------------------------------------------------------------------------- // Copyright (C) 2013 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ---------------------------------- <commit_msg>use mmap on all unix platforms<commit_after>// bdlma_guardingallocator.cpp -*-C++-*- #include <bdlma_guardingallocator.h> #include <bsls_ident.h> BSLS_IDENT_RCSID(bdlma_guardingallocator_cpp,"$Id$ $CSID$") #include <bsls_alignmentutil.h> #include <bsls_assert.h> #include <bsls_atomic.h> #include <bsls_exceptionutil.h> // 'BSLS_THROW' #include <bsls_performancehint.h> #include <bsls_platform.h> #include <bsls_types.h> #include <bsl_cstddef.h> // 'bsl::size_t' #include <bsl_new.h> // 'bsl::bad_alloc' #ifdef BSLS_PLATFORM_OS_WINDOWS #include <windows.h> // 'GetSystemInfo', 'VirtualAlloc', 'VirtualFree', // 'VirtualProtect' #else #include <errno.h> // 'errno' #include <stdio.h> // 'fprintf' #include <string.h> // 'strerror' #include <sys/mman.h> // 'mmap', 'mprotect', 'munmap' #include <unistd.h> // 'sysconf' #endif namespace BloombergLP { namespace { // HELPER FUNCTIONS // Define the offset (in bytes) from the address returned to the user in which // to stash reference addresses ('e_AFTER_USER_BLOCK' only). const bslma::Allocator::size_type OFFSET = bsls::AlignmentUtil::BSLS_MAX_ALIGNMENT; int getSystemPageSize() // Return the size (in bytes) of a system memory page. { static bsls::AtomicInt pageSize(0); if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(0 == pageSize.loadRelaxed())) { BSLS_PERFORMANCEHINT_UNLIKELY_HINT; #ifdef BSLS_PLATFORM_OS_WINDOWS SYSTEM_INFO info; GetSystemInfo(&info); pageSize = static_cast<int>(info.dwPageSize); #else pageSize = static_cast<int>(sysconf(_SC_PAGESIZE)); #endif } return pageSize.loadRelaxed(); } void *systemAlloc(bsl::size_t size) // Allocate a page-aligned block of memory of the specified 'size' (in // bytes), and return the address of the allocated block. The behavior is // undefined unless 'size > 0'. { BSLS_ASSERT(size > 0); #ifdef BSLS_PLATFORM_OS_WINDOWS return VirtualAlloc(0, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); // RETURN #else void *address = mmap(0, size, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0); if (MAP_FAILED == address) { /* fprintf(stderr, "mmap failed, errno %d (%s)\n", errno, strerror(errno) ); */ return 0; // RETURN } return address; // RETURN #endif } void systemFree(void *address, size_t size) // Return the memory block at the specified 'address' back to its // allocator. The behavior is undefined unless 'address' was returned by // 'systemAlloc' and has not already been freed. { BSLS_ASSERT(address); #ifdef BSLS_PLATFORM_OS_WINDOWS VirtualFree(address, 0, MEM_RELEASE); (void) size; #else // On some of our platforms, 'munmap' takes a 'char*' argument, while on // others it takes a 'void*'. Casting to 'char*', which will work in both // cases. munmap(static_cast<char*>(address), size); #endif } int systemProtect(void *address, int pageSize) // Protect from read/write access the page of memory at the specified // 'address' having the specified 'pageSize' (in bytes). The behavior is // undefined unless 'pageSize == getSystemPageSize()'. { BSLS_ASSERT(address); BSLS_ASSERT_SAFE(pageSize == getSystemPageSize()); #ifdef BSLS_PLATFORM_OS_WINDOWS DWORD oldProtect; return !VirtualProtect(address, pageSize, PAGE_NOACCESS, &oldProtect); // RETURN #else return mprotect(static_cast<char *>(address), pageSize, PROT_NONE); // RETURN #endif } int systemUnprotect(void *address, int pageSize) // Unprotect from read/write access the page of memory at the specified // 'address' having the specified 'pageSize' (in bytes). The behavior is // undefined unless 'pageSize == getSystemPageSize()'. { BSLS_ASSERT(address); BSLS_ASSERT_SAFE(pageSize == getSystemPageSize()); #ifdef BSLS_PLATFORM_OS_WINDOWS DWORD oldProtect; return !VirtualProtect(address, pageSize, PAGE_READWRITE, &oldProtect); // RETURN #else return mprotect(static_cast<char *>(address), pageSize, PROT_READ | PROT_WRITE); // RETURN #endif } } // close unnamed namespace namespace bdlma { // ----------------------- // class GuardingAllocator // ----------------------- // CREATORS GuardingAllocator::~GuardingAllocator() { } // MANIPULATORS void *GuardingAllocator::allocate(size_type size) { if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(0 == size)) { BSLS_PERFORMANCEHINT_UNLIKELY_HINT; return 0; // RETURN } const size_type paddedSize = bsls::AlignmentUtil::roundUpToMaximalAlignment(size); // Adjust for additional memory needed to stash reference addresses when // 'e_AFTER_USER_BLOCK' is in use. const int adjustedSize = e_AFTER_USER_BLOCK == d_guardPageLocation ? paddedSize + OFFSET * 2 : paddedSize; // Calculate the number of pages to allocate, *not* counting the guard // page. const int pageSize = getSystemPageSize(); const int numPages = (adjustedSize + pageSize - 1) / pageSize; const size_type totalSize = (numPages + 1) * pageSize; // add 1 for guard void *firstPage = systemAlloc(totalSize); if (!firstPage) { #ifdef BDE_BUILD_TARGET_EXC BSLS_THROW(bsl::bad_alloc()); #else return 0; // RETURN #endif } void *userAddress; // address to return to the caller void *guardPage; // address of the guard page for this allocation if (e_BEFORE_USER_BLOCK == d_guardPageLocation) { // Protect the memory page before the block returned to the user. guardPage = firstPage; userAddress = static_cast<char *>(firstPage) + pageSize; } else { // Protect the memory page after the block returned to the user. guardPage = static_cast<char *>(firstPage) + (numPages * pageSize); userAddress = static_cast<char *>(guardPage) - paddedSize; // Stash the reference addresses required by 'deallocate'. *(void **)(static_cast<char *>(userAddress) - OFFSET) = firstPage; *(void **)(static_cast<char *>(userAddress) - OFFSET * 2) = guardPage; } // Save 'totalSize' - we'll need it for 'systemFree' in 'deallocate'. *(int *)(guardPage) = totalSize; // Protect the guard page from read/write access. if (0 != systemProtect(guardPage, pageSize)) { systemFree(firstPage, totalSize); #ifdef BDE_BUILD_TARGET_EXC BSLS_THROW(bsl::bad_alloc()); #else return 0; // RETURN #endif } return userAddress; } void GuardingAllocator::deallocate(void *address) { if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(0 == address)) { BSLS_PERFORMANCEHINT_UNLIKELY_HINT; return; // RETURN } const int pageSize = getSystemPageSize(); void *firstPage; // address of the first page of the allocation void *guardPage; // address of the guard page if (e_BEFORE_USER_BLOCK == d_guardPageLocation) { // The memory page before the block returned to the user is protected. firstPage = static_cast<char *>(address) - pageSize; guardPage = firstPage; } else { // The memory page after the block returned to the user is protected. firstPage = *(void **)(static_cast<char *>(address) - OFFSET); guardPage = *(void **)(static_cast<char *>(address) - OFFSET * 2); } // Unprotect the guard page and free the memory. const int rc = systemUnprotect(guardPage, pageSize); (void)rc; BSLS_ASSERT_OPT(0 == rc); size_t totalSize = *(int *)(guardPage); systemFree(firstPage, totalSize); } } // close package namespace } // close enterprise namespace // ---------------------------------------------------------------------------- // Copyright (C) 2013 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ---------------------------------- <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // Peloton // // operator_to_plan_transformer.cpp // // Identification: src/optimizer/operator_to_plan_transformer.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "optimizer/plan_generator.h" #include "optimizer/operator_expression.h" #include "planner/aggregate_plan.h" #include "planner/delete_plan.h" #include "planner/hash_join_plan.h" #include "planner/hash_plan.h" #include "planner/index_scan_plan.h" #include "planner/insert_plan.h" #include "planner/limit_plan.h" #include "planner/nested_loop_join_plan.h" #include "planner/order_by_plan.h" #include "planner/projection_plan.h" #include "planner/seq_scan_plan.h" #include "planner/update_plan.h" #include "settings/settings_manager.h" #include "storage/data_table.h" using std::vector; using std::make_pair; using std::string; using std::to_string; using std::unique_ptr; using std::shared_ptr; using std::move; using std::make_tuple; using std::make_pair; using std::pair; namespace peloton { namespace optimizer { PlanGenerator::PlanGenerator() {} unique_ptr<planner::AbstractPlan> PlanGenerator::ConvertOpExpression( shared_ptr<OperatorExpression> op, shared_ptr<PropertySet> required_props, vector<expression::AbstractExpression *> required_cols, vector<expression::AbstractExpression *> output_cols, vector<unique_ptr<planner::AbstractPlan>> &children_plans, vector<ExprMap> children_expr_map) { required_props_ = required_props; required_cols_ = required_cols; output_cols_ = output_cols; children_plans_ = move(children_plans); children_expr_map_ = move(children_expr_map); op->Op().Accept(this); BuildProjectionPlan(); return move(output_plan_); } void PlanGenerator::Visit(const DummyScan *) { // DummyScan is used in case of SELECT without FROM so that enforcer // can enforce a PhysicalProjection on top of DummyScan to generate correct // result. But here, no need to translate DummyScan to any physical plan. output_plan_ = nullptr; } void PlanGenerator::Visit(const PhysicalSeqScan *op) { vector<oid_t> column_ids = GenerateColumnsForScan(); auto predicate = GeneratePredicateForScan( expression::ExpressionUtil::JoinAnnotatedExprs(op->predicates), op->table_alias, op->table_); output_plan_.reset( new planner::SeqScanPlan(op->table_, predicate.release(), column_ids)); } void PlanGenerator::Visit(const PhysicalIndexScan *op) { vector<oid_t> column_ids = GenerateColumnsForScan(); auto predicate = GeneratePredicateForScan( expression::ExpressionUtil::JoinAnnotatedExprs(op->predicates), op->table_alias, op->table_); auto index = op->table_->GetIndex(op->index_id); vector<expression::AbstractExpression *> runtime_keys; // Create index scan desc planner::IndexScanPlan::IndexScanDesc index_scan_desc( index, op->key_column_id_list, op->expr_type_list, op->value_list, runtime_keys); output_plan_.reset(new planner::IndexScanPlan( op->table_, predicate.release(), column_ids, index_scan_desc, false)); } void PlanGenerator::Visit(const QueryDerivedScan *) {} void PlanGenerator::Visit(const PhysicalProject *) {} void PlanGenerator::Visit(const PhysicalLimit *op) { unique_ptr<planner::AbstractPlan> limit_plan( new planner::LimitPlan(op->limit, op->offset)); limit_plan->AddChild(move(children_plans_[0])); output_plan_ = move(limit_plan); } void PlanGenerator::Visit(const PhysicalOrderBy *) { vector<oid_t> column_ids; PL_ASSERT(children_expr_map_.size() == 1); auto &child_cols_map = children_expr_map_[0]; for (size_t i = 0; i < required_cols_.size(); ++i) { column_ids.push_back(child_cols_map[required_cols_[i]]); } auto sort_prop = required_props_->GetPropertyOfType(PropertyType::SORT) ->As<PropertySort>(); auto sort_columns_size = sort_prop->GetSortColumnSize(); vector<oid_t> sort_col_ids; vector<bool> sort_flags; for (size_t i = 0; i < sort_columns_size; ++i) { sort_col_ids.push_back(child_cols_map[sort_prop->GetSortColumn(i)]); // planner use desc flag sort_flags.push_back(!sort_prop->GetSortAscending(i)); } output_plan_.reset( new planner::OrderByPlan(sort_col_ids, sort_flags, column_ids)); output_plan_->AddChild(move(children_plans_[0])); } void PlanGenerator::Visit(const PhysicalHashGroupBy *) {} void PlanGenerator::Visit(const PhysicalSortGroupBy *) {} void PlanGenerator::Visit(const PhysicalAggregate *) {} void PlanGenerator::Visit(const PhysicalDistinct *) {} void PlanGenerator::Visit(const PhysicalFilter *) {} void PlanGenerator::Visit(const PhysicalInnerNLJoin *) {} void PlanGenerator::Visit(const PhysicalLeftNLJoin *) {} void PlanGenerator::Visit(const PhysicalRightNLJoin *) {} void PlanGenerator::Visit(const PhysicalOuterNLJoin *) {} void PlanGenerator::Visit(const PhysicalInnerHashJoin *) {} void PlanGenerator::Visit(const PhysicalLeftHashJoin *) {} void PlanGenerator::Visit(const PhysicalRightHashJoin *) {} void PlanGenerator::Visit(const PhysicalOuterHashJoin *) {} void PlanGenerator::Visit(const PhysicalInsert *op) { unique_ptr<planner::AbstractPlan> insert_plan( new planner::InsertPlan(op->target_table, op->columns, op->values)); output_plan_ = move(insert_plan); } void PlanGenerator::Visit(const PhysicalInsertSelect *op) { unique_ptr<planner::AbstractPlan> insert_plan( new planner::InsertPlan(op->target_table)); // Add child insert_plan->AddChild(move(children_plans_[0])); output_plan_ = move(insert_plan); } void PlanGenerator::Visit(const PhysicalDelete *op) { unique_ptr<planner::AbstractPlan> delete_plan( new planner::DeletePlan(op->target_table)); // Add child delete_plan->AddChild(move(children_plans_[0])); output_plan_ = move(delete_plan); } void PlanGenerator::Visit(const PhysicalUpdate *op) { DirectMapList dml; TargetList tl; std::unordered_set<oid_t> update_col_ids; auto schema = op->target_table->GetSchema(); auto table_alias = op->target_table->GetName(); ExprMap table_expr_map = GenerateTableExprMap(table_alias, op->target_table); // Evaluate update expression and add to target list for (auto &update : *(op->updates)) { auto column = update->column; auto col_id = schema->GetColumnID(column); if (update_col_ids.find(col_id) != update_col_ids.end()) throw SyntaxException("Multiple assignments to same column " + column); update_col_ids.insert(col_id); expression::ExpressionUtil::EvaluateExpression({table_expr_map}, update->value.get()); planner::DerivedAttribute attribute{update->value->Copy()}; tl.emplace_back(col_id, attribute); } // Add other columns to direct map auto col_size = schema->GetColumnCount(); for (size_t i = 0; i < col_size; i++) { if (update_col_ids.find(i) == update_col_ids.end()) dml.emplace_back(i, std::pair<oid_t, oid_t>(0, i)); } unique_ptr<const planner::ProjectInfo> proj_info( new planner::ProjectInfo(move(tl), move(dml))); unique_ptr<planner::AbstractPlan> update_plan( new planner::UpdatePlan(op->target_table, move(proj_info))); update_plan->AddChild(move(children_plans_[0])); output_plan_ = move(update_plan); } /************************* Private Functions *******************************/ ExprMap PlanGenerator::GenerateTableExprMap(const std::string &alias, const storage::DataTable *table) { ExprMap expr_map; auto db_id = table->GetDatabaseOid(); oid_t table_id = table->GetOid(); auto cols = table->GetSchema()->GetColumns(); size_t num_col = cols.size(); for (oid_t col_id = 0; col_id < num_col; ++col_id) { // Only bound_obj_id is needed for expr_map // TODO potential memory leak here? expression::TupleValueExpression *col_expr = new expression::TupleValueExpression(cols[col_id].column_name.c_str(), alias.c_str()); col_expr->SetValueType(table->GetSchema()->GetColumn(col_id).GetType()); col_expr->SetBoundOid(db_id, table_id, col_id); expr_map[col_expr] = col_id; } return expr_map; } // Generate columns for scan plan vector<oid_t> PlanGenerator::GenerateColumnsForScan() { vector<oid_t> column_ids; for (oid_t idx = 0; idx < output_cols_.size(); ++idx) { auto &output_expr = output_cols_[idx]; PL_ASSERT(output_expr->GetExpressionType() == ExpressionType::VALUE_TUPLE); auto output_tvexpr = reinterpret_cast<expression::TupleValueExpression *>(output_expr); // Set column offset PL_ASSERT(output_tvexpr->GetIsBound() == true); auto col_id = std::get<2>(output_tvexpr->GetBoundOid()); column_ids.push_back(col_id); } return column_ids; } std::unique_ptr<expression::AbstractExpression> PlanGenerator::GeneratePredicateForScan( const std::shared_ptr<expression::AbstractExpression> predicate_expr, const std::string &alias, const storage::DataTable *table) { if (predicate_expr == nullptr) { return nullptr; } ExprMap table_expr_map = GenerateTableExprMap(alias, table); unique_ptr<expression::AbstractExpression> predicate = std::unique_ptr<expression::AbstractExpression>(predicate_expr->Copy()); expression::ExpressionUtil::ConvertToTvExpr(col_copy, child_expr_map); expression::ExpressionUtil::EvaluateExpression({table_expr_map}, predicate.get()); return predicate; } void PlanGenerator::BuildProjectionPlan() { bool no_projection = false; if (output_cols_.size() == required_cols_.size()) { no_projection = true; size_t cols_size = output_cols_.size(); for (size_t idx = 0; idx < cols_size; ++idx) { if (output_cols_[idx] != required_cols_[idx]) { no_projection = false; break; } } } if (no_projection) { return; } vector<ExprMap> output_expr_maps = {ExprMap{}}; auto &child_expr_map = output_expr_maps[0]; for (size_t idx = 0; idx < output_cols_.size(); ++idx) { auto &col = output_cols_[idx]; child_expr_map[col] = idx; } TargetList tl; DirectMapList dml; vector<catalog::Column> columns; for (size_t idx = 0; idx < required_cols_.size(); ++idx) { auto &col = required_cols_[idx]; if (child_expr_map.find(col) != child_expr_map.end()) { dml.emplace_back(idx, make_pair(0, child_expr_map[col])); } else { // Copy then evaluate the expression and add to target list auto col_copy = col->Copy(); expression::ExpressionUtil::ConvertToTvExpr(col_copy, child_expr_map); expression::ExpressionUtil::EvaluateExpression(children_expr_map_, col_copy); planner::DerivedAttribute attribute{col_copy}; tl.emplace_back(idx, attribute); } columns.push_back(catalog::Column( col->GetValueType(), type::Type::GetTypeSize(col->GetValueType()), col->GetExpressionName())); } unique_ptr<planner::ProjectInfo> proj_info( new planner::ProjectInfo(move(tl), move(dml))); // TODO since the plan will own the schema, we may not want to use unique_ptr // to initialize the plan shared_ptr<catalog::Schema> schema_ptr(new catalog::Schema(columns)); unique_ptr<planner::AbstractPlan> project_plan( new planner::ProjectionPlan(move(proj_info), schema_ptr)); PL_ASSERT(children_plans_.size() < 2); if (!children_plans_.empty()) { project_plan->AddChild(move(children_plans_[0])); } output_plan_ = move(project_plan); } } // namespace optimizer } // namespace peloton <commit_msg>Minor fix for compilation error<commit_after>//===----------------------------------------------------------------------===// // // Peloton // // operator_to_plan_transformer.cpp // // Identification: src/optimizer/operator_to_plan_transformer.cpp // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "optimizer/plan_generator.h" #include "optimizer/operator_expression.h" #include "planner/aggregate_plan.h" #include "planner/delete_plan.h" #include "planner/hash_join_plan.h" #include "planner/hash_plan.h" #include "planner/index_scan_plan.h" #include "planner/insert_plan.h" #include "planner/limit_plan.h" #include "planner/nested_loop_join_plan.h" #include "planner/order_by_plan.h" #include "planner/projection_plan.h" #include "planner/seq_scan_plan.h" #include "planner/update_plan.h" #include "settings/settings_manager.h" #include "storage/data_table.h" using std::vector; using std::make_pair; using std::string; using std::to_string; using std::unique_ptr; using std::shared_ptr; using std::move; using std::make_tuple; using std::make_pair; using std::pair; namespace peloton { namespace optimizer { PlanGenerator::PlanGenerator() {} unique_ptr<planner::AbstractPlan> PlanGenerator::ConvertOpExpression( shared_ptr<OperatorExpression> op, shared_ptr<PropertySet> required_props, vector<expression::AbstractExpression *> required_cols, vector<expression::AbstractExpression *> output_cols, vector<unique_ptr<planner::AbstractPlan>> &children_plans, vector<ExprMap> children_expr_map) { required_props_ = required_props; required_cols_ = required_cols; output_cols_ = output_cols; children_plans_ = move(children_plans); children_expr_map_ = move(children_expr_map); op->Op().Accept(this); BuildProjectionPlan(); return move(output_plan_); } void PlanGenerator::Visit(const DummyScan *) { // DummyScan is used in case of SELECT without FROM so that enforcer // can enforce a PhysicalProjection on top of DummyScan to generate correct // result. But here, no need to translate DummyScan to any physical plan. output_plan_ = nullptr; } void PlanGenerator::Visit(const PhysicalSeqScan *op) { vector<oid_t> column_ids = GenerateColumnsForScan(); auto predicate = GeneratePredicateForScan( expression::ExpressionUtil::JoinAnnotatedExprs(op->predicates), op->table_alias, op->table_); output_plan_.reset( new planner::SeqScanPlan(op->table_, predicate.release(), column_ids)); } void PlanGenerator::Visit(const PhysicalIndexScan *op) { vector<oid_t> column_ids = GenerateColumnsForScan(); auto predicate = GeneratePredicateForScan( expression::ExpressionUtil::JoinAnnotatedExprs(op->predicates), op->table_alias, op->table_); auto index = op->table_->GetIndex(op->index_id); vector<expression::AbstractExpression *> runtime_keys; // Create index scan desc planner::IndexScanPlan::IndexScanDesc index_scan_desc( index, op->key_column_id_list, op->expr_type_list, op->value_list, runtime_keys); output_plan_.reset(new planner::IndexScanPlan( op->table_, predicate.release(), column_ids, index_scan_desc, false)); } void PlanGenerator::Visit(const QueryDerivedScan *) {} void PlanGenerator::Visit(const PhysicalProject *) {} void PlanGenerator::Visit(const PhysicalLimit *op) { unique_ptr<planner::AbstractPlan> limit_plan( new planner::LimitPlan(op->limit, op->offset)); limit_plan->AddChild(move(children_plans_[0])); output_plan_ = move(limit_plan); } void PlanGenerator::Visit(const PhysicalOrderBy *) { vector<oid_t> column_ids; PL_ASSERT(children_expr_map_.size() == 1); auto &child_cols_map = children_expr_map_[0]; for (size_t i = 0; i < required_cols_.size(); ++i) { column_ids.push_back(child_cols_map[required_cols_[i]]); } auto sort_prop = required_props_->GetPropertyOfType(PropertyType::SORT) ->As<PropertySort>(); auto sort_columns_size = sort_prop->GetSortColumnSize(); vector<oid_t> sort_col_ids; vector<bool> sort_flags; for (size_t i = 0; i < sort_columns_size; ++i) { sort_col_ids.push_back(child_cols_map[sort_prop->GetSortColumn(i)]); // planner use desc flag sort_flags.push_back(!sort_prop->GetSortAscending(i)); } output_plan_.reset( new planner::OrderByPlan(sort_col_ids, sort_flags, column_ids)); output_plan_->AddChild(move(children_plans_[0])); } void PlanGenerator::Visit(const PhysicalHashGroupBy *) {} void PlanGenerator::Visit(const PhysicalSortGroupBy *) {} void PlanGenerator::Visit(const PhysicalAggregate *) {} void PlanGenerator::Visit(const PhysicalDistinct *) {} void PlanGenerator::Visit(const PhysicalFilter *) {} void PlanGenerator::Visit(const PhysicalInnerNLJoin *) {} void PlanGenerator::Visit(const PhysicalLeftNLJoin *) {} void PlanGenerator::Visit(const PhysicalRightNLJoin *) {} void PlanGenerator::Visit(const PhysicalOuterNLJoin *) {} void PlanGenerator::Visit(const PhysicalInnerHashJoin *) {} void PlanGenerator::Visit(const PhysicalLeftHashJoin *) {} void PlanGenerator::Visit(const PhysicalRightHashJoin *) {} void PlanGenerator::Visit(const PhysicalOuterHashJoin *) {} void PlanGenerator::Visit(const PhysicalInsert *op) { unique_ptr<planner::AbstractPlan> insert_plan( new planner::InsertPlan(op->target_table, op->columns, op->values)); output_plan_ = move(insert_plan); } void PlanGenerator::Visit(const PhysicalInsertSelect *op) { unique_ptr<planner::AbstractPlan> insert_plan( new planner::InsertPlan(op->target_table)); // Add child insert_plan->AddChild(move(children_plans_[0])); output_plan_ = move(insert_plan); } void PlanGenerator::Visit(const PhysicalDelete *op) { unique_ptr<planner::AbstractPlan> delete_plan( new planner::DeletePlan(op->target_table)); // Add child delete_plan->AddChild(move(children_plans_[0])); output_plan_ = move(delete_plan); } void PlanGenerator::Visit(const PhysicalUpdate *op) { DirectMapList dml; TargetList tl; std::unordered_set<oid_t> update_col_ids; auto schema = op->target_table->GetSchema(); auto table_alias = op->target_table->GetName(); ExprMap table_expr_map = GenerateTableExprMap(table_alias, op->target_table); // Evaluate update expression and add to target list for (auto &update : *(op->updates)) { auto column = update->column; auto col_id = schema->GetColumnID(column); if (update_col_ids.find(col_id) != update_col_ids.end()) throw SyntaxException("Multiple assignments to same column " + column); update_col_ids.insert(col_id); expression::ExpressionUtil::EvaluateExpression({table_expr_map}, update->value.get()); planner::DerivedAttribute attribute{update->value->Copy()}; tl.emplace_back(col_id, attribute); } // Add other columns to direct map auto col_size = schema->GetColumnCount(); for (size_t i = 0; i < col_size; i++) { if (update_col_ids.find(i) == update_col_ids.end()) dml.emplace_back(i, std::pair<oid_t, oid_t>(0, i)); } unique_ptr<const planner::ProjectInfo> proj_info( new planner::ProjectInfo(move(tl), move(dml))); unique_ptr<planner::AbstractPlan> update_plan( new planner::UpdatePlan(op->target_table, move(proj_info))); update_plan->AddChild(move(children_plans_[0])); output_plan_ = move(update_plan); } /************************* Private Functions *******************************/ ExprMap PlanGenerator::GenerateTableExprMap(const std::string &alias, const storage::DataTable *table) { ExprMap expr_map; auto db_id = table->GetDatabaseOid(); oid_t table_id = table->GetOid(); auto cols = table->GetSchema()->GetColumns(); size_t num_col = cols.size(); for (oid_t col_id = 0; col_id < num_col; ++col_id) { // Only bound_obj_id is needed for expr_map // TODO potential memory leak here? expression::TupleValueExpression *col_expr = new expression::TupleValueExpression(cols[col_id].column_name.c_str(), alias.c_str()); col_expr->SetValueType(table->GetSchema()->GetColumn(col_id).GetType()); col_expr->SetBoundOid(db_id, table_id, col_id); expr_map[col_expr] = col_id; } return expr_map; } // Generate columns for scan plan vector<oid_t> PlanGenerator::GenerateColumnsForScan() { vector<oid_t> column_ids; for (oid_t idx = 0; idx < output_cols_.size(); ++idx) { auto &output_expr = output_cols_[idx]; PL_ASSERT(output_expr->GetExpressionType() == ExpressionType::VALUE_TUPLE); auto output_tvexpr = reinterpret_cast<expression::TupleValueExpression *>(output_expr); // Set column offset PL_ASSERT(output_tvexpr->GetIsBound() == true); auto col_id = std::get<2>(output_tvexpr->GetBoundOid()); column_ids.push_back(col_id); } return column_ids; } std::unique_ptr<expression::AbstractExpression> PlanGenerator::GeneratePredicateForScan( const std::shared_ptr<expression::AbstractExpression> predicate_expr, const std::string &alias, const storage::DataTable *table) { if (predicate_expr == nullptr) { return nullptr; } ExprMap table_expr_map = GenerateTableExprMap(alias, table); unique_ptr<expression::AbstractExpression> predicate = std::unique_ptr<expression::AbstractExpression>(predicate_expr->Copy()); expression::ExpressionUtil::ConvertToTvExpr(predicate.get(), table_expr_map); expression::ExpressionUtil::EvaluateExpression({table_expr_map}, predicate.get()); return predicate; } void PlanGenerator::BuildProjectionPlan() { bool no_projection = false; if (output_cols_.size() == required_cols_.size()) { no_projection = true; size_t cols_size = output_cols_.size(); for (size_t idx = 0; idx < cols_size; ++idx) { if (output_cols_[idx] != required_cols_[idx]) { no_projection = false; break; } } } if (no_projection) { return; } vector<ExprMap> output_expr_maps = {ExprMap{}}; auto &child_expr_map = output_expr_maps[0]; for (size_t idx = 0; idx < output_cols_.size(); ++idx) { auto &col = output_cols_[idx]; child_expr_map[col] = idx; } TargetList tl; DirectMapList dml; vector<catalog::Column> columns; for (size_t idx = 0; idx < required_cols_.size(); ++idx) { auto &col = required_cols_[idx]; if (child_expr_map.find(col) != child_expr_map.end()) { dml.emplace_back(idx, make_pair(0, child_expr_map[col])); } else { // Copy then evaluate the expression and add to target list auto col_copy = col->Copy(); expression::ExpressionUtil::ConvertToTvExpr(col_copy, child_expr_map); expression::ExpressionUtil::EvaluateExpression(children_expr_map_, col_copy); planner::DerivedAttribute attribute{col_copy}; tl.emplace_back(idx, attribute); } columns.push_back(catalog::Column( col->GetValueType(), type::Type::GetTypeSize(col->GetValueType()), col->GetExpressionName())); } unique_ptr<planner::ProjectInfo> proj_info( new planner::ProjectInfo(move(tl), move(dml))); // TODO since the plan will own the schema, we may not want to use unique_ptr // to initialize the plan shared_ptr<catalog::Schema> schema_ptr(new catalog::Schema(columns)); unique_ptr<planner::AbstractPlan> project_plan( new planner::ProjectionPlan(move(proj_info), schema_ptr)); PL_ASSERT(children_plans_.size() < 2); if (!children_plans_.empty()) { project_plan->AddChild(move(children_plans_[0])); } output_plan_ = move(project_plan); } } // namespace optimizer } // namespace peloton <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // Name: lexer.cpp // Purpose: Implementation of wxExLexer class // Author: Anton van Wezenbeek // Copyright: (c) 2014 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <algorithm> #include <functional> //#include <numeric> // both for accumulate #include <wx/stc/stc.h> #include <wx/tokenzr.h> #include <wx/xml/xml.h> #include <wx/extension/lexer.h> #include <wx/extension/lexers.h> #include <wx/extension/util.h> // for wxExAlignText // We always use lines with 80 characters. const int line_size = 80; wxExLexer::wxExLexer() { Initialize(); } wxExLexer::wxExLexer(const wxXmlNode* node) { Initialize(); Set(node); } wxExLexer::wxExLexer(const wxString& lexer, wxStyledTextCtrl* stc, bool clear) { Initialize(); Set(lexer, stc, true); } wxExLexer::wxExLexer(const wxExLexer& lexer, wxStyledTextCtrl* stc) { Initialize(); Set(lexer, stc); } // Adds the specified keywords to the keywords map and the keywords set. // The text might contain the keyword set after a ':'. // Returns false if specified set is illegal or value is empty. bool wxExLexer::AddKeywords(const wxString& value) { if (value.empty()) { return false; } std::set<wxString> keywords_set; wxStringTokenizer tkz(value, "\r\n "); int setno = 0; while (tkz.HasMoreTokens()) { const wxString line = tkz.GetNextToken(); wxStringTokenizer fields(line, ":"); wxString keyword; if (fields.CountTokens() > 1) { keyword = fields.GetNextToken(); const int new_setno = atoi(fields.GetNextToken().c_str()); if (new_setno <= 0 || new_setno >= wxSTC_KEYWORDSET_MAX) { wxLogError("Invalid keyword set: %d", new_setno); return false; } if (new_setno != setno) { if (!keywords_set.empty()) { m_KeywordsSet.insert(make_pair(setno, keywords_set)); keywords_set.clear(); } setno = new_setno; } } else { keyword = line; } keywords_set.insert(keyword); m_Keywords.insert(keyword); } auto it = m_KeywordsSet.find(setno); if (it == m_KeywordsSet.end()) { m_KeywordsSet.insert(make_pair(setno, keywords_set)); } else { it->second.insert(keywords_set.begin(), keywords_set.end()); } return true; } void wxExLexer::Apply(wxStyledTextCtrl* stc, bool clear) const { if (clear) { stc->ClearDocumentStyle(); } for_each (m_Properties.begin(), m_Properties.end(), std::bind2nd(std::mem_fun_ref(&wxExProperty::ApplyReset), stc)); // Reset keywords, also if no lexer is available. for (size_t setno = 0; setno < wxSTC_KEYWORDSET_MAX; setno++) { stc->SetKeyWords(setno, wxEmptyString); } if (clear) { wxExLexers::Get()->ApplyGlobalStyles(stc); } if (wxExLexers::Get()->GetThemeOk()) { for (const auto& it : m_KeywordsSet) { stc->SetKeyWords( it.first, GetKeywordsString(it.first)); } wxExLexers::Get()->GetDefaultStyle().Apply(stc); wxExLexers::Get()->ApplyIndicators(stc); wxExLexers::Get()->ApplyProperties(stc); wxExLexers::Get()->ApplyMarkers(stc); for_each (m_Properties.begin(), m_Properties.end(), std::bind2nd(std::mem_fun_ref(&wxExProperty::Apply), stc)); for_each (m_Styles.begin(), m_Styles.end(), std::bind2nd(std::mem_fun_ref(&wxExStyle::Apply), stc)); } // And finally colour the entire document. stc->Colourise(0, stc->GetLength() - 1); } void wxExLexer::ApplyWhenSet( const wxString& lexer, wxStyledTextCtrl* stc, bool clear) { if (stc == NULL) { return; } stc->SetLexerLanguage(m_ScintillaLexer); if (m_ScintillaLexer.empty() && lexer.empty()) { m_IsOk = (stc->GetLexer() == wxSTC_LEX_NULL); } else { m_IsOk = (stc->GetLexer() != wxSTC_LEX_NULL); } if (m_IsOk) { stc->SetStyleBits(stc->GetStyleBitsNeeded()); Apply(stc, clear); if (m_ScintillaLexer == "diff") { stc->SetEdgeMode(wxSTC_EDGE_NONE); } } } void wxExLexer::AutoMatch(const wxString& lexer) { for (const auto& it : wxExLexers::Get()->GetMacros(lexer)) { for (const auto& style : wxExLexers::Get()->GetThemeMacros()) { if (it.first.Contains(style.first)) { m_Styles.push_back(wxExStyle(it.second, style.second)); break; } } } } const wxString wxExLexer::CommentComplete(const wxString& comment) const { if (m_CommentEnd.empty()) { return wxEmptyString; } // Fill out rest of comment with spaces, and comment end string. const int n = line_size - comment.size() - m_CommentEnd.size(); if (n <= 0) { return wxEmptyString; } const wxString blanks = wxString(' ', n); return blanks + m_CommentEnd; } const wxString wxExLexer::GetFormattedText( const wxString& lines, const wxString& header, bool fill_out_with_space, bool fill_out) const { wxString text = lines, header_to_use = header; size_t nCharIndex; wxString out; // Process text between the carriage return line feeds. while ((nCharIndex = text.find("\n")) != wxString::npos) { out << wxExAlignText( text.substr(0, nCharIndex), header_to_use, fill_out_with_space, fill_out, *this); text = text.substr(nCharIndex + 1); header_to_use = wxString(' ', header.size()); } if (!text.empty()) { out << wxExAlignText( text, header_to_use, fill_out_with_space, fill_out, *this); } return out; } const wxString wxExLexer::GetKeywordsString(int keyword_set) const { if (keyword_set == -1) { return GetKeywordsStringSet(m_Keywords); } else { const auto it = m_KeywordsSet.find(keyword_set); if (it != m_KeywordsSet.end()) { return GetKeywordsStringSet(it->second); } } return wxEmptyString; } const wxString wxExLexer::GetKeywordsStringSet( const std::set<wxString>& kset) const { // accumulate would be nice, but does not add a space, could not do it easily. // return accumulate(kset.begin(), kset.end(), wxEmptyString); wxString keywords; for (const auto& it : kset) { keywords += it + " "; } return keywords.Trim(); // remove the ending space } void wxExLexer::Initialize() { m_IsOk = false; m_CommentBegin.clear(); m_CommentBegin2.clear(); m_CommentEnd.clear(); m_CommentEnd2.clear(); m_Styles.clear(); m_Extensions.clear(); m_Properties.clear(); m_Keywords.clear(); m_KeywordsSet.clear(); m_ScintillaLexer.clear(); m_DisplayLexer.clear(); } bool wxExLexer::IsKeyword(const wxString& word) const { return m_Keywords.find(word) != m_Keywords.end(); } bool wxExLexer::KeywordStartsWith(const wxString& word) const { const auto it = m_Keywords.lower_bound(word); return it != m_Keywords.end() && it->StartsWith(word); } const wxString wxExLexer::MakeComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, wxEmptyString, fill_out_with_space, fill_out): out << wxExAlignText(text, wxEmptyString, fill_out_with_space, fill_out, *this); return out; } const wxString wxExLexer::MakeComment( const wxString& prefix, const wxString& text) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, prefix, true, true): out << wxExAlignText(text, prefix, true, true, *this); return out; } const wxString wxExLexer::MakeSingleLineComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { if (m_CommentBegin.empty() && m_CommentEnd.empty()) { return text; } // First set the fill_out_character. wxUniChar fill_out_character; if (fill_out_with_space || m_ScintillaLexer == "hypertext") { fill_out_character = ' '; } else { if (text.empty()) { if (m_CommentBegin == m_CommentEnd) fill_out_character = '-'; else fill_out_character = m_CommentBegin[m_CommentBegin.size() - 1]; } else fill_out_character = ' '; } wxString out = m_CommentBegin + fill_out_character + text; // Fill out characters. if (fill_out) { // To prevent filling out spaces if (fill_out_character != ' ' || !m_CommentEnd.empty()) { const int fill_chars = UsableCharactersPerLine() - text.size(); if (fill_chars > 0) { const wxString fill_out(fill_out_character, fill_chars); out += fill_out; } } } if (!m_CommentEnd.empty()) out += fill_out_character + m_CommentEnd; return out; } bool wxExLexer::Reset(wxStyledTextCtrl* stc) { Initialize(); stc->SetLexer(wxSTC_LEX_NULL); m_IsOk = (stc->GetLexer() == wxSTC_LEX_NULL); if (m_IsOk) { Apply(stc, true); } return m_IsOk; } bool wxExLexer::Set( const wxString& lexer, wxStyledTextCtrl* stc, bool clear) { (*this) = wxExLexers::Get()->FindByName(lexer); if (!m_IsOk && stc != NULL) { (*this) = wxExLexers::Get()->FindByText(stc->GetLine(0)); } ApplyWhenSet(lexer, stc, clear); if (!m_IsOk) { wxLogError("Lexer is not known: " + lexer); } return m_IsOk; } bool wxExLexer::Set(const wxExLexer& lexer, wxStyledTextCtrl* stc) { if (lexer.GetScintillaLexer().empty() && stc != NULL) { (*this) = wxExLexers::Get()->FindByText(stc->GetLine(0)); } else { if (this != &lexer) { (*this) = lexer; } } ApplyWhenSet(lexer.GetScintillaLexer(), stc, true); return m_IsOk; } void wxExLexer::Set(const wxXmlNode* node) { m_ScintillaLexer = node->GetAttribute("name"); // Just set ok if there is a lexer, // when we Apply to a stc component we really can set it. m_IsOk = !m_ScintillaLexer.empty(); if (!m_IsOk) { wxLogError("Missing lexer on line: %d", node->GetLineNumber()); } else { m_DisplayLexer = (!node->GetAttribute("display").empty() ? node->GetAttribute("display"): m_ScintillaLexer); m_Extensions = node->GetAttribute("extensions"); AutoMatch((!node->GetAttribute("macro").empty() ? node->GetAttribute("macro"): m_ScintillaLexer)); if (m_ScintillaLexer == "hypertext") { // As our lexers.xml files cannot use xml comments, // add them here. m_CommentBegin = "<!--"; m_CommentEnd = "-->"; } wxXmlNode *child = node->GetChildren(); while (child) { if (child->GetName() == "styles") { wxExNodeStyles(child, m_ScintillaLexer, m_Styles); } else if (child->GetName() == "keywords") { // Add all direct keywords const wxString& direct(child->GetNodeContent().Strip(wxString::both)); if (!direct.empty() && !AddKeywords(direct)) { wxLogError( "Keywords could not be set on line: %d", child->GetLineNumber()); } // Add all keywords that point to a keyword set. wxXmlAttribute* att = child->GetAttributes(); while (att != NULL) { if (!AddKeywords(wxExLexers::Get()->GetKeywords( att->GetValue().Strip(wxString::both)))) { wxLogError( "Keywords for %s could not be set on line: %d", att->GetValue().c_str(), child->GetLineNumber()); } att = att->GetNext(); } } else if (child->GetName() == "properties") { wxExNodeProperties(child, m_Properties); } else if (child->GetName() == "comments") { m_CommentBegin = child->GetAttribute("begin1"); m_CommentEnd = child->GetAttribute("end1"); m_CommentBegin2 = child->GetAttribute("begin2"); m_CommentEnd2 = child->GetAttribute("end2"); } child = child->GetNext(); } } #ifdef DEBUG wxString keywords; for (const auto& it : m_KeywordsSet) { keywords += wxString::Format("set: %d %s\n", it.first, GetKeywordsString(it.first).c_str()); } if (!keywords.empty()) { wxLogMessage("Lexer: %s Display: %s Keywords: %s", m_ScintillaLexer.c_str(), m_DisplayLexer.c_str(), keywords.c_str()); } #endif } void wxExLexer::SetProperty(const wxString& name, const wxString& value) { for (auto& it : m_Properties) { if (it.GetName() == name) { it.Set(value); return; } } m_Properties.push_back(wxExProperty(name, value)); } int wxExLexer::UsableCharactersPerLine() const { // We adjust this here for // the space the beginning and end of the comment characters occupy. return line_size - ((m_CommentBegin.size() != 0) ? m_CommentBegin.size() + 1 : 0) - ((m_CommentEnd.size() != 0) ? m_CommentEnd.size() + 1 : 0); } <commit_msg>minor simplification<commit_after>//////////////////////////////////////////////////////////////////////////////// // Name: lexer.cpp // Purpose: Implementation of wxExLexer class // Author: Anton van Wezenbeek // Copyright: (c) 2014 Anton van Wezenbeek //////////////////////////////////////////////////////////////////////////////// #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <algorithm> #include <functional> //#include <numeric> // both for accumulate #include <wx/stc/stc.h> #include <wx/tokenzr.h> #include <wx/xml/xml.h> #include <wx/extension/lexer.h> #include <wx/extension/lexers.h> #include <wx/extension/util.h> // for wxExAlignText // We always use lines with 80 characters. const int line_size = 80; wxExLexer::wxExLexer() { Initialize(); } wxExLexer::wxExLexer(const wxXmlNode* node) { Initialize(); Set(node); } wxExLexer::wxExLexer(const wxString& lexer, wxStyledTextCtrl* stc, bool clear) { Initialize(); Set(lexer, stc, true); } wxExLexer::wxExLexer(const wxExLexer& lexer, wxStyledTextCtrl* stc) { Initialize(); Set(lexer, stc); } // Adds the specified keywords to the keywords map and the keywords set. // The text might contain the keyword set after a ':'. // Returns false if specified set is illegal or value is empty. bool wxExLexer::AddKeywords(const wxString& value) { if (value.empty()) { return false; } std::set<wxString> keywords_set; wxStringTokenizer tkz(value, "\r\n "); int setno = 0; while (tkz.HasMoreTokens()) { const wxString line = tkz.GetNextToken(); wxStringTokenizer fields(line, ":"); wxString keyword; if (fields.CountTokens() > 1) { keyword = fields.GetNextToken(); const int new_setno = atoi(fields.GetNextToken().c_str()); if (new_setno <= 0 || new_setno >= wxSTC_KEYWORDSET_MAX) { wxLogError("Invalid keyword set: %d", new_setno); return false; } if (new_setno != setno) { if (!keywords_set.empty()) { m_KeywordsSet.insert(make_pair(setno, keywords_set)); keywords_set.clear(); } setno = new_setno; } } else { keyword = line; } keywords_set.insert(keyword); m_Keywords.insert(keyword); } auto it = m_KeywordsSet.find(setno); if (it == m_KeywordsSet.end()) { m_KeywordsSet.insert(make_pair(setno, keywords_set)); } else { it->second.insert(keywords_set.begin(), keywords_set.end()); } return true; } void wxExLexer::Apply(wxStyledTextCtrl* stc, bool clear) const { if (clear) { stc->ClearDocumentStyle(); } for_each (m_Properties.begin(), m_Properties.end(), std::bind2nd(std::mem_fun_ref(&wxExProperty::ApplyReset), stc)); // Reset keywords, also if no lexer is available. for (size_t setno = 0; setno < wxSTC_KEYWORDSET_MAX; setno++) { stc->SetKeyWords(setno, wxEmptyString); } if (clear) { wxExLexers::Get()->ApplyGlobalStyles(stc); } if (wxExLexers::Get()->GetThemeOk()) { for (const auto& it : m_KeywordsSet) { stc->SetKeyWords(it.first, GetKeywordsStringSet(it.second)); } wxExLexers::Get()->GetDefaultStyle().Apply(stc); wxExLexers::Get()->ApplyIndicators(stc); wxExLexers::Get()->ApplyProperties(stc); wxExLexers::Get()->ApplyMarkers(stc); for_each (m_Properties.begin(), m_Properties.end(), std::bind2nd(std::mem_fun_ref(&wxExProperty::Apply), stc)); for_each (m_Styles.begin(), m_Styles.end(), std::bind2nd(std::mem_fun_ref(&wxExStyle::Apply), stc)); } // And finally colour the entire document. stc->Colourise(0, stc->GetLength() - 1); } void wxExLexer::ApplyWhenSet( const wxString& lexer, wxStyledTextCtrl* stc, bool clear) { if (stc == NULL) { return; } stc->SetLexerLanguage(m_ScintillaLexer); if (m_ScintillaLexer.empty() && lexer.empty()) { m_IsOk = (stc->GetLexer() == wxSTC_LEX_NULL); } else { m_IsOk = (stc->GetLexer() != wxSTC_LEX_NULL); } if (m_IsOk) { stc->SetStyleBits(stc->GetStyleBitsNeeded()); Apply(stc, clear); if (m_ScintillaLexer == "diff") { stc->SetEdgeMode(wxSTC_EDGE_NONE); } } } void wxExLexer::AutoMatch(const wxString& lexer) { for (const auto& it : wxExLexers::Get()->GetMacros(lexer)) { for (const auto& style : wxExLexers::Get()->GetThemeMacros()) { if (it.first.Contains(style.first)) { m_Styles.push_back(wxExStyle(it.second, style.second)); break; } } } } const wxString wxExLexer::CommentComplete(const wxString& comment) const { if (m_CommentEnd.empty()) { return wxEmptyString; } // Fill out rest of comment with spaces, and comment end string. const int n = line_size - comment.size() - m_CommentEnd.size(); if (n <= 0) { return wxEmptyString; } const wxString blanks = wxString(' ', n); return blanks + m_CommentEnd; } const wxString wxExLexer::GetFormattedText( const wxString& lines, const wxString& header, bool fill_out_with_space, bool fill_out) const { wxString text = lines, header_to_use = header; size_t nCharIndex; wxString out; // Process text between the carriage return line feeds. while ((nCharIndex = text.find("\n")) != wxString::npos) { out << wxExAlignText( text.substr(0, nCharIndex), header_to_use, fill_out_with_space, fill_out, *this); text = text.substr(nCharIndex + 1); header_to_use = wxString(' ', header.size()); } if (!text.empty()) { out << wxExAlignText( text, header_to_use, fill_out_with_space, fill_out, *this); } return out; } const wxString wxExLexer::GetKeywordsString(int keyword_set) const { if (keyword_set == -1) { return GetKeywordsStringSet(m_Keywords); } else { const auto it = m_KeywordsSet.find(keyword_set); if (it != m_KeywordsSet.end()) { return GetKeywordsStringSet(it->second); } } return wxEmptyString; } const wxString wxExLexer::GetKeywordsStringSet( const std::set<wxString>& kset) const { // accumulate would be nice, but does not add a space, could not do it easily. // return accumulate(kset.begin(), kset.end(), wxEmptyString); wxString keywords; for (const auto& it : kset) { keywords += it + " "; } return keywords.Trim(); // remove the ending space } void wxExLexer::Initialize() { m_IsOk = false; m_CommentBegin.clear(); m_CommentBegin2.clear(); m_CommentEnd.clear(); m_CommentEnd2.clear(); m_Styles.clear(); m_Extensions.clear(); m_Properties.clear(); m_Keywords.clear(); m_KeywordsSet.clear(); m_ScintillaLexer.clear(); m_DisplayLexer.clear(); } bool wxExLexer::IsKeyword(const wxString& word) const { return m_Keywords.find(word) != m_Keywords.end(); } bool wxExLexer::KeywordStartsWith(const wxString& word) const { const auto it = m_Keywords.lower_bound(word); return it != m_Keywords.end() && it->StartsWith(word); } const wxString wxExLexer::MakeComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, wxEmptyString, fill_out_with_space, fill_out): out << wxExAlignText(text, wxEmptyString, fill_out_with_space, fill_out, *this); return out; } const wxString wxExLexer::MakeComment( const wxString& prefix, const wxString& text) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, prefix, true, true): out << wxExAlignText(text, prefix, true, true, *this); return out; } const wxString wxExLexer::MakeSingleLineComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { if (m_CommentBegin.empty() && m_CommentEnd.empty()) { return text; } // First set the fill_out_character. wxUniChar fill_out_character; if (fill_out_with_space || m_ScintillaLexer == "hypertext") { fill_out_character = ' '; } else { if (text.empty()) { if (m_CommentBegin == m_CommentEnd) fill_out_character = '-'; else fill_out_character = m_CommentBegin[m_CommentBegin.size() - 1]; } else fill_out_character = ' '; } wxString out = m_CommentBegin + fill_out_character + text; // Fill out characters. if (fill_out) { // To prevent filling out spaces if (fill_out_character != ' ' || !m_CommentEnd.empty()) { const int fill_chars = UsableCharactersPerLine() - text.size(); if (fill_chars > 0) { const wxString fill_out(fill_out_character, fill_chars); out += fill_out; } } } if (!m_CommentEnd.empty()) out += fill_out_character + m_CommentEnd; return out; } bool wxExLexer::Reset(wxStyledTextCtrl* stc) { Initialize(); stc->SetLexer(wxSTC_LEX_NULL); m_IsOk = (stc->GetLexer() == wxSTC_LEX_NULL); if (m_IsOk) { Apply(stc, true); } return m_IsOk; } bool wxExLexer::Set( const wxString& lexer, wxStyledTextCtrl* stc, bool clear) { (*this) = wxExLexers::Get()->FindByName(lexer); if (!m_IsOk && stc != NULL) { (*this) = wxExLexers::Get()->FindByText(stc->GetLine(0)); } ApplyWhenSet(lexer, stc, clear); if (!m_IsOk) { wxLogError("Lexer is not known: " + lexer); } return m_IsOk; } bool wxExLexer::Set(const wxExLexer& lexer, wxStyledTextCtrl* stc) { if (lexer.GetScintillaLexer().empty() && stc != NULL) { (*this) = wxExLexers::Get()->FindByText(stc->GetLine(0)); } else { if (this != &lexer) { (*this) = lexer; } } ApplyWhenSet(lexer.GetScintillaLexer(), stc, true); return m_IsOk; } void wxExLexer::Set(const wxXmlNode* node) { m_ScintillaLexer = node->GetAttribute("name"); // Just set ok if there is a lexer, // when we Apply to a stc component we really can set it. m_IsOk = !m_ScintillaLexer.empty(); if (!m_IsOk) { wxLogError("Missing lexer on line: %d", node->GetLineNumber()); } else { m_DisplayLexer = (!node->GetAttribute("display").empty() ? node->GetAttribute("display"): m_ScintillaLexer); m_Extensions = node->GetAttribute("extensions"); AutoMatch((!node->GetAttribute("macro").empty() ? node->GetAttribute("macro"): m_ScintillaLexer)); if (m_ScintillaLexer == "hypertext") { // As our lexers.xml files cannot use xml comments, // add them here. m_CommentBegin = "<!--"; m_CommentEnd = "-->"; } wxXmlNode *child = node->GetChildren(); while (child) { if (child->GetName() == "styles") { wxExNodeStyles(child, m_ScintillaLexer, m_Styles); } else if (child->GetName() == "keywords") { // Add all direct keywords const wxString& direct(child->GetNodeContent().Strip(wxString::both)); if (!direct.empty() && !AddKeywords(direct)) { wxLogError( "Keywords could not be set on line: %d", child->GetLineNumber()); } // Add all keywords that point to a keyword set. wxXmlAttribute* att = child->GetAttributes(); while (att != NULL) { if (!AddKeywords(wxExLexers::Get()->GetKeywords( att->GetValue().Strip(wxString::both)))) { wxLogError( "Keywords for %s could not be set on line: %d", att->GetValue().c_str(), child->GetLineNumber()); } att = att->GetNext(); } } else if (child->GetName() == "properties") { wxExNodeProperties(child, m_Properties); } else if (child->GetName() == "comments") { m_CommentBegin = child->GetAttribute("begin1"); m_CommentEnd = child->GetAttribute("end1"); m_CommentBegin2 = child->GetAttribute("begin2"); m_CommentEnd2 = child->GetAttribute("end2"); } child = child->GetNext(); } } #ifdef DEBUG wxString keywords; for (const auto& it : m_KeywordsSet) { keywords += wxString::Format("set: %d %s\n", it.first, GetKeywordsString(it.first).c_str()); } if (!keywords.empty()) { wxLogMessage("Lexer: %s Display: %s Keywords: %s", m_ScintillaLexer.c_str(), m_DisplayLexer.c_str(), keywords.c_str()); } #endif } void wxExLexer::SetProperty(const wxString& name, const wxString& value) { for (auto& it : m_Properties) { if (it.GetName() == name) { it.Set(value); return; } } m_Properties.push_back(wxExProperty(name, value)); } int wxExLexer::UsableCharactersPerLine() const { // We adjust this here for // the space the beginning and end of the comment characters occupy. return line_size - ((m_CommentBegin.size() != 0) ? m_CommentBegin.size() + 1 : 0) - ((m_CommentEnd.size() != 0) ? m_CommentEnd.size() + 1 : 0); } <|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. // // See the corresponding header file for description of the functions in this // file. #include "install_util.h" #include <algorithm> #include <shellapi.h> #include <shlobj.h> #include "base/logging.h" #include "base/registry.h" #include "base/string_util.h" #include "base/win_util.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/google_update_constants.h" #include "chrome/installer/util/l10n_string_util.h" #include "chrome/installer/util/work_item_list.h" bool InstallUtil::ExecuteExeAsAdmin(const std::wstring& exe, const std::wstring& params, DWORD* exit_code) { SHELLEXECUTEINFO info = {0}; info.cbSize = sizeof(SHELLEXECUTEINFO); info.fMask = SEE_MASK_NOCLOSEPROCESS; info.lpVerb = L"runas"; info.lpFile = exe.c_str(); info.lpParameters = params.c_str(); info.nShow = SW_SHOW; if (::ShellExecuteEx(&info) == FALSE) return false; ::WaitForSingleObject(info.hProcess, INFINITE); DWORD ret_val = 0; if (!::GetExitCodeProcess(info.hProcess, &ret_val)) return false; if (exit_code) *exit_code = ret_val; return true; } std::wstring InstallUtil::GetChromeUninstallCmd(bool system_install) { HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; BrowserDistribution* dist = BrowserDistribution::GetDistribution(); RegKey key(root, dist->GetUninstallRegPath().c_str()); std::wstring uninstall_cmd; key.ReadValue(installer_util::kUninstallStringField, &uninstall_cmd); return uninstall_cmd; } installer::Version* InstallUtil::GetChromeVersion(bool system_install) { RegKey key; std::wstring version_str; HKEY reg_root = (system_install) ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; BrowserDistribution* dist = BrowserDistribution::GetDistribution(); if (!key.Open(reg_root, dist->GetVersionKey().c_str(), KEY_READ) || !key.ReadValue(google_update::kRegVersionField, &version_str)) { LOG(INFO) << "No existing Chrome install found."; key.Close(); return NULL; } key.Close(); LOG(INFO) << "Existing Chrome version found " << version_str; return installer::Version::GetVersionFromString(version_str); } bool InstallUtil::IsOSSupported() { int major, minor; win_util::WinVersion version = win_util::GetWinVersion(); win_util::GetServicePackLevel(&major, &minor); // We do not support Win2K or older, or XP without service pack 1. LOG(INFO) << "Windows Version: " << version << ", Service Pack: " << major << "." << minor; if ((version == win_util::WINVERSION_VISTA) || (version == win_util::WINVERSION_SERVER_2003) || (version == win_util::WINVERSION_XP && major >= 1)) { return true; } return false; } void InstallUtil::WriteInstallerResult(bool system_install, installer_util::InstallStatus status, int string_resource_id, const std::wstring* const launch_cmd) { HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; BrowserDistribution* dist = BrowserDistribution::GetDistribution(); std::wstring key = dist->GetStateKey(); int installer_result = (dist->GetInstallReturnCode(status) == 0) ? 0 : 1; scoped_ptr<WorkItemList> install_list(WorkItem::CreateWorkItemList()); install_list->AddCreateRegKeyWorkItem(root, key); install_list->AddSetRegValueWorkItem(root, key, L"InstallerResult", installer_result, true); install_list->AddSetRegValueWorkItem(root, key, L"InstallerError", status, true); if (string_resource_id != 0) { std::wstring msg = installer_util::GetLocalizedString(string_resource_id); install_list->AddSetRegValueWorkItem(root, key, L"InstallerResultUIString", msg, true); } if (launch_cmd != NULL) { install_list->AddSetRegValueWorkItem(root, key, L"InstallerSuccessLaunchCmdLine", *launch_cmd, true); } if (!install_list->Do()) LOG(ERROR) << "Failed to record installer error information in registry."; } bool InstallUtil::IsPerUserInstall(const wchar_t* const exe_path) { wchar_t program_files_path[MAX_PATH] = {0}; if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, SHGFP_TYPE_CURRENT, program_files_path))) { return !StartsWith(exe_path, program_files_path, false); } else { NOTREACHED(); } return true; } <commit_msg>Fix mini_installer failing on Windows 7 (issue 7732).<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. // // See the corresponding header file for description of the functions in this // file. #include "install_util.h" #include <algorithm> #include <shellapi.h> #include <shlobj.h> #include "base/logging.h" #include "base/registry.h" #include "base/string_util.h" #include "base/win_util.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/google_update_constants.h" #include "chrome/installer/util/l10n_string_util.h" #include "chrome/installer/util/work_item_list.h" bool InstallUtil::ExecuteExeAsAdmin(const std::wstring& exe, const std::wstring& params, DWORD* exit_code) { SHELLEXECUTEINFO info = {0}; info.cbSize = sizeof(SHELLEXECUTEINFO); info.fMask = SEE_MASK_NOCLOSEPROCESS; info.lpVerb = L"runas"; info.lpFile = exe.c_str(); info.lpParameters = params.c_str(); info.nShow = SW_SHOW; if (::ShellExecuteEx(&info) == FALSE) return false; ::WaitForSingleObject(info.hProcess, INFINITE); DWORD ret_val = 0; if (!::GetExitCodeProcess(info.hProcess, &ret_val)) return false; if (exit_code) *exit_code = ret_val; return true; } std::wstring InstallUtil::GetChromeUninstallCmd(bool system_install) { HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; BrowserDistribution* dist = BrowserDistribution::GetDistribution(); RegKey key(root, dist->GetUninstallRegPath().c_str()); std::wstring uninstall_cmd; key.ReadValue(installer_util::kUninstallStringField, &uninstall_cmd); return uninstall_cmd; } installer::Version* InstallUtil::GetChromeVersion(bool system_install) { RegKey key; std::wstring version_str; HKEY reg_root = (system_install) ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; BrowserDistribution* dist = BrowserDistribution::GetDistribution(); if (!key.Open(reg_root, dist->GetVersionKey().c_str(), KEY_READ) || !key.ReadValue(google_update::kRegVersionField, &version_str)) { LOG(INFO) << "No existing Chrome install found."; key.Close(); return NULL; } key.Close(); LOG(INFO) << "Existing Chrome version found " << version_str; return installer::Version::GetVersionFromString(version_str); } bool InstallUtil::IsOSSupported() { int major, minor; win_util::WinVersion version = win_util::GetWinVersion(); win_util::GetServicePackLevel(&major, &minor); // We do not support Win2K or older, or XP without service pack 1. LOG(INFO) << "Windows Version: " << version << ", Service Pack: " << major << "." << minor; if ((version > win_util::WINVERSION_XP) || (version == win_util::WINVERSION_XP && major >= 1)) { return true; } return false; } void InstallUtil::WriteInstallerResult(bool system_install, installer_util::InstallStatus status, int string_resource_id, const std::wstring* const launch_cmd) { HKEY root = system_install ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; BrowserDistribution* dist = BrowserDistribution::GetDistribution(); std::wstring key = dist->GetStateKey(); int installer_result = (dist->GetInstallReturnCode(status) == 0) ? 0 : 1; scoped_ptr<WorkItemList> install_list(WorkItem::CreateWorkItemList()); install_list->AddCreateRegKeyWorkItem(root, key); install_list->AddSetRegValueWorkItem(root, key, L"InstallerResult", installer_result, true); install_list->AddSetRegValueWorkItem(root, key, L"InstallerError", status, true); if (string_resource_id != 0) { std::wstring msg = installer_util::GetLocalizedString(string_resource_id); install_list->AddSetRegValueWorkItem(root, key, L"InstallerResultUIString", msg, true); } if (launch_cmd != NULL) { install_list->AddSetRegValueWorkItem(root, key, L"InstallerSuccessLaunchCmdLine", *launch_cmd, true); } if (!install_list->Do()) LOG(ERROR) << "Failed to record installer error information in registry."; } bool InstallUtil::IsPerUserInstall(const wchar_t* const exe_path) { wchar_t program_files_path[MAX_PATH] = {0}; if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES, NULL, SHGFP_TYPE_CURRENT, program_files_path))) { return !StartsWith(exe_path, program_files_path, false); } else { NOTREACHED(); } return true; } <|endoftext|>
<commit_before>#include <SDL2/SDL.h> #include <string> #include "spinner/misc.hpp" #include <exception> #include <stdexcept> #define Assert(expr) AssertMsg(expr, "Assertion failed") #define AssertMsg(expr, msg) { if(!(expr)) throw std::runtime_error(msg); } #define SDLW_Check sdlw::CheckSDLError(__LINE__); #ifdef DEBUG #define AAssert(expr) AAssertMsg(expr, "Assertion failed") #define AAssertMsg(expr, msg) AssertMsg(expr, msg) #define SDLW_ACheck sdlw::CheckSDLError(__LINE__); #else #define AAssert(expr) #define AAssertMsg(expr,msg) #define SDLW_ACheck #endif namespace sdlw { extern SDL_threadID thread_local tls_threadID; void CheckSDLError(int line=-1); //! 実行環境に関する情報を取得 class Spec : public spn::Singleton<Spec> { public: enum Feature : uint32_t { F_3DNow = 0x01, F_AltiVec = 0x02, F_MMX = 0x04, F_RDTSC = 0x08, F_SSE = 0x10, F_SSE2 = 0x11, F_SSE3 = 0x12, F_SSE41 = 0x14, F_SSE42 = 0x18 }; enum class PStatN { Unknown, OnBattery, NoBattery, Charging, Charged }; struct PStat { PStatN state; int seconds, percentage; void output(std::ostream& os) const; }; private: uint32_t _feature; std::string _platform; int _nCacheLine, _nCpu; public: Spec(); const std::string& getPlatform() const; int cpuCacheLineSize() const; int cpuCount() const; bool hasFuture(uint32_t flag) const; PStat powerStatus() const; }; //! SDLのMutexラッパ class Mutex { SDL_mutex* _mutex; public: Mutex(); Mutex(const Mutex& m) = delete; Mutex& operator = (const Mutex& m) = delete; ~Mutex(); bool lock(); bool try_lock(); void unlock(); SDL_mutex* getMutex(); }; //! 再帰対応のスピンロック template <class T> class SpinLock { struct Inner { SpinLock& _src; T* _data; Inner(const Inner&) = delete; Inner& operator = (const Inner&) = delete; Inner(SpinLock& src, T* data): _src(src), _data(data) { _src._lock(); } ~Inner() { unlock(); } T* operator -> () { return _data; } bool valid() const { return _data != nullptr; } void unlock() { if(_data) { _src._unlock(); _data = nullptr; } } }; SDL_atomic_t _atmLock, _atmCount; void _unlock() { if(SDL_AtomicDecRef(&_atmCount) == SDL_TRUE) SDL_AtomicSet(&_atmLock, 0); } T _data; Inner _lock(bool bBlock) { do { bool bSuccess = false; if(SDL_AtomicCAS(&_atmLock, 0, tls_threadID) == 0) bSuccess = true; else if(SDL_AtomicGet(&_atmLock) == tls_threadID) { // 同じスレッドからのロック bSuccess = true; } if(bSuccess) { // ロック成功 SDL_AtomicAddRef(&_atmCount); return Inner(*this, &_data); } } while(bBlock); return Inner(*this, nullptr); } public: SpinLock() { SDL_AtomicSet(&_atmLock, 0); SDL_AtomicSet(&_atmCount, 0); } Inner lock() { return _lock(true); } Inner try_lock() { return _lock(false); } }; // SIG = スレッドに関するシグニチャ template <class SIG> class Thread; template <class RET, class... Args> class Thread<RET (Args...)> { using This = Thread<RET (Args...)>; RET _retVal; SDL_atomic_t _atmInt; SDL_Thread* _thread; std::exception_ptr _eptr; enum Stat { Idle, //!< スレッド開始前 Running, //!< スレッド実行中 Interrupted, //!< 中断要求がされたが、まだスレッドが終了していない Interrupted_End,//!< 中断要求によりスレッドが終了した Error_End, //!< 例外による異常終了 Finished //!< 正常終了 }; SDL_atomic_t _atmStat; SDL_cond *_condC, //!< 子スレッドが開始された事を示す *_condP; //!< 親スレッドがクラス変数にスレッドポインタを格納した事を示す Mutex _mtxC, _mtxP; static int ThreadFunc(void* p) { This* ths = reinterpret_cast<This*>(p); ths->_mtxC.lock(); ths->_mtxP.lock(); SDL_CondBroadcast(ths->_condC); ths->_mtxC.unlock(); // 親スレッドが子スレッド変数をセットするまで待つ SDL_CondWait(ths->_condP, ths->_mtxP.getMutex()); ths->_mtxP.unlock(); // この時点でスレッドのポインタは有効な筈 tls_threadID = SDL_GetThreadID(ths->_thread); Stat stat; try { ths->_retVal = ths->run(); stat = (ths->isInterrupted()) ? Interrupted_End : Finished; } catch(...) { ths->_eptr = std::current_exception(); stat = Error_End; } SDL_AtomicSet(&ths->_atmStat, stat); // SDLの戻り値は使わない return 0; } protected: virtual RET run(Args...) = 0; public: Thread(const Thread& t) = delete; Thread& operator = (const Thread& t) = delete; Thread(): _thread(nullptr), _eptr(nullptr) { _condC = SDL_CreateCond(); _condP = SDL_CreateCond(); // 中断フラグに0をセット SDL_AtomicSet(&_atmInt, 0); SDL_AtomicSet(&_atmStat, Idle); } ~Thread() { // スレッド実行中だったらエラーを出す Assert(!isRunning()) SDL_DestroyCond(_condC); SDL_DestroyCond(_condP); } template <class... Args0> void start(Args0&&... args0) { // 2回以上呼ぶとエラー Assert(SDL_AtomicGet(&_atmStat) == Idle) SDL_AtomicSet(&_atmStat, Running); _mtxC.lock(); // 一旦クラス内部に変数を参照で取っておく SDL_Thread* th = SDL_CreateThread(ThreadFunc, "", this); // 子スレッドが開始されるまで待つ SDL_CondWait(_condC, _mtxC.getMutex()); _mtxC.unlock(); _mtxP.lock(); _thread = th; SDL_CondBroadcast(_condP); _mtxP.unlock(); } Stat getStatus() { return static_cast<Stat>(SDL_AtomicGet(&_atmStat)); } bool isRunning() { Stat stat = getStatus(); return stat==Running || stat==Interrupted; } //! 中断を指示する bool interrupt() { auto ret = SDL_AtomicCAS(&_atmStat, Running, Interrupted); SDL_AtomicSet(&_atmInt, 1); SDLW_ACheck return ret == SDL_TRUE; } //! スレッド内部で中断指示がされているかを確認 bool isInterrupted() { return SDL_AtomicGet(&_atmInt) == 1; } void join() { _mtxP.lock(); if(_thread) { int ret; SDL_WaitThread(_thread, &ret); _thread = nullptr; } _mtxP.unlock(); } bool try_join(uint32_t ms) { _mtxP.lock(); int res = SDL_CondWaitTimeout(_condP, _mtxP.getMutex(), ms); _mtxP.unlock(); SDLW_Check return res == 0; } const RET& getResult() { // まだスレッドが終了して無い時の為にjoinを呼ぶ join(); return _retVal; } }; class Window; using SPWindow = std::shared_ptr<Window>; class GLContext; using SPGLContext = std::shared_ptr<GLContext>; class Window { public: enum class Stat { Minimized, Maximized, Hidden, Fullscreen, Shown }; private: SDL_Window* _window; Stat _stat; Window(SDL_Window* w); void _checkState(); public: static SPWindow CreateWindow(const std::string& title, int w, int h, uint32_t flag=0); static SPWindow CreateWindow(const std::string& title, int x, int y, int w, int h, uint32_t flag=0); ~Window(); void setFullscreen(bool bFull); void setGrab(bool bGrab); void setMaximumSize(int w, int h); void setMinimumSize(int w, int h); void setSize(int w, int h); void setTitle(const std::string& title); void show(bool bShow); void maximize(); void minimize(); void restore(); void setPosition(int x, int y); void raise(); // for logging uint32_t getID() const; Stat getState() const; bool isGrabbed() const; bool isResizable() const; bool hasInputFocus() const; bool hasMouseFocus() const; uint32_t getSDLFlag() const; SDL_Window* getWindow() const; static void EnableScreenSaver(bool bEnable); }; class GLContext { SPWindow _spWindow; SDL_GLContext _ctx; GLContext(const SPWindow& w); public: static SPGLContext CreateContext(const SPWindow& w); ~GLContext(); void makeCurrent(const SPWindow& w); void makeCurrent(); void swapWindow(); static int SetSwapInterval(int n); }; } <commit_msg>SpinLock: カウンタのバグ修正<commit_after>#include <SDL2/SDL.h> #include <string> #include "spinner/misc.hpp" #include <exception> #include <stdexcept> #define Assert(expr) AssertMsg(expr, "Assertion failed") #define AssertMsg(expr, msg) { if(!(expr)) throw std::runtime_error(msg); } #define SDLW_Check sdlw::CheckSDLError(__LINE__); #ifdef DEBUG #define AAssert(expr) AAssertMsg(expr, "Assertion failed") #define AAssertMsg(expr, msg) AssertMsg(expr, msg) #define SDLW_ACheck sdlw::CheckSDLError(__LINE__); #else #define AAssert(expr) #define AAssertMsg(expr,msg) #define SDLW_ACheck #endif namespace sdlw { extern SDL_threadID thread_local tls_threadID; void CheckSDLError(int line=-1); //! 実行環境に関する情報を取得 class Spec : public spn::Singleton<Spec> { public: enum Feature : uint32_t { F_3DNow = 0x01, F_AltiVec = 0x02, F_MMX = 0x04, F_RDTSC = 0x08, F_SSE = 0x10, F_SSE2 = 0x11, F_SSE3 = 0x12, F_SSE41 = 0x14, F_SSE42 = 0x18 }; enum class PStatN { Unknown, OnBattery, NoBattery, Charging, Charged }; struct PStat { PStatN state; int seconds, percentage; void output(std::ostream& os) const; }; private: uint32_t _feature; std::string _platform; int _nCacheLine, _nCpu; public: Spec(); const std::string& getPlatform() const; int cpuCacheLineSize() const; int cpuCount() const; bool hasFuture(uint32_t flag) const; PStat powerStatus() const; }; //! SDLのMutexラッパ class Mutex { SDL_mutex* _mutex; public: Mutex(); Mutex(const Mutex& m) = delete; Mutex& operator = (const Mutex& m) = delete; ~Mutex(); bool lock(); bool try_lock(); void unlock(); SDL_mutex* getMutex(); }; //! 再帰対応のスピンロック template <class T> class SpinLock { struct Inner { SpinLock& _src; T* _data; Inner(const Inner&) = delete; Inner& operator = (const Inner&) = delete; Inner(Inner&& n): _src(n._src), _data(n._data) {} Inner(SpinLock& src, T* data): _src(src), _data(data) {} ~Inner() { unlock(); } T& operator * () { return *_data; } T* operator -> () { return _data; } bool valid() const { return _data != nullptr; } void unlock() { if(_data) { _src._unlock(); _data = nullptr; } } }; SDL_atomic_t _atmLock, _atmCount; void _unlock() { if(SDL_AtomicDecRef(&_atmCount) == SDL_TRUE) SDL_AtomicSet(&_atmLock, 0); } T _data; Inner _lock(bool bBlock) { do { bool bSuccess = false; if(SDL_AtomicCAS(&_atmLock, 0, tls_threadID) == SDL_TRUE) bSuccess = true; else if(SDL_AtomicGet(&_atmLock) == tls_threadID) { // 同じスレッドからのロック bSuccess = true; } if(bSuccess) { // ロック成功 SDL_AtomicAdd(&_atmCount, 1); return Inner(*this, &_data); } } while(bBlock); return Inner(*this, nullptr); } public: SpinLock() { SDL_AtomicSet(&_atmLock, 0); SDL_AtomicSet(&_atmCount, 0); } Inner lock() { return _lock(true); } Inner try_lock() { return _lock(false); } }; // SIG = スレッドに関するシグニチャ template <class SIG> class Thread; template <class RET, class... Args> class Thread<RET (Args...)> { using This = Thread<RET (Args...)>; RET _retVal; SDL_atomic_t _atmInt; SDL_Thread* _thread; std::exception_ptr _eptr; enum Stat { Idle, //!< スレッド開始前 Running, //!< スレッド実行中 Interrupted, //!< 中断要求がされたが、まだスレッドが終了していない Interrupted_End,//!< 中断要求によりスレッドが終了した Error_End, //!< 例外による異常終了 Finished //!< 正常終了 }; SDL_atomic_t _atmStat; SDL_cond *_condC, //!< 子スレッドが開始された事を示す *_condP; //!< 親スレッドがクラス変数にスレッドポインタを格納した事を示す Mutex _mtxC, _mtxP; static int ThreadFunc(void* p) { This* ths = reinterpret_cast<This*>(p); ths->_mtxC.lock(); ths->_mtxP.lock(); SDL_CondBroadcast(ths->_condC); ths->_mtxC.unlock(); // 親スレッドが子スレッド変数をセットするまで待つ SDL_CondWait(ths->_condP, ths->_mtxP.getMutex()); ths->_mtxP.unlock(); // この時点でスレッドのポインタは有効な筈 tls_threadID = SDL_GetThreadID(ths->_thread); Stat stat; try { ths->_retVal = ths->run(); stat = (ths->isInterrupted()) ? Interrupted_End : Finished; } catch(...) { ths->_eptr = std::current_exception(); stat = Error_End; } SDL_AtomicSet(&ths->_atmStat, stat); // SDLの戻り値は使わない return 0; } protected: virtual RET run(Args...) = 0; public: Thread(const Thread& t) = delete; Thread& operator = (const Thread& t) = delete; Thread(): _thread(nullptr), _eptr(nullptr) { _condC = SDL_CreateCond(); _condP = SDL_CreateCond(); // 中断フラグに0をセット SDL_AtomicSet(&_atmInt, 0); SDL_AtomicSet(&_atmStat, Idle); } ~Thread() { // スレッド実行中だったらエラーを出す Assert(!isRunning()) SDL_DestroyCond(_condC); SDL_DestroyCond(_condP); } template <class... Args0> void start(Args0&&... args0) { // 2回以上呼ぶとエラー Assert(SDL_AtomicGet(&_atmStat) == Idle) SDL_AtomicSet(&_atmStat, Running); _mtxC.lock(); // 一旦クラス内部に変数を参照で取っておく SDL_Thread* th = SDL_CreateThread(ThreadFunc, "", this); // 子スレッドが開始されるまで待つ SDL_CondWait(_condC, _mtxC.getMutex()); _mtxC.unlock(); _mtxP.lock(); _thread = th; SDL_CondBroadcast(_condP); _mtxP.unlock(); } Stat getStatus() { return static_cast<Stat>(SDL_AtomicGet(&_atmStat)); } bool isRunning() { Stat stat = getStatus(); return stat==Running || stat==Interrupted; } //! 中断を指示する bool interrupt() { auto ret = SDL_AtomicCAS(&_atmStat, Running, Interrupted); SDL_AtomicSet(&_atmInt, 1); SDLW_ACheck return ret == SDL_TRUE; } //! スレッド内部で中断指示がされているかを確認 bool isInterrupted() { return SDL_AtomicGet(&_atmInt) == 1; } void join() { _mtxP.lock(); if(_thread) { int ret; SDL_WaitThread(_thread, &ret); _thread = nullptr; } _mtxP.unlock(); } bool try_join(uint32_t ms) { _mtxP.lock(); int res = SDL_CondWaitTimeout(_condP, _mtxP.getMutex(), ms); _mtxP.unlock(); SDLW_Check return res == 0; } const RET& getResult() { // まだスレッドが終了して無い時の為にjoinを呼ぶ join(); return _retVal; } }; class Window; using SPWindow = std::shared_ptr<Window>; class GLContext; using SPGLContext = std::shared_ptr<GLContext>; class Window { public: enum class Stat { Minimized, Maximized, Hidden, Fullscreen, Shown }; private: SDL_Window* _window; Stat _stat; Window(SDL_Window* w); void _checkState(); public: static SPWindow CreateWindow(const std::string& title, int w, int h, uint32_t flag=0); static SPWindow CreateWindow(const std::string& title, int x, int y, int w, int h, uint32_t flag=0); ~Window(); void setFullscreen(bool bFull); void setGrab(bool bGrab); void setMaximumSize(int w, int h); void setMinimumSize(int w, int h); void setSize(int w, int h); void setTitle(const std::string& title); void show(bool bShow); void maximize(); void minimize(); void restore(); void setPosition(int x, int y); void raise(); // for logging uint32_t getID() const; Stat getState() const; bool isGrabbed() const; bool isResizable() const; bool hasInputFocus() const; bool hasMouseFocus() const; uint32_t getSDLFlag() const; SDL_Window* getWindow() const; static void EnableScreenSaver(bool bEnable); }; class GLContext { SPWindow _spWindow; SDL_GLContext _ctx; GLContext(const SPWindow& w); public: static SPGLContext CreateContext(const SPWindow& w); ~GLContext(); void makeCurrent(const SPWindow& w); void makeCurrent(); void swapWindow(); static int SetSwapInterval(int n); }; } <|endoftext|>
<commit_before>#include "MyArea.h" #include "figuras/Arco.h" #include "figuras/Circulo.h" #include "figuras/Elipse.h" #include "figuras/Quadrado.h" #include "figuras/Retangulo.h" #include <cstdlib> #include <ctime> #include <iostream> using namespace Gtk; using namespace std; MyArea::MyArea() { tempo = false; srand( time( NULL ) ); add_events( Gdk::BUTTON_PRESS_MASK ); int timeOutValue = 1000; // 1000 in ms (1.0 sec) sigc::slot<bool> mySlot = sigc::mem_fun( *this, &MyArea::on_timeout ); Glib::signal_timeout().connect( mySlot, timeOutValue ); } bool MyArea::on_timeout() { tempo = true; cout << "Tempo" << endl; queue_draw(); return true; } MyArea::~MyArea() { cout << "Chamando destrutor" << '\n'; for( Figura *figura : figuras ) { delete figura; } } Ponto MyArea::randPosition() const { Gtk::Allocation allocation = get_allocation(); const int width = allocation.get_width(); const int height = allocation.get_height(); int x = rand() % width; int y = rand() % height; return Ponto( x, y ); } bool MyArea::on_draw( const Cairo::RefPtr<Cairo::Context> &cr ) { for( vector<Figura *>::iterator it = figuras.begin(); it != figuras.end(); it++ ) { if( tempo ) { ( *it )->setPosition( randPosition() ); } cr->save(); ( *it )->draw( cr ); cr->stroke(); cr->restore(); } tempo = false; return true; } int sortearTipoFigura( const int quantidadeDeTipo ) { return rand() % quantidadeDeTipo; } bool MyArea::on_button_press_event( GdkEventButton *event ) { cout << "Clicou" << '\n'; if( ( event->type == GDK_BUTTON_PRESS ) && ( event->button == 1 ) ) { tipoFigura = sortearTipoFigura( 5 ); // 5 é qtd de tipos de figuras switch( tipoFigura ) { case 0: addFigura( new Circulo( event->x, event->y, 2 ) ); break; case 1: addFigura( new Elipse( event->x, event->y, 2 ) ); break; case 2: addFigura( new Quadrado( event->x, event->y, 2 ) ); break; case 3: addFigura( new Retangulo( event->x, event->y, 1, 2 ) ); break; case 4: addFigura( new Arco( event->x, event->y, 4 ) ); break; default: cout << "Erro" << '\n'; } queue_draw(); } return true; } void MyArea::addFigura( Figura *figura ) { figuras.push_back( figura ); } <commit_msg>Organização do código<commit_after>#include "MyArea.h" #include "figuras/Arco.h" #include "figuras/Circulo.h" #include "figuras/Elipse.h" #include "figuras/Quadrado.h" #include "figuras/Retangulo.h" #include <cstdlib> #include <ctime> #include <iostream> using namespace Gtk; using namespace std; MyArea::MyArea() { tempo = false; int timeOutValue = 1000; // 1000 in ms (1.0 sec) srand( time( NULL ) ); sigc::slot<bool> mySlot = sigc::mem_fun( *this, &MyArea::on_timeout ); add_events( Gdk::BUTTON_PRESS_MASK ); Glib::signal_timeout().connect( mySlot, timeOutValue ); } bool MyArea::on_timeout() { tempo = true; cout << "Tempo" << endl; queue_draw(); return true; } MyArea::~MyArea() { cout << "Chamando destrutor" << '\n'; for( Figura *figura : figuras ) { delete figura; } } Ponto MyArea::randPosition() const { Gtk::Allocation allocation = get_allocation(); const int width = allocation.get_width(); const int height = allocation.get_height(); int x = rand() % width; int y = rand() % height; return Ponto( x, y ); } bool MyArea::on_draw( const Cairo::RefPtr<Cairo::Context> &cr ) { for( vector<Figura *>::iterator it = figuras.begin(); it != figuras.end(); it++ ) { if( tempo ) { ( *it )->setPosition( randPosition() ); } cr->save(); ( *it )->draw( cr ); cr->stroke(); cr->restore(); } tempo = false; return true; } int sortearTipoFigura( const int quantidadeDeTipo ) { return rand() % quantidadeDeTipo; } bool MyArea::on_button_press_event( GdkEventButton *event ) { cout << "Clicou" << '\n'; if( ( event->type == GDK_BUTTON_PRESS ) && ( event->button == 1 ) ) { tipoFigura = sortearTipoFigura( 5 ); // 5 é qtd de tipos de figuras switch( tipoFigura ) { case 0: addFigura( new Circulo( event->x, event->y, 2 ) ); break; case 1: addFigura( new Elipse( event->x, event->y, 2 ) ); break; case 2: addFigura( new Quadrado( event->x, event->y, 2 ) ); break; case 3: addFigura( new Retangulo( event->x, event->y, 1, 2 ) ); break; case 4: addFigura( new Arco( event->x, event->y, 4 ) ); break; default: cout << "Erro" << '\n'; } queue_draw(); } return true; } void MyArea::addFigura( Figura *figura ) { figuras.push_back( figura ); } <|endoftext|>
<commit_before>#include <Energia.h> #include "inc/hw_gpio.h" #include "driverlib/rom_map.h" #include "driverlib/prcm.h" #include "driverlib/interrupt.h" #include "driverlib/systick.h" #include <driverlib/utils.h> #include "inc/hw_hib1p2.h" #include "inc/hw_hib3p3.h" extern void (* const g_pfnVectors[])(void); extern void setup1(); extern void foo(); void MCUInit(void) { unsigned long ulRegVal; // // DIG DCDC NFET SEL and COT mode disable // HWREG(0x4402F010) = 0x30031820; HWREG(0x4402F00C) = 0x04000000; UtilsDelay(32000); // // ANA DCDC clock config // HWREG(0x4402F11C) = 0x099; HWREG(0x4402F11C) = 0x0AA; HWREG(0x4402F11C) = 0x1AA; // // PA DCDC clock config // HWREG(0x4402F124) = 0x099; HWREG(0x4402F124) = 0x0AA; HWREG(0x4402F124) = 0x1AA; // // Enable RTC // if(MAP_PRCMSysResetCauseGet()== PRCM_POWER_ON) { HWREG(0x4402F804) = 0x1; } // // TD Flash timing configurations in case of MCU WDT reset // if((HWREG(0x4402D00C) & 0xFF) == 0x00000005) { HWREG(0x400F707C) |= 0x01840082; HWREG(0x400F70C4)= 0x1; HWREG(0x400F70C4)= 0x0; } // // JTAG override for I2C in SWD mode // if(((HWREG(0x4402F0C8) & 0xFF) == 0x2)) { MAP_PinModeSet(PIN_19,PIN_MODE_2); MAP_PinModeSet(PIN_20,PIN_MODE_2); HWREG(0x4402E184) |= 0x1; } // // Enable uDMA // PRCMPeripheralClkEnable(PRCM_UDMA,PRCM_RUN_MODE_CLK); // // Reset uDMA // PRCMPeripheralReset(PRCM_UDMA); // // Disable uDMA // PRCMPeripheralClkDisable(PRCM_UDMA,PRCM_RUN_MODE_CLK); } int main(void) { IntVTableBaseSet((unsigned long)&g_pfnVectors[0]); MAP_PRCMPeripheralClkEnable(PRCM_GPIOA0, PRCM_RUN_MODE_CLK); MAP_PRCMPeripheralClkEnable(PRCM_GPIOA1, PRCM_RUN_MODE_CLK); MAP_PRCMPeripheralClkEnable(PRCM_GPIOA2, PRCM_RUN_MODE_CLK); MAP_PRCMPeripheralClkEnable(PRCM_GPIOA3, PRCM_RUN_MODE_CLK); MAP_IntMasterEnable(); MCUInit(); MAP_SysTickIntEnable(); MAP_SysTickPeriodSet(F_CPU / 1000); MAP_SysTickEnable(); setup(); for (;;) { loop(); if (serialEventRun) serialEventRun(); } } <commit_msg>Change CPU init to use driverlib internal func<commit_after>#include <Energia.h> #include "inc/hw_gpio.h" #include "driverlib/rom_map.h" #include "driverlib/prcm.h" #include "driverlib/interrupt.h" #include "driverlib/systick.h" #include <driverlib/utils.h> #include "inc/hw_hib1p2.h" #include "inc/hw_hib3p3.h" extern void (* const g_pfnVectors[])(void); int main(void) { IntVTableBaseSet((unsigned long)&g_pfnVectors[0]); MAP_PRCMPeripheralClkEnable(PRCM_GPIOA0, PRCM_RUN_MODE_CLK); MAP_PRCMPeripheralClkEnable(PRCM_GPIOA1, PRCM_RUN_MODE_CLK); MAP_PRCMPeripheralClkEnable(PRCM_GPIOA2, PRCM_RUN_MODE_CLK); MAP_PRCMPeripheralClkEnable(PRCM_GPIOA3, PRCM_RUN_MODE_CLK); MAP_IntMasterEnable(); PRCMCC3200MCUInit(); MAP_SysTickIntEnable(); MAP_SysTickPeriodSet(F_CPU / 1000); MAP_SysTickEnable(); setup(); for (;;) { loop(); if (serialEventRun) serialEventRun(); } } <|endoftext|>
<commit_before>/** * Copyright 2017 Shusheng Shao <iblackangel@163.com> * * 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 <mpl/mstring.h> #ifdef _MSC_VER # pragma warning (push) # pragma warning (disable: 4996) #endif MPL_BEGIN_NAMESPACE std::string toXString(const char *fmt, ...) { std::string buffer; va_list vargs; va_start(vargs, fmt); int len = vsnprintf(NULL, 0, fmt, vargs); buffer.resize(len); va_start(vargs, fmt); vsnprintf(&buffer[0], len + 1, fmt, vargs); va_end(vargs); return buffer; } std::string hex2str(const uint8_t *data, size_t len) { std::string buffer; char buf[3] = {0x00}; for (size_t m = 0; m < len; ++m) { snprintf (buf, sizeof(buf), "%02X", data[m]); buf[2] = '\0'; buffer += buf; buffer += " "; } if (buffer.size() > 0) { buffer.erase(buffer.begin() + (buffer.size() - 1)); } return buffer; } std::string toString(int val) { return toXString("%d", val); } std::string toString(unsigned val) { return toXString("%u", val); } std::string toString(long val) { return toXString("%ld", val); } std::string toString(unsigned long val) { return toXString("%lu", val); } std::string toString(long long val) { return toXString("%lld", val); } std::string toString(unsigned long long val) { return toXString("%llu", val); } std::string toString(float val) { return toXString("%f", val); } std::string toString(double val) { return toXString("%f", val); } std::string toString(long double val) { return toXString("%Lf", val); } std::string toUTF8(const std::string &str) { #if defined(_MSC_VER) || defined(M_OS_WIN) // convert GBK to Unicode int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0); wchar_t *strUnicode = new wchar_t[len]; wmemset(strUnicode, 0, len); MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, strUnicode, len); // convert Unicode to UTF-8 len = WideCharToMultiByte(CP_UTF8, 0, strUnicode, -1, NULL, 0, NULL, NULL); char * strUtf8 = new char[len]; WideCharToMultiByte(CP_UTF8, 0, strUnicode, -1, strUtf8, len, NULL, NULL); std::string strOut(strUtf8); // strTemp is encoding UTF-8 delete[]strUnicode; delete[]strUtf8; strUnicode = NULL; strUtf8 = NULL; return strOut; #else char *gbk = new char[str.size() + 1]; size_t inbytes = str.size(); strcpy(gbk, str.c_str()); char *utf8 = new char[str.size() * 2 + 1]; // twice of gbk size_t outbytes = str.size() * 2; char *inptr = gbk; char *outptr = utf8; // iconv_open iconv_t cd = iconv_open("UTF-8", "GB18030"); if (cd == (iconv_t)-1) { log_error("iconv_open failed: %s", error().c_str()); delete gbk; delete utf8; return std::string(); } // iconv size_t res = iconv(cd, &inptr, &inbytes, &outptr, &outbytes); if (res == -1) { log_error("iconv failed: %s", error().c_str()); iconv_close(cd); delete gbk; delete utf8; return std::string(); } // iconv_close std::string outstr = utf8; iconv_close(cd); delete gbk; delete utf8; return outstr; #endif } std::string toGBK(const std::string &str) { #if defined(_MSC_VER) || defined(M_OS_WIN) // convert UTF-8 to Unicode int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0); unsigned short *wszGBK = new unsigned short[len + 1]; memset(wszGBK, 0, len * 2 + 2); MultiByteToWideChar(CP_UTF8, 0, (LPCTSTR)str.c_str(), -1, (LPWSTR)wszGBK, len); // convert UTF-8 to Unicode len = WideCharToMultiByte(CP_ACP, 0, (LPCWCH)wszGBK, -1, NULL, 0, NULL, NULL); char *szGBK = new char[len + 1]; memset(szGBK, 0, len + 1); WideCharToMultiByte(CP_ACP, 0, (LPCWCH)wszGBK, -1, szGBK, len, NULL, NULL); std::string strTemp(szGBK); delete[]szGBK; delete[]wszGBK; return strTemp; #else char *utf8 = new char[str.size() + 1]; size_t inbytes = str.size(); strcpy(utf8, str.c_str()); char *gbk = new char[str.size() * 2 + 1]; // twice size size_t outbytes = str.size() * 2; char *inptr = utf8; char *outptr = gbk; // iconv_open iconv_t cd = iconv_open("GB18030", "UTF-8"); if (cd == (iconv_t)-1) { log_error("iconv_open failed: %s", error().c_str()); delete gbk; delete utf8; return std::string(); } // iconv size_t res = iconv(cd, &inptr, &inbytes, &outptr, &outbytes); if (res == -1) { log_error("iconv failed: %s", error().c_str()); iconv_close(cd); delete gbk; delete utf8; return std::string(); } // iconv_close std::string outstr = gbk; iconv_close(cd); delete gbk; delete utf8; return outstr; #endif } MString::MString() { } MString::MString(const std::string &str) : std::string(str) { } MString::MString(const char *s) : std::string(s) { } MString::~MString() { } std::string& MString::replace(char before, char after) { size_type pos = rfind(before); while (pos != npos) { std::string::replace(pos, 1, 1, after); pos = rfind(before); } return *this; } std::string& MString::replace(const std::string &before, const std::string &after) { size_type pos = rfind(before); while (pos != npos) { std::string::replace(pos, before.size(), after); pos = rfind(before); } return *this; } MPL_END_NAMESPACE #ifdef _MSC_VER # pragma warning (pop) #endif <commit_msg>update new revision<commit_after>/** * Copyright 2017 Shusheng Shao <iblackangel@163.com> * * 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 <mpl/mstring.h> #ifdef _MSC_VER # pragma warning (push) # pragma warning (disable: 4996) #endif MPL_BEGIN_NAMESPACE std::string toXString(const char *fmt, ...) { std::string buffer; va_list vargs; va_start(vargs, fmt); int len = vsnprintf(NULL, 0, fmt, vargs); buffer.resize(len); va_start(vargs, fmt); vsnprintf(&buffer[0], len + 1, fmt, vargs); va_end(vargs); return buffer; } std::string hex2str(const uint8_t *data, size_t len) { std::string buffer; char buf[3] = {0x00}; for (size_t m = 0; m < len; ++m) { snprintf (buf, sizeof(buf), "%02X", data[m]); buf[2] = '\0'; buffer += buf; buffer += " "; } if (buffer.size() > 0) { buffer.erase(buffer.begin() + (buffer.size() - 1)); } return buffer; } std::string toString(int val) { return toXString("%d", val); } std::string toString(unsigned val) { return toXString("%u", val); } std::string toString(long val) { return toXString("%ld", val); } std::string toString(unsigned long val) { return toXString("%lu", val); } std::string toString(long long val) { return toXString("%lld", val); } std::string toString(unsigned long long val) { return toXString("%llu", val); } std::string toString(float val) { return toXString("%f", val); } std::string toString(double val) { return toXString("%f", val); } std::string toString(long double val) { return toXString("%Lf", val); } std::string toUTF8(const std::string &str) { #if defined(_MSC_VER) || defined(M_OS_WIN) // convert GBK to Unicode int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, NULL, 0); wchar_t *strUnicode = new wchar_t[len]; wmemset(strUnicode, 0, len); MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, strUnicode, len); // convert Unicode to UTF-8 len = WideCharToMultiByte(CP_UTF8, 0, strUnicode, -1, NULL, 0, NULL, NULL); char * strUtf8 = new char[len]; WideCharToMultiByte(CP_UTF8, 0, strUnicode, -1, strUtf8, len, NULL, NULL); std::string strOut(strUtf8); // strTemp is encoding UTF-8 delete[]strUnicode; delete[]strUtf8; strUnicode = NULL; strUtf8 = NULL; return strOut; #elif defined(HAVE_ICONV_H) char *gbk = new char[str.size() + 1]; size_t inbytes = str.size(); strcpy(gbk, str.c_str()); char *utf8 = new char[str.size() * 2 + 1]; // twice of gbk size_t outbytes = str.size() * 2; char *inptr = gbk; char *outptr = utf8; // iconv_open iconv_t cd = iconv_open("UTF-8", "GB18030"); if (cd == (iconv_t)-1) { log_error("iconv_open failed: %s", error().c_str()); delete gbk; delete utf8; return std::string(); } // iconv size_t res = iconv(cd, &inptr, &inbytes, &outptr, &outbytes); if (res == -1) { log_error("iconv failed: %s", error().c_str()); iconv_close(cd); delete gbk; delete utf8; return std::string(); } // iconv_close std::string outstr = utf8; iconv_close(cd); delete gbk; delete utf8; return outstr; #else return str; #endif } std::string toGBK(const std::string &str) { #if defined(_MSC_VER) || defined(M_OS_WIN) // convert UTF-8 to Unicode int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0); unsigned short *wszGBK = new unsigned short[len + 1]; memset(wszGBK, 0, len * 2 + 2); MultiByteToWideChar(CP_UTF8, 0, (LPCTSTR)str.c_str(), -1, (LPWSTR)wszGBK, len); // convert UTF-8 to Unicode len = WideCharToMultiByte(CP_ACP, 0, (LPCWCH)wszGBK, -1, NULL, 0, NULL, NULL); char *szGBK = new char[len + 1]; memset(szGBK, 0, len + 1); WideCharToMultiByte(CP_ACP, 0, (LPCWCH)wszGBK, -1, szGBK, len, NULL, NULL); std::string strTemp(szGBK); delete[]szGBK; delete[]wszGBK; return strTemp; #elif defined(HAVE_ICONV_H) char *utf8 = new char[str.size() + 1]; size_t inbytes = str.size(); strcpy(utf8, str.c_str()); char *gbk = new char[str.size() * 2 + 1]; // twice size size_t outbytes = str.size() * 2; char *inptr = utf8; char *outptr = gbk; // iconv_open iconv_t cd = iconv_open("GB18030", "UTF-8"); if (cd == (iconv_t)-1) { log_error("iconv_open failed: %s", error().c_str()); delete gbk; delete utf8; return std::string(); } // iconv size_t res = iconv(cd, &inptr, &inbytes, &outptr, &outbytes); if (res == -1) { log_error("iconv failed: %s", error().c_str()); iconv_close(cd); delete gbk; delete utf8; return std::string(); } // iconv_close std::string outstr = gbk; iconv_close(cd); delete gbk; delete utf8; return outstr; #else return str; #endif } MString::MString() { } MString::MString(const std::string &str) : std::string(str) { } MString::MString(const char *s) : std::string(s) { } MString::~MString() { } std::string& MString::replace(char before, char after) { size_type pos = rfind(before); while (pos != npos) { std::string::replace(pos, 1, 1, after); pos = rfind(before); } return *this; } std::string& MString::replace(const std::string &before, const std::string &after) { size_type pos = rfind(before); while (pos != npos) { std::string::replace(pos, before.size(), after); pos = rfind(before); } return *this; } MPL_END_NAMESPACE #ifdef _MSC_VER # pragma warning (pop) #endif <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "VTKOutput.h" #include "libmesh/vtk_io.h" #include "libmesh/equation_systems.h" #ifdef LIBMESH_HAVE_VTK registerMooseObjectAliased("MooseApp", VTKOutput, "VTK"); #endif template <> InputParameters validParams<VTKOutput>() { InputParameters params = validParams<OversampleOutput>(); // Set default padding to 3 params.set<unsigned int>("padding") = 3; // Add binary toggle params.addParam<bool>("binary", false, "Set VTK files to output in binary format"); params.addParamNamesToGroup("binary", "Advanced"); return params; } VTKOutput::VTKOutput(const InputParameters & parameters) : OversampleOutput(parameters), _binary(getParam<bool>("binary")) { } void VTKOutput::output(const ExecFlagType & /*type*/) { #ifdef LIBMESH_HAVE_VTK /// Create VTKIO object VTKIO vtk(_es_ptr->get_mesh()); // Set the comppression vtk.set_compression(_binary); // Write the data vtk.write_equation_systems(filename(), *_es_ptr); _file_num++; #else mooseError("libMesh not configured with VTK"); #endif } std::string VTKOutput::filename() { // Append the .e extension on the base file name std::ostringstream output; output << _file_base; // In serial, add the _00x.vtk extension. // In parallel, add the _00x.pvtu extension. std::string ext = (n_processors() == 1) ? ".vtk" : ".pvtu"; output << "_" << std::setw(_padding) << std::setfill('0') << std::right << _file_num << ext; // Return the filename return output.str(); } <commit_msg>Registered VTK even if LIBMESH_HAVE_VTK is false<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "VTKOutput.h" #include "libmesh/vtk_io.h" #include "libmesh/equation_systems.h" registerMooseObjectAliased("MooseApp", VTKOutput, "VTK"); template <> InputParameters validParams<VTKOutput>() { InputParameters params = validParams<OversampleOutput>(); // Set default padding to 3 params.set<unsigned int>("padding") = 3; // Add binary toggle params.addParam<bool>("binary", false, "Set VTK files to output in binary format"); params.addParamNamesToGroup("binary", "Advanced"); return params; } VTKOutput::VTKOutput(const InputParameters & parameters) : OversampleOutput(parameters), _binary(getParam<bool>("binary")) { #ifndef LIBMESH_HAVE_VTK mooseError("VTK output was requested, but libMesh was not configured with VTK. To fix this, you " "must reconfigure libMesh to use VTK."); #endif } void VTKOutput::output(const ExecFlagType & /*type*/) { #ifdef LIBMESH_HAVE_VTK /// Create VTKIO object VTKIO vtk(_es_ptr->get_mesh()); // Set the comppression vtk.set_compression(_binary); // Write the data vtk.write_equation_systems(filename(), *_es_ptr); _file_num++; #endif } std::string VTKOutput::filename() { // Append the .e extension on the base file name std::ostringstream output; output << _file_base; // In serial, add the _00x.vtk extension. // In parallel, add the _00x.pvtu extension. std::string ext = (n_processors() == 1) ? ".vtk" : ".pvtu"; output << "_" << std::setw(_padding) << std::setfill('0') << std::right << _file_num << ext; // Return the filename return output.str(); } <|endoftext|>
<commit_before>#include <kernel/ext2.h> #include <kernel/ata.h> #include <kernel/panic.h> Ext2::Ext2(Pager *pager, uint32_t lba) : pager(pager), lba(lba) { ata_pio_read(lba + 1024 / 512, 2, &this->superblock); if(this->superblock.base.signature != SUPERBLOCK_SIGNATURE) { kernel_panic("invalid ext2 superblock signature"); } } uint32_t Ext2::GetBlockSize(void) { return 1024u << this->superblock.base.block_shift; } uint32_t Ext2::GetBlockAddr(uint32_t block_id) { return block_id * this->GetBlockSize(); } uint32_t Ext2::GetInodeAddr(uint32_t inode_id) { uint32_t group_id = (inode_id - 1) / this->superblock.base.group_inode_count; GroupDesc gd = this->GetGroupDesc(group_id); uint32_t index = (inode_id - 1) % this->superblock.base.group_inode_count; return gd.inode_table_addr * this->GetBlockSize() + index * sizeof(Inode); } uint32_t Ext2::GetGroupDescAddr(uint32_t group_id) { uint32_t block_id = this->superblock.base.superblock_id + 1; return this->GetBlockAddr(block_id) + group_id * sizeof(GroupDesc); } #include <kernel/itoa.h> uint32_t Ext2::GetInodeBlockAddr(Inode inode, uint32_t block_ptr_id) { uint32_t block_size = this->GetBlockSize(); uint32_t block_num_ptrs = block_size / sizeof(uint32_t); uint32_t block_addr; if(block_ptr_id < 12) { block_addr = this->GetBlockAddr(inode.block_ptr[block_ptr_id]); } else if(block_ptr_id < 12 + block_num_ptrs) { uint32_t singly_addr = this->GetBlockAddr(inode.block_ptr_singly); uint32_t singly_offset = (block_ptr_id - 12) * sizeof(uint32_t); ata_pio_read_bytes(this->lba * 512 + singly_addr + singly_offset, &block_addr); } else { kernel_panic("doubly indirect ptrs not implemented yet"); } return block_addr; } Ext2::GroupDesc Ext2::GetGroupDesc(uint32_t group_id) { uint32_t offset = this->GetGroupDescAddr(group_id); GroupDesc gd; ata_pio_read_bytes(this->lba * 512 + offset, &gd); return gd; } Maybe<Ext2::Inode> Ext2::GetInode(uint32_t inode_id) { uint32_t inode_addr = this->GetInodeAddr(inode_id); Inode inode; ata_pio_read_bytes(this->lba * 512 + inode_addr, &inode); return Maybe<Inode>(inode); } Maybe<Ext2::Inode> Ext2::GetInode(Inode &pwd, const char *name) { // XXX: this assumes all dir entries will fit in a single block, which is bad auto mDirent = this->GetDirectoryEntry(pwd.block_ptr[0], name); if(mDirent.IsNothing()) { return Maybe<Inode>(); } else { return this->GetInode(mDirent.FromJust().inode_id); } } Maybe<Ext2::Inode> Ext2::GetInode(size_t count, const char *paths[]) { auto mRoot = this->GetInode(ROOT_INODE); if(mRoot.IsNothing()) { return Maybe<Inode>(); } Inode ref = mRoot.FromJust(); for(size_t i = 0; i < count; ++i) { auto mRef = this->GetInode(ref, paths[i]); if(mRef.IsNothing()) { return Maybe<Inode>(); } ref = mRef.FromJust(); } return ref; } Maybe<Ext2::DirectoryEntry> Ext2::GetDirectoryEntry(uint32_t block_id, const char *name) { uint32_t block_size = this->GetBlockSize(); uint32_t block_addr = this->GetBlockAddr(block_id); // XXX: this assumes a block is 1024 bytes, which is very bad if it's not char buffer[1024]; ata_pio_read(this->lba + block_addr / 512, 2, &buffer); DirectoryEntry *dirent; for(size_t offset = 0; offset < block_size; offset += dirent->size) { dirent = reinterpret_cast<DirectoryEntry *>(&buffer[offset]); if(dirent->inode_id == 0) { break; } bool match = true; for(size_t n = 0; n < dirent->len; ++n) { if(buffer[offset + sizeof(DirectoryEntry) + n] != name[n]) { match = false; break; } } if(match) { return Maybe<DirectoryEntry>(*dirent); } } return Maybe<DirectoryEntry>(); } #include <kernel/screen.h> void Ext2::ReadInode(Inode inode, uint32_t offset, size_t count, char *ptr) { uint32_t block_size = this->GetBlockSize(); size_t offset_end = offset + count; size_t block_ptr_begin = offset / block_size; size_t block_ptr_end = offset_end / block_size + (offset_end % block_size != 0) + 1; size_t n = 0; size_t off = offset % block_size; for(size_t b = block_ptr_begin; b < block_ptr_end; ++b) { uint32_t block_ptr = this->GetInodeBlockAddr(inode, b); char buffer[1024]; // XXX: assuming block size is 1024 again ata_pio_read(this->lba + block_ptr / 512, block_size / 512, &buffer); while(off < block_size && n < count) { ptr[n++] = buffer[off++]; } off = 0; } } <commit_msg>Fix ext2 block index=>id lookups<commit_after>#include <kernel/ext2.h> #include <kernel/ata.h> #include <kernel/panic.h> Ext2::Ext2(Pager *pager, uint32_t lba) : pager(pager), lba(lba) { ata_pio_read(lba + 1024 / 512, 2, &this->superblock); if(this->superblock.base.signature != SUPERBLOCK_SIGNATURE) { kernel_panic("invalid ext2 superblock signature"); } } uint32_t Ext2::GetBlockSize(void) { return 1024u << this->superblock.base.block_shift; } uint32_t Ext2::GetBlockAddr(uint32_t block_id) { return block_id * this->GetBlockSize(); } uint32_t Ext2::GetInodeAddr(uint32_t inode_id) { uint32_t group_id = (inode_id - 1) / this->superblock.base.group_inode_count; GroupDesc gd = this->GetGroupDesc(group_id); uint32_t index = (inode_id - 1) % this->superblock.base.group_inode_count; return gd.inode_table_addr * this->GetBlockSize() + index * sizeof(Inode); } uint32_t Ext2::GetGroupDescAddr(uint32_t group_id) { uint32_t block_id = this->superblock.base.superblock_id + 1; return this->GetBlockAddr(block_id) + group_id * sizeof(GroupDesc); } uint32_t Ext2::GetInodeBlockAddr(Inode inode, uint32_t block_index) { uint32_t block_size = this->GetBlockSize(); uint32_t block_num_ptrs = block_size / sizeof(uint32_t); uint32_t block_id; if(block_index < 12) { block_id = inode.block_ptr[block_index]; } else if(block_index - 12 < block_num_ptrs) { uint32_t addr = this->GetBlockAddr(inode.block_ptr_singly); uint32_t offset = (block_index - 12) * sizeof(uint32_t); ata_pio_read_bytes(this->lba * 512 + addr + offset, &block_id); } else { kernel_panic("doubly indirect ptrs not implemented yet"); } return this->GetBlockAddr(block_id); } Ext2::GroupDesc Ext2::GetGroupDesc(uint32_t group_id) { uint32_t offset = this->GetGroupDescAddr(group_id); GroupDesc gd; ata_pio_read_bytes(this->lba * 512 + offset, &gd); return gd; } Maybe<Ext2::Inode> Ext2::GetInode(uint32_t inode_id) { uint32_t inode_addr = this->GetInodeAddr(inode_id); Inode inode; ata_pio_read_bytes(this->lba * 512 + inode_addr, &inode); return Maybe<Inode>(inode); } Maybe<Ext2::Inode> Ext2::GetInode(Inode &pwd, const char *name) { // XXX: this assumes all dir entries will fit in a single block, which is bad auto mDirent = this->GetDirectoryEntry(pwd.block_ptr[0], name); if(mDirent.IsNothing()) { return Maybe<Inode>(); } else { return this->GetInode(mDirent.FromJust().inode_id); } } Maybe<Ext2::Inode> Ext2::GetInode(size_t count, const char *paths[]) { auto mRoot = this->GetInode(ROOT_INODE); if(mRoot.IsNothing()) { return Maybe<Inode>(); } Inode ref = mRoot.FromJust(); for(size_t i = 0; i < count; ++i) { auto mRef = this->GetInode(ref, paths[i]); if(mRef.IsNothing()) { return Maybe<Inode>(); } ref = mRef.FromJust(); } return ref; } Maybe<Ext2::DirectoryEntry> Ext2::GetDirectoryEntry(uint32_t block_id, const char *name) { uint32_t block_size = this->GetBlockSize(); uint32_t block_addr = this->GetBlockAddr(block_id); // XXX: this assumes a block is 1024 bytes, which is very bad if it's not char buffer[1024]; ata_pio_read(this->lba + block_addr / 512, 2, &buffer); DirectoryEntry *dirent; for(size_t offset = 0; offset < block_size; offset += dirent->size) { dirent = reinterpret_cast<DirectoryEntry *>(&buffer[offset]); if(dirent->inode_id == 0) { break; } bool match = true; for(size_t n = 0; n < dirent->len; ++n) { if(buffer[offset + sizeof(DirectoryEntry) + n] != name[n]) { match = false; break; } } if(match) { return Maybe<DirectoryEntry>(*dirent); } } return Maybe<DirectoryEntry>(); } void Ext2::ReadInode(Inode inode, uint32_t offset, size_t count, char *ptr) { uint32_t block_size = this->GetBlockSize(); size_t offset_end = offset + count; size_t block_ptr_begin = offset / block_size; size_t block_ptr_end = offset_end / block_size + (offset_end % block_size != 0) + 1; size_t n = 0; size_t off = offset % block_size; for(size_t b = block_ptr_begin; b < block_ptr_end; ++b) { uint32_t block_ptr = this->GetInodeBlockAddr(inode, b); char buffer[1024]; // XXX: assuming block size is 1024 again ata_pio_read(this->lba + block_ptr / 512, block_size / 512, &buffer); while(off < block_size && n < count) { ptr[n++] = buffer[off++]; } off = 0; } } <|endoftext|>
<commit_before>#include <cstdio> #include <cstdlib> #include <unistd.h> #include <string> #include <string.h> #include <csignal> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/wait.h> #include <dirent.h> #include <fcntl.h> #include <errno.h> #include <functional> #include <unordered_map> #include <algorithm> #include <iostream> #include <sstream> #if defined(__APPLE__) || defined(__GNUC__) && __GNUC__ * 10 + __GNUC_MINOR__ >= 49 #include <regex> #endif #include <cassert> #include <vector> #include <fstream> #include <future> #include <ctime> #define BUF_SIZE 4096 #define MAX_LISTEN 128 namespace Cappuccino{ class Request; class Response; struct { time_t time; struct tm *t_st; int port = 1204; int sockfd = 0; int sessionfd = 0; fd_set mask1fds, mask2fds; std::shared_ptr<std::string> view_root; std::shared_ptr<std::string> static_root; std::unordered_map<std::string, std::function<Response(std::shared_ptr<Request>)> > routes; } context; namespace Log{ std::string current(){ char timestr[256]; time(&context.time); strftime(timestr, 255, "%Y-%m-%d %H:%M:%S %Z", localtime(&context.time)); return timestr; } static int LogLevel = 0; static void debug(std::string msg){ if(LogLevel >= 1){ std::cout <<current()<<" "<< msg << std::endl; } } static void info(std::string msg){ if(LogLevel >= 2){ std::cout <<current()<<" "<< msg << std::endl; } } }; namespace signal_utils{ void signal_handler(int signal){ close(context.sessionfd); close(context.sockfd); exit(0); } void signal_handler_child(int SignalName){ while(waitpid(-1,NULL,WNOHANG)>0){} signal(SIGCHLD, signal_utils::signal_handler_child); } void init_signal(){ if(signal(SIGINT, signal_utils::signal_handler) == SIG_ERR){ exit(1); } if(signal(SIGCHLD, signal_utils::signal_handler_child) == SIG_ERR){ exit(1); } } } namespace utils{ std::vector<std::string> split(const std::string& str, std::string delim) noexcept{ std::vector<std::string> result; std::string::size_type pos = 0; while(pos != std::string::npos ){ std::string::size_type p = str.find(delim, pos); if(p == std::string::npos){ result.push_back(str.substr(pos)); break; }else{ result.push_back(str.substr(pos, p - pos)); } pos = p + delim.size(); } return result; } }; void init_socket(){ struct sockaddr_in server; if((context.sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){ exit(EXIT_FAILURE); } memset( &server, 0, sizeof(server)); server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons(context.port); char opt = 1; setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(char)); int temp = 1; if(setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR, &temp, sizeof(int))){ } if (bind(context.sockfd, (struct sockaddr *) &server, sizeof(server)) < 0) { exit(EXIT_FAILURE); } if(listen(context.sockfd, MAX_LISTEN) < 0) { exit(EXIT_FAILURE); } FD_ZERO(&context.mask1fds); FD_SET(context.sockfd, &context.mask1fds); } using namespace std; pair<string,string> openFile(string aFilename){ auto filename = aFilename; std::ifstream ifs( filename, std::ios::in | std::ios::binary); if(ifs.fail()){ throw std::runtime_error("No such file or directory \""+ filename +"\"\n"); } ifs.seekg( 0, std::ios::end); auto pos = ifs.tellg(); ifs.seekg( 0, std::ios::beg); std::vector<char> buf(pos); ifs.read(buf.data(), pos); string response(buf.cbegin(), buf.cend()); if( response[0] == '\xFF' && response[1] == '\xD8'){ return make_pair(response, "image/jpg"); }else if( response[0] == '\x89' && response[1] == 'P' && response[2] == 'N' && response[3] == 'G'){ return make_pair(response, "image/png"); }else if( response[0] == 'G' && response[1] == 'I' && response[2] == 'F' && response[3] == '8' && (response[4] == '7' || response[4] == '9') && response[2] == 'a'){ return make_pair(response, "image/gif"); }else{ return make_pair(response, "text/html"); } } void option(int argc, char *argv[]) noexcept{ char result; while((result = getopt(argc,argv,"dvp:")) != -1){ switch(result){ case 'd': Log::LogLevel = 1; break; case 'p': context.port = atoi(optarg); break; case 'v': Log::info("version 0.0.3"); exit(0); } } } class Request{ unordered_map<string, string> headerset; unordered_map<string, string> paramset; public: Request(string method, string url,string protocol): method(move(method)), url(move(url)), protocol(move(protocol)) {} const string method; const string url; const string protocol; void addHeader(string key,string value){ headerset[key] = move(value); } void addParams(string key,string value){ paramset[key] = move(value); } string header(string key){ if(headerset.find(key) == headerset.end()) return "INVALID"; return headerset[key]; } string params(string key){ if(paramset.find(key) == paramset.end()) return "INVALID"; return paramset[key]; } }; class Response{ unordered_map<string, string> headerset; int status_; string message_; string url_; string body_; string protocol_; public: Response(weak_ptr<Request> req){ auto r = req.lock(); if(r){ url_ = r->url; protocol_ = r->protocol; }else{ throw std::runtime_error("Request expired!\n"); } } Response(int st,string msg,string pro, string bod): status_(st), message_(msg), body_(bod), protocol_(pro) {} Response* message(string msg){ message_ = msg; return this; } Response* status(int st){ status_ = st; return this; } Response* file(string filename){ auto file = openFile(*context.view_root + "/" + filename); body_ = file.first; headerset["Content-type"] = move(file.second); return this; } operator string(){ return protocol_ + " " + to_string(status_) +" "+ message_ + "\n\n" + body_; } }; string createResponse(char* req) noexcept{ auto lines = utils::split(string(req), "\n"); if(lines.empty()) return Response(400, "Bad Request", "HTTP/1.1", "NN"); auto tops = utils::split(lines[0], " "); if(tops.size() < 3) return Response(401, "Bad Request", "HTTP/1.1", "NN"); Log::debug(tops[0] +" "+ tops[1] +" "+ tops[2]); auto request = shared_ptr<Request>(new Request(tops[0],tops[1],tops[2])); if(context.routes.find(tops[1]) != context.routes.end()){ return context.routes[tops[1]](move(request)); } return Response( 404,"Not found", tops[2], "AA"); } string receiveProcess(int sessionfd){ char buf[BUF_SIZE] = {}; if (recv(sessionfd, buf, sizeof(buf), 0) < 0) { exit(EXIT_FAILURE); } do{ if(strstr(buf, "\r\n")){ break; } if (strlen(buf) >= sizeof(buf)) { memset(&buf, 0, sizeof(buf)); } }while(read(sessionfd, buf+strlen(buf), sizeof(buf) - strlen(buf)) > 0); return createResponse(buf); } void load(string directory, string filename) noexcept{ if(filename == "." || filename == "..") return; if(filename!="") directory += "/" + filename; DIR* dir = opendir(directory.c_str()); if(dir != NULL){ struct dirent* dent; dent = readdir(dir); while(dent!=NULL){ dent = readdir(dir); if(dent!=NULL) load(directory, string(dent->d_name)); } closedir(dir); delete dent; delete dir; }else{ Log::debug("add "+directory); context.routes.insert( make_pair( "/" + directory, [directory,filename](std::shared_ptr<Request> request) -> Cappuccino::Response{ return Response(200,"OK","HTTP/1.1",openFile(directory).first); } )); } } void loadStaticFiles() noexcept{ load(*context.static_root,""); } void route(string url,std::function<Response(std::shared_ptr<Request>)> F){ context.routes.insert( make_pair( move(url), move(F) )); } void root(string r){ context.view_root = make_shared<string>(move(r)); } void resource(string s){ context.static_root = make_shared<string>(move(s)); } void run(){ init_socket(); signal_utils::init_signal(); loadStaticFiles(); int cd[FD_SETSIZE]; struct sockaddr_in client; int fd; struct timeval tv; for(int i = 0;i < FD_SETSIZE; i++){ cd[i] = 0; } int I = 0; while(1) { if(I>5){ return; } tv.tv_sec = 0; tv.tv_usec = 0; memcpy(&context.mask2fds, &context.mask1fds, sizeof(context.mask1fds)); int select_result = select(FD_SETSIZE, &context.mask2fds, (fd_set *)0, (fd_set *)0, &tv); if(select_result < 1) { for(fd = 0; fd < FD_SETSIZE; fd++) { if(cd[fd] == 1) { close(fd); FD_CLR(fd, &context.mask1fds); cd[fd] = 0; } } continue; } for(fd = 0; fd < FD_SETSIZE; fd++){ if(FD_ISSET(fd,&context.mask2fds)) { if(fd == context.sockfd) { memset( &client, 0, sizeof(client)); int len = sizeof(client); int clientfd = accept(context.sockfd, (struct sockaddr *)&client,(socklen_t *) &len); FD_SET(clientfd, &context.mask1fds); }else { if(cd[fd] == 1) { close(fd); FD_CLR(fd, &context.mask1fds); cd[fd] = 0; } else { string response = receiveProcess(fd); write(fd, response.c_str(), response.size()); cd[fd] = 1; I++; } } } } } } void Cappuccino(int argc, char *argv[]) { option(argc, argv); context.view_root = make_shared<string>(""); context.static_root = make_shared<string>("public"); } }; namespace Cocoa{ using namespace Cappuccino; using namespace std; // Unit Test void testOpenFile(){ auto res = openFile("html/index.html"); auto lines = utils::split(res.first, "\n"); assert(!lines.empty()); } void testOpenInvalidFile(){ try{ auto res = openFile("html/index"); }catch(std::runtime_error e){ cout<< e.what() << endl; } } }; <commit_msg>[fix] Segv.<commit_after>#include <cstdio> #include <cstdlib> #include <unistd.h> #include <string> #include <string.h> #include <csignal> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/wait.h> #include <dirent.h> #include <fcntl.h> #include <errno.h> #include <functional> #include <unordered_map> #include <algorithm> #include <iostream> #include <sstream> #if defined(__APPLE__) || defined(__GNUC__) && __GNUC__ * 10 + __GNUC_MINOR__ >= 49 #include <regex> #endif #include <cassert> #include <vector> #include <fstream> #include <future> #include <ctime> #define BUF_SIZE 4096 #define MAX_LISTEN 128 namespace Cappuccino { class Request; class Response; struct { time_t time; struct tm *t_st; int port = 1204; int sockfd = 0; int sessionfd = 0; fd_set mask1fds, mask2fds; std::shared_ptr<std::string> view_root; std::shared_ptr<std::string> static_root; std::unordered_map<std::string, std::function<Response(std::shared_ptr<Request>)> > routes; } context; namespace Log{ std::string current(){ char timestr[256]; time(&context.time); strftime(timestr, 255, "%Y-%m-%d %H:%M:%S %Z", localtime(&context.time)); return timestr; } static int LogLevel = 0; static void debug(std::string msg){ if(LogLevel >= 1){ std::cout <<current()<<"[debug] "<< msg << std::endl; } } static void info(std::string msg){ if(LogLevel >= 2){ std::cout <<current()<<"[info] "<< msg << std::endl; } } }; namespace signal_utils{ void signal_handler(int signal){ close(context.sessionfd); close(context.sockfd); exit(0); } void signal_handler_child(int SignalName){ while(waitpid(-1,NULL,WNOHANG)>0){} signal(SIGCHLD, signal_utils::signal_handler_child); } void init_signal(){ if(signal(SIGINT, signal_utils::signal_handler) == SIG_ERR){ exit(1); } if(signal(SIGCHLD, signal_utils::signal_handler_child) == SIG_ERR){ exit(1); } } } namespace utils{ std::vector<std::string> split(const std::string& str, std::string delim) noexcept{ std::vector<std::string> result; std::string::size_type pos = 0; while(pos != std::string::npos ){ std::string::size_type p = str.find(delim, pos); if(p == std::string::npos){ result.push_back(str.substr(pos)); break; }else{ result.push_back(str.substr(pos, p - pos)); } pos = p + delim.size(); } return result; } }; void init_socket(){ struct sockaddr_in server; if((context.sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){ exit(EXIT_FAILURE); } memset( &server, 0, sizeof(server)); server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = htons(context.port); char opt = 1; setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(char)); int temp = 1; if(setsockopt(context.sockfd, SOL_SOCKET, SO_REUSEADDR, &temp, sizeof(int))){ } if (bind(context.sockfd, (struct sockaddr *) &server, sizeof(server)) < 0) { exit(EXIT_FAILURE); } if(listen(context.sockfd, MAX_LISTEN) < 0) { exit(EXIT_FAILURE); } FD_ZERO(&context.mask1fds); FD_SET(context.sockfd, &context.mask1fds); } using namespace std; pair<string,string> openFile(string aFilename){ auto filename = aFilename; std::ifstream ifs( filename, std::ios::in | std::ios::binary); if(ifs.fail()){ throw std::runtime_error("No such file or directory \""+ filename +"\"\n"); } ifs.seekg( 0, std::ios::end); auto pos = ifs.tellg(); ifs.seekg( 0, std::ios::beg); std::vector<char> buf(pos); ifs.read(buf.data(), pos); string response(buf.cbegin(), buf.cend()); if( response[0] == '\xFF' && response[1] == '\xD8'){ return make_pair(response, "image/jpg"); }else if( response[0] == '\x89' && response[1] == 'P' && response[2] == 'N' && response[3] == 'G'){ return make_pair(response, "image/png"); }else if( response[0] == 'G' && response[1] == 'I' && response[2] == 'F' && response[3] == '8' && (response[4] == '7' || response[4] == '9') && response[2] == 'a'){ return make_pair(response, "image/gif"); }else{ return make_pair(response, "text/html"); } } void option(int argc, char *argv[]) noexcept{ char result; while((result = getopt(argc,argv,"dvp:")) != -1){ switch(result){ case 'd': Log::LogLevel = 1; break; case 'p': context.port = atoi(optarg); break; case 'v': Log::info("version 0.0.3"); exit(0); } } } class Request{ unordered_map<string, string> headerset; unordered_map<string, string> paramset; public: Request(string method, string url,string protocol): method(move(method)), url(move(url)), protocol(move(protocol)) {} const string method; const string url; const string protocol; void addHeader(string key,string value){ headerset[key] = move(value); } void addParams(string key,string value){ paramset[key] = move(value); } string header(string key){ if(headerset.find(key) == headerset.end()) return "INVALID"; return headerset[key]; } string params(string key){ if(paramset.find(key) == paramset.end()) return "INVALID"; return paramset[key]; } }; class Response{ unordered_map<string, string> headerset; int status_; string message_; string url_; string body_; string protocol_; public: Response(weak_ptr<Request> req){ auto r = req.lock(); if(r){ url_ = r->url; protocol_ = r->protocol; }else{ throw std::runtime_error("Request expired!\n"); } } Response(int st,string msg,string pro, string bod): status_(st), message_(msg), body_(bod), protocol_(pro) {} Response* message(string msg){ message_ = msg; return this; } Response* status(int st){ status_ = st; return this; } Response* file(string filename){ auto file = openFile(*context.view_root + "/" + filename); body_ = file.first; headerset["Content-type"] = move(file.second); return this; } operator string(){ return protocol_ + " " + to_string(status_) +" "+ message_ + "\n\n" + body_; } }; string createResponse(char* req) noexcept{ auto lines = utils::split(string(req), "\n"); if(lines.empty()) return Response(400, "Bad Request", "HTTP/1.1", "NN"); auto tops = utils::split(lines[0], " "); if(tops.size() < 3) return Response(401, "Bad Request", "HTTP/1.1", "NN"); Log::debug(tops[0] +" "+ tops[1] +" "+ tops[2]); auto request = shared_ptr<Request>(new Request(tops[0],tops[1],tops[2])); if(context.routes.find(tops[1]) != context.routes.end()){ return context.routes[tops[1]](move(request)); } return Response( 404,"Not found", tops[2], "AA"); } string receiveProcess(int sessionfd){ char buf[BUF_SIZE] = {}; if (recv(sessionfd, buf, sizeof(buf), 0) < 0) { exit(EXIT_FAILURE); } do{ if(strstr(buf, "\r\n")){ break; } if (strlen(buf) >= sizeof(buf)) { memset(&buf, 0, sizeof(buf)); } }while(read(sessionfd, buf+strlen(buf), sizeof(buf) - strlen(buf)) > 0); return createResponse(buf); } void load(string directory, string filename) noexcept{ if(filename == "." || filename == "..") return; if(filename!="") directory += "/" + move(filename); DIR* dir = opendir(directory.c_str()); if(dir != NULL){ struct dirent* dent; dent = readdir(dir); while(dent!=NULL){ dent = readdir(dir); if(dent!=NULL) load(directory, string(dent->d_name)); } if(dir!=NULL){ closedir(dir); //delete dent; //delete dir; } }else{ Log::debug("add "+directory); context.routes.insert( make_pair( "/" + directory, [directory,filename](std::shared_ptr<Request> request) -> Cappuccino::Response{ return Response(200,"OK","HTTP/1.1",openFile(directory).first); } )); } } void loadStaticFiles() noexcept{ load(*context.static_root,""); } void route(string url,std::function<Response(std::shared_ptr<Request>)> F){ context.routes.insert( make_pair( move(url), move(F) )); } void root(string r){ context.view_root = make_shared<string>(move(r)); } void resource(string s){ context.static_root = make_shared<string>(move(s)); } void run(){ init_socket(); signal_utils::init_signal(); loadStaticFiles(); int cd[FD_SETSIZE]; struct sockaddr_in client; int fd; struct timeval tv; for(int i = 0;i < FD_SETSIZE; i++){ cd[i] = 0; } int I = 0; while(1) { if(I>5){ return; } tv.tv_sec = 0; tv.tv_usec = 0; memcpy(&context.mask2fds, &context.mask1fds, sizeof(context.mask1fds)); int select_result = select(FD_SETSIZE, &context.mask2fds, (fd_set *)0, (fd_set *)0, &tv); if(select_result < 1) { for(fd = 0; fd < FD_SETSIZE; fd++) { if(cd[fd] == 1) { close(fd); FD_CLR(fd, &context.mask1fds); cd[fd] = 0; } } continue; } for(fd = 0; fd < FD_SETSIZE; fd++){ if(FD_ISSET(fd,&context.mask2fds)) { if(fd == context.sockfd) { memset( &client, 0, sizeof(client)); int len = sizeof(client); int clientfd = accept(context.sockfd, (struct sockaddr *)&client,(socklen_t *) &len); FD_SET(clientfd, &context.mask1fds); }else { if(cd[fd] == 1) { close(fd); FD_CLR(fd, &context.mask1fds); cd[fd] = 0; } else { string response = receiveProcess(fd); write(fd, response.c_str(), response.size()); cd[fd] = 1; I++; } } } } } } void Cappuccino(int argc, char *argv[]) { option(argc, argv); context.view_root = make_shared<string>(""); context.static_root = make_shared<string>("public"); } }; namespace Cocoa{ using namespace Cappuccino; using namespace std; // Unit Test void testOpenFile(){ auto res = openFile("html/index.html"); auto lines = utils::split(res.first, "\n"); assert(!lines.empty()); } void testOpenInvalidFile(){ try{ auto res = openFile("html/index"); }catch(std::runtime_error e){ cout<< e.what() << endl; } } }; <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef SUPPORT_NASTY_MACROS_HPP #define SUPPORT_NASTY_MACROS_HPP #define NASTY_MACRO This should not be expanded!!! #define _A NASTY_MACRO #define _B NASTY_MACRO #define _C NASTY_MACRO #define _D NASTY_MACRO #define _E NASTY_MACRO #define _F NASTY_MACRO #define _G NASTY_MACRO #define _H NASTY_MACRO #define _I NASTY_MACRO #define _J NASTY_MACRO #define _K NASTY_MACRO #define _L NASTY_MACRO #define _M NASTY_MACRO #define _N NASTY_MACRO #define _O NASTY_MACRO #define _P NASTY_MACRO #define _Q NASTY_MACRO #define _R NASTY_MACRO #define _S NASTY_MACRO #define _T NASTY_MACRO #define _U NASTY_MACRO #define _V NASTY_MACRO #define _W NASTY_MACRO #define _X NASTY_MACRO #define _Y NASTY_MACRO #define _Z NASTY_MACRO // tchar.h defines these macros on Windows. #define _UI NASTY_MACRO #define _PUC NASTY_MACRO #define _CPUC NASTY_MACRO #define _PC NASTY_MACRO #define _CRPC NASTY_MACRO #define _CPC NASTY_MACRO // Test that libc++ doesn't use names reserved by WIN32 API Macros. // NOTE: Obviously we can only define these on non-windows platforms. #ifndef _WIN32 #define __deallocate NASTY_MACRO #define __out NASTY_MACRO #endif #define __output NASTY_MACRO #define __input NASTY_MACRO #endif // SUPPORT_NASTY_MACROS_HPP <commit_msg>For FreeBSD, don't define _M in nasty_macros.hpp<commit_after>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef SUPPORT_NASTY_MACROS_HPP #define SUPPORT_NASTY_MACROS_HPP #define NASTY_MACRO This should not be expanded!!! #define _A NASTY_MACRO #define _B NASTY_MACRO #define _C NASTY_MACRO #define _D NASTY_MACRO #define _E NASTY_MACRO #define _F NASTY_MACRO #define _G NASTY_MACRO #define _H NASTY_MACRO #define _I NASTY_MACRO #define _J NASTY_MACRO #define _K NASTY_MACRO #define _L NASTY_MACRO // Because FreeBSD uses _M in its <sys/types.h>, and it is hard to avoid // including that header, only define _M for other operating systems. #ifndef __FreeBSD__ #define _M NASTY_MACRO #endif #define _N NASTY_MACRO #define _O NASTY_MACRO #define _P NASTY_MACRO #define _Q NASTY_MACRO #define _R NASTY_MACRO #define _S NASTY_MACRO #define _T NASTY_MACRO #define _U NASTY_MACRO #define _V NASTY_MACRO #define _W NASTY_MACRO #define _X NASTY_MACRO #define _Y NASTY_MACRO #define _Z NASTY_MACRO // tchar.h defines these macros on Windows. #define _UI NASTY_MACRO #define _PUC NASTY_MACRO #define _CPUC NASTY_MACRO #define _PC NASTY_MACRO #define _CRPC NASTY_MACRO #define _CPC NASTY_MACRO // Test that libc++ doesn't use names reserved by WIN32 API Macros. // NOTE: Obviously we can only define these on non-windows platforms. #ifndef _WIN32 #define __deallocate NASTY_MACRO #define __out NASTY_MACRO #endif #define __output NASTY_MACRO #define __input NASTY_MACRO #endif // SUPPORT_NASTY_MACROS_HPP <|endoftext|>
<commit_before>#pragma once #include "acmacs-base/fmt.hh" #include "acmacs-base/rjson.hh" #include "acmacs-base/flat-map.hh" // ---------------------------------------------------------------------- namespace acmacs::settings::inline v2 { class error : public std::runtime_error { using std::runtime_error::runtime_error; }; class Settings { public: Settings() = default; Settings(const std::vector<std::string_view>& filenames) { load(filenames); } virtual ~Settings() = default; // read settings from files, upon reading each file apply "init" in it (if found) void load(const std::vector<std::string_view>& filenames) { for (const auto& filename : filenames) load(filename); } void load(std::string_view filename); // substitute vars in name, find name in environment or in data_ or in built-in and apply it // if name starts with ? do nothing // if name not found, throw virtual void apply(std::string_view name = "main") const; void apply(const char* name) const { apply(std::string_view{name}); } // substitute vars in name, find name in the top of data_ and apply it // do nothing if name starts with ? or if it is not found in top of data_ virtual void apply_top(std::string_view name) const; virtual bool apply_built_in(std::string_view name) const; // returns true if built-in command with that name found and applied void setenv_from_string(std::string_view key, std::string_view value); template <typename T> void setenv(std::string_view key, T&& value) { setenv(key, rjson::value{std::forward<T>(value)}); } template <typename T> T getenv(std::string_view key, T&& a_default) const { if (const auto& val = environment_.get(static_cast<std::string>(environment_.substitute(key))); !val.is_const_null()) return static_cast<T>(val); else return std::move(a_default); } std::string getenv(std::string_view key, const char* a_default) const { return getenv(key, std::string{a_default}); } protected: template <typename... Key> const rjson::value& get(Key&&... keys) const; void apply(const rjson::value& entry) const; private: class Environment { public: Environment() { push(); } const rjson::value& get(std::string_view key) const; void push() { data_.emplace_back(); } void pop() { data_.erase(std::prev(std::end(data_))); } size_t size() const { return data_.size(); } void add(std::string_view key, const rjson::value& val) { data_.rbegin()->emplace_or_replace(std::string{key}, val); } void add(std::string_view key, rjson::value&& val) { data_.rbegin()->emplace_or_replace(std::string{key}, std::move(val)); } void print() const; void print_key_value() const; rjson::value substitute(std::string_view source) const; private: std::vector<acmacs::flat_map_t<std::string, rjson::value>> data_; rjson::value substitute(const rjson::value& source) const; }; std::vector<rjson::value> data_; mutable Environment environment_; void push_and_apply(const rjson::object& entry) const; friend class Subenvironment; }; } // namespace acmacs::settings::inline v2 // ---------------------------------------------------------------------- namespace acmacs::settings::inline v2 { template <typename... Key> const rjson::value& Settings::get(Key && ... keys) const { for (auto it = data_.rbegin(); it != data_.rend(); ++it) { if (const auto& val = it->get(std::forward<Key>(keys)...); !val.is_const_null()) return val; } return rjson::ConstNull; } // acmacs::settings::v2::Settings::get template <> inline void Settings::setenv(std::string_view key, const rjson::value& value) { environment_.add(key, value); } template <> inline void Settings::setenv(std::string_view key, rjson::value && value) { environment_.add(key, std::move(value)); } } // namespace acmacs::settings::inline v2 // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>settings-v2<commit_after>#pragma once #include "acmacs-base/fmt.hh" #include "acmacs-base/rjson.hh" #include "acmacs-base/flat-map.hh" // ---------------------------------------------------------------------- namespace acmacs::settings::inline v2 { class error : public std::runtime_error { using std::runtime_error::runtime_error; }; class Settings { public: Settings() = default; Settings(const std::vector<std::string_view>& filenames) { load(filenames); } virtual ~Settings() = default; // read settings from files, upon reading each file apply "init" in it (if found) void load(const std::vector<std::string_view>& filenames) { for (const auto& filename : filenames) load(filename); } void load(std::string_view filename); // substitute vars in name, find name in environment or in data_ or in built-in and apply it // if name starts with ? do nothing // if name not found, throw virtual void apply(std::string_view name = "main") const; void apply(const char* name) const { apply(std::string_view{name}); } // substitute vars in name, find name in the top of data_ and apply it // do nothing if name starts with ? or if it is not found in top of data_ virtual void apply_top(std::string_view name) const; virtual bool apply_built_in(std::string_view name) const; // returns true if built-in command with that name found and applied void setenv_from_string(std::string_view key, std::string_view value); template <typename T> void setenv(std::string_view key, T&& value) { setenv(key, rjson::value{std::forward<T>(value)}); } template <typename T> T getenv(std::string_view key, T&& a_default) const { if (const auto& val = environment_.get(static_cast<std::string>(environment_.substitute(key))); !val.is_const_null()) return static_cast<T>(val); else return std::move(a_default); } std::string getenv(std::string_view key, const char* a_default) const { return getenv(key, std::string{a_default}); } void printenv() const { environment_.print(); } protected: template <typename... Key> const rjson::value& get(Key&&... keys) const; void apply(const rjson::value& entry) const; private: class Environment { public: Environment() { push(); } const rjson::value& get(std::string_view key) const; void push() { data_.emplace_back(); } void pop() { data_.erase(std::prev(std::end(data_))); } size_t size() const { return data_.size(); } void add(std::string_view key, const rjson::value& val) { data_.rbegin()->emplace_or_replace(std::string{key}, val); } void add(std::string_view key, rjson::value&& val) { data_.rbegin()->emplace_or_replace(std::string{key}, std::move(val)); } void print() const; void print_key_value() const; rjson::value substitute(std::string_view source) const; private: std::vector<acmacs::flat_map_t<std::string, rjson::value>> data_; rjson::value substitute(const rjson::value& source) const; }; std::vector<rjson::value> data_; mutable Environment environment_; void push_and_apply(const rjson::object& entry) const; friend class Subenvironment; }; } // namespace acmacs::settings::inline v2 // ---------------------------------------------------------------------- namespace acmacs::settings::inline v2 { template <typename... Key> const rjson::value& Settings::get(Key && ... keys) const { for (auto it = data_.rbegin(); it != data_.rend(); ++it) { if (const auto& val = it->get(std::forward<Key>(keys)...); !val.is_const_null()) return val; } return rjson::ConstNull; } // acmacs::settings::v2::Settings::get template <> inline void Settings::setenv(std::string_view key, const rjson::value& value) { environment_.add(key, value); } template <> inline void Settings::setenv(std::string_view key, rjson::value && value) { environment_.add(key, std::move(value)); } } // namespace acmacs::settings::inline v2 // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>#include <algorithm> #include <functional> #include <iomanip> #include "hidb.hh" #include "variant-id.hh" #include "vaccines.hh" // ---------------------------------------------------------------------- #pragma GCC diagnostic push #ifdef __clang__ #pragma GCC diagnostic ignored "-Wexit-time-destructors" #pragma GCC diagnostic ignored "-Wglobal-constructors" #endif static std::map<std::string, std::vector<hidb::Vaccine>> sVaccines = { {"A(H1N1)", { {"CALIFORNIA/7/2009", hidb::Vaccine::Previous}, {"MICHIGAN/45/2015", hidb::Vaccine::Current}, }}, {"A(H3N2)", { {"BRISBANE/10/2007", hidb::Vaccine::Previous}, {"PERTH/16/2009", hidb::Vaccine::Previous}, {"VICTORIA/361/2011", hidb::Vaccine::Previous}, {"TEXAS/50/2012", hidb::Vaccine::Previous}, {"SWITZERLAND/9715293/2013", hidb::Vaccine::Previous}, {"HONG KONG/4801/2014", hidb::Vaccine::Current}, {"SAITAMA/103/2014", hidb::Vaccine::Surrogate}, {"HONG KONG/7295/2014", hidb::Vaccine::Surrogate}, }}, {"BVICTORIA", { {"MALAYSIA/2506/2004", hidb::Vaccine::Previous}, {"BRISBANE/60/2008", hidb::Vaccine::Current}, // {"PARIS/1762/2009", hidb::Vaccine::Current}, // not used by Crick anymore, B/Ireland/3154/2016 is used instead (2017-08-21) {"SOUTH AUSTRALIA/81/2012", hidb::Vaccine::Surrogate}, {"IRELAND/3154/2016", hidb::Vaccine::Surrogate}, }}, {"BYAMAGATA", { {"FLORIDA/4/2006", hidb::Vaccine::Previous}, {"WISCONSIN/1/2010", hidb::Vaccine::Previous}, {"MASSACHUSETTS/2/2012", hidb::Vaccine::Previous}, {"PHUKET/3073/2013", hidb::Vaccine::Current}, }}, }; #pragma GCC diagnostic pop // ---------------------------------------------------------------------- std::string hidb::Vaccine::type_as_string(hidb::Vaccine::Type aType) { switch (aType) { case Previous: return "previous"; case Current: return "current"; case Surrogate: return "surrogate"; } return {}; } // hidb::Vaccine::type_as_string // ---------------------------------------------------------------------- hidb::Vaccine::Type hidb::Vaccine::type_from_string(std::string aType) { if (aType == "previous") return Previous; else if (aType == "current") return Current; else if (aType == "surrogate") return Surrogate; return Previous; } // hidb::Vaccine::type_from_string // ---------------------------------------------------------------------- const std::vector<hidb::Vaccine>& hidb::vaccines(std::string aSubtype, std::string aLineage) { return sVaccines.at(aSubtype + aLineage); } // hidb::vaccines // ---------------------------------------------------------------------- const std::vector<hidb::Vaccine>& hidb::vaccines(const Chart& aChart) { return vaccines(aChart.chart_info().virus_type(), aChart.lineage()); } // hidb::vaccines // ---------------------------------------------------------------------- std::string hidb::Vaccine::type_as_string() const { return type_as_string(type); } // hidb::Vaccine::type_as_string // ---------------------------------------------------------------------- inline bool hidb::Vaccines::Entry::operator < (const hidb::Vaccines::Entry& a) const { const auto a_nt = a.antigen_data->number_of_tables(), t_nt = antigen_data->number_of_tables(); return t_nt == a_nt ? most_recent_table_date > a.most_recent_table_date : t_nt > a_nt; } // ---------------------------------------------------------------------- bool hidb::Vaccines::HomologousSerum::operator < (const hidb::Vaccines::HomologousSerum& a) const { bool result = true; if (serum->serum_species() == "SHEEP") { // avoid using sheep serum as homologous (NIMR) result = false; } else { const auto s_nt = a.serum_data->number_of_tables(), t_nt = serum_data->number_of_tables(); result = t_nt == s_nt ? most_recent_table_date > a.most_recent_table_date : t_nt > s_nt; } return result; } // hidb::Vaccines::HomologousSerum::operator < // ---------------------------------------------------------------------- size_t hidb::Vaccines::HomologousSerum::number_of_tables() const { return serum_data->number_of_tables(); } // hidb::Vaccines::HomologousSerum::number_of_tables // ---------------------------------------------------------------------- std::string hidb::Vaccines::report(size_t aIndent) const { std::ostringstream out; if (!empty()) { out << std::string(aIndent, ' ') << "Vaccine " << type_as_string() << ' ' << mNameType.name << std::endl; for_each_passage_type([&](PassageType pt) { out << this->report(pt, aIndent + 2); }); } return out.str(); } // hidb::Vaccines::report // ---------------------------------------------------------------------- std::string hidb::Vaccines::report(PassageType aPassageType, size_t aIndent, size_t aMark) const { std::ostringstream out; const std::string indent(aIndent, ' '); auto entry_report = [&](size_t aNo, const auto& entry, bool aMarkIt) { out << indent << (aMarkIt ? ">>" : " ") << std::setw(2) << aNo << ' ' << entry.antigen_index << ' ' << entry.antigen->full_name() << " tables:" << entry.antigen_data->number_of_tables() << " recent:" << entry.antigen_data->most_recent_table().table_id() << std::endl; for (const auto& hs: entry.homologous_sera) out << indent << " " << hs.serum->serum_id() << ' ' << hs.serum->annotations().join() << " tables:" << hs.serum_data->number_of_tables() << " recent:" << hs.serum_data->most_recent_table().table_id() << std::endl; }; const auto& entry = mEntries[aPassageType]; if (!entry.empty()) { out << indent << passage_type_name(aPassageType) << " (" << entry.size() << ')' << std::endl; for (size_t no = 0; no < entry.size(); ++no) entry_report(no, entry[no], aMark == no); } return out.str(); } // hidb::Vaccines::report // ---------------------------------------------------------------------- void hidb::vaccines_for_name(Vaccines& aVaccines, std::string aName, const Chart& aChart, const hidb::HiDb& aHiDb) { std::vector<size_t> by_name; aChart.antigens().find_by_name(aName, by_name); for (size_t ag_no: by_name) { try { const auto& ag = static_cast<const Antigen&>(aChart.antigen(ag_no)); // std::cerr << ag.full_name() << std::endl; const auto& data = aHiDb.find_antigen_of_chart(ag); std::vector<hidb::Vaccines::HomologousSerum> homologous_sera; for (const auto* sd: aHiDb.find_homologous_sera(data)) { const size_t sr_no = aChart.sera().find_by_full_name(hidb::name_for_exact_matching(sd->data())); // std::cerr << " " << sd->data().name_for_exact_matching() << " " << (serum ? "Y" : "N") << std::endl; if (sr_no != static_cast<size_t>(-1)) homologous_sera.emplace_back(sr_no, static_cast<const Serum*>(&aChart.serum(sr_no)), sd, aHiDb.charts()[sd->most_recent_table().table_id()].chart_info().date()); } aVaccines.add(ag_no, ag, &data, std::move(homologous_sera), aHiDb.charts()[data.most_recent_table().table_id()].chart_info().date()); } catch (hidb::HiDb::NotFound&) { } } aVaccines.sort(); } // hidb::vaccines_for_name // ---------------------------------------------------------------------- hidb::Vaccines* hidb::find_vaccines_in_chart(std::string aName, const Chart& aChart, const hidb::HiDb& aHiDb) { Vaccines* result = new Vaccines(Vaccine(aName, hidb::Vaccine::Previous)); vaccines_for_name(*result, aName, aChart, aHiDb); return result; } // find_vaccines_in_chart // ---------------------------------------------------------------------- void hidb::vaccines(VaccinesOfChart& aVaccinesOfChart, const Chart& aChart, const hidb::HiDb& aHiDb) { for (const auto& name_type: vaccines(aChart)) { aVaccinesOfChart.emplace_back(name_type); vaccines_for_name(aVaccinesOfChart.back(), name_type.name, aChart, aHiDb); } } // hidb::vaccines // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- std::string hidb::VaccinesOfChart::report(size_t aIndent) const { std::string result; for (const auto& v: *this) result += v.report(aIndent); return result; } // hidb::VaccinesOfChart::report // ---------------------------------------------------------------------- // void hidb::VaccinesOfChart::remove(std::string aName, std::string aType, std::string aPassageType) // { // for (auto& v: *this) { // if (v.match(aName, aType)) // v.remove(aPassageType); // } // erase(std::remove_if(begin(), end(), std::mem_fn<bool() const>(&hidb::Vaccines::empty)), end()); // } // hidb::VaccinesOfChart::remove // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>find_by_full_name<commit_after>#include <algorithm> #include <functional> #include <iomanip> #include "hidb.hh" #include "variant-id.hh" #include "vaccines.hh" // ---------------------------------------------------------------------- #pragma GCC diagnostic push #ifdef __clang__ #pragma GCC diagnostic ignored "-Wexit-time-destructors" #pragma GCC diagnostic ignored "-Wglobal-constructors" #endif static std::map<std::string, std::vector<hidb::Vaccine>> sVaccines = { {"A(H1N1)", { {"CALIFORNIA/7/2009", hidb::Vaccine::Previous}, {"MICHIGAN/45/2015", hidb::Vaccine::Current}, }}, {"A(H3N2)", { {"BRISBANE/10/2007", hidb::Vaccine::Previous}, {"PERTH/16/2009", hidb::Vaccine::Previous}, {"VICTORIA/361/2011", hidb::Vaccine::Previous}, {"TEXAS/50/2012", hidb::Vaccine::Previous}, {"SWITZERLAND/9715293/2013", hidb::Vaccine::Previous}, {"HONG KONG/4801/2014", hidb::Vaccine::Current}, {"SAITAMA/103/2014", hidb::Vaccine::Surrogate}, {"HONG KONG/7295/2014", hidb::Vaccine::Surrogate}, }}, {"BVICTORIA", { {"MALAYSIA/2506/2004", hidb::Vaccine::Previous}, {"BRISBANE/60/2008", hidb::Vaccine::Current}, // {"PARIS/1762/2009", hidb::Vaccine::Current}, // not used by Crick anymore, B/Ireland/3154/2016 is used instead (2017-08-21) {"SOUTH AUSTRALIA/81/2012", hidb::Vaccine::Surrogate}, {"IRELAND/3154/2016", hidb::Vaccine::Surrogate}, }}, {"BYAMAGATA", { {"FLORIDA/4/2006", hidb::Vaccine::Previous}, {"WISCONSIN/1/2010", hidb::Vaccine::Previous}, {"MASSACHUSETTS/2/2012", hidb::Vaccine::Previous}, {"PHUKET/3073/2013", hidb::Vaccine::Current}, }}, }; #pragma GCC diagnostic pop // ---------------------------------------------------------------------- std::string hidb::Vaccine::type_as_string(hidb::Vaccine::Type aType) { switch (aType) { case Previous: return "previous"; case Current: return "current"; case Surrogate: return "surrogate"; } return {}; } // hidb::Vaccine::type_as_string // ---------------------------------------------------------------------- hidb::Vaccine::Type hidb::Vaccine::type_from_string(std::string aType) { if (aType == "previous") return Previous; else if (aType == "current") return Current; else if (aType == "surrogate") return Surrogate; return Previous; } // hidb::Vaccine::type_from_string // ---------------------------------------------------------------------- const std::vector<hidb::Vaccine>& hidb::vaccines(std::string aSubtype, std::string aLineage) { return sVaccines.at(aSubtype + aLineage); } // hidb::vaccines // ---------------------------------------------------------------------- const std::vector<hidb::Vaccine>& hidb::vaccines(const Chart& aChart) { return vaccines(aChart.chart_info().virus_type(), aChart.lineage()); } // hidb::vaccines // ---------------------------------------------------------------------- std::string hidb::Vaccine::type_as_string() const { return type_as_string(type); } // hidb::Vaccine::type_as_string // ---------------------------------------------------------------------- inline bool hidb::Vaccines::Entry::operator < (const hidb::Vaccines::Entry& a) const { const auto a_nt = a.antigen_data->number_of_tables(), t_nt = antigen_data->number_of_tables(); return t_nt == a_nt ? most_recent_table_date > a.most_recent_table_date : t_nt > a_nt; } // ---------------------------------------------------------------------- bool hidb::Vaccines::HomologousSerum::operator < (const hidb::Vaccines::HomologousSerum& a) const { bool result = true; if (serum->serum_species() == "SHEEP") { // avoid using sheep serum as homologous (NIMR) result = false; } else { const auto s_nt = a.serum_data->number_of_tables(), t_nt = serum_data->number_of_tables(); result = t_nt == s_nt ? most_recent_table_date > a.most_recent_table_date : t_nt > s_nt; } return result; } // hidb::Vaccines::HomologousSerum::operator < // ---------------------------------------------------------------------- size_t hidb::Vaccines::HomologousSerum::number_of_tables() const { return serum_data->number_of_tables(); } // hidb::Vaccines::HomologousSerum::number_of_tables // ---------------------------------------------------------------------- std::string hidb::Vaccines::report(size_t aIndent) const { std::ostringstream out; if (!empty()) { out << std::string(aIndent, ' ') << "Vaccine " << type_as_string() << ' ' << mNameType.name << std::endl; for_each_passage_type([&](PassageType pt) { out << this->report(pt, aIndent + 2); }); } return out.str(); } // hidb::Vaccines::report // ---------------------------------------------------------------------- std::string hidb::Vaccines::report(PassageType aPassageType, size_t aIndent, size_t aMark) const { std::ostringstream out; const std::string indent(aIndent, ' '); auto entry_report = [&](size_t aNo, const auto& entry, bool aMarkIt) { out << indent << (aMarkIt ? ">>" : " ") << std::setw(2) << aNo << ' ' << entry.antigen_index << ' ' << entry.antigen->full_name() << " tables:" << entry.antigen_data->number_of_tables() << " recent:" << entry.antigen_data->most_recent_table().table_id() << std::endl; for (const auto& hs: entry.homologous_sera) out << indent << " " << hs.serum->serum_id() << ' ' << hs.serum->annotations().join() << " tables:" << hs.serum_data->number_of_tables() << " recent:" << hs.serum_data->most_recent_table().table_id() << std::endl; }; const auto& entry = mEntries[aPassageType]; if (!entry.empty()) { out << indent << passage_type_name(aPassageType) << " (" << entry.size() << ')' << std::endl; for (size_t no = 0; no < entry.size(); ++no) entry_report(no, entry[no], aMark == no); } return out.str(); } // hidb::Vaccines::report // ---------------------------------------------------------------------- void hidb::vaccines_for_name(Vaccines& aVaccines, std::string aName, const Chart& aChart, const hidb::HiDb& aHiDb) { std::vector<size_t> by_name; aChart.antigens().find_by_name(aName, by_name); for (size_t ag_no: by_name) { try { const auto& ag = static_cast<const Antigen&>(aChart.antigen(ag_no)); // std::cerr << ag.full_name() << std::endl; const auto& data = aHiDb.find_antigen_of_chart(ag); std::vector<hidb::Vaccines::HomologousSerum> homologous_sera; for (const auto* sd: aHiDb.find_homologous_sera(data)) { if (const auto sr_no = aChart.sera().find_by_full_name(hidb::name_for_exact_matching(sd->data()))) homologous_sera.emplace_back(*sr_no, static_cast<const Serum*>(&aChart.serum(sr_no)), sd, aHiDb.charts()[sd->most_recent_table().table_id()].chart_info().date()); } aVaccines.add(ag_no, ag, &data, std::move(homologous_sera), aHiDb.charts()[data.most_recent_table().table_id()].chart_info().date()); } catch (hidb::HiDb::NotFound&) { } } aVaccines.sort(); } // hidb::vaccines_for_name // ---------------------------------------------------------------------- hidb::Vaccines* hidb::find_vaccines_in_chart(std::string aName, const Chart& aChart, const hidb::HiDb& aHiDb) { Vaccines* result = new Vaccines(Vaccine(aName, hidb::Vaccine::Previous)); vaccines_for_name(*result, aName, aChart, aHiDb); return result; } // find_vaccines_in_chart // ---------------------------------------------------------------------- void hidb::vaccines(VaccinesOfChart& aVaccinesOfChart, const Chart& aChart, const hidb::HiDb& aHiDb) { for (const auto& name_type: vaccines(aChart)) { aVaccinesOfChart.emplace_back(name_type); vaccines_for_name(aVaccinesOfChart.back(), name_type.name, aChart, aHiDb); } } // hidb::vaccines // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- std::string hidb::VaccinesOfChart::report(size_t aIndent) const { std::string result; for (const auto& v: *this) result += v.report(aIndent); return result; } // hidb::VaccinesOfChart::report // ---------------------------------------------------------------------- // void hidb::VaccinesOfChart::remove(std::string aName, std::string aType, std::string aPassageType) // { // for (auto& v: *this) { // if (v.match(aName, aType)) // v.remove(aPassageType); // } // erase(std::remove_if(begin(), end(), std::mem_fn<bool() const>(&hidb::Vaccines::empty)), end()); // } // hidb::VaccinesOfChart::remove // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>#include "RenderCameraSystem.hpp" #include <Components/CameraComponent.hpp> #include <Components/SpotLight.hh> #include <Components/DirectionalLightComponent.hh> #include <Components/Light.hh> #include <Core/Engine.hh> #include <Core/AScene.hh> #include <glm/gtc/matrix_transform.hpp> #include <BFC/BFCLinkTracker.hpp> #include <BFC/BFCBlockManagerFactory.hpp> #include <BFC/BFCCullableObject.hpp> #include <Graphic/DRBCameraDrawableList.hpp> #include <Graphic/DRBSpotLightData.hpp> #include <Graphic/BFCCullableTypes.hpp> #include <Graphic/DRBMeshData.hpp> #include <Threads/ThreadManager.hpp> #include <Threads/RenderThread.hpp> #include <Threads/MainThread.hpp> #include <Threads/Commands/ToRenderCommands.hpp> #include "Utils/Frustum.hh" #include "Utils/AABoundingBox.hh" #include <Render/OcclusionTools/DepthMap.hpp> #include <Render/OcclusionTools/DepthMapManager.hpp> #include <Render/OcclusionTools/DepthMapHandle.hpp> #include <Threads/TaskScheduler.hpp> #include <Threads/Tasks/BasicTasks.hpp> //temp #include <chrono> namespace AGE { RenderCameraSystem::RenderCameraSystem(AScene *scene) : System(std::move(scene)), _cameras(std::move(scene)), _spotLights(std::move(scene)), _directionnalLights(std::move(scene)), _pointLights(std::move(scene)) { _name = "Camera system"; } bool RenderCameraSystem::initialize() { _cameras.requireComponent<CameraComponent>(); _spotLights.requireComponent<SpotLightComponent>(); _directionnalLights.requireComponent<DirectionalLightComponent>(); _pointLights.requireComponent<PointLightComponent>(); return (true); } void RenderCameraSystem::updateBegin(float time) { } void occlusionCulling(std::list<std::shared_ptr<DRBData>> &list) { SCOPE_profile_cpu_function("Camera system"); auto depthMap = GetRenderThread()->getDepthMapManager().getReadableMap(); //for (auto &e : cameraList->meshs) //{ // readableDepthMap->testBox() //} if (depthMap.isValid() == false) { return; } auto j = list.begin(); while (j != std::end(list)) { auto &d = *j; auto BB = std::static_pointer_cast<DRBMeshData>(d)->getAABB(); glm::vec2 minPoint = glm::vec2(1); glm::vec2 maxPoint = glm::vec2(-1); float minZ = std::numeric_limits<float>::max(); for (std::size_t i = 0; i < 8; ++i) { auto point = depthMap->getMV() * d->getTransformation() * glm::vec4(BB.getCornerPoint(i), 1.0f); point /= point.w; if (point.x < -1) { point.x = -1; } if (point.y < -1) { point.y = -1; } if (point.x > 1) { point.x = 1; } if (point.y > 1) { point.y = 1; } minPoint.x = std::min(minPoint.x, point.x); minPoint.y = std::min(minPoint.y, point.y); maxPoint.x = std::max(maxPoint.x, point.x); maxPoint.y = std::max(maxPoint.y, point.y); point.z = (point.z + 1.0f) * 0.5f; minZ = std::min(minZ, point.z); } glm::uvec2 screenMin(((minPoint + glm::vec2(1)) / glm::vec2(2)) * glm::vec2(depthMap->getMipmapWidth(), depthMap->getMipmapHeight())); glm::uvec2 screenMax(((maxPoint + glm::vec2(1)) / glm::vec2(2)) * glm::vec2(depthMap->getMipmapWidth(), depthMap->getMipmapHeight())); if (minZ < 0) { minZ = 0; } if (depthMap->testBox((uint32_t)(minZ * (1 << 24)), screenMin, screenMax) == false) { list.erase(j++); } else { GetRenderThread()->getQueue()->emplaceTask<AGE::Commands::ToRender::Draw2DQuad>(glm::vec2(minPoint.x, minPoint.y), glm::vec2(minPoint.x, maxPoint.y), glm::vec2(maxPoint.x, maxPoint.y), glm::vec2(maxPoint.x, minPoint.y), glm::vec3(0.2666, 0.73725, 0.9921)); //GetRenderThread()->getQueue()->emplaceTask<AGE::Commands::ToRender::Draw2DLine>(glm::vec2(minPoint.x, minPoint.y), glm::vec2(minPoint.x, maxPoint.y), glm::vec3(0.2666, 0.73725, 0.9921)); //GetRenderThread()->getQueue()->emplaceTask<AGE::Commands::ToRender::Draw2DLine>(glm::vec2(minPoint.x, maxPoint.y), glm::vec2(maxPoint.x, maxPoint.y), glm::vec3(0.2666, 0.73725, 0.9921)); //GetRenderThread()->getQueue()->emplaceTask<AGE::Commands::ToRender::Draw2DLine>(glm::vec2(maxPoint.x, maxPoint.y), glm::vec2(maxPoint.x, minPoint.y), glm::vec3(0.2666, 0.73725, 0.9921)); //GetRenderThread()->getQueue()->emplaceTask<AGE::Commands::ToRender::Draw2DLine>(glm::vec2(maxPoint.x, minPoint.y), glm::vec2(minPoint.x, minPoint.y), glm::vec3(0.2666, 0.73725, 0.9921)); ++j; } } } void RenderCameraSystem::mainUpdate(float time) { SCOPE_profile_cpu_function("Camera system"); _scene->getBfcLinkTracker()->reset(); // check if the render thread does not already have stuff to draw if (GetMainThread()->isRenderFrame() == false) { return; } std::list<std::shared_ptr<DRBSpotLightDrawableList>> spotLightList; std::list<std::shared_ptr<DRBData>> pointLightList; for (auto &spotEntity : _spotLights.getCollection()) { auto spot = spotEntity->getComponent<SpotLightComponent>(); auto spotDrawableList = std::make_shared<DRBSpotLightDrawableList>(); spotDrawableList->spotLight = spot->getCullableHandle().getPtr()->getDatas(); auto spotData = std::static_pointer_cast<DRBSpotLightData>(spotDrawableList->spotLight); glm::mat4 spotViewProj = spot->updateShadowMatrix(); Frustum spotlightFrustum; spotlightFrustum.setMatrix(spotViewProj); // Draw spotlight frustum debug: glm::vec4 worldPos = glm::inverse(spotViewProj) * glm::vec4(-1, -1, -1, 1.0f); glm::vec3 aNear = glm::vec3(worldPos / worldPos.w); worldPos = glm::inverse(spotViewProj) * glm::vec4(-1, 1, -1, 1.0f); glm::vec3 bNear = glm::vec3(worldPos / worldPos.w); worldPos = glm::inverse(spotViewProj) * glm::vec4(1, 1, -1, 1.0f); glm::vec3 cNear = glm::vec3(worldPos / worldPos.w); worldPos = glm::inverse(spotViewProj) * glm::vec4(1, -1, -1, 1.0f); glm::vec3 dNear = glm::vec3(worldPos / worldPos.w); worldPos = glm::inverse(spotViewProj) * glm::vec4(-1, -1, 1, 1.0f); glm::vec3 aFar = glm::vec3(worldPos / worldPos.w); worldPos = glm::inverse(spotViewProj) * glm::vec4(-1, 1, 1, 1.0f); glm::vec3 bFar = glm::vec3(worldPos / worldPos.w); worldPos = glm::inverse(spotViewProj) * glm::vec4(1, 1, 1, 1.0f); glm::vec3 cFar = glm::vec3(worldPos / worldPos.w); worldPos = glm::inverse(spotViewProj) * glm::vec4(1, -1, 1, 1.0f); glm::vec3 dFar = glm::vec3(worldPos / worldPos.w); glm::vec3 color = glm::vec3(1, 0, 0); bool activateDepth = true; AGE::GetRenderThread()->getQueue()->emplaceTask<Commands::ToRender::Draw3DQuad>(aNear, bNear, cNear, dNear, color, activateDepth); AGE::GetRenderThread()->getQueue()->emplaceTask<Commands::ToRender::Draw3DQuad>(aFar, bFar, cFar, dFar, color, activateDepth); AGE::GetRenderThread()->getQueue()->emplaceTask<Commands::ToRender::Draw3DLine>(aNear, aFar, color, activateDepth); AGE::GetRenderThread()->getQueue()->emplaceTask<Commands::ToRender::Draw3DLine>(bNear, bFar, color, activateDepth); AGE::GetRenderThread()->getQueue()->emplaceTask<Commands::ToRender::Draw3DLine>(cNear, cFar, color, activateDepth); AGE::GetRenderThread()->getQueue()->emplaceTask<Commands::ToRender::Draw3DLine>(dNear, dFar, color, activateDepth); std::atomic_size_t counter = 0; LFList<BFCItem> meshInLightList; std::size_t meshBlocksToCullNumber = _scene->getBfcBlockManagerFactory()->getBlockNumberToCull(BFCCullableType::CullableMesh); for (std::size_t i = 0; i < meshBlocksToCullNumber; ++i) { BFCBlockManagerFactory *bf = _scene->getBfcBlockManagerFactory(); EmplaceTask<Tasks::Basic::VoidFunction>([bf, i, &spotlightFrustum, &counter, &meshInLightList](){ bf->cullOnBlock(BFCCullableType::CullableMesh, meshInLightList, spotlightFrustum, i); counter.fetch_add(1); }); } GetMainThread()->computeTasksWhile(std::function<bool()>([&counter, meshBlocksToCullNumber]() { return counter >= meshBlocksToCullNumber; })); while (meshInLightList.getSize() > 0) { spotDrawableList->meshs.push_back(meshInLightList.pop()->getDrawable()->getDatas()); } spotLightList.push_back(spotDrawableList); } for (auto &pointLightEntity : _pointLights.getCollection()) { auto point = pointLightEntity->getComponent<PointLightComponent>(); pointLightList.push_back(point->getCullableHandle().getPtr()->getDatas()); } for (auto &cameraEntity : _cameras.getCollection()) { Frustum cameraFrustum; auto camera = cameraEntity->getComponent<CameraComponent>(); std::atomic_size_t counter = 0; auto cameraList = std::make_shared<DRBCameraDrawableList>(); cameraList->cameraInfos.data = camera->getData(); cameraList->cameraInfos.view = glm::inverse(cameraEntity->getLink().getGlobalTransform()); cameraFrustum.setMatrix(camera->getProjection() * cameraList->cameraInfos.view); LFList<BFCItem> meshList; LFList<BFCItem> pointLightListToCull; std::size_t meshBlocksToCullNumber = _scene->getBfcBlockManagerFactory()->getBlockNumberToCull(BFCCullableType::CullableMesh); std::size_t pointLightBlocksToCullNumber = _scene->getBfcBlockManagerFactory()->getBlockNumberToCull(BFCCullableType::CullablePointLight); std::size_t totalToCullNumber = meshBlocksToCullNumber + pointLightBlocksToCullNumber; for (std::size_t i = 0; i < meshBlocksToCullNumber; ++i) { BFCBlockManagerFactory *bf = _scene->getBfcBlockManagerFactory(); EmplaceTask<Tasks::Basic::VoidFunction>([bf, i, &cameraFrustum, &counter, &meshList](){ bf->cullOnBlock(BFCCullableType::CullableMesh, meshList, cameraFrustum, i); counter.fetch_add(1); }); } for (std::size_t i = 0; i < pointLightBlocksToCullNumber; ++i) { BFCBlockManagerFactory *bf = _scene->getBfcBlockManagerFactory(); EmplaceTask<Tasks::Basic::VoidFunction>([bf, i, &cameraFrustum, &counter, &pointLightListToCull](){ bf->cullOnBlock(BFCCullableType::CullablePointLight, pointLightListToCull, cameraFrustum, i); counter.fetch_add(1); }); } GetMainThread()->computeTasksWhile(std::function<bool()>([&counter, totalToCullNumber]() { return counter >= totalToCullNumber; })); { SCOPE_profile_cpu_i("Camera system", "Copy LFList to std"); while (meshList.getSize() > 0) { cameraList->meshs.push_back(meshList.pop()->getDrawable()->getDatas()); } while (pointLightListToCull.getSize() > 0) { cameraList->pointLights.push_back(pointLightListToCull.pop()->getDrawable()->getDatas()); } } occlusionCulling(cameraList->meshs); cameraList->spotLights = spotLightList; cameraList->pointLights = pointLightList; AGE::GetRenderThread()->getQueue()->emplaceTask<AGE::DRBCameraDrawableListCommand>(cameraList); } } void RenderCameraSystem::updateEnd(float time) { } }<commit_msg>Profiling on camera system<commit_after>#include "RenderCameraSystem.hpp" #include <Components/CameraComponent.hpp> #include <Components/SpotLight.hh> #include <Components/DirectionalLightComponent.hh> #include <Components/Light.hh> #include <Core/Engine.hh> #include <Core/AScene.hh> #include <glm/gtc/matrix_transform.hpp> #include <BFC/BFCLinkTracker.hpp> #include <BFC/BFCBlockManagerFactory.hpp> #include <BFC/BFCCullableObject.hpp> #include <Graphic/DRBCameraDrawableList.hpp> #include <Graphic/DRBSpotLightData.hpp> #include <Graphic/BFCCullableTypes.hpp> #include <Graphic/DRBMeshData.hpp> #include <Threads/ThreadManager.hpp> #include <Threads/RenderThread.hpp> #include <Threads/MainThread.hpp> #include <Threads/Commands/ToRenderCommands.hpp> #include "Utils/Frustum.hh" #include "Utils/AABoundingBox.hh" #include <Render/OcclusionTools/DepthMap.hpp> #include <Render/OcclusionTools/DepthMapManager.hpp> #include <Render/OcclusionTools/DepthMapHandle.hpp> #include <Threads/TaskScheduler.hpp> #include <Threads/Tasks/BasicTasks.hpp> //temp #include <chrono> namespace AGE { RenderCameraSystem::RenderCameraSystem(AScene *scene) : System(std::move(scene)), _cameras(std::move(scene)), _spotLights(std::move(scene)), _directionnalLights(std::move(scene)), _pointLights(std::move(scene)) { _name = "Camera system"; } bool RenderCameraSystem::initialize() { _cameras.requireComponent<CameraComponent>(); _spotLights.requireComponent<SpotLightComponent>(); _directionnalLights.requireComponent<DirectionalLightComponent>(); _pointLights.requireComponent<PointLightComponent>(); return (true); } void RenderCameraSystem::updateBegin(float time) { } void occlusionCulling(std::list<std::shared_ptr<DRBData>> &list) { SCOPE_profile_cpu_function("Camera system"); auto depthMap = GetRenderThread()->getDepthMapManager().getReadableMap(); //for (auto &e : cameraList->meshs) //{ // readableDepthMap->testBox() //} if (depthMap.isValid() == false) { return; } auto j = list.begin(); while (j != std::end(list)) { auto &d = *j; auto BB = std::static_pointer_cast<DRBMeshData>(d)->getAABB(); glm::vec2 minPoint = glm::vec2(1); glm::vec2 maxPoint = glm::vec2(-1); float minZ = std::numeric_limits<float>::max(); for (std::size_t i = 0; i < 8; ++i) { auto point = depthMap->getMV() * d->getTransformation() * glm::vec4(BB.getCornerPoint(i), 1.0f); point /= point.w; if (point.x < -1) { point.x = -1; } if (point.y < -1) { point.y = -1; } if (point.x > 1) { point.x = 1; } if (point.y > 1) { point.y = 1; } minPoint.x = std::min(minPoint.x, point.x); minPoint.y = std::min(minPoint.y, point.y); maxPoint.x = std::max(maxPoint.x, point.x); maxPoint.y = std::max(maxPoint.y, point.y); point.z = (point.z + 1.0f) * 0.5f; minZ = std::min(minZ, point.z); } glm::uvec2 screenMin(((minPoint + glm::vec2(1)) / glm::vec2(2)) * glm::vec2(depthMap->getMipmapWidth(), depthMap->getMipmapHeight())); glm::uvec2 screenMax(((maxPoint + glm::vec2(1)) / glm::vec2(2)) * glm::vec2(depthMap->getMipmapWidth(), depthMap->getMipmapHeight())); if (minZ < 0) { minZ = 0; } if (depthMap->testBox((uint32_t)(minZ * (1 << 24)), screenMin, screenMax) == false) { list.erase(j++); } else { GetRenderThread()->getQueue()->emplaceTask<AGE::Commands::ToRender::Draw2DQuad>(glm::vec2(minPoint.x, minPoint.y), glm::vec2(minPoint.x, maxPoint.y), glm::vec2(maxPoint.x, maxPoint.y), glm::vec2(maxPoint.x, minPoint.y), glm::vec3(0.2666, 0.73725, 0.9921)); //GetRenderThread()->getQueue()->emplaceTask<AGE::Commands::ToRender::Draw2DLine>(glm::vec2(minPoint.x, minPoint.y), glm::vec2(minPoint.x, maxPoint.y), glm::vec3(0.2666, 0.73725, 0.9921)); //GetRenderThread()->getQueue()->emplaceTask<AGE::Commands::ToRender::Draw2DLine>(glm::vec2(minPoint.x, maxPoint.y), glm::vec2(maxPoint.x, maxPoint.y), glm::vec3(0.2666, 0.73725, 0.9921)); //GetRenderThread()->getQueue()->emplaceTask<AGE::Commands::ToRender::Draw2DLine>(glm::vec2(maxPoint.x, maxPoint.y), glm::vec2(maxPoint.x, minPoint.y), glm::vec3(0.2666, 0.73725, 0.9921)); //GetRenderThread()->getQueue()->emplaceTask<AGE::Commands::ToRender::Draw2DLine>(glm::vec2(maxPoint.x, minPoint.y), glm::vec2(minPoint.x, minPoint.y), glm::vec3(0.2666, 0.73725, 0.9921)); ++j; } } } void RenderCameraSystem::mainUpdate(float time) { SCOPE_profile_cpu_function("Camera system"); _scene->getBfcLinkTracker()->reset(); // check if the render thread does not already have stuff to draw if (GetMainThread()->isRenderFrame() == false) { return; } std::list<std::shared_ptr<DRBSpotLightDrawableList>> spotLightList; std::list<std::shared_ptr<DRBData>> pointLightList; for (auto &spotEntity : _spotLights.getCollection()) { auto spot = spotEntity->getComponent<SpotLightComponent>(); auto spotDrawableList = std::make_shared<DRBSpotLightDrawableList>(); spotDrawableList->spotLight = spot->getCullableHandle().getPtr()->getDatas(); auto spotData = std::static_pointer_cast<DRBSpotLightData>(spotDrawableList->spotLight); glm::mat4 spotViewProj = spot->updateShadowMatrix(); Frustum spotlightFrustum; spotlightFrustum.setMatrix(spotViewProj); // Draw spotlight frustum debug: glm::vec4 worldPos = glm::inverse(spotViewProj) * glm::vec4(-1, -1, -1, 1.0f); glm::vec3 aNear = glm::vec3(worldPos / worldPos.w); worldPos = glm::inverse(spotViewProj) * glm::vec4(-1, 1, -1, 1.0f); glm::vec3 bNear = glm::vec3(worldPos / worldPos.w); worldPos = glm::inverse(spotViewProj) * glm::vec4(1, 1, -1, 1.0f); glm::vec3 cNear = glm::vec3(worldPos / worldPos.w); worldPos = glm::inverse(spotViewProj) * glm::vec4(1, -1, -1, 1.0f); glm::vec3 dNear = glm::vec3(worldPos / worldPos.w); worldPos = glm::inverse(spotViewProj) * glm::vec4(-1, -1, 1, 1.0f); glm::vec3 aFar = glm::vec3(worldPos / worldPos.w); worldPos = glm::inverse(spotViewProj) * glm::vec4(-1, 1, 1, 1.0f); glm::vec3 bFar = glm::vec3(worldPos / worldPos.w); worldPos = glm::inverse(spotViewProj) * glm::vec4(1, 1, 1, 1.0f); glm::vec3 cFar = glm::vec3(worldPos / worldPos.w); worldPos = glm::inverse(spotViewProj) * glm::vec4(1, -1, 1, 1.0f); glm::vec3 dFar = glm::vec3(worldPos / worldPos.w); glm::vec3 color = glm::vec3(1, 0, 0); bool activateDepth = true; AGE::GetRenderThread()->getQueue()->emplaceTask<Commands::ToRender::Draw3DQuad>(aNear, bNear, cNear, dNear, color, activateDepth); AGE::GetRenderThread()->getQueue()->emplaceTask<Commands::ToRender::Draw3DQuad>(aFar, bFar, cFar, dFar, color, activateDepth); AGE::GetRenderThread()->getQueue()->emplaceTask<Commands::ToRender::Draw3DLine>(aNear, aFar, color, activateDepth); AGE::GetRenderThread()->getQueue()->emplaceTask<Commands::ToRender::Draw3DLine>(bNear, bFar, color, activateDepth); AGE::GetRenderThread()->getQueue()->emplaceTask<Commands::ToRender::Draw3DLine>(cNear, cFar, color, activateDepth); AGE::GetRenderThread()->getQueue()->emplaceTask<Commands::ToRender::Draw3DLine>(dNear, dFar, color, activateDepth); std::atomic_size_t counter = 0; LFList<BFCItem> meshInLightList; std::size_t meshBlocksToCullNumber = _scene->getBfcBlockManagerFactory()->getBlockNumberToCull(BFCCullableType::CullableMesh); for (std::size_t i = 0; i < meshBlocksToCullNumber; ++i) { BFCBlockManagerFactory *bf = _scene->getBfcBlockManagerFactory(); EmplaceTask<Tasks::Basic::VoidFunction>([bf, i, &spotlightFrustum, &counter, &meshInLightList](){ bf->cullOnBlock(BFCCullableType::CullableMesh, meshInLightList, spotlightFrustum, i); counter.fetch_add(1); }); } { SCOPE_profile_cpu_i("Camera system", "Cull for spots"); GetMainThread()->computeTasksWhile(std::function<bool()>([&counter, meshBlocksToCullNumber]() { return counter >= meshBlocksToCullNumber; })); } while (meshInLightList.getSize() > 0) { spotDrawableList->meshs.push_back(meshInLightList.pop()->getDrawable()->getDatas()); } spotLightList.push_back(spotDrawableList); } for (auto &pointLightEntity : _pointLights.getCollection()) { auto point = pointLightEntity->getComponent<PointLightComponent>(); pointLightList.push_back(point->getCullableHandle().getPtr()->getDatas()); } for (auto &cameraEntity : _cameras.getCollection()) { Frustum cameraFrustum; auto camera = cameraEntity->getComponent<CameraComponent>(); std::atomic_size_t counter = 0; auto cameraList = std::make_shared<DRBCameraDrawableList>(); cameraList->cameraInfos.data = camera->getData(); cameraList->cameraInfos.view = glm::inverse(cameraEntity->getLink().getGlobalTransform()); cameraFrustum.setMatrix(camera->getProjection() * cameraList->cameraInfos.view); LFList<BFCItem> meshList; LFList<BFCItem> pointLightListToCull; std::size_t meshBlocksToCullNumber = _scene->getBfcBlockManagerFactory()->getBlockNumberToCull(BFCCullableType::CullableMesh); std::size_t pointLightBlocksToCullNumber = _scene->getBfcBlockManagerFactory()->getBlockNumberToCull(BFCCullableType::CullablePointLight); std::size_t totalToCullNumber = meshBlocksToCullNumber + pointLightBlocksToCullNumber; for (std::size_t i = 0; i < meshBlocksToCullNumber; ++i) { BFCBlockManagerFactory *bf = _scene->getBfcBlockManagerFactory(); EmplaceTask<Tasks::Basic::VoidFunction>([bf, i, &cameraFrustum, &counter, &meshList](){ bf->cullOnBlock(BFCCullableType::CullableMesh, meshList, cameraFrustum, i); counter.fetch_add(1); }); } for (std::size_t i = 0; i < pointLightBlocksToCullNumber; ++i) { BFCBlockManagerFactory *bf = _scene->getBfcBlockManagerFactory(); EmplaceTask<Tasks::Basic::VoidFunction>([bf, i, &cameraFrustum, &counter, &pointLightListToCull](){ bf->cullOnBlock(BFCCullableType::CullablePointLight, pointLightListToCull, cameraFrustum, i); counter.fetch_add(1); }); } { SCOPE_profile_cpu_i("Camera system", "Cull for cam"); GetMainThread()->computeTasksWhile(std::function<bool()>([&counter, totalToCullNumber]() { return counter >= totalToCullNumber; })); } { SCOPE_profile_cpu_i("Camera system", "Copy LFList to std"); while (meshList.getSize() > 0) { cameraList->meshs.push_back(meshList.pop()->getDrawable()->getDatas()); } while (pointLightListToCull.getSize() > 0) { cameraList->pointLights.push_back(pointLightListToCull.pop()->getDrawable()->getDatas()); } } occlusionCulling(cameraList->meshs); cameraList->spotLights = spotLightList; cameraList->pointLights = pointLightList; AGE::GetRenderThread()->getQueue()->emplaceTask<AGE::DRBCameraDrawableListCommand>(cameraList); } } void RenderCameraSystem::updateEnd(float time) { } }<|endoftext|>
<commit_before>enum Atom { atomRegister, atomSum, atomDereference, atomByte, atomWord, atomMov, atomPop, atomALU, atomOut, atomXchg, atomSegmentOverride, atomInc, atomJCond, atomJmp }; #include "unity/symbol.h" static const int c = 52; static const int s = 22; static const int b = 21; int state = 0; // States: // 0 = Block start // 1 = Mixing // 2 = Block finish // 3 = Frame update int mixingSample = 0; int block = 0; int voice = 0; class InstructionByte { private: Instruction* _instruction; int _byte; }; class InstructionCycle { private: Instruction* _instruction; int _cycle; }; Symbol parseRegister(CharacterSource* source) { static String ax("ax"); static String bx("bx"); static String cx("cx"); static String dx("dx"); static String si("si"); static String di("di"); static String sp("sp"); static String bp("bp"); static String al("al"); static String bl("bl"); static String cl("cl"); static String dl("dl"); static String ah("ah"); static String bh("bh"); static String ch("ch"); static String dh("dh"); static String cs("cs"); static String ss("ss"); static String es("es"); static String ds("ds"); Span span; if (Space::parseKeyword(source, ax, &span)) return Symbol(atomRegister, Symbol(atomWord), 0); if (Space::parseKeyword(source, cx, &span)) return Symbol(atomRegister, Symbol(atomWord), 1); if (Space::parseKeyword(source, dx, &span)) return Symbol(atomRegister, Symbol(atomWord), 2); if (Space::parseKeyword(source, bx, &span)) return Symbol(atomRegister, Symbol(atomWord), 3); if (Space::parseKeyword(source, sp, &span)) return Symbol(atomRegister, Symbol(atomWord), 4); if (Space::parseKeyword(source, bp, &span)) return Symbol(atomRegister, Symbol(atomWord), 5); if (Space::parseKeyword(source, si, &span)) return Symbol(atomRegister, Symbol(atomWord), 6); if (Space::parseKeyword(source, di, &span)) return Symbol(atomRegister, Symbol(atomWord), 7); if (Space::parseKeyword(source, al, &span)) return Symbol(atomRegister, Symbol(atomWord), 0); if (Space::parseKeyword(source, cl, &span)) return Symbol(atomRegister, Symbol(atomWord), 1); if (Space::parseKeyword(source, dl, &span)) return Symbol(atomRegister, Symbol(atomWord), 2); if (Space::parseKeyword(source, bl, &span)) return Symbol(atomRegister, Symbol(atomWord), 3); if (Space::parseKeyword(source, ah, &span)) return Symbol(atomRegister, Symbol(atomWord), 4); if (Space::parseKeyword(source, ch, &span)) return Symbol(atomRegister, Symbol(atomWord), 5); if (Space::parseKeyword(source, dh, &span)) return Symbol(atomRegister, Symbol(atomWord), 6); if (Space::parseKeyword(source, bh, &span)) return Symbol(atomRegister, Symbol(atomWord), 7); if (Space::parseKeyword(source, es, &span)) return Symbol(atomRegister, Symbol(atomSegmentOverride), 0); if (Space::parseKeyword(source, cs, &span)) return Symbol(atomRegister, Symbol(atomSegmentOverride), 1); if (Space::parseKeyword(source, ss, &span)) return Symbol(atomRegister, Symbol(atomSegmentOverride), 2); if (Space::parseKeyword(source, ds, &span)) return Symbol(atomRegister, Symbol(atomSegmentOverride), 3); return Symbol(); } Symbol parseMemory(CharacterSource* source) { } int parseHexadecimalCharacter(CharacterSource* source, Span* span) { CharacterSource s = *source; int c = s.get(span); if (c >= '0' && c <= '9') { *source = s; return c - '0'; } if (c >= 'A' && c <= 'F') { *source = s; return c + 10 - 'A'; } if (c >= 'a' && c <= 'f') { *source = s; return c + 10 - 'a'; } return -1; } Symbol parseInteger(CharacterSource* source) { CharacterSource s = *source; int n = 0; Span span; int c = s.get(&span); if (c < '0' || c > '9') return Symbol(); if (c == '0') { do { Span span2; int d = parseHexadecimalCharacter(source, &span2); if (d == -1) break; n = n*16 + d; span += span2; } while (true); } do { n = n*10 + c - '0'; *source = s; Span span2; c = s.get(&span2); if (c < '0' || c > '9') break; span += span2; } while (true); Space::parse(source); return Symbol(atomIntegerConstant, n); } Symbol parseLValue(CharacterSource* source) { Symbol l = parseRegister(source); if (l.valid()) return l; l = parseMemory(source); if (l.valid()) return l; throw Exception(); } Symbol parseExpression(CharacterSource* source) { Symbol e = parseInteger(source); if (e.valid()) return e; return parseLValue(source); } class Instruction { public: Instruction(String text) { CharacterSource source(text, ""); Space::parse(&source); Span span; static String mov("mov"); if (Space::parseKeyword(source, mov, &span)) { Symbol left = parseLValue(&source); if (!Space::parseCharacter(&source, ',', &span)) throw Exception(); Symbol right = parseExpression(&source); /* 88 /r MOV rmb,rb 2 5+EA+4 89 /r MOV rmw,rw 2 5+EA+8 8A /r MOV rb,rmb 2 4+EA+4 8B /r MOV rw,rmw 2 4+EA+8 A0 iw MOV AL,xb 6+4 A1 iw MOV AX,xw 6+8 A2 iw MOV xb,AL 6+4 A3 iw MOV xw,AX 6+8 B? ib MOV rb,ib 4 B? iw MOV rw,iw 4 C6 /0 ib MOV rmb,ib 4 6+EA+4 C6 /r ib MOV rmb,ib 4 6+EA+4 C7 /0 iw MOV rmw,iw 4 6+EA+8 C7 /r iw MOV rmw,iw 4 6+EA+8 8C /r MOV rmw,segreg 2 5+EA+8 8E /r MOV segreg,rmw 2 4+EA+8 */ } static String pop("pop"); /* 5? POP rw 4+8 */ static String add("add"); static String adc("adc"); static String sub("sub"); static String cmp("cmp"); /* ?? /r alu rmb,rb 3 8+EA+4+4 ?? /r alu rmw,rw 3 8+EA+8+8 ?? /r alu rb,rmb 3 5+EA+4 ?? /r alu rw,rmw 3 5+EA+8 ?? ib alu AL,ib 4 ?? iw alu AX,iw 4 80 /? ib alu rmb,ib 4 9+EA+4+4 81 /0 iw alu rmw,iw 4 9+EA+8+8 83 /? ib alu rmw,ib 4 9+EA+8+8 38 /r CMP rmb,rb 3 5+EA+4 39 /r CMP rmw,rw 3 5+EA+8 80 /7 ib CMP rmb,ib 4 6+EA+4 81 /7 iw CMP rmw,iw 4 6+EA+8 83 /7 ib CMP rmw,ib 4 6+EA+8 */ static String out("out"); /* E6 ib OUT ib,AL 6+4 */ static String xchg("xchg"); /* 86 /r XCHG rmb,rb 4 9+EA+4+4 */ static String es("es:"); /* ?? segreg: */ static String inc("inc"); /* 4? INC rw 2 */ static String je("je"); /* 7? cb Jcond cb 4/16 */ static String jmp("jmp"); /* E9 cw JMP cw 15 */ } private: String _text; int _bytes; Byte _data[5]; int _ios; int _position; int _cycle; }; Instruction getNextInstruction() { do { Instruction i; switch (state) { case 0: i = getNextInstructionMixing(); if (i.valid()) return i; state = 1; break; case 1: i = getNextInstruction } int main() { } <commit_msg>MOD player assembler<commit_after>enum Atom { atomRegister, atomSum, atomDereference, atomByte, atomWord, atomMov, atomPop, atomALU, atomOut, atomXchg, atomSegmentOverride, atomInc, atomJCond, atomJmp }; #include "unity/symbol.h" static const int c = 52; static const int s = 22; static const int b = 21; int state = 0; // States: // 0 = Block start // 1 = Mixing // 2 = Block finish // 3 = Frame update int mixingSample = 0; int block = 0; int voice = 0; class InstructionByte { private: Instruction* _instruction; int _byte; }; class InstructionCycle { private: Instruction* _instruction; int _cycle; }; Symbol parseRegister(CharacterSource* source) { static String ax("ax"); static String bx("bx"); static String cx("cx"); static String dx("dx"); static String si("si"); static String di("di"); static String sp("sp"); static String bp("bp"); static String al("al"); static String bl("bl"); static String cl("cl"); static String dl("dl"); static String ah("ah"); static String bh("bh"); static String ch("ch"); static String dh("dh"); static String cs("cs"); static String ss("ss"); static String es("es"); static String ds("ds"); Span span; if (Space::parseKeyword(source, ax, &span)) return Symbol(atomRegister, Symbol(atomWord), 0); if (Space::parseKeyword(source, cx, &span)) return Symbol(atomRegister, Symbol(atomWord), 1); if (Space::parseKeyword(source, dx, &span)) return Symbol(atomRegister, Symbol(atomWord), 2); if (Space::parseKeyword(source, bx, &span)) return Symbol(atomRegister, Symbol(atomWord), 3); if (Space::parseKeyword(source, sp, &span)) return Symbol(atomRegister, Symbol(atomWord), 4); if (Space::parseKeyword(source, bp, &span)) return Symbol(atomRegister, Symbol(atomWord), 5); if (Space::parseKeyword(source, si, &span)) return Symbol(atomRegister, Symbol(atomWord), 6); if (Space::parseKeyword(source, di, &span)) return Symbol(atomRegister, Symbol(atomWord), 7); if (Space::parseKeyword(source, al, &span)) return Symbol(atomRegister, Symbol(atomWord), 0); if (Space::parseKeyword(source, cl, &span)) return Symbol(atomRegister, Symbol(atomWord), 1); if (Space::parseKeyword(source, dl, &span)) return Symbol(atomRegister, Symbol(atomWord), 2); if (Space::parseKeyword(source, bl, &span)) return Symbol(atomRegister, Symbol(atomWord), 3); if (Space::parseKeyword(source, ah, &span)) return Symbol(atomRegister, Symbol(atomWord), 4); if (Space::parseKeyword(source, ch, &span)) return Symbol(atomRegister, Symbol(atomWord), 5); if (Space::parseKeyword(source, dh, &span)) return Symbol(atomRegister, Symbol(atomWord), 6); if (Space::parseKeyword(source, bh, &span)) return Symbol(atomRegister, Symbol(atomWord), 7); if (Space::parseKeyword(source, es, &span)) return Symbol(atomRegister, Symbol(atomSegmentOverride), 0); if (Space::parseKeyword(source, cs, &span)) return Symbol(atomRegister, Symbol(atomSegmentOverride), 1); if (Space::parseKeyword(source, ss, &span)) return Symbol(atomRegister, Symbol(atomSegmentOverride), 2); if (Space::parseKeyword(source, ds, &span)) return Symbol(atomRegister, Symbol(atomSegmentOverride), 3); return Symbol(); } Symbol parseMemory(CharacterSource* source, Span* span) { CharacterSource s = *source; Span span; Span span2; int c = s.get(span); int size = 0; if (c == 'b' || c == 'B') { Space::parse(&s); size = 1; c = s.get(span2); span += span2; } else if (c == 'w' || c == 'W') { Space::parse(&s); size = 2; c = s.get(span2); span += span2; } if (c != '[') return Symbol(); Space::parse(&s); Symbol expression = parseExpression(&s, &span2); if (!expression.valid()) throw Exception(); span += span2; c = s.get(span); if (c != ']') throw Exception(); Space::parse(&s); span += span2; *source = s; return Symbol(atomDereference, size, expression); } int parseHexadecimalCharacter(CharacterSource* source, Span* span) { CharacterSource s = *source; int c = s.get(span); if (c >= '0' && c <= '9') { *source = s; return c - '0'; } if (c >= 'A' && c <= 'F') { *source = s; return c + 10 - 'A'; } if (c >= 'a' && c <= 'f') { *source = s; return c + 10 - 'a'; } return -1; } Symbol parseInteger(CharacterSource* source) { CharacterSource s = *source; int n = 0; Span span; int c = s.get(&span); if (c < '0' || c > '9') return Symbol(); if (c == '0') { do { Span span2; int d = parseHexadecimalCharacter(source, &span2); if (d == -1) break; n = n*16 + d; span += span2; } while (true); } do { n = n*10 + c - '0'; *source = s; Span span2; c = s.get(&span2); if (c < '0' || c > '9') break; span += span2; } while (true); Space::parse(source); return Symbol(atomIntegerConstant, n); } Symbol parseLValue(CharacterSource* source) { Symbol l = parseRegister(source); if (l.valid()) return l; l = parseMemory(source); if (l.valid()) return l; throw Exception(); } Symbol parseExpression(CharacterSource* source) { Symbol e = parseInteger(source); if (e.valid()) return e; return parseLValue(source); } class Instruction { public: Instruction(String text) { CharacterSource source(text, ""); Space::parse(&source); Span span; static String mov("mov"); if (Space::parseKeyword(source, mov, &span)) { Symbol left = parseLValue(&source); if (!Space::parseCharacter(&source, ',', &span)) throw Exception(); Symbol right = parseExpression(&source); /* 88 /r MOV rmb,rb 2 5+EA+4 89 /r MOV rmw,rw 2 5+EA+8 8A /r MOV rb,rmb 2 4+EA+4 8B /r MOV rw,rmw 2 4+EA+8 A0 iw MOV AL,xb 6+4 A1 iw MOV AX,xw 6+8 A2 iw MOV xb,AL 6+4 A3 iw MOV xw,AX 6+8 B? ib MOV rb,ib 4 B? iw MOV rw,iw 4 C6 /0 ib MOV rmb,ib 4 6+EA+4 C6 /r ib MOV rmb,ib 4 6+EA+4 C7 /0 iw MOV rmw,iw 4 6+EA+8 C7 /r iw MOV rmw,iw 4 6+EA+8 8C /r MOV rmw,segreg 2 5+EA+8 8E /r MOV segreg,rmw 2 4+EA+8 */ } static String pop("pop"); /* 5? POP rw 4+8 */ static String add("add"); static String adc("adc"); static String sub("sub"); static String cmp("cmp"); /* ?? /r alu rmb,rb 3 8+EA+4+4 ?? /r alu rmw,rw 3 8+EA+8+8 ?? /r alu rb,rmb 3 5+EA+4 ?? /r alu rw,rmw 3 5+EA+8 ?? ib alu AL,ib 4 ?? iw alu AX,iw 4 80 /? ib alu rmb,ib 4 9+EA+4+4 81 /0 iw alu rmw,iw 4 9+EA+8+8 83 /? ib alu rmw,ib 4 9+EA+8+8 38 /r CMP rmb,rb 3 5+EA+4 39 /r CMP rmw,rw 3 5+EA+8 80 /7 ib CMP rmb,ib 4 6+EA+4 81 /7 iw CMP rmw,iw 4 6+EA+8 83 /7 ib CMP rmw,ib 4 6+EA+8 */ static String out("out"); /* E6 ib OUT ib,AL 6+4 */ static String xchg("xchg"); /* 86 /r XCHG rmb,rb 4 9+EA+4+4 */ static String es("es:"); /* ?? segreg: */ static String inc("inc"); /* 4? INC rw 2 */ static String je("je"); /* 7? cb Jcond cb 4/16 */ static String jmp("jmp"); /* E9 cw JMP cw 15 */ } private: String _text; int _bytes; Byte _data[5]; int _ios; int _position; int _cycle; }; Instruction getNextInstruction() { do { Instruction i; switch (state) { case 0: i = getNextInstructionMixing(); if (i.valid()) return i; state = 1; break; case 1: i = getNextInstruction } int main() { } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved */ #include "../../StroikaPreComp.h" #include <cstdio> #if qPlatform_POSIX #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <net/if.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <netinet/in.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #elif qPlatform_Windows #include <WinSock2.h> #include <WS2tcpip.h> #include <Iphlpapi.h> #include <netioapi.h> #endif #include "../../Characters/CString/Utilities.h" #include "../../Containers/Collection.h" #include "../../Execution/ErrNoException.h" #include "../../Execution/Thread.h" #if qPlatform_Windows #include "../../../Foundation/Execution/Platform/Windows/Exception.h" #endif #include "Socket.h" #include "Interface.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Memory; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::Network; Traversal::Iterable<Interface> Network::GetInterfaces () { Collection<Interface> result; #if qPlatform_POSIX auto getFlags = [] (int sd, const char* name) { char buf[1024]; struct ifreq ifreq; memset(&ifreq, 0, sizeof (ifreq)); strcpy (ifreq.ifr_name, name); int r = ioctl (sd, SIOCGIFFLAGS, (char*)&ifreq); Assert (r == 0); return (ifreq.ifr_flags); }; struct ifreq ifreqs[64]; struct ifconf ifconf; memset (&ifconf, 0, sizeof(ifconf)); ifconf.ifc_req = ifreqs; ifconf.ifc_len = sizeof(ifreqs); int sd = socket (PF_INET, SOCK_STREAM, 0); Assert (sd >= 0); int r = ioctl (sd, SIOCGIFCONF, (char*)&ifconf); Assert (r == 0); InternetAddress result; for (int i = 0; i < ifconf.ifc_len / sizeof(struct ifreq); ++i) { Interface newInterface; newInterface.fInterfaceName = String::FromSDKString (ifreqs[i].ifr_name); int flags = getFlags (sd, ifreqs[i].ifr_name); if (flags & IFF_LOOPBACK) { newInterface.fType = Interface::Type::eLoopback; } else { // NYI newInterface.fType = Interface::Type::eEthernet; // WAY - not the right way to tell! } { Containers::Set<Interface::Status> status; if (flags & IFF_RUNNING) { // not right!!! But a start... status.Add (Interface::Status::eConnected); status.Add (Interface::Status::eRunning); } newInterface.fStatus = status; } newInterface.fBindings.Add (InternetAddress (((struct sockaddr_in*)&ifreqs[i].ifr_addr)->sin_addr)); } close (sd); #else AssertNotImplemented (); #endif return result; }<commit_msg>minor poxix tweaks on recent changes<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2014. All rights reserved */ #include "../../StroikaPreComp.h" #include <cstdio> #if qPlatform_POSIX #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <net/if.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <netinet/in.h> #include <linux/netlink.h> #include <linux/rtnetlink.h> #elif qPlatform_Windows #include <WinSock2.h> #include <WS2tcpip.h> #include <Iphlpapi.h> #include <netioapi.h> #endif #include "../../Characters/CString/Utilities.h" #include "../../Containers/Collection.h" #include "../../Execution/ErrNoException.h" #include "../../Execution/Thread.h" #if qPlatform_Windows #include "../../../Foundation/Execution/Platform/Windows/Exception.h" #endif #include "Socket.h" #include "Interface.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::Memory; using namespace Stroika::Foundation::IO; using namespace Stroika::Foundation::IO::Network; Traversal::Iterable<Interface> Network::GetInterfaces () { Collection<Interface> result; #if qPlatform_POSIX auto getFlags = [] (int sd, const char* name) { char buf[1024]; struct ifreq ifreq; memset(&ifreq, 0, sizeof (ifreq)); strcpy (ifreq.ifr_name, name); int r = ioctl (sd, SIOCGIFFLAGS, (char*)&ifreq); Assert (r == 0); return (ifreq.ifr_flags); }; struct ifreq ifreqs[64]; struct ifconf ifconf; memset (&ifconf, 0, sizeof(ifconf)); ifconf.ifc_req = ifreqs; ifconf.ifc_len = sizeof(ifreqs); int sd = socket (PF_INET, SOCK_STREAM, 0); Assert (sd >= 0); int r = ioctl (sd, SIOCGIFCONF, (char*)&ifconf); Assert (r == 0); for (int i = 0; i < ifconf.ifc_len / sizeof(struct ifreq); ++i) { Interface newInterface; newInterface.fInterfaceName = String::FromSDKString (ifreqs[i].ifr_name); int flags = getFlags (sd, ifreqs[i].ifr_name); if (flags & IFF_LOOPBACK) { newInterface.fType = Interface::Type::eLoopback; } else { // NYI newInterface.fType = Interface::Type::eWiredEthernet; // WAY - not the right way to tell! } { Containers::Set<Interface::Status> status; if (flags & IFF_RUNNING) { // not right!!! But a start... status.Add (Interface::Status::eConnected); status.Add (Interface::Status::eRunning); } newInterface.fStatus = status; } newInterface.fBindings.Add (InternetAddress (((struct sockaddr_in*)&ifreqs[i].ifr_addr)->sin_addr)); } close (sd); #else AssertNotImplemented (); #endif return result; } <|endoftext|>
<commit_before>//===--- driver.cpp - Swift Compiler Driver -------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This is the entry point to the swift compiler driver. // //===----------------------------------------------------------------------===// #include "swift/AST/DiagnosticEngine.h" #include "swift/Basic/LLVMInitialize.h" #include "swift/Basic/Program.h" #include "swift/Basic/SourceManager.h" #include "swift/Driver/Compilation.h" #include "swift/Driver/Driver.h" #include "swift/Driver/FrontendUtil.h" #include "swift/Driver/Job.h" #include "swift/Driver/ToolChain.h" #include "swift/Frontend/Frontend.h" #include "swift/Frontend/PrintingDiagnosticConsumer.h" #include "swift/FrontendTool/FrontendTool.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Errno.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Host.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/Path.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Process.h" #include "llvm/Support/Program.h" #include "llvm/Support/Signals.h" #include "llvm/Support/StringSaver.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/raw_ostream.h" #include <memory> #include <stdlib.h> using namespace swift; using namespace swift::driver; std::string getExecutablePath(const char *FirstArg) { void *P = (void *)(intptr_t)getExecutablePath; return llvm::sys::fs::getMainExecutable(FirstArg, P); } /// Run 'swift-autolink-extract'. extern int autolink_extract_main(ArrayRef<const char *> Args, const char *Argv0, void *MainAddr); extern int modulewrap_main(ArrayRef<const char *> Args, const char *Argv0, void *MainAddr); /// Run 'swift-format' extern int swift_format_main(ArrayRef<const char *> Args, const char *Argv0, void *MainAddr); /// Determine if the given invocation should run as a subcommand. /// /// \param ExecName The name of the argv[0] we were invoked as. /// \param SubcommandName On success, the full name of the subcommand to invoke. /// \param Args On return, the adjusted program arguments to use. /// \returns True if running as a subcommand. static bool shouldRunAsSubcommand(StringRef ExecName, SmallString<256> &SubcommandName, SmallVectorImpl<const char *> &Args) { assert(!Args.empty()); // If we are not run as 'swift', don't do anything special. This doesn't work // with symlinks with alternate names, but we can't detect 'swift' vs 'swiftc' // if we try and resolve using the actual executable path. if (ExecName != "swift") return false; // If there are no program arguments, always invoke as normal. if (Args.size() == 1) return false; // Otherwise, we have a program argument. If it looks like an option or a // path, then invoke in interactive mode with the arguments as given. StringRef FirstArg(Args[1]); if (FirstArg.startswith("-") || FirstArg.find('.') != StringRef::npos || FirstArg.find('/') != StringRef::npos) return false; // Otherwise, we should have some sort of subcommand. Get the subcommand name // and remove it from the program arguments. StringRef Subcommand = Args[1]; Args.erase(&Args[1]); // If the subcommand is the "built-in" 'repl', then use the // normal driver. if (Subcommand == "repl") return false; // Form the subcommand name. SubcommandName.assign("swift-"); SubcommandName.append(Subcommand); return true; } extern int apinotes_main(ArrayRef<const char *> Args); int main(int argc_, const char **argv_) { PROGRAM_START(argc_, argv_); SmallVector<const char *, 256> argv; llvm::SpecificBumpPtrAllocator<char> ArgAllocator; std::error_code EC = llvm::sys::Process::GetArgumentVector( argv, llvm::ArrayRef<const char *>(argv_, argc_), ArgAllocator); if (EC) { llvm::errs() << "error: couldn't get arguments: " << EC.message() << '\n'; return 1; } // Expand any response files in the command line argument vector llvm::BumpPtrAllocator Allocator; llvm::StringSaver Saver(Allocator); llvm::cl::ExpandResponseFiles( Saver, llvm::Triple(llvm::sys::getProcessTriple()).isOSWindows() ? llvm::cl::TokenizeWindowsCommandLine : llvm::cl::TokenizeGNUCommandLine, argv); // Check if this invocation should execute a subcommand. StringRef ExecName = llvm::sys::path::stem(argv[0]); SmallString<256> SubcommandName; if (shouldRunAsSubcommand(ExecName, SubcommandName, argv)) { // We are running as a subcommand, try to find the subcommand adjacent to // the executable we are running as. SmallString<256> SubcommandPath( llvm::sys::path::parent_path(getExecutablePath(argv[0]))); llvm::sys::path::append(SubcommandPath, SubcommandName); // If we didn't find the tool there, let the OS search for it. if (!llvm::sys::fs::exists(SubcommandPath)) { // Search for the program and use the path if found. If there was an // error, ignore it and just let the exec fail. auto result = llvm::sys::findProgramByName(SubcommandName); if (!result.getError()) SubcommandPath = *result; } // Rewrite the program argument. argv[0] = SubcommandPath.c_str(); // Execute the subcommand. argv.push_back(nullptr); ExecuteInPlace(SubcommandPath.c_str(), argv.data()); // If we reach here then an error occurred (typically a missing path). std::string ErrorString = llvm::sys::StrError(); llvm::errs() << "error: unable to invoke subcommand: " << argv[0] << " (" << ErrorString << ")\n"; return 2; } // Handle integrated tools. if (argv.size() > 1) { StringRef FirstArg(argv[1]); if (FirstArg == "-frontend") { return performFrontend(llvm::makeArrayRef(argv.data()+2, argv.data()+argv.size()), argv[0], (void *)(intptr_t)getExecutablePath); } if (FirstArg == "-modulewrap") { return modulewrap_main(llvm::makeArrayRef(argv.data()+2, argv.data()+argv.size()), argv[0], (void *)(intptr_t)getExecutablePath); } if (FirstArg == "-apinotes") { return apinotes_main(llvm::makeArrayRef(argv.data()+1, argv.data()+argv.size())); } } std::string Path = getExecutablePath(argv[0]); PrintingDiagnosticConsumer PDC; SourceManager SM; DiagnosticEngine Diags(SM); Diags.addConsumer(PDC); Driver TheDriver(Path, ExecName, argv, Diags); switch (TheDriver.getDriverKind()) { case Driver::DriverKind::AutolinkExtract: return autolink_extract_main( TheDriver.getArgsWithoutProgramNameAndDriverMode(argv), argv[0], (void *)(intptr_t)getExecutablePath); case Driver::DriverKind::SwiftFormat: return swift_format_main( TheDriver.getArgsWithoutProgramNameAndDriverMode(argv), argv[0], (void *)(intptr_t)getExecutablePath); default: break; } std::unique_ptr<llvm::opt::InputArgList> ArgList = TheDriver.parseArgStrings(ArrayRef<const char*>(argv).slice(1)); if (Diags.hadAnyError()) return 1; std::unique_ptr<ToolChain> TC = TheDriver.buildToolChain(*ArgList); if (Diags.hadAnyError()) return 1; std::unique_ptr<Compilation> C = TheDriver.buildCompilation(*TC, std::move(ArgList)); if (Diags.hadAnyError()) return 1; if (C) { return C->performJobs(); } return 0; } <commit_msg>Elaborate on the purpose of response files.<commit_after>//===--- driver.cpp - Swift Compiler Driver -------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This is the entry point to the swift compiler driver. // //===----------------------------------------------------------------------===// #include "swift/AST/DiagnosticEngine.h" #include "swift/Basic/LLVMInitialize.h" #include "swift/Basic/Program.h" #include "swift/Basic/SourceManager.h" #include "swift/Driver/Compilation.h" #include "swift/Driver/Driver.h" #include "swift/Driver/FrontendUtil.h" #include "swift/Driver/Job.h" #include "swift/Driver/ToolChain.h" #include "swift/Frontend/Frontend.h" #include "swift/Frontend/PrintingDiagnosticConsumer.h" #include "swift/FrontendTool/FrontendTool.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Errno.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Host.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/Path.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Process.h" #include "llvm/Support/Program.h" #include "llvm/Support/Signals.h" #include "llvm/Support/StringSaver.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/raw_ostream.h" #include <memory> #include <stdlib.h> using namespace swift; using namespace swift::driver; std::string getExecutablePath(const char *FirstArg) { void *P = (void *)(intptr_t)getExecutablePath; return llvm::sys::fs::getMainExecutable(FirstArg, P); } /// Run 'swift-autolink-extract'. extern int autolink_extract_main(ArrayRef<const char *> Args, const char *Argv0, void *MainAddr); extern int modulewrap_main(ArrayRef<const char *> Args, const char *Argv0, void *MainAddr); /// Run 'swift-format' extern int swift_format_main(ArrayRef<const char *> Args, const char *Argv0, void *MainAddr); /// Determine if the given invocation should run as a subcommand. /// /// \param ExecName The name of the argv[0] we were invoked as. /// \param SubcommandName On success, the full name of the subcommand to invoke. /// \param Args On return, the adjusted program arguments to use. /// \returns True if running as a subcommand. static bool shouldRunAsSubcommand(StringRef ExecName, SmallString<256> &SubcommandName, SmallVectorImpl<const char *> &Args) { assert(!Args.empty()); // If we are not run as 'swift', don't do anything special. This doesn't work // with symlinks with alternate names, but we can't detect 'swift' vs 'swiftc' // if we try and resolve using the actual executable path. if (ExecName != "swift") return false; // If there are no program arguments, always invoke as normal. if (Args.size() == 1) return false; // Otherwise, we have a program argument. If it looks like an option or a // path, then invoke in interactive mode with the arguments as given. StringRef FirstArg(Args[1]); if (FirstArg.startswith("-") || FirstArg.find('.') != StringRef::npos || FirstArg.find('/') != StringRef::npos) return false; // Otherwise, we should have some sort of subcommand. Get the subcommand name // and remove it from the program arguments. StringRef Subcommand = Args[1]; Args.erase(&Args[1]); // If the subcommand is the "built-in" 'repl', then use the // normal driver. if (Subcommand == "repl") return false; // Form the subcommand name. SubcommandName.assign("swift-"); SubcommandName.append(Subcommand); return true; } extern int apinotes_main(ArrayRef<const char *> Args); int main(int argc_, const char **argv_) { PROGRAM_START(argc_, argv_); SmallVector<const char *, 256> argv; llvm::SpecificBumpPtrAllocator<char> ArgAllocator; std::error_code EC = llvm::sys::Process::GetArgumentVector( argv, llvm::ArrayRef<const char *>(argv_, argc_), ArgAllocator); if (EC) { llvm::errs() << "error: couldn't get arguments: " << EC.message() << '\n'; return 1; } // Expand any response files in the command line argument vector - arguments // may be passed through response files in the event of command line length // restrictions. llvm::BumpPtrAllocator Allocator; llvm::StringSaver Saver(Allocator); llvm::cl::ExpandResponseFiles( Saver, llvm::Triple(llvm::sys::getProcessTriple()).isOSWindows() ? llvm::cl::TokenizeWindowsCommandLine : llvm::cl::TokenizeGNUCommandLine, argv); // Check if this invocation should execute a subcommand. StringRef ExecName = llvm::sys::path::stem(argv[0]); SmallString<256> SubcommandName; if (shouldRunAsSubcommand(ExecName, SubcommandName, argv)) { // We are running as a subcommand, try to find the subcommand adjacent to // the executable we are running as. SmallString<256> SubcommandPath( llvm::sys::path::parent_path(getExecutablePath(argv[0]))); llvm::sys::path::append(SubcommandPath, SubcommandName); // If we didn't find the tool there, let the OS search for it. if (!llvm::sys::fs::exists(SubcommandPath)) { // Search for the program and use the path if found. If there was an // error, ignore it and just let the exec fail. auto result = llvm::sys::findProgramByName(SubcommandName); if (!result.getError()) SubcommandPath = *result; } // Rewrite the program argument. argv[0] = SubcommandPath.c_str(); // Execute the subcommand. argv.push_back(nullptr); ExecuteInPlace(SubcommandPath.c_str(), argv.data()); // If we reach here then an error occurred (typically a missing path). std::string ErrorString = llvm::sys::StrError(); llvm::errs() << "error: unable to invoke subcommand: " << argv[0] << " (" << ErrorString << ")\n"; return 2; } // Handle integrated tools. if (argv.size() > 1) { StringRef FirstArg(argv[1]); if (FirstArg == "-frontend") { return performFrontend(llvm::makeArrayRef(argv.data()+2, argv.data()+argv.size()), argv[0], (void *)(intptr_t)getExecutablePath); } if (FirstArg == "-modulewrap") { return modulewrap_main(llvm::makeArrayRef(argv.data()+2, argv.data()+argv.size()), argv[0], (void *)(intptr_t)getExecutablePath); } if (FirstArg == "-apinotes") { return apinotes_main(llvm::makeArrayRef(argv.data()+1, argv.data()+argv.size())); } } std::string Path = getExecutablePath(argv[0]); PrintingDiagnosticConsumer PDC; SourceManager SM; DiagnosticEngine Diags(SM); Diags.addConsumer(PDC); Driver TheDriver(Path, ExecName, argv, Diags); switch (TheDriver.getDriverKind()) { case Driver::DriverKind::AutolinkExtract: return autolink_extract_main( TheDriver.getArgsWithoutProgramNameAndDriverMode(argv), argv[0], (void *)(intptr_t)getExecutablePath); case Driver::DriverKind::SwiftFormat: return swift_format_main( TheDriver.getArgsWithoutProgramNameAndDriverMode(argv), argv[0], (void *)(intptr_t)getExecutablePath); default: break; } std::unique_ptr<llvm::opt::InputArgList> ArgList = TheDriver.parseArgStrings(ArrayRef<const char*>(argv).slice(1)); if (Diags.hadAnyError()) return 1; std::unique_ptr<ToolChain> TC = TheDriver.buildToolChain(*ArgList); if (Diags.hadAnyError()) return 1; std::unique_ptr<Compilation> C = TheDriver.buildCompilation(*TC, std::move(ArgList)); if (Diags.hadAnyError()) return 1; if (C) { return C->performJobs(); } return 0; } <|endoftext|>
<commit_before>/****************************************************************************** * * Project: integrating laszip into liblas - http://liblas.org - * Purpose: * Author: Martin Isenburg * isenburg at cs.unc.edu * ****************************************************************************** * Copyright (c) 2010, Martin Isenburg * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Licence as published * by the Free Software Foundation. * * See the COPYING file for more information. * ****************************************************************************/ /* =============================================================================== FILE: laszippertest.cpp CONTENTS: This tool reads and writes point data in the LAS 1.X format compressed or uncompressed to test the laszipper and lasunzipper interfaces. PROGRAMMERS: martin isenburg@cs.unc.edu COPYRIGHT: copyright (C) 2010 martin isenburg@cs.unc.edu This software 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. CHANGE HISTORY: 13 December 2010 -- created to test the remodularized laszip compressor =============================================================================== */ #include "laszipper.hpp" #include "lasunzipper.hpp" #ifdef LZ_WIN32_VC6 #include <fstream.h> #else #include <istream> #include <fstream> using namespace std; #endif #include <time.h> #include <stdio.h> static double taketime() { return (double)(clock())/CLOCKS_PER_SEC; } int main(int argc, char *argv[]) { unsigned char c; unsigned int i, j; unsigned int num_points = 100000; unsigned int num_errors, num_bytes; double start_time, end_time; FILE* ofile1 = 0; FILE* ofile2 = 0; FILE* ofile3 = 0; FILE* ifile1 = 0; FILE* ifile2 = 0; FILE* ifile3 = 0; filebuf ofb1; filebuf ofb2; filebuf ofb3; filebuf ifb1; filebuf ifb2; filebuf ifb3; #ifdef LZ_WIN32_VC6 ostream* ostream1 = 0; ostream* ostream2 = 0; ostream* ostream3 = 0; istream* istream1 = 0; istream* istream2 = 0; istream* istream3 = 0; #else ofstream* ostream1 = 0; ofstream* ostream2 = 0; ofstream* ostream3 = 0; ifstream* istream1 = 0; ifstream* istream2 = 0; ifstream* istream3 = 0; #endif bool use_iostream = false; // describe the point structure unsigned int num_items = 5; LASitem items[5]; items[0].type = LASitem::POINT10; items[0].size = 20; items[0].version = 0; items[1].type = LASitem::GPSTIME11; items[1].size = 8; items[1].version = 0; items[2].type = LASitem::RGB12; items[2].size = 6; items[2].version = 0; items[3].type = LASitem::WAVEPACKET13; items[3].size = 29; items[3].version = 0; items[4].type = LASitem::BYTE; items[4].size = 7; items[4].version = 0; // compute the point size unsigned int point_size = 0; for (i = 0; i < num_items; i++) point_size += items[i].size; // create the point data unsigned int point_offset = 0; unsigned char** point = new unsigned char*[num_items]; unsigned char* point_data = new unsigned char[point_size]; for (i = 0; i < num_items; i++) { point[i] = &(point_data[point_offset]); point_offset += items[i].size; } LASzipper* laszipper1 = new LASzipper(); // without compression LASzipper* laszipper2 = new LASzipper(); // with arithmetic compression LASzipper* laszipper3 = new LASzipper(); // with range compression if (use_iostream) { #ifdef LZ_WIN32_VC6 ofb1.open("test1.lax", ios::out); ofb1.setmode(filebuf::binary); ostream1 = new ostream(&ofb1); #else ostream1 = new ofstream(); ostream1->open("test1.lax", std::ios::out | std::ios::binary ); #endif if (laszipper1->open(*ostream1, num_items, items, LASZIP_COMPRESSION_NONE) != 0) { fprintf(stderr, "ERROR: could not open laszipper1\n"); return 0; } #ifdef LZ_WIN32_VC6 ofb2.open("test2.lax", ios::out); ofb2.setmode(filebuf::binary); ostream2 = new ostream(&ofb2); #else ostream2 = new ofstream(); ostream2->open("test2.lax", std::ios::out | std::ios::binary ); #endif if (laszipper2->open(*ostream2, num_items, items, LASZIP_COMPRESSION_ARITHMETIC) != 0) { fprintf(stderr, "ERROR: could not open laszipper2\n"); return 0; } #ifdef LZ_WIN32_VC6 ofb3.open("test3.lax", ios::out); ofb3.setmode(filebuf::binary); ostream3 = new ostream(&ofb3); #else ostream3 = new ofstream(); ostream3->open("test3.lax", std::ios::out | std::ios::binary ); #endif if (laszipper3->open(*ostream3, num_items, items, LASZIP_COMPRESSION_RANGE) != 0) { fprintf(stderr, "ERROR: could not open laszipper3\n"); return 0; } } else { ofile1 = fopen("test1.lax", "wb"); if (!laszipper1->open(ofile1, num_items, items, LASZIP_COMPRESSION_NONE)) { fprintf(stderr, "ERROR: could not open laszipper1\n"); return 0; } ofile2 = fopen("test2.lax", "wb"); if (!laszipper2->open(ofile2, num_items, items, LASZIP_COMPRESSION_ARITHMETIC)) { fprintf(stderr, "ERROR: could not open laszipper2\n"); return 0; } ofile3 = fopen("test3.lax", "wb"); if (!laszipper3->open(ofile3, num_items, items, LASZIP_COMPRESSION_RANGE)) { fprintf(stderr, "ERROR: could not open laszipper3\n"); return 0; } } // write / compress num_points with "random" data start_time = taketime(); c = 0; for (i = 0; i < num_points; i++) { for (j = 0; j < point_size; j++) { point_data[j] = c; c++; } laszipper1->write(point); } num_bytes = laszipper1->close(); end_time = taketime(); fprintf(stderr, "laszipper1 wrote %d bytes in %g seconds\n", num_bytes, end_time-start_time); start_time = taketime(); c = 0; for (i = 0; i < num_points; i++) { for (j = 0; j < point_size; j++) { point_data[j] = c; c++; } laszipper2->write(point); } num_bytes = laszipper2->close(); end_time = taketime(); fprintf(stderr, "laszipper2 wrote %d bytes in %g seconds\n", num_bytes, end_time-start_time); start_time = taketime(); c = 0; for (i = 0; i < num_points; i++) { for (j = 0; j < point_size; j++) { point_data[j] = c; c++; } laszipper3->write(point); } num_bytes = laszipper3->close(); end_time = taketime(); fprintf(stderr, "laszipper3 wrote %d bytes in %g seconds\n", num_bytes, end_time-start_time); delete laszipper1; delete laszipper2; delete laszipper3; if (use_iostream) { delete ostream1; delete ostream2; delete ostream3; #ifdef LZ_WIN32_VC6 ofb1.close(); ofb2.close(); ofb3.close(); #endif } else { fclose(ofile1); fclose(ofile2); fclose(ofile3); } LASunzipper* lasunzipper1 = new LASunzipper(); // without compression LASunzipper* lasunzipper2 = new LASunzipper(); // with arithmetic compression LASunzipper* lasunzipper3 = new LASunzipper(); // with range compression if (use_iostream) { #ifdef LZ_WIN32_VC6 ifb1.open("test1.lax", ios::in); ifb1.setmode(filebuf::binary); istream1 = new istream(&ifb1); #else istream1 = new ifstream(); istream1->open("test1.lax", std::ios::in | std::ios::binary ); #endif if (lasunzipper1->open(*istream1, num_items, items, LASZIP_COMPRESSION_NONE) != 0) { fprintf(stderr, "ERROR: could not open lasunzipper1\n"); return 0; } #ifdef LZ_WIN32_VC6 ifb2.open("test2.lax", ios::in); ifb2.setmode(filebuf::binary); istream2 = new istream(&ifb2); #else istream2 = new ifstream(); istream2->open("test2.lax", std::ios::in | std::ios::binary ); #endif if (lasunzipper2->open(istream2, num_items, items, LASZIP_COMPRESSION_ARITHMETIC) != 0) { fprintf(stderr, "ERROR: could not open lasunzipper2\n"); return 0; } #ifdef LZ_WIN32_VC6 ifb3.open("test3.lax", ios::in); ifb3.setmode(filebuf::binary); istream3 = new istream(&ifb3); #else istream3 = new ifstream(); istream3->open("test3.lax", std::ios::in | std::ios::binary ); #endif if (lasunzipper3->open(istream3, num_items, items, LASZIP_COMPRESSION_RANGE) != 0) { fprintf(stderr, "ERROR: could not open lasunzipper3\n"); return 0; } } else { ifile1 = fopen("test1.lax", "rb"); if (!lasunzipper1->open(ifile1, num_items, items, LASZIP_COMPRESSION_NONE)) { fprintf(stderr, "ERROR: could not open lasunzipper1\n"); return 0; } ifile2 = fopen("test2.lax", "rb"); if (!lasunzipper2->open(ifile2, num_items, items, LASZIP_COMPRESSION_ARITHMETIC)) { fprintf(stderr, "ERROR: could not open lasunzipper2\n"); return 0; } ifile3 = fopen("test3.lax", "rb"); if (!lasunzipper3->open(ifile3, num_items, items, LASZIP_COMPRESSION_RANGE)) { fprintf(stderr, "ERROR: could not open lasunzipper3\n"); return 0; } } // read num_points with "random" data start_time = taketime(); num_errors = 0; c = 0; for (i = 0; i < num_points; i++) { lasunzipper1->read(point); for (j = 0; j < point_size; j++) { if (point_data[j] != c) { fprintf(stderr, "%d %d %d != %d\n", i, j, point_data[j], c); num_errors++; if (num_errors > 20) return -1; } c++; } } num_bytes = lasunzipper1->close(); end_time = taketime(); if (num_errors) { fprintf(stderr, "ERROR: with lasunzipper1 %d\n", num_errors); } else { fprintf(stderr, "SUCCESS: lasunzipper1 read %d bytes in %g seconds\n", num_bytes, end_time-start_time); } // decompress num_points with "random" data start_time = taketime(); num_errors = 0; c = 0; for (i = 0; i < num_points; i++) { lasunzipper2->read(point); for (j = 0; j < point_size; j++) { if (point_data[j] != c) { fprintf(stderr, "%d %d %d != %d\n", i, j, point_data[j], c); num_errors++; if (num_errors > 20) return -1; } c++; } } num_bytes = lasunzipper2->close(); end_time = taketime(); if (num_errors) { fprintf(stderr, "ERROR: with lasunzipper2 %d\n", num_errors); } else { fprintf(stderr, "SUCCESS: lasunzipper2 read %d bytes in %g seconds\n", num_bytes, end_time-start_time); } // decompress num_points with "random" data start_time = taketime(); num_errors = 0; c = 0; for (i = 0; i < num_points; i++) { lasunzipper3->read(point); for (j = 0; j < point_size; j++) { if (point_data[j] != c) { fprintf(stderr, "%d %d %d != %d\n", i, j, point_data[j], c); num_errors++; if (num_errors > 20) return -1; } c++; } } num_bytes = lasunzipper3->close(); end_time = taketime(); if (num_errors) { fprintf(stderr, "ERROR: with lasunzipper3 %d\n", num_errors); } else { fprintf(stderr, "SUCCESS: lasunzipper3 read %d bytes in %g seconds\n", num_bytes, end_time-start_time); } delete lasunzipper1; delete lasunzipper2; delete lasunzipper3; if (use_iostream) { delete istream1; delete istream2; delete istream3; #ifdef LZ_WIN32_VC6 ifb1.close(); ifb2.close(); ifb3.close(); #endif } else { fclose(ifile1); fclose(ifile2); fclose(ifile3); } return 0; } <commit_msg>added test for new WAVEPACKET13 compressor<commit_after>/****************************************************************************** * * Project: integrating laszip into liblas - http://liblas.org - * Purpose: * Author: Martin Isenburg * isenburg at cs.unc.edu * ****************************************************************************** * Copyright (c) 2010, Martin Isenburg * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Licence as published * by the Free Software Foundation. * * See the COPYING file for more information. * ****************************************************************************/ /* =============================================================================== FILE: laszippertest.cpp CONTENTS: This tool reads and writes point data in the LAS 1.X format compressed or uncompressed to test the laszipper and lasunzipper interfaces. PROGRAMMERS: martin isenburg@cs.unc.edu COPYRIGHT: copyright (C) 2010 martin isenburg@cs.unc.edu This software 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. CHANGE HISTORY: 13 December 2010 -- created to test the remodularized laszip compressor =============================================================================== */ #include "laszipper.hpp" #include "lasunzipper.hpp" #ifdef LZ_WIN32_VC6 #include <fstream.h> #else #include <istream> #include <fstream> using namespace std; #endif #include <time.h> #include <stdio.h> static double taketime() { return (double)(clock())/CLOCKS_PER_SEC; } int main(int argc, char *argv[]) { unsigned char c; unsigned int i, j; unsigned int num_points = 100000; unsigned int num_errors, num_bytes; double start_time, end_time; FILE* ofile1 = 0; FILE* ofile2 = 0; FILE* ofile3 = 0; FILE* ifile1 = 0; FILE* ifile2 = 0; FILE* ifile3 = 0; filebuf ofb1; filebuf ofb2; filebuf ofb3; filebuf ifb1; filebuf ifb2; filebuf ifb3; #ifdef LZ_WIN32_VC6 ostream* ostream1 = 0; ostream* ostream2 = 0; ostream* ostream3 = 0; istream* istream1 = 0; istream* istream2 = 0; istream* istream3 = 0; #else ofstream* ostream1 = 0; ofstream* ostream2 = 0; ofstream* ostream3 = 0; ifstream* istream1 = 0; ifstream* istream2 = 0; ifstream* istream3 = 0; #endif bool use_iostream = false; // describe the point structure unsigned int num_items = 5; LASitem items[5]; items[0].type = LASitem::POINT10; items[0].size = 20; items[0].version = 0; items[1].type = LASitem::GPSTIME11; items[1].size = 8; items[1].version = 0; items[2].type = LASitem::RGB12; items[2].size = 6; items[2].version = 0; items[3].type = LASitem::WAVEPACKET13; items[3].size = 29; items[3].version = 0; items[4].type = LASitem::BYTE; items[4].size = 7; items[4].version = 0; // compute the point size unsigned int point_size = 0; for (i = 0; i < num_items; i++) point_size += items[i].size; // create the point data unsigned int point_offset = 0; unsigned char** point = new unsigned char*[num_items]; unsigned char* point_data = new unsigned char[point_size]; for (i = 0; i < num_items; i++) { point[i] = &(point_data[point_offset]); point_offset += items[i].size; } LASzipper* laszipper1 = new LASzipper(); // without compression LASzipper* laszipper2 = new LASzipper(); // with arithmetic compression LASzipper* laszipper3 = new LASzipper(); // with range compression if (use_iostream) { #ifdef LZ_WIN32_VC6 ofb1.open("test1.lax", ios::out); ofb1.setmode(filebuf::binary); ostream1 = new ostream(&ofb1); #else ostream1 = new ofstream(); ostream1->open("test1.lax", std::ios::out | std::ios::binary ); #endif if (laszipper1->open(*ostream1, num_items, items, LASZIP_COMPRESSION_NONE) != 0) { fprintf(stderr, "ERROR: could not open laszipper1\n"); return 0; } #ifdef LZ_WIN32_VC6 ofb2.open("test2.lax", ios::out); ofb2.setmode(filebuf::binary); ostream2 = new ostream(&ofb2); #else ostream2 = new ofstream(); ostream2->open("test2.lax", std::ios::out | std::ios::binary ); #endif if (laszipper2->open(*ostream2, num_items, items, LASZIP_COMPRESSION_ARITHMETIC) != 0) { fprintf(stderr, "ERROR: could not open laszipper2\n"); return 0; } #ifdef LZ_WIN32_VC6 ofb3.open("test3.lax", ios::out); ofb3.setmode(filebuf::binary); ostream3 = new ostream(&ofb3); #else ostream3 = new ofstream(); ostream3->open("test3.lax", std::ios::out | std::ios::binary ); #endif if (laszipper3->open(*ostream3, num_items, items, LASZIP_COMPRESSION_RANGE) != 0) { fprintf(stderr, "ERROR: could not open laszipper3\n"); return 0; } } else { ofile1 = fopen("test1.lax", "wb"); if (!laszipper1->open(ofile1, num_items, items, LASZIP_COMPRESSION_NONE)) { fprintf(stderr, "ERROR: could not open laszipper1\n"); return 0; } ofile2 = fopen("test2.lax", "wb"); if (!laszipper2->open(ofile2, num_items, items, LASZIP_COMPRESSION_ARITHMETIC)) { fprintf(stderr, "ERROR: could not open laszipper2\n"); return 0; } ofile3 = fopen("test3.lax", "wb"); if (!laszipper3->open(ofile3, num_items, items, LASZIP_COMPRESSION_RANGE)) { fprintf(stderr, "ERROR: could not open laszipper3\n"); return 0; } } // write / compress num_points with "random" data start_time = taketime(); c = 0; for (i = 0; i < num_points; i++) { for (j = 0; j < point_size; j++) { point_data[j] = c; c++; } laszipper1->write(point); } num_bytes = laszipper1->close(); end_time = taketime(); fprintf(stderr, "laszipper1 wrote %d bytes in %g seconds\n", num_bytes, end_time-start_time); start_time = taketime(); c = 0; for (i = 0; i < num_points; i++) { for (j = 0; j < point_size; j++) { point_data[j] = c; c++; } laszipper2->write(point); } num_bytes = laszipper2->close(); end_time = taketime(); fprintf(stderr, "laszipper2 wrote %d bytes in %g seconds\n", num_bytes, end_time-start_time); start_time = taketime(); c = 0; for (i = 0; i < num_points; i++) { for (j = 0; j < point_size; j++) { point_data[j] = c; c++; } laszipper3->write(point); } num_bytes = laszipper3->close(); end_time = taketime(); fprintf(stderr, "laszipper3 wrote %d bytes in %g seconds\n", num_bytes, end_time-start_time); delete laszipper1; delete laszipper2; delete laszipper3; if (use_iostream) { delete ostream1; delete ostream2; delete ostream3; #ifdef LZ_WIN32_VC6 ofb1.close(); ofb2.close(); ofb3.close(); #endif } else { fclose(ofile1); fclose(ofile2); fclose(ofile3); } LASunzipper* lasunzipper1 = new LASunzipper(); // without compression LASunzipper* lasunzipper2 = new LASunzipper(); // with arithmetic compression LASunzipper* lasunzipper3 = new LASunzipper(); // with range compression if (use_iostream) { #ifdef LZ_WIN32_VC6 ifb1.open("test1.lax", ios::in); ifb1.setmode(filebuf::binary); istream1 = new istream(&ifb1); #else istream1 = new ifstream(); istream1->open("test1.lax", std::ios::in | std::ios::binary ); #endif if (lasunzipper1->open(*istream1, num_items, items, LASZIP_COMPRESSION_NONE) != 0) { fprintf(stderr, "ERROR: could not open lasunzipper1\n"); return 0; } #ifdef LZ_WIN32_VC6 ifb2.open("test2.lax", ios::in); ifb2.setmode(filebuf::binary); istream2 = new istream(&ifb2); #else istream2 = new ifstream(); istream2->open("test2.lax", std::ios::in | std::ios::binary ); #endif if (lasunzipper2->open(*istream2, num_items, items, LASZIP_COMPRESSION_ARITHMETIC) != 0) { fprintf(stderr, "ERROR: could not open lasunzipper2\n"); return 0; } #ifdef LZ_WIN32_VC6 ifb3.open("test3.lax", ios::in); ifb3.setmode(filebuf::binary); istream3 = new istream(&ifb3); #else istream3 = new ifstream(); istream3->open("test3.lax", std::ios::in | std::ios::binary ); #endif if (lasunzipper3->open(*istream3, num_items, items, LASZIP_COMPRESSION_RANGE) != 0) { fprintf(stderr, "ERROR: could not open lasunzipper3\n"); return 0; } } else { ifile1 = fopen("test1.lax", "rb"); if (!lasunzipper1->open(ifile1, num_items, items, LASZIP_COMPRESSION_NONE)) { fprintf(stderr, "ERROR: could not open lasunzipper1\n"); return 0; } ifile2 = fopen("test2.lax", "rb"); if (!lasunzipper2->open(ifile2, num_items, items, LASZIP_COMPRESSION_ARITHMETIC)) { fprintf(stderr, "ERROR: could not open lasunzipper2\n"); return 0; } ifile3 = fopen("test3.lax", "rb"); if (!lasunzipper3->open(ifile3, num_items, items, LASZIP_COMPRESSION_RANGE)) { fprintf(stderr, "ERROR: could not open lasunzipper3\n"); return 0; } } // read num_points with "random" data start_time = taketime(); num_errors = 0; c = 0; for (i = 0; i < num_points; i++) { lasunzipper1->read(point); for (j = 0; j < point_size; j++) { if (point_data[j] != c) { fprintf(stderr, "%d %d %d != %d\n", i, j, point_data[j], c); num_errors++; if (num_errors > 20) return -1; } c++; } } num_bytes = lasunzipper1->close(); end_time = taketime(); if (num_errors) { fprintf(stderr, "ERROR: with lasunzipper1 %d\n", num_errors); } else { fprintf(stderr, "SUCCESS: lasunzipper1 read %d bytes in %g seconds\n", num_bytes, end_time-start_time); } // decompress num_points with "random" data start_time = taketime(); num_errors = 0; c = 0; for (i = 0; i < num_points; i++) { lasunzipper2->read(point); for (j = 0; j < point_size; j++) { if (point_data[j] != c) { fprintf(stderr, "%d %d %d != %d\n", i, j, point_data[j], c); num_errors++; if (num_errors > 20) return -1; } c++; } } num_bytes = lasunzipper2->close(); end_time = taketime(); if (num_errors) { fprintf(stderr, "ERROR: with lasunzipper2 %d\n", num_errors); } else { fprintf(stderr, "SUCCESS: lasunzipper2 read %d bytes in %g seconds\n", num_bytes, end_time-start_time); } // decompress num_points with "random" data start_time = taketime(); num_errors = 0; c = 0; for (i = 0; i < num_points; i++) { lasunzipper3->read(point); for (j = 0; j < point_size; j++) { if (point_data[j] != c) { fprintf(stderr, "%d %d %d != %d\n", i, j, point_data[j], c); num_errors++; if (num_errors > 20) return -1; } c++; } } num_bytes = lasunzipper3->close(); end_time = taketime(); if (num_errors) { fprintf(stderr, "ERROR: with lasunzipper3 %d\n", num_errors); } else { fprintf(stderr, "SUCCESS: lasunzipper3 read %d bytes in %g seconds\n", num_bytes, end_time-start_time); } delete lasunzipper1; delete lasunzipper2; delete lasunzipper3; if (use_iostream) { delete istream1; delete istream2; delete istream3; #ifdef LZ_WIN32_VC6 ifb1.close(); ifb2.close(); ifb3.close(); #endif } else { fclose(ifile1); fclose(ifile2); fclose(ifile3); } return 0; } <|endoftext|>
<commit_before>#include <shogun/features/Labels.h> #include <shogun/io/StreamingAsciiFile.h> #include <shogun/io/SGIO.h> #include <shogun/features/StreamingDenseFeatures.h> #include <shogun/features/DenseFeatures.h> #include <shogun/multiclass/MulticlassOneVsOneStrategy.h> #include <shogun/machine/LinearMulticlassMachine.h> #include <shogun/classifier/svm/LibLinear.h> #include <shogun/base/init.h> #define EPSILON 1e-5 using namespace shogun; int main(int argc, char** argv) { int32_t num_vectors = 0; int32_t num_feats = 2; init_shogun_with_defaults(); // Prepare to read a file for the training data char fname_feats[] = "../data/fm_train_real.dat"; char fname_labels[] = "../data/label_train_multiclass.dat"; CStreamingAsciiFile* ffeats_train = new CStreamingAsciiFile(fname_feats); CStreamingAsciiFile* flabels_train = new CStreamingAsciiFile(fname_labels); SG_REF(ffeats_train); SG_REF(flabels_train); CStreamingDenseFeatures< float64_t >* stream_features = new CStreamingDenseFeatures< float64_t >(ffeats_train, false, 1024); CStreamingDenseFeatures< float64_t >* stream_labels = new CStreamingDenseFeatures< float64_t >(flabels_train, true, 1024); SG_REF(stream_features); SG_REF(stream_labels); // Create a matrix with enough space to read all the feature vectors SGMatrix< float64_t > mat = SGMatrix< float64_t >(num_feats, 1000); // Read the values from the file and store them in mat SGVector< float64_t > vec; stream_features->start_parser(); while ( stream_features->get_next_example() ) { vec = stream_features->get_vector(); for ( int32_t i = 0 ; i < num_feats ; ++i ) mat[num_vectors*num_feats + i] = vec[i]; num_vectors++; stream_features->release_example(); } stream_features->end_parser(); // Create features with the useful values from mat CDenseFeatures< float64_t >* features = new CDenseFeatures< float64_t >(mat.matrix, num_feats, num_vectors); CLabels* labels = new CLabels(num_vectors); SG_REF(features); SG_REF(labels); // Read the labels from the file int32_t idx = 0; stream_labels->start_parser(); while ( stream_labels->get_next_example() ) { labels->set_int_label( idx++, (int32_t)stream_labels->get_label() ); stream_labels->release_example(); } stream_labels->end_parser(); // Create liblinear svm classifier with L2-regularized L2-loss CLibLinear* svm = new CLibLinear(L2R_L2LOSS_SVC); SG_REF(svm); // Add some configuration to the svm svm->set_epsilon(EPSILON); svm->set_bias_enabled(true); // Create a multiclass svm classifier that consists of several of the previous one CLinearMulticlassMachine* mc_svm = new CLinearMulticlassMachine( new CMulticlassOneVsOneStrategy(), (CDotFeatures*) features, svm, labels); SG_REF(mc_svm); // Train the multiclass machine using the data passed in the constructor mc_svm->train(); // Classify the training examples and show the results CLabels* output = mc_svm->apply(); SGVector< int32_t > out_labels = output->get_int_labels(); CMath::display_vector(out_labels.vector, out_labels.vlen); // Free resources SG_UNREF(mc_svm); SG_UNREF(svm); SG_UNREF(output); SG_UNREF(features); SG_UNREF(labels); SG_UNREF(ffeats_train); SG_UNREF(flabels_train); SG_UNREF(stream_features); SG_UNREF(stream_labels); exit_shogun(); return 0; } <commit_msg>fix double free in example<commit_after>#include <shogun/features/Labels.h> #include <shogun/io/StreamingAsciiFile.h> #include <shogun/io/SGIO.h> #include <shogun/features/StreamingDenseFeatures.h> #include <shogun/features/DenseFeatures.h> #include <shogun/multiclass/MulticlassOneVsOneStrategy.h> #include <shogun/machine/LinearMulticlassMachine.h> #include <shogun/classifier/svm/LibLinear.h> #include <shogun/base/init.h> #define EPSILON 1e-5 using namespace shogun; int main(int argc, char** argv) { int32_t num_vectors = 0; int32_t num_feats = 2; init_shogun_with_defaults(); // Prepare to read a file for the training data char fname_feats[] = "../data/fm_train_real.dat"; char fname_labels[] = "../data/label_train_multiclass.dat"; CStreamingAsciiFile* ffeats_train = new CStreamingAsciiFile(fname_feats); CStreamingAsciiFile* flabels_train = new CStreamingAsciiFile(fname_labels); SG_REF(ffeats_train); SG_REF(flabels_train); CStreamingDenseFeatures< float64_t >* stream_features = new CStreamingDenseFeatures< float64_t >(ffeats_train, false, 1024); CStreamingDenseFeatures< float64_t >* stream_labels = new CStreamingDenseFeatures< float64_t >(flabels_train, true, 1024); SG_REF(stream_features); SG_REF(stream_labels); // Create a matrix with enough space to read all the feature vectors SGMatrix< float64_t > mat = SGMatrix< float64_t >(num_feats, 1000); // Read the values from the file and store them in mat SGVector< float64_t > vec; stream_features->start_parser(); while ( stream_features->get_next_example() ) { vec = stream_features->get_vector(); for ( int32_t i = 0 ; i < num_feats ; ++i ) mat.matrix[num_vectors*num_feats + i] = vec[i]; num_vectors++; stream_features->release_example(); } stream_features->end_parser(); // Create features with the useful values from mat CDenseFeatures< float64_t >* features = new CDenseFeatures<float64_t>(mat); CLabels* labels = new CLabels(num_vectors); SG_REF(features); SG_REF(labels); // Read the labels from the file int32_t idx = 0; stream_labels->start_parser(); while ( stream_labels->get_next_example() ) { labels->set_int_label( idx++, (int32_t)stream_labels->get_label() ); stream_labels->release_example(); } stream_labels->end_parser(); // Create liblinear svm classifier with L2-regularized L2-loss CLibLinear* svm = new CLibLinear(L2R_L2LOSS_SVC); SG_REF(svm); // Add some configuration to the svm svm->set_epsilon(EPSILON); svm->set_bias_enabled(true); // Create a multiclass svm classifier that consists of several of the previous one CLinearMulticlassMachine* mc_svm = new CLinearMulticlassMachine( new CMulticlassOneVsOneStrategy(), (CDotFeatures*) features, svm, labels); SG_REF(mc_svm); // Train the multiclass machine using the data passed in the constructor mc_svm->train(); // Classify the training examples and show the results CLabels* output = mc_svm->apply(); SGVector< int32_t > out_labels = output->get_int_labels(); CMath::display_vector(out_labels.vector, out_labels.vlen); // Free resources SG_UNREF(mc_svm); SG_UNREF(svm); SG_UNREF(output); SG_UNREF(features); SG_UNREF(labels); SG_UNREF(ffeats_train); SG_UNREF(flabels_train); SG_UNREF(stream_features); SG_UNREF(stream_labels); exit_shogun(); return 0; } <|endoftext|>
<commit_before>/**\file * \ingroup example-programmes * \brief FaaS: Fortune as a Service * * Call it like this: * \code * $ ./fortuned http:localhost:8080 * \endcode * * With localhost and 8080 being a host name and port of your choosing. Then, * while the programme is running. * * \copyright * Copyright (c) 2015, ef.gy Project Members * \copyright * 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: * \copyright * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * \copyright * 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. * * \see Project Documentation: https://ef.gy/documentation/libefgy * \see Project Source Code: https://github.com/ef-gy/libefgy */ #define ASIO_DISABLE_THREADS #include <ef.gy/httpd.h> #include <cstdlib> #include <dirent.h> #include <iostream> #include <fstream> using namespace efgy; using namespace std; map<string, string> fortuneData; std::string replace(std::string subject, const std::string &search, const std::string &replace) { size_t pos = 0; while ((pos = subject.find(search, pos)) != std::string::npos) { subject.replace(pos, search.length(), replace); pos += replace.length(); } return subject; } class cookie { public: enum encoding { ePlain, eROT13 } encoding; string file; size_t offset; size_t length; cookie(enum encoding pE, const string &pFile, size_t pOffset, size_t pLength) : encoding(pE), file(pFile), offset(pOffset), length(pLength) {} operator string(void) const { string r(fortuneData[file].data() + offset, length); if (encoding == eROT13) { for (size_t i = 0; i < r.size(); i++) { char c = r[i]; switch (c) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': r[i] = c + 13; break; case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': r[i] = c - 13; break; default: break; } } } return r; } }; vector<cookie> cookies; static bool prepareFortunes(const string &pInoffensive = "/usr/share/games/fortunes/", const string &pOffensive = "/usr/share/games/fortunes/off/") { static const regex dataFile(".*/[a-zA-Z-]+"); smatch matches; for (unsigned int q = 0; q < 2; q++) { string dir = (q == 0) ? pInoffensive : pOffensive; bool doROT13 = (q == 1); DIR *d = opendir(dir.c_str()); if (!d) { continue; } struct dirent *en; while ((en = readdir(d)) != 0) { string e = dir + en->d_name; if (regex_match(e, matches, dataFile)) { std::ifstream t(e); std::stringstream buffer; buffer << t.rdbuf(); fortuneData[e] = buffer.str(); const string &p = fortuneData[e]; const char *data = p.c_str(); size_t start = 0; enum { stN, stNL, stNLP } state = stN; for (size_t c = 0; c < p.size(); c++) { switch (data[c]) { case '\n': switch (state) { case stN: state = stNL; break; case stNLP: cookies.push_back( cookie((doROT13 ? cookie::eROT13 : cookie::ePlain), e, start, c - start - 1)); start = c + 1; default: state = stN; break; } break; case '%': switch (state) { case stNL: state = stNLP; break; default: state = stN; break; } break; case '\r': break; default: state = stN; break; } } } } closedir(d); } return true; } template <class transport> static bool fortune(typename net::http::server<transport>::session &session, std::smatch &) { const int id = rand() % cookies.size(); const cookie &c = cookies[id]; char nbuf[20]; snprintf(nbuf, 20, "%i", id); string sc = string(c); /* note: this escaping is not exactly efficient, but it's fairly simple and the strings are fairly short, so it shouldn't be much of an issue. */ for (char i = 0; i < 0x20; i++) { if ((i == '\n') || (i == '\t')) { continue; } const char org[2] = {i, 0}; const char rep[3] = {'^', (char)(('A' - 1) + i), 0}; replace(sc, org, rep); } sc = "<![CDATA[" + sc + "]]>"; session.reply(200, "Content-Type: text/xml; charset=utf-8\r\n", string("<?xml version='1.0' encoding='utf-8'?>" "<fortune xmlns='http://ef.gy/2012/fortune' quoteID='") + nbuf + "' sourceFile='" + c.file + "'>" + sc + "</fortune>"); return true; } namespace tcp { using asio::ip::tcp; static httpd::servlet<tcp> fortune("^/fortune$", ::fortune<tcp>); static httpd::servlet<tcp> quit("^/quit$", httpd::quit<tcp>); } namespace unix { using asio::local::stream_protocol; static httpd::servlet<stream_protocol> fortune("^/fortune$", ::fortune<stream_protocol>); static httpd::servlet<stream_protocol> quit("^/quit$", httpd::quit<stream_protocol>); } static cli::option count("count", [](std::smatch &m) -> bool { std::cout << cookies.size() << " cookie(s) loaded\n"; return true; }, "prints the number of fortune cookies in the database."); static cli::option print("print(:([0-9]+))?", [](std::smatch &m) -> bool { if (m[1] != "") { std::stringstream s(m[2]); std::size_t n; s >> n; if (n < cookies.size()) { std::cout << std::string(cookies[n]); } else { return false; } } else { std::cout << std::string( cookies[(rand() % cookies.size())]); } return true; }, "print a fortune to stdout" " - a numerical parameter selects a specific cookie."); int main(int argc, char *argv[]) { prepareFortunes(); srand(time(0)); return io::main(argc, argv); } <commit_msg>this daemon will need more cleaning<commit_after>/**\file * \ingroup example-programmes * \brief FaaS: Fortune as a Service * * Call it like this: * \code * $ ./fortuned http:localhost:8080 * \endcode * * With localhost and 8080 being a host name and port of your choosing. Then, * while the programme is running. * * \copyright * Copyright (c) 2015, ef.gy Project Members * \copyright * 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: * \copyright * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * \copyright * 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. * * \see Project Documentation: https://ef.gy/documentation/libefgy * \see Project Source Code: https://github.com/ef-gy/libefgy */ #define ASIO_DISABLE_THREADS #include <ef.gy/httpd.h> #include <cstdlib> #include <dirent.h> #include <iostream> #include <fstream> using namespace efgy; using namespace std; map<string, string> fortuneData; class cookie { public: enum encoding { ePlain, eROT13 } encoding; string file; size_t offset; size_t length; cookie(enum encoding pE, const string &pFile, size_t pOffset, size_t pLength) : encoding(pE), file(pFile), offset(pOffset), length(pLength) {} operator string(void) const { string r(fortuneData[file].data() + offset, length); if (encoding == eROT13) { for (size_t i = 0; i < r.size(); i++) { char c = r[i]; switch (c) { case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': r[i] = c + 13; break; case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': r[i] = c - 13; break; default: break; } } } return r; } }; vector<cookie> cookies; static bool prepareFortunes(const string &dir, const bool doROT13 = false) { static const regex dataFile(".*/[a-zA-Z-]+"); smatch matches; DIR *d = opendir(dir.c_str()); if (!d) { return false; } struct dirent *en; while ((en = readdir(d)) != 0) { string e = dir + en->d_name; if (regex_match(e, matches, dataFile)) { std::ifstream t(e); std::stringstream buffer; buffer << t.rdbuf(); fortuneData[e] = buffer.str(); const string &p = fortuneData[e]; const char *data = p.c_str(); size_t start = 0; enum { stN, stNL, stNLP } state = stN; for (size_t c = 0; c < p.size(); c++) { switch (data[c]) { case '\n': switch (state) { case stN: state = stNL; break; case stNLP: cookies.push_back( cookie((doROT13 ? cookie::eROT13 : cookie::ePlain), e, start, c - start - 1)); start = c + 1; default: state = stN; break; } break; case '%': switch (state) { case stNL: state = stNLP; break; default: state = stN; break; } break; case '\r': break; default: state = stN; break; } } } } closedir(d); return true; } template <class transport> static bool fortune(typename net::http::server<transport>::session &session, std::smatch &) { const int id = rand() % cookies.size(); const cookie &c = cookies[id]; char nbuf[20]; snprintf(nbuf, 20, "%i", id); string sc = string(c); /* note: this escaping is not exactly efficient, but it's fairly simple and the strings are fairly short, so it shouldn't be much of an issue. */ for (char i = 0; i < 0x20; i++) { if ((i == '\n') || (i == '\t')) { continue; } const char org[2] = {i, 0}; const char rep[3] = {'^', (char)(('A' - 1) + i), 0}; for (size_t pos = sc.find(org, pos); pos != std::string::npos; pos = sc.find(org, pos)) { sc.replace(pos, 2, rep); pos += 3; } } sc = "<![CDATA[" + sc + "]]>"; session.reply(200, "Content-Type: text/xml; charset=utf-8\r\n", string("<?xml version='1.0' encoding='utf-8'?>" "<fortune xmlns='http://ef.gy/2012/fortune' quoteID='") + nbuf + "' sourceFile='" + c.file + "'>" + sc + "</fortune>"); return true; } namespace tcp { using asio::ip::tcp; static httpd::servlet<tcp> fortune("^/fortune$", ::fortune<tcp>); static httpd::servlet<tcp> quit("^/quit$", httpd::quit<tcp>); } namespace unix { using asio::local::stream_protocol; static httpd::servlet<stream_protocol> fortune("^/fortune$", ::fortune<stream_protocol>); static httpd::servlet<stream_protocol> quit("^/quit$", httpd::quit<stream_protocol>); } static cli::option count("count", [](std::smatch &m) -> bool { std::cout << cookies.size() << " cookie(s) loaded\n"; return true; }, "prints the number of fortune cookies in the database."); static cli::option print("print(:([0-9]+))?", [](std::smatch &m) -> bool { if (m[1] != "") { std::stringstream s(m[2]); std::size_t n; s >> n; if (n < cookies.size()) { std::cout << std::string(cookies[n]); } else { return false; } } else { std::cout << std::string( cookies[(rand() % cookies.size())]); } return true; }, "print a fortune to stdout - a numerical parameter " "selects a specific cookie."); int main(int argc, char *argv[]) { prepareFortunes("/usr/share/games/fortunes/"); prepareFortunes("/usr/share/games/fortunes/off/", true); srand(time(0)); return io::main(argc, argv); } <|endoftext|>
<commit_before>#include "command.hh" #include "shared.hh" #include "store-api.hh" #include "sync.hh" #include "thread-pool.hh" #include <atomic> using namespace nix; struct CmdCopy : StorePathsCommand { std::string srcUri, dstUri; CheckSigsFlag checkSigs = CheckSigs; CmdCopy() { mkFlag(0, "from", "store-uri", "URI of the source Nix store", &srcUri); mkFlag(0, "to", "store-uri", "URI of the destination Nix store", &dstUri); mkFlag() .longName("no-check-sigs") .description("do not require that paths are signed by trusted keys") .set(&checkSigs, NoCheckSigs); } std::string name() override { return "copy"; } std::string description() override { return "copy paths between Nix stores"; } Examples examples() override { return { Example{ "To copy Firefox from the local store to a binary cache in file:///tmp/cache:", "nix copy --to file:///tmp/cache -r $(type -p firefox)" }, Example{ "To copy the entire current NixOS system closure to another machine via SSH:", "nix copy --to ssh://server -r /run/current-system" }, Example{ "To copy a closure from another machine via SSH:", "nix copy --from ssh://server -r /nix/store/a6cnl93nk1wxnq84brbbwr6hxw9gp2w9-blender-2.79-rc2" }, }; } ref<Store> createStore() override { return srcUri.empty() ? StoreCommand::createStore() : openStore(srcUri); } void run(ref<Store> srcStore, Paths storePaths) override { if (srcUri.empty() && dstUri.empty()) throw UsageError("you must pass '--from' and/or '--to'"); ref<Store> dstStore = dstUri.empty() ? openStore() : openStore(dstUri); copyPaths(srcStore, dstStore, PathSet(storePaths.begin(), storePaths.end()), NoRepair, checkSigs); } }; static RegisterCommand r1(make_ref<CmdCopy>()); <commit_msg>nix copy: Add --substitute flag<commit_after>#include "command.hh" #include "shared.hh" #include "store-api.hh" #include "sync.hh" #include "thread-pool.hh" #include <atomic> using namespace nix; struct CmdCopy : StorePathsCommand { std::string srcUri, dstUri; CheckSigsFlag checkSigs = CheckSigs; SubstituteFlag substitute = NoSubstitute; CmdCopy() { mkFlag(0, "from", "store-uri", "URI of the source Nix store", &srcUri); mkFlag(0, "to", "store-uri", "URI of the destination Nix store", &dstUri); mkFlag() .longName("no-check-sigs") .description("do not require that paths are signed by trusted keys") .set(&checkSigs, NoCheckSigs); mkFlag() .longName("substitute") .shortName('s') .description("whether to try substitutes on the destination store (only supported by SSH)") .set(&substitute, Substitute); } std::string name() override { return "copy"; } std::string description() override { return "copy paths between Nix stores"; } Examples examples() override { return { Example{ "To copy Firefox from the local store to a binary cache in file:///tmp/cache:", "nix copy --to file:///tmp/cache -r $(type -p firefox)" }, Example{ "To copy the entire current NixOS system closure to another machine via SSH:", "nix copy --to ssh://server -r /run/current-system" }, Example{ "To copy a closure from another machine via SSH:", "nix copy --from ssh://server -r /nix/store/a6cnl93nk1wxnq84brbbwr6hxw9gp2w9-blender-2.79-rc2" }, }; } ref<Store> createStore() override { return srcUri.empty() ? StoreCommand::createStore() : openStore(srcUri); } void run(ref<Store> srcStore, Paths storePaths) override { if (srcUri.empty() && dstUri.empty()) throw UsageError("you must pass '--from' and/or '--to'"); ref<Store> dstStore = dstUri.empty() ? openStore() : openStore(dstUri); copyPaths(srcStore, dstStore, PathSet(storePaths.begin(), storePaths.end()), NoRepair, checkSigs, substitute); } }; static RegisterCommand r1(make_ref<CmdCopy>()); <|endoftext|>
<commit_before>#include "notebook.h" #include "logging.h" #include "sourcefile.h" #include "singletons.h" #include <fstream> #include <regex> #include "cmake.h" #if GTK_VERSION_GE(3, 18) #include "gtksourceview-3.0/gtksourceview/gtksourcemap.h" #endif #include <iostream> //TODO: remove using namespace std; //TODO: remove namespace sigc { #ifndef SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE template <typename Functor> struct functor_trait<Functor, false> { typedef decltype (::sigc::mem_fun(std::declval<Functor&>(), &Functor::operator())) _intermediate; typedef typename _intermediate::result_type result_type; typedef Functor functor_type; }; #else SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE #endif } Notebook::Notebook(Directories &directories) : Gtk::Notebook(), directories(directories) { Gsv::init(); } int Notebook::size() { return get_n_pages(); } Source::View* Notebook::get_view(int page) { return source_views.at(get_index(page)); } size_t Notebook::get_index(int page) { for(size_t c=0;c<hboxes.size();c++) { if(page_num(*hboxes.at(c))==page) return c; } return -1; } Source::View* Notebook::get_current_view() { return get_view(get_current_page()); } void Notebook::open(const boost::filesystem::path &file_path) { DEBUG("start"); for(int c=0;c<size();c++) { if(file_path==get_view(c)->file_path) { set_current_page(c); get_current_view()->grab_focus(); return; } } std::ifstream can_read(file_path.string()); if(!can_read) { Singleton::terminal()->print("Error: could not open "+file_path.string()+"\n"); return; } can_read.close(); auto language=Source::guess_language(file_path); if(language && (language->get_id()=="chdr" || language->get_id()=="cpphdr" || language->get_id()=="c" || language->get_id()=="cpp" || language->get_id()=="objc")) { boost::filesystem::path project_path; if(directories.cmake && directories.cmake->project_path!="" && file_path.generic_string().substr(0, directories.cmake->project_path.generic_string().size()+1)==directories.cmake->project_path.generic_string()+'/') { project_path=directories.cmake->project_path; if(boost::filesystem::exists(project_path.string()+"/CMakeLists.txt") && !boost::filesystem::exists(project_path.string()+"/compile_commands.json")) CMake::create_compile_commands(project_path); } else { project_path=file_path.parent_path(); CMake cmake(project_path); if(cmake.project_path!="") { project_path=cmake.project_path; Singleton::terminal()->print("Project path for "+file_path.string()+" set to "+project_path.string()+"\n"); } else Singleton::terminal()->print("Error: could not find project path for "+file_path.string()+"\n"); } source_views.emplace_back(new Source::ClangView(file_path, project_path, language)); } else source_views.emplace_back(new Source::GenericView(file_path, language)); source_views.back()->on_update_status=[this](Source::View* view, const std::string &status) { if(get_current_page()!=-1 && get_current_view()==view) Singleton::status()->set_text(status+" "); }; source_views.back()->on_update_info=[this](Source::View* view, const std::string &info) { if(get_current_page()!=-1 && get_current_view()==view) Singleton::info()->set_text(" "+info); }; scrolled_windows.emplace_back(new Gtk::ScrolledWindow()); hboxes.emplace_back(new Gtk::HBox()); scrolled_windows.back()->add(*source_views.back()); hboxes.back()->pack_start(*scrolled_windows.back()); #if GTK_VERSION_GE(3, 18) source_maps.emplace_back(Glib::wrap(gtk_source_map_new())); hboxes.back()->pack_end(*source_maps.back(), Gtk::PACK_SHRINK); gtk_source_map_set_view(GTK_SOURCE_MAP(source_maps.back()->gobj()), source_views.back()->gobj()); #endif configure(source_views.size()-1); std::string title=file_path.filename().string(); append_page(*hboxes.back(), title); set_tab_reorderable(*hboxes.back(), true); show_all_children(); set_current_page(size()-1); set_focus_child(*source_views.back()); get_current_view()->get_buffer()->set_modified(false); get_current_view()->grab_focus(); //Add star on tab label when the page is not saved: auto source_view=get_current_view(); get_current_view()->get_buffer()->signal_modified_changed().connect([this, source_view]() { std::string title=source_view->file_path.filename().string(); if(source_view->get_buffer()->get_modified()) title+="*"; int page=-1; for(int c=0;c<size();c++) { if(get_view(c)==source_view) { page=c; break; } } if(page!=-1) set_tab_label_text(*(get_nth_page(page)), title); }); DEBUG("end"); } void Notebook::configure(int view_nr) { #if GTK_VERSION_GE(3, 18) auto source_font_description=Pango::FontDescription(Singleton::Config::source()->font); auto source_map_font_desc=Pango::FontDescription(static_cast<std::string>(source_font_description.get_family())+" "+Singleton::Config::source()->map_font_size); source_maps.at(view_nr)->override_font(source_map_font_desc); if(Singleton::Config::source()->show_map) source_maps.at(view_nr)->show(); else source_maps.at(view_nr)->hide(); #endif } bool Notebook::save(int page, bool reparse_needed) { DEBUG("start"); if(page>=size()) { DEBUG("end false"); return false; } auto view=get_view(page); if (view->file_path != "" && view->get_buffer()->get_modified()) { if(juci::filesystem::write(view->file_path, view->get_buffer())) { if(reparse_needed) { if(auto clang_view=dynamic_cast<Source::ClangView*>(view)) { for(auto a_view: source_views) { if(auto a_clang_view=dynamic_cast<Source::ClangView*>(a_view)) { if(clang_view!=a_clang_view) a_clang_view->reparse_needed=true; } } } } view->get_buffer()->set_modified(false); Singleton::terminal()->print("File saved to: " +view->file_path.string()+"\n"); //If CMakeLists.txt have been modified: //TODO: recreate cmake even without directories open? if(view->file_path.filename()=="CMakeLists.txt") { if(directories.cmake && directories.cmake->project_path!="" && view->file_path.generic_string().substr(0, directories.cmake->project_path.generic_string().size()+1)==directories.cmake->project_path.generic_string()+'/' && CMake::create_compile_commands(directories.cmake->project_path)) { for(auto source_view: source_views) { if(auto source_clang_view=dynamic_cast<Source::ClangView*>(source_view)) { if(directories.cmake->project_path.string()==source_clang_view->project_path) { if(source_clang_view->restart_parse()) Singleton::terminal()->async_print("Reparsing "+source_clang_view->file_path.string()+"\n"); else Singleton::terminal()->async_print("Error: failed to reparse "+source_clang_view->file_path.string()+". Please reopen the file manually.\n"); } } } } } DEBUG("end true"); return true; } Singleton::terminal()->print("Error: could not save file " +view->file_path.string()+"\n"); } DEBUG("end false"); return false; } bool Notebook::save_current() { if(get_current_page()==-1) return false; return save(get_current_page(), true); } bool Notebook::close_current_page() { DEBUG("start"); if (get_current_page()!=-1) { if(get_current_view()->get_buffer()->get_modified()){ if(!save_modified_dialog()) { DEBUG("end false"); return false; } } int page = get_current_page(); int index=get_index(page); remove_page(page); #if GTK_VERSION_GE(3, 18) source_maps.erase(source_maps.begin()+index); #endif auto source_view=source_views.at(index); if(auto source_clang_view=dynamic_cast<Source::ClangView*>(source_view)) source_clang_view->async_delete(); else delete source_view; source_views.erase(source_views.begin()+index); scrolled_windows.erase(scrolled_windows.begin()+index); hboxes.erase(hboxes.begin()+index); } DEBUG("end true"); return true; } bool Notebook::save_modified_dialog() { Gtk::MessageDialog dialog((Gtk::Window&)(*get_toplevel()), "Save file!", false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_YES_NO); dialog.set_default_response(Gtk::RESPONSE_YES); dialog.set_secondary_text("Do you want to save: " + get_current_view()->file_path.string()+" ?"); int result = dialog.run(); if(result==Gtk::RESPONSE_YES) { save_current(); return true; } else if(result==Gtk::RESPONSE_NO) { return true; } else { return false; } } <commit_msg>Source map show/hide configuration is now working.<commit_after>#include "notebook.h" #include "logging.h" #include "sourcefile.h" #include "singletons.h" #include <fstream> #include <regex> #include "cmake.h" #if GTK_VERSION_GE(3, 18) #include "gtksourceview-3.0/gtksourceview/gtksourcemap.h" #endif #include <iostream> //TODO: remove using namespace std; //TODO: remove namespace sigc { #ifndef SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE template <typename Functor> struct functor_trait<Functor, false> { typedef decltype (::sigc::mem_fun(std::declval<Functor&>(), &Functor::operator())) _intermediate; typedef typename _intermediate::result_type result_type; typedef Functor functor_type; }; #else SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE #endif } Notebook::Notebook(Directories &directories) : Gtk::Notebook(), directories(directories) { Gsv::init(); } int Notebook::size() { return get_n_pages(); } Source::View* Notebook::get_view(int page) { return source_views.at(get_index(page)); } size_t Notebook::get_index(int page) { for(size_t c=0;c<hboxes.size();c++) { if(page_num(*hboxes.at(c))==page) return c; } return -1; } Source::View* Notebook::get_current_view() { return get_view(get_current_page()); } void Notebook::open(const boost::filesystem::path &file_path) { DEBUG("start"); for(int c=0;c<size();c++) { if(file_path==get_view(c)->file_path) { set_current_page(c); get_current_view()->grab_focus(); return; } } std::ifstream can_read(file_path.string()); if(!can_read) { Singleton::terminal()->print("Error: could not open "+file_path.string()+"\n"); return; } can_read.close(); auto language=Source::guess_language(file_path); if(language && (language->get_id()=="chdr" || language->get_id()=="cpphdr" || language->get_id()=="c" || language->get_id()=="cpp" || language->get_id()=="objc")) { boost::filesystem::path project_path; if(directories.cmake && directories.cmake->project_path!="" && file_path.generic_string().substr(0, directories.cmake->project_path.generic_string().size()+1)==directories.cmake->project_path.generic_string()+'/') { project_path=directories.cmake->project_path; if(boost::filesystem::exists(project_path.string()+"/CMakeLists.txt") && !boost::filesystem::exists(project_path.string()+"/compile_commands.json")) CMake::create_compile_commands(project_path); } else { project_path=file_path.parent_path(); CMake cmake(project_path); if(cmake.project_path!="") { project_path=cmake.project_path; Singleton::terminal()->print("Project path for "+file_path.string()+" set to "+project_path.string()+"\n"); } else Singleton::terminal()->print("Error: could not find project path for "+file_path.string()+"\n"); } source_views.emplace_back(new Source::ClangView(file_path, project_path, language)); } else source_views.emplace_back(new Source::GenericView(file_path, language)); source_views.back()->on_update_status=[this](Source::View* view, const std::string &status) { if(get_current_page()!=-1 && get_current_view()==view) Singleton::status()->set_text(status+" "); }; source_views.back()->on_update_info=[this](Source::View* view, const std::string &info) { if(get_current_page()!=-1 && get_current_view()==view) Singleton::info()->set_text(" "+info); }; scrolled_windows.emplace_back(new Gtk::ScrolledWindow()); hboxes.emplace_back(new Gtk::HBox()); scrolled_windows.back()->add(*source_views.back()); hboxes.back()->pack_start(*scrolled_windows.back()); #if GTK_VERSION_GE(3, 18) source_maps.emplace_back(Glib::wrap(gtk_source_map_new())); gtk_source_map_set_view(GTK_SOURCE_MAP(source_maps.back()->gobj()), source_views.back()->gobj()); #endif configure(source_views.size()-1); std::string title=file_path.filename().string(); append_page(*hboxes.back(), title); set_tab_reorderable(*hboxes.back(), true); show_all_children(); set_current_page(size()-1); set_focus_child(*source_views.back()); get_current_view()->get_buffer()->set_modified(false); get_current_view()->grab_focus(); //Add star on tab label when the page is not saved: auto source_view=get_current_view(); get_current_view()->get_buffer()->signal_modified_changed().connect([this, source_view]() { std::string title=source_view->file_path.filename().string(); if(source_view->get_buffer()->get_modified()) title+="*"; int page=-1; for(int c=0;c<size();c++) { if(get_view(c)==source_view) { page=c; break; } } if(page!=-1) set_tab_label_text(*(get_nth_page(page)), title); }); DEBUG("end"); } void Notebook::configure(int view_nr) { #if GTK_VERSION_GE(3, 18) auto source_font_description=Pango::FontDescription(Singleton::Config::source()->font); auto source_map_font_desc=Pango::FontDescription(static_cast<std::string>(source_font_description.get_family())+" "+Singleton::Config::source()->map_font_size); source_maps.at(view_nr)->override_font(source_map_font_desc); if(Singleton::Config::source()->show_map) { if(hboxes.at(view_nr)->get_children().size()==1) hboxes.at(view_nr)->pack_end(*source_maps.at(view_nr), Gtk::PACK_SHRINK); } else if(hboxes.at(view_nr)->get_children().size()==2) hboxes.at(view_nr)->remove(*source_maps.at(view_nr)); #endif } bool Notebook::save(int page, bool reparse_needed) { DEBUG("start"); if(page>=size()) { DEBUG("end false"); return false; } auto view=get_view(page); if (view->file_path != "" && view->get_buffer()->get_modified()) { if(juci::filesystem::write(view->file_path, view->get_buffer())) { if(reparse_needed) { if(auto clang_view=dynamic_cast<Source::ClangView*>(view)) { for(auto a_view: source_views) { if(auto a_clang_view=dynamic_cast<Source::ClangView*>(a_view)) { if(clang_view!=a_clang_view) a_clang_view->reparse_needed=true; } } } } view->get_buffer()->set_modified(false); Singleton::terminal()->print("File saved to: " +view->file_path.string()+"\n"); //If CMakeLists.txt have been modified: //TODO: recreate cmake even without directories open? if(view->file_path.filename()=="CMakeLists.txt") { if(directories.cmake && directories.cmake->project_path!="" && view->file_path.generic_string().substr(0, directories.cmake->project_path.generic_string().size()+1)==directories.cmake->project_path.generic_string()+'/' && CMake::create_compile_commands(directories.cmake->project_path)) { for(auto source_view: source_views) { if(auto source_clang_view=dynamic_cast<Source::ClangView*>(source_view)) { if(directories.cmake->project_path.string()==source_clang_view->project_path) { if(source_clang_view->restart_parse()) Singleton::terminal()->async_print("Reparsing "+source_clang_view->file_path.string()+"\n"); else Singleton::terminal()->async_print("Error: failed to reparse "+source_clang_view->file_path.string()+". Please reopen the file manually.\n"); } } } } } DEBUG("end true"); return true; } Singleton::terminal()->print("Error: could not save file " +view->file_path.string()+"\n"); } DEBUG("end false"); return false; } bool Notebook::save_current() { if(get_current_page()==-1) return false; return save(get_current_page(), true); } bool Notebook::close_current_page() { DEBUG("start"); if (get_current_page()!=-1) { if(get_current_view()->get_buffer()->get_modified()){ if(!save_modified_dialog()) { DEBUG("end false"); return false; } } int page = get_current_page(); int index=get_index(page); remove_page(page); #if GTK_VERSION_GE(3, 18) source_maps.erase(source_maps.begin()+index); #endif auto source_view=source_views.at(index); if(auto source_clang_view=dynamic_cast<Source::ClangView*>(source_view)) source_clang_view->async_delete(); else delete source_view; source_views.erase(source_views.begin()+index); scrolled_windows.erase(scrolled_windows.begin()+index); hboxes.erase(hboxes.begin()+index); } DEBUG("end true"); return true; } bool Notebook::save_modified_dialog() { Gtk::MessageDialog dialog((Gtk::Window&)(*get_toplevel()), "Save file!", false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_YES_NO); dialog.set_default_response(Gtk::RESPONSE_YES); dialog.set_secondary_text("Do you want to save: " + get_current_view()->file_path.string()+" ?"); int result = dialog.run(); if(result==Gtk::RESPONSE_YES) { save_current(); return true; } else if(result==Gtk::RESPONSE_NO) { return true; } else { return false; } } <|endoftext|>
<commit_before>// Copyright (c) 2012 Intel Corp // Copyright (c) 2012 The Chromium Authors // // 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 co // pies 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 al // l copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM // PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES // S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS // OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH // ETHER 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 "content/nw/src/nw_shell.h" #include "base/command_line.h" #include "base/message_loop.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "content/public/browser/devtools_http_handler.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/nw/src/api/api_messages.h" #include "content/nw/src/api/app/app.h" #include "content/nw/src/browser/file_select_helper.h" #include "content/nw/src/browser/native_window.h" #include "content/nw/src/browser/shell_devtools_delegate.h" #include "content/nw/src/browser/shell_javascript_dialog_creator.h" #include "content/nw/src/common/shell_switches.h" #include "content/nw/src/media/media_stream_devices_controller.h" #include "content/nw/src/nw_package.h" #include "content/nw/src/shell_browser_main_parts.h" #include "content/nw/src/shell_content_browser_client.h" namespace content { std::vector<Shell*> Shell::windows_; bool Shell::quit_message_loop_ = true; Shell* Shell::Create(BrowserContext* browser_context, const GURL& url, SiteInstance* site_instance, int routing_id, WebContents* base_web_contents) { WebContents* web_contents = WebContents::Create( browser_context, site_instance, routing_id, base_web_contents); Shell* shell = new Shell(web_contents, GetPackage()->window()); web_contents->GetController().LoadURL( url, Referrer(), PAGE_TRANSITION_TYPED, std::string()); return shell; } Shell* Shell::FromRenderViewHost(RenderViewHost* rvh) { for (size_t i = 0; i < windows_.size(); ++i) { if (windows_[i]->web_contents() && windows_[i]->web_contents()->GetRenderViewHost() == rvh) { return windows_[i]; } } return NULL; } Shell::Shell(WebContents* web_contents, base::DictionaryValue* manifest) : ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)), is_devtools_(false), force_close_(false), id_(-1) { // Register shell. registrar_.Add(this, NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED, Source<WebContents>(web_contents)); windows_.push_back(this); // Add web contents. web_contents_.reset(web_contents); content::WebContentsObserver::Observe(web_contents); web_contents_->SetDelegate(this); // Create window. window_.reset(nw::NativeWindow::Create(this, manifest)); } Shell::~Shell() { SendEvent("closed"); for (size_t i = 0; i < windows_.size(); ++i) { if (windows_[i] == this) { windows_.erase(windows_.begin() + i); // Close the devtools window if it has one. if (devtools_window_) devtools_window_->CloseContents(web_contents()); break; } } if (windows_.empty() && quit_message_loop_) api::App::Quit(); } void Shell::SendEvent(const std::string& event) { if (id() < 0) return; base::ListValue args; web_contents()->GetRenderViewHost()->Send(new ShellViewMsg_Object_On_Event( web_contents()->GetRoutingID(), id(), event, args)); } bool Shell::ShouldCloseWindow() { if (id() < 0 || force_close_) return true; SendEvent("close"); return false; } nw::Package* Shell::GetPackage() { ShellContentBrowserClient* browser_client = static_cast<ShellContentBrowserClient*>(GetContentClient()->browser()); return browser_client->shell_browser_main_parts()->package(); } void Shell::LoadURL(const GURL& url) { web_contents_->GetController().LoadURL( url, Referrer(), PAGE_TRANSITION_TYPED, std::string()); web_contents_->Focus(); window()->SetToolbarButtonEnabled(nw::NativeWindow::BUTTON_FORWARD, false); } void Shell::GoBackOrForward(int offset) { web_contents_->GetController().GoToOffset(offset); web_contents_->Focus(); } void Shell::Reload() { web_contents_->GetController().Reload(false); web_contents_->Focus(); } void Shell::Stop() { web_contents_->Stop(); web_contents_->Focus(); } void Shell::ReloadOrStop() { if (web_contents_->IsLoading()) Stop(); else Reload(); } void Shell::ShowDevTools() { ShellContentBrowserClient* browser_client = static_cast<ShellContentBrowserClient*>( GetContentClient()->browser()); // Reuse reopened one if we have. if (devtools_window_) { devtools_window_->window_->Focus(true); return; } ShellDevToolsDelegate* delegate = browser_client->shell_browser_main_parts()->devtools_delegate(); GURL url = delegate->devtools_http_handler()->GetFrontendURL( web_contents()->GetRenderViewHost()); // Use our minimum set manifest base::DictionaryValue manifest; manifest.SetBoolean(switches::kmToolbar, false); manifest.SetBoolean(switches::kmFullscreen, false); manifest.SetInteger(switches::kmWidth, 600); manifest.SetInteger(switches::kmHeight, 500); Shell* shell = new Shell( WebContents::Create(web_contents()->GetBrowserContext(), NULL, MSG_ROUTING_NONE, NULL), &manifest); shell->is_devtools_ = true; shell->force_close_ = true; shell->LoadURL(url); // Save devtools window in current shell. devtools_window_ = shell->weak_ptr_factory_.GetWeakPtr(); } void Shell::UpdateDraggableRegions( const std::vector<extensions::DraggableRegion>& regions) { window()->UpdateDraggableRegions(regions); } bool Shell::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(Shell, message) IPC_MESSAGE_HANDLER(ShellViewHostMsg_UpdateDraggableRegions, UpdateDraggableRegions) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } WebContents* Shell::OpenURLFromTab(WebContents* source, const OpenURLParams& params) { // The only one we implement for now. DCHECK(params.disposition == CURRENT_TAB); source->GetController().LoadURL( params.url, params.referrer, params.transition, std::string()); return source; } void Shell::LoadingStateChanged(WebContents* source) { int current_index = web_contents_->GetController().GetCurrentEntryIndex(); int max_index = web_contents_->GetController().GetEntryCount() - 1; window()->SetToolbarButtonEnabled(nw::NativeWindow::BUTTON_BACK, current_index > 0); window()->SetToolbarButtonEnabled(nw::NativeWindow::BUTTON_FORWARD, current_index < max_index); window()->SetToolbarIsLoading(source->IsLoading()); } void Shell::ActivateContents(content::WebContents* contents) { window()->Focus(true); } void Shell::DeactivateContents(content::WebContents* contents) { if (windows_.size() == 1) { window()->Focus(false); return; } // Move focus to other window for (unsigned i = 0; i < windows_.size(); ++i) if (windows_[i] != this) { windows_[i]->window()->Focus(true); break; } } void Shell::CloseContents(WebContents* source) { window()->Close(); } void Shell::MoveContents(WebContents* source, const gfx::Rect& pos) { window()->Move(pos); } bool Shell::IsPopupOrPanel(const WebContents* source) const { // Treat very window as popup so we can use window operations return true; } // Window opened by window.open void Shell::WebContentsCreated(WebContents* source_contents, int64 source_frame_id, const GURL& target_url, WebContents* new_contents) { // Create with package's manifest scoped_ptr<base::DictionaryValue> manifest( GetPackage()->window()->DeepCopy()); // Get window features WebKit::WebWindowFeatures features = new_contents->GetWindowFeatures(); manifest->SetBoolean(switches::kmResizable, features.resizable); manifest->SetBoolean(switches::kmFullscreen, features.fullscreen); if (features.widthSet) manifest->SetInteger(switches::kmWidth, features.width); if (features.heightSet) manifest->SetInteger(switches::kmHeight, features.height); if (features.xSet) manifest->SetInteger(switches::kmX, features.x); if (features.ySet) manifest->SetInteger(switches::kmY, features.y); new Shell(new_contents, manifest.get()); } void Shell::RunFileChooser(WebContents* web_contents, const content::FileChooserParams& params) { FileSelectHelper::RunFileChooser(web_contents, params); } void Shell::EnumerateDirectory(WebContents* web_contents, int request_id, const FilePath& path) { FileSelectHelper::EnumerateDirectory(web_contents, request_id, path); } void Shell::DidNavigateMainFramePostCommit(WebContents* web_contents) { window()->SetToolbarUrlEntry(web_contents->GetURL().spec()); } JavaScriptDialogCreator* Shell::GetJavaScriptDialogCreator() { if (!dialog_creator_.get()) dialog_creator_.reset(new ShellJavaScriptDialogCreator()); return dialog_creator_.get(); } bool Shell::AddMessageToConsole(WebContents* source, int32 level, const string16& message, int32 line_no, const string16& source_id) { return false; } void Shell::HandleKeyboardEvent(WebContents* source, const NativeWebKeyboardEvent& event) { window()->HandleKeyboardEvent(event); } void Shell::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest* request, const content::MediaResponseCallback& callback) { scoped_ptr<MediaStreamDevicesController> controller(new MediaStreamDevicesController(request, callback)); controller->DismissInfoBarAndTakeActionOnSettings(); } void Shell::Observe(int type, const NotificationSource& source, const NotificationDetails& details) { if (type == NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED) { std::pair<NavigationEntry*, bool>* title = Details<std::pair<NavigationEntry*, bool> >(details).ptr(); if (title->first) { string16 text = title->first->GetTitle(); window()->SetTitle(UTF16ToUTF8(text)); } } } } // namespace content <commit_msg>Force closing previous debug session<commit_after>// Copyright (c) 2012 Intel Corp // Copyright (c) 2012 The Chromium Authors // // 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 co // pies 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 al // l copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM // PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES // S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS // OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH // ETHER 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 "content/nw/src/nw_shell.h" #include "base/command_line.h" #include "base/message_loop.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "content/public/browser/devtools_agent_host_registry.h" #include "content/public/browser/devtools_http_handler.h" #include "content/public/browser/devtools_manager.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/nw/src/api/api_messages.h" #include "content/nw/src/api/app/app.h" #include "content/nw/src/browser/file_select_helper.h" #include "content/nw/src/browser/native_window.h" #include "content/nw/src/browser/shell_devtools_delegate.h" #include "content/nw/src/browser/shell_javascript_dialog_creator.h" #include "content/nw/src/common/shell_switches.h" #include "content/nw/src/media/media_stream_devices_controller.h" #include "content/nw/src/nw_package.h" #include "content/nw/src/shell_browser_main_parts.h" #include "content/nw/src/shell_content_browser_client.h" namespace content { std::vector<Shell*> Shell::windows_; bool Shell::quit_message_loop_ = true; Shell* Shell::Create(BrowserContext* browser_context, const GURL& url, SiteInstance* site_instance, int routing_id, WebContents* base_web_contents) { WebContents* web_contents = WebContents::Create( browser_context, site_instance, routing_id, base_web_contents); Shell* shell = new Shell(web_contents, GetPackage()->window()); web_contents->GetController().LoadURL( url, Referrer(), PAGE_TRANSITION_TYPED, std::string()); return shell; } Shell* Shell::FromRenderViewHost(RenderViewHost* rvh) { for (size_t i = 0; i < windows_.size(); ++i) { if (windows_[i]->web_contents() && windows_[i]->web_contents()->GetRenderViewHost() == rvh) { return windows_[i]; } } return NULL; } Shell::Shell(WebContents* web_contents, base::DictionaryValue* manifest) : ALLOW_THIS_IN_INITIALIZER_LIST(weak_ptr_factory_(this)), is_devtools_(false), force_close_(false), id_(-1) { // Register shell. registrar_.Add(this, NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED, Source<WebContents>(web_contents)); windows_.push_back(this); // Add web contents. web_contents_.reset(web_contents); content::WebContentsObserver::Observe(web_contents); web_contents_->SetDelegate(this); // Create window. window_.reset(nw::NativeWindow::Create(this, manifest)); } Shell::~Shell() { SendEvent("closed"); for (size_t i = 0; i < windows_.size(); ++i) { if (windows_[i] == this) { windows_.erase(windows_.begin() + i); // Close the devtools window if it has one. if (devtools_window_) devtools_window_->CloseContents(web_contents()); break; } } if (windows_.empty() && quit_message_loop_) api::App::Quit(); } void Shell::SendEvent(const std::string& event) { if (id() < 0) return; base::ListValue args; web_contents()->GetRenderViewHost()->Send(new ShellViewMsg_Object_On_Event( web_contents()->GetRoutingID(), id(), event, args)); } bool Shell::ShouldCloseWindow() { if (id() < 0 || force_close_) return true; SendEvent("close"); return false; } nw::Package* Shell::GetPackage() { ShellContentBrowserClient* browser_client = static_cast<ShellContentBrowserClient*>(GetContentClient()->browser()); return browser_client->shell_browser_main_parts()->package(); } void Shell::LoadURL(const GURL& url) { web_contents_->GetController().LoadURL( url, Referrer(), PAGE_TRANSITION_TYPED, std::string()); web_contents_->Focus(); window()->SetToolbarButtonEnabled(nw::NativeWindow::BUTTON_FORWARD, false); } void Shell::GoBackOrForward(int offset) { web_contents_->GetController().GoToOffset(offset); web_contents_->Focus(); } void Shell::Reload() { web_contents_->GetController().Reload(false); web_contents_->Focus(); } void Shell::Stop() { web_contents_->Stop(); web_contents_->Focus(); } void Shell::ReloadOrStop() { if (web_contents_->IsLoading()) Stop(); else Reload(); } void Shell::ShowDevTools() { ShellContentBrowserClient* browser_client = static_cast<ShellContentBrowserClient*>( GetContentClient()->browser()); // Reuse reopened one if we have. if (devtools_window_) { devtools_window_->window_->Focus(true); return; } RenderViewHost* inspected_rvh = web_contents()->GetRenderViewHost(); DevToolsAgentHost* agent = DevToolsAgentHostRegistry::GetDevToolsAgentHost( inspected_rvh); DevToolsManager* manager = DevToolsManager::GetInstance(); DevToolsClientHost* host = manager->GetDevToolsClientHostFor(agent); if (host) { // Break remote debugging debugging session. manager->UnregisterDevToolsClientHostFor(agent); } ShellDevToolsDelegate* delegate = browser_client->shell_browser_main_parts()->devtools_delegate(); GURL url = delegate->devtools_http_handler()->GetFrontendURL(inspected_rvh); // Use our minimum set manifest base::DictionaryValue manifest; manifest.SetBoolean(switches::kmToolbar, false); manifest.SetBoolean(switches::kmFullscreen, false); manifest.SetInteger(switches::kmWidth, 600); manifest.SetInteger(switches::kmHeight, 500); Shell* shell = new Shell( WebContents::Create(web_contents()->GetBrowserContext(), NULL, MSG_ROUTING_NONE, NULL), &manifest); shell->is_devtools_ = true; shell->force_close_ = true; shell->LoadURL(url); // Save devtools window in current shell. devtools_window_ = shell->weak_ptr_factory_.GetWeakPtr(); } void Shell::UpdateDraggableRegions( const std::vector<extensions::DraggableRegion>& regions) { window()->UpdateDraggableRegions(regions); } bool Shell::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(Shell, message) IPC_MESSAGE_HANDLER(ShellViewHostMsg_UpdateDraggableRegions, UpdateDraggableRegions) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } WebContents* Shell::OpenURLFromTab(WebContents* source, const OpenURLParams& params) { // The only one we implement for now. DCHECK(params.disposition == CURRENT_TAB); source->GetController().LoadURL( params.url, params.referrer, params.transition, std::string()); return source; } void Shell::LoadingStateChanged(WebContents* source) { int current_index = web_contents_->GetController().GetCurrentEntryIndex(); int max_index = web_contents_->GetController().GetEntryCount() - 1; window()->SetToolbarButtonEnabled(nw::NativeWindow::BUTTON_BACK, current_index > 0); window()->SetToolbarButtonEnabled(nw::NativeWindow::BUTTON_FORWARD, current_index < max_index); window()->SetToolbarIsLoading(source->IsLoading()); } void Shell::ActivateContents(content::WebContents* contents) { window()->Focus(true); } void Shell::DeactivateContents(content::WebContents* contents) { if (windows_.size() == 1) { window()->Focus(false); return; } // Move focus to other window for (unsigned i = 0; i < windows_.size(); ++i) if (windows_[i] != this) { windows_[i]->window()->Focus(true); break; } } void Shell::CloseContents(WebContents* source) { window()->Close(); } void Shell::MoveContents(WebContents* source, const gfx::Rect& pos) { window()->Move(pos); } bool Shell::IsPopupOrPanel(const WebContents* source) const { // Treat very window as popup so we can use window operations return true; } // Window opened by window.open void Shell::WebContentsCreated(WebContents* source_contents, int64 source_frame_id, const GURL& target_url, WebContents* new_contents) { // Create with package's manifest scoped_ptr<base::DictionaryValue> manifest( GetPackage()->window()->DeepCopy()); // Get window features WebKit::WebWindowFeatures features = new_contents->GetWindowFeatures(); manifest->SetBoolean(switches::kmResizable, features.resizable); manifest->SetBoolean(switches::kmFullscreen, features.fullscreen); if (features.widthSet) manifest->SetInteger(switches::kmWidth, features.width); if (features.heightSet) manifest->SetInteger(switches::kmHeight, features.height); if (features.xSet) manifest->SetInteger(switches::kmX, features.x); if (features.ySet) manifest->SetInteger(switches::kmY, features.y); new Shell(new_contents, manifest.get()); } void Shell::RunFileChooser(WebContents* web_contents, const content::FileChooserParams& params) { FileSelectHelper::RunFileChooser(web_contents, params); } void Shell::EnumerateDirectory(WebContents* web_contents, int request_id, const FilePath& path) { FileSelectHelper::EnumerateDirectory(web_contents, request_id, path); } void Shell::DidNavigateMainFramePostCommit(WebContents* web_contents) { window()->SetToolbarUrlEntry(web_contents->GetURL().spec()); } JavaScriptDialogCreator* Shell::GetJavaScriptDialogCreator() { if (!dialog_creator_.get()) dialog_creator_.reset(new ShellJavaScriptDialogCreator()); return dialog_creator_.get(); } bool Shell::AddMessageToConsole(WebContents* source, int32 level, const string16& message, int32 line_no, const string16& source_id) { return false; } void Shell::HandleKeyboardEvent(WebContents* source, const NativeWebKeyboardEvent& event) { window()->HandleKeyboardEvent(event); } void Shell::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest* request, const content::MediaResponseCallback& callback) { scoped_ptr<MediaStreamDevicesController> controller(new MediaStreamDevicesController(request, callback)); controller->DismissInfoBarAndTakeActionOnSettings(); } void Shell::Observe(int type, const NotificationSource& source, const NotificationDetails& details) { if (type == NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED) { std::pair<NavigationEntry*, bool>* title = Details<std::pair<NavigationEntry*, bool> >(details).ptr(); if (title->first) { string16 text = title->first->GetTitle(); window()->SetTitle(UTF16ToUTF8(text)); } } } } // namespace content <|endoftext|>
<commit_before>/* * PixBinarizer.cpp * * Created on: Jul 8, 2014 * Author: renard */ #include "PixBinarizer.h" #include <stdio.h> #include <iostream> #include <sstream> #include <cmath> #include "image_processing.h" using namespace std; PixBinarizer::PixBinarizer(bool debug) { mDebug= debug; } int PixBinarizer::determineThresholdForTile(Pix* pixt, bool debug) { l_int32 start = 0, end = 255, i, error, closeSize = 0; l_float32 sum, moment, var, y, variance, mean, meanY, countPixels; NUMA* norm; NUMA* histo = pixGetGrayHistogram(pixt, 1); numaSetValue(histo, 255, 0); //ignore white pixels error = numaGetNonzeroRange(histo, 0, &start, &end); if (end == start || error == 1) { numaDestroy(&histo); return 0; } closeSize = end - start; if (closeSize % 2 == 0) { closeSize++; } norm = numaNormalizeHistogram(histo, 1); /* l_float32 median; numaGetMedian(histo,&median); printf("%2.1f\t", median); */ l_float32 iMulty; for (sum = 0.0, moment = 0.0, var = 0.0, countPixels = 0, i = start; i < end; i++) { numaGetFValue(norm, i, &y); sum += y; iMulty = i * y; moment += iMulty; var += i * iMulty; numaGetFValue(histo, i, &y); countPixels += y; } variance = sqrt(var / sum - moment * moment / (sum * sum)); mean = moment / sum; meanY = sum / (end - start); int result = 0; if (variance < 8) { result = 0; } else { if ((mean * 0.5) < variance) { result = mean;// + variance*0.4; } else { //high variance means we have probably have a very good separation between fore and background //in that case the threshold be closer to the mean result = mean - sqrt(variance) * 3; //result = mean - variance*0.66; } //result = mean - variance*0.66; //0.2 when median is activated, 0.66 otherwise } if (debug == true) { printf("mean = %f , variance = %f, meanY = %f \n", mean, variance, meanY); printf("%i ,%i\n", start, end); GPLOT *gplot; ostringstream name; name << mean; gplot = gplotCreate(name.str().c_str(), GPLOT_X11, name.str().c_str(), "x", "y"); ostringstream title; title << "mean = " << mean << ", " << "variance = " << variance << ", thresh = " << result; //gplotAddPlot(gplot, NULL, diff, GPLOT_LINES, "diff histogram"); gplotAddPlot(gplot, NULL, norm, GPLOT_LINES, title.str().c_str()); gplotMakeOutput(gplot); gplotDestroy(&gplot); } numaDestroy(&norm); numaDestroy(&histo); //TODO check std dev of y values. large value > foreground and background, low value > only background //idea: narrow histogramm means a high likelyhood for bg return result; } Pix* PixBinarizer::createEdgeMask(Pix* pixs) { L_TIMER timer = startTimerNested(); ostringstream s; Pix* pixConv = pixBlockconvGray(pixs, NULL, 5, 5); Pix* pixConvEdges = pixSobelEdgeFilter(pixConv, L_ALL_EDGES); pixDestroy(&pixConv); pixInvert(pixConvEdges, pixConvEdges); s << "sobel edge detection: " << stopTimerNested(timer) << std::endl; timer = startTimerNested(); if(mDebug){ pixWrite("pixConvEdges.bmp", pixConvEdges, IFF_BMP); } NUMA* histo = pixGetGrayHistogram(pixConvEdges, 8); NUMA* norm = numaNormalizeHistogram(histo, 1.0); l_float32 median, mean, variance; numaGetHistogramStats(norm, 0, 1, &mean, &median, NULL, &variance); numaDestroy(&histo); numaDestroy(&norm); l_int32 thresh = 0; if (variance < 1.0) { thresh = 255; } else { thresh = 254; } if(mDebug){ printf("mean = %f, median = %f, std dev = %f, thresh = %i\n", mean, median, variance, thresh); } Pix* pixForeground = pixThresholdToBinary(pixConvEdges, thresh); pixDestroy(&pixConvEdges); pixCloseSafeBrick(pixForeground,pixForeground,64,64); pixWrite("foreground.bmp", pixForeground, IFF_BMP); if(mDebug){ s << "binarization of edge mask: " << stopTimerNested(timer) << std::endl; } timer = startTimerNested(); Pix* pixacc = pixBlockconvAccum(pixForeground); Pix* pixRank = pixBlockrank(pixForeground, pixacc, 8, 8, 0.1); pixDestroy(&pixacc); pixDestroy(&pixForeground); pixInvert(pixRank, pixRank); Pix* pixResult = pixOpenBrick(NULL, pixRank, 10, 10); pixDestroy(&pixRank); if(mDebug){ pixWrite("rank.bmp", pixResult, IFF_BMP); s << "mask generation: " << stopTimerNested(timer) << std::endl; printf("%s", s.str().c_str()); } return pixResult; } /** * determines and applies a threshold for each tile separately */ Pix* PixBinarizer::binarizeTiled(Pix* pixs, const l_uint32 tileSize) { L_TIMER timer = startTimerNested(); l_int32 thresh, w, h; Pix* pixb; ostringstream s; pixGetDimensions(pixs, &w, &h, NULL); l_int32 nx = L_MAX(1, w / tileSize); l_int32 ny = L_MAX(1, h / tileSize); l_int32 ox = L_MAX(1,nx/6); l_int32 oy = L_MAX(1,ny/6); PIXTILING* pt = pixTilingCreate(pixs, nx, ny, 0, 0, ox, oy); Pix* pixth = pixCreate(nx, ny, 8); Pix* pixt; bool debug = false; for (int i = 0; i < ny; i++) { for (int j = 0; j < nx; j++) { pixt = pixTilingGetTile(pt, i, j); if (i == 0 && j == 0) { debug = false; } else { debug = false; } thresh = determineThresholdForTile(pixt, debug); pixSetPixel(pixth, j, i, thresh); pixDestroy(&pixt); } } pixTilingDestroy(&pt); if(mDebug){ s << "local threshhold determination: " << stopTimerNested(timer)<< std::endl; timer = startTimerNested(); } pt = pixTilingCreate(pixs, nx, ny, 0, 0, 0, 0); pixb = pixCreate(w, h, 1); l_uint32 val; for (int i = 0; i < ny; i++) { for (int j = 0; j < nx; j++) { pixt = pixTilingGetTile(pt, i, j); pixGetPixel(pixth, j, i, &val); Pix* pixbTile = pixThresholdToBinary(pixt, val); pixTilingPaintTile(pixb, i, j, pixbTile, pt); pixDestroy(&pixt); pixDestroy(&pixbTile); } } pixTilingDestroy(&pt); pixDestroy(&pixth); if(mDebug){ s << "local threshhold application: " << stopTimerNested(timer)<< std::endl; printf("%s", s.str().c_str()); } return pixb; } void PixBinarizer::binarizeInternal(Pix* pixGrey, Pix* pixhm, Pix** pixb) { Pix* pixEdgeMask; l_int32 width = pixGetWidth(pixGrey); const l_uint32 tileSize = width/10; //size of tile during threshholding L_TIMER timer = startTimerNested(); ostringstream s; pixEdgeMask = createEdgeMask(pixGrey); pixSetMasked(pixGrey, pixEdgeMask, 255); if (pixhm != NULL) { //dont allow image mask to cover text pixAnd(pixhm, pixhm, pixEdgeMask); } pixDestroy(&pixEdgeMask); if(mDebug){ s << "text mask creation: " << stopTimerNested(timer) << std::endl; printf("%s", s.str().c_str()); pixDisplay(pixGrey,0,0); pixWrite("toThresh.bmp", pixGrey, IFF_BMP); } /* timer = startTimerNested(); Pix* pixMedian = pixRankFilterGray(pixGrey,3,3,0.25); printf("rank filter = %f\n",stopTimerNested(timer)); pixWrite("rank.bmp",pixMedian,IFF_BMP); */ *pixb = binarizeTiled(pixGrey, tileSize); //pixDestroy(&pixMedian); if (pixhm != NULL) { pixSetMasked(*pixb, pixhm, 0); } } Pix* PixBinarizer::binarize(Pix* pix){ l_int32 depth = pixGetDepth(pix); Pix* pixGrey; Pix* pixtContrast; Pix* pixBinary; switch(depth){ case 1: return pixClone(pix); case 8: pixGrey = pixClone(pix); break; case 32: pixGrey = pixConvertRGBToLuminance(pix); } //binarizeInternal(pixGrey, NULL, &pixBinary); /* Do combination of contrast norm and sauvola */ pixtContrast = pixContrastNorm(NULL, pixGrey, 100, 100, 55, 1, 1); pixSauvolaBinarizeTiled(pixtContrast, 9, 0.15, 1, 1, NULL, &pixBinary); // pixDestroy(&pixtContrast); pixDestroy(&pixGrey); return pixBinary; } PixBinarizer::~PixBinarizer() { } <commit_msg>fix: use original binarisation algorithm<commit_after>/* * PixBinarizer.cpp * * Created on: Jul 8, 2014 * Author: renard */ #include "PixBinarizer.h" #include <stdio.h> #include <iostream> #include <sstream> #include <cmath> #include "image_processing.h" using namespace std; PixBinarizer::PixBinarizer(bool debug) { mDebug= debug; } int PixBinarizer::determineThresholdForTile(Pix* pixt, bool debug) { l_int32 start = 0, end = 255, i, error, closeSize = 0; l_float32 sum, moment, var, y, variance, mean, meanY, countPixels; NUMA* norm; NUMA* histo = pixGetGrayHistogram(pixt, 1); numaSetValue(histo, 255, 0); //ignore white pixels error = numaGetNonzeroRange(histo, 0, &start, &end); if (end == start || error == 1) { numaDestroy(&histo); return 0; } closeSize = end - start; if (closeSize % 2 == 0) { closeSize++; } norm = numaNormalizeHistogram(histo, 1); /* l_float32 median; numaGetMedian(histo,&median); printf("%2.1f\t", median); */ l_float32 iMulty; for (sum = 0.0, moment = 0.0, var = 0.0, countPixels = 0, i = start; i < end; i++) { numaGetFValue(norm, i, &y); sum += y; iMulty = i * y; moment += iMulty; var += i * iMulty; numaGetFValue(histo, i, &y); countPixels += y; } variance = sqrt(var / sum - moment * moment / (sum * sum)); mean = moment / sum; meanY = sum / (end - start); int result = 0; if (variance < 8) { result = 0; } else { if ((mean * 0.5) < variance) { result = mean;// + variance*0.4; } else { //high variance means we have probably have a very good separation between fore and background //in that case the threshold be closer to the mean result = mean - sqrt(variance) * 3; //result = mean - variance*0.66; } //result = mean - variance*0.66; //0.2 when median is activated, 0.66 otherwise } if (debug == true) { printf("mean = %f , variance = %f, meanY = %f \n", mean, variance, meanY); printf("%i ,%i\n", start, end); GPLOT *gplot; ostringstream name; name << mean; gplot = gplotCreate(name.str().c_str(), GPLOT_X11, name.str().c_str(), "x", "y"); ostringstream title; title << "mean = " << mean << ", " << "variance = " << variance << ", thresh = " << result; //gplotAddPlot(gplot, NULL, diff, GPLOT_LINES, "diff histogram"); gplotAddPlot(gplot, NULL, norm, GPLOT_LINES, title.str().c_str()); gplotMakeOutput(gplot); gplotDestroy(&gplot); } numaDestroy(&norm); numaDestroy(&histo); //TODO check std dev of y values. large value > foreground and background, low value > only background //idea: narrow histogramm means a high likelyhood for bg return result; } Pix* PixBinarizer::createEdgeMask(Pix* pixs) { L_TIMER timer = startTimerNested(); ostringstream s; Pix* pixConv = pixBlockconvGray(pixs, NULL, 5, 5); Pix* pixConvEdges = pixSobelEdgeFilter(pixConv, L_ALL_EDGES); pixDestroy(&pixConv); pixInvert(pixConvEdges, pixConvEdges); s << "sobel edge detection: " << stopTimerNested(timer) << std::endl; timer = startTimerNested(); if(mDebug){ pixWrite("pixConvEdges.bmp", pixConvEdges, IFF_BMP); } NUMA* histo = pixGetGrayHistogram(pixConvEdges, 8); NUMA* norm = numaNormalizeHistogram(histo, 1.0); l_float32 median, mean, variance; numaGetHistogramStats(norm, 0, 1, &mean, &median, NULL, &variance); numaDestroy(&histo); numaDestroy(&norm); l_int32 thresh = 0; if (variance < 1.0) { thresh = 255; } else { thresh = 254; } if(mDebug){ printf("mean = %f, median = %f, std dev = %f, thresh = %i\n", mean, median, variance, thresh); } Pix* pixForeground = pixThresholdToBinary(pixConvEdges, thresh); pixDestroy(&pixConvEdges); pixCloseSafeBrick(pixForeground,pixForeground,64,64); pixWrite("foreground.bmp", pixForeground, IFF_BMP); if(mDebug){ s << "binarization of edge mask: " << stopTimerNested(timer) << std::endl; } timer = startTimerNested(); Pix* pixacc = pixBlockconvAccum(pixForeground); Pix* pixRank = pixBlockrank(pixForeground, pixacc, 8, 8, 0.1); pixDestroy(&pixacc); pixDestroy(&pixForeground); pixInvert(pixRank, pixRank); Pix* pixResult = pixOpenBrick(NULL, pixRank, 10, 10); pixDestroy(&pixRank); if(mDebug){ pixWrite("rank.bmp", pixResult, IFF_BMP); s << "mask generation: " << stopTimerNested(timer) << std::endl; printf("%s", s.str().c_str()); } return pixResult; } /** * determines and applies a threshold for each tile separately */ Pix* PixBinarizer::binarizeTiled(Pix* pixs, const l_uint32 tileSize) { L_TIMER timer = startTimerNested(); l_int32 thresh, w, h; Pix* pixb; ostringstream s; pixGetDimensions(pixs, &w, &h, NULL); l_int32 nx = L_MAX(1, w / tileSize); l_int32 ny = L_MAX(1, h / tileSize); l_int32 ox = L_MAX(1,nx/6); l_int32 oy = L_MAX(1,ny/6); PIXTILING* pt = pixTilingCreate(pixs, nx, ny, 0, 0, ox, oy); Pix* pixth = pixCreate(nx, ny, 8); Pix* pixt; bool debug = false; for (int i = 0; i < ny; i++) { for (int j = 0; j < nx; j++) { pixt = pixTilingGetTile(pt, i, j); if (i == 0 && j == 0) { debug = false; } else { debug = false; } thresh = determineThresholdForTile(pixt, debug); pixSetPixel(pixth, j, i, thresh); pixDestroy(&pixt); } } pixTilingDestroy(&pt); if(mDebug){ s << "local threshhold determination: " << stopTimerNested(timer)<< std::endl; timer = startTimerNested(); } pt = pixTilingCreate(pixs, nx, ny, 0, 0, 0, 0); pixb = pixCreate(w, h, 1); l_uint32 val; for (int i = 0; i < ny; i++) { for (int j = 0; j < nx; j++) { pixt = pixTilingGetTile(pt, i, j); pixGetPixel(pixth, j, i, &val); Pix* pixbTile = pixThresholdToBinary(pixt, val); pixTilingPaintTile(pixb, i, j, pixbTile, pt); pixDestroy(&pixt); pixDestroy(&pixbTile); } } pixTilingDestroy(&pt); pixDestroy(&pixth); if(mDebug){ s << "local threshhold application: " << stopTimerNested(timer)<< std::endl; printf("%s", s.str().c_str()); } return pixb; } void PixBinarizer::binarizeInternal(Pix* pixGrey, Pix* pixhm, Pix** pixb) { Pix* pixEdgeMask; l_int32 width = pixGetWidth(pixGrey); const l_uint32 tileSize = width/10; //size of tile during threshholding L_TIMER timer = startTimerNested(); ostringstream s; pixEdgeMask = createEdgeMask(pixGrey); pixSetMasked(pixGrey, pixEdgeMask, 255); if (pixhm != NULL) { //dont allow image mask to cover text pixAnd(pixhm, pixhm, pixEdgeMask); } pixDestroy(&pixEdgeMask); if(mDebug){ s << "text mask creation: " << stopTimerNested(timer) << std::endl; printf("%s", s.str().c_str()); pixDisplay(pixGrey,0,0); pixWrite("toThresh.bmp", pixGrey, IFF_BMP); } /* timer = startTimerNested(); Pix* pixMedian = pixRankFilterGray(pixGrey,3,3,0.25); printf("rank filter = %f\n",stopTimerNested(timer)); pixWrite("rank.bmp",pixMedian,IFF_BMP); */ *pixb = binarizeTiled(pixGrey, tileSize); //pixDestroy(&pixMedian); if (pixhm != NULL) { pixSetMasked(*pixb, pixhm, 0); } } Pix* PixBinarizer::binarize(Pix* pix){ l_int32 depth = pixGetDepth(pix); Pix* pixGrey = NULL; Pix* pixtContrast; Pix* pixBinary; switch(depth){ case 1: return pixClone(pix); case 8: pixGrey = pixClone(pix); break; case 32: pixGrey = pixConvertRGBToLuminance(pix); } binarizeInternal(pixGrey, NULL, &pixBinary); /* Do combination of contrast norm and sauvola */ // pixtContrast = pixContrastNorm(NULL, pixGrey, 100, 100, 55, 1, 1); // pixSauvolaBinarizeTiled(pixtContrast, 9, 0.15, 1, 1, NULL, &pixBinary); pixDestroy(&pixtContrast); pixDestroy(&pixGrey); return pixBinary; } PixBinarizer::~PixBinarizer() { } <|endoftext|>
<commit_before>// Catch #include <catch.hpp> #include <helper.hpp> // C++ Standard Library #include <cmath> // Mantella #include <mantella> template <typename ParameterType> class MockDistanceFunction : public mant::DistanceFunction<ParameterType>{ public: ParameterType getDistanceImplementation( const arma::Col<ParameterType>& parameter) const noexcept override; arma::Col<ParameterType> getRandomNeighbourImplementation( const arma::Col<ParameterType>& parameter, const ParameterType& minimalDistance, const ParameterType& maximalDistance) const noexcept override; }; template <> double MockDistanceFunction<double>::getDistanceImplementation( const arma::Col<double>& parameter) const noexcept { return arma::norm(parameter, 1); } template <> unsigned int MockDistanceFunction<unsigned int>::getDistanceImplementation( const arma::Col<unsigned int>& parameter) const noexcept { return arma::accu(parameter); } template <ParameterType> arma::Col<ParameterType> MockDistanceFunction<ParameterType>::getRandomNeighbourImplementation( const arma::Col<ParameterType>& parameter, const ParameterType& minimalDistance, const ParameterType& maximalDistance) const noexcept { arma::Col<ParameterType> result = parameter; result.at(0) += std::floor(maximalDistance + minimalDistance / 2.0); return result; } TEST_CASE("DistanceFunction<double>", "") { MockDistanceFunction<double> distanceFunction; SECTION("Testing getRandomNeighbour(..)") { SECTION("Selected random neighbour remains unchanged, considering an unrestricted minimal distance.") { compare(distanceFunction.getRandomNeighbour(arma::zeros<arma::Col<double>>(1), 0.0, 2.3), distanceFunction.getRandomNeighbourImplementation(arma::zeros<arma::Col<double>>(1), 0.0, 2.3)); } SECTION("Selected random neighbour remains unchanged, considering an unrestricted minimal distance.") { compare(distanceFunction.getRandomNeighbour(arma::zeros<arma::Col<double>>(1), 0.5, 2.3), distanceFunction.getRandomNeighbourImplementation(arma::zeros<arma::Col<double>>(1), 0.5, 2.3)); } SECTION("Selected random neighbour remains unchanged, considering an equal minimal and maximal distance.") { compare(distanceFunction.getRandomNeighbour(arma::zeros<arma::Col<double>>(1), 3.0, 3.0), distanceFunction.getRandomNeighbourImplementation(arma::zeros<arma::Col<double>>(1), 1.0, 1.0)); } SECTION("Throws an exception, if minimal distance < 0.") { arma::Col<double>::fixed<5> parameter = arma::zeros<arma::Col<double>>(5); CHECK_THROWS_AS(distanceFunction.getRandomNeighbour(parameter, -10.3, 4.0), std::logic_error); } SECTION("Throws an exception, if maximal distance < 0.") { arma::Col<double>::fixed<5> parameter = arma::zeros<arma::Col<double>>(5); CHECK_THROWS_AS(distanceFunction.getRandomNeighbour(parameter, -8.3, -4.0), std::logic_error); } SECTION("Throws an exception, if minimal distance > maximal distance.") { arma::Col<double>::fixed<5> parameter = arma::zeros<arma::Col<double>>(5); CHECK_THROWS_AS(distanceFunction.getRandomNeighbour(parameter, 10.3, 4.0), std::logic_error); } } SECTION("Testing getDistance(...)") { SECTION("Distance value remains unchanged.") { CHECK(distanceFunction.getDistance(arma::zeros<arma::Col<double>>(1)) == distanceFunction.getDistanceImplementation(arma::zeros<arma::Col<double>>(1))); CHECK(distanceFunction.getDistance(arma::Col<double>::fixed<5>({-1.2, 3.0, 1.0, -4.0, 0.0})) == distanceFunction.getDistanceImplementation(arma::Col<double>::fixed<5>({-1.2, 3.0, 1.0, -4.0, 0.0}))); } } } TEST_CASE("DistanceFunction<unsigned int>", "") { MockDistanceFunction<unsigned int> distanceFunction; SECTION("Testing getRandomNeighbour(..)") { SECTION("Selected random neighbour remains unchanged, considering an unrestricted minimal distance.") { compare(distanceFunction.getRandomNeighbour(arma::zeros<arma::Col<unsigned int>>(1), 0, 2), distanceFunction.getRandomNeighbourImplementation(arma::zeros<arma::Col<unsigned int>>(1), 0, 2)); } SECTION("Selected random neighbour remains unchanged, considering an unrestricted minimal distance.") { compare(distanceFunction.getRandomNeighbour(arma::zeros<arma::Col<unsigned int>>(1), 1, 2), distanceFunction.getRandomNeighbourImplementation(arma::zeros<arma::Col<unsigned int>>(1), 1, 2)); } SECTION("Selected random neighbour remains unchanged, considering an equal minimal and maximal distance.") { compare(distanceFunction.getRandomNeighbour(arma::zeros<arma::Col<unsigned int>>(1), 3, 3), distanceFunction.getRandomNeighbourImplementation(arma::zeros<arma::Col<unsigned int>>(1), 3, 3)); } SECTION("Throws an exception, if minimal distance > maximal distance.") { arma::Col<unsigned int>::fixed<5> parameter = arma::zeros<arma::Col<unsigned int>>(5); CHECK_THROWS_AS(distanceFunction.getRandomNeighbour(parameter, 10, 4), std::logic_error); } } SECTION("Testing getDistance(...)") { SECTION("Distance value remains unchanged.") { CHECK(distanceFunction.getDistance(arma::zeros<arma::Col<unsigned int>>(1)) == distanceFunction.getDistanceImplementation(arma::zeros<arma::Col<unsigned int>>(1))); CHECK(distanceFunction.getDistance(arma::Col<unsigned int>::fixed<5>({1, 3, 1, 4, 0})) == distanceFunction.getDistanceImplementation(arma::Col<unsigned int>::fixed<5>({1, 3, 1, 4, 0}))); } } } <commit_msg>test: Fixed minor typo<commit_after>// Catch #include <catch.hpp> #include <helper.hpp> // C++ Standard Library #include <cmath> // Mantella #include <mantella> template <typename ParameterType> class MockDistanceFunction : public mant::DistanceFunction<ParameterType>{ public: ParameterType getDistanceImplementation( const arma::Col<ParameterType>& parameter) const noexcept override; arma::Col<ParameterType> getRandomNeighbourImplementation( const arma::Col<ParameterType>& parameter, const ParameterType& minimalDistance, const ParameterType& maximalDistance) const noexcept override; }; template <> double MockDistanceFunction<double>::getDistanceImplementation( const arma::Col<double>& parameter) const noexcept { return arma::norm(parameter, 1); } template <> unsigned int MockDistanceFunction<unsigned int>::getDistanceImplementation( const arma::Col<unsigned int>& parameter) const noexcept { return arma::accu(parameter); } template <typename ParameterType> arma::Col<ParameterType> MockDistanceFunction<ParameterType>::getRandomNeighbourImplementation( const arma::Col<ParameterType>& parameter, const ParameterType& minimalDistance, const ParameterType& maximalDistance) const noexcept { arma::Col<ParameterType> result = parameter; result.at(0) += std::floor(maximalDistance + minimalDistance / 2.0); return result; } TEST_CASE("DistanceFunction<double>", "") { MockDistanceFunction<double> distanceFunction; SECTION("Testing getRandomNeighbour(..)") { SECTION("Selected random neighbour remains unchanged, considering an unrestricted minimal distance.") { compare(distanceFunction.getRandomNeighbour(arma::zeros<arma::Col<double>>(1), 0.0, 2.3), distanceFunction.getRandomNeighbourImplementation(arma::zeros<arma::Col<double>>(1), 0.0, 2.3)); } SECTION("Selected random neighbour remains unchanged, considering an unrestricted minimal distance.") { compare(distanceFunction.getRandomNeighbour(arma::zeros<arma::Col<double>>(1), 0.5, 2.3), distanceFunction.getRandomNeighbourImplementation(arma::zeros<arma::Col<double>>(1), 0.5, 2.3)); } SECTION("Selected random neighbour remains unchanged, considering an equal minimal and maximal distance.") { compare(distanceFunction.getRandomNeighbour(arma::zeros<arma::Col<double>>(1), 3.0, 3.0), distanceFunction.getRandomNeighbourImplementation(arma::zeros<arma::Col<double>>(1), 1.0, 1.0)); } SECTION("Throws an exception, if minimal distance < 0.") { arma::Col<double>::fixed<5> parameter = arma::zeros<arma::Col<double>>(5); CHECK_THROWS_AS(distanceFunction.getRandomNeighbour(parameter, -10.3, 4.0), std::logic_error); } SECTION("Throws an exception, if maximal distance < 0.") { arma::Col<double>::fixed<5> parameter = arma::zeros<arma::Col<double>>(5); CHECK_THROWS_AS(distanceFunction.getRandomNeighbour(parameter, -8.3, -4.0), std::logic_error); } SECTION("Throws an exception, if minimal distance > maximal distance.") { arma::Col<double>::fixed<5> parameter = arma::zeros<arma::Col<double>>(5); CHECK_THROWS_AS(distanceFunction.getRandomNeighbour(parameter, 10.3, 4.0), std::logic_error); } } SECTION("Testing getDistance(...)") { SECTION("Distance value remains unchanged.") { CHECK(distanceFunction.getDistance(arma::zeros<arma::Col<double>>(1)) == distanceFunction.getDistanceImplementation(arma::zeros<arma::Col<double>>(1))); CHECK(distanceFunction.getDistance(arma::Col<double>::fixed<5>({-1.2, 3.0, 1.0, -4.0, 0.0})) == distanceFunction.getDistanceImplementation(arma::Col<double>::fixed<5>({-1.2, 3.0, 1.0, -4.0, 0.0}))); } } } TEST_CASE("DistanceFunction<unsigned int>", "") { MockDistanceFunction<unsigned int> distanceFunction; SECTION("Testing getRandomNeighbour(..)") { SECTION("Selected random neighbour remains unchanged, considering an unrestricted minimal distance.") { compare(distanceFunction.getRandomNeighbour(arma::zeros<arma::Col<unsigned int>>(1), 0, 2), distanceFunction.getRandomNeighbourImplementation(arma::zeros<arma::Col<unsigned int>>(1), 0, 2)); } SECTION("Selected random neighbour remains unchanged, considering an unrestricted minimal distance.") { compare(distanceFunction.getRandomNeighbour(arma::zeros<arma::Col<unsigned int>>(1), 1, 2), distanceFunction.getRandomNeighbourImplementation(arma::zeros<arma::Col<unsigned int>>(1), 1, 2)); } SECTION("Selected random neighbour remains unchanged, considering an equal minimal and maximal distance.") { compare(distanceFunction.getRandomNeighbour(arma::zeros<arma::Col<unsigned int>>(1), 3, 3), distanceFunction.getRandomNeighbourImplementation(arma::zeros<arma::Col<unsigned int>>(1), 3, 3)); } SECTION("Throws an exception, if minimal distance > maximal distance.") { arma::Col<unsigned int>::fixed<5> parameter = arma::zeros<arma::Col<unsigned int>>(5); CHECK_THROWS_AS(distanceFunction.getRandomNeighbour(parameter, 10, 4), std::logic_error); } } SECTION("Testing getDistance(...)") { SECTION("Distance value remains unchanged.") { CHECK(distanceFunction.getDistance(arma::zeros<arma::Col<unsigned int>>(1)) == distanceFunction.getDistanceImplementation(arma::zeros<arma::Col<unsigned int>>(1))); CHECK(distanceFunction.getDistance(arma::Col<unsigned int>::fixed<5>({1, 3, 1, 4, 0})) == distanceFunction.getDistanceImplementation(arma::Col<unsigned int>::fixed<5>({1, 3, 1, 4, 0}))); } } } <|endoftext|>
<commit_before>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: include/eos/fitting/linear_shape_fitting.hpp * * Copyright 2014, 2015 Patrik Huber * * 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. */ #pragma once #ifndef LINEARSHAPEFITTING_HPP_ #define LINEARSHAPEFITTING_HPP_ #include "eos/morphablemodel/MorphableModel.hpp" //#include "Eigen/LU" #include "opencv2/core/core.hpp" #include "boost/optional.hpp" #include <vector> #include <cassert> namespace eos { namespace fitting { /** * Fits the shape of a Morphable Model to given 2D landmarks (i.e. estimates the maximum likelihood solution of the shape coefficients) as proposed in [1]. * It's a linear, closed-form solution fitting of the shape, with regularisation (prior towards the mean). * * [1] O. Aldrian & W. Smith, Inverse Rendering of Faces with a 3D Morphable Model, PAMI 2013. * * Note: Using less than the maximum number of coefficients to fit is not thoroughly tested yet and may contain an error. * Note: Returns coefficients following standard normal distribution (i.e. all have similar magnitude). Why? Because we fit using the normalised basis? * Note: The standard deviations given should be a vector, i.e. different for each landmark. This is not implemented yet. * * @param[in] morphable_model The Morphable Model whose shape (coefficients) are estimated. * @param[in] affine_camera_matrix A 3x4 affine camera matrix from model to screen-space (should probably be of type CV_32FC1 as all our calculations are done with float). * @param[in] landmarks 2D landmarks from an image to fit the model to. * @param[in] vertex_ids The vertex ids in the model that correspond to the 2D points. * @param[in] base_face The base or reference face from where the fitting is started. Usually this would be the models mean face, which is what will be used if the parameter is not explicitly specified. * @param[in] lambda The regularisation parameter (weight of the prior towards the mean). * @param[in] num_coefficients_to_fit How many shape-coefficients to fit (all others will stay 0). Should be bigger than zero, or boost::none to fit all coefficients. * @param[in] detector_standard_deviation The standard deviation of the 2D landmarks given (e.g. of the detector used), in pixels. * @param[in] model_standard_deviation The standard deviation of the 3D vertex points in the 3D model, projected to 2D (so the value is in pixels). * @return The estimated shape-coefficients (alphas). */ inline std::vector<float> fit_shape_to_landmarks_linear(const morphablemodel::MorphableModel& morphable_model, cv::Mat affine_camera_matrix, const std::vector<cv::Vec2f>& landmarks, const std::vector<int>& vertex_ids, Eigen::VectorXf base_face=Eigen::VectorXf(), float lambda=3.0f, boost::optional<int> num_coefficients_to_fit=boost::optional<int>(), boost::optional<float> detector_standard_deviation=boost::optional<float>(), boost::optional<float> model_standard_deviation=boost::optional<float>()) { using cv::Mat; assert(landmarks.size() == vertex_ids.size()); int num_coeffs_to_fit = num_coefficients_to_fit.get_value_or(morphable_model.get_shape_model().get_num_principal_components()); int num_landmarks = static_cast<int>(landmarks.size()); if (base_face.size() == 0) { base_face = morphable_model.get_shape_model().get_mean(); } // $\hat{V} \in R^{3N\times m-1}$, subselect the rows of the eigenvector matrix $V$ associated with the $N$ feature points // And we insert a row of zeros after every third row, resulting in matrix $\hat{V}_h \in R^{4N\times m-1}$: Mat V_hat_h = Mat::zeros(4 * num_landmarks, num_coeffs_to_fit, CV_32FC1); int row_index = 0; for (int i = 0; i < num_landmarks; ++i) { Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> basis_rows_ = morphable_model.get_shape_model().get_rescaled_pca_basis_at_point(vertex_ids[i]); // In the paper, the orthonormal basis might be used? I'm not sure, check it. It's even a mess in the paper. PH 26.5.2014: I think the rescaled basis is fine/better. // Above converts to a RowMajor matrix on return - for now, since the core algorithm still uses cv::Mat (and OpenCV stores data in row-major memory order). Mat basis_rows = Mat(basis_rows_.rows(), basis_rows_.cols(), CV_32FC1, basis_rows_.data()); //basisRows.copyTo(V_hat_h.rowRange(rowIndex, rowIndex + 3)); basis_rows.colRange(0, num_coeffs_to_fit).copyTo(V_hat_h.rowRange(row_index, row_index + 3)); row_index += 4; // replace 3 rows and skip the 4th one, it has all zeros } // Form a block diagonal matrix $P \in R^{3N\times 4N}$ in which the camera matrix C (P_Affine, affine_camera_matrix) is placed on the diagonal: Mat P = Mat::zeros(3 * num_landmarks, 4 * num_landmarks, CV_32FC1); for (int i = 0; i < num_landmarks; ++i) { Mat submatrix_to_replace = P.colRange(4 * i, (4 * i) + 4).rowRange(3 * i, (3 * i) + 3); affine_camera_matrix.copyTo(submatrix_to_replace); } // The variances: Add the 2D and 3D standard deviations. // If the user doesn't provide them, we choose the following: // 2D (detector) standard deviation: In pixel, we follow [1] and choose sqrt(3) as the default value. // 3D (model) variance: 0.0f. It only makes sense to set it to something when we have a different variance for different vertices. // The 3D variance has to be projected to 2D (for details, see paper [1]) so the units do match up. float sigma_squared_2D = std::pow(detector_standard_deviation.get_value_or(std::sqrt(3.0f)), 2) + std::pow(model_standard_deviation.get_value_or(0.0f), 2); Mat Omega = Mat::zeros(3 * num_landmarks, 3 * num_landmarks, CV_32FC1); for (int i = 0; i < 3 * num_landmarks; ++i) { // Sigma(i, i) = sqrt(sigma_squared_2D), but then Omega is Sigma.t() * Sigma (squares the diagonal) - so we just assign 1/sigma_squared_2D to Omega here: Omega.at<float>(i, i) = 1.0f / sigma_squared_2D; // the higher the sigma_squared_2D, the smaller the diagonal entries of Sigma will be } // The landmarks in matrix notation (in homogeneous coordinates), $3N\times 1$ Mat y = Mat::ones(3 * num_landmarks, 1, CV_32FC1); for (int i = 0; i < num_landmarks; ++i) { y.at<float>(3 * i, 0) = landmarks[i][0]; y.at<float>((3 * i) + 1, 0) = landmarks[i][1]; //y.at<float>((3 * i) + 2, 0) = 1; // already 1, stays (homogeneous coordinate) } // The mean, with an added homogeneous coordinate (x_1, y_1, z_1, 1, x_2, ...)^t Mat v_bar = Mat::ones(4 * num_landmarks, 1, CV_32FC1); for (int i = 0; i < num_landmarks; ++i) { //cv::Vec4f model_mean = morphable_model.get_shape_model().get_mean_at_point(vertex_ids[i]); cv::Vec4f model_mean(base_face(vertex_ids[i] * 3), base_face(vertex_ids[i] * 3 + 1), base_face(vertex_ids[i] * 3 + 2), 1.0f); v_bar.at<float>(4 * i, 0) = model_mean[0]; v_bar.at<float>((4 * i) + 1, 0) = model_mean[1]; v_bar.at<float>((4 * i) + 2, 0) = model_mean[2]; //v_bar.at<float>((4 * i) + 3, 0) = 1; // already 1, stays (homogeneous coordinate) // note: now that a Vec4f is returned, we could use copyTo? } // Bring into standard regularised quadratic form with diagonal distance matrix Omega Mat A = P * V_hat_h; // camera matrix times the basis Mat b = P * v_bar - y; // camera matrix times the mean, minus the landmarks. //Mat c_s; // The x, we solve for this! (the variance-normalised shape parameter vector, $c_s = [a_1/sigma_{s,1} , ..., a_m-1/sigma_{s,m-1}]^t$ //int numShapePc = morphableModel.getShapeModel().getNumberOfPrincipalComponents(); const int num_shape_pc = num_coeffs_to_fit; Mat AtOmegaA = A.t() * Omega * A; Mat AtOmegaAReg = AtOmegaA + lambda * Mat::eye(num_shape_pc, num_shape_pc, CV_32FC1); // Invert (and perform some sanity checks) using Eigen: /* using RowMajorMatrixXf = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>; Eigen::Map<RowMajorMatrixXf> AtOmegaAReg_Eigen(AtOmegaAReg.ptr<float>(), AtOmegaAReg.rows, AtOmegaAReg.cols); Eigen::FullPivLU<RowMajorMatrixXf> luOfAtOmegaAReg(AtOmegaAReg_Eigen); // Calculate the full-pivoting LU decomposition of the regularized AtA. Note: We could also try FullPivHouseholderQR if our system is non-minimal (i.e. there are more constraints than unknowns). auto rankOfAtOmegaAReg = luOfAtOmegaAReg.rank(); bool isAtOmegaARegInvertible = luOfAtOmegaAReg.isInvertible(); float threshold = std::abs(luOfAtOmegaAReg.maxPivot()) * luOfAtOmegaAReg.threshold(); // originaly "2 * ..." but I commented it out RowMajorMatrixXf AtARegInv_EigenFullLU = luOfAtOmegaAReg.inverse(); // Note: We should use ::solve() instead Mat AtOmegaARegInvFullLU(AtARegInv_EigenFullLU.rows(), AtARegInv_EigenFullLU.cols(), CV_32FC1, AtARegInv_EigenFullLU.data()); // create an OpenCV Mat header for the Eigen data */ // Solve using OpenCV: Mat c_s; // Note/Todo: We get coefficients ~ N(0, sigma) I think. They are not multiplied with the eigenvalues. bool non_singular = cv::solve(AtOmegaAReg, -A.t() * Omega.t() * b, c_s, cv::DECOMP_SVD); // DECOMP_SVD calculates the pseudo-inverse if the matrix is not invertible. // Because we're using SVD, non_singular will always be true. If we were to use e.g. Cholesky, we could return an expected<T>. return std::vector<float>(c_s); }; } /* namespace fitting */ } /* namespace eos */ #endif /* LINEARSHAPEFITTING_HPP_ */ <commit_msg>Changed linear shape fitting to use Eigen<commit_after>/* * eos - A 3D Morphable Model fitting library written in modern C++11/14. * * File: include/eos/fitting/linear_shape_fitting.hpp * * Copyright 2014, 2015 Patrik Huber * * 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. */ #pragma once #ifndef LINEARSHAPEFITTING_HPP_ #define LINEARSHAPEFITTING_HPP_ #include "eos/morphablemodel/MorphableModel.hpp" #include "Eigen/QR" #include "opencv2/core/core.hpp" #include "boost/optional.hpp" #include <vector> #include <cassert> namespace eos { namespace fitting { /** * Fits the shape of a Morphable Model to given 2D landmarks (i.e. estimates the maximum likelihood solution of the shape coefficients) as proposed in [1]. * It's a linear, closed-form solution fitting of the shape, with regularisation (prior towards the mean). * * [1] O. Aldrian & W. Smith, Inverse Rendering of Faces with a 3D Morphable Model, PAMI 2013. * * Note: Using less than the maximum number of coefficients to fit is not thoroughly tested yet and may contain an error. * Note: Returns coefficients following standard normal distribution (i.e. all have similar magnitude). Why? Because we fit using the normalised basis? * Note: The standard deviations given should be a vector, i.e. different for each landmark. This is not implemented yet. * * @param[in] morphable_model The Morphable Model whose shape (coefficients) are estimated. * @param[in] affine_camera_matrix A 3x4 affine camera matrix from model to screen-space (should probably be of type CV_32FC1 as all our calculations are done with float). * @param[in] landmarks 2D landmarks from an image to fit the model to. * @param[in] vertex_ids The vertex ids in the model that correspond to the 2D points. * @param[in] base_face The base or reference face from where the fitting is started. Usually this would be the models mean face, which is what will be used if the parameter is not explicitly specified. * @param[in] lambda The regularisation parameter (weight of the prior towards the mean). * @param[in] num_coefficients_to_fit How many shape-coefficients to fit (all others will stay 0). Should be bigger than zero, or boost::none to fit all coefficients. * @param[in] detector_standard_deviation The standard deviation of the 2D landmarks given (e.g. of the detector used), in pixels. * @param[in] model_standard_deviation The standard deviation of the 3D vertex points in the 3D model, projected to 2D (so the value is in pixels). * @return The estimated shape-coefficients (alphas). */ inline std::vector<float> fit_shape_to_landmarks_linear(const morphablemodel::MorphableModel& morphable_model, cv::Mat affine_camera_matrix, const std::vector<cv::Vec2f>& landmarks, const std::vector<int>& vertex_ids, Eigen::VectorXf base_face=Eigen::VectorXf(), float lambda=3.0f, boost::optional<int> num_coefficients_to_fit=boost::optional<int>(), boost::optional<float> detector_standard_deviation=boost::optional<float>(), boost::optional<float> model_standard_deviation=boost::optional<float>()) { assert(landmarks.size() == vertex_ids.size()); using Eigen::VectorXf; using Eigen::MatrixXf; int num_coeffs_to_fit = num_coefficients_to_fit.get_value_or(morphable_model.get_shape_model().get_num_principal_components()); int num_landmarks = static_cast<int>(landmarks.size()); if (base_face.size() == 0) { base_face = morphable_model.get_shape_model().get_mean(); } // $\hat{V} \in R^{3N\times m-1}$, subselect the rows of the eigenvector matrix $V$ associated with the $N$ feature points // And we insert a row of zeros after every third row, resulting in matrix $\hat{V}_h \in R^{4N\times m-1}$: MatrixXf V_hat_h = MatrixXf::Zero(4 * num_landmarks, num_coeffs_to_fit); int row_index = 0; for (int i = 0; i < num_landmarks; ++i) { MatrixXf basis_rows_ = morphable_model.get_shape_model().get_rescaled_pca_basis_at_point(vertex_ids[i]); // In the paper, the orthonormal basis might be used? I'm not sure, check it. It's even a mess in the paper. PH 26.5.2014: I think the rescaled basis is fine/better. V_hat_h.block(row_index, 0, 3, V_hat_h.cols()) = basis_rows_.block(0, 0, basis_rows_.rows(), num_coeffs_to_fit); row_index += 4; // replace 3 rows and skip the 4th one, it has all zeros } // Form a block diagonal matrix $P \in R^{3N\times 4N}$ in which the camera matrix C (P_Affine, affine_camera_matrix) is placed on the diagonal: MatrixXf P = MatrixXf::Zero(3 * num_landmarks, 4 * num_landmarks); for (int i = 0; i < num_landmarks; ++i) { using RowMajorMatrixXf = Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>; P.block(3 * i, 4 * i, 3, 4) = Eigen::Map<RowMajorMatrixXf>(affine_camera_matrix.ptr<float>(), affine_camera_matrix.rows, affine_camera_matrix.cols); } // The variances: Add the 2D and 3D standard deviations. // If the user doesn't provide them, we choose the following: // 2D (detector) standard deviation: In pixel, we follow [1] and choose sqrt(3) as the default value. // 3D (model) variance: 0.0f. It only makes sense to set it to something when we have a different variance for different vertices. // The 3D variance has to be projected to 2D (for details, see paper [1]) so the units do match up. float sigma_squared_2D = std::pow(detector_standard_deviation.get_value_or(std::sqrt(3.0f)), 2) + std::pow(model_standard_deviation.get_value_or(0.0f), 2); MatrixXf Omega = MatrixXf::Zero(3 * num_landmarks, 3 * num_landmarks); for (int i = 0; i < 3 * num_landmarks; ++i) { // Sigma(i, i) = sqrt(sigma_squared_2D), but then Omega is Sigma.t() * Sigma (squares the diagonal) - so we just assign 1/sigma_squared_2D to Omega here: Omega(i, i) = 1.0f / sigma_squared_2D; } // The landmarks in matrix notation (in homogeneous coordinates), $3N\times 1$ VectorXf y = VectorXf::Ones(3 * num_landmarks); for (int i = 0; i < num_landmarks; ++i) { y(3 * i) = landmarks[i][0]; y((3 * i) + 1) = landmarks[i][1]; //y((3 * i) + 2) = 1; // already 1, stays (homogeneous coordinate) } // The mean, with an added homogeneous coordinate (x_1, y_1, z_1, 1, x_2, ...)^t VectorXf v_bar = VectorXf::Ones(4 * num_landmarks); for (int i = 0; i < num_landmarks; ++i) { const cv::Vec4f model_mean(base_face(vertex_ids[i] * 3), base_face(vertex_ids[i] * 3 + 1), base_face(vertex_ids[i] * 3 + 2), 1.0f); v_bar(4 * i) = model_mean[0]; v_bar((4 * i) + 1) = model_mean[1]; v_bar((4 * i) + 2) = model_mean[2]; //v_bar((4 * i) + 3) = 1; // already 1, stays (homogeneous coordinate) } // Bring into standard regularised quadratic form with diagonal distance matrix Omega: const MatrixXf A = P * V_hat_h; // camera matrix times the basis const MatrixXf b = P * v_bar - y; // camera matrix times the mean, minus the landmarks const MatrixXf AtOmegaAReg = A.transpose() * Omega * A + lambda * Eigen::MatrixXf::Identity(num_coeffs_to_fit, num_coeffs_to_fit); const MatrixXf rhs = -A.transpose() * Omega.transpose() * b; // c_s: The 'x' that we solve for. (The variance-normalised shape parameter vector, $c_s = [a_1/sigma_{s,1} , ..., a_m-1/sigma_{s,m-1}]^t$.) // We get coefficients ~ N(0, 1), because we're fitting with the rescaled basis. The coefficients are not multiplied with their eigenvalues. const VectorXf c_s = AtOmegaAReg.colPivHouseholderQr().solve(rhs); return std::vector<float>(c_s.data(), c_s.data() + c_s.size()); }; } /* namespace fitting */ } /* namespace eos */ #endif /* LINEARSHAPEFITTING_HPP_ */ <|endoftext|>
<commit_before>#ifndef TEST_VECTOR_DS_HPP #define TEST_VECTOR_DS_HPP #include <boost/test/unit_test.hpp> #include <iostream> #include "types/vector_ds.hpp" int ITEM_COUNTER = 0; class Item { public: Item() : Item(-1) {} Item(const int& val) : value(val) { id = ITEM_COUNTER; ++ITEM_COUNTER; std::cout << "Item() #" << id << ": " << value << std::endl; } Item(const Item& other) : Item(other.value) { // std::cout << "In copy constructor" << std::endl; } ~Item() { std::cout << "Destruct Item #" << id << ", value = " << value << std::endl; } Item& operator=(const Item& other) { std::cout << "In copy assignment operator" << std::endl; this->value = other.value; return (*this); } friend bool operator==(const Item& left, const Item& right); public: int value; private: int id; }; bool operator==(const Item& left, const Item& right) { return left.value == right.value; } BOOST_AUTO_TEST_CASE(test_vds_create_vector) { DS::Vector<int> vector; BOOST_CHECK(true == vector.isEmpty()); BOOST_CHECK(0 == vector.size()); BOOST_CHECK(16 == vector.capacity()); } BOOST_AUTO_TEST_CASE(test_vds_create_with_size) { DS::Vector<int> vector(3); BOOST_CHECK(false == vector.isEmpty()); BOOST_CHECK(3 == vector.size()); BOOST_CHECK(0 == vector.at(0)); BOOST_CHECK(0 == vector.at(1)); BOOST_CHECK(0 == vector.at(2)); } BOOST_AUTO_TEST_CASE(test_vds_create_with_size_and_default_value) { Item item(42); DS::Vector<Item> vector(5, item); BOOST_CHECK(false == vector.isEmpty()); BOOST_CHECK(5 == vector.size()); BOOST_CHECK(item == vector.at(0)); BOOST_CHECK(item == vector.at(1)); BOOST_CHECK(item == vector.at(2)); BOOST_CHECK(item == vector.at(3)); BOOST_CHECK(item == vector.at(4)); } BOOST_AUTO_TEST_CASE(test_vds_add_elements) { DS::Vector<Item> vector(0); BOOST_CHECK(vector.isEmpty()); BOOST_CHECK(0 == vector.capacity()); vector.pushBack(1); vector.pushBack(2); vector.pushBack(3); vector.pushBack(4); BOOST_CHECK(false == vector.isEmpty()); BOOST_CHECK(4 == vector.size()); BOOST_CHECK(Item(1) == vector.at(0)); BOOST_CHECK(Item(2) == vector.at(1)); BOOST_CHECK(Item(3) == vector.at(2)); BOOST_CHECK(Item(4) == vector.at(3)); } /* BOOST_AUTO_TEST_CASE(test_vds_clear) { DS::Vector<int> vector; list.clear(); BOOST_CHECK(true == vector.isEmpty()); BOOST_CHECK(0 == vector.size()); list.addLast(1); list.addLast(2); list.clear(); BOOST_CHECK(true == vector.isEmpty()); BOOST_CHECK(0 == vector.size()); } BOOST_AUTO_TEST_CASE(test_vds_first_last) { DS::Vector<unsigned int> vector; BOOST_CHECK_THROW(vector.first(), std::length_error); BOOST_CHECK_THROW(vector.last(), std::length_error); list.addLast(186); list.addLast(187); list.addLast(28786); BOOST_CHECK(186 == vector.first()); BOOST_CHECK(28786 == vector.last()); } BOOST_AUTO_TEST_CASE(test_vds_at) { DS::Vector<unsigned int> vector; BOOST_CHECK_THROW(vector.at(0), std::length_error); list.addLast(186); list.addLast(187); list.addLast(28786); BOOST_CHECK_THROW(vector.at(-156), std::runtime_error); BOOST_CHECK_THROW(vector.at(10), std::runtime_error); BOOST_CHECK(186 == vector.at(0)); BOOST_CHECK(187 == vector.at(1)); BOOST_CHECK(28786 == vector.at(2)); } BOOST_AUTO_TEST_CASE(test_vds_add_first) { DS::Vector<unsigned int> vector; list.addFirst(186); list.addLast(187); list.addFirst(28786); BOOST_CHECK(3 == vector.size()); BOOST_CHECK(28786 == vector.first()); BOOST_CHECK(186 == vector.at(1)); BOOST_CHECK(187 == vector.last()); } BOOST_AUTO_TEST_CASE(test_vds_add_last) { DS::Vector<unsigned int> vector; list.addLast(186); list.addLast(187); BOOST_CHECK(186 == vector.first()); BOOST_CHECK(187 == vector.last()); } BOOST_AUTO_TEST_CASE(test_vds_insert) { DS::Vector<unsigned int> vector; list.insert(-100, 1); list.insert(1500, 2); list.insert(0, 3); list.insert(1, 4); BOOST_CHECK(3 == vector.at(0)); BOOST_CHECK(4 == vector.at(1)); BOOST_CHECK(1 == vector.at(2)); BOOST_CHECK(2 == vector.at(3)); } BOOST_AUTO_TEST_CASE(test_vds_remove) { DS::Vector<int> vector; list.remove(0); list.addLast(-100); list.addLast(1500); list.addLast(0); list.addLast(1); list.remove(-100); list.remove(1501); list.remove(1); BOOST_CHECK(3 == vector.size()); BOOST_CHECK(-100 == vector.at(0)); BOOST_CHECK(0 == vector.at(1)); BOOST_CHECK(1 == vector.at(2)); list.remove(2); BOOST_CHECK(2 == vector.size()); BOOST_CHECK(-100 == vector.at(0)); BOOST_CHECK(0 == vector.at(1)); list.remove(0); BOOST_CHECK(1 == vector.size()); BOOST_CHECK(0 == vector.at(0)); list.remove(0); BOOST_CHECK(0 == vector.size()); BOOST_CHECK(true == vector.isEmpty()); } BOOST_AUTO_TEST_CASE(test_vds_remove_first) { DS::Vector<unsigned int> vector; list.addLast(1); list.addLast(2); list.addLast(3); list.addLast(4); list.removeFirst(); BOOST_CHECK(3 == vector.size()); BOOST_CHECK(2 == vector.at(0)); BOOST_CHECK(3 == vector.at(1)); BOOST_CHECK(4 == vector.at(2)); list.removeFirst(); BOOST_CHECK(2 == vector.size()); BOOST_CHECK(3 == vector.at(0)); BOOST_CHECK(4 == vector.at(1)); list.removeFirst(); BOOST_CHECK(1 == vector.size()); BOOST_CHECK(4 == vector.at(0)); list.removeFirst(); BOOST_CHECK(0 == vector.size()); } BOOST_AUTO_TEST_CASE(test_vds_remove_last) { DS::Vector<unsigned int> vector; list.addLast(1); list.addLast(2); list.addLast(3); list.addLast(4); list.removeLast(); BOOST_CHECK(3 == vector.size()); BOOST_CHECK(1 == vector.at(0)); BOOST_CHECK(2 == vector.at(1)); BOOST_CHECK(3 == vector.at(2)); list.removeLast(); BOOST_CHECK(2 == vector.size()); BOOST_CHECK(1 == vector.at(0)); BOOST_CHECK(2 == vector.at(1)); list.removeLast(); BOOST_CHECK(1 == vector.size()); BOOST_CHECK(1 == vector.at(0)); list.removeLast(); BOOST_CHECK(0 == vector.size()); } */ #endif // TEST_VECTOR_DS_HPP <commit_msg>Add tests for Vector<commit_after>#ifndef TEST_VECTOR_DS_HPP #define TEST_VECTOR_DS_HPP #include <boost/test/unit_test.hpp> #include <iostream> #include "types/vector_ds.hpp" int ITEM_COUNTER = 0; class Item { public: Item() : Item(-1) {} Item(const int& val) : value(val) { id = ITEM_COUNTER; ++ITEM_COUNTER; std::cout << "Item() #" << id << ": " << value << std::endl; } Item(const Item& other) : Item(other.value) { // std::cout << "In copy constructor" << std::endl; } ~Item() { std::cout << "Destruct Item #" << id << ", value = " << value << std::endl; } Item& operator=(const Item& other) { std::cout << "In copy assignment operator" << std::endl; this->value = other.value; return (*this); } friend bool operator==(const Item& left, const Item& right); public: int value; private: int id; }; bool operator==(const Item& left, const Item& right) { return left.value == right.value; } BOOST_AUTO_TEST_CASE(test_vds_create_vector) { DS::Vector<int> vector; BOOST_CHECK(true == vector.isEmpty()); BOOST_CHECK(0 == vector.size()); BOOST_CHECK(16 == vector.capacity()); } BOOST_AUTO_TEST_CASE(test_vds_create_with_size) { DS::Vector<int> vector(3); BOOST_CHECK(false == vector.isEmpty()); BOOST_CHECK(3 == vector.size()); BOOST_CHECK(0 == vector.at(0)); BOOST_CHECK(0 == vector.at(1)); BOOST_CHECK(0 == vector.at(2)); } BOOST_AUTO_TEST_CASE(test_vds_create_with_size_and_default_value) { Item item(42); DS::Vector<Item> vector(5, item); BOOST_CHECK(false == vector.isEmpty()); BOOST_CHECK(5 == vector.size()); BOOST_CHECK(item == vector.at(0)); BOOST_CHECK(item == vector.at(1)); BOOST_CHECK(item == vector.at(2)); BOOST_CHECK(item == vector.at(3)); BOOST_CHECK(item == vector.at(4)); } BOOST_AUTO_TEST_CASE(test_vds_add_elements) { DS::Vector<Item> vector(0); BOOST_CHECK(vector.isEmpty()); BOOST_CHECK(0 == vector.capacity()); vector.pushBack(1); vector.pushBack(2); vector.pushBack(3); vector.pushBack(4); BOOST_CHECK(false == vector.isEmpty()); BOOST_CHECK(4 == vector.size()); BOOST_CHECK(Item(1) == vector.at(0)); BOOST_CHECK(Item(2) == vector.at(1)); BOOST_CHECK(Item(3) == vector.at(2)); BOOST_CHECK(Item(4) == vector.at(3)); } BOOST_AUTO_TEST_CASE(test_vds_clear) { DS::Vector<Item> vector; vector.clear(); BOOST_CHECK(true == vector.isEmpty()); BOOST_CHECK(0 == vector.size()); BOOST_CHECK(0 == vector.capacity()); vector.pushBack(1); vector.pushBack(2); vector.clear(); BOOST_CHECK(true == vector.isEmpty()); BOOST_CHECK(0 == vector.size()); BOOST_CHECK(0 == vector.capacity()); } BOOST_AUTO_TEST_CASE(test_vds_at) { DS::Vector<Item> vector; BOOST_CHECK_THROW(vector.at(0), std::out_of_range); vector.pushBack(186); vector.pushBack(187); vector.pushBack(28786); BOOST_CHECK_THROW(vector.at(156), std::out_of_range); BOOST_CHECK_THROW(vector.at(10), std::out_of_range); BOOST_CHECK(Item(186) == vector.at(0)); BOOST_CHECK(Item(187) == vector.at(1)); BOOST_CHECK(Item(28786) == vector.at(2)); vector.clear(); BOOST_CHECK_THROW(vector.at(0), std::out_of_range); } BOOST_AUTO_TEST_CASE(test_vds_prepend) { DS::Vector<unsigned int> vector; vector.prepend(186); vector.prepend(187); vector.prepend(28786); BOOST_CHECK(3 == vector.size()); BOOST_CHECK(28786 == vector.at(0)); BOOST_CHECK(187 == vector.at(1)); BOOST_CHECK(186 == vector.at(2)); } /* BOOST_AUTO_TEST_CASE(test_vds_insert) { DS::Vector<unsigned int> vector; list.insert(-100, 1); list.insert(1500, 2); list.insert(0, 3); list.insert(1, 4); BOOST_CHECK(3 == vector.at(0)); BOOST_CHECK(4 == vector.at(1)); BOOST_CHECK(1 == vector.at(2)); BOOST_CHECK(2 == vector.at(3)); } BOOST_AUTO_TEST_CASE(test_vds_remove) { DS::Vector<int> vector; list.remove(0); list.addLast(-100); list.addLast(1500); list.addLast(0); list.addLast(1); list.remove(-100); list.remove(1501); list.remove(1); BOOST_CHECK(3 == vector.size()); BOOST_CHECK(-100 == vector.at(0)); BOOST_CHECK(0 == vector.at(1)); BOOST_CHECK(1 == vector.at(2)); list.remove(2); BOOST_CHECK(2 == vector.size()); BOOST_CHECK(-100 == vector.at(0)); BOOST_CHECK(0 == vector.at(1)); list.remove(0); BOOST_CHECK(1 == vector.size()); BOOST_CHECK(0 == vector.at(0)); list.remove(0); BOOST_CHECK(0 == vector.size()); BOOST_CHECK(true == vector.isEmpty()); } BOOST_AUTO_TEST_CASE(test_vds_remove_first) { DS::Vector<unsigned int> vector; list.addLast(1); list.addLast(2); list.addLast(3); list.addLast(4); list.removeFirst(); BOOST_CHECK(3 == vector.size()); BOOST_CHECK(2 == vector.at(0)); BOOST_CHECK(3 == vector.at(1)); BOOST_CHECK(4 == vector.at(2)); list.removeFirst(); BOOST_CHECK(2 == vector.size()); BOOST_CHECK(3 == vector.at(0)); BOOST_CHECK(4 == vector.at(1)); list.removeFirst(); BOOST_CHECK(1 == vector.size()); BOOST_CHECK(4 == vector.at(0)); list.removeFirst(); BOOST_CHECK(0 == vector.size()); } BOOST_AUTO_TEST_CASE(test_vds_remove_last) { DS::Vector<unsigned int> vector; list.addLast(1); list.addLast(2); list.addLast(3); list.addLast(4); list.removeLast(); BOOST_CHECK(3 == vector.size()); BOOST_CHECK(1 == vector.at(0)); BOOST_CHECK(2 == vector.at(1)); BOOST_CHECK(3 == vector.at(2)); list.removeLast(); BOOST_CHECK(2 == vector.size()); BOOST_CHECK(1 == vector.at(0)); BOOST_CHECK(2 == vector.at(1)); list.removeLast(); BOOST_CHECK(1 == vector.size()); BOOST_CHECK(1 == vector.at(0)); list.removeLast(); BOOST_CHECK(0 == vector.size()); } */ #endif // TEST_VECTOR_DS_HPP <|endoftext|>
<commit_before>/** * @file ReactorFactory.cpp */ // Copyright 2006 California Institute of Technology #include "cantera/zeroD/ReactorFactory.h" #include "cantera/zeroD/Reservoir.h" #include "cantera/zeroD/Reactor.h" #include "cantera/zeroD/FlowReactor.h" #include "cantera/zeroD/ConstPressureReactor.h" using namespace std; namespace Cantera { ReactorFactory* ReactorFactory::s_factory = 0; mutex_t ReactorFactory::reactor_mutex; static int ntypes = 4; static string _types[] = {"Reservoir", "Reactor", "ConstPressureReactor", "FlowReactor" }; // these constants are defined in ReactorBase.h static int _itypes[] = {ReservoirType, ReactorType, FlowReactorType, ConstPressureReactorType }; /** * This method returns a new instance of a subclass of ThermoPhase */ ReactorBase* ReactorFactory::newReactor(string reactorType) { int ir=-1; for (int n = 0; n < ntypes; n++) { if (reactorType == _types[n]) { ir = _itypes[n]; } } return newReactor(ir); } ReactorBase* ReactorFactory::newReactor(int ir) { switch (ir) { case ReservoirType: return new Reservoir(); case ReactorType: return new Reactor(); case FlowReactorType: return new FlowReactor(); case ConstPressureReactorType: return new ConstPressureReactor(); default: throw Cantera::CanteraError("ReactorFactory::newReactor", "unknown reactor type!"); } return 0; } } <commit_msg>Fixed correspondence of reactor type string names to integer constants<commit_after>/** * @file ReactorFactory.cpp */ // Copyright 2006 California Institute of Technology #include "cantera/zeroD/ReactorFactory.h" #include "cantera/zeroD/Reservoir.h" #include "cantera/zeroD/Reactor.h" #include "cantera/zeroD/FlowReactor.h" #include "cantera/zeroD/ConstPressureReactor.h" using namespace std; namespace Cantera { ReactorFactory* ReactorFactory::s_factory = 0; mutex_t ReactorFactory::reactor_mutex; static int ntypes = 4; static string _types[] = {"Reservoir", "Reactor", "ConstPressureReactor", "FlowReactor" }; // these constants are defined in ReactorBase.h static int _itypes[] = {ReservoirType, ReactorType, ConstPressureReactorType, FlowReactorType }; /** * This method returns a new instance of a subclass of ThermoPhase */ ReactorBase* ReactorFactory::newReactor(string reactorType) { int ir=-1; for (int n = 0; n < ntypes; n++) { if (reactorType == _types[n]) { ir = _itypes[n]; } } return newReactor(ir); } ReactorBase* ReactorFactory::newReactor(int ir) { switch (ir) { case ReservoirType: return new Reservoir(); case ReactorType: return new Reactor(); case FlowReactorType: return new FlowReactor(); case ConstPressureReactorType: return new ConstPressureReactor(); default: throw Cantera::CanteraError("ReactorFactory::newReactor", "unknown reactor type!"); } return 0; } } <|endoftext|>
<commit_before>/* * Mod.cpp * OpenLieroX * * Created by Albert Zeyer on 08.12.09. * code under LGPL * */ #include <boost/bind.hpp> #include "Mod.h" #include "CGameScript.h" #include "FindFile.h" #include "Options.h" #include "util/macros.h" #include "ConfigHandler.h" #include "DeprecatedGUI/CCombobox.h" #include "gui/List.h" ModInfo infoForMod(const std::string& f, bool absolute) { std::string name; ModInfo info; CGameScript::CheckFile(f, name, absolute, &info); return info; } std::string modName(const std::string& f) { ModInfo info = infoForMod(f); if(info.valid) return info.name; return ""; } static GameSettingsPresetInfo settingsInfo(const std::string& path, bool global) { GameSettingsPresetInfo info; info.global = global; if(!ReadString(path, "GameSettings", "Name", info.name, "")) info.name = GetBaseFilenameWithoutExt(path); ReadString(path, "GameSettings", "Description", info.description, ""); info.path = path; return info; } std::set<GameSettingsPresetInfo> presetsForMod(const std::string& modDir) { std::set<GameSettingsPresetInfo> presets; for(Iterator<std::string>::Ref it = FileListIter(".", false, FM_REG, "*.gamesettings"); it->isValid(); it->next()) presets.insert(settingsInfo("./" + GetBaseFilename(it->get()), true)); for(Iterator<std::string>::Ref it = FileListIter(modDir, false, FM_REG, "*.gamesettings"); it->isValid(); it->next()) presets.insert(settingsInfo(modDir + "/" + GetBaseFilename(it->get()), false)); return presets; } GuiListItem::Pt infoForSettingsPreset(const GameSettingsPresetInfo& preset) { struct Item : GuiListItem { Item(const GameSettingsPresetInfo& p) : preset(p) {} GameSettingsPresetInfo preset; virtual std::string caption() { return preset.name; } virtual std::string tooltip() { return preset.description; } virtual std::string index() { return preset.path; } }; return new Item(preset); } static std::list<GuiListItem::Pt> getCurrentSettingsPresetList() { std::set<GameSettingsPresetInfo> presets = presetsForMod(tLXOptions->tGameInfo.sModDir); std::list<GuiListItem::Pt> presetList; foreach(i, presets) presetList.push_back(infoForSettingsPreset(*i)); return presetList; } GuiList::Pt dynamicPresetListForCurrentMod() { return dynamicGuiList(boost::bind(&getCurrentSettingsPresetList)); } void setupModGameSettingsPresetComboboxes(DeprecatedGUI::CCombobox* modList, DeprecatedGUI::CCombobox* presetList) { presetList->setListBackend( dynamicPresetListForCurrentMod() ); modList->OnChangeSelection.connect( boost::bind(&DeprecatedGUI::CCombobox::updateFromListBackend, presetList) ); presetList->updateFromListBackend(); // also update right now } <commit_msg>small workaround, so that you have a working version for now (but why the hell does that hang?)<commit_after>/* * Mod.cpp * OpenLieroX * * Created by Albert Zeyer on 08.12.09. * code under LGPL * */ #include <boost/bind.hpp> #include "Mod.h" #include "CGameScript.h" #include "FindFile.h" #include "Options.h" #include "util/macros.h" #include "ConfigHandler.h" #include "DeprecatedGUI/CCombobox.h" #include "gui/List.h" ModInfo infoForMod(const std::string& f, bool absolute) { std::string name; ModInfo info; CGameScript::CheckFile(f, name, absolute, &info); return info; } std::string modName(const std::string& f) { ModInfo info = infoForMod(f); if(info.valid) return info.name; return ""; } static GameSettingsPresetInfo settingsInfo(const std::string& path, bool global) { GameSettingsPresetInfo info; info.global = global; if(!ReadString(path, "GameSettings", "Name", info.name, "")) info.name = GetBaseFilenameWithoutExt(path); ReadString(path, "GameSettings", "Description", info.description, ""); info.path = path; return info; } std::set<GameSettingsPresetInfo> presetsForMod(const std::string& modDir) { std::set<GameSettingsPresetInfo> presets; for(Iterator<std::string>::Ref it = FileListIter(".", false, FM_REG, "*.gamesettings"); it->isValid(); it->next()) presets.insert(settingsInfo("./" + GetBaseFilename(it->get()), true)); for(Iterator<std::string>::Ref it = FileListIter(modDir, false, FM_REG, "*.gamesettings"); it->isValid(); it->next()) presets.insert(settingsInfo(modDir + "/" + GetBaseFilename(it->get()), false)); return presets; } GuiListItem::Pt infoForSettingsPreset(const GameSettingsPresetInfo& preset) { struct Item : GuiListItem { Item(const GameSettingsPresetInfo& p) : preset(p) {} GameSettingsPresetInfo preset; virtual std::string caption() { return preset.name; } virtual std::string tooltip() { return preset.description; } virtual std::string index() { return preset.path; } }; return new Item(preset); } static std::list<GuiListItem::Pt> getCurrentSettingsPresetList() { std::set<GameSettingsPresetInfo> presets = presetsForMod(tLXOptions->tGameInfo.sModDir); std::list<GuiListItem::Pt> presetList; foreach(i, presets) presetList.push_back(infoForSettingsPreset(*i)); return presetList; } GuiList::Pt dynamicPresetListForCurrentMod() { return dynamicGuiList(boost::bind(&getCurrentSettingsPresetList)); } void setupModGameSettingsPresetComboboxes(DeprecatedGUI::CCombobox* modList, DeprecatedGUI::CCombobox* presetList) { return; // TODO: ??? presetList->setListBackend( dynamicPresetListForCurrentMod() ); modList->OnChangeSelection.connect( boost::bind(&DeprecatedGUI::CCombobox::updateFromListBackend, presetList) ); presetList->updateFromListBackend(); // also update right now } <|endoftext|>
<commit_before>#include "gfx.h" #include <FreeImage.h> #ifdef _RASPI #include <GLES2/gl2.h> #else #include <GL/glew.h> #endif using namespace gfx; Image::Image(const _priv&, uint32_t w, uint32_t h, uint8_t* pixmap) : _pixmap(pixmap), _width(w), _height(h) { _tex = 0; } Image::~Image() { free(_pixmap); if (_tex){ glDeleteTextures(1, &_tex); } } std::shared_ptr<Image> Image::create(const std::string& filename) { FREE_IMAGE_FORMAT fmt = FreeImage_GetFileType(filename.c_str(), 0); if (fmt == FIF_UNKNOWN) { fmt = FreeImage_GetFIFFromFilename(filename.c_str() ); } // if still unkown, return failure. if (fmt == FIF_UNKNOWN) { LOG(ERR) << "image: could not determine format: " << filename; return nullptr; } FIBITMAP* bmp = FreeImage_Load(fmt, filename.c_str()); if (!bmp) { LOG(ERR) << "image: could not load image: " << filename; return nullptr; } uint32_t w = FreeImage_GetWidth(bmp); uint32_t h = FreeImage_GetHeight(bmp); if (!w || !h) { LOG(ERR) << "image: invalid dimension: " << filename; FreeImage_Unload(bmp); return nullptr; } bool alpha = true; FIBITMAP* temp = bmp; bmp = FreeImage_ConvertTo32Bits(temp); FreeImage_Unload(temp); uint8_t* pixmap = reinterpret_cast<uint8_t*>(malloc(w * h * 4)); if (!pixmap) { FreeImage_Unload(bmp); return nullptr; } //FreeImage_ConvertToRawBits(pixmap, bmp, w*4, 32, 0, 0, 0); uint8_t* pixels = reinterpret_cast<uint8_t*>(FreeImage_GetBits(bmp)); for (int j= 0; j < w*h; ++j) { pixmap[j*4+0] = pixels[j*4+2]; pixmap[j*4+1] = pixels[j*4+1]; pixmap[j*4+2] = pixels[j*4+0]; pixmap[j*4+3] = pixels[j*4+3]; } FreeImage_Unload(bmp); auto img(std::make_shared<Image>(_priv{}, w, h, pixmap)); GLenum err; GLuint tex; glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); //glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D( GL_TEXTURE_2D, 0, alpha ? GL_RGBA : GL_RGB, w, h, 0, alpha ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, pixmap); err = glGetError(); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); err = glGetError(); glBindTexture(GL_TEXTURE_2D, 0); img->_tex = tex; return img; } uint32_t Image::texture() { return _tex; }<commit_msg>compiler errors on pi<commit_after>#include "gfx.h" #include <FreeImage.h> #ifdef _RASPI #include <GLES2/gl2.h> #else #include <GL/glew.h> #endif using namespace gfx; Image::Image(const _priv&, uint32_t w, uint32_t h, uint8_t* pixmap) : _pixmap(pixmap), _width(w), _height(h) { _tex = 0; } Image::~Image() { free(_pixmap); if (_tex){ glDeleteTextures(1, &_tex); } } std::shared_ptr<Image> Image::create(const std::string& filename) { FREE_IMAGE_FORMAT fmt = FreeImage_GetFileType(filename.c_str(), 0); if (fmt == FIF_UNKNOWN) { fmt = FreeImage_GetFIFFromFilename(filename.c_str() ); } // if still unkown, return failure. if (fmt == FIF_UNKNOWN) { LOG(ERR) << "image: could not determine format: " << filename; return nullptr; } FIBITMAP* bmp = FreeImage_Load(fmt, filename.c_str()); if (!bmp) { LOG(ERR) << "image: could not load image: " << filename; return nullptr; } uint32_t w = FreeImage_GetWidth(bmp); uint32_t h = FreeImage_GetHeight(bmp); if (!w || !h) { LOG(ERR) << "image: invalid dimension: " << filename; FreeImage_Unload(bmp); return nullptr; } bool alpha = true; FIBITMAP* temp = bmp; bmp = FreeImage_ConvertTo32Bits(temp); FreeImage_Unload(temp); uint8_t* pixmap = reinterpret_cast<uint8_t*>(malloc(w * h * 4)); if (!pixmap) { FreeImage_Unload(bmp); return nullptr; } //FreeImage_ConvertToRawBits(pixmap, bmp, w*4, 32, 0, 0, 0); uint8_t* pixels = reinterpret_cast<uint8_t*>(FreeImage_GetBits(bmp)); for (int j= 0; j < w*h; ++j) { pixmap[j*4+0] = pixels[j*4+2]; pixmap[j*4+1] = pixels[j*4+1]; pixmap[j*4+2] = pixels[j*4+0]; pixmap[j*4+3] = pixels[j*4+3]; } FreeImage_Unload(bmp); auto img(std::make_shared<Image>(_priv{}, w, h, pixmap)); GLenum err; GLuint tex; glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); //glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D( GL_TEXTURE_2D, 0, alpha ? GL_RGBA : GL_RGB, w, h, 0, alpha ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, pixmap); err = glGetError(); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_BASE_LEVEL, 0); //glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); err = glGetError(); glBindTexture(GL_TEXTURE_2D, 0); img->_tex = tex; return img; } uint32_t Image::texture() { return _tex; } <|endoftext|>
<commit_before>// Copyright 2015 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "benchmark/reporter.h" #include <cstdint> #include <cstdio> #include <iostream> #include <string> #include <tuple> #include <vector> #include "check.h" #include "colorprint.h" #include "string_util.h" #include "walltime.h" namespace benchmark { bool ConsoleReporter::ReportContext(const Context& context) { name_field_width_ = context.name_field_width; std::cerr << "Run on (" << context.num_cpus << " X " << context.mhz_per_cpu << " MHz CPU " << ((context.num_cpus > 1) ? "s" : "") << ")\n"; std::cerr << LocalDateTimeString() << "\n"; if (context.cpu_scaling_enabled) { std::cerr << "***WARNING*** CPU scaling is enabled, the benchmark " "real time measurements may be noisy and will incur extra " "overhead.\n"; } #ifndef NDEBUG std::cerr << "***WARNING*** Library was built as DEBUG. Timings may be " "affected.\n"; #endif int output_width = fprintf(stdout, "%-*s %13s %13s %10s\n", static_cast<int>(name_field_width_), "Benchmark", "Time", "CPU", "Iterations"); std::cout << std::string(output_width - 1, '-') << "\n"; return true; } void ConsoleReporter::ReportRuns(const std::vector<Run>& reports) { if (reports.empty()) { return; } for (Run const& run : reports) { CHECK_EQ(reports[0].benchmark_name, run.benchmark_name); PrintRunData(run); } if (reports.size() < 2) { // We don't report aggregated data if there was a single run. return; } Run mean_data; Run stddev_data; BenchmarkReporter::ComputeStats(reports, &mean_data, &stddev_data); // Output using PrintRun. PrintRunData(mean_data); PrintRunData(stddev_data); } void ConsoleReporter::ReportComplexity(const std::vector<Run> & complexity_reports) { if (complexity_reports.size() < 2) { // We don't report asymptotic complexity data if there was a single run. return; } Run big_o_data; Run rms_data; BenchmarkReporter::ComputeBigO(complexity_reports, &big_o_data, &rms_data); // Output using PrintRun. PrintRunData(big_o_data); PrintRunData(rms_data); } void ConsoleReporter::PrintRunData(const Run& result) { // Format bytes per second std::string rate; if (result.bytes_per_second > 0) { rate = StrCat(" ", HumanReadableNumber(result.bytes_per_second), "B/s"); } // Format items per second std::string items; if (result.items_per_second > 0) { items = StrCat(" ", HumanReadableNumber(result.items_per_second), " items/s"); } double multiplier; const char* timeLabel; std::tie(timeLabel, multiplier) = GetTimeUnitAndMultiplier(result.time_unit); ColorPrintf((result.report_big_o ||result.report_rms) ? COLOR_BLUE : COLOR_GREEN, "%-*s ", name_field_width_, result.benchmark_name.c_str()); if(result.report_big_o) { std::string big_o = result.report_big_o ? GetBigO(result.complexity) : ""; ColorPrintf(COLOR_YELLOW, "%10.4f %s %10.4f %s ", result.real_accumulated_time * multiplier, big_o.c_str(), result.cpu_accumulated_time * multiplier, big_o.c_str()); } else if(result.report_rms) { ColorPrintf(COLOR_YELLOW, "%10.0f %s %10.0f %s ", result.real_accumulated_time * multiplier * 100, "%", result.cpu_accumulated_time * multiplier * 100, "%"); } else if (result.iterations == 0) { ColorPrintf(COLOR_YELLOW, "%10.0f %s %10.0f %s ", result.real_accumulated_time * multiplier, timeLabel, result.cpu_accumulated_time * multiplier, timeLabel); } else { ColorPrintf(COLOR_YELLOW, "%10.0f %s %10.0f %s ", (result.real_accumulated_time * multiplier) / (static_cast<double>(result.iterations)), timeLabel, (result.cpu_accumulated_time * multiplier) / (static_cast<double>(result.iterations)), timeLabel); } if(!result.report_big_o && !result.report_rms) ColorPrintf(COLOR_CYAN, "%10lld", result.iterations); if (!rate.empty()) { ColorPrintf(COLOR_DEFAULT, " %*s", 13, rate.c_str()); } if (!items.empty()) { ColorPrintf(COLOR_DEFAULT, " %*s", 18, items.c_str()); } if (!result.report_label.empty()) { ColorPrintf(COLOR_DEFAULT, " %s", result.report_label.c_str()); } ColorPrintf(COLOR_DEFAULT, "\n"); } } // end namespace benchmark <commit_msg>simplify format string for complexity output<commit_after>// Copyright 2015 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "benchmark/reporter.h" #include <cstdint> #include <cstdio> #include <iostream> #include <string> #include <tuple> #include <vector> #include "check.h" #include "colorprint.h" #include "string_util.h" #include "walltime.h" namespace benchmark { bool ConsoleReporter::ReportContext(const Context& context) { name_field_width_ = context.name_field_width; std::cerr << "Run on (" << context.num_cpus << " X " << context.mhz_per_cpu << " MHz CPU " << ((context.num_cpus > 1) ? "s" : "") << ")\n"; std::cerr << LocalDateTimeString() << "\n"; if (context.cpu_scaling_enabled) { std::cerr << "***WARNING*** CPU scaling is enabled, the benchmark " "real time measurements may be noisy and will incur extra " "overhead.\n"; } #ifndef NDEBUG std::cerr << "***WARNING*** Library was built as DEBUG. Timings may be " "affected.\n"; #endif int output_width = fprintf(stdout, "%-*s %13s %13s %10s\n", static_cast<int>(name_field_width_), "Benchmark", "Time", "CPU", "Iterations"); std::cout << std::string(output_width - 1, '-') << "\n"; return true; } void ConsoleReporter::ReportRuns(const std::vector<Run>& reports) { if (reports.empty()) { return; } for (Run const& run : reports) { CHECK_EQ(reports[0].benchmark_name, run.benchmark_name); PrintRunData(run); } if (reports.size() < 2) { // We don't report aggregated data if there was a single run. return; } Run mean_data; Run stddev_data; BenchmarkReporter::ComputeStats(reports, &mean_data, &stddev_data); // Output using PrintRun. PrintRunData(mean_data); PrintRunData(stddev_data); } void ConsoleReporter::ReportComplexity(const std::vector<Run> & complexity_reports) { if (complexity_reports.size() < 2) { // We don't report asymptotic complexity data if there was a single run. return; } Run big_o_data; Run rms_data; BenchmarkReporter::ComputeBigO(complexity_reports, &big_o_data, &rms_data); // Output using PrintRun. PrintRunData(big_o_data); PrintRunData(rms_data); } void ConsoleReporter::PrintRunData(const Run& result) { // Format bytes per second std::string rate; if (result.bytes_per_second > 0) { rate = StrCat(" ", HumanReadableNumber(result.bytes_per_second), "B/s"); } // Format items per second std::string items; if (result.items_per_second > 0) { items = StrCat(" ", HumanReadableNumber(result.items_per_second), " items/s"); } double multiplier; const char* timeLabel; std::tie(timeLabel, multiplier) = GetTimeUnitAndMultiplier(result.time_unit); ColorPrintf((result.report_big_o ||result.report_rms) ? COLOR_BLUE : COLOR_GREEN, "%-*s ", name_field_width_, result.benchmark_name.c_str()); if(result.report_big_o) { std::string big_o = result.report_big_o ? GetBigO(result.complexity) : ""; ColorPrintf(COLOR_YELLOW, "%10.4f %s %10.4f %s ", result.real_accumulated_time * multiplier, big_o.c_str(), result.cpu_accumulated_time * multiplier, big_o.c_str()); } else if(result.report_rms) { ColorPrintf(COLOR_YELLOW, "%10.0f %% %10.0f %% ", result.real_accumulated_time * multiplier * 100, result.cpu_accumulated_time * multiplier * 100); } else if (result.iterations == 0) { ColorPrintf(COLOR_YELLOW, "%10.0f %s %10.0f %s ", result.real_accumulated_time * multiplier, timeLabel, result.cpu_accumulated_time * multiplier, timeLabel); } else { ColorPrintf(COLOR_YELLOW, "%10.0f %s %10.0f %s ", (result.real_accumulated_time * multiplier) / (static_cast<double>(result.iterations)), timeLabel, (result.cpu_accumulated_time * multiplier) / (static_cast<double>(result.iterations)), timeLabel); } if(!result.report_big_o && !result.report_rms) ColorPrintf(COLOR_CYAN, "%10lld", result.iterations); if (!rate.empty()) { ColorPrintf(COLOR_DEFAULT, " %*s", 13, rate.c_str()); } if (!items.empty()) { ColorPrintf(COLOR_DEFAULT, " %*s", 18, items.c_str()); } if (!result.report_label.empty()) { ColorPrintf(COLOR_DEFAULT, " %s", result.report_label.c_str()); } ColorPrintf(COLOR_DEFAULT, "\n"); } } // end namespace benchmark <|endoftext|>
<commit_before>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include <vistk/pipeline/schedule.h> #include <vistk/pipeline/schedule_exception.h> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <boost/python/class.hpp> #include <boost/python/exception_translator.hpp> #include <boost/python/module.hpp> #include <boost/python/override.hpp> #include <boost/python/pure_virtual.hpp> /** * \file schedule.cxx * * \brief Python bindings for \link vistk::schedule\endlink. */ using namespace boost::python; static void translator(vistk::schedule_exception const& e); class wrap_schedule : public vistk::schedule , public wrapper<vistk::schedule> { public: wrap_schedule(vistk::config_t const& config, vistk::pipeline_t const& pipe); ~wrap_schedule(); void start(); void wait(); void stop(); override get_pure_override(char const* name); }; BOOST_PYTHON_MODULE(schedule) { register_exception_translator< vistk::schedule_exception>(translator); class_<wrap_schedule, boost::noncopyable>("PythonSchedule" , "The base class for Python schedules." , no_init) .def(init<vistk::config_t, vistk::pipeline_t>()) .def("start", pure_virtual(&vistk::schedule::start) , "Start the execution of the pipeline.") .def("wait", pure_virtual(&vistk::schedule::wait) , "Wait until the pipeline execution is complete.") .def("stop", pure_virtual(&vistk::schedule::stop) , "Stop the execution of the pipeline.") ; } void translator(vistk::schedule_exception const& e) { PyErr_SetString(PyExc_RuntimeError, e.what()); } wrap_schedule ::wrap_schedule(vistk::config_t const& config, vistk::pipeline_t const& pipe) : vistk::schedule(config, pipe) { } wrap_schedule ::~wrap_schedule() { } void wrap_schedule ::start() { get_pure_override("start")(); } void wrap_schedule ::wait() { get_pure_override("wait")(); } void wrap_schedule ::stop() { get_pure_override("stop")(); } override wrap_schedule ::get_pure_override(char const* name) { override const o = get_override(name); if (!o) { std::ostringstream sstr; sstr << name << " is not implemented"; throw std::runtime_error(sstr.str().c_str()); } return o; } <commit_msg>Add the pipeline method to schedules<commit_after>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include <vistk/pipeline/pipeline.h> #include <vistk/pipeline/schedule.h> #include <vistk/pipeline/schedule_exception.h> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <boost/python/class.hpp> #include <boost/python/exception_translator.hpp> #include <boost/python/module.hpp> #include <boost/python/override.hpp> #include <boost/python/pure_virtual.hpp> /** * \file schedule.cxx * * \brief Python bindings for \link vistk::schedule\endlink. */ using namespace boost::python; static void translator(vistk::schedule_exception const& e); class wrap_schedule : public vistk::schedule , public wrapper<vistk::schedule> { public: wrap_schedule(vistk::config_t const& config, vistk::pipeline_t const& pipe); ~wrap_schedule(); void start(); void wait(); void stop(); vistk::pipeline_t _pipeline() const; override get_pure_override(char const* name); }; BOOST_PYTHON_MODULE(schedule) { register_exception_translator< vistk::schedule_exception>(translator); class_<wrap_schedule, boost::noncopyable>("PythonSchedule" , "The base class for Python schedules." , no_init) .def(init<vistk::config_t, vistk::pipeline_t>()) .def("start", pure_virtual(&vistk::schedule::start) , "Start the execution of the pipeline.") .def("wait", pure_virtual(&vistk::schedule::wait) , "Wait until the pipeline execution is complete.") .def("stop", pure_virtual(&vistk::schedule::stop) , "Stop the execution of the pipeline.") .def("pipeline", &wrap_schedule::_pipeline , "The pipeline the schedule is to run.") ; } void translator(vistk::schedule_exception const& e) { PyErr_SetString(PyExc_RuntimeError, e.what()); } wrap_schedule ::wrap_schedule(vistk::config_t const& config, vistk::pipeline_t const& pipe) : vistk::schedule(config, pipe) { } wrap_schedule ::~wrap_schedule() { } void wrap_schedule ::start() { get_pure_override("start")(); } void wrap_schedule ::wait() { get_pure_override("wait")(); } void wrap_schedule ::stop() { get_pure_override("stop")(); } vistk::pipeline_t wrap_schedule ::_pipeline() const { return pipeline(); } override wrap_schedule ::get_pure_override(char const* name) { override const o = get_override(name); if (!o) { std::ostringstream sstr; sstr << name << " is not implemented"; throw std::runtime_error(sstr.str().c_str()); } return o; } <|endoftext|>
<commit_before>/* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004 darkbits Js_./ * Per Larsson a.k.a finalman _RqZ{a<^_aa * Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a// * _Qhm`] _f "'c 1!5m * Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[ * .)j(] .d_/ '-( P . S * License: (BSD) <Td/Z <fP"5(\"??"\a. .L * Redistribution and use in source and _dV>ws?a-?' ._/L #' * binary forms, with or without )4d[#7r, . ' )d`)[ * modification, are permitted provided _Q-5'5W..j/?' -?!\)cam' * that the following conditions are met: j<<WP+k/);. _W=j f * 1. Redistributions of source code must .$%w\/]Q . ."' . mj$ * retain the above copyright notice, ]E.pYY(Q]>. a J@\ * this list of conditions and the j(]1u<sE"L,. . ./^ ]{a * following disclaimer. 4'_uomm\. )L);-4 (3= * 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[ * reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/ * following disclaimer in the <B!</]C)d_, '(<' .f. =C+m * documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]' * provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W" * 3. Neither the name of Guichan nor the :$we` _! + _/ . j? * names of its contributors may be used =3)= _f (_yQmWW$#( " * to endorse or promote products derived - W, sQQQQmZQ#Wwa].. * from this software without specific (js, \[QQW$QWW#?!V"". * prior written permission. ]y:.<\.. . * -]n w/ ' [. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ ! * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , ' * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- % * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'., * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?" * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. . * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _, * 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. */ /* * For comments regarding functions please see the header file. */ #include "guichan/graphics.hpp" #include "guichan/exception.hpp" #include "guichan/font.hpp" namespace gcn { Graphics::Graphics() { mFont = NULL; } // end graphics bool Graphics::pushClipArea(Rectangle area) { if (mClipStack.empty()) { ClipRectangle carea; carea.x = area.x; carea.y = area.y; carea.width = area.width; carea.height = area.height; mClipStack.push(carea); return true; } ClipRectangle top = mClipStack.top(); ClipRectangle carea; carea = area; carea.xOffset = top.xOffset + carea.x; carea.yOffset = top.yOffset + carea.y; carea.x += top.xOffset; carea.y += top.yOffset; bool result = carea.intersect(top); mClipStack.push(carea); return result; } // end pushClipArea void Graphics::popClipArea() { if (mClipStack.empty()) { throw GCN_EXCEPTION("Graphics::popClipArea. Tried to pop clip area from empty stack."); } mClipStack.pop(); } // end popClipArea void Graphics::drawImage(const Image* image, int dstX, int dstY) { drawImage(image, 0, 0, dstX, dstY, image->getWidth(), image->getHeight()); } // end drawImage void Graphics::setFont(Font* font) { mFont = font; } // end setFont void Graphics::drawText(const std::string& text, int x, int y) { if (mFont == NULL) { throw GCN_EXCEPTION("Graphics::drawText. No font set."); } mFont->drawString(this, text, x, y); } // end drawText void Graphics::drawTextCenter(const std::string& text, int x, int y) { if (mFont == NULL) { throw GCN_EXCEPTION("Graphics::drawTextCenter. No font set."); } int width = mFont->getWidth(text); mFont->drawString(this, text, x - width / 2, y); } void Graphics::drawTextRight(const std::string& text, int x, int y) { if (mFont == NULL) { throw GCN_EXCEPTION("Graphics::drawTextRight. No font set."); } int width = mFont->getWidth(text); mFont->drawString(this, text, x - width, y); } } // end gcn <commit_msg>Added getColor and merged drawText, drawTextCenter and drawTextLeft into one function drawText which also takes an alignment parameter.<commit_after>/* _______ __ __ __ ______ __ __ _______ __ __ * / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\ * / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / / * / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / / * / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / / * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ / * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/ * * Copyright (c) 2004 darkbits Js_./ * Per Larsson a.k.a finalman _RqZ{a<^_aa * Olof Naessn a.k.a jansem/yakslem _asww7!uY`> )\a// * _Qhm`] _f "'c 1!5m * Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[ * .)j(] .d_/ '-( P . S * License: (BSD) <Td/Z <fP"5(\"??"\a. .L * Redistribution and use in source and _dV>ws?a-?' ._/L #' * binary forms, with or without )4d[#7r, . ' )d`)[ * modification, are permitted provided _Q-5'5W..j/?' -?!\)cam' * that the following conditions are met: j<<WP+k/);. _W=j f * 1. Redistributions of source code must .$%w\/]Q . ."' . mj$ * retain the above copyright notice, ]E.pYY(Q]>. a J@\ * this list of conditions and the j(]1u<sE"L,. . ./^ ]{a * following disclaimer. 4'_uomm\. )L);-4 (3= * 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[ * reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m * this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/ * following disclaimer in the <B!</]C)d_, '(<' .f. =C+m * documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]' * provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W" * 3. Neither the name of Guichan nor the :$we` _! + _/ . j? * names of its contributors may be used =3)= _f (_yQmWW$#( " * to endorse or promote products derived - W, sQQQQmZQ#Wwa].. * from this software without specific (js, \[QQW$QWW#?!V"". * prior written permission. ]y:.<\.. . * -]n w/ ' [. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ ! * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , ' * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- % * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r * MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'., * EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?" * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. . * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _, * 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. */ /* * For comments regarding functions please see the header file. */ #include "guichan/graphics.hpp" #include "guichan/exception.hpp" #include "guichan/font.hpp" namespace gcn { Graphics::Graphics() { mFont = NULL; } // end graphics bool Graphics::pushClipArea(Rectangle area) { if (mClipStack.empty()) { ClipRectangle carea; carea.x = area.x; carea.y = area.y; carea.width = area.width; carea.height = area.height; mClipStack.push(carea); return true; } ClipRectangle top = mClipStack.top(); ClipRectangle carea; carea = area; carea.xOffset = top.xOffset + carea.x; carea.yOffset = top.yOffset + carea.y; carea.x += top.xOffset; carea.y += top.yOffset; bool result = carea.intersect(top); mClipStack.push(carea); return result; } // end pushClipArea void Graphics::popClipArea() { if (mClipStack.empty()) { throw GCN_EXCEPTION("Graphics::popClipArea. Tried to pop clip area from empty stack."); } mClipStack.pop(); } // end popClipArea void Graphics::drawImage(const Image* image, int dstX, int dstY) { drawImage(image, 0, 0, dstX, dstY, image->getWidth(), image->getHeight()); } // end drawImage void Graphics::setFont(Font* font) { mFont = font; } // end setFont void Graphics::drawText(const std::string& text, int x, int y, unsigned int alignment) { if (mFont == NULL) { throw GCN_EXCEPTION("Graphics::drawText. No font set."); } switch (alignment) { case LEFT: mFont->drawString(this, text, x, y); break; case CENTER: mFont->drawString(this, text, x - mFont->getWidth(text) / 2, y); break; case RIGHT: mFont->drawString(this, text, x - mFont->getWidth(text), y); break; default: throw GCN_EXCEPTION("Graphics::drawText. Unknown alignment."); } } // end drawText } // end gcn <|endoftext|>
<commit_before>// // Created by mistlight on 1/28/2017. // #include <src/core/tasks/PlayerScanTask.h> #include <QDebug> #include <include/vlc/vlc.h> #include <src/simple-lib/ThreadPool.h> #include <QThread> #include "ScanPlayer.h" Core::ScanPlayer::ScanPlayer() { /* Load the VLC engine */ this->inst = libvlc_new(0, NULL); if(this->inst == NULL) { qWarning() << "ERROR"; throw "Exception has occured, cannot init vlc engine from Scanning"; } this->mediaPlayer = libvlc_media_player_new(this->inst); if(this->mediaPlayer == NULL) { qWarning() << "ERROR: Could not create media player in Scanning"; } this->threadPool = std::unique_ptr<ThreadPool>(new ThreadPool(1)); this->hasScanFinished = true; } void Core::ScanPlayer::addAudiobook(std::shared_ptr<AudiobookProxy> audiobook) { qDebug() << "Scan audiobook called"; auto fileList = audiobook->getFilesForAudiobook(); this->mutex.lock(); for(int i = 0; i < fileList.size(); i++) { this->fileQueue.push(fileList[i]); } this->mutex.unlock(); this->startScanTask(audiobook); } void Core::ScanPlayer::addAudiobookFile(std::shared_ptr<AudiobookFileProxy> file) { // don't need to call this function on already scanned items if(file->getMediaDuration() > 0) { return; } this->mutex.lock(); this->fileQueue.push(file); this->mutex.unlock(); this->startScanTask(nullptr); } void Core::ScanPlayer::startScanTask(std::shared_ptr<AudiobookProxy> audiobook) { auto scanTask = new PlayerScanTask(this, audiobook); this->scanThread.start(scanTask); } void Core::ScanPlayer::performScan() { this->mutex.lock(); qDebug() << "Scan task started"; while(!this->fileQueue.empty()) { this->hasScanFinished = false; std::shared_ptr<AudiobookFileProxy> & element = this->fileQueue.front(); this->currentlyScanning = element; qDebug() << "Currently scanning file: " << element->path(); auto path = element->path(); auto currentFile = std::unique_ptr<QFile>(new QFile(path)); if(!currentFile->open(QIODevice::ReadWrite)) { qDebug() << "QFILE FAILED!: " << path; return; } this->mediaItem = libvlc_media_new_fd(this->inst, currentFile->handle()); if(this->mediaItem == NULL) { return; } libvlc_media_player_set_media(this->mediaPlayer, this->mediaItem); libvlc_media_player_play(this->mediaPlayer); libvlc_event_manager_t* eventManager = libvlc_media_event_manager(this->mediaItem); libvlc_event_attach(eventManager, libvlc_MediaParsedChanged, (libvlc_callback_t) [](const struct libvlc_event_t * event, void *data) { auto player = reinterpret_cast<ScanPlayer*>(data); int parsedStatus = libvlc_media_is_parsed(player->mediaItem); if(parsedStatus) { player->threadPool->enqueue([player]() { long long duration = libvlc_media_get_duration(player->mediaItem); if(duration > 0) { player->currentlyScanning->setMediaDuration(duration); qDebug() << "performScan() SUCCESS: " << player->currentlyScanning->path(); } else { qWarning() << "performScan() failed for: " << player->currentlyScanning->path(); } player->hasScanFinished = true; }); } }, this); while(!hasScanFinished) { QThread::msleep(10); } libvlc_media_player_stop(this->mediaPlayer); this->fileQueue.pop(); } this->mutex.unlock(); qDebug() << "Scan task ended"; } void Core::ScanPlayer::retrieveScanResults() { } <commit_msg>remove debugging messages<commit_after>// // Created by mistlight on 1/28/2017. // #include <src/core/tasks/PlayerScanTask.h> #include <QDebug> #include <include/vlc/vlc.h> #include <src/simple-lib/ThreadPool.h> #include <QThread> #include "ScanPlayer.h" Core::ScanPlayer::ScanPlayer() { /* Load the VLC engine */ this->inst = libvlc_new(0, NULL); if(this->inst == NULL) { qWarning() << "ERROR"; throw "Exception has occured, cannot init vlc engine from Scanning"; } this->mediaPlayer = libvlc_media_player_new(this->inst); if(this->mediaPlayer == NULL) { qWarning() << "ERROR: Could not create media player in Scanning"; } this->threadPool = std::unique_ptr<ThreadPool>(new ThreadPool(1)); this->hasScanFinished = true; } void Core::ScanPlayer::addAudiobook(std::shared_ptr<AudiobookProxy> audiobook) { auto fileList = audiobook->getFilesForAudiobook(); this->mutex.lock(); for(int i = 0; i < fileList.size(); i++) { this->fileQueue.push(fileList[i]); } this->mutex.unlock(); this->startScanTask(audiobook); } void Core::ScanPlayer::addAudiobookFile(std::shared_ptr<AudiobookFileProxy> file) { // don't need to call this function on already scanned items if(file->getMediaDuration() > 0) { return; } this->mutex.lock(); this->fileQueue.push(file); this->mutex.unlock(); this->startScanTask(nullptr); } void Core::ScanPlayer::startScanTask(std::shared_ptr<AudiobookProxy> audiobook) { auto scanTask = new PlayerScanTask(this, audiobook); this->scanThread.start(scanTask); } void Core::ScanPlayer::performScan() { this->mutex.lock(); qDebug() << "Scan task started"; while(!this->fileQueue.empty()) { this->hasScanFinished = false; std::shared_ptr<AudiobookFileProxy> & element = this->fileQueue.front(); this->currentlyScanning = element; auto path = element->path(); auto currentFile = std::unique_ptr<QFile>(new QFile(path)); if(!currentFile->open(QIODevice::ReadWrite)) { qDebug() << "QFILE FAILED!: " << path; return; } this->mediaItem = libvlc_media_new_fd(this->inst, currentFile->handle()); if(this->mediaItem == NULL) { return; } libvlc_media_player_set_media(this->mediaPlayer, this->mediaItem); libvlc_media_player_play(this->mediaPlayer); libvlc_event_manager_t* eventManager = libvlc_media_event_manager(this->mediaItem); libvlc_event_attach(eventManager, libvlc_MediaParsedChanged, (libvlc_callback_t) [](const struct libvlc_event_t * event, void *data) { auto player = reinterpret_cast<ScanPlayer*>(data); int parsedStatus = libvlc_media_is_parsed(player->mediaItem); if(parsedStatus) { player->threadPool->enqueue([player]() { long long duration = libvlc_media_get_duration(player->mediaItem); if(duration > 0) { player->currentlyScanning->setMediaDuration(duration); } else { qWarning() << "performScan() failed for: " << player->currentlyScanning->path(); } player->hasScanFinished = true; }); } }, this); while(!hasScanFinished) { QThread::msleep(10); } libvlc_media_player_stop(this->mediaPlayer); this->fileQueue.pop(); } this->mutex.unlock(); qDebug() << "Scan task ended"; } void Core::ScanPlayer::retrieveScanResults() { } <|endoftext|>
<commit_before>/* This file is part of Ingen. Copyright 2007-2015 David Robillard <http://drobilla.net/> Ingen is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. Ingen 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 Affero General Public License for details. You should have received a copy of the GNU Affero General Public License along with Ingen. If not, see <http://www.gnu.org/licenses/>. */ #include "ingen/Forge.hpp" #include "ingen/Log.hpp" #include "ingen/Properties.hpp" #include "ingen/URIs.hpp" #include "ingen/World.hpp" #include "ingen/client/ObjectModel.hpp" #include "lilv/lilv.h" #include "RDFS.hpp" #include <utility> namespace ingen { namespace gui { namespace rdfs { std::string label(World& world, const LilvNode* node) { LilvNode* rdfs_label = lilv_new_uri( world.lilv_world(), LILV_NS_RDFS "label"); LilvNodes* labels = lilv_world_find_nodes( world.lilv_world(), node, rdfs_label, nullptr); const LilvNode* first = lilv_nodes_get_first(labels); std::string label = first ? lilv_node_as_string(first) : ""; lilv_nodes_free(labels); lilv_node_free(rdfs_label); return label; } std::string comment(World& world, const LilvNode* node) { LilvNode* rdfs_comment = lilv_new_uri( world.lilv_world(), LILV_NS_RDFS "comment"); LilvNodes* comments = lilv_world_find_nodes( world.lilv_world(), node, rdfs_comment, nullptr); const LilvNode* first = lilv_nodes_get_first(comments); std::string comment = first ? lilv_node_as_string(first) : ""; lilv_nodes_free(comments); lilv_node_free(rdfs_comment); return comment; } static void closure(World& world, const LilvNode* pred, URISet& types, bool super) { unsigned added = 0; do { added = 0; URISet klasses; for (const auto& t : types) { LilvNode* type = lilv_new_uri(world.lilv_world(), t.c_str()); LilvNodes* matches = (super) ? lilv_world_find_nodes( world.lilv_world(), type, pred, nullptr) : lilv_world_find_nodes( world.lilv_world(), nullptr, pred, type); LILV_FOREACH(nodes, m, matches) { const LilvNode* klass_node = lilv_nodes_get(matches, m); if (lilv_node_is_uri(klass_node)) { URI klass(lilv_node_as_uri(klass_node)); if (!types.count(klass)) { ++added; klasses.insert(klass); } } } lilv_nodes_free(matches); lilv_node_free(type); } types.insert(klasses.begin(), klasses.end()); } while (added > 0); } void classes(World& world, URISet& types, bool super) { LilvNode* rdfs_subClassOf = lilv_new_uri( world.lilv_world(), LILV_NS_RDFS "subClassOf"); closure(world, rdfs_subClassOf, types, super); lilv_node_free(rdfs_subClassOf); } void datatypes(World& world, URISet& types, bool super) { LilvNode* owl_onDatatype = lilv_new_uri( world.lilv_world(), LILV_NS_OWL "onDatatype"); closure(world, owl_onDatatype, types, super); lilv_node_free(owl_onDatatype); } URISet types(World& world, const std::shared_ptr<const client::ObjectModel>& model) { using PropIter = Properties::const_iterator; using PropRange = std::pair<PropIter, PropIter>; // Start with every rdf:type URISet types; types.insert(URI(LILV_NS_RDFS "Resource")); PropRange range = model->properties().equal_range(world.uris().rdf_type); for (auto t = range.first; t != range.second; ++t) { if (t->second.type() == world.forge().URI || t->second.type() == world.forge().URID) { const URI type(world.forge().str(t->second, false)); types.insert(type); if (world.uris().ingen_Graph == type) { // Add lv2:Plugin as a type for graphs so plugin properties show up types.insert(world.uris().lv2_Plugin); } } else { world.log().error("<%1%> has non-URI type\n", model->uri()); } } // Add every superclass of every type, recursively rdfs::classes(world, types, true); return types; } URISet properties(World& world, const std::shared_ptr<const client::ObjectModel>& model) { URISet properties; URISet types = rdfs::types(world, model); LilvNode* rdf_type = lilv_new_uri(world.lilv_world(), LILV_NS_RDF "type"); LilvNode* rdf_Property = lilv_new_uri(world.lilv_world(), LILV_NS_RDF "Property"); LilvNode* rdfs_domain = lilv_new_uri(world.lilv_world(), LILV_NS_RDFS "domain"); LilvNodes* props = lilv_world_find_nodes( world.lilv_world(), nullptr, rdf_type, rdf_Property); LILV_FOREACH(nodes, p, props) { const LilvNode* prop = lilv_nodes_get(props, p); if (lilv_node_is_uri(prop)) { LilvNodes* domains = lilv_world_find_nodes( world.lilv_world(), prop, rdfs_domain, nullptr); unsigned n_matching_domains = 0; LILV_FOREACH(nodes, d, domains) { const LilvNode* domain_node = lilv_nodes_get(domains, d); if (!lilv_node_is_uri(domain_node)) { // TODO: Blank node domains (e.g. unions) continue; } const URI domain(lilv_node_as_uri(domain_node)); if (types.count(domain)) { ++n_matching_domains; } } if (lilv_nodes_size(domains) == 0 || ( n_matching_domains > 0 && n_matching_domains == lilv_nodes_size(domains))) { properties.insert(URI(lilv_node_as_uri(prop))); } lilv_nodes_free(domains); } } lilv_node_free(rdfs_domain); lilv_node_free(rdf_Property); lilv_node_free(rdf_type); return properties; } Objects instances(World& world, const URISet& types) { LilvNode* rdf_type = lilv_new_uri( world.lilv_world(), LILV_NS_RDF "type"); Objects result; for (const auto& t : types) { LilvNode* type = lilv_new_uri(world.lilv_world(), t.c_str()); LilvNodes* objects = lilv_world_find_nodes( world.lilv_world(), nullptr, rdf_type, type); LILV_FOREACH(nodes, o, objects) { const LilvNode* object = lilv_nodes_get(objects, o); if (!lilv_node_is_uri(object)) { continue; } const std::string label = rdfs::label(world, object); result.emplace(label, URI(lilv_node_as_string(object))); } lilv_node_free(type); } lilv_node_free(rdf_type); return result; } URISet range(World& world, const LilvNode* prop, bool recursive) { LilvNode* rdfs_range = lilv_new_uri( world.lilv_world(), LILV_NS_RDFS "range"); LilvNodes* nodes = lilv_world_find_nodes( world.lilv_world(), prop, rdfs_range, nullptr); URISet ranges; LILV_FOREACH(nodes, n, nodes) { ranges.insert(URI(lilv_node_as_string(lilv_nodes_get(nodes, n)))); } if (recursive) { rdfs::classes(world, ranges, false); } lilv_nodes_free(nodes); lilv_node_free(rdfs_range); return ranges; } bool is_a(World& world, const LilvNode* inst, const LilvNode* klass) { LilvNode* rdf_type = lilv_new_uri(world.lilv_world(), LILV_NS_RDF "type"); const bool is_instance = lilv_world_ask( world.lilv_world(), inst, rdf_type, klass); lilv_node_free(rdf_type); return is_instance; } } // namespace rdfs } // namespace gui } // namespace ingen <commit_msg>Fix invalid URI mapping when a property range is a blank node<commit_after>/* This file is part of Ingen. Copyright 2007-2015 David Robillard <http://drobilla.net/> Ingen is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. Ingen 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 Affero General Public License for details. You should have received a copy of the GNU Affero General Public License along with Ingen. If not, see <http://www.gnu.org/licenses/>. */ #include "ingen/Forge.hpp" #include "ingen/Log.hpp" #include "ingen/Properties.hpp" #include "ingen/URIs.hpp" #include "ingen/World.hpp" #include "ingen/client/ObjectModel.hpp" #include "lilv/lilv.h" #include "RDFS.hpp" #include <utility> namespace ingen { namespace gui { namespace rdfs { std::string label(World& world, const LilvNode* node) { LilvNode* rdfs_label = lilv_new_uri( world.lilv_world(), LILV_NS_RDFS "label"); LilvNodes* labels = lilv_world_find_nodes( world.lilv_world(), node, rdfs_label, nullptr); const LilvNode* first = lilv_nodes_get_first(labels); std::string label = first ? lilv_node_as_string(first) : ""; lilv_nodes_free(labels); lilv_node_free(rdfs_label); return label; } std::string comment(World& world, const LilvNode* node) { LilvNode* rdfs_comment = lilv_new_uri( world.lilv_world(), LILV_NS_RDFS "comment"); LilvNodes* comments = lilv_world_find_nodes( world.lilv_world(), node, rdfs_comment, nullptr); const LilvNode* first = lilv_nodes_get_first(comments); std::string comment = first ? lilv_node_as_string(first) : ""; lilv_nodes_free(comments); lilv_node_free(rdfs_comment); return comment; } static void closure(World& world, const LilvNode* pred, URISet& types, bool super) { unsigned added = 0; do { added = 0; URISet klasses; for (const auto& t : types) { LilvNode* type = lilv_new_uri(world.lilv_world(), t.c_str()); LilvNodes* matches = (super) ? lilv_world_find_nodes( world.lilv_world(), type, pred, nullptr) : lilv_world_find_nodes( world.lilv_world(), nullptr, pred, type); LILV_FOREACH(nodes, m, matches) { const LilvNode* klass_node = lilv_nodes_get(matches, m); if (lilv_node_is_uri(klass_node)) { URI klass(lilv_node_as_uri(klass_node)); if (!types.count(klass)) { ++added; klasses.insert(klass); } } } lilv_nodes_free(matches); lilv_node_free(type); } types.insert(klasses.begin(), klasses.end()); } while (added > 0); } void classes(World& world, URISet& types, bool super) { LilvNode* rdfs_subClassOf = lilv_new_uri( world.lilv_world(), LILV_NS_RDFS "subClassOf"); closure(world, rdfs_subClassOf, types, super); lilv_node_free(rdfs_subClassOf); } void datatypes(World& world, URISet& types, bool super) { LilvNode* owl_onDatatype = lilv_new_uri( world.lilv_world(), LILV_NS_OWL "onDatatype"); closure(world, owl_onDatatype, types, super); lilv_node_free(owl_onDatatype); } URISet types(World& world, const std::shared_ptr<const client::ObjectModel>& model) { using PropIter = Properties::const_iterator; using PropRange = std::pair<PropIter, PropIter>; // Start with every rdf:type URISet types; types.insert(URI(LILV_NS_RDFS "Resource")); PropRange range = model->properties().equal_range(world.uris().rdf_type); for (auto t = range.first; t != range.second; ++t) { if (t->second.type() == world.forge().URI || t->second.type() == world.forge().URID) { const URI type(world.forge().str(t->second, false)); types.insert(type); if (world.uris().ingen_Graph == type) { // Add lv2:Plugin as a type for graphs so plugin properties show up types.insert(world.uris().lv2_Plugin); } } else { world.log().error("<%1%> has non-URI type\n", model->uri()); } } // Add every superclass of every type, recursively rdfs::classes(world, types, true); return types; } URISet properties(World& world, const std::shared_ptr<const client::ObjectModel>& model) { URISet properties; URISet types = rdfs::types(world, model); LilvNode* rdf_type = lilv_new_uri(world.lilv_world(), LILV_NS_RDF "type"); LilvNode* rdf_Property = lilv_new_uri(world.lilv_world(), LILV_NS_RDF "Property"); LilvNode* rdfs_domain = lilv_new_uri(world.lilv_world(), LILV_NS_RDFS "domain"); LilvNodes* props = lilv_world_find_nodes( world.lilv_world(), nullptr, rdf_type, rdf_Property); LILV_FOREACH(nodes, p, props) { const LilvNode* prop = lilv_nodes_get(props, p); if (lilv_node_is_uri(prop)) { LilvNodes* domains = lilv_world_find_nodes( world.lilv_world(), prop, rdfs_domain, nullptr); unsigned n_matching_domains = 0; LILV_FOREACH(nodes, d, domains) { const LilvNode* domain_node = lilv_nodes_get(domains, d); if (!lilv_node_is_uri(domain_node)) { // TODO: Blank node domains (e.g. unions) continue; } const URI domain(lilv_node_as_uri(domain_node)); if (types.count(domain)) { ++n_matching_domains; } } if (lilv_nodes_size(domains) == 0 || ( n_matching_domains > 0 && n_matching_domains == lilv_nodes_size(domains))) { properties.insert(URI(lilv_node_as_uri(prop))); } lilv_nodes_free(domains); } } lilv_node_free(rdfs_domain); lilv_node_free(rdf_Property); lilv_node_free(rdf_type); return properties; } Objects instances(World& world, const URISet& types) { LilvNode* rdf_type = lilv_new_uri( world.lilv_world(), LILV_NS_RDF "type"); Objects result; for (const auto& t : types) { LilvNode* type = lilv_new_uri(world.lilv_world(), t.c_str()); LilvNodes* objects = lilv_world_find_nodes( world.lilv_world(), nullptr, rdf_type, type); LILV_FOREACH(nodes, o, objects) { const LilvNode* object = lilv_nodes_get(objects, o); if (!lilv_node_is_uri(object)) { continue; } const std::string label = rdfs::label(world, object); result.emplace(label, URI(lilv_node_as_string(object))); } lilv_node_free(type); } lilv_node_free(rdf_type); return result; } URISet range(World& world, const LilvNode* prop, bool recursive) { LilvNode* rdfs_range = lilv_new_uri( world.lilv_world(), LILV_NS_RDFS "range"); LilvNodes* nodes = lilv_world_find_nodes( world.lilv_world(), prop, rdfs_range, nullptr); URISet ranges; LILV_FOREACH(nodes, n, nodes) { if (lilv_node_is_uri(lilv_nodes_get(nodes, n))) { ranges.insert(URI(lilv_node_as_string(lilv_nodes_get(nodes, n)))); } } if (recursive) { rdfs::classes(world, ranges, false); } lilv_nodes_free(nodes); lilv_node_free(rdfs_range); return ranges; } bool is_a(World& world, const LilvNode* inst, const LilvNode* klass) { LilvNode* rdf_type = lilv_new_uri(world.lilv_world(), LILV_NS_RDF "type"); const bool is_instance = lilv_world_ask( world.lilv_world(), inst, rdf_type, klass); lilv_node_free(rdf_type); return is_instance; } } // namespace rdfs } // namespace gui } // namespace ingen <|endoftext|>
<commit_before>#include "histogram.h" #include <algorithm> #include <limits> #include <cstdlib> #include <cmath> #include <iostream> #include <glog/logging.h> Histogram::Histogram(unsigned int num_bins): max_num_bins_(num_bins), dirty_(true), cumsums_(num_bins+1) { }; void Histogram::Update(double x, double y) { BinVal val; val.m = 1; val.y = y; Bin bin; bin.p = x; bin.val = val; HistogramTypeIter insert_location = std::lower_bound(bins_.begin(), bins_.end(), bin); if (insert_location != bins_.end() && insert_location->p == x) { insert_location->val.m += 1; insert_location->val.y += y; } else { bins_.insert(insert_location, bin); Trim(); } dirty_ = true; CHECK(bins_.size() > 0) << "Bin size is 0 after Update"; }; void Histogram::Merge(const Histogram& other) { for (unsigned int i = 0; i < other.bins_.size(); ++i) { bins_.push_back(other.bins_[i]); } std::sort(bins_.begin(), bins_.end()); Trim(); dirty_ = true; }; // Compute the additional offset to be added to the accumulated sum double trapezoid_estimate(double s, double p1, double p2, double v1, double v2) { // Bottom base w.r.t trepezoid truncated at s // TODO: Remove max() if not handling boundary cases here double vs = v1 + (v2 - v1) * std::max((s - p1), 0.0) / (p2 - p1); double as = (v1 + vs) * std::max((s - p1), 0.0) / 2; double a2 = (v1 + v2) * (p2 - p1) / 2; double R = (v1 + v2) / 2; //LOG(INFO) << "as : a2: -->" << as << " vs " <<a2; double res = (as / a2) * R; return res; }; Histogram::BinVal Histogram::Interpolate(double x) const { // TODO: assert the x in between p_min and p_max // TODO: For completeness sake, need to handle -ve and +ve infinity, as it2 // below might hit the boundaries Bin bin; bin.p = x; HistogramTypeConstIter it2 = std::upper_bound(bins_.begin(), bins_.end(), bin); HistogramTypeConstIter it1 = it2 - 1; //LOG(INFO) << "it2 index: " << it2 - bins_.begin() << "; is end: " << (it2 == bins_.end())?1:0; //LOG(INFO) << "bins_ max: " << it2 - bins_.begin(); double m_summed = 0.0; double y_summed = 0.0; /* for (HistogramTypeConstIter it = bins_.begin(); it != it2; ++it) { if (it != it1) { m_summed += it->val.m; y_summed += it->val.y; } else{ m_summed += it->val.m / 2.0; y_summed += it->val.y / 2.0; } } */ PrecomputeCumsums(); if (it2 != bins_.begin()) { unsigned int index_upto = it2 - bins_.begin() - 1; m_summed = cumsums_[index_upto].m; y_summed = cumsums_[index_upto].y; } double m_offset, y_offset; // Take care of two critical bin locations: first and last if (it2 == bins_.begin()) { //LOG(INFO) << "Handling special case of neg_inf!"; double p_neg_inf = bins_[0].p - (bins_[1].p - bins_[0].p); //LOG(INFO) << "p_0: " << it2->p << " m_0: " << it2->val.m; if (x < p_neg_inf) { m_offset = 0; y_offset = 0; } else { m_offset = trapezoid_estimate(x, p_neg_inf, it2->p, 0.0, it2->val.m); y_offset = trapezoid_estimate(x, p_neg_inf, it2->p, 0.0, it2->val.y); } //LOG(INFO) << "p_neg_inf: " << p_neg_inf << " offsets: " << m_offset << " " << y_offset; } else if (it2 == bins_.end()) { //LOG(INFO) << "Handling special case of pos_inf!"; double p_pos_inf = bins_[bins_.size()-1].p + (bins_[bins_.size()-1].p - bins_[bins_.size()-2].p); if (x > p_pos_inf) { m_offset = it2->val.m / 2; y_offset = it2->val.y / 2; } else{ m_offset = trapezoid_estimate(x, it2->p, p_pos_inf, it1->val.m, 0.0); y_offset = trapezoid_estimate(x, it2->p, p_pos_inf, it1->val.y, 0.0); } //LOG(INFO) << "p_pos_inf: " << p_pos_inf << " offsets: " << m_offset << " " << y_offset; } else { m_offset = trapezoid_estimate(x, it1->p, it2->p, it1->val.m, it2->val.m); y_offset = trapezoid_estimate(x, it1->p, it2->p, it1->val.y, it2->val.y); } BinVal val; val.m = m_summed + m_offset; val.y = y_summed + y_offset; return val; }; Histogram::BinVal Histogram::InterpolateInf() const { /* double m_summed = 0.0; double y_summed = 0.0; for (HistogramTypeConstIter it = bins_.begin(); it != bins_.end(); ++it) { m_summed += it->val.m; y_summed += it->val.y; } BinVal val; val.m = m_summed; val.y = y_summed; return val; */ PrecomputeCumsums(); const BinVal& binval = cumsums_[bins_.size()]; return binval; }; void Histogram::Trim() { while (bins_.size() > max_num_bins_) { // TODO: Handle ties in minimum distance double min_dist = std::numeric_limits<double>::max(); unsigned int combine_location = 0; for (unsigned int i = 0; i < bins_.size() - 1; ++i) { double dist = std::fabs(bins_[i].p - bins_[i+1].p); if (dist < min_dist) { min_dist = dist; combine_location = i; } } //std::cout << "combine_location: " << combine_location << std::endl; //std::cout << "min_dist: " << min_dist << std::endl; int i = combine_location; int j = combine_location + 1; bins_[i].p = ((bins_[i].p * bins_[i].val.m) + (bins_[j].p * bins_[j].val.m)) / (bins_[i].val.m + bins_[j].val.m); bins_[i].val.m += bins_[j].val.m; bins_[i].val.y += bins_[j].val.y; bins_.erase(bins_.begin() + j); } }; // Implements Algorithm 4 in Ben-Haim-10 paper std::vector<double> Histogram::Uniform(int N) const { // N corresponds to tilde B in the paper CHECK(N >= 1) << "Histogram's Uniform routine requires N >= 1"; //CHECK(bins_.size() >= 2) << "Histogrom does not have enough bins"; std::vector<double> results; double sum_m = 0.0; for (unsigned int i = 0; i < bins_.size(); ++i) { sum_m += bins_[i].val.m; } std::vector<double> cumsums(bins_.size(), 0.0); for (unsigned int i = 0; i < bins_.size(); ++i) { // Special case of Sum / Interpolate where the target x is always at the // center of a bin -- can be computed inplace directly if (i == 0) { cumsums[i] = bins_[i].val.m / 2.0; } else { cumsums[i] = cumsums[i-1] + bins_[i-1].val.m / 2.0 + bins_[i].val.m / 2.0; } } for (int j = 1; j <= N - 1; ++j) { double s = ((double)j / N) * sum_m; // This is (i+1) -- the first element that is larger than s std::vector<double>::iterator it = std::upper_bound(cumsums.begin(), cumsums.end(), s); if (it == cumsums.begin()) { continue; } unsigned int i = it - cumsums.begin() - 1; double d = s - cumsums[i]; double a = bins_[i+1].val.m - bins_[i].val.m; double z; if (std::fabs(a) > 10e-8) { double b = 2.0 * bins_[i].val.m; double c = -2.0 * d; z = (- b + sqrt(b*b - 4*a*c)) / (2*a); } else { z = d / bins_[i].val.m; } double uj = bins_[i].p + (bins_[i+1].p - bins_[i].p)*z; results.push_back(uj); } return results; }; void Histogram::PrecomputeCumsums() const { // Pre-compute the cummulative sums // cumsums_[i] means summations up to 1//2 of the i-th bin. // Only recompute when necessary if (!dirty_) { return; } for (unsigned int i = 0; i < bins_.size(); ++i) { if (i == 0) { cumsums_[i].m = bins_[i].val.m / 2.0; cumsums_[i].y = bins_[i].val.y / 2.0; } else { cumsums_[i].m = cumsums_[i-1].m + bins_[i-1].val.m / 2.0 + bins_[i].val.m / 2.0; cumsums_[i].y = cumsums_[i-1].y + bins_[i-1].val.y / 2.0 + bins_[i].val.y / 2.0; } } // Sums at +ve infinity (i.e. sum up all) unsigned int index_inf = bins_.size(); cumsums_[index_inf].m = cumsums_[index_inf-1].m + bins_.back().val.m/2.0; cumsums_[index_inf].y = cumsums_[index_inf-1].y + bins_.back().val.y/2.0; dirty_ = false; }; <commit_msg>Use caching in Uniform procedure<commit_after>#include "histogram.h" #include <algorithm> #include <limits> #include <cstdlib> #include <cmath> #include <iostream> #include <glog/logging.h> Histogram::Histogram(unsigned int num_bins): max_num_bins_(num_bins), dirty_(true), cumsums_(num_bins+1) { }; void Histogram::Update(double x, double y) { BinVal val; val.m = 1; val.y = y; Bin bin; bin.p = x; bin.val = val; HistogramTypeIter insert_location = std::lower_bound(bins_.begin(), bins_.end(), bin); if (insert_location != bins_.end() && insert_location->p == x) { insert_location->val.m += 1; insert_location->val.y += y; } else { bins_.insert(insert_location, bin); Trim(); } dirty_ = true; CHECK(bins_.size() > 0) << "Bin size is 0 after Update"; }; void Histogram::Merge(const Histogram& other) { for (unsigned int i = 0; i < other.bins_.size(); ++i) { bins_.push_back(other.bins_[i]); } std::sort(bins_.begin(), bins_.end()); Trim(); dirty_ = true; }; // Compute the additional offset to be added to the accumulated sum double trapezoid_estimate(double s, double p1, double p2, double v1, double v2) { // Bottom base w.r.t trepezoid truncated at s // TODO: Remove max() if not handling boundary cases here double vs = v1 + (v2 - v1) * std::max((s - p1), 0.0) / (p2 - p1); double as = (v1 + vs) * std::max((s - p1), 0.0) / 2; double a2 = (v1 + v2) * (p2 - p1) / 2; double R = (v1 + v2) / 2; //LOG(INFO) << "as : a2: -->" << as << " vs " <<a2; double res = (as / a2) * R; return res; }; Histogram::BinVal Histogram::Interpolate(double x) const { // TODO: assert the x in between p_min and p_max // TODO: For completeness sake, need to handle -ve and +ve infinity, as it2 // below might hit the boundaries Bin bin; bin.p = x; HistogramTypeConstIter it2 = std::upper_bound(bins_.begin(), bins_.end(), bin); HistogramTypeConstIter it1 = it2 - 1; //LOG(INFO) << "it2 index: " << it2 - bins_.begin() << "; is end: " << (it2 == bins_.end())?1:0; //LOG(INFO) << "bins_ max: " << it2 - bins_.begin(); double m_summed = 0.0; double y_summed = 0.0; /* for (HistogramTypeConstIter it = bins_.begin(); it != it2; ++it) { if (it != it1) { m_summed += it->val.m; y_summed += it->val.y; } else{ m_summed += it->val.m / 2.0; y_summed += it->val.y / 2.0; } } */ PrecomputeCumsums(); if (it2 != bins_.begin()) { unsigned int index_upto = it2 - bins_.begin() - 1; m_summed = cumsums_[index_upto].m; y_summed = cumsums_[index_upto].y; } double m_offset, y_offset; // Take care of two critical bin locations: first and last if (it2 == bins_.begin()) { //LOG(INFO) << "Handling special case of neg_inf!"; double p_neg_inf = bins_[0].p - (bins_[1].p - bins_[0].p); //LOG(INFO) << "p_0: " << it2->p << " m_0: " << it2->val.m; if (x < p_neg_inf) { m_offset = 0; y_offset = 0; } else { m_offset = trapezoid_estimate(x, p_neg_inf, it2->p, 0.0, it2->val.m); y_offset = trapezoid_estimate(x, p_neg_inf, it2->p, 0.0, it2->val.y); } //LOG(INFO) << "p_neg_inf: " << p_neg_inf << " offsets: " << m_offset << " " << y_offset; } else if (it2 == bins_.end()) { //LOG(INFO) << "Handling special case of pos_inf!"; double p_pos_inf = bins_[bins_.size()-1].p + (bins_[bins_.size()-1].p - bins_[bins_.size()-2].p); if (x > p_pos_inf) { m_offset = it2->val.m / 2; y_offset = it2->val.y / 2; } else{ m_offset = trapezoid_estimate(x, it2->p, p_pos_inf, it1->val.m, 0.0); y_offset = trapezoid_estimate(x, it2->p, p_pos_inf, it1->val.y, 0.0); } //LOG(INFO) << "p_pos_inf: " << p_pos_inf << " offsets: " << m_offset << " " << y_offset; } else { m_offset = trapezoid_estimate(x, it1->p, it2->p, it1->val.m, it2->val.m); y_offset = trapezoid_estimate(x, it1->p, it2->p, it1->val.y, it2->val.y); } BinVal val; val.m = m_summed + m_offset; val.y = y_summed + y_offset; return val; }; Histogram::BinVal Histogram::InterpolateInf() const { /* double m_summed = 0.0; double y_summed = 0.0; for (HistogramTypeConstIter it = bins_.begin(); it != bins_.end(); ++it) { m_summed += it->val.m; y_summed += it->val.y; } BinVal val; val.m = m_summed; val.y = y_summed; return val; */ PrecomputeCumsums(); const BinVal& binval = cumsums_[bins_.size()]; return binval; }; void Histogram::Trim() { while (bins_.size() > max_num_bins_) { // TODO: Handle ties in minimum distance double min_dist = std::numeric_limits<double>::max(); unsigned int combine_location = 0; for (unsigned int i = 0; i < bins_.size() - 1; ++i) { double dist = std::fabs(bins_[i].p - bins_[i+1].p); if (dist < min_dist) { min_dist = dist; combine_location = i; } } //std::cout << "combine_location: " << combine_location << std::endl; //std::cout << "min_dist: " << min_dist << std::endl; int i = combine_location; int j = combine_location + 1; bins_[i].p = ((bins_[i].p * bins_[i].val.m) + (bins_[j].p * bins_[j].val.m)) / (bins_[i].val.m + bins_[j].val.m); bins_[i].val.m += bins_[j].val.m; bins_[i].val.y += bins_[j].val.y; bins_.erase(bins_.begin() + j); } }; // Implements Algorithm 4 in Ben-Haim-10 paper std::vector<double> Histogram::Uniform(int N) const { // N corresponds to tilde B in the paper CHECK(N >= 1) << "Histogram's Uniform routine requires N >= 1"; //CHECK(bins_.size() >= 2) << "Histogrom does not have enough bins"; std::vector<double> results; /* double sum_m = 0.0; for (unsigned int i = 0; i < bins_.size(); ++i) { sum_m += bins_[i].val.m; } std::vector<double> cumsums(bins_.size(), 0.0); for (unsigned int i = 0; i < bins_.size(); ++i) { // Special case of Sum / Interpolate where the target x is always at the // center of a bin -- can be computed inplace directly if (i == 0) { cumsums[i] = bins_[i].val.m / 2.0; } else { cumsums[i] = cumsums[i-1] + bins_[i-1].val.m / 2.0 + bins_[i].val.m / 2.0; } } */ PrecomputeCumsums(); // Last of cumsums_ adds up all bins double sum_m = cumsums_.back().m; BinVal binval; for (int j = 1; j <= N - 1; ++j) { double s = ((double)j / N) * sum_m; // This is (i+1) -- the first element that is larger than s //std::vector<double>::iterator it = std::upper_bound(cumsums.begin(), //cumsums.end(), s); binval.m = s; std::vector<BinVal>::iterator it = std::upper_bound( cumsums_.begin(), cumsums_.end(), binval, [](const BinVal& a, const BinVal& b) -> bool { return a.m < b.m; }); if (it == cumsums_.begin()) { continue; } unsigned int i = it - cumsums_.begin() - 1; double d = s - cumsums_[i].m; double a = bins_[i+1].val.m - bins_[i].val.m; double z; if (std::fabs(a) > 10e-8) { double b = 2.0 * bins_[i].val.m; double c = -2.0 * d; z = (- b + sqrt(b*b - 4*a*c)) / (2*a); } else { z = d / bins_[i].val.m; } double uj = bins_[i].p + (bins_[i+1].p - bins_[i].p)*z; results.push_back(uj); } return results; }; void Histogram::PrecomputeCumsums() const { // Pre-compute the cummulative sums // cumsums_[i] means summations up to 1//2 of the i-th bin. // Only recompute when necessary if (!dirty_) { return; } for (unsigned int i = 0; i < bins_.size(); ++i) { if (i == 0) { cumsums_[i].m = bins_[i].val.m / 2.0; cumsums_[i].y = bins_[i].val.y / 2.0; } else { cumsums_[i].m = cumsums_[i-1].m + bins_[i-1].val.m / 2.0 + bins_[i].val.m / 2.0; cumsums_[i].y = cumsums_[i-1].y + bins_[i-1].val.y / 2.0 + bins_[i].val.y / 2.0; } } // Sums at +ve infinity (i.e. sum up all) unsigned int index_inf = bins_.size(); cumsums_[index_inf].m = cumsums_[index_inf-1].m + bins_.back().val.m/2.0; cumsums_[index_inf].y = cumsums_[index_inf-1].y + bins_.back().val.y/2.0; dirty_ = false; }; <|endoftext|>
<commit_before>#include "core/world/tile.h" #include "core/world/tile_descriptor.h" namespace eversim { namespace core { namespace world { tile_descriptor blank_tile = { "blank" }; bool tile::point_inside(glm::vec2 p) const { auto center = position(); auto min = center - glm::vec2(size() / 2); auto max = center + glm::vec2(size() / 2); return p.x >= min.x && p.x < max.x && p.y >= min.y && p.y < max.y; } }}} <commit_msg>super hacky rendering implementation<commit_after>#include "core/world/tile.h" #include "core/world/tile_descriptor.h" #include "core/rendering/render_manager.h" // VERY hacky! extern eversim::core::rendering::ShaderProgram* default_shader; namespace eversim { namespace core { namespace world { tile_descriptor blank_tile = { "blank" }; bool tile::point_inside(glm::vec2 p) const { auto center = position(); auto min = center - glm::vec2(size() / 2); auto max = center + glm::vec2(size() / 2); return p.x >= min.x && p.x < max.x && p.y >= min.y && p.y < max.y; } void tile::initialize_graphics(rendering::render_manager& mng) { auto const& tex_name = descriptor->texture_name; if (tex_name.empty()) return; display = mng.register_entity(); auto M = display->get_M(); M[2] = glm::vec3(position() - glm::vec2(size()), 1); display->set_M(M); LOG(WARNING) << "Hacky solution for tile display!"; static std::map<std::string, rendering::Texture> textures; const auto it = textures.find(tex_name); if(it == textures.end()) { textures[tex_name] = rendering::Texture(tex_name); } display->set_Texture(textures[tex_name]); display->set_ShaderProgram(default_shader); } }}} <|endoftext|>
<commit_before>/* * Copyright (c) 2016 tildearrow * * 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. */ #ifdef _WIN32 #define FONT "C:\\Windows\\Fonts\\segoeui.ttf" #elif __APPLE__ #define FONT "/System/Library/Fonts/SFNSDisplay-Regular.otf" #elif __linux__ #define FONT "/usr/share/fonts/TTF/Ubuntu-R.ttf" #else #warning "really? please tell me if you are compiling on this OS" #endif #include "includes.h" #include "font.h" #include "ui.h" SDL_Window* mainWindow; SDL_Renderer* mainRenderer; SDL_Event* event; int mouseX; int mouseY; unsigned int mouseB; unsigned int mouseBold; SDL_Color color; bool willquit; uisystem* ui; font* mainFont; int curview; int cureditid, curedittype; const char* viewname[6]={"Graphics","Audio","Entity Types","Scenes","Functions"}; struct graphic { string name; int id; int width; int height; int originX, originY; int subgraphics; bool background; unsigned char** data; int colmode; unsigned char** colmask; }; struct audio { string name; int id; int size; float* data; int finaltype; }; struct etype { string name; int id; int initialgraphic; int initialsubgraphic; int parent; int category; std::vector<string> eventcode; string headercode; }; struct viewport { SDL_Rect view, port; float viewangle, portangle; }; struct scene { string name; int width; int height; bool freeze; std::vector<viewport> viewports; }; struct function { string name; string code; }; std::vector<graphic> graphics; std::vector<audio> sounds; std::vector<etype> etypes; std::vector<scene> scenes; void doNothing(){ printf("hello world!\n"); } void drawscreen() { SDL_RenderDrawLine(mainRenderer,0,32,1024,32); SDL_RenderDrawLine(mainRenderer,256,32,256,600); SDL_RenderDrawLine(mainRenderer,0,53,256,53); mainFont->drawf(128,41,color,1,1,"%s List",viewname[curview]); switch (curview) { case 0: for (int i=0; i<graphics.size(); i++) { mainFont->draw(0,64+(i*20),color,0,0,false,graphics[i].name); } break; case 1: for (int i=0; i<sounds.size(); i++) { mainFont->draw(0,64+(i*20),color,0,0,false,sounds[i].name); } break; case 2: for (int i=0; i<etypes.size(); i++) { mainFont->draw(0,64+(i*20),color,0,0,false,etypes[i].name); } break; } } void goGraphicsView() { curview=0; } void goAudioView() { curview=1; } void goETypesView() { curview=2; } void goScenesView() { curview=3; } void goFunctionsView() { curview=4; } void makeNewResource() { printf("ok, will be done\n"); // make new resource int formersize; switch (curview) { case 0: formersize=graphics.size(); graphics.resize(formersize+1); graphics[formersize].id=formersize; graphics[formersize].name="graphic"; graphics[formersize].name+=std::to_string(formersize); break; case 1: formersize=sounds.size(); sounds.resize(formersize+1); sounds[formersize].id=formersize; sounds[formersize].name="sound"; sounds[formersize].name+=std::to_string(formersize); break; case 2: formersize=etypes.size(); etypes.resize(formersize+1); etypes[formersize].id=formersize; etypes[formersize].name="type"; etypes[formersize].name+=std::to_string(formersize); break; } } int main() { willquit=false; // init everything SDL_Init(SDL_INIT_VIDEO); TTF_Init(); ui=new uisystem; event=new SDL_Event; string title; title="LowerTriad"; mainWindow=SDL_CreateWindow(title.c_str(),0,0,1024,600,SDL_WINDOW_RESIZABLE); if (!mainWindow) { printf("i'm sorry, but window can't be created: %s\n",SDL_GetError()); return 1; } mainRenderer=SDL_CreateRenderer(mainWindow,-1,SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC); // initialize UI mainFont=new font; mainFont->setrenderer(mainRenderer); if (!mainFont->load(FONT,14)) { printf("can't load font, which means this application is going to crash now...\n"); } ui->setrenderer(mainRenderer); color.r=0; color.g=255; color.b=0; color.a=255; ui->setfont(mainFont); ui->addbutton(0,0,48,22,"Prepare","Prepare CMake project",color,color,doNothing); ui->addbutton(48,0,40,22,"Build","Build game",color,color,doNothing); ui->addbutton(100,0,32,22,"Run","Run compiled game",color,color,doNothing); ui->addbutton(132,0,56,22,"Package","Create package",color,color,doNothing); ui->addbutton(200,0,64,22,"Graphics","",color,color,goGraphicsView); ui->addbutton(264,0,50,22,"Audio","",color,color,goAudioView); ui->addbutton(314,0,80,22,"EntityTypes","",color,color,goETypesView); ui->addbutton(394,0,50,22,"Scenes","",color,color,goScenesView); ui->addbutton(444,0,72,22,"Functions","",color,color,goFunctionsView); ui->addbutton(225,32,32,22,"Add","",color,color,makeNewResource); ui->setmouse(&mouseX,&mouseY,&mouseB,&mouseBold); // initialize IDE variables cureditid=-1; curedittype=0; curview=0; while (1) { // check events while (SDL_PollEvent(event)) { if (event->type==SDL_QUIT) { willquit=true; } } SDL_SetRenderDrawColor(mainRenderer,0,0,0,0); SDL_RenderClear(mainRenderer); mouseBold=mouseB; mouseB=SDL_GetMouseState(&mouseX, &mouseY); ui->drawall(); drawscreen(); SDL_RenderPresent(mainRenderer); if (willquit) { break; } } return 0; } <commit_msg>ui and code changes<commit_after>/* * Copyright (c) 2016 tildearrow * * 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. */ #ifdef _WIN32 #define FONT "C:\\Windows\\Fonts\\segoeui.ttf" #elif __APPLE__ #define FONT "/System/Library/Fonts/SFNSDisplay-Regular.otf" #elif __linux__ #define FONT "/usr/share/fonts/TTF/Ubuntu-R.ttf" #else #warning "really? please tell me if you are compiling on this OS" #endif #include "includes.h" #include "font.h" #include "ui.h" SDL_Window* mainWindow; SDL_Renderer* mainRenderer; SDL_Event* event; int mouseX; int mouseY; unsigned int mouseB; unsigned int mouseBold; SDL_Color color; bool willquit; uisystem* ui; font* mainFont; int curview; int cureditid, curedittype; const char* viewname[6]={"Graphics","Audio","Entity Types","Scenes","Functions"}; struct graphic { string name; int id; int width; int height; int originX, originY; int subgraphics; bool background; unsigned char** data; int colmode; unsigned char** colmask; }; struct audio { string name; int id; int size; float* data; int finaltype; }; struct etype { string name; int id; int initialgraphic; int initialsubgraphic; int parent; int category; std::vector<string> eventcode; string headercode; }; struct viewport { SDL_Rect view, port; float viewangle, portangle; }; struct scene { string name; int id; int width; int height; bool freeze; std::vector<viewport> viewports; }; struct function { string name; int id; string code; }; std::vector<graphic> graphics; std::vector<audio> sounds; std::vector<etype> etypes; std::vector<scene> scenes; std::vector<function> functions; void doNothing(){ printf("hello world!\n"); } void drawScreen() { SDL_RenderDrawLine(mainRenderer,0,32,1024,32); SDL_RenderDrawLine(mainRenderer,256,32,256,600); SDL_RenderDrawLine(mainRenderer,0,53,256,53); mainFont->drawf(128,41,color,1,1,"%s List",viewname[curview]); switch (curview) { case 0: for (int i=0; i<graphics.size(); i++) { mainFont->draw(0+((cureditid==i)?(16):(0)),64+(i*20),color,0,0,false,graphics[i].name); } break; case 1: for (int i=0; i<sounds.size(); i++) { mainFont->draw(0,64+(i*20),color,0,0,false,sounds[i].name); } break; case 2: for (int i=0; i<etypes.size(); i++) { mainFont->draw(0,64+(i*20),color,0,0,false,etypes[i].name); } break; case 3: for (int i=0; i<scenes.size(); i++) { mainFont->draw(0,64+(i*20),color,0,0,false,scenes[i].name); } break; case 4: for (int i=0; i<functions.size(); i++) { mainFont->draw(0,64+(i*20),color,0,0,false,functions[i].name); } break; } } void goGraphicsView() { curview=0; } void goAudioView() { curview=1; } void goETypesView() { curview=2; } void goScenesView() { curview=3; } void goFunctionsView() { curview=4; } void handleMouse() { if (mouseB&1) { if (mouseX<256 && mouseY>64) { cureditid=(mouseY-64)/20; } } } void makeNewResource() { // make new resource int formersize; switch (curview) { case 0: formersize=graphics.size(); graphics.resize(formersize+1); graphics[formersize].id=formersize; graphics[formersize].name="graphic"; graphics[formersize].name+=std::to_string(formersize); break; case 1: formersize=sounds.size(); sounds.resize(formersize+1); sounds[formersize].id=formersize; sounds[formersize].name="sound"; sounds[formersize].name+=std::to_string(formersize); break; case 2: formersize=etypes.size(); etypes.resize(formersize+1); etypes[formersize].id=formersize; etypes[formersize].name="type"; etypes[formersize].name+=std::to_string(formersize); break; case 3: formersize=scenes.size(); scenes.resize(formersize+1); scenes[formersize].id=formersize; scenes[formersize].name="scene"; scenes[formersize].name+=std::to_string(formersize); break; case 4: formersize=functions.size(); functions.resize(formersize+1); functions[formersize].id=formersize; functions[formersize].name="func"; functions[formersize].name+=std::to_string(formersize); break; } } int main() { willquit=false; // init everything SDL_Init(SDL_INIT_VIDEO); TTF_Init(); ui=new uisystem; event=new SDL_Event; string title; title="LowerTriad"; mainWindow=SDL_CreateWindow(title.c_str(),0,0,1024,600,SDL_WINDOW_RESIZABLE); if (!mainWindow) { printf("i'm sorry, but window can't be created: %s\n",SDL_GetError()); return 1; } mainRenderer=SDL_CreateRenderer(mainWindow,-1,SDL_RENDERER_ACCELERATED|SDL_RENDERER_PRESENTVSYNC); // initialize UI mainFont=new font; mainFont->setrenderer(mainRenderer); if (!mainFont->load(FONT,14)) { printf("can't load font, which means this application is going to crash now...\n"); } ui->setrenderer(mainRenderer); color.r=0; color.g=255; color.b=0; color.a=255; ui->setfont(mainFont); ui->addbutton(0,0,48,22,"Prepare","Prepare CMake project",color,color,doNothing); ui->addbutton(48,0,40,22,"Build","Build game",color,color,doNothing); ui->addbutton(100,0,32,22,"Run","Run compiled game",color,color,doNothing); ui->addbutton(132,0,56,22,"Package","Create package",color,color,doNothing); ui->addbutton(200,0,64,22,"Graphics","",color,color,goGraphicsView); ui->addbutton(264,0,50,22,"Audio","",color,color,goAudioView); ui->addbutton(314,0,80,22,"EntityTypes","",color,color,goETypesView); ui->addbutton(394,0,50,22,"Scenes","",color,color,goScenesView); ui->addbutton(444,0,72,22,"Functions","",color,color,goFunctionsView); ui->addbutton(225,32,32,22,"Add","",color,color,makeNewResource); ui->setmouse(&mouseX,&mouseY,&mouseB,&mouseBold); // initialize IDE variables cureditid=-1; curedittype=0; curview=0; while (1) { // check events while (SDL_PollEvent(event)) { if (event->type==SDL_QUIT) { willquit=true; } } SDL_SetRenderDrawColor(mainRenderer,0,0,0,0); SDL_RenderClear(mainRenderer); mouseBold=mouseB; mouseB=SDL_GetMouseState(&mouseX, &mouseY); handleMouse(); ui->drawall(); drawScreen(); SDL_RenderPresent(mainRenderer); if (willquit) { break; } } return 0; } <|endoftext|>
<commit_before>/* Copyright (C) <2010> <Frank Scheffold (fscheffold@googlemail.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. */ /** @author: Frank Scheffold */ #include "kremotecontroldaemon.h" #include "krcdadaptor.h" #include <kdelirc/libkremotecontrol/dbusinterface.h> #include <kdelirc/libkremotecontrol/mode.h> #include <kdelirc/libkremotecontrol/action.h> #include <kdelirc/libkremotecontrol/executionengine.h> #include <kdelirc/libkremotecontrol/remotelist.h> #include <KCModuleInfo> #include <KDebug> #include <KNotification> #include <KAboutData> #include <KIconLoader> #include <KToolInvocation> #include<QPixmap> // #include <QErrorMessage> using namespace Solid::Control; K_PLUGIN_FACTORY(KRemoteControlDaemonFactory, registerPlugin<KRemoteControlDaemon>();) K_EXPORT_PLUGIN(KRemoteControlDaemonFactory("kremotecontroldaemon")) class KRemoteControlDaemonPrivate { private: KRemoteControlDaemon *m_parent; RemoteList m_remoteList; QStringList m_ignoreNextButtonList; public: KComponentData applicationData; KRemoteControlDaemonPrivate(KRemoteControlDaemon *parent) { m_parent = parent; }; ~KRemoteControlDaemonPrivate() { }; RemoteList remoteList(){ return m_remoteList; }; void reload(){ m_remoteList.loadFromConfig("kremotecontrolrc"); KConfig config("kremotecontrolrc"); KConfigGroup globalGroup(&config, "Global"); if(globalGroup.readEntry("ShowTrayIcon", true)){ kDebug() << "starting notifier item" << KToolInvocation::kdeinitExec("krcdnotifieritem"); } else { emit m_parent->unloadTray(); } }; Remote* getRemote(const QString& remoteName) { return m_remoteList.getRemote(remoteName); }; bool isButtonEventIgnored(const QString &remote){ return m_ignoreNextButtonList.contains(remote); }; void ignoreButtonEvents(const QString& remote){ kDebug() << "muting remote" << remote; m_ignoreNextButtonList.append(remote); m_ignoreNextButtonList.removeDuplicates(); } void considerButtonEvents(const QString& remote){ kDebug() << "unmuting remote" << remote; m_ignoreNextButtonList.removeAll(remote); } void clearIgnore(){ m_remoteList.clear(); } }; KRemoteControlDaemon::KRemoteControlDaemon(QObject* parent, const QVariantList& ): KDEDModule(parent), d_ptr(new KRemoteControlDaemonPrivate(this)) { Q_D(KRemoteControlDaemon); // QErrorMessage::qtHandler () ; //qInstallMsgHandler(); new KrcdAdaptor(this); KAboutData aboutData("krcd", "krcd", ki18n("K Remote Control Daemon"), "0.1", ki18n("Remote Control Daemon for KDE4"), KAboutData::License_GPL, ki18n("(c) 2010 Frank Scheffold"), KLocalizedString(), "http://www.kde.org"); aboutData.addAuthor(ki18n("Michael Zanetti"), ki18n("Maintainer"), "michal_zanetti@gmx.net"); aboutData.addAuthor(ki18n("Frank Scheffold"), ki18n("Developer"), "fscheffold@googlemail.com"); aboutData.addAuthor(ki18n("Gav Wood"), ki18n("Original KDELirc Developer"), "gav.wood@kde.org"); d->applicationData = KComponentData(aboutData); connect(RemoteControlManager::notifier(), SIGNAL(statusChanged(bool)), this, SLOT(slotStatusChanged(bool))); connect(RemoteControlManager::notifier(), SIGNAL(remoteControlAdded(const QString&)), this, SLOT(slotRemoteControlAdded(const QString&))); connect(RemoteControlManager::notifier(), SIGNAL(remoteControlRemoved(const QString&)), this, SLOT(slotRemoteControlRemoved(const QString&))); d_ptr->reload(); foreach(const QString &remote, RemoteControl::allRemoteNames()){ RemoteControl *rc = new RemoteControl(remote); kDebug() << "connecting to remote" << remote; connect(rc, SIGNAL(buttonPressed(const Solid::Control::RemoteControlButton &)), this, SLOT(gotMessage(const Solid::Control::RemoteControlButton &))); } } KRemoteControlDaemon::~KRemoteControlDaemon() { emit unloadTray(); } void KRemoteControlDaemon::slotStatusChanged(bool connected) { if(connected){ foreach(const QString &remote, RemoteControl::allRemoteNames()){ RemoteControl *rc = new RemoteControl(remote); kDebug() << "connecting to remote" << remote; connect(rc, SIGNAL(buttonPressed(const Solid::Control::RemoteControlButton &)), this, SLOT(gotMessage(const Solid::Control::RemoteControlButton &))); } } emit connectionChanged(connected); } void KRemoteControlDaemon::gotMessage(const Solid::Control::RemoteControlButton& button) { kDebug()<< "Got message from remote " << button.remoteName() << " button " << button.name(); Remote *remote= d_ptr->getRemote(button.remoteName()); if(! remote){ kDebug()<< "No remote found for remote" << button.remoteName();; return; } if(d_ptr->isButtonEventIgnored(remote->name())){ kDebug() << "Events for "<< remote->name() << " are currently ignored"; return; } emit(buttonPressed()); //This is for debugging purposes, till we got our tray icon back // notifyEvent("<b>" + remote->name() + ":</b><br>" + i18n("Button %1 pressed" , button.name())); if(remote->currentMode()){ QList<Action*> actionList = remote->currentMode()->actionsForButton(button.name()); if(remote->nextMode(button.name())){ Mode *mode = remote->currentMode(); notifyModeChanged(remote); if(remote->currentMode()-> doAfter()){ actionList.append(remote->currentMode()->actionsForButton(button.name())); } emit(modeChanged(remote->name(), mode->name())); } foreach(Action *action, actionList){ ExecutionEngine::executeAction(action); } } } void KRemoteControlDaemon::reloadConfiguration() { d_ptr->reload(); notifyEvent(i18n("Configuration reloaded.")); foreach(const Remote *remote, d_ptr->remoteList()){ emit modeChanged(remote->name(), remote->masterMode()->name()); } } void KRemoteControlDaemon::changeMode(const QString& remoteName, Mode* mode) { Remote *remote= d_ptr->getRemote(remoteName); if(remote && remote->allModes().contains(mode)){ remote->setCurrentMode(mode); } } void KRemoteControlDaemon::ignoreButtonEvents(const QString& remoteName) { if(remoteName.isEmpty()){ foreach(const Remote *remote, d_ptr->remoteList()){ d_ptr->ignoreButtonEvents(remote->name()); } }else{ d_ptr->ignoreButtonEvents(remoteName); } } void KRemoteControlDaemon::considerButtonEvents(const QString& remoteName) { if(remoteName.isEmpty()){ d_ptr->clearIgnore(); }else{ foreach(const Remote *remote, d_ptr->remoteList()){ d_ptr->considerButtonEvents(remote->name()); } } } void KRemoteControlDaemon::slotRemoteControlAdded(const QString& name) { if(d_ptr->getRemote(name)){ kDebug() << "remote found"; notifyEvent(i18n("The remote control %1 is now available.", name)); }else{ kDebug() << "remote not found"; KNotification *notification = KNotification::event("global_event", i18n("An unconfigured remote control %1 is now available.", name), DesktopIcon("infrared-remote"), 0, KNotification::Persistant, d_ptr->applicationData); notification->setActions(QStringList() << i18nc("Configure the remote", "Configure remote")); connect(notification, SIGNAL(activated(unsigned int)), SLOT(lauchKcmShell())); } emit remoteControlAdded(name); } void KRemoteControlDaemon::lauchKcmShell() { kDebug() << "Launch kcmshell"; KToolInvocation::startServiceByDesktopName("kcm_lirc"); } void KRemoteControlDaemon::slotRemoteControlRemoved(const QString& name) { notifyEvent(i18n("The remote %1 was removed from system.", name)); emit remoteControlRemoved(name); } bool KRemoteControlDaemon::changeMode(const QString& remoteName, const QString& modeName) { Remote *remote = d_ptr->remoteList().getRemote(remoteName); if(remote){ foreach(Mode *mode, remote-> allModes()){ if(mode->name() == modeName){ remote->setCurrentMode(mode); notifyModeChanged(remote); return true; } } } return false; } QStringList KRemoteControlDaemon::getModesForRemote(const QString& remoteName) { QStringList list; Remote *remote = d_ptr->remoteList().getRemote(remoteName); if(remote){ foreach(const Mode *mode, remote->allModes()){ list << mode->name(); } } return list; } QStringList KRemoteControlDaemon::getConfiguredRemotes() { QStringList list; foreach(Remote *remote, d_ptr->remoteList()){ list << remote->name(); } return list; } void KRemoteControlDaemon::notifyModeChanged(Remote* remote) { KNotification::event("mode_event", "<b>" + remote->name() + ":</b><br>" + i18n("Mode switched to %1" , remote->currentMode()->name()), DesktopIcon(remote->currentMode()->iconName().isEmpty() ? "infrared-remote" : remote->currentMode()->iconName()), 0, KNotification::CloseOnTimeout, d_ptr->applicationData); } QString KRemoteControlDaemon::getCurrentMode(const QString& remoteName) { Remote *remote = d_ptr->remoteList().getRemote(remoteName); if(remote){ return remote->currentMode()->name(); } return "modeNotFound"; } QString KRemoteControlDaemon::getModeIcon(const QString &remoteName, const QString& modeName) { Remote *remote = d_ptr->remoteList().getRemote(remoteName); if(remote){ Mode *mode = remote->modeByName(modeName); if(mode){ return mode->iconName(); } } return ""; } void KRemoteControlDaemon::notifyEvent(const QString& message, const QString& iconName, const QString& event) { KNotification::event(event, message, DesktopIcon(iconName), 0, KNotification::CloseOnTimeout, d_ptr->applicationData); } bool KRemoteControlDaemon::eventsIgnored(const QString& remoteName) { return d_ptr->isButtonEventIgnored(remoteName); } <commit_msg>always execute actions in Master mode<commit_after>/* Copyright (C) <2010> <Frank Scheffold (fscheffold@googlemail.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. */ /** @author: Frank Scheffold */ #include "kremotecontroldaemon.h" #include "krcdadaptor.h" #include <kdelirc/libkremotecontrol/dbusinterface.h> #include <kdelirc/libkremotecontrol/mode.h> #include <kdelirc/libkremotecontrol/action.h> #include <kdelirc/libkremotecontrol/executionengine.h> #include <kdelirc/libkremotecontrol/remotelist.h> #include <KCModuleInfo> #include <KDebug> #include <KNotification> #include <KAboutData> #include <KIconLoader> #include <KToolInvocation> #include<QPixmap> // #include <QErrorMessage> using namespace Solid::Control; K_PLUGIN_FACTORY(KRemoteControlDaemonFactory, registerPlugin<KRemoteControlDaemon>();) K_EXPORT_PLUGIN(KRemoteControlDaemonFactory("kremotecontroldaemon")) class KRemoteControlDaemonPrivate { private: KRemoteControlDaemon *m_parent; RemoteList m_remoteList; QStringList m_ignoreNextButtonList; public: KComponentData applicationData; KRemoteControlDaemonPrivate(KRemoteControlDaemon *parent) { m_parent = parent; }; ~KRemoteControlDaemonPrivate() { }; RemoteList remoteList(){ return m_remoteList; }; void reload(){ m_remoteList.loadFromConfig("kremotecontrolrc"); KConfig config("kremotecontrolrc"); KConfigGroup globalGroup(&config, "Global"); if(globalGroup.readEntry("ShowTrayIcon", true)){ kDebug() << "starting notifier item" << KToolInvocation::kdeinitExec("krcdnotifieritem"); } else { emit m_parent->unloadTray(); } }; Remote* getRemote(const QString& remoteName) { return m_remoteList.getRemote(remoteName); }; bool isButtonEventIgnored(const QString &remote){ return m_ignoreNextButtonList.contains(remote); }; void ignoreButtonEvents(const QString& remote){ kDebug() << "muting remote" << remote; m_ignoreNextButtonList.append(remote); m_ignoreNextButtonList.removeDuplicates(); } void considerButtonEvents(const QString& remote){ kDebug() << "unmuting remote" << remote; m_ignoreNextButtonList.removeAll(remote); } void clearIgnore(){ m_remoteList.clear(); } }; KRemoteControlDaemon::KRemoteControlDaemon(QObject* parent, const QVariantList& ): KDEDModule(parent), d_ptr(new KRemoteControlDaemonPrivate(this)) { Q_D(KRemoteControlDaemon); // QErrorMessage::qtHandler () ; //qInstallMsgHandler(); new KrcdAdaptor(this); KAboutData aboutData("krcd", "krcd", ki18n("K Remote Control Daemon"), "0.1", ki18n("Remote Control Daemon for KDE4"), KAboutData::License_GPL, ki18n("(c) 2010 Frank Scheffold"), KLocalizedString(), "http://www.kde.org"); aboutData.addAuthor(ki18n("Michael Zanetti"), ki18n("Maintainer"), "michal_zanetti@gmx.net"); aboutData.addAuthor(ki18n("Frank Scheffold"), ki18n("Developer"), "fscheffold@googlemail.com"); aboutData.addAuthor(ki18n("Gav Wood"), ki18n("Original KDELirc Developer"), "gav.wood@kde.org"); d->applicationData = KComponentData(aboutData); connect(RemoteControlManager::notifier(), SIGNAL(statusChanged(bool)), this, SLOT(slotStatusChanged(bool))); connect(RemoteControlManager::notifier(), SIGNAL(remoteControlAdded(const QString&)), this, SLOT(slotRemoteControlAdded(const QString&))); connect(RemoteControlManager::notifier(), SIGNAL(remoteControlRemoved(const QString&)), this, SLOT(slotRemoteControlRemoved(const QString&))); d_ptr->reload(); foreach(const QString &remote, RemoteControl::allRemoteNames()){ RemoteControl *rc = new RemoteControl(remote); kDebug() << "connecting to remote" << remote; connect(rc, SIGNAL(buttonPressed(const Solid::Control::RemoteControlButton &)), this, SLOT(gotMessage(const Solid::Control::RemoteControlButton &))); } } KRemoteControlDaemon::~KRemoteControlDaemon() { emit unloadTray(); } void KRemoteControlDaemon::slotStatusChanged(bool connected) { if(connected){ foreach(const QString &remote, RemoteControl::allRemoteNames()){ RemoteControl *rc = new RemoteControl(remote); kDebug() << "connecting to remote" << remote; connect(rc, SIGNAL(buttonPressed(const Solid::Control::RemoteControlButton &)), this, SLOT(gotMessage(const Solid::Control::RemoteControlButton &))); } } emit connectionChanged(connected); } void KRemoteControlDaemon::gotMessage(const Solid::Control::RemoteControlButton& button) { kDebug()<< "Got message from remote " << button.remoteName() << " button " << button.name(); Remote *remote= d_ptr->getRemote(button.remoteName()); if(! remote){ kDebug()<< "No remote found for remote" << button.remoteName();; return; } if(d_ptr->isButtonEventIgnored(remote->name())){ kDebug() << "Events for "<< remote->name() << " are currently ignored"; return; } emit(buttonPressed()); if(remote->currentMode()){ QList<Action*> actionList = remote->masterMode()->actionsForButton(button.name()); actionList.append(remote->currentMode()->actionsForButton(button.name())); if(remote->nextMode(button.name())){ Mode *mode = remote->currentMode(); notifyModeChanged(remote); if(remote->currentMode()-> doAfter()){ actionList.append(remote->currentMode()->actionsForButton(button.name())); } emit(modeChanged(remote->name(), mode->name())); } foreach(Action *action, actionList){ ExecutionEngine::executeAction(action); } } } void KRemoteControlDaemon::reloadConfiguration() { d_ptr->reload(); notifyEvent(i18n("Configuration reloaded.")); foreach(const Remote *remote, d_ptr->remoteList()){ emit modeChanged(remote->name(), remote->masterMode()->name()); } } void KRemoteControlDaemon::changeMode(const QString& remoteName, Mode* mode) { Remote *remote= d_ptr->getRemote(remoteName); if(remote && remote->allModes().contains(mode)){ remote->setCurrentMode(mode); } } void KRemoteControlDaemon::ignoreButtonEvents(const QString& remoteName) { if(remoteName.isEmpty()){ foreach(const Remote *remote, d_ptr->remoteList()){ d_ptr->ignoreButtonEvents(remote->name()); } }else{ d_ptr->ignoreButtonEvents(remoteName); } } void KRemoteControlDaemon::considerButtonEvents(const QString& remoteName) { if(remoteName.isEmpty()){ d_ptr->clearIgnore(); }else{ foreach(const Remote *remote, d_ptr->remoteList()){ d_ptr->considerButtonEvents(remote->name()); } } } void KRemoteControlDaemon::slotRemoteControlAdded(const QString& name) { if(d_ptr->getRemote(name)){ kDebug() << "remote found"; notifyEvent(i18n("The remote control %1 is now available.", name)); }else{ kDebug() << "remote not found"; KNotification *notification = KNotification::event("global_event", i18n("An unconfigured remote control %1 is now available.", name), DesktopIcon("infrared-remote"), 0, KNotification::Persistant, d_ptr->applicationData); notification->setActions(QStringList() << i18nc("Configure the remote", "Configure remote")); connect(notification, SIGNAL(activated(unsigned int)), SLOT(lauchKcmShell())); } emit remoteControlAdded(name); } void KRemoteControlDaemon::lauchKcmShell() { kDebug() << "Launch kcmshell"; KToolInvocation::startServiceByDesktopName("kcm_lirc"); } void KRemoteControlDaemon::slotRemoteControlRemoved(const QString& name) { notifyEvent(i18n("The remote %1 was removed from system.", name)); emit remoteControlRemoved(name); } bool KRemoteControlDaemon::changeMode(const QString& remoteName, const QString& modeName) { Remote *remote = d_ptr->remoteList().getRemote(remoteName); if(remote){ foreach(Mode *mode, remote-> allModes()){ if(mode->name() == modeName){ remote->setCurrentMode(mode); notifyModeChanged(remote); return true; } } } return false; } QStringList KRemoteControlDaemon::getModesForRemote(const QString& remoteName) { QStringList list; Remote *remote = d_ptr->remoteList().getRemote(remoteName); if(remote){ foreach(const Mode *mode, remote->allModes()){ list << mode->name(); } } return list; } QStringList KRemoteControlDaemon::getConfiguredRemotes() { QStringList list; foreach(Remote *remote, d_ptr->remoteList()){ list << remote->name(); } return list; } void KRemoteControlDaemon::notifyModeChanged(Remote* remote) { KNotification::event("mode_event", "<b>" + remote->name() + ":</b><br>" + i18n("Mode switched to %1" , remote->currentMode()->name()), DesktopIcon(remote->currentMode()->iconName().isEmpty() ? "infrared-remote" : remote->currentMode()->iconName()), 0, KNotification::CloseOnTimeout, d_ptr->applicationData); } QString KRemoteControlDaemon::getCurrentMode(const QString& remoteName) { Remote *remote = d_ptr->remoteList().getRemote(remoteName); if(remote){ return remote->currentMode()->name(); } return "modeNotFound"; } QString KRemoteControlDaemon::getModeIcon(const QString &remoteName, const QString& modeName) { Remote *remote = d_ptr->remoteList().getRemote(remoteName); if(remote){ Mode *mode = remote->modeByName(modeName); if(mode){ return mode->iconName(); } } return ""; } void KRemoteControlDaemon::notifyEvent(const QString& message, const QString& iconName, const QString& event) { KNotification::event(event, message, DesktopIcon(iconName), 0, KNotification::CloseOnTimeout, d_ptr->applicationData); } bool KRemoteControlDaemon::eventsIgnored(const QString& remoteName) { return d_ptr->isButtonEventIgnored(remoteName); } <|endoftext|>
<commit_before>/* * Copyright (c) 2007 MIPS Technologies, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders 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 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Korey Sewell * */ #ifndef __CPU_INORDER_COMM_HH__ #define __CPU_INORDER_COMM_HH__ #include <vector> #include "arch/faults.hh" #include "arch/isa_traits.hh" #include "base/types.hh" #include "cpu/inorder/inorder_dyn_inst.hh" #include "cpu/inorder/pipeline_traits.hh" #include "cpu/inst_seq.hh" /** Struct that defines the information passed from in between stages */ /** This information mainly goes forward through the pipeline. */ struct InterStageStruct { std::vector<ThePipeline::DynInstPtr> insts; bool squash; bool branchMispredict; bool branchTaken; uint64_t mispredPC; uint64_t nextPC; InstSeqNum squashedSeqNum; bool includeSquashInst; InterStageStruct() : squash(false), branchMispredict(false), branchTaken(false), mispredPC(0), nextPC(0), squashedSeqNum(0), includeSquashInst(false) { } }; /** Turn This into a Class */ /** Struct that defines all backwards communication. */ struct TimeStruct { struct stageComm { bool squash; bool predIncorrect; uint64_t branchAddr; // @todo: Might want to package this kind of branch stuff into a single // struct as it is used pretty frequently. bool branchMispredict; bool branchTaken; Addr mispredPC; TheISA::PCState nextPC; unsigned branchCount; // Represents the instruction that has either been retired or // squashed. Similar to having a single bus that broadcasts the // retired or squashed sequence number. InstSeqNum doneSeqNum; InstSeqNum bdelayDoneSeqNum; bool squashDelaySlot; //Just in case we want to do a commit/squash on a cycle //(necessary for multiple ROBs?) bool commitInsts; InstSeqNum squashSeqNum; // Communication specifically to the IQ to tell the IQ that it can // schedule a non-speculative instruction. InstSeqNum nonSpecSeqNum; bool uncached; ThePipeline::DynInstPtr uncachedLoad; bool interruptPending; bool clearInterrupt; }; stageComm stageInfo[ThePipeline::NumStages][ThePipeline::MaxThreads]; bool stageBlock[ThePipeline::NumStages][ThePipeline::MaxThreads]; bool stageUnblock[ThePipeline::NumStages][ThePipeline::MaxThreads]; }; #endif //__CPU_INORDER_COMM_HH__ <commit_msg>inorder: cleanup intercomm. structs/squash info<commit_after>/* * Copyright (c) 2007 MIPS Technologies, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders 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 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Korey Sewell * */ #ifndef __CPU_INORDER_COMM_HH__ #define __CPU_INORDER_COMM_HH__ #include <vector> #include "arch/faults.hh" #include "arch/isa_traits.hh" #include "base/types.hh" #include "cpu/inorder/inorder_dyn_inst.hh" #include "cpu/inorder/pipeline_traits.hh" #include "cpu/inst_seq.hh" /** Struct that defines the information passed from in between stages */ /** This information mainly goes forward through the pipeline. */ struct InterStageStruct { //@todo: probably should make this a list since the amount of // instructions that get passed forward per cycle is // really dependent on issue width, CPI, etc. std::vector<ThePipeline::DynInstPtr> insts; // Add any information that needs to be passed forward to stages // below ... }; /** Struct that defines all backwards communication. */ struct TimeStruct { struct stageComm { bool squash; InstSeqNum doneSeqNum; bool uncached; ThePipeline::DynInstPtr uncachedLoad; }; stageComm stageInfo[ThePipeline::NumStages][ThePipeline::MaxThreads]; bool stageBlock[ThePipeline::NumStages][ThePipeline::MaxThreads]; bool stageUnblock[ThePipeline::NumStages][ThePipeline::MaxThreads]; }; #endif //__CPU_INORDER_COMM_HH__ <|endoftext|>
<commit_before>#include "rdb_protocol/op.hpp" #include "rdb_protocol/term.hpp" #include "rdb_protocol/terms/terms.hpp" namespace ql { class sample_term_t : public op_term_t { public: sample_term_t(env_t *env, protob_t<const Term> term) : op_term_t(env, term, argspec_t(2)) { } counted_t<val_t> eval_impl() { int num_int = arg(1)->as_int(); rcheck(num_int >= 0, strprintf("Number of items to sample must be non-negative, got `%d`.", num_int)); size_t num = num_int; counted_t<table_t> t; counted_t<datum_stream_t> seq; counted_t<val_t> v = arg(0); if (v->get_type().is_convertible(val_t::type_t::SELECTION)) { std::pair<counted_t<table_t>, counted_t<datum_stream_t> > t_seq = v->as_selection(); t = t_seq.first; seq = t_seq.second; } else { seq = v->as_seq(); } std::vector<counted_t<const datum_t> > result; int element_number = 0; while (counted_t<const datum_t> row = seq->next()) { element_number++; if (result.size() < num) { result.push_back(row); } else { /* We have a limitation on the size of arrays that makes * sure they are less than the size of an integer. */ size_t new_index = randint(element_number); if (new_index < num) { result[new_index] = row; } } } rcheck(result.size() == num, strprintf("Trying to sample `%zu` elements from" \ "a sequence of size `%zu`.", num, result.size())); counted_t<datum_stream_t> new_ds( new array_datum_stream_t(env, make_counted<const datum_t>(result), backtrace())); return t.has() ? new_val(new_ds, t) : new_val(new_ds); } bool is_deterministic_impl() const { return false; } virtual const char *name() const { return "sample"; } }; counted_t<term_t> make_sample_term(env_t *env, protob_t<const Term> term) { return counted_t<sample_term_t>(new sample_term_t(env, term)); } } //namespace ql <commit_msg>Adds shuffling to sample output.<commit_after>#include <algorithm> #include "rdb_protocol/op.hpp" #include "rdb_protocol/term.hpp" #include "rdb_protocol/terms/terms.hpp" namespace ql { class sample_term_t : public op_term_t { public: sample_term_t(env_t *env, protob_t<const Term> term) : op_term_t(env, term, argspec_t(2)) { } counted_t<val_t> eval_impl() { int num_int = arg(1)->as_int(); rcheck(num_int >= 0, strprintf("Number of items to sample must be non-negative, got `%d`.", num_int)); size_t num = num_int; counted_t<table_t> t; counted_t<datum_stream_t> seq; counted_t<val_t> v = arg(0); if (v->get_type().is_convertible(val_t::type_t::SELECTION)) { std::pair<counted_t<table_t>, counted_t<datum_stream_t> > t_seq = v->as_selection(); t = t_seq.first; seq = t_seq.second; } else { seq = v->as_seq(); } std::vector<counted_t<const datum_t> > result; int element_number = 0; while (counted_t<const datum_t> row = seq->next()) { element_number++; if (result.size() < num) { result.push_back(row); } else { /* We have a limitation on the size of arrays that makes * sure they are less than the size of an integer. */ size_t new_index = randint(element_number); if (new_index < num) { result[new_index] = row; } } } std::random_shuffle(result.begin(), result.end()); counted_t<datum_stream_t> new_ds( new array_datum_stream_t(env, make_counted<const datum_t>(result), backtrace())); return t.has() ? new_val(new_ds, t) : new_val(new_ds); } bool is_deterministic_impl() const { return false; } virtual const char *name() const { return "sample"; } }; counted_t<term_t> make_sample_term(env_t *env, protob_t<const Term> term) { return counted_t<sample_term_t>(new sample_term_t(env, term)); } } //namespace ql <|endoftext|>
<commit_before>#ifndef _internal_hpp_INCLUDED #define _internal_hpp_INCLUDED #include <cassert> #include <climits> #include <cstdio> #include <vector> /*------------------------------------------------------------------------*/ using namespace std; /*------------------------------------------------------------------------*/ #include "arena.hpp" #include "avg.hpp" #include "ema.hpp" #include "flags.hpp" #include "format.hpp" #include "level.hpp" #include "link.hpp" #include "logging.hpp" #include "options.hpp" #include "profile.hpp" #include "queue.hpp" #include "stats.hpp" #include "timer.hpp" #include "watch.hpp" #include "var.hpp" #include "util.hpp" #include "limit.hpp" #include "inc.hpp" #include "clause.hpp" /*------------------------------------------------------------------------*/ namespace CaDiCaL { class Proof; class File; class Internal { friend class Solver; friend class Arena; friend struct Logger; friend struct Message; friend class Parser; friend class Proof; friend struct Stats; friend struct bumped_earlier; friend struct trail_bumped_smaller; friend struct trail_smaller; /*----------------------------------------------------------------------*/ // The actual state of the solver is in this section. bool unsat; // empty clause found or learned bool iterating; // report learned unit (iteration) bool clashing; // found clashing units in 'parse_dimacs' size_t vsize; // actually allocated variable data size int max_var; // maximum variable index int level; // decision level ('control.size () - 1') signed char * vals; // assignment [-max_var,max_var] signed char * solution; // for debugging [-max_var,max_var] signed char * marks; // signed marks [1,max_var] signed char * phases; // saved assignment [1,max_var] Var * vtab; // variable table Link * ltab; // table of links for decision queue Flags * ftab; // seen, poison, minimized flags table long * btab; // enqueue time stamps for queue Queue queue; // variable move to front decision queue Watches * wtab; // table of watches for all literals Clause * conflict; // set in 'propagation', reset in 'analyze' size_t propagated; // next trail position to propagate vector<int> trail; // assigned literals vector<int> clause; // temporary in parsing & learning vector<int> levels; // decision levels in learned clause vector<int> analyzed; // analyzed literals in 'analyze' vector<int> minimized; // removable or poison in 'minimize' vector<Level> control; // 'level + 1 == control.size ()' vector<Clause*> clauses; // ordered collection of all clauses vector<Clause*> resolved; // large clauses in 'analyze' EMA fast_glue_avg; // fast glue average EMA slow_glue_avg; // slow glue average EMA restartint; // actual restart interval average EMA restarteff; // restart effectiveness average EMA size_avg; // learned clause size average EMA jump_avg; // jump average Limit lim; // limits for various phases Inc inc; // limit increments Proof * proof; // trace clausal proof if non zero Options opts; // run-time options Stats stats; // statistics vector<int> original; // original CNF for debugging vector<Timer> timers; // active timers for profiling functions Profiles profiles; // global profiled time for functions Arena arena; // memory arena for moving garbage collector Format error; // last (persistent) error message Internal * internal; // proxy to 'this' in macros (redundant) /*----------------------------------------------------------------------*/ // Internal delegates and helpers for corresponding functions in 'Solver'. // void resize_queue (int new_max_var); void resize (int new_max_var); void add_original_lit (int lit); // Enlarge tables. // void enlarge_vals (int new_vsize); void enlarge (int new_max_var); // Functions for monitoring resources. // size_t vector_bytes (); void inc_bytes (size_t); void dec_bytes (size_t); double seconds (); size_t max_bytes (); size_t current_bytes (); int active_variables () const { return max_var - stats.fixed; } // Regularly reports what is going on in 'report.cpp'. // void report (char type, bool verbose = false); // Unsigned literals (abs) with checks. // int vidx (int lit) const { int idx; assert (lit), assert (lit != INT_MIN); idx = abs (lit); assert (idx <= max_var); return idx; } // Unsigned version with LSB denoting sign. This is used in indexing arrays // by literals. The idea is to keep the elements in such an array for both // the positive and negated version of a literal close together. // unsigned vlit (int lit) { return (lit < 0) + 2u * (unsigned) vidx (lit); } // Helper functions to access variable and literal data. // Var & var (int lit) { return vtab[vidx (lit)]; } Link & link (int lit) { return ltab[vidx (lit)]; } Flags & flags (int lit) { return ftab[vidx (lit)]; } const Flags & flags (int lit) const { return ftab[vidx (lit)]; } Watches & watches (int lit) { return wtab[vlit (lit)]; } // Marking variables with a sign (positive or negative). // signed char marked (int lit) const { signed char res = marks [ vidx (lit) ]; if (lit < 0) res = -res; return res; } void mark (int lit) { assert (!marked (lit)); marks[vidx (lit)] = sign (lit); } void unmark (int lit) { marks [ vidx (lit) ] = 0; } void mark_clause (); // mark 'this->clause' void unmark_clause (); // unmark 'this->clause' void mark (Clause *); void unmark (Clause *); // Watch literal 'lit' in clause with blocking literal 'blit'. // Inlined here, since it occurs in the tight inner loop of 'propagate'. // inline void watch_literal (int lit, int blit, Clause * c, int size) { Watches & ws = watches (lit); ws.push_back (Watch (blit, c, size)); LOG (c, "watch %d blit %d in", lit, blit); } void unwatch_literal (int lit, Clause * c); void update_size_watch (int lit, Clause * c, int new_size); // Update queue to point to last potentially still unassigned variable. // All variables after 'queue.unassigned' in bump order are assumed to be // assigned. Then update the 'queue.bumped' field and log it. This is // inlined here since it occurs in several inner loops. // inline void update_queue_unassigned (int idx) { assert (0 < idx), assert (idx <= max_var); queue.unassigned = idx; queue.bumped = btab[idx]; LOG ("queue unassigned now %d bumped %ld", idx, btab[idx]); } // Managing clauses in 'clause.cpp'. Without explicit 'Clause' argument // these functions work on the global temporary 'clause'. // void watch_clause (Clause *); size_t bytes_clause (int size); Clause * new_clause (bool red, int glue = 0); void deallocate_clause (Clause *); void delete_clause (Clause *); bool tautological_clause (); void add_new_original_clause (); Clause * new_learned_clause (int glue); // We want to eagerly update statistics as soon clauses are marked // garbage. Otherwise 'report' for instance gives wrong numbers after // 'subsume' before the next 'reduce'. Thus we factored out marking and // accounting for garbage clauses. Note that we do not update allocated // bytes statistics at this point, but wait until the next 'collect'. // void mark_garbage (Clause * c) { assert (!c->garbage); if (c->redundant) assert (stats.redundant), stats.redundant--; else assert (stats.irredundant), stats.irredundant--; c->garbage = true; } // Forward reasoning through propagation in 'propagate.cpp'. // void assign (int lit); // unit or decision void assign (int lit, Clause *); // driving learned clause void assign (int lit, Clause *, int); // inlined in 'propagate.cpp' bool propagate (); // Undo and restart in 'backtrack.cpp'. // void unassign (int lit); void backtrack (int target_level = 0); // Learning from conflicts in 'analyze.cc'. // void learn_empty_clause (); void learn_unit_clause (int lit); bool minimize_literal (int lit, int depth = 0); void minimize_clause (); bool shrink_literal (int lit, int depth = 0); void shrink_clause (); void bump_variable (int lit); void bump_variables (); void bump_resolved_clauses (); void resolve_clause (Clause *); void clear_seen (); void clear_levels (); void clear_minimized (); void analyze_literal (int lit, int & open); void analyze_reason (int lit, Clause *, int & open); void analyze (); void iterate (); // for reporting learned unit clause // Restarting policy in 'restart.cc'. // bool restarting (); int reuse_trail (); void restart (); // Asynchronous terminating check. // bool terminating (); void terminate (); // TODO: not implemented yet. // Reducing means determining useless clauses with 'reduce' in // 'reduce.cpp' as well as root level satisfied clause and then collecting // them with 'garbage_collection' in 'collect.cpp'. // bool reducing (); void protect_reasons (); void unprotect_reasons (); int clause_contains_fixed_literal (Clause *); void flush_falsified_literals (Clause *); void mark_satisfied_clauses_as_garbage (); void mark_useless_redundant_clauses_as_garbage (); void move_clause (Clause *); void move_non_garbage_clauses (); void delete_garbage_clauses (); void flush_watches (); void setup_watches (); void check_clause_stats (); void garbage_collection (); void reduce (); // Eager backward subsumption checking of learned clauses. // bool eagerly_subsume_last_learned (Clause *); void eagerly_subsume_last_learned (); // Regular forward subsumption checking. // bool subsuming (); void strengthen_clause (Clause *, int); void subsume_clause (Clause * subsuming, Clause * subsumed); int subsume_check (Clause * subsuming, Clause * subsumed); int subsume (Clause *, vector<Clause*> * occs); void subsume (); // Part on picking the next decision in 'decide.cpp'. // bool satisfied () const { return trail.size () == (size_t) max_var; } int next_decision_variable (); void decide (); // Main search functions in 'internal.cpp'. // int search (); // CDCL loop void init_solving (); int solve (); // Built in profiling in 'profile.cpp'. // void start_profiling (Profile * p, double); void stop_profiling (Profile * p, double); void start_profiling (Profile * p) { start_profiling (p, seconds ()); } void stop_profiling (Profile * p) { stop_profiling (p, seconds ()); } void update_all_timers (double now); void print_profile (double now); // Checking solutions (see 'solution.cpp'). // int sol (int lit) const; void check_clause (); void check (int (Internal::*assignment) (int) const); Internal (); ~Internal (); // Get the value of a literal: -1 = false, 0 = unassigned, 1 = true. // int val (int lit) const { assert (lit), assert (abs (lit) <= max_var); return vals[lit]; } long & bumped (int lit) { return btab[vidx (lit)]; } // As 'val' but restricted to the root-level value of a literal. // int fixed (int lit) { int idx = vidx (lit), res = vals[idx]; if (res && vtab[idx].level) res = 0; if (lit < 0) res = -res; return res; } // Parsing functions (handed over to 'parse.cpp'). // const char * parse_dimacs (FILE *); const char * parse_dimacs (const char *); const char * parse_solution (const char *); // Enable and disable proof logging. void close_proof (); void new_proof (File *, bool owned = false); }; struct trail_smaller { Internal * internal; trail_smaller (Internal * s) : internal (s) { } bool operator () (int a, int b) { return internal->var (a).trail < internal->var (b).trail; } }; }; #endif <commit_msg>another comment<commit_after>#ifndef _internal_hpp_INCLUDED #define _internal_hpp_INCLUDED #include <cassert> #include <climits> #include <cstdio> #include <vector> /*------------------------------------------------------------------------*/ using namespace std; /*------------------------------------------------------------------------*/ #include "arena.hpp" #include "avg.hpp" #include "ema.hpp" #include "flags.hpp" #include "format.hpp" #include "level.hpp" #include "link.hpp" #include "logging.hpp" #include "options.hpp" #include "profile.hpp" #include "queue.hpp" #include "stats.hpp" #include "timer.hpp" #include "watch.hpp" #include "var.hpp" #include "util.hpp" #include "limit.hpp" #include "inc.hpp" #include "clause.hpp" /*------------------------------------------------------------------------*/ namespace CaDiCaL { class Proof; class File; class Internal { friend class Solver; friend class Arena; friend struct Logger; friend struct Message; friend class Parser; friend class Proof; friend struct Stats; friend struct bumped_earlier; friend struct trail_bumped_smaller; friend struct trail_smaller; /*----------------------------------------------------------------------*/ // The actual state of the solver is in this section. bool unsat; // empty clause found or learned bool iterating; // report learned unit (iteration) bool clashing; // found clashing units in 'parse_dimacs' size_t vsize; // actually allocated variable data size int max_var; // maximum variable index int level; // decision level ('control.size () - 1') signed char * vals; // assignment [-max_var,max_var] signed char * solution; // for debugging [-max_var,max_var] signed char * marks; // signed marks [1,max_var] signed char * phases; // saved assignment [1,max_var] Var * vtab; // variable table Link * ltab; // table of links for decision queue Flags * ftab; // seen, poison, minimized flags table long * btab; // enqueue time stamps for queue Queue queue; // variable move to front decision queue Watches * wtab; // table of watches for all literals Clause * conflict; // set in 'propagation', reset in 'analyze' size_t propagated; // next trail position to propagate vector<int> trail; // assigned literals vector<int> clause; // temporary in parsing & learning vector<int> levels; // decision levels in learned clause vector<int> analyzed; // analyzed literals in 'analyze' vector<int> minimized; // removable or poison in 'minimize' vector<Level> control; // 'level + 1 == control.size ()' vector<Clause*> clauses; // ordered collection of all clauses vector<Clause*> resolved; // large clauses in 'analyze' EMA fast_glue_avg; // fast glue average EMA slow_glue_avg; // slow glue average EMA restartint; // actual restart interval average EMA restarteff; // restart effectiveness average EMA size_avg; // learned clause size average EMA jump_avg; // jump average Limit lim; // limits for various phases Inc inc; // limit increments Proof * proof; // trace clausal proof if non zero Options opts; // run-time options Stats stats; // statistics vector<int> original; // original CNF for debugging vector<Timer> timers; // active timers for profiling functions Profiles profiles; // global profiled time for functions Arena arena; // memory arena for moving garbage collector Format error; // last (persistent) error message Internal * internal; // proxy to 'this' in macros (redundant) /*----------------------------------------------------------------------*/ // Internal delegates and helpers for corresponding functions in 'Solver'. // void resize_queue (int new_max_var); void resize (int new_max_var); void add_original_lit (int lit); // Enlarge tables. // void enlarge_vals (int new_vsize); void enlarge (int new_max_var); // Functions for monitoring resources. // size_t vector_bytes (); void inc_bytes (size_t); void dec_bytes (size_t); double seconds (); size_t max_bytes (); size_t current_bytes (); int active_variables () const { return max_var - stats.fixed; } // Regularly reports what is going on in 'report.cpp'. // void report (char type, bool verbose = false); // Unsigned literals (abs) with checks. // int vidx (int lit) const { int idx; assert (lit), assert (lit != INT_MIN); idx = abs (lit); assert (idx <= max_var); return idx; } // Unsigned version with LSB denoting sign. This is used in indexing arrays // by literals. The idea is to keep the elements in such an array for both // the positive and negated version of a literal close together. // unsigned vlit (int lit) { return (lit < 0) + 2u * (unsigned) vidx (lit); } // Helper functions to access variable and literal data. // Var & var (int lit) { return vtab[vidx (lit)]; } Link & link (int lit) { return ltab[vidx (lit)]; } Flags & flags (int lit) { return ftab[vidx (lit)]; } const Flags & flags (int lit) const { return ftab[vidx (lit)]; } Watches & watches (int lit) { return wtab[vlit (lit)]; } // Marking variables with a sign (positive or negative). // signed char marked (int lit) const { signed char res = marks [ vidx (lit) ]; if (lit < 0) res = -res; return res; } void mark (int lit) { assert (!marked (lit)); marks[vidx (lit)] = sign (lit); } void unmark (int lit) { marks [ vidx (lit) ] = 0; } void mark_clause (); // mark 'this->clause' void unmark_clause (); // unmark 'this->clause' void mark (Clause *); void unmark (Clause *); // Watch literal 'lit' in clause with blocking literal 'blit'. // Inlined here, since it occurs in the tight inner loop of 'propagate'. // inline void watch_literal (int lit, int blit, Clause * c, int size) { Watches & ws = watches (lit); ws.push_back (Watch (blit, c, size)); LOG (c, "watch %d blit %d in", lit, blit); } void unwatch_literal (int lit, Clause * c); void update_size_watch (int lit, Clause * c, int new_size); // Update queue to point to last potentially still unassigned variable. // All variables after 'queue.unassigned' in bump order are assumed to be // assigned. Then update the 'queue.bumped' field and log it. This is // inlined here since it occurs in several inner loops. // inline void update_queue_unassigned (int idx) { assert (0 < idx), assert (idx <= max_var); queue.unassigned = idx; queue.bumped = btab[idx]; LOG ("queue unassigned now %d bumped %ld", idx, btab[idx]); } // Managing clauses in 'clause.cpp'. Without explicit 'Clause' argument // these functions work on the global temporary 'clause'. // void watch_clause (Clause *); size_t bytes_clause (int size); Clause * new_clause (bool red, int glue = 0); void deallocate_clause (Clause *); void delete_clause (Clause *); bool tautological_clause (); void add_new_original_clause (); Clause * new_learned_clause (int glue); // We want to eagerly update statistics as soon clauses are marked // garbage. Otherwise 'report' for instance gives wrong numbers after // 'subsume' before the next 'reduce'. Thus we factored out marking and // accounting for garbage clauses. Note that we do not update allocated // bytes statistics at this point, but wait until the next 'collect'. // In order not to miss any update to those statistics we call // 'check_clause_stats' after garbage collection in debugging mode. // void mark_garbage (Clause * c) { assert (!c->garbage); if (c->redundant) assert (stats.redundant), stats.redundant--; else assert (stats.irredundant), stats.irredundant--; c->garbage = true; } // Forward reasoning through propagation in 'propagate.cpp'. // void assign (int lit); // unit or decision void assign (int lit, Clause *); // driving learned clause void assign (int lit, Clause *, int); // inlined in 'propagate.cpp' bool propagate (); // Undo and restart in 'backtrack.cpp'. // void unassign (int lit); void backtrack (int target_level = 0); // Learning from conflicts in 'analyze.cc'. // void learn_empty_clause (); void learn_unit_clause (int lit); bool minimize_literal (int lit, int depth = 0); void minimize_clause (); bool shrink_literal (int lit, int depth = 0); void shrink_clause (); void bump_variable (int lit); void bump_variables (); void bump_resolved_clauses (); void resolve_clause (Clause *); void clear_seen (); void clear_levels (); void clear_minimized (); void analyze_literal (int lit, int & open); void analyze_reason (int lit, Clause *, int & open); void analyze (); void iterate (); // for reporting learned unit clause // Restarting policy in 'restart.cc'. // bool restarting (); int reuse_trail (); void restart (); // Asynchronous terminating check. // bool terminating (); void terminate (); // TODO: not implemented yet. // Reducing means determining useless clauses with 'reduce' in // 'reduce.cpp' as well as root level satisfied clause and then collecting // them with 'garbage_collection' in 'collect.cpp'. // bool reducing (); void protect_reasons (); void unprotect_reasons (); int clause_contains_fixed_literal (Clause *); void flush_falsified_literals (Clause *); void mark_satisfied_clauses_as_garbage (); void mark_useless_redundant_clauses_as_garbage (); void move_clause (Clause *); void move_non_garbage_clauses (); void delete_garbage_clauses (); void flush_watches (); void setup_watches (); void check_clause_stats (); void garbage_collection (); void reduce (); // Eager backward subsumption checking of learned clauses. // bool eagerly_subsume_last_learned (Clause *); void eagerly_subsume_last_learned (); // Regular forward subsumption checking. // bool subsuming (); void strengthen_clause (Clause *, int); void subsume_clause (Clause * subsuming, Clause * subsumed); int subsume_check (Clause * subsuming, Clause * subsumed); int subsume (Clause *, vector<Clause*> * occs); void subsume (); // Part on picking the next decision in 'decide.cpp'. // bool satisfied () const { return trail.size () == (size_t) max_var; } int next_decision_variable (); void decide (); // Main search functions in 'internal.cpp'. // int search (); // CDCL loop void init_solving (); int solve (); // Built in profiling in 'profile.cpp'. // void start_profiling (Profile * p, double); void stop_profiling (Profile * p, double); void start_profiling (Profile * p) { start_profiling (p, seconds ()); } void stop_profiling (Profile * p) { stop_profiling (p, seconds ()); } void update_all_timers (double now); void print_profile (double now); // Checking solutions (see 'solution.cpp'). // int sol (int lit) const; void check_clause (); void check (int (Internal::*assignment) (int) const); Internal (); ~Internal (); // Get the value of a literal: -1 = false, 0 = unassigned, 1 = true. // int val (int lit) const { assert (lit), assert (abs (lit) <= max_var); return vals[lit]; } long & bumped (int lit) { return btab[vidx (lit)]; } // As 'val' but restricted to the root-level value of a literal. // int fixed (int lit) { int idx = vidx (lit), res = vals[idx]; if (res && vtab[idx].level) res = 0; if (lit < 0) res = -res; return res; } // Parsing functions (handed over to 'parse.cpp'). // const char * parse_dimacs (FILE *); const char * parse_dimacs (const char *); const char * parse_solution (const char *); // Enable and disable proof logging. void close_proof (); void new_proof (File *, bool owned = false); }; struct trail_smaller { Internal * internal; trail_smaller (Internal * s) : internal (s) { } bool operator () (int a, int b) { return internal->var (a).trail < internal->var (b).trail; } }; }; #endif <|endoftext|>
<commit_before><commit_msg>dom_operations to use WebAnimationController<commit_after><|endoftext|>
<commit_before>/** @file @brief Implementation @date 2016 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2016 Razer 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. // Internal Includes #include "DriverLoader.h" #include "InterfaceTraits.h" #include "SearchPathExtender.h" // Library/third-party includes #include <osvr/Util/PlatformConfig.h> // Standard includes #include <iostream> #if defined(OSVR_WINDOWS) #define WIN32_LEAN_AND_MEAN #define NO_MINMAX #include <windows.h> #elif defined(OSVR_LINUX) || defined(OSVR_MACOSX) #include <dlfcn.h> #endif namespace osvr { namespace vive { static const auto ENTRY_POINT_FUNCTION_NAME = "HmdDriverFactory"; struct DriverLoader::Impl { /// Platform-specific handle to dynamic library #if defined(OSVR_WINDOWS) HMODULE driver_ = nullptr; #elif defined(OSVR_MACOSX) || defined(OSVR_LINUX) void *driver_ = nullptr; #endif /// Destructor: should contain platform-specific code to unload dynamic /// library. ~Impl() { #if defined(OSVR_WINDOWS) if (driver_) { FreeLibrary(driver_); } #elif defined(OSVR_MACOSX) || defined(OSVR_LINUX) if (driver_) { dlclose(driver_); } #endif } }; /// Constructor should contain platform-specific code to load dynamic /// library to populate handle in pimpl struct and extract the entry point /// function pointer. DriverLoader::DriverLoader(std::string const &driverRoot, std::string const &driverFile) : impl_(new Impl) { /// Set the PATH to include the driver directory so it can /// find its deps. SearchPathExtender extender(driverRoot); #if defined(OSVR_WINDOWS) impl_->driver_ = LoadLibraryA(driverFile.c_str()); if (!impl_->driver_) { reset(); throw CouldNotLoadDriverModule(); } auto proc = GetProcAddress(impl_->driver_, ENTRY_POINT_FUNCTION_NAME); if (!proc) { reset(); throw CouldNotLoadEntryPoint(); } factory_ = reinterpret_cast<DriverFactory>(proc); #elif defined(OSVR_LINUX) || defined(OSVR_MACOSX) impl_->driver_ = dlopen(driverFile.c_str()); if (!impl_->driver_) { reset(); throw CouldNotLoadDriverModule(dlerror()); } auto proc = dlsym(impl_->driver_, ENTRY_POINT_FUNCTION_NAME); if (!proc) { reset(); throw CouldNotLoadEntryPoint(dlerror()); } factory_ = reinterpret_cast<DriverFactory>(proc); \ #endif } std::unique_ptr<DriverLoader> DriverLoader::make(std::string const &driverRoot, std::string const &driverFile) { std::unique_ptr<DriverLoader> ret( new DriverLoader(driverRoot, driverFile)); return ret; } DriverLoader::~DriverLoader() { reset(); } DriverLoader::operator bool() const { /// Presence of a valid private impl object is equivalent to validity of /// the object overall. return static_cast<bool>(impl_); } bool DriverLoader::isHMDPresent(std::string const &userConfigDir) const { auto ret = getInterface<vr::IClientTrackedDeviceProvider>(); if (ret.first) { // std::cout << "Successfully got the // IClientTrackedDeviceProvider!"; auto clientProvider = ret.first; auto isPresent = clientProvider->BIsHmdPresent(userConfigDir.c_str()); // std::cout << " is present? " << std::boolalpha << isPresent // << std::endl; return isPresent; } // std::cout << "Couldn't get it, error code " << ret.second << // std::endl; return false; } void DriverLoader::reset() { if (cleanup_) { #if 0 std::cout << "osvr::vive::DriverLoader::reset() - cleaning " "up main provider" << std::endl; #endif cleanup_(); cleanup_ = std::function<void()>{}; } if (impl_) { #if 0 std::cout << "osvr::vive::DriverLoader::reset() - unloading driver" << std::endl; #endif impl_.reset(); } } } // namespace vive } // namespace osvr <commit_msg>Fix invalid dlopen() call. Use RTLD_NOW, so it will return error on opening, if there is unresolved symbols. Use RTLD_GLOBAL, so other libraries can access the driver, if it need<commit_after>/** @file @brief Implementation @date 2016 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2016 Razer 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. // Internal Includes #include "DriverLoader.h" #include "InterfaceTraits.h" #include "SearchPathExtender.h" // Library/third-party includes #include <osvr/Util/PlatformConfig.h> // Standard includes #include <iostream> #if defined(OSVR_WINDOWS) #define WIN32_LEAN_AND_MEAN #define NO_MINMAX #include <windows.h> #elif defined(OSVR_LINUX) || defined(OSVR_MACOSX) #include <dlfcn.h> #endif namespace osvr { namespace vive { static const auto ENTRY_POINT_FUNCTION_NAME = "HmdDriverFactory"; struct DriverLoader::Impl { /// Platform-specific handle to dynamic library #if defined(OSVR_WINDOWS) HMODULE driver_ = nullptr; #elif defined(OSVR_MACOSX) || defined(OSVR_LINUX) void *driver_ = nullptr; #endif /// Destructor: should contain platform-specific code to unload dynamic /// library. ~Impl() { #if defined(OSVR_WINDOWS) if (driver_) { FreeLibrary(driver_); } #elif defined(OSVR_MACOSX) || defined(OSVR_LINUX) if (driver_) { dlclose(driver_); } #endif } }; /// Constructor should contain platform-specific code to load dynamic /// library to populate handle in pimpl struct and extract the entry point /// function pointer. DriverLoader::DriverLoader(std::string const &driverRoot, std::string const &driverFile) : impl_(new Impl) { /// Set the PATH to include the driver directory so it can /// find its deps. SearchPathExtender extender(driverRoot); #if defined(OSVR_WINDOWS) impl_->driver_ = LoadLibraryA(driverFile.c_str()); if (!impl_->driver_) { reset(); throw CouldNotLoadDriverModule(); } auto proc = GetProcAddress(impl_->driver_, ENTRY_POINT_FUNCTION_NAME); if (!proc) { reset(); throw CouldNotLoadEntryPoint(); } factory_ = reinterpret_cast<DriverFactory>(proc); #elif defined(OSVR_LINUX) || defined(OSVR_MACOSX) impl_->driver_ = dlopen(driverFile.c_str(), RTLD_NOW | RTLD_GLOBAL); if (!impl_->driver_) { reset(); throw CouldNotLoadDriverModule(dlerror()); } auto proc = dlsym(impl_->driver_, ENTRY_POINT_FUNCTION_NAME); if (!proc) { reset(); throw CouldNotLoadEntryPoint(dlerror()); } factory_ = reinterpret_cast<DriverFactory>(proc); \ #endif } std::unique_ptr<DriverLoader> DriverLoader::make(std::string const &driverRoot, std::string const &driverFile) { std::unique_ptr<DriverLoader> ret( new DriverLoader(driverRoot, driverFile)); return ret; } DriverLoader::~DriverLoader() { reset(); } DriverLoader::operator bool() const { /// Presence of a valid private impl object is equivalent to validity of /// the object overall. return static_cast<bool>(impl_); } bool DriverLoader::isHMDPresent(std::string const &userConfigDir) const { auto ret = getInterface<vr::IClientTrackedDeviceProvider>(); if (ret.first) { // std::cout << "Successfully got the // IClientTrackedDeviceProvider!"; auto clientProvider = ret.first; auto isPresent = clientProvider->BIsHmdPresent(userConfigDir.c_str()); // std::cout << " is present? " << std::boolalpha << isPresent // << std::endl; return isPresent; } // std::cout << "Couldn't get it, error code " << ret.second << // std::endl; return false; } void DriverLoader::reset() { if (cleanup_) { #if 0 std::cout << "osvr::vive::DriverLoader::reset() - cleaning " "up main provider" << std::endl; #endif cleanup_(); cleanup_ = std::function<void()>{}; } if (impl_) { #if 0 std::cout << "osvr::vive::DriverLoader::reset() - unloading driver" << std::endl; #endif impl_.reset(); } } } // namespace vive } // namespace osvr <|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org> Copyright (C) 2001 Joseph Wenninger <jowenn@kde.org> Copyright (C) 2001 Anders Lund <anders.lund@lund.tdcadsl.dk> Copyright (C) 2007 Mirko Stocker <me@misto.ch> Copyright (C) 2009 Dominik Haumann <dhaumann 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 version 2 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 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. */ //BEGIN Includes #include "katefilebrowser.h" #include "katefilebrowser.moc" #include "katebookmarkhandler.h" #include <ktexteditor/document.h> #include <ktexteditor/view.h> #include <KActionCollection> #include <KActionMenu> #include <KConfigGroup> #include <KDebug> #include <KDirOperator> #include <KFilePlacesModel> #include <KHistoryComboBox> #include <KLocale> #include <KToolBar> #include <KUrlNavigator> #include <QAbstractItemView> #include <QDir> #include <QLabel> #include <QLineEdit> #include <QToolButton> #include <KMessageBox> #include <kdeversion.h> //END Includes KateFileBrowser::KateFileBrowser(Kate::MainWindow *mainWindow, QWidget * parent, const char * name) : KVBox (parent) , m_mainWindow(mainWindow) { setObjectName(name); m_toolbar = new KToolBar(this); m_toolbar->setMovable(false); m_toolbar->setToolButtonStyle(Qt::ToolButtonIconOnly); m_toolbar->setContextMenuPolicy(Qt::NoContextMenu); // includes some actions, but not hooked into the shortcut dialog atm m_actionCollection = new KActionCollection(this); m_actionCollection->addAssociatedWidget(this); KFilePlacesModel* model = new KFilePlacesModel(this); m_urlNavigator = new KUrlNavigator(model, KUrl(QDir::homePath()), this); connect(m_urlNavigator, SIGNAL(urlChanged(KUrl)), SLOT(updateDirOperator(KUrl))); m_dirOperator = new KDirOperator(KUrl(), this); m_dirOperator->setView(KFile::/* Simple */Detail); m_dirOperator->view()->setSelectionMode(QAbstractItemView::ExtendedSelection); m_dirOperator->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); #if KDE_IS_VERSION(4, 4, 60) // Mime filter for the KDirOperator QStringList filter; filter << "text/plain" << "text/html" << "inode/directory"; m_dirOperator->setNewFileMenuSupportedMimeTypes(filter); #endif setFocusProxy(m_dirOperator); connect(m_dirOperator, SIGNAL(viewChanged(QAbstractItemView*)), this, SLOT(selectorViewChanged(QAbstractItemView*))); connect(m_urlNavigator, SIGNAL(returnPressed()), m_dirOperator, SLOT(setFocus())); // now all actions exist in dir operator and we can use them in the toolbar setupActions(); setupToolbar(); KHBox* filterBox = new KHBox(this); QLabel* filterLabel = new QLabel(i18n("Filter:"), filterBox); m_filter = new KHistoryComboBox(true, filterBox); filterLabel->setBuddy(m_filter); m_filter->setMaxCount(10); m_filter->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed)); connect(m_filter, SIGNAL(editTextChanged(QString)), SLOT(slotFilterChange(QString))); connect(m_filter, SIGNAL(returnPressed(QString)), m_filter, SLOT(addToHistory(QString))); connect(m_filter, SIGNAL(returnPressed(QString)), m_dirOperator, SLOT(setFocus())); connect(m_dirOperator, SIGNAL(urlEntered(KUrl)), this, SLOT(updateUrlNavigator(KUrl))); // Connect the bookmark handler connect(m_bookmarkHandler, SIGNAL(openUrl(QString)), this, SLOT(setDir(QString))); m_filter->setWhatsThis(i18n("Enter a name filter to limit which files are displayed.")); connect(m_dirOperator, SIGNAL(fileSelected(KFileItem)), this, SLOT(fileSelected(KFileItem))); connect(m_mainWindow, SIGNAL(viewChanged()), this, SLOT(autoSyncFolder())); } KateFileBrowser::~KateFileBrowser() { } //END Constroctor/Destrctor //BEGIN Public Methods void KateFileBrowser::setupToolbar() { KConfigGroup config(KGlobal::config(), "filebrowser"); QStringList actions = config.readEntry( "toolbar actions", QStringList() ); if ( actions.isEmpty() ) // default toolbar actions << "back" << "forward" << "bookmarks" << "sync_dir" << "configure"; // remove all actions from the toolbar (there should be none) m_toolbar->clear(); // now add all actions to the toolbar foreach (const QString& it, actions) { QAction *ac = 0; if (it.isEmpty()) continue; if (it == "bookmarks" || it == "sync_dir" || it == "configure") ac = actionCollection()->action(it); else ac = m_dirOperator->actionCollection()->action(it); if (ac) m_toolbar->addAction(ac); } } void KateFileBrowser::readSessionConfig(KConfigBase *config, const QString & name) { KConfigGroup cgDir(config, name + ":dir"); m_dirOperator->readConfig(cgDir); m_dirOperator->setView(KFile::Default); KConfigGroup cg(config, name); m_urlNavigator->setLocationUrl(cg.readPathEntry("location", QDir::homePath())); setDir(cg.readPathEntry("location", QDir::homePath())); m_autoSyncFolder->setChecked(cg.readEntry("auto sync folder", false)); m_filter->setHistoryItems(cg.readEntry("filter history", QStringList()), true); } void KateFileBrowser::writeSessionConfig(KConfigBase *config, const QString & name) { KConfigGroup cgDir(config, name + ":dir"); m_dirOperator->writeConfig(cgDir); KConfigGroup cg = KConfigGroup(config, name); cg.writePathEntry("location", m_urlNavigator->locationUrl().url()); cg.writeEntry("auto sync folder", m_autoSyncFolder->isChecked()); cg.writeEntry("filter history", m_filter->historyItems()); } //END Public Methods //BEGIN Public Slots void KateFileBrowser::slotFilterChange(const QString & nf) { QString f = nf.trimmed(); const bool empty = f.isEmpty() || f == "*"; if (empty) { m_dirOperator->clearFilter(); } else { m_dirOperator->setNameFilter(f); } m_dirOperator->updateDir(); } bool kateFileSelectorIsReadable (const KUrl& url) { if (!url.isLocalFile()) return true; // what else can we say? QDir dir(url.toLocalFile()); return dir.exists (); } void KateFileBrowser::setDir(KUrl u) { KUrl newurl; if (!u.isValid()) newurl.setPath(QDir::homePath()); else newurl = u; QString pathstr = newurl.path(KUrl::AddTrailingSlash); newurl.setPath(pathstr); if (!kateFileSelectorIsReadable (newurl)) newurl.cd(QString::fromLatin1("..")); if (!kateFileSelectorIsReadable (newurl)) newurl.setPath(QDir::homePath()); m_dirOperator->setUrl(newurl, true); } //END Public Slots //BEGIN Private Slots void KateFileBrowser::fileSelected(const KFileItem & /*file*/) { openSelectedFiles(); } void KateFileBrowser::openSelectedFiles() { const KFileItemList list = m_dirOperator->selectedItems(); if (list.count()>20) { if (KMessageBox::questionYesNo(this,i18n("You are trying to open %1 files, are your sure?").arg(list.count())) == KMessageBox::No) return; } foreach (const KFileItem& item, list) { m_mainWindow->openUrl(item.url()); } m_dirOperator->view()->selectionModel()->clear(); } void KateFileBrowser::updateDirOperator(const KUrl& u) { m_dirOperator->setUrl(u, true); } void KateFileBrowser::updateUrlNavigator(const KUrl& u) { m_urlNavigator->setLocationUrl(u); } void KateFileBrowser::setActiveDocumentDir() { // kDebug(13001)<<"KateFileBrowser::setActiveDocumentDir()"; KUrl u = activeDocumentUrl(); // kDebug(13001)<<"URL: "<<u.pathOrUrl(); if (!u.isEmpty()) setDir(u.upUrl()); // kDebug(13001)<<"... setActiveDocumentDir() DONE!"; } void KateFileBrowser::autoSyncFolder() { if (m_autoSyncFolder->isChecked()) { setActiveDocumentDir(); } } void KateFileBrowser::selectorViewChanged(QAbstractItemView * newView) { newView->setSelectionMode(QAbstractItemView::ExtendedSelection); } //END Private Slots //BEGIN Protected KUrl KateFileBrowser::activeDocumentUrl() { KTextEditor::View *v = m_mainWindow->activeView(); if (v) return v->document()->url(); return KUrl(); } void KateFileBrowser::setupActions() { // bookmarks action! KActionMenu *acmBookmarks = new KActionMenu(KIcon("bookmarks"), i18n("Bookmarks"), this); acmBookmarks->setDelayed(false); m_bookmarkHandler = new KateBookmarkHandler(this, acmBookmarks->menu()); acmBookmarks->setShortcutContext(Qt::WidgetWithChildrenShortcut); // action for synchronizing the dir operator with the current document path KAction* syncFolder = new KAction(this); syncFolder->setShortcutContext(Qt::WidgetWithChildrenShortcut); syncFolder->setText(i18n("Current Document Folder")); syncFolder->setIcon(KIcon("system-switch-user")); connect(syncFolder, SIGNAL(triggered()), this, SLOT(setActiveDocumentDir())); m_actionCollection->addAction("sync_dir", syncFolder); m_actionCollection->addAction("bookmarks", acmBookmarks); // section for settings menu KActionMenu *optionsMenu = new KActionMenu(KIcon("configure"), i18n("Options"), this); optionsMenu->setDelayed(false); optionsMenu->addAction(m_dirOperator->actionCollection()->action("short view")); optionsMenu->addAction(m_dirOperator->actionCollection()->action("detailed view")); optionsMenu->addAction(m_dirOperator->actionCollection()->action("tree view")); optionsMenu->addAction(m_dirOperator->actionCollection()->action("detailed tree view")); optionsMenu->addSeparator(); optionsMenu->addAction(m_dirOperator->actionCollection()->action("show hidden")); // action for synchronising the dir operator with the current document path m_autoSyncFolder = new KAction(this); m_autoSyncFolder->setCheckable(true); m_autoSyncFolder->setText(i18n("Automatically synchronize with current document")); m_autoSyncFolder->setIcon(KIcon("system-switch-user")); connect(m_autoSyncFolder, SIGNAL(triggered()), this, SLOT(autoSyncFolder())); optionsMenu->addAction(m_autoSyncFolder); m_actionCollection->addAction("configure", optionsMenu); // // Remove all shortcuts due to shortcut clashes (e.g. F5: reload, Ctrl+B: bookmark) // BUGS: #188954, #236368 // foreach (QAction* a, m_actionCollection->actions()) { a->setShortcut(QKeySequence()); } foreach (QAction* a, m_dirOperator->actionCollection()->actions()) { a->setShortcut(QKeySequence()); } } //END Protected // kate: space-indent on; indent-width 2; replace-tabs on; <commit_msg>i18n: properly use plural form and pass arguments to i18n*()<commit_after>/* This file is part of the KDE project Copyright (C) 2001 Christoph Cullmann <cullmann@kde.org> Copyright (C) 2001 Joseph Wenninger <jowenn@kde.org> Copyright (C) 2001 Anders Lund <anders.lund@lund.tdcadsl.dk> Copyright (C) 2007 Mirko Stocker <me@misto.ch> Copyright (C) 2009 Dominik Haumann <dhaumann 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 version 2 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 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. */ //BEGIN Includes #include "katefilebrowser.h" #include "katefilebrowser.moc" #include "katebookmarkhandler.h" #include <ktexteditor/document.h> #include <ktexteditor/view.h> #include <KActionCollection> #include <KActionMenu> #include <KConfigGroup> #include <KDebug> #include <KDirOperator> #include <KFilePlacesModel> #include <KHistoryComboBox> #include <KLocale> #include <KToolBar> #include <KUrlNavigator> #include <QAbstractItemView> #include <QDir> #include <QLabel> #include <QLineEdit> #include <QToolButton> #include <KMessageBox> #include <kdeversion.h> //END Includes KateFileBrowser::KateFileBrowser(Kate::MainWindow *mainWindow, QWidget * parent, const char * name) : KVBox (parent) , m_mainWindow(mainWindow) { setObjectName(name); m_toolbar = new KToolBar(this); m_toolbar->setMovable(false); m_toolbar->setToolButtonStyle(Qt::ToolButtonIconOnly); m_toolbar->setContextMenuPolicy(Qt::NoContextMenu); // includes some actions, but not hooked into the shortcut dialog atm m_actionCollection = new KActionCollection(this); m_actionCollection->addAssociatedWidget(this); KFilePlacesModel* model = new KFilePlacesModel(this); m_urlNavigator = new KUrlNavigator(model, KUrl(QDir::homePath()), this); connect(m_urlNavigator, SIGNAL(urlChanged(KUrl)), SLOT(updateDirOperator(KUrl))); m_dirOperator = new KDirOperator(KUrl(), this); m_dirOperator->setView(KFile::/* Simple */Detail); m_dirOperator->view()->setSelectionMode(QAbstractItemView::ExtendedSelection); m_dirOperator->setSizePolicy(QSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding)); #if KDE_IS_VERSION(4, 4, 60) // Mime filter for the KDirOperator QStringList filter; filter << "text/plain" << "text/html" << "inode/directory"; m_dirOperator->setNewFileMenuSupportedMimeTypes(filter); #endif setFocusProxy(m_dirOperator); connect(m_dirOperator, SIGNAL(viewChanged(QAbstractItemView*)), this, SLOT(selectorViewChanged(QAbstractItemView*))); connect(m_urlNavigator, SIGNAL(returnPressed()), m_dirOperator, SLOT(setFocus())); // now all actions exist in dir operator and we can use them in the toolbar setupActions(); setupToolbar(); KHBox* filterBox = new KHBox(this); QLabel* filterLabel = new QLabel(i18n("Filter:"), filterBox); m_filter = new KHistoryComboBox(true, filterBox); filterLabel->setBuddy(m_filter); m_filter->setMaxCount(10); m_filter->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed)); connect(m_filter, SIGNAL(editTextChanged(QString)), SLOT(slotFilterChange(QString))); connect(m_filter, SIGNAL(returnPressed(QString)), m_filter, SLOT(addToHistory(QString))); connect(m_filter, SIGNAL(returnPressed(QString)), m_dirOperator, SLOT(setFocus())); connect(m_dirOperator, SIGNAL(urlEntered(KUrl)), this, SLOT(updateUrlNavigator(KUrl))); // Connect the bookmark handler connect(m_bookmarkHandler, SIGNAL(openUrl(QString)), this, SLOT(setDir(QString))); m_filter->setWhatsThis(i18n("Enter a name filter to limit which files are displayed.")); connect(m_dirOperator, SIGNAL(fileSelected(KFileItem)), this, SLOT(fileSelected(KFileItem))); connect(m_mainWindow, SIGNAL(viewChanged()), this, SLOT(autoSyncFolder())); } KateFileBrowser::~KateFileBrowser() { } //END Constroctor/Destrctor //BEGIN Public Methods void KateFileBrowser::setupToolbar() { KConfigGroup config(KGlobal::config(), "filebrowser"); QStringList actions = config.readEntry( "toolbar actions", QStringList() ); if ( actions.isEmpty() ) // default toolbar actions << "back" << "forward" << "bookmarks" << "sync_dir" << "configure"; // remove all actions from the toolbar (there should be none) m_toolbar->clear(); // now add all actions to the toolbar foreach (const QString& it, actions) { QAction *ac = 0; if (it.isEmpty()) continue; if (it == "bookmarks" || it == "sync_dir" || it == "configure") ac = actionCollection()->action(it); else ac = m_dirOperator->actionCollection()->action(it); if (ac) m_toolbar->addAction(ac); } } void KateFileBrowser::readSessionConfig(KConfigBase *config, const QString & name) { KConfigGroup cgDir(config, name + ":dir"); m_dirOperator->readConfig(cgDir); m_dirOperator->setView(KFile::Default); KConfigGroup cg(config, name); m_urlNavigator->setLocationUrl(cg.readPathEntry("location", QDir::homePath())); setDir(cg.readPathEntry("location", QDir::homePath())); m_autoSyncFolder->setChecked(cg.readEntry("auto sync folder", false)); m_filter->setHistoryItems(cg.readEntry("filter history", QStringList()), true); } void KateFileBrowser::writeSessionConfig(KConfigBase *config, const QString & name) { KConfigGroup cgDir(config, name + ":dir"); m_dirOperator->writeConfig(cgDir); KConfigGroup cg = KConfigGroup(config, name); cg.writePathEntry("location", m_urlNavigator->locationUrl().url()); cg.writeEntry("auto sync folder", m_autoSyncFolder->isChecked()); cg.writeEntry("filter history", m_filter->historyItems()); } //END Public Methods //BEGIN Public Slots void KateFileBrowser::slotFilterChange(const QString & nf) { QString f = nf.trimmed(); const bool empty = f.isEmpty() || f == "*"; if (empty) { m_dirOperator->clearFilter(); } else { m_dirOperator->setNameFilter(f); } m_dirOperator->updateDir(); } bool kateFileSelectorIsReadable (const KUrl& url) { if (!url.isLocalFile()) return true; // what else can we say? QDir dir(url.toLocalFile()); return dir.exists (); } void KateFileBrowser::setDir(KUrl u) { KUrl newurl; if (!u.isValid()) newurl.setPath(QDir::homePath()); else newurl = u; QString pathstr = newurl.path(KUrl::AddTrailingSlash); newurl.setPath(pathstr); if (!kateFileSelectorIsReadable (newurl)) newurl.cd(QString::fromLatin1("..")); if (!kateFileSelectorIsReadable (newurl)) newurl.setPath(QDir::homePath()); m_dirOperator->setUrl(newurl, true); } //END Public Slots //BEGIN Private Slots void KateFileBrowser::fileSelected(const KFileItem & /*file*/) { openSelectedFiles(); } void KateFileBrowser::openSelectedFiles() { const KFileItemList list = m_dirOperator->selectedItems(); if (list.count()>20) { if (KMessageBox::questionYesNo(this,i18np("You are trying to open 1 file, are your sure?", "You are trying to open %1 files, are your sure?", list.count())) == KMessageBox::No) return; } foreach (const KFileItem& item, list) { m_mainWindow->openUrl(item.url()); } m_dirOperator->view()->selectionModel()->clear(); } void KateFileBrowser::updateDirOperator(const KUrl& u) { m_dirOperator->setUrl(u, true); } void KateFileBrowser::updateUrlNavigator(const KUrl& u) { m_urlNavigator->setLocationUrl(u); } void KateFileBrowser::setActiveDocumentDir() { // kDebug(13001)<<"KateFileBrowser::setActiveDocumentDir()"; KUrl u = activeDocumentUrl(); // kDebug(13001)<<"URL: "<<u.pathOrUrl(); if (!u.isEmpty()) setDir(u.upUrl()); // kDebug(13001)<<"... setActiveDocumentDir() DONE!"; } void KateFileBrowser::autoSyncFolder() { if (m_autoSyncFolder->isChecked()) { setActiveDocumentDir(); } } void KateFileBrowser::selectorViewChanged(QAbstractItemView * newView) { newView->setSelectionMode(QAbstractItemView::ExtendedSelection); } //END Private Slots //BEGIN Protected KUrl KateFileBrowser::activeDocumentUrl() { KTextEditor::View *v = m_mainWindow->activeView(); if (v) return v->document()->url(); return KUrl(); } void KateFileBrowser::setupActions() { // bookmarks action! KActionMenu *acmBookmarks = new KActionMenu(KIcon("bookmarks"), i18n("Bookmarks"), this); acmBookmarks->setDelayed(false); m_bookmarkHandler = new KateBookmarkHandler(this, acmBookmarks->menu()); acmBookmarks->setShortcutContext(Qt::WidgetWithChildrenShortcut); // action for synchronizing the dir operator with the current document path KAction* syncFolder = new KAction(this); syncFolder->setShortcutContext(Qt::WidgetWithChildrenShortcut); syncFolder->setText(i18n("Current Document Folder")); syncFolder->setIcon(KIcon("system-switch-user")); connect(syncFolder, SIGNAL(triggered()), this, SLOT(setActiveDocumentDir())); m_actionCollection->addAction("sync_dir", syncFolder); m_actionCollection->addAction("bookmarks", acmBookmarks); // section for settings menu KActionMenu *optionsMenu = new KActionMenu(KIcon("configure"), i18n("Options"), this); optionsMenu->setDelayed(false); optionsMenu->addAction(m_dirOperator->actionCollection()->action("short view")); optionsMenu->addAction(m_dirOperator->actionCollection()->action("detailed view")); optionsMenu->addAction(m_dirOperator->actionCollection()->action("tree view")); optionsMenu->addAction(m_dirOperator->actionCollection()->action("detailed tree view")); optionsMenu->addSeparator(); optionsMenu->addAction(m_dirOperator->actionCollection()->action("show hidden")); // action for synchronising the dir operator with the current document path m_autoSyncFolder = new KAction(this); m_autoSyncFolder->setCheckable(true); m_autoSyncFolder->setText(i18n("Automatically synchronize with current document")); m_autoSyncFolder->setIcon(KIcon("system-switch-user")); connect(m_autoSyncFolder, SIGNAL(triggered()), this, SLOT(autoSyncFolder())); optionsMenu->addAction(m_autoSyncFolder); m_actionCollection->addAction("configure", optionsMenu); // // Remove all shortcuts due to shortcut clashes (e.g. F5: reload, Ctrl+B: bookmark) // BUGS: #188954, #236368 // foreach (QAction* a, m_actionCollection->actions()) { a->setShortcut(QKeySequence()); } foreach (QAction* a, m_dirOperator->actionCollection()->actions()) { a->setShortcut(QKeySequence()); } } //END Protected // kate: space-indent on; indent-width 2; replace-tabs on; <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <vector.hpp> #include <string.hpp> #include "ethernet_layer.hpp" #include "logging.hpp" #include "kernel_utils.hpp" #include "arp_layer.hpp" namespace { network::ethernet::ether_type decode_ether_type(network::ethernet::header* header){ auto type = switch_endian_16(header->type); if(type == 0x800){ return network::ethernet::ether_type::IPV4; } else if(type == 0x86DD){ return network::ethernet::ether_type::IPV6; } else if(type == 0x806){ return network::ethernet::ether_type::ARP; } else { return network::ethernet::ether_type::UNKNOWN; } } uint16_t type_to_code(network::ethernet::ether_type type){ switch(type){ case network::ethernet::ether_type::IPV4: return 0x800; case network::ethernet::ether_type::IPV6: return 0x86DD; case network::ethernet::ether_type::ARP: return 0x806; case network::ethernet::ether_type::UNKNOWN: logging::logf(logging::log_level::ERROR, "ethernet: Decoding UNKOWN code\n"); return 0x0; } } } //end of anonymous namespace void network::ethernet::decode(network::interface_descriptor& interface, packet& packet){ header* ether_header = reinterpret_cast<header*>(packet.payload); // Filter out non-ethernet II frames if(switch_endian_16(ether_header->type) < 1536){ logging::logf(logging::log_level::ERROR, "ethernet: error only ethernet frame type II is supported\n"); return; } size_t source_mac = 0; size_t target_mac = 0; for(size_t i = 0; i < 6; ++i){ source_mac |= uint64_t(ether_header->source.mac[i]) << ((5 - i) * 8); target_mac |= uint64_t(ether_header->target.mac[i]) << ((5 - i) * 8); } logging::logf(logging::log_level::TRACE, "ethernet: Source MAC Address %h \n", source_mac); logging::logf(logging::log_level::TRACE, "ethernet: Destination MAC Address %h \n", target_mac); packet.type = decode_ether_type(ether_header); packet.index += sizeof(header); switch(packet.type){ case ether_type::IPV4: logging::logf(logging::log_level::TRACE, "ethernet: IPV4 Packet (unsupported)\n"); break; case ether_type::IPV6: logging::logf(logging::log_level::TRACE, "ethernet: IPV6 Packet (unsupported)\n"); break; case ether_type::ARP: network::arp::decode(interface, packet); break; case ether_type::UNKNOWN: logging::logf(logging::log_level::TRACE, "ethernet: Unhandled Packet Type: %u\n", uint64_t(switch_endian_16(ether_header->type))); break; } } network::ethernet::packet network::ethernet::prepare_packet(network::interface_descriptor& interface, size_t size, size_t destination, ether_type type){ auto total_size = size + sizeof(header); network::ethernet::packet p(new char[total_size], total_size); p.type = type; p.index = sizeof(header); auto source_mac = interface.mac_address; auto* ether_header = reinterpret_cast<header*>(p.payload); ether_header->type = switch_endian_16(type_to_code(type)); for(size_t i = 0; i < 6; ++i){ ether_header->source.mac[i] = (source_mac >> ((5 - i) * 8)); ether_header->target.mac[i] = (destination >> ((5 - i) * 8)); } return p; } void network::ethernet::finalize_packet(network::interface_descriptor& interface, packet& p){ interface.send(p); } <commit_msg>Safety net<commit_after>//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <vector.hpp> #include <string.hpp> #include "ethernet_layer.hpp" #include "logging.hpp" #include "kernel_utils.hpp" #include "arp_layer.hpp" namespace { network::ethernet::ether_type decode_ether_type(network::ethernet::header* header){ auto type = switch_endian_16(header->type); if(type == 0x800){ return network::ethernet::ether_type::IPV4; } else if(type == 0x86DD){ return network::ethernet::ether_type::IPV6; } else if(type == 0x806){ return network::ethernet::ether_type::ARP; } else { return network::ethernet::ether_type::UNKNOWN; } } uint16_t type_to_code(network::ethernet::ether_type type){ switch(type){ case network::ethernet::ether_type::IPV4: return 0x800; case network::ethernet::ether_type::IPV6: return 0x86DD; case network::ethernet::ether_type::ARP: return 0x806; case network::ethernet::ether_type::UNKNOWN: logging::logf(logging::log_level::ERROR, "ethernet: Decoding UNKOWN code\n"); return 0x0; } } } //end of anonymous namespace void network::ethernet::decode(network::interface_descriptor& interface, packet& packet){ header* ether_header = reinterpret_cast<header*>(packet.payload); // Filter out non-ethernet II frames if(switch_endian_16(ether_header->type) < 1536){ logging::logf(logging::log_level::ERROR, "ethernet: error only ethernet frame type II is supported\n"); return; } size_t source_mac = 0; size_t target_mac = 0; for(size_t i = 0; i < 6; ++i){ source_mac |= uint64_t(ether_header->source.mac[i]) << ((5 - i) * 8); target_mac |= uint64_t(ether_header->target.mac[i]) << ((5 - i) * 8); } logging::logf(logging::log_level::TRACE, "ethernet: Source MAC Address %h \n", source_mac); logging::logf(logging::log_level::TRACE, "ethernet: Destination MAC Address %h \n", target_mac); packet.type = decode_ether_type(ether_header); packet.index += sizeof(header); switch(packet.type){ case ether_type::IPV4: logging::logf(logging::log_level::TRACE, "ethernet: IPV4 Packet (unsupported)\n"); break; case ether_type::IPV6: logging::logf(logging::log_level::TRACE, "ethernet: IPV6 Packet (unsupported)\n"); break; case ether_type::ARP: network::arp::decode(interface, packet); break; case ether_type::UNKNOWN: logging::logf(logging::log_level::TRACE, "ethernet: Unhandled Packet Type: %u\n", uint64_t(switch_endian_16(ether_header->type))); break; default: logging::logf(logging::log_level::ERROR, "ethernet: Unhandled Packet Type in switch: %u\n", uint64_t(switch_endian_16(ether_header->type))); break; } } network::ethernet::packet network::ethernet::prepare_packet(network::interface_descriptor& interface, size_t size, size_t destination, ether_type type){ auto total_size = size + sizeof(header); network::ethernet::packet p(new char[total_size], total_size); p.type = type; p.index = sizeof(header); auto source_mac = interface.mac_address; auto* ether_header = reinterpret_cast<header*>(p.payload); ether_header->type = switch_endian_16(type_to_code(type)); for(size_t i = 0; i < 6; ++i){ ether_header->source.mac[i] = (source_mac >> ((5 - i) * 8)); ether_header->target.mac[i] = (destination >> ((5 - i) * 8)); } return p; } void network::ethernet::finalize_packet(network::interface_descriptor& interface, packet& p){ interface.send(p); } <|endoftext|>
<commit_before>/* * File: updates.cpp * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS) */ #include "common/sedna.h" #include "tr/updates/updates.h" #include "tr/mo/mo.h" #include "tr/crmutils/node_utils.h" #include "tr/executor/base/xptr_sequence.h" #include "tr/nid/numb_scheme.h" #include "tr/executor/xqops/PPConstructors.h" #include "tr/mo/indirection.h" #ifdef SE_ENABLE_TRIGGERS #include "tr/triggers/triggers.h" #endif #define IGNORE_UPDATE_ERRORS #ifdef SE_ENABLE_FTSEARCH std::map<ft_index_cell_xptr,update_history*> ft_updates; #endif #ifdef SE_ENABLE_FTSEARCH void clear_ft_sequences() { std::map<ft_index_cell_xptr,update_history*>::iterator it=ft_updates.begin(); while (it!=ft_updates.end()) { delete it->second; it++; } ft_updates.clear(); } void execute_modifications() { if (indirectionGetRollbackMode()) return; std::map<ft_index_cell_xptr,update_history*>::iterator it=ft_updates.begin(); while (it!=ft_updates.end()) { it->first->update_index(it->second); it++; } } void update_insert_sequence(xptr node,ft_index_cell_cptr icell) { std::map<ft_index_cell_xptr,update_history*>::iterator it=ft_updates.find(icell.ptr()); if (it==ft_updates.end()) { update_history *h=se_new update_history(); h->add_insert_node(node); ft_updates[icell.ptr()]=h; } else it->second->add_insert_node(node); } void update_update_sequence(xptr node,ft_index_cell_cptr icell) { std::map<ft_index_cell_xptr,update_history*>::iterator it=ft_updates.find(icell.ptr()); if (it==ft_updates.end()) { update_history *h=se_new update_history(); h->add_update_node(node); ft_updates[icell.ptr()]=h; } else it->second->add_update_node(node); } void update_delete_sequence(xptr node,ft_index_cell_cptr icell) { std::map<ft_index_cell_xptr,update_history*>::iterator it=ft_updates.find(icell.ptr()); if (it==ft_updates.end()) { update_history* h=se_new update_history(); h->add_delete_node(node); ft_updates[icell.ptr()]=h; } else it->second->add_delete_node(node); } void update_insert_sequence(xptr node,schema_node_cptr icell) { cat_list<ft_index_cell_xptr>::item* obj=icell->ft_index_list.first; if (obj == NULL) return; CHECKP(node); xptr ind=((n_dsc*)XADDR(node))->indir; while (obj!=NULL) { update_insert_sequence(ind,ft_index_cell_cptr(obj->object)); obj=obj->next; } CHECKP(node); } void update_update_sequence(xptr node,schema_node_cptr icell) { cat_list<ft_index_cell_xptr>::item* obj=icell->ft_index_list.first; if (obj==NULL) return; CHECKP(node); xptr ind=((n_dsc*)XADDR(node))->indir; while (obj!=NULL) { update_update_sequence(ind,ft_index_cell_cptr(obj->object)); obj=obj->next; } CHECKP(node); } void update_delete_sequence(xptr node,schema_node_cptr icell) { cat_list<ft_index_cell_xptr>::item* obj=icell->ft_index_list.first; if (obj==NULL) return; CHECKP(node); xptr ind=((n_dsc*)XADDR(node))->indir; while (obj!=NULL) { update_delete_sequence(ind,ft_index_cell_cptr(obj->object)); obj=obj->next; } CHECKP(node); } void init_ft_sequences (const xptr& left, const xptr& right, const xptr& parent) { if (IS_TMP_BLOCK(left)||IS_TMP_BLOCK(right)||IS_TMP_BLOCK(parent)) return; xptr tmp; schema_node_cptr scn = XNULL; if (parent!=XNULL) { tmp=parent; CHECKP(parent); scn=(GETBLOCKBYNODE(parent))->snode; } else { tmp=(left==XNULL)?right:left; CHECKP(tmp); scn=(GETBLOCKBYNODE(tmp))->snode->parent; } if (scn->root == scn.ptr() || scn->root->full_ft_index_list.empty()) return; while (scn.found()) { cat_list<ft_index_cell_xptr>::item* obj=scn->ft_index_list.first; if (obj!=NULL) { tmp=getNodeAncestorIndirectionByScheme(tmp,scn); while (obj!=NULL) { update_update_sequence(tmp,ft_index_cell_cptr(obj->object)); obj=obj->next; } tmp=removeIndirection(tmp); } scn=scn->parent; } } #endif xptr copy_node_content(xptr new_node_i, xptr node, xptr left_node_i, upd_ns_map** nsupdmap, bool save_types, unsigned short depth) { xptr left_node = XNULL; xptr childi = getIndirectionSafeCP(getFirstByOrderChildCP(node)); while (childi != XNULL) { left_node = deep_copy_node_i(left_node_i, XNULL, new_node_i, indirectionDereferenceCP(childi), nsupdmap, save_types, depth + 1); /* due to : MG: deep_temp_copy can return XNULL if a trigger canceled * the insertion and there were now any left sibling */ if (left_node != XNULL) { left_node_i = getIndirectionSafeCP(left_node); } childi = getRightSiblingIndirectionCP(indirectionDereferenceCP(childi)); } return left_node_i; } void swizzleNamespace (xmlns_ptr & ns, upd_ns_map*& updmap) { if (updmap == NULL) updmap = se_new upd_ns_map; upd_ns_map::const_iterator it = updmap->find(ns); if (it == updmap->end()) { ns = xmlns_touch(ns->prefix, ns->uri); } else { ns = it->second; } } xptr deep_copy_node(xptr left, xptr right, xptr parent, xptr node, upd_ns_map** nsupdmap, bool save_types, unsigned short depth) { xptr result; xptr node_indir; schema_node_cptr scmnode; xmlscm_type scm_type; #ifdef SE_ENABLE_FTSEARCH if (!depth) init_ft_sequences(left,right,parent); #endif #ifdef SE_ENABLE_TRIGGERS if (parent == XNULL) { if (left != XNULL) { CHECKP(left); parent = removeIndirection(((n_dsc*) XADDR(left))->pdsc); } else { CHECKP(right); parent = removeIndirection(((n_dsc*) XADDR(right))->pdsc); } } node = apply_per_node_triggers(node, XNULL, parent, XNULL, TRIGGER_BEFORE, TRIGGER_INSERT_EVENT); if (node == XNULL) { if (left == XNULL) { return XNULL; } CHECKP(left); return left; } #endif node_indir = getIndirectionSafeCP(node); scmnode = getBlockHeaderCP(node)->snode; switch (scmnode->type) { case element: { xptr result_indir; xmlns_ptr ns = scmnode->get_xmlns(); if (nsupdmap != NULL && ns != NULL_XMLNS) { swizzleNamespace(ns, *nsupdmap); } scm_type = (save_types) ? E_DSC(node)->type : xs_untyped; result = insert_element(left, right, parent, scmnode->name, scm_type, ns); result_indir = get_last_mo_inderection(); copy_node_content(result_indir, indirectionDereferenceCP(node_indir), XNULL, nsupdmap, save_types, depth); result = indirectionDereferenceCP(result_indir); CHECKP(result); } break; case text: { if (isTextEmpty(T_DSC(node))) { throw SYSTEM_EXCEPTION("BAD DATA!!!"); } else { xptr data = getTextPtr(T_DSC(node)); CHECKP(node); result = insert_text(left, right, parent, &data, getTextSize(T_DSC(node)), text_doc); } } break; case cdata: { text_cptr buf(node); result = insert_cdata(left, right, parent, buf.get(), buf.getSize()); } break; case comment: { text_cptr buf(node); result = insert_comment(left, right, parent, buf.get(), buf.getSize()); } break; case pr_ins: { size_t tsize = PI_DSC(node)->target; text_cptr buf(node); result = insert_pi(left, right, parent, buf.get(), tsize, buf.get() + tsize + 1, buf.getSize() - tsize - 1); } break; case attribute: { xmlns_ptr ns = scmnode->get_xmlns(); text_cptr buf(node); if (nsupdmap != NULL && ns != NULL_XMLNS) { swizzleNamespace(ns, *nsupdmap); } CHECKP(node); scm_type = (save_types) ? A_DSC(node)->type : xs_untypedAtomic; result = insert_attribute(left, right, parent, scmnode->name, scm_type, buf.get(), buf.getSize(), ns); } break; case xml_namespace: { xmlns_ptr ns = xmlns_touch(NS_DSC(node)->ns); if (nsupdmap != NULL && ns != NULL_XMLNS) { swizzleNamespace(ns, *nsupdmap); } result = insert_namespace(left, right, parent, ns); } break; default: throw SYSTEM_EXCEPTION("Deep copy error: document node copied"); } CHECKP(result); #ifdef SE_ENABLE_FTSEARCH update_insert_sequence(result, schema_node_cptr((GETBLOCKBYNODE(result))->snode)); #endif #ifdef SE_ENABLE_TRIGGERS if (parent==XNULL) parent=removeIndirection(((n_dsc*)XADDR(left))->pdsc); apply_per_node_triggers(result, XNULL, parent, XNULL, TRIGGER_AFTER, TRIGGER_INSERT_EVENT); #endif CHECKP(result); return result; } xptr copy_to_temp(xptr node) { PPConstructor::checkInitial(); return deep_copy_node(XNULL, XNULL, PPConstructor::get_virtual_root(), node, NULL, true); } <commit_msg>full-text updates fix<commit_after>/* * File: updates.cpp * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS) */ #include "common/sedna.h" #include "tr/updates/updates.h" #include "tr/mo/mo.h" #include "tr/crmutils/node_utils.h" #include "tr/executor/base/xptr_sequence.h" #include "tr/nid/numb_scheme.h" #include "tr/executor/xqops/PPConstructors.h" #include "tr/mo/indirection.h" #ifdef SE_ENABLE_TRIGGERS #include "tr/triggers/triggers.h" #endif #define IGNORE_UPDATE_ERRORS #ifdef SE_ENABLE_FTSEARCH std::map<ft_index_cell_xptr,update_history*> ft_updates; #endif #ifdef SE_ENABLE_FTSEARCH void clear_ft_sequences() { std::map<ft_index_cell_xptr,update_history*>::iterator it=ft_updates.begin(); while (it!=ft_updates.end()) { delete it->second; it++; } ft_updates.clear(); } void execute_modifications() { if (indirectionGetRollbackMode()) return; std::map<ft_index_cell_xptr,update_history*>::iterator it=ft_updates.begin(); while (it!=ft_updates.end()) { it->first->update_index(it->second); it++; } //FIXME: dirty fix for bug with missing clear_ft_sequences() call //TODO: remove this and add clear_ft_sequences() call or remove all other clear_ft_sequences() calls clear_ft_sequences(); } void update_insert_sequence(xptr node,ft_index_cell_cptr icell) { std::map<ft_index_cell_xptr,update_history*>::iterator it=ft_updates.find(icell.ptr()); if (it==ft_updates.end()) { update_history *h=se_new update_history(); h->add_insert_node(node); ft_updates[icell.ptr()]=h; } else it->second->add_insert_node(node); } void update_update_sequence(xptr node,ft_index_cell_cptr icell) { std::map<ft_index_cell_xptr,update_history*>::iterator it=ft_updates.find(icell.ptr()); if (it==ft_updates.end()) { update_history *h=se_new update_history(); h->add_update_node(node); ft_updates[icell.ptr()]=h; } else it->second->add_update_node(node); } void update_delete_sequence(xptr node,ft_index_cell_cptr icell) { std::map<ft_index_cell_xptr,update_history*>::iterator it=ft_updates.find(icell.ptr()); if (it==ft_updates.end()) { update_history* h=se_new update_history(); h->add_delete_node(node); ft_updates[icell.ptr()]=h; } else it->second->add_delete_node(node); } void update_insert_sequence(xptr node,schema_node_cptr icell) { cat_list<ft_index_cell_xptr>::item* obj=icell->ft_index_list.first; if (obj == NULL) return; CHECKP(node); xptr ind=((n_dsc*)XADDR(node))->indir; while (obj!=NULL) { update_insert_sequence(ind,ft_index_cell_cptr(obj->object)); obj=obj->next; } CHECKP(node); } void update_update_sequence(xptr node,schema_node_cptr icell) { cat_list<ft_index_cell_xptr>::item* obj=icell->ft_index_list.first; if (obj==NULL) return; CHECKP(node); xptr ind=((n_dsc*)XADDR(node))->indir; while (obj!=NULL) { update_update_sequence(ind,ft_index_cell_cptr(obj->object)); obj=obj->next; } CHECKP(node); } void update_delete_sequence(xptr node,schema_node_cptr icell) { cat_list<ft_index_cell_xptr>::item* obj=icell->ft_index_list.first; if (obj==NULL) return; CHECKP(node); xptr ind=((n_dsc*)XADDR(node))->indir; while (obj!=NULL) { update_delete_sequence(ind,ft_index_cell_cptr(obj->object)); obj=obj->next; } CHECKP(node); } void init_ft_sequences (const xptr& left, const xptr& right, const xptr& parent) { if (IS_TMP_BLOCK(left)||IS_TMP_BLOCK(right)||IS_TMP_BLOCK(parent)) return; xptr tmp; schema_node_cptr scn = XNULL; if (parent!=XNULL) { tmp=parent; CHECKP(parent); scn=(GETBLOCKBYNODE(parent))->snode; } else { tmp=(left==XNULL)?right:left; CHECKP(tmp); scn=(GETBLOCKBYNODE(tmp))->snode->parent; } if (scn->root == scn.ptr() || scn->root->full_ft_index_list.empty()) return; while (scn.found()) { cat_list<ft_index_cell_xptr>::item* obj=scn->ft_index_list.first; if (obj!=NULL) { tmp=getNodeAncestorIndirectionByScheme(tmp,scn); while (obj!=NULL) { update_update_sequence(tmp,ft_index_cell_cptr(obj->object)); obj=obj->next; } tmp=removeIndirection(tmp); } scn=scn->parent; } } #endif xptr copy_node_content(xptr new_node_i, xptr node, xptr left_node_i, upd_ns_map** nsupdmap, bool save_types, unsigned short depth) { xptr left_node = XNULL; xptr childi = getIndirectionSafeCP(getFirstByOrderChildCP(node)); while (childi != XNULL) { left_node = deep_copy_node_i(left_node_i, XNULL, new_node_i, indirectionDereferenceCP(childi), nsupdmap, save_types, depth + 1); /* due to : MG: deep_temp_copy can return XNULL if a trigger canceled * the insertion and there were now any left sibling */ if (left_node != XNULL) { left_node_i = getIndirectionSafeCP(left_node); } childi = getRightSiblingIndirectionCP(indirectionDereferenceCP(childi)); } return left_node_i; } void swizzleNamespace (xmlns_ptr & ns, upd_ns_map*& updmap) { if (updmap == NULL) updmap = se_new upd_ns_map; upd_ns_map::const_iterator it = updmap->find(ns); if (it == updmap->end()) { ns = xmlns_touch(ns->prefix, ns->uri); } else { ns = it->second; } } xptr deep_copy_node(xptr left, xptr right, xptr parent, xptr node, upd_ns_map** nsupdmap, bool save_types, unsigned short depth) { xptr result; xptr node_indir; schema_node_cptr scmnode; xmlscm_type scm_type; #ifdef SE_ENABLE_FTSEARCH if (!depth) init_ft_sequences(left,right,parent); #endif #ifdef SE_ENABLE_TRIGGERS if (parent == XNULL) { if (left != XNULL) { CHECKP(left); parent = removeIndirection(((n_dsc*) XADDR(left))->pdsc); } else { CHECKP(right); parent = removeIndirection(((n_dsc*) XADDR(right))->pdsc); } } node = apply_per_node_triggers(node, XNULL, parent, XNULL, TRIGGER_BEFORE, TRIGGER_INSERT_EVENT); if (node == XNULL) { if (left == XNULL) { return XNULL; } CHECKP(left); return left; } #endif node_indir = getIndirectionSafeCP(node); scmnode = getBlockHeaderCP(node)->snode; switch (scmnode->type) { case element: { xptr result_indir; xmlns_ptr ns = scmnode->get_xmlns(); if (nsupdmap != NULL && ns != NULL_XMLNS) { swizzleNamespace(ns, *nsupdmap); } scm_type = (save_types) ? E_DSC(node)->type : xs_untyped; result = insert_element(left, right, parent, scmnode->name, scm_type, ns); result_indir = get_last_mo_inderection(); copy_node_content(result_indir, indirectionDereferenceCP(node_indir), XNULL, nsupdmap, save_types, depth); result = indirectionDereferenceCP(result_indir); CHECKP(result); } break; case text: { if (isTextEmpty(T_DSC(node))) { throw SYSTEM_EXCEPTION("BAD DATA!!!"); } else { xptr data = getTextPtr(T_DSC(node)); CHECKP(node); result = insert_text(left, right, parent, &data, getTextSize(T_DSC(node)), text_doc); } } break; case cdata: { text_cptr buf(node); result = insert_cdata(left, right, parent, buf.get(), buf.getSize()); } break; case comment: { text_cptr buf(node); result = insert_comment(left, right, parent, buf.get(), buf.getSize()); } break; case pr_ins: { size_t tsize = PI_DSC(node)->target; text_cptr buf(node); result = insert_pi(left, right, parent, buf.get(), tsize, buf.get() + tsize + 1, buf.getSize() - tsize - 1); } break; case attribute: { xmlns_ptr ns = scmnode->get_xmlns(); text_cptr buf(node); if (nsupdmap != NULL && ns != NULL_XMLNS) { swizzleNamespace(ns, *nsupdmap); } CHECKP(node); scm_type = (save_types) ? A_DSC(node)->type : xs_untypedAtomic; result = insert_attribute(left, right, parent, scmnode->name, scm_type, buf.get(), buf.getSize(), ns); } break; case xml_namespace: { xmlns_ptr ns = xmlns_touch(NS_DSC(node)->ns); if (nsupdmap != NULL && ns != NULL_XMLNS) { swizzleNamespace(ns, *nsupdmap); } result = insert_namespace(left, right, parent, ns); } break; default: throw SYSTEM_EXCEPTION("Deep copy error: document node copied"); } CHECKP(result); #ifdef SE_ENABLE_FTSEARCH update_insert_sequence(result, schema_node_cptr((GETBLOCKBYNODE(result))->snode)); #endif #ifdef SE_ENABLE_TRIGGERS if (parent==XNULL) parent=removeIndirection(((n_dsc*)XADDR(left))->pdsc); apply_per_node_triggers(result, XNULL, parent, XNULL, TRIGGER_AFTER, TRIGGER_INSERT_EVENT); #endif CHECKP(result); return result; } xptr copy_to_temp(xptr node) { PPConstructor::checkInitial(); return deep_copy_node(XNULL, XNULL, PPConstructor::get_virtual_root(), node, NULL, true); } <|endoftext|>
<commit_before>/** * Mutable Fibonacci Heap implementation * © 2013 Philips Healthcare * Author: Maurice Termeer */ #ifndef _FIBONACCI_HEAP_ #define _FIBONACCI_HEAP_ #include <algorithm> #include <deque> #include <functional> #include <iterator> #include <list> #include <map> #include <utility> #include <vector> template<typename T> class fibonacci_heap { public: struct node { T element; node* parent; std::vector<node*> children; }; typedef T value_type; typedef std::size_t size_type; typedef const T& const_reference; typedef T& reference; typedef const node* const_pointer; typedef node* pointer; struct iterator { const_reference operator*() const { return p_->element; } reference operator*() { return p_->element; } iterator(pointer p) : p_(p) { } pointer p_; }; fibonacci_heap() : n_(0) { } iterator top() const { return iterator(roots_.front()); } void insert(const_reference element) { pointer new_node = allocator_.allocate(1); allocator_.construct(new_node); new_node->element = element; new_node->parent = nullptr; roots_.push_back(new_node); if (new_node->element < roots_.front()->element) { std::swap(roots_.front(), roots_.back()); } ++n_; } void pop() { pointer old_node = roots_.front(); std::swap(roots_.front(), roots_.back()); roots_.pop_back(); std::for_each( std::begin(old_node->children), std::end(old_node->children), [&](pointer p) { roots_.push_back(p); p->parent = nullptr; }); allocator_.deallocate(old_node, 1); merge_roots(); --n_; } private: void merge_roots() { std::vector<pointer> degrees; for (std::size_t i = 0; i < roots_.size(); ++i) { auto root = roots_[i]; if (root->parent != nullptr) continue; auto degree = root->children.size(); while (true) { if (degrees.size() <= degree) { degrees.resize(degree + 1); } auto k = degrees[degree]; if (k == nullptr) { degrees[degree] = root; break; } else if (k == root) { break; } else { auto other = k; if (other->element < root->element) { other->children.push_back(root); root->parent = other; root = other; } else { root->children.push_back(other); other->parent = root; } degrees[degree] = nullptr; ++degree; } } } roots_.clear(); for (auto i = std::begin(degrees); i != std::end(degrees); ++i) { if (*i == nullptr) continue; roots_.push_back(*i); if (!(roots_.front()->element < (*i)->element)) { std::swap(roots_.front(), roots_.back()); } } } std::deque<pointer> roots_; std::allocator<node> allocator_; size_type n_; }; #endif // _FIBONACCI_HEAP_ <commit_msg>use constant-size array for degrees map<commit_after>/** * Mutable Fibonacci Heap implementation * © 2013 Philips Healthcare * Author: Maurice Termeer */ #ifndef _FIBONACCI_HEAP_ #define _FIBONACCI_HEAP_ #include <algorithm> #include <array> #include <deque> #include <functional> #include <iterator> #include <list> #include <map> #include <utility> #include <vector> template<typename T> class fibonacci_heap { public: struct node { T element; node* parent; std::vector<node*> children; }; typedef T value_type; typedef std::size_t size_type; typedef const T& const_reference; typedef T& reference; typedef const node* const_pointer; typedef node* pointer; struct iterator { const_reference operator*() const { return p_->element; } reference operator*() { return p_->element; } iterator(pointer p) : p_(p) { } pointer p_; }; fibonacci_heap() : n_(0) { degrees_.fill(nullptr); } iterator top() const { return iterator(roots_.front()); } void insert(const_reference element) { pointer new_node = allocator_.allocate(1); allocator_.construct(new_node); new_node->element = element; new_node->parent = nullptr; roots_.push_back(new_node); if (new_node->element < roots_.front()->element) { std::swap(roots_.front(), roots_.back()); } if (degrees_[0] == nullptr) { degrees_[0] = new_node; } ++n_; } void pop() { pointer old_node = roots_.front(); std::swap(roots_.front(), roots_.back()); roots_.pop_back(); std::size_t degree = old_node->children.size(); if (degrees_[degree] == old_node) { degrees_[degree] = nullptr; } std::for_each( std::begin(old_node->children), std::end(old_node->children), [&](pointer p) { roots_.push_back(p); p->parent = nullptr; }); allocator_.deallocate(old_node, 1); merge_roots(); --n_; } private: void merge_roots() { for (std::size_t i = 0; i < roots_.size(); ++i) { auto root = roots_[i]; if (root->parent != nullptr) continue; auto degree = root->children.size(); while (true) { auto k = degrees_[degree]; if (k == nullptr) { degrees_[degree] = root; break; } else if (k == root) { break; } else { auto other = k; if (other->element < root->element) { other->children.push_back(root); root->parent = other; root = other; } else { root->children.push_back(other); other->parent = root; } degrees_[degree] = nullptr; ++degree; } } } roots_.clear(); for (auto i = std::begin(degrees_); i != std::end(degrees_); ++i) { if (*i == nullptr) continue; roots_.push_back(*i); if (!(roots_.front()->element < (*i)->element)) { std::swap(roots_.front(), roots_.back()); } } } std::array<pointer,sizeof(std::size_t) * 8> degrees_; std::deque<pointer> roots_; std::allocator<node> allocator_; size_type n_; }; #endif // _FIBONACCI_HEAP_ <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2007 Rony Shapiro <ronys@users.sourceforge.net>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ // ExpPWListDlg.cpp : implementation file // #include "stdafx.h" #include "ExpPWListDlg.h" #include "DboxMain.h" #include "corelib/MyString.h" #include "corelib/Util.h" #include "corelib/ItemData.h" #include "resource2.h" // Menu, Toolbar & Accelerator resources #include "resource3.h" // String resources using namespace std; ExpPWEntry::ExpPWEntry(const CItemData &ci, time_t now, time_t LTime) { group = ci.GetGroup(); title = ci.GetTitle(); user = ci.GetUser(); // Expired or Warning / Normal or Base - see image list below type = (LTime <= now ? 0 : 1) + (ci.IsBase() ? 2 : 0); expirylocdate = ci.GetLTimeL(); expiryexpdate = ci.GetLTimeExp(); expirytttdate = LTime; } // CExpPWListDlg dialog CExpPWListDlg::CExpPWListDlg(CWnd* pParent, const ExpiredList &expPWList, const CString& a_filespec) : CPWDialog(CExpPWListDlg::IDD, pParent), m_expPWList(expPWList) { const int FILE_DISP_LEN = 75; if (a_filespec.GetLength() > FILE_DISP_LEN) { // m_message = a_filespec.Right(FILE_DISP_LEN - 3); // truncate for display // m_message.Insert(0, _T("...")); m_message = a_filespec.Left(FILE_DISP_LEN/2-5) + _T(" ... ") + a_filespec.Right(FILE_DISP_LEN/2); } else { m_message = a_filespec; } m_iSortedColumn = -1; m_bSortAscending = TRUE; } CExpPWListDlg::~CExpPWListDlg() { } void CExpPWListDlg::DoDataExchange(CDataExchange* pDX) { CPWDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_EXPIRED_PASSWORD_LIST, m_expPWListCtrl); DDX_Text(pDX, IDC_MESSAGE, m_message); } BEGIN_MESSAGE_MAP(CExpPWListDlg, CPWDialog) ON_BN_CLICKED(IDC_COPY_EXP_TO_CLIPBOARD, OnBnClickedCopyExpToClipboard) ON_BN_CLICKED(IDOK, OnOK) ON_NOTIFY(HDN_ITEMCLICKA, 0, OnHeaderClicked) ON_NOTIFY(HDN_ITEMCLICKW, 0, OnHeaderClicked) END_MESSAGE_MAP() // CExpPWListDlg message handlers BOOL CExpPWListDlg::OnInitDialog() { CPWDialog::OnInitDialog(); //m_expPWListCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_SUBITEMIMAGES ); CString cs_text; m_expPWListCtrl.InsertColumn(0, _T("")); cs_text.LoadString(IDS_GROUP); m_expPWListCtrl.InsertColumn(1, cs_text); cs_text.LoadString(IDS_TITLE); m_expPWListCtrl.InsertColumn(3, cs_text); cs_text.LoadString(IDS_USERNAME); m_expPWListCtrl.InsertColumn(3, cs_text); cs_text.LoadString(IDS_EXPIRYDATETIME); m_expPWListCtrl.InsertColumn(4, cs_text); m_pImageList = new CImageList(); // Number (4) same as total of warn/expired images below BOOL status = m_pImageList->Create(9, 9, ILC_COLOR, 4, 0); ASSERT(status != 0); CBitmap bitmap; bitmap.LoadBitmap(IDB_LEAF_EXPIRED); m_pImageList->Add(&bitmap, (COLORREF)0x0); bitmap.DeleteObject(); bitmap.LoadBitmap(IDB_LEAF_WARNEXPIRED); m_pImageList->Add(&bitmap, (COLORREF)0x0); bitmap.DeleteObject(); bitmap.LoadBitmap(IDB_LEAF_BASE_EXPIRED); m_pImageList->Add(&bitmap, (COLORREF)0x0); bitmap.DeleteObject(); bitmap.LoadBitmap(IDB_LEAF_BASE_WARNEXPIRED); m_pImageList->Add(&bitmap, (COLORREF)0x0); bitmap.DeleteObject(); m_expPWListCtrl.SetImageList(m_pImageList, LVSIL_SMALL); m_expPWListCtrl.SetImageList(m_pImageList, LVSIL_NORMAL); int nPos = 0; ExpiredList::const_iterator itempos; for (itempos = m_expPWList.begin(); itempos != m_expPWList.end(); itempos++) { const ExpPWEntry exppwentry = *itempos; nPos = m_expPWListCtrl.InsertItem(nPos, NULL, exppwentry.type); m_expPWListCtrl.SetItemText(nPos, 1, exppwentry.group); m_expPWListCtrl.SetItemText(nPos, 2, exppwentry.title); m_expPWListCtrl.SetItemText(nPos, 3, exppwentry.user); m_expPWListCtrl.SetItemText(nPos, 4, exppwentry.expirylocdate); // original nPos == index in vector: save for Sort m_expPWListCtrl.SetItemData(nPos, static_cast<DWORD>(nPos)); } m_expPWListCtrl.SetRedraw(FALSE); for (int i = 0; i < 5; i++) { m_expPWListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE); int nColumnWidth = m_expPWListCtrl.GetColumnWidth(i); m_expPWListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE_USEHEADER); int nHeaderWidth = m_expPWListCtrl.GetColumnWidth(i); m_expPWListCtrl.SetColumnWidth(i, max(nColumnWidth, nHeaderWidth)); } m_expPWListCtrl.SetRedraw(TRUE); return TRUE; } void CExpPWListDlg::OnOK() { delete m_pImageList; CPWDialog::OnOK(); } void CExpPWListDlg::OnBnClickedCopyExpToClipboard() { CString data(MAKEINTRESOURCE(IDS_COPYTITLE)); const CString CRLF = _T("\r\n"); const CString TAB = _T('\t'); ExpiredList::const_iterator itempos; for (itempos = m_expPWList.begin(); itempos != m_expPWList.end(); itempos++) { const ExpPWEntry exppwentry = *itempos; data = data + (CString)exppwentry.group + TAB + (CString)exppwentry.title + TAB + (CString)exppwentry.user + TAB + (CString)exppwentry.expiryexpdate + CRLF; } DboxMain *dbx = static_cast<DboxMain *>(GetParent()); dbx->SetClipboardData(data); } void CExpPWListDlg::OnHeaderClicked(NMHDR* pNMHDR, LRESULT* pResult) { HD_NOTIFY *phdn = (HD_NOTIFY *) pNMHDR; if(phdn->iButton == 0) { // User clicked on header using left mouse button if(phdn->iItem == m_iSortedColumn) m_bSortAscending = !m_bSortAscending; else m_bSortAscending = TRUE; m_iSortedColumn = phdn->iItem; m_expPWListCtrl.SortItems(ExpPWCompareFunc, (LPARAM)this); // Note: WINVER defines the minimum system level for which this is program compiled and // NOT the level of system it is running on! // In this case, these values are defined in Windows XP and later and supported // by V6 of comctl32.dll (supplied with Windows XP) and later. // They should be ignored by earlier levels of this dll or ..... // we can check the dll version (code available on request)! #if (WINVER < 0x0501) // These are already defined for WinXP and later #define HDF_SORTUP 0x0400 #define HDF_SORTDOWN 0x0200 #endif HDITEM HeaderItem; HeaderItem.mask = HDI_FORMAT; m_expPWListCtrl.GetHeaderCtrl()->GetItem(m_iSortedColumn, &HeaderItem); // Turn off all arrows HeaderItem.fmt &= ~(HDF_SORTUP | HDF_SORTDOWN); // Turn on the correct arrow HeaderItem.fmt |= ((m_bSortAscending == TRUE) ? HDF_SORTUP : HDF_SORTDOWN); m_expPWListCtrl.GetHeaderCtrl()->SetItem(m_iSortedColumn, &HeaderItem); } *pResult = 0; } int CALLBACK CExpPWListDlg::ExpPWCompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM closure) { CExpPWListDlg *self = (CExpPWListDlg*)closure; int nSortColumn = self->m_iSortedColumn; const ExpPWEntry pLHS = self->m_expPWList[lParam1]; const ExpPWEntry pRHS = self->m_expPWList[lParam2]; CMyString group1, title1, username1; CMyString group2, title2, username2; int type1, type2; time_t t1, t2; int iResult; switch(nSortColumn) { case 0: type1 = pLHS.type; type2 = pRHS.type; iResult = (type1 < type2) ? -1 : 1; break; case 1: group1 = pLHS.group; group2 = pRHS.group; iResult = ((CString)group1).CompareNoCase(group2); break; case 2: title1 = pLHS.title; title2 = pRHS.title; iResult = ((CString)title1).CompareNoCase(title2); break; case 3: username1 = pLHS.user; username2 = pRHS.user; iResult = ((CString)username1).CompareNoCase(username2); break; case 4: t1 = pLHS.expirytttdate; t2 = pRHS.expirytttdate; iResult = ((long) t1 < (long) t2) ? -1 : 1; break; default: iResult = 0; // should never happen - just keep compiler happy ASSERT(FALSE); } if (!self->m_bSortAscending) iResult *= -1; return iResult; } <commit_msg>Correct column number in Expired Password dialog<commit_after>/* * Copyright (c) 2003-2007 Rony Shapiro <ronys@users.sourceforge.net>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ // ExpPWListDlg.cpp : implementation file // #include "stdafx.h" #include "ExpPWListDlg.h" #include "DboxMain.h" #include "corelib/MyString.h" #include "corelib/Util.h" #include "corelib/ItemData.h" #include "resource2.h" // Menu, Toolbar & Accelerator resources #include "resource3.h" // String resources using namespace std; ExpPWEntry::ExpPWEntry(const CItemData &ci, time_t now, time_t LTime) { group = ci.GetGroup(); title = ci.GetTitle(); user = ci.GetUser(); // Expired or Warning / Normal or Base - see image list below type = (LTime <= now ? 0 : 1) + (ci.IsBase() ? 2 : 0); expirylocdate = ci.GetLTimeL(); expiryexpdate = ci.GetLTimeExp(); expirytttdate = LTime; } // CExpPWListDlg dialog CExpPWListDlg::CExpPWListDlg(CWnd* pParent, const ExpiredList &expPWList, const CString& a_filespec) : CPWDialog(CExpPWListDlg::IDD, pParent), m_expPWList(expPWList) { const int FILE_DISP_LEN = 75; if (a_filespec.GetLength() > FILE_DISP_LEN) { // m_message = a_filespec.Right(FILE_DISP_LEN - 3); // truncate for display // m_message.Insert(0, _T("...")); m_message = a_filespec.Left(FILE_DISP_LEN/2-5) + _T(" ... ") + a_filespec.Right(FILE_DISP_LEN/2); } else { m_message = a_filespec; } m_iSortedColumn = -1; m_bSortAscending = TRUE; } CExpPWListDlg::~CExpPWListDlg() { } void CExpPWListDlg::DoDataExchange(CDataExchange* pDX) { CPWDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_EXPIRED_PASSWORD_LIST, m_expPWListCtrl); DDX_Text(pDX, IDC_MESSAGE, m_message); } BEGIN_MESSAGE_MAP(CExpPWListDlg, CPWDialog) ON_BN_CLICKED(IDC_COPY_EXP_TO_CLIPBOARD, OnBnClickedCopyExpToClipboard) ON_BN_CLICKED(IDOK, OnOK) ON_NOTIFY(HDN_ITEMCLICKA, 0, OnHeaderClicked) ON_NOTIFY(HDN_ITEMCLICKW, 0, OnHeaderClicked) END_MESSAGE_MAP() // CExpPWListDlg message handlers BOOL CExpPWListDlg::OnInitDialog() { CPWDialog::OnInitDialog(); //m_expPWListCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_SUBITEMIMAGES ); CString cs_text; m_expPWListCtrl.InsertColumn(0, _T("")); cs_text.LoadString(IDS_GROUP); m_expPWListCtrl.InsertColumn(1, cs_text); cs_text.LoadString(IDS_TITLE); m_expPWListCtrl.InsertColumn(2, cs_text); cs_text.LoadString(IDS_USERNAME); m_expPWListCtrl.InsertColumn(3, cs_text); cs_text.LoadString(IDS_EXPIRYDATETIME); m_expPWListCtrl.InsertColumn(4, cs_text); m_pImageList = new CImageList(); // Number (4) same as total of warn/expired images below BOOL status = m_pImageList->Create(9, 9, ILC_COLOR, 4, 0); ASSERT(status != 0); CBitmap bitmap; bitmap.LoadBitmap(IDB_LEAF_EXPIRED); m_pImageList->Add(&bitmap, (COLORREF)0x0); bitmap.DeleteObject(); bitmap.LoadBitmap(IDB_LEAF_WARNEXPIRED); m_pImageList->Add(&bitmap, (COLORREF)0x0); bitmap.DeleteObject(); bitmap.LoadBitmap(IDB_LEAF_BASE_EXPIRED); m_pImageList->Add(&bitmap, (COLORREF)0x0); bitmap.DeleteObject(); bitmap.LoadBitmap(IDB_LEAF_BASE_WARNEXPIRED); m_pImageList->Add(&bitmap, (COLORREF)0x0); bitmap.DeleteObject(); m_expPWListCtrl.SetImageList(m_pImageList, LVSIL_SMALL); m_expPWListCtrl.SetImageList(m_pImageList, LVSIL_NORMAL); int nPos = 0; ExpiredList::const_iterator itempos; for (itempos = m_expPWList.begin(); itempos != m_expPWList.end(); itempos++) { const ExpPWEntry exppwentry = *itempos; nPos = m_expPWListCtrl.InsertItem(nPos, NULL, exppwentry.type); m_expPWListCtrl.SetItemText(nPos, 1, exppwentry.group); m_expPWListCtrl.SetItemText(nPos, 2, exppwentry.title); m_expPWListCtrl.SetItemText(nPos, 3, exppwentry.user); m_expPWListCtrl.SetItemText(nPos, 4, exppwentry.expirylocdate); // original nPos == index in vector: save for Sort m_expPWListCtrl.SetItemData(nPos, static_cast<DWORD>(nPos)); } m_expPWListCtrl.SetRedraw(FALSE); for (int i = 0; i < 5; i++) { m_expPWListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE); int nColumnWidth = m_expPWListCtrl.GetColumnWidth(i); m_expPWListCtrl.SetColumnWidth(i, LVSCW_AUTOSIZE_USEHEADER); int nHeaderWidth = m_expPWListCtrl.GetColumnWidth(i); m_expPWListCtrl.SetColumnWidth(i, max(nColumnWidth, nHeaderWidth)); } m_expPWListCtrl.SetRedraw(TRUE); return TRUE; } void CExpPWListDlg::OnOK() { delete m_pImageList; CPWDialog::OnOK(); } void CExpPWListDlg::OnBnClickedCopyExpToClipboard() { CString data(MAKEINTRESOURCE(IDS_COPYTITLE)); const CString CRLF = _T("\r\n"); const CString TAB = _T('\t'); ExpiredList::const_iterator itempos; for (itempos = m_expPWList.begin(); itempos != m_expPWList.end(); itempos++) { const ExpPWEntry exppwentry = *itempos; data = data + (CString)exppwentry.group + TAB + (CString)exppwentry.title + TAB + (CString)exppwentry.user + TAB + (CString)exppwentry.expiryexpdate + CRLF; } DboxMain *dbx = static_cast<DboxMain *>(GetParent()); dbx->SetClipboardData(data); } void CExpPWListDlg::OnHeaderClicked(NMHDR* pNMHDR, LRESULT* pResult) { HD_NOTIFY *phdn = (HD_NOTIFY *) pNMHDR; if(phdn->iButton == 0) { // User clicked on header using left mouse button if(phdn->iItem == m_iSortedColumn) m_bSortAscending = !m_bSortAscending; else m_bSortAscending = TRUE; m_iSortedColumn = phdn->iItem; m_expPWListCtrl.SortItems(ExpPWCompareFunc, (LPARAM)this); // Note: WINVER defines the minimum system level for which this is program compiled and // NOT the level of system it is running on! // In this case, these values are defined in Windows XP and later and supported // by V6 of comctl32.dll (supplied with Windows XP) and later. // They should be ignored by earlier levels of this dll or ..... // we can check the dll version (code available on request)! #if (WINVER < 0x0501) // These are already defined for WinXP and later #define HDF_SORTUP 0x0400 #define HDF_SORTDOWN 0x0200 #endif HDITEM HeaderItem; HeaderItem.mask = HDI_FORMAT; m_expPWListCtrl.GetHeaderCtrl()->GetItem(m_iSortedColumn, &HeaderItem); // Turn off all arrows HeaderItem.fmt &= ~(HDF_SORTUP | HDF_SORTDOWN); // Turn on the correct arrow HeaderItem.fmt |= ((m_bSortAscending == TRUE) ? HDF_SORTUP : HDF_SORTDOWN); m_expPWListCtrl.GetHeaderCtrl()->SetItem(m_iSortedColumn, &HeaderItem); } *pResult = 0; } int CALLBACK CExpPWListDlg::ExpPWCompareFunc(LPARAM lParam1, LPARAM lParam2, LPARAM closure) { CExpPWListDlg *self = (CExpPWListDlg*)closure; int nSortColumn = self->m_iSortedColumn; const ExpPWEntry pLHS = self->m_expPWList[lParam1]; const ExpPWEntry pRHS = self->m_expPWList[lParam2]; CMyString group1, title1, username1; CMyString group2, title2, username2; int type1, type2; time_t t1, t2; int iResult; switch(nSortColumn) { case 0: type1 = pLHS.type; type2 = pRHS.type; iResult = (type1 < type2) ? -1 : 1; break; case 1: group1 = pLHS.group; group2 = pRHS.group; iResult = ((CString)group1).CompareNoCase(group2); break; case 2: title1 = pLHS.title; title2 = pRHS.title; iResult = ((CString)title1).CompareNoCase(title2); break; case 3: username1 = pLHS.user; username2 = pRHS.user; iResult = ((CString)username1).CompareNoCase(username2); break; case 4: t1 = pLHS.expirytttdate; t2 = pRHS.expirytttdate; iResult = ((long) t1 < (long) t2) ? -1 : 1; break; default: iResult = 0; // should never happen - just keep compiler happy ASSERT(FALSE); } if (!self->m_bSortAscending) iResult *= -1; return iResult; } <|endoftext|>
<commit_before>/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2011-2016 Martin Raiber * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ #include "../vld.h" #include <fstream> #include <iostream> #ifdef _WIN32 # include <conio.h> # include <ws2tcpip.h> #endif #include "../Interface/Server.h" #include "CTCPFileServ.h" #include "settings.h" #include "../stringtools.h" #include "log.h" std::fstream logfile; CTCPFileServ *TCPServer=NULL; #ifdef LINUX #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <syslog.h> #include <string.h> #endif #include <algorithm> #ifdef DLL_EXPORT # define EXPORT_METHOD_INT 5 #endif #ifdef _WIN32 void RestartServer() { _u16 tcpport=TCPServer->getTCPPort(); _u16 udpport=TCPServer->getUDPPort(); std::string servername=TCPServer->getServername(); bool use_fqdn=TCPServer->getUseFQDN(); TCPServer->KickClients(); delete TCPServer; Sleep(1000); TCPServer=new CTCPFileServ; int tries=20; while(!TCPServer->Start(tcpport, udpport, servername, use_fqdn) ) { Sleep(1000); if(tries<=0) { _exit(32); } --tries; } } bool EnumerateInterfaces() { static std::vector<std::vector<char> > ips; char hostname[MAX_PATH]; _i32 rc=gethostname(hostname, MAX_PATH); if(rc==SOCKET_ERROR) return false; bool new_ifs=false; std::vector<std::vector<char> > new_ips; struct addrinfo* h; if(getaddrinfo(hostname, NULL, NULL, &h)==0) { for(addrinfo* ptr = h;ptr!=NULL;ptr=ptr->ai_next) { if(ptr->ai_family==AF_INET || ptr->ai_family==AF_INET6) { std::vector<char> address; address.resize(ptr->ai_addrlen); memcpy(&address[0], ptr->ai_addr, ptr->ai_addrlen); if(std::find(ips.begin(), ips.end(), address)==ips.end()) { new_ifs=true; } new_ips.push_back(address); } } freeaddrinfo(h); } for(size_t i=0;i<ips.size();++i) { if(std::find(new_ips.begin(), new_ips.end(), ips[i])==new_ips.end()) { new_ifs=true; } } ips=new_ips; return new_ifs; } void LookForInterfaceChanges() { static int num=-1; if(num>=10 ) { num=0; if(EnumerateInterfaces()==true) { RestartServer(); } } if( num==-1 ) EnumerateInterfaces(); ++num; } HRESULT ModifyPrivilege( IN LPCTSTR szPrivilege, IN BOOL fEnable) { HRESULT hr = S_OK; TOKEN_PRIVILEGES NewState; LUID luid; HANDLE hToken = NULL; // Open the process token for this process. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken )) { Log("Failed OpenProcessToken", LL_ERROR); return ERROR_FUNCTION_FAILED; } // Get the local unique ID for the privilege. if ( !LookupPrivilegeValue( NULL, szPrivilege, &luid )) { CloseHandle( hToken ); Log("Failed LookupPrivilegeValue", LL_ERROR); return ERROR_FUNCTION_FAILED; } // Assign values to the TOKEN_PRIVILEGE structure. NewState.PrivilegeCount = 1; NewState.Privileges[0].Luid = luid; NewState.Privileges[0].Attributes = (fEnable ? SE_PRIVILEGE_ENABLED : 0); // Adjust the token privilege. if (!AdjustTokenPrivileges(hToken, FALSE, &NewState, 0, NULL, NULL)) { Log("Failed AdjustTokenPrivileges", LL_ERROR); hr = ERROR_FUNCTION_FAILED; } // Close the handle. CloseHandle(hToken); return hr; } bool optain_backup_privs() { #ifdef BACKUP_SEM bool ret = true; HRESULT hr = ModifyPrivilege(SE_BACKUP_NAME, TRUE); if (!SUCCEEDED(hr)) { Log("Failed to modify backup privileges", LL_ERROR); ret = false; } else { Log("Backup privileges set successfully", LL_DEBUG); } hr = ModifyPrivilege(SE_SECURITY_NAME, TRUE); if (!SUCCEEDED(hr)) { Log("Failed to modify backup privileges (SE_SECURITY_NAME)", LL_ERROR); ret = false; } else { Log("Backup privileges set successfully (SE_SECURITY_NAME)", LL_DEBUG); } hr = ModifyPrivilege(SE_RESTORE_NAME, TRUE); if (!SUCCEEDED(hr)) { Log("Failed to modify backup privileges (SE_RESTORE_NAME)", LL_ERROR); ret = false; } else { Log("Backup privileges set successfully (SE_RESTORE_NAME)", LL_DEBUG); } return ret; #else return false; #endif } #endif //_WIN32 #ifdef LINUX_DAEMON bool c_run=true; void termination_handler(int signum) { c_run=false; _exit(2); } #endif #ifdef CONSOLE_ON int main(int argc, char* argv[]) { #elif AS_SERVICE void my_init_fcn(void) { #elif EXPORT_METHOD_INT int start_server_int(unsigned short tcpport, unsigned short udpport, const std::string &pSname, const bool *pDostop, bool use_fqdn) { #else int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { #endif #ifdef _DEBUG { #endif #ifdef LINUX_DAEMON std::cout << "Starting as Daemon..." << std::endl; if( fork()==0 ) { setsid(); for (int i=getdtablesize();i>=0;--i) close(i); int i=open("/dev/null",O_RDWR); dup(i); dup(i); } else exit(0); if (signal (SIGINT, termination_handler) == SIG_IGN) signal (SIGINT, SIG_IGN); if (signal (SIGHUP, termination_handler) == SIG_IGN) signal (SIGHUP, SIG_IGN); if (signal (SIGTERM, termination_handler) == SIG_IGN) signal (SIGTERM, SIG_IGN); c_run=true; #endif #ifndef _DEBUG #ifndef AS_SERVICE #ifndef EXPORT_METHOD_INT WriteReg(); #endif #endif #endif std::string servername; #ifdef CONSOLE_ON if(argc==2) servername=argv[1]; #endif optain_backup_privs(); #ifdef LOG_FILE #ifdef _WIN32 logfile.open("C:\\urinstallsrv.log", std::ios::out | std::ios::binary ); #else logfile.open("/var/log/urinstallsrv.log", std::ios::out | std::ios::binary ); #endif #endif /*std::fstream out(testfilename.c_str(), std::ios::out | std::ios::binary ); if( out.is_open()==false ) Log("Can't create testfile... Could perhaps cause problems."); char* buffer=new char[1024]; for(size_t i=0;i<1024;++i) out.write(buffer, 1024); out.close(); delete[] buffer; */ #ifdef _WIN32 SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_HIGHEST); #endif TCPServer=new CTCPFileServ; #ifndef EXPORT_METHOD_INT bool suc=TCPServer->Start(55634,55635,servername); #else bool suc=TCPServer->Start(tcpport, udpport, (pSname=="")?servername:pSname, use_fqdn); #endif if(suc==false) { delete TCPServer; TCPServer=NULL; #ifdef _WIN32 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL); #endif return 99; } #ifndef AS_SERVICE while(true) { #if defined(_DEBUG) && defined(_WIN32) if( _kbhit() ) { break; } #endif bool b=TCPServer->Run(); if( b==false ) break; #ifdef LINUX_DEAMON if( c_run==false ) break; #endif #if EXPORT_METHOD_INT if(*pDostop==true) { TCPServer->KickClients(); break; } #endif } delete TCPServer; #endif //AS_SERVICE #ifdef _WIN32 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL); #endif #ifndef AS_SERVICE return 2; #endif #ifdef _DEBUG } #endif } <commit_msg>Obtain backup/restore privileges on Windows to read symlinks<commit_after>/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2011-2016 Martin Raiber * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ #include "../vld.h" #include <fstream> #include <iostream> #ifdef _WIN32 # include <conio.h> # include <ws2tcpip.h> #endif #include "../Interface/Server.h" #include "CTCPFileServ.h" #include "settings.h" #include "../stringtools.h" #include "log.h" std::fstream logfile; CTCPFileServ *TCPServer=NULL; #ifdef LINUX #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <syslog.h> #include <string.h> #endif #include <algorithm> #ifdef DLL_EXPORT # define EXPORT_METHOD_INT 5 #endif #ifdef _WIN32 void RestartServer() { _u16 tcpport=TCPServer->getTCPPort(); _u16 udpport=TCPServer->getUDPPort(); std::string servername=TCPServer->getServername(); bool use_fqdn=TCPServer->getUseFQDN(); TCPServer->KickClients(); delete TCPServer; Sleep(1000); TCPServer=new CTCPFileServ; int tries=20; while(!TCPServer->Start(tcpport, udpport, servername, use_fqdn) ) { Sleep(1000); if(tries<=0) { _exit(32); } --tries; } } bool EnumerateInterfaces() { static std::vector<std::vector<char> > ips; char hostname[MAX_PATH]; _i32 rc=gethostname(hostname, MAX_PATH); if(rc==SOCKET_ERROR) return false; bool new_ifs=false; std::vector<std::vector<char> > new_ips; struct addrinfo* h; if(getaddrinfo(hostname, NULL, NULL, &h)==0) { for(addrinfo* ptr = h;ptr!=NULL;ptr=ptr->ai_next) { if(ptr->ai_family==AF_INET || ptr->ai_family==AF_INET6) { std::vector<char> address; address.resize(ptr->ai_addrlen); memcpy(&address[0], ptr->ai_addr, ptr->ai_addrlen); if(std::find(ips.begin(), ips.end(), address)==ips.end()) { new_ifs=true; } new_ips.push_back(address); } } freeaddrinfo(h); } for(size_t i=0;i<ips.size();++i) { if(std::find(new_ips.begin(), new_ips.end(), ips[i])==new_ips.end()) { new_ifs=true; } } ips=new_ips; return new_ifs; } void LookForInterfaceChanges() { static int num=-1; if(num>=10 ) { num=0; if(EnumerateInterfaces()==true) { RestartServer(); } } if( num==-1 ) EnumerateInterfaces(); ++num; } HRESULT ModifyPrivilege( IN LPCTSTR szPrivilege, IN BOOL fEnable) { HRESULT hr = S_OK; TOKEN_PRIVILEGES NewState; LUID luid; HANDLE hToken = NULL; // Open the process token for this process. if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken )) { Log("Failed OpenProcessToken", LL_ERROR); return ERROR_FUNCTION_FAILED; } // Get the local unique ID for the privilege. if ( !LookupPrivilegeValue( NULL, szPrivilege, &luid )) { CloseHandle( hToken ); Log("Failed LookupPrivilegeValue", LL_ERROR); return ERROR_FUNCTION_FAILED; } // Assign values to the TOKEN_PRIVILEGE structure. NewState.PrivilegeCount = 1; NewState.Privileges[0].Luid = luid; NewState.Privileges[0].Attributes = (fEnable ? SE_PRIVILEGE_ENABLED : 0); // Adjust the token privilege. if (!AdjustTokenPrivileges(hToken, FALSE, &NewState, 0, NULL, NULL)) { Log("Failed AdjustTokenPrivileges", LL_ERROR); hr = ERROR_FUNCTION_FAILED; } // Close the handle. CloseHandle(hToken); return hr; } bool optain_backup_privs() { #ifdef BACKUP_SEM bool ret = true; HRESULT hr = ModifyPrivilege(SE_BACKUP_NAME, TRUE); if (!SUCCEEDED(hr)) { Log("Failed to modify backup privileges", LL_ERROR); ret = false; } else { Log("Backup privileges set successfully", LL_DEBUG); } hr = ModifyPrivilege(SE_SECURITY_NAME, TRUE); if (!SUCCEEDED(hr)) { Log("Failed to modify backup privileges (SE_SECURITY_NAME)", LL_ERROR); ret = false; } else { Log("Backup privileges set successfully (SE_SECURITY_NAME)", LL_DEBUG); } hr = ModifyPrivilege(SE_RESTORE_NAME, TRUE); if (!SUCCEEDED(hr)) { Log("Failed to modify backup privileges (SE_RESTORE_NAME)", LL_ERROR); ret = false; } else { Log("Backup privileges set successfully (SE_RESTORE_NAME)", LL_DEBUG); } return ret; #else return false; #endif } #endif //_WIN32 #ifdef LINUX_DAEMON bool c_run=true; void termination_handler(int signum) { c_run=false; _exit(2); } #endif #ifdef CONSOLE_ON int main(int argc, char* argv[]) { #elif AS_SERVICE void my_init_fcn(void) { #elif EXPORT_METHOD_INT int start_server_int(unsigned short tcpport, unsigned short udpport, const std::string &pSname, const bool *pDostop, bool use_fqdn) { #else int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { #endif #ifdef _DEBUG { #endif #ifdef LINUX_DAEMON std::cout << "Starting as Daemon..." << std::endl; if( fork()==0 ) { setsid(); for (int i=getdtablesize();i>=0;--i) close(i); int i=open("/dev/null",O_RDWR); dup(i); dup(i); } else exit(0); if (signal (SIGINT, termination_handler) == SIG_IGN) signal (SIGINT, SIG_IGN); if (signal (SIGHUP, termination_handler) == SIG_IGN) signal (SIGHUP, SIG_IGN); if (signal (SIGTERM, termination_handler) == SIG_IGN) signal (SIGTERM, SIG_IGN); c_run=true; #endif #ifndef _DEBUG #ifndef AS_SERVICE #ifndef EXPORT_METHOD_INT WriteReg(); #endif #endif #endif std::string servername; #ifdef CONSOLE_ON if(argc==2) servername=argv[1]; #endif #ifdef _WIN32 optain_backup_privs(); #endif #ifdef LOG_FILE #ifdef _WIN32 logfile.open("C:\\urinstallsrv.log", std::ios::out | std::ios::binary ); #else logfile.open("/var/log/urinstallsrv.log", std::ios::out | std::ios::binary ); #endif #endif /*std::fstream out(testfilename.c_str(), std::ios::out | std::ios::binary ); if( out.is_open()==false ) Log("Can't create testfile... Could perhaps cause problems."); char* buffer=new char[1024]; for(size_t i=0;i<1024;++i) out.write(buffer, 1024); out.close(); delete[] buffer; */ #ifdef _WIN32 SetThreadPriority( GetCurrentThread(), THREAD_PRIORITY_HIGHEST); #endif TCPServer=new CTCPFileServ; #ifndef EXPORT_METHOD_INT bool suc=TCPServer->Start(55634,55635,servername); #else bool suc=TCPServer->Start(tcpport, udpport, (pSname=="")?servername:pSname, use_fqdn); #endif if(suc==false) { delete TCPServer; TCPServer=NULL; #ifdef _WIN32 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL); #endif return 99; } #ifndef AS_SERVICE while(true) { #if defined(_DEBUG) && defined(_WIN32) if( _kbhit() ) { break; } #endif bool b=TCPServer->Run(); if( b==false ) break; #ifdef LINUX_DEAMON if( c_run==false ) break; #endif #if EXPORT_METHOD_INT if(*pDostop==true) { TCPServer->KickClients(); break; } #endif } delete TCPServer; #endif //AS_SERVICE #ifdef _WIN32 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL); #endif #ifndef AS_SERVICE return 2; #endif #ifdef _DEBUG } #endif } <|endoftext|>
<commit_before>/* * Copyright (C) 2018 Dubalu LLC. All rights reserved. * * 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 "database_updater.h" #ifdef XAPIAND_CLUSTERING #include <utility> // for std::move #include "log.h" // for L_OBJ, L_CALL, L_DEBUG, L_WARNING #include "manager.h" // for XapiandManager::manager #include "server/discovery.h" // for Discovery::signal_db_update #include "string.hh" // for string::from_delta #include "time_point.hh" // for time_point_to_ullong #define NORMALY_UPDATE_AFTER 5s #define WHEN_BUSY_UPDATE_AFTER 15s #define FORCE_UPDATE_AFTER 75s std::mutex DatabaseUpdater::statuses_mtx; std::unordered_map<DatabaseUpdate, DatabaseUpdater::Status> DatabaseUpdater::statuses; DatabaseUpdater::DatabaseUpdater(bool forced_, DatabaseUpdate&& update_) : forced(forced_), update(std::move(update_)) { } void DatabaseUpdater::send(DatabaseUpdate&& update) { L_CALL("DatabaseUpdater::send(<update>)"); std::shared_ptr<DatabaseUpdater> task; unsigned long long next_wakeup_time; { auto now = std::chrono::system_clock::now(); std::lock_guard<std::mutex> statuses_lk(DatabaseUpdater::statuses_mtx); auto it = DatabaseUpdater::statuses.find(update); DatabaseUpdater::Status* status; if (it == DatabaseUpdater::statuses.end()) { auto& status_ref = DatabaseUpdater::statuses[update] = { nullptr, time_point_to_ullong(now + FORCE_UPDATE_AFTER) }; status = &status_ref; next_wakeup_time = time_point_to_ullong(now + NORMALY_UPDATE_AFTER); } else { status = &(it->second); next_wakeup_time = time_point_to_ullong(now + WHEN_BUSY_UPDATE_AFTER); } bool forced; if (next_wakeup_time > status->max_wakeup_time) { next_wakeup_time = status->max_wakeup_time; forced = true; } else { forced = false; } if (status->task) { if (status->task->wakeup_time == next_wakeup_time) { return; } status->task->clear(); } status->task = std::make_shared<DatabaseUpdater>(forced, std::move(update)); task = status->task; } scheduler().add(task, next_wakeup_time); } void DatabaseUpdater::run() { L_CALL("DatabaseUpdater::run()"); L_DEBUG_HOOK("DatabaseUpdater::run", "DatabaseUpdater::run()"); { std::lock_guard<std::mutex> statuses_lk(DatabaseUpdater::statuses_mtx); DatabaseUpdater::statuses.erase(update); } auto start = std::chrono::system_clock::now(); std::string error; try { if (auto discovery = XapiandManager::manager->weak_discovery.lock()) { L_DEBUG("Replicator was informed database was updated: %s", repr(update.endpoint.to_string())); discovery->signal_db_update(update); } } catch (const Exception& exc) { error = exc.get_message(); } auto end = std::chrono::system_clock::now(); if (error.empty()) { L_DEBUG("Updater%s succeeded after %s", forced ? " (forced)" : "", string::from_delta(start, end)); } else { L_WARNING("Updater%s falied after %s: %s", forced ? " (forced)" : "", string::from_delta(start, end), error); } } #endif <commit_msg>DatabaseUpdater: Log wording tweaked<commit_after>/* * Copyright (C) 2018 Dubalu LLC. All rights reserved. * * 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 "database_updater.h" #ifdef XAPIAND_CLUSTERING #include <utility> // for std::move #include "log.h" // for L_OBJ, L_CALL, L_DEBUG, L_WARNING #include "manager.h" // for XapiandManager::manager #include "server/discovery.h" // for Discovery::signal_db_update #include "string.hh" // for string::from_delta #include "time_point.hh" // for time_point_to_ullong #define NORMALY_UPDATE_AFTER 5s #define WHEN_BUSY_UPDATE_AFTER 15s #define FORCE_UPDATE_AFTER 75s std::mutex DatabaseUpdater::statuses_mtx; std::unordered_map<DatabaseUpdate, DatabaseUpdater::Status> DatabaseUpdater::statuses; DatabaseUpdater::DatabaseUpdater(bool forced_, DatabaseUpdate&& update_) : forced(forced_), update(std::move(update_)) { } void DatabaseUpdater::send(DatabaseUpdate&& update) { L_CALL("DatabaseUpdater::send(<update>)"); std::shared_ptr<DatabaseUpdater> task; unsigned long long next_wakeup_time; { auto now = std::chrono::system_clock::now(); std::lock_guard<std::mutex> statuses_lk(DatabaseUpdater::statuses_mtx); auto it = DatabaseUpdater::statuses.find(update); DatabaseUpdater::Status* status; if (it == DatabaseUpdater::statuses.end()) { auto& status_ref = DatabaseUpdater::statuses[update] = { nullptr, time_point_to_ullong(now + FORCE_UPDATE_AFTER) }; status = &status_ref; next_wakeup_time = time_point_to_ullong(now + NORMALY_UPDATE_AFTER); } else { status = &(it->second); next_wakeup_time = time_point_to_ullong(now + WHEN_BUSY_UPDATE_AFTER); } bool forced; if (next_wakeup_time > status->max_wakeup_time) { next_wakeup_time = status->max_wakeup_time; forced = true; } else { forced = false; } if (status->task) { if (status->task->wakeup_time == next_wakeup_time) { return; } status->task->clear(); } status->task = std::make_shared<DatabaseUpdater>(forced, std::move(update)); task = status->task; } scheduler().add(task, next_wakeup_time); } void DatabaseUpdater::run() { L_CALL("DatabaseUpdater::run()"); L_DEBUG_HOOK("DatabaseUpdater::run", "DatabaseUpdater::run()"); { std::lock_guard<std::mutex> statuses_lk(DatabaseUpdater::statuses_mtx); DatabaseUpdater::statuses.erase(update); } auto start = std::chrono::system_clock::now(); std::string error; try { if (auto discovery = XapiandManager::manager->weak_discovery.lock()) { discovery->signal_db_update(update); L_DEBUG("Replicators where informed about the database update: %s", repr(update.endpoint.to_string())); } } catch (const Exception& exc) { error = exc.get_message(); } auto end = std::chrono::system_clock::now(); if (error.empty()) { L_DEBUG("Updater%s succeeded after %s", forced ? " (forced)" : "", string::from_delta(start, end)); } else { L_WARNING("Updater%s falied after %s: %s", forced ? " (forced)" : "", string::from_delta(start, end), error); } } #endif <|endoftext|>
<commit_before>// Time: O(m * n * max(logm, logn)) // Space: O(m * n) // BFS with priority queue (min heap), refactored version. class Solution { public: struct Cell { int i; int j; int height; }; struct Compare { bool operator()(const Cell& a, const Cell& b) { return a.height > b.height; } }; /** * @param heights: a matrix of integers * @return: an integer */ int trapRainWater(vector<vector<int> > &heights) { // Init m_, n_, is_visited_. m_ = heights.size(); n_ = heights[0].size(); is_visited_ = vector<vector<bool>>(m_, vector<bool>(n_, false)); int trap = 0; // Put the cells on the border into min heap. for (int i = 0; i < m_; ++i) { heap_.emplace(Cell{i, 0, heights[i][0]}); heap_.emplace(Cell{i, n_ - 1, heights[i][n_ - 1]}); } for (int j = 0; j < n_; ++j) { heap_.emplace(Cell{0, j, heights[0][j]}); heap_.emplace(Cell{m_ - 1, j, heights[m_ - 1][j]}); } // BFS with priority queue (min heap) while (!heap_.empty()) { Cell c = heap_.top(); heap_.pop(); is_visited_[c.i][c.j] = true; trap += fill(heights, c.i + 1, c.j, c.height); // Up trap += fill(heights, c.i - 1, c.j, c.height); // Down trap += fill(heights, c.i, c.j + 1, c.height); // Right trap += fill(heights, c.i, c.j - 1, c.height); // Left } return trap; } int fill(vector<vector<int>>& heights, int i, int j, int height) { // Out of border. if ( i < 0 || i >= m_ || j < 0 || j >= n_) { return 0; } // Fill unvisited cell. if (!is_visited_[i][j]) { is_visited_[i][j] = true; // Marked as visited. heap_.emplace(Cell{i, j, max(height, heights[i][j])}); return max(0, height - heights[i][j]); // Fill in the gap. } return 0; } private: int m_; int n_; vector<vector<bool>> is_visited_; priority_queue<Cell ,vector<Cell>, Compare> heap_; // Use min heap to get the lowerest cell. }; // Time: O(m * n * max(logm, logn)) // Space: O(m * n) // BFS with priority queue (min heap) class Solution2 { public: struct Cell { int i; int j; int height; }; /** * @param heights: a matrix of integers * @return: an integer */ int trapRainWater(vector<vector<int> > &heights) { const int m = heights.size(); const int n = heights[0].size(); int trap = 0; vector<vector<bool>> is_visited(m, vector<bool>(n, false)); // Use min heap to get the lowerest Cell. auto comp = [](const Cell& a, const Cell& b ) { return a.height > b.height; }; priority_queue<Cell , vector<Cell>, decltype(comp)> heap(comp); // Put the Cells on the border into min heap. for (int i = 0; i < m; ++i) { heap.emplace(Cell{i, 0, heights[i][0]}); heap.emplace(Cell{i, n - 1, heights[i][n - 1]}); } for (int j = 0; j < n; ++j) { heap.emplace(Cell{0, j, heights[0][j]}); heap.emplace(Cell{m - 1, j, heights[m - 1][j]}); } // BFS with priority queue (min heap) while (!heap.empty()) { // Get the lowest Cell. Cell c = heap.top(); heap.pop(); is_visited[c.i][c.j] = true; // Up if (c.i + 1 < m && !is_visited[c.i + 1][c.j]) { is_visited[c.i + 1][c.j] = true; trap += max(0, c.height - heights[c.i + 1][c.j]); // Fill in the gap. heap.emplace(Cell{c.i + 1, c.j, max(c.height, heights[c.i + 1][c.j])}); } // Down if (c.i - 1 >= 0 && !is_visited[c.i - 1][c.j]) { is_visited[c.i - 1][c.j] = true; trap += max(0, c.height - heights[c.i - 1][c.j]); // Fill in the gap. heap.emplace(Cell{c.i - 1, c.j, max(c.height, heights[c.i - 1][c.j])}); } // Right if (c.j + 1 < n && !is_visited[c.i][c.j + 1]) { is_visited[c.i][c.j + 1] = true; trap += max(0, c.height - heights[c.i][c.j + 1]); // Fill in the gap. heap.emplace(Cell{c.i, c.j + 1, max(c.height, heights[c.i][c.j + 1])}); } // Left if (c.j - 1 >= 0 && !is_visited[c.i][c.j - 1]) { is_visited[c.i][c.j - 1] = true; trap += max(0, c.height - heights[c.i][c.j - 1]); // Fill in the gap. heap.emplace(Cell{c.i, c.j - 1, max(c.height, heights[c.i][c.j - 1])}); } } return trap; } }; <commit_msg>Update trapping-rain-water-ii.cpp<commit_after>// Time: O(m * n * (logm + logn)) // Space: O(m * n) // BFS with priority queue (min heap), refactored version. class Solution { public: struct Cell { int i; int j; int height; }; struct Compare { bool operator()(const Cell& a, const Cell& b) { return a.height > b.height; } }; /** * @param heights: a matrix of integers * @return: an integer */ int trapRainWater(vector<vector<int> > &heights) { // Init m_, n_, is_visited_. m_ = heights.size(); n_ = heights[0].size(); is_visited_ = vector<vector<bool>>(m_, vector<bool>(n_, false)); int trap = 0; // Put the cells on the border into min heap. for (int i = 0; i < m_; ++i) { heap_.emplace(Cell{i, 0, heights[i][0]}); heap_.emplace(Cell{i, n_ - 1, heights[i][n_ - 1]}); } for (int j = 0; j < n_; ++j) { heap_.emplace(Cell{0, j, heights[0][j]}); heap_.emplace(Cell{m_ - 1, j, heights[m_ - 1][j]}); } // BFS with priority queue (min heap) while (!heap_.empty()) { Cell c = heap_.top(); heap_.pop(); is_visited_[c.i][c.j] = true; trap += fill(heights, c.i + 1, c.j, c.height); // Up trap += fill(heights, c.i - 1, c.j, c.height); // Down trap += fill(heights, c.i, c.j + 1, c.height); // Right trap += fill(heights, c.i, c.j - 1, c.height); // Left } return trap; } int fill(vector<vector<int>>& heights, int i, int j, int height) { // Out of border. if ( i < 0 || i >= m_ || j < 0 || j >= n_) { return 0; } // Fill unvisited cell. if (!is_visited_[i][j]) { is_visited_[i][j] = true; // Marked as visited. heap_.emplace(Cell{i, j, max(height, heights[i][j])}); return max(0, height - heights[i][j]); // Fill in the gap. } return 0; } private: int m_; int n_; vector<vector<bool>> is_visited_; priority_queue<Cell ,vector<Cell>, Compare> heap_; // Use min heap to get the lowerest cell. }; // Time: O(m * n * (logm + logn)) // Space: O(m * n) // BFS with priority queue (min heap) class Solution2 { public: struct Cell { int i; int j; int height; }; /** * @param heights: a matrix of integers * @return: an integer */ int trapRainWater(vector<vector<int> > &heights) { const int m = heights.size(); const int n = heights[0].size(); int trap = 0; vector<vector<bool>> is_visited(m, vector<bool>(n, false)); // Use min heap to get the lowerest Cell. auto comp = [](const Cell& a, const Cell& b ) { return a.height > b.height; }; priority_queue<Cell , vector<Cell>, decltype(comp)> heap(comp); // Put the Cells on the border into min heap. for (int i = 0; i < m; ++i) { heap.emplace(Cell{i, 0, heights[i][0]}); heap.emplace(Cell{i, n - 1, heights[i][n - 1]}); } for (int j = 0; j < n; ++j) { heap.emplace(Cell{0, j, heights[0][j]}); heap.emplace(Cell{m - 1, j, heights[m - 1][j]}); } // BFS with priority queue (min heap) while (!heap.empty()) { // Get the lowest Cell. Cell c = heap.top(); heap.pop(); is_visited[c.i][c.j] = true; // Up if (c.i + 1 < m && !is_visited[c.i + 1][c.j]) { is_visited[c.i + 1][c.j] = true; trap += max(0, c.height - heights[c.i + 1][c.j]); // Fill in the gap. heap.emplace(Cell{c.i + 1, c.j, max(c.height, heights[c.i + 1][c.j])}); } // Down if (c.i - 1 >= 0 && !is_visited[c.i - 1][c.j]) { is_visited[c.i - 1][c.j] = true; trap += max(0, c.height - heights[c.i - 1][c.j]); // Fill in the gap. heap.emplace(Cell{c.i - 1, c.j, max(c.height, heights[c.i - 1][c.j])}); } // Right if (c.j + 1 < n && !is_visited[c.i][c.j + 1]) { is_visited[c.i][c.j + 1] = true; trap += max(0, c.height - heights[c.i][c.j + 1]); // Fill in the gap. heap.emplace(Cell{c.i, c.j + 1, max(c.height, heights[c.i][c.j + 1])}); } // Left if (c.j - 1 >= 0 && !is_visited[c.i][c.j - 1]) { is_visited[c.i][c.j - 1] = true; trap += max(0, c.height - heights[c.i][c.j - 1]); // Fill in the gap. heap.emplace(Cell{c.i, c.j - 1, max(c.height, heights[c.i][c.j - 1])}); } } return trap; } }; <|endoftext|>
<commit_before>/* * Copyright (c) 2000-2004 The Regents of The University of Michigan * 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 copyright holders 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 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /// /// @file sim/main.cc /// #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <libgen.h> #include <stdlib.h> #include <signal.h> #include <list> #include <string> #include <vector> #include "base/copyright.hh" #include "base/embedfile.hh" #include "base/inifile.hh" #include "base/misc.hh" #include "base/output.hh" #include "base/pollevent.hh" #include "base/statistics.hh" #include "base/str.hh" #include "base/time.hh" #include "cpu/base_cpu.hh" #include "cpu/full_cpu/smt.hh" #include "python/pyconfig.hh" #include "sim/async.hh" #include "sim/builder.hh" #include "sim/configfile.hh" #include "sim/host.hh" #include "sim/sim_events.hh" #include "sim/sim_exit.hh" #include "sim/sim_object.hh" #include "sim/stat_control.hh" #include "sim/stats.hh" #include "sim/root.hh" using namespace std; // See async.h. volatile bool async_event = false; volatile bool async_dump = false; volatile bool async_dumpreset = false; volatile bool async_exit = false; volatile bool async_io = false; volatile bool async_alarm = false; /// Stats signal handler. void dumpStatsHandler(int sigtype) { async_event = true; async_dump = true; } void dumprstStatsHandler(int sigtype) { async_event = true; async_dumpreset = true; } /// Exit signal handler. void exitNowHandler(int sigtype) { async_event = true; async_exit = true; } /// Abort signal handler. void abortHandler(int sigtype) { cerr << "Program aborted at cycle " << curTick << endl; #if TRACING_ON // dump trace buffer, if there is one Trace::theLog.dump(cerr); #endif } /// Simulator executable name char *myProgName = ""; /// Show brief help message. void showBriefHelp(ostream &out) { char *prog = basename(myProgName); ccprintf(out, "Usage:\n"); ccprintf(out, "%s [-d <dir>] [-E <var>[=<val>]] [-I <dir>] [-P <python>]\n" " [--<var>=<val>] <config file>\n" "\n" " -d set the output directory to <dir>\n" " -E set the environment variable <var> to <val> (or 'True')\n" " -I add the directory <dir> to python's path\n" " -P execute <python> directly in the configuration\n" " --var=val set the python variable <var> to '<val>'\n" " <configfile> config file name (ends in .py)\n\n", prog); ccprintf(out, "%s -X\n -X extract embedded files\n\n", prog); ccprintf(out, "%s -h\n -h print short help\n\n", prog); ccprintf(out, "%s -H\n -H print long help\n\n", prog); } /// Show verbose help message. Includes parameter listing from /// showBriefHelp(), plus an exhaustive list of ini-file parameters /// and SimObjects (with their parameters). void showLongHelp(ostream &out) { showBriefHelp(out); out << endl << endl << "-----------------" << endl << "Global Parameters" << endl << "-----------------" << endl << endl; ParamContext::describeAllContexts(out); out << endl << endl << "-----------------" << endl << "Simulator Objects" << endl << "-----------------" << endl << endl; SimObjectClass::describeAllClasses(out); } /// Print welcome message. void sayHello(ostream &out) { extern const char *compileDate; // from date.cc ccprintf(out, "M5 Simulator System\n"); // display copyright ccprintf(out, "%s\n", briefCopyright); ccprintf(out, "M5 compiled on %d\n", compileDate); char *host = getenv("HOSTNAME"); if (!host) host = getenv("HOST"); if (host) ccprintf(out, "M5 executing on %s\n", host); ccprintf(out, "M5 simulation started %s\n", Time::start); } /// /// Echo the command line for posterity in such a way that it can be /// used to rerun the same simulation (given the same .ini files). /// void echoCommandLine(int argc, char **argv, ostream &out) { out << "command line: " << argv[0]; for (int i = 1; i < argc; i++) { string arg(argv[i]); out << ' '; // If the arg contains spaces, we need to quote it. // The rest of this is overkill to make it look purty. // print dashes first outside quotes int non_dash_pos = arg.find_first_not_of("-"); out << arg.substr(0, non_dash_pos); // print dashes string body = arg.substr(non_dash_pos); // the rest // if it's an assignment, handle the lhs & rhs separately int eq_pos = body.find("="); if (eq_pos == string::npos) { out << quote(body); } else { string lhs(body.substr(0, eq_pos)); string rhs(body.substr(eq_pos + 1)); out << quote(lhs) << "=" << quote(rhs); } } out << endl << endl; } char * getOptionString(int &index, int argc, char **argv) { char *option = argv[index] + 2; if (*option != '\0') return option; // We didn't find an argument, it must be in the next variable. if (++index >= argc) panic("option string for option '%s' not found", argv[index - 1]); return argv[index]; } int main(int argc, char **argv) { // Save off program name myProgName = argv[0]; signal(SIGFPE, SIG_IGN); // may occur on misspeculated paths signal(SIGTRAP, SIG_IGN); signal(SIGUSR1, dumpStatsHandler); // dump intermediate stats signal(SIGUSR2, dumprstStatsHandler); // dump and reset stats signal(SIGINT, exitNowHandler); // dump final stats and exit signal(SIGABRT, abortHandler); bool configfile_found = false; PythonConfig pyconfig; string outdir; if (argc < 2) { showBriefHelp(cerr); exit(1); } sayHello(cerr); // Parse command-line options. // Since most of the complex options are handled through the // config database, we don't mess with getopts, and just parse // manually. for (int i = 1; i < argc; ++i) { char *arg_str = argv[i]; // if arg starts with '--', parse as a special python option // of the format --<python var>=<string value>, if the arg // starts with '-', it should be a simulator option with a // format similar to getopt. In any other case, treat the // option as a configuration file name and load it. if (arg_str[0] == '-' && arg_str[1] == '-') { string str = &arg_str[2]; string var, val; if (!split_first(str, var, val, '=')) panic("Could not parse configuration argument '%s'\n" "Expecting --<variable>=<value>\n", arg_str); pyconfig.setVariable(var, val); } else if (arg_str[0] == '-') { char *option; string var, val; // switch on second char switch (arg_str[1]) { case 'd': outdir = getOptionString(i, argc, argv); break; case 'h': showBriefHelp(cerr); exit(1); case 'H': showLongHelp(cerr); exit(1); case 'E': option = getOptionString(i, argc, argv); if (!split_first(option, var, val, '=')) val = "True"; if (setenv(var.c_str(), val.c_str(), true) == -1) panic("setenv: %s\n", strerror(errno)); break; case 'I': option = getOptionString(i, argc, argv); pyconfig.addPath(option); break; case 'P': option = getOptionString(i, argc, argv); pyconfig.writeLine(option); break; case 'X': { list<EmbedFile> lst; EmbedMap::all(lst); list<EmbedFile>::iterator i = lst.begin(); list<EmbedFile>::iterator end = lst.end(); while (i != end) { cprintf("Embedded File: %s\n", i->name); cout.write(i->data, i->length); ++i; } return 0; } default: showBriefHelp(cerr); panic("invalid argument '%s'\n", arg_str); } } else { string file(arg_str); string base, ext; if (!split_last(file, base, ext, '.') || ext != "py") panic("Config file '%s' must end in '.py'\n", file); pyconfig.load(file); configfile_found = true; } } if (outdir.empty()) { char *env = getenv("OUTPUT_DIR"); outdir = env ? env : "."; } simout.setDirectory(outdir); char *env = getenv("CONFIG_OUTPUT"); if (!env) env = "config.out"; configStream = simout.find(env); if (!configfile_found) panic("no configuration file specified!"); // The configuration database is now complete; start processing it. IniFile inifile; if (!pyconfig.output(inifile)) panic("Error processing python code"); // Initialize statistics database Stats::InitSimStats(); // Now process the configuration hierarchy and create the SimObjects. ConfigHierarchy configHierarchy(inifile); configHierarchy.build(); configHierarchy.createSimObjects(); // Parse and check all non-config-hierarchy parameters. ParamContext::parseAllContexts(inifile); ParamContext::checkAllContexts(); // Print hello message to stats file if it's actually a file. If // it's not (i.e. it's cout or cerr) then we already did it above. if (simout.isFile(*outputStream)) sayHello(*outputStream); // Echo command line and all parameter settings to stats file as well. echoCommandLine(argc, argv, *outputStream); ParamContext::showAllContexts(*configStream); // Do a second pass to finish initializing the sim objects SimObject::initAll(); // Restore checkpointed state, if any. configHierarchy.unserializeSimObjects(); // Done processing the configuration database. // Check for unreferenced entries. if (inifile.printUnreferenced()) panic("unreferenced sections/entries in the intermediate ini file"); SimObject::regAllStats(); // uncomment the following to get PC-based execution-time profile #ifdef DO_PROFILE init_profile((char *)&_init, (char *)&_fini); #endif // Check to make sure that the stats package is properly initialized Stats::check(); // Reset to put the stats in a consistent state. Stats::reset(); warn("Entering event queue. Starting simulation...\n"); SimStartup(); while (!mainEventQueue.empty()) { assert(curTick <= mainEventQueue.nextTick() && "event scheduled in the past"); // forward current cycle to the time of the first event on the // queue curTick = mainEventQueue.nextTick(); mainEventQueue.serviceOne(); if (async_event) { async_event = false; if (async_dump) { async_dump = false; using namespace Stats; SetupEvent(Dump, curTick); } if (async_dumpreset) { async_dumpreset = false; using namespace Stats; SetupEvent(Dump | Reset, curTick); } if (async_exit) { async_exit = false; new SimExitEvent("User requested STOP"); } if (async_io || async_alarm) { async_io = false; async_alarm = false; pollQueue.service(); } } } // This should never happen... every conceivable way for the // simulation to terminate (hit max cycles/insts, signal, // simulated system halts/exits) generates an exit event, so we // should never run out of events on the queue. exitNow("no events on event loop! All CPUs must be idle.", 1); return 0; } <commit_msg>Get rid of broken "long help" option.<commit_after>/* * Copyright (c) 2000-2004 The Regents of The University of Michigan * 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 copyright holders 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 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /// /// @file sim/main.cc /// #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <libgen.h> #include <stdlib.h> #include <signal.h> #include <list> #include <string> #include <vector> #include "base/copyright.hh" #include "base/embedfile.hh" #include "base/inifile.hh" #include "base/misc.hh" #include "base/output.hh" #include "base/pollevent.hh" #include "base/statistics.hh" #include "base/str.hh" #include "base/time.hh" #include "cpu/base_cpu.hh" #include "cpu/full_cpu/smt.hh" #include "python/pyconfig.hh" #include "sim/async.hh" #include "sim/builder.hh" #include "sim/configfile.hh" #include "sim/host.hh" #include "sim/sim_events.hh" #include "sim/sim_exit.hh" #include "sim/sim_object.hh" #include "sim/stat_control.hh" #include "sim/stats.hh" #include "sim/root.hh" using namespace std; // See async.h. volatile bool async_event = false; volatile bool async_dump = false; volatile bool async_dumpreset = false; volatile bool async_exit = false; volatile bool async_io = false; volatile bool async_alarm = false; /// Stats signal handler. void dumpStatsHandler(int sigtype) { async_event = true; async_dump = true; } void dumprstStatsHandler(int sigtype) { async_event = true; async_dumpreset = true; } /// Exit signal handler. void exitNowHandler(int sigtype) { async_event = true; async_exit = true; } /// Abort signal handler. void abortHandler(int sigtype) { cerr << "Program aborted at cycle " << curTick << endl; #if TRACING_ON // dump trace buffer, if there is one Trace::theLog.dump(cerr); #endif } /// Simulator executable name char *myProgName = ""; /// Show brief help message. void showBriefHelp(ostream &out) { char *prog = basename(myProgName); ccprintf(out, "Usage:\n"); ccprintf(out, "%s [-d <dir>] [-E <var>[=<val>]] [-I <dir>] [-P <python>]\n" " [--<var>=<val>] <config file>\n" "\n" " -d set the output directory to <dir>\n" " -E set the environment variable <var> to <val> (or 'True')\n" " -I add the directory <dir> to python's path\n" " -P execute <python> directly in the configuration\n" " --var=val set the python variable <var> to '<val>'\n" " <configfile> config file name (ends in .py)\n\n", prog); ccprintf(out, "%s -X\n -X extract embedded files\n\n", prog); ccprintf(out, "%s -h\n -h print short help\n\n", prog); } /// Print welcome message. void sayHello(ostream &out) { extern const char *compileDate; // from date.cc ccprintf(out, "M5 Simulator System\n"); // display copyright ccprintf(out, "%s\n", briefCopyright); ccprintf(out, "M5 compiled on %d\n", compileDate); char *host = getenv("HOSTNAME"); if (!host) host = getenv("HOST"); if (host) ccprintf(out, "M5 executing on %s\n", host); ccprintf(out, "M5 simulation started %s\n", Time::start); } /// /// Echo the command line for posterity in such a way that it can be /// used to rerun the same simulation (given the same .ini files). /// void echoCommandLine(int argc, char **argv, ostream &out) { out << "command line: " << argv[0]; for (int i = 1; i < argc; i++) { string arg(argv[i]); out << ' '; // If the arg contains spaces, we need to quote it. // The rest of this is overkill to make it look purty. // print dashes first outside quotes int non_dash_pos = arg.find_first_not_of("-"); out << arg.substr(0, non_dash_pos); // print dashes string body = arg.substr(non_dash_pos); // the rest // if it's an assignment, handle the lhs & rhs separately int eq_pos = body.find("="); if (eq_pos == string::npos) { out << quote(body); } else { string lhs(body.substr(0, eq_pos)); string rhs(body.substr(eq_pos + 1)); out << quote(lhs) << "=" << quote(rhs); } } out << endl << endl; } char * getOptionString(int &index, int argc, char **argv) { char *option = argv[index] + 2; if (*option != '\0') return option; // We didn't find an argument, it must be in the next variable. if (++index >= argc) panic("option string for option '%s' not found", argv[index - 1]); return argv[index]; } int main(int argc, char **argv) { // Save off program name myProgName = argv[0]; signal(SIGFPE, SIG_IGN); // may occur on misspeculated paths signal(SIGTRAP, SIG_IGN); signal(SIGUSR1, dumpStatsHandler); // dump intermediate stats signal(SIGUSR2, dumprstStatsHandler); // dump and reset stats signal(SIGINT, exitNowHandler); // dump final stats and exit signal(SIGABRT, abortHandler); bool configfile_found = false; PythonConfig pyconfig; string outdir; if (argc < 2) { showBriefHelp(cerr); exit(1); } sayHello(cerr); // Parse command-line options. // Since most of the complex options are handled through the // config database, we don't mess with getopts, and just parse // manually. for (int i = 1; i < argc; ++i) { char *arg_str = argv[i]; // if arg starts with '--', parse as a special python option // of the format --<python var>=<string value>, if the arg // starts with '-', it should be a simulator option with a // format similar to getopt. In any other case, treat the // option as a configuration file name and load it. if (arg_str[0] == '-' && arg_str[1] == '-') { string str = &arg_str[2]; string var, val; if (!split_first(str, var, val, '=')) panic("Could not parse configuration argument '%s'\n" "Expecting --<variable>=<value>\n", arg_str); pyconfig.setVariable(var, val); } else if (arg_str[0] == '-') { char *option; string var, val; // switch on second char switch (arg_str[1]) { case 'd': outdir = getOptionString(i, argc, argv); break; case 'h': showBriefHelp(cerr); exit(1); case 'E': option = getOptionString(i, argc, argv); if (!split_first(option, var, val, '=')) val = "True"; if (setenv(var.c_str(), val.c_str(), true) == -1) panic("setenv: %s\n", strerror(errno)); break; case 'I': option = getOptionString(i, argc, argv); pyconfig.addPath(option); break; case 'P': option = getOptionString(i, argc, argv); pyconfig.writeLine(option); break; case 'X': { list<EmbedFile> lst; EmbedMap::all(lst); list<EmbedFile>::iterator i = lst.begin(); list<EmbedFile>::iterator end = lst.end(); while (i != end) { cprintf("Embedded File: %s\n", i->name); cout.write(i->data, i->length); ++i; } return 0; } default: showBriefHelp(cerr); panic("invalid argument '%s'\n", arg_str); } } else { string file(arg_str); string base, ext; if (!split_last(file, base, ext, '.') || ext != "py") panic("Config file '%s' must end in '.py'\n", file); pyconfig.load(file); configfile_found = true; } } if (outdir.empty()) { char *env = getenv("OUTPUT_DIR"); outdir = env ? env : "."; } simout.setDirectory(outdir); char *env = getenv("CONFIG_OUTPUT"); if (!env) env = "config.out"; configStream = simout.find(env); if (!configfile_found) panic("no configuration file specified!"); // The configuration database is now complete; start processing it. IniFile inifile; if (!pyconfig.output(inifile)) panic("Error processing python code"); // Initialize statistics database Stats::InitSimStats(); // Now process the configuration hierarchy and create the SimObjects. ConfigHierarchy configHierarchy(inifile); configHierarchy.build(); configHierarchy.createSimObjects(); // Parse and check all non-config-hierarchy parameters. ParamContext::parseAllContexts(inifile); ParamContext::checkAllContexts(); // Print hello message to stats file if it's actually a file. If // it's not (i.e. it's cout or cerr) then we already did it above. if (simout.isFile(*outputStream)) sayHello(*outputStream); // Echo command line and all parameter settings to stats file as well. echoCommandLine(argc, argv, *outputStream); ParamContext::showAllContexts(*configStream); // Do a second pass to finish initializing the sim objects SimObject::initAll(); // Restore checkpointed state, if any. configHierarchy.unserializeSimObjects(); // Done processing the configuration database. // Check for unreferenced entries. if (inifile.printUnreferenced()) panic("unreferenced sections/entries in the intermediate ini file"); SimObject::regAllStats(); // uncomment the following to get PC-based execution-time profile #ifdef DO_PROFILE init_profile((char *)&_init, (char *)&_fini); #endif // Check to make sure that the stats package is properly initialized Stats::check(); // Reset to put the stats in a consistent state. Stats::reset(); warn("Entering event queue. Starting simulation...\n"); SimStartup(); while (!mainEventQueue.empty()) { assert(curTick <= mainEventQueue.nextTick() && "event scheduled in the past"); // forward current cycle to the time of the first event on the // queue curTick = mainEventQueue.nextTick(); mainEventQueue.serviceOne(); if (async_event) { async_event = false; if (async_dump) { async_dump = false; using namespace Stats; SetupEvent(Dump, curTick); } if (async_dumpreset) { async_dumpreset = false; using namespace Stats; SetupEvent(Dump | Reset, curTick); } if (async_exit) { async_exit = false; new SimExitEvent("User requested STOP"); } if (async_io || async_alarm) { async_io = false; async_alarm = false; pollQueue.service(); } } } // This should never happen... every conceivable way for the // simulation to terminate (hit max cycles/insts, signal, // simulated system halts/exits) generates an exit event, so we // should never run out of events on the queue. exitNow("no events on event loop! All CPUs must be idle.", 1); return 0; } <|endoftext|>
<commit_before>/*============================================================================= NiftyLink: A software library to facilitate communication over OpenIGTLink. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #include "OIGTLMessage.h" #include "QsLog.h" #include "QsLogDest.h" #include "NiftyLinkUtils.h" OIGTLMessage::OIGTLMessage(void) { m_timeCreated = igtl::TimeStamp::New(); m_timeCreated->GetTime(); m_senderPort = -1; m_senderHostName = QString("localhost"); m_id = GetTimeInNanoSeconds(m_timeCreated); //m_timeCreated = NULL; m_resolution = 0; m_processed = 0; m_ownerName.append("!"); } OIGTLMessage::~OIGTLMessage(void) { //QLOG_INFO() <<"Message destructor (Base class): "<<m_ownerName <<m_id; m_message.operator =(NULL); m_timeReceived.operator =(NULL); m_timeCreated.operator =(NULL); } OIGTLMessage::OIGTLMessage(const OIGTLMessage &other) : QSharedData(other) { // Copy constructor m_message.operator =(other.m_message); m_timeReceived.operator=(other.m_timeReceived); m_senderHostName = other.m_senderHostName; m_messageType = other.m_messageType; m_senderPort = other.m_senderPort; m_resolution = other.m_resolution; m_id = other.m_id; m_ownerName = other.m_ownerName; } void OIGTLMessage::setMessagePointer(igtl::MessageBase::Pointer mp) { // Embeds the OpenIGTLink message pointer into the message m_message.operator =(mp); m_messageType = QString(m_message->GetDeviceType()); m_message->GetTimeStamp(m_timeCreated); m_senderHostName = QString(m_message->GetDeviceName()); } void OIGTLMessage::getMessagePointer(igtl::MessageBase::Pointer &mp) { mp.operator = (m_message); } void OIGTLMessage::setTimeReceived(igtl::TimeStamp::Pointer ts) { m_timeReceived.operator=(ts); } igtl::TimeStamp::Pointer OIGTLMessage::getTimeReceived(void) { return m_timeReceived; } igtl::TimeStamp::Pointer OIGTLMessage::getTimeCreated(void) { return m_timeCreated; } igtlUint64 OIGTLMessage::getId(void) { return m_id; } void OIGTLMessage::changeHostName(QString hname) { if (m_message.IsNull()) return; m_senderHostName = hname; m_message->Unpack(); m_message->SetDeviceName(m_senderHostName.toStdString().c_str()); m_message->Pack(); } QString OIGTLMessage::getHostName(void) { if (m_message.IsNull()) return QString(); m_message->Unpack(); m_senderHostName = m_message->GetDeviceName(); m_message->Pack(); return m_senderHostName; } void OIGTLMessage::setPort(int port) { m_senderPort = port; } int OIGTLMessage::getPort(void) { return m_senderPort; } void OIGTLMessage::changeMessageType(QString type) { m_messageType = type; } QString OIGTLMessage::getMessageType(void) { return m_messageType; } void OIGTLMessage::setResolution(igtlUint64 res) { // This is to set the streaming frequency m_resolution = res; if (m_message.IsNull()) return; QString className(m_message->GetNameOfClass()); if (!className.contains("Start")) return; m_message->Unpack(); if (strcmp(m_message->GetNameOfClass(), "igtl::StartTransformMessage") == 0) { igtl::StartTransformMessage::Pointer pointer = static_cast<igtl::StartTransformMessage *>(m_message.GetPointer()); pointer->SetResolution(res); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartTrajectoryMessage") == 0) { igtl::StartTrajectoryMessage::Pointer pointer = static_cast<igtl::StartTrajectoryMessage *>(m_message.GetPointer()); pointer->SetResolution(res); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartTrackingDataMessage") == 0) { igtl::StartTrackingDataMessage::Pointer pointer = static_cast<igtl::StartTrackingDataMessage *>(m_message.GetPointer()); pointer->SetResolution(res); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartStringMessage") == 0) { igtl::StartStringMessage::Pointer pointer = static_cast<igtl::StartStringMessage *>(m_message.GetPointer()); pointer->SetResolution(res); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartStatusMessage") == 0) { igtl::StartStatusMessage::Pointer pointer = static_cast<igtl::StartStatusMessage *>(m_message.GetPointer()); pointer->SetResolution(res); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartQuaternionTrackingDataMessage") == 0) { igtl::StartQuaternionTrackingDataMessage::Pointer pointer = static_cast<igtl::StartQuaternionTrackingDataMessage *>(m_message.GetPointer()); pointer->SetResolution(res); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartPositionMessage") == 0) { igtl::StartPositionMessage::Pointer pointer = static_cast<igtl::StartPositionMessage *>(m_message.GetPointer()); pointer->SetResolution(res); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartPointMessage") == 0) { igtl::StartPointMessage::Pointer pointer = static_cast<igtl::StartPointMessage *>(m_message.GetPointer()); pointer->SetResolution(res); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartImageMessage") == 0) { igtl::StartImageMessage::Pointer pointer = static_cast<igtl::StartImageMessage *>(m_message.GetPointer()); pointer->SetResolution(res); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartBindMessage") == 0) { igtl::StartBindMessage::Pointer pointer = static_cast<igtl::StartBindMessage *>(m_message.GetPointer()); pointer->SetResolution(res); } m_message->Pack(); } void OIGTLMessage::getResolution(igtlUint64 &res) { if (m_message.IsNull()) return; QString className(m_message->GetNameOfClass()); if (!className.contains("Start")) return; m_message->Unpack(); if (strcmp(m_message->GetNameOfClass(), "igtl::StartTransformMessage") == 0) { igtl::StartTransformMessage::Pointer pointer = static_cast<igtl::StartTransformMessage *>(m_message.GetPointer()); m_resolution = pointer->GetResolution(); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartTrajectoryMessage") == 0) { igtl::StartTrajectoryMessage::Pointer pointer = static_cast<igtl::StartTrajectoryMessage *>(m_message.GetPointer()); m_resolution = pointer->GetResolution(); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartTrackingDataMessage") == 0) { igtl::StartTrackingDataMessage::Pointer pointer = static_cast<igtl::StartTrackingDataMessage *>(m_message.GetPointer()); m_resolution = pointer->GetResolution(); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartStringMessage") == 0) { igtl::StartStringMessage::Pointer pointer = static_cast<igtl::StartStringMessage *>(m_message.GetPointer()); m_resolution = pointer->GetResolution(); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartStatusMessage") == 0) { igtl::StartStatusMessage::Pointer pointer = static_cast<igtl::StartStatusMessage *>(m_message.GetPointer()); m_resolution = pointer->GetResolution(); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartQuaternionTrackingDataMessage") == 0) { igtl::StartQuaternionTrackingDataMessage::Pointer pointer = static_cast<igtl::StartQuaternionTrackingDataMessage *>(m_message.GetPointer()); m_resolution = pointer->GetResolution(); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartPositionMessage") == 0) { igtl::StartPositionMessage::Pointer pointer = static_cast<igtl::StartPositionMessage *>(m_message.GetPointer()); m_resolution = pointer->GetResolution(); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartPointMessage") == 0) { igtl::StartPointMessage::Pointer pointer = static_cast<igtl::StartPointMessage *>(m_message.GetPointer()); m_resolution = pointer->GetResolution(); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartImageMessage") == 0) { igtl::StartImageMessage::Pointer pointer = static_cast<igtl::StartImageMessage *>(m_message.GetPointer()); m_resolution = pointer->GetResolution(); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartBindMessage") == 0) { igtl::StartBindMessage::Pointer pointer = static_cast<igtl::StartBindMessage *>(m_message.GetPointer()); m_resolution = pointer->GetResolution(); } m_message->Pack(); res = m_resolution; } void OIGTLMessage::update(QString hostname, igtl::TimeStamp::Pointer ts) { // Updates timestamp and hostname if (m_message.IsNull()) return; m_timeCreated.operator =(ts); m_senderHostName = hostname; m_message->Unpack(); m_message->SetTimeStamp(ts); m_message->SetDeviceName(m_senderHostName.toStdString().c_str()); m_message->Pack(); } void OIGTLMessage::update(QString hostname) { // Updates timestamp and hostname if (m_message.IsNull()) return; igtl::TimeStamp::Pointer ts; ts = igtl::TimeStamp::New(); ts->GetTime_TAI(); m_timeCreated.operator =(ts); m_senderHostName = hostname; m_id = GetTimeInNanoSeconds(ts); m_message->Unpack(); m_message->SetTimeStamp(ts); m_message->SetDeviceName(m_senderHostName.toStdString().c_str()); m_message->Pack(); } void OIGTLMessage::setOwnerName(QString str) { if (!m_ownerName.isEmpty() && !m_ownerName.isNull()) m_ownerName.clear(); m_ownerName.append(str); } <commit_msg>Bug #1967: Switch back to UTC as too many places create UTC timestamps<commit_after>/*============================================================================= NiftyLink: A software library to facilitate communication over OpenIGTLink. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #include "OIGTLMessage.h" #include "QsLog.h" #include "QsLogDest.h" #include "NiftyLinkUtils.h" OIGTLMessage::OIGTLMessage(void) { m_timeCreated = igtl::TimeStamp::New(); m_timeCreated->GetTime(); m_senderPort = -1; m_senderHostName = QString("localhost"); m_id = GetTimeInNanoSeconds(m_timeCreated); //m_timeCreated = NULL; m_resolution = 0; m_processed = 0; m_ownerName.append("!"); } OIGTLMessage::~OIGTLMessage(void) { //QLOG_INFO() <<"Message destructor (Base class): "<<m_ownerName <<m_id; m_message.operator =(NULL); m_timeReceived.operator =(NULL); m_timeCreated.operator =(NULL); } OIGTLMessage::OIGTLMessage(const OIGTLMessage &other) : QSharedData(other) { // Copy constructor m_message.operator =(other.m_message); m_timeReceived.operator=(other.m_timeReceived); m_senderHostName = other.m_senderHostName; m_messageType = other.m_messageType; m_senderPort = other.m_senderPort; m_resolution = other.m_resolution; m_id = other.m_id; m_ownerName = other.m_ownerName; } void OIGTLMessage::setMessagePointer(igtl::MessageBase::Pointer mp) { // Embeds the OpenIGTLink message pointer into the message m_message.operator =(mp); m_messageType = QString(m_message->GetDeviceType()); m_message->GetTimeStamp(m_timeCreated); m_senderHostName = QString(m_message->GetDeviceName()); } void OIGTLMessage::getMessagePointer(igtl::MessageBase::Pointer &mp) { mp.operator = (m_message); } void OIGTLMessage::setTimeReceived(igtl::TimeStamp::Pointer ts) { m_timeReceived.operator=(ts); } igtl::TimeStamp::Pointer OIGTLMessage::getTimeReceived(void) { return m_timeReceived; } igtl::TimeStamp::Pointer OIGTLMessage::getTimeCreated(void) { return m_timeCreated; } igtlUint64 OIGTLMessage::getId(void) { return m_id; } void OIGTLMessage::changeHostName(QString hname) { if (m_message.IsNull()) return; m_senderHostName = hname; m_message->Unpack(); m_message->SetDeviceName(m_senderHostName.toStdString().c_str()); m_message->Pack(); } QString OIGTLMessage::getHostName(void) { if (m_message.IsNull()) return QString(); m_message->Unpack(); m_senderHostName = m_message->GetDeviceName(); m_message->Pack(); return m_senderHostName; } void OIGTLMessage::setPort(int port) { m_senderPort = port; } int OIGTLMessage::getPort(void) { return m_senderPort; } void OIGTLMessage::changeMessageType(QString type) { m_messageType = type; } QString OIGTLMessage::getMessageType(void) { return m_messageType; } void OIGTLMessage::setResolution(igtlUint64 res) { // This is to set the streaming frequency m_resolution = res; if (m_message.IsNull()) return; QString className(m_message->GetNameOfClass()); if (!className.contains("Start")) return; m_message->Unpack(); if (strcmp(m_message->GetNameOfClass(), "igtl::StartTransformMessage") == 0) { igtl::StartTransformMessage::Pointer pointer = static_cast<igtl::StartTransformMessage *>(m_message.GetPointer()); pointer->SetResolution(res); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartTrajectoryMessage") == 0) { igtl::StartTrajectoryMessage::Pointer pointer = static_cast<igtl::StartTrajectoryMessage *>(m_message.GetPointer()); pointer->SetResolution(res); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartTrackingDataMessage") == 0) { igtl::StartTrackingDataMessage::Pointer pointer = static_cast<igtl::StartTrackingDataMessage *>(m_message.GetPointer()); pointer->SetResolution(res); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartStringMessage") == 0) { igtl::StartStringMessage::Pointer pointer = static_cast<igtl::StartStringMessage *>(m_message.GetPointer()); pointer->SetResolution(res); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartStatusMessage") == 0) { igtl::StartStatusMessage::Pointer pointer = static_cast<igtl::StartStatusMessage *>(m_message.GetPointer()); pointer->SetResolution(res); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartQuaternionTrackingDataMessage") == 0) { igtl::StartQuaternionTrackingDataMessage::Pointer pointer = static_cast<igtl::StartQuaternionTrackingDataMessage *>(m_message.GetPointer()); pointer->SetResolution(res); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartPositionMessage") == 0) { igtl::StartPositionMessage::Pointer pointer = static_cast<igtl::StartPositionMessage *>(m_message.GetPointer()); pointer->SetResolution(res); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartPointMessage") == 0) { igtl::StartPointMessage::Pointer pointer = static_cast<igtl::StartPointMessage *>(m_message.GetPointer()); pointer->SetResolution(res); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartImageMessage") == 0) { igtl::StartImageMessage::Pointer pointer = static_cast<igtl::StartImageMessage *>(m_message.GetPointer()); pointer->SetResolution(res); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartBindMessage") == 0) { igtl::StartBindMessage::Pointer pointer = static_cast<igtl::StartBindMessage *>(m_message.GetPointer()); pointer->SetResolution(res); } m_message->Pack(); } void OIGTLMessage::getResolution(igtlUint64 &res) { if (m_message.IsNull()) return; QString className(m_message->GetNameOfClass()); if (!className.contains("Start")) return; m_message->Unpack(); if (strcmp(m_message->GetNameOfClass(), "igtl::StartTransformMessage") == 0) { igtl::StartTransformMessage::Pointer pointer = static_cast<igtl::StartTransformMessage *>(m_message.GetPointer()); m_resolution = pointer->GetResolution(); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartTrajectoryMessage") == 0) { igtl::StartTrajectoryMessage::Pointer pointer = static_cast<igtl::StartTrajectoryMessage *>(m_message.GetPointer()); m_resolution = pointer->GetResolution(); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartTrackingDataMessage") == 0) { igtl::StartTrackingDataMessage::Pointer pointer = static_cast<igtl::StartTrackingDataMessage *>(m_message.GetPointer()); m_resolution = pointer->GetResolution(); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartStringMessage") == 0) { igtl::StartStringMessage::Pointer pointer = static_cast<igtl::StartStringMessage *>(m_message.GetPointer()); m_resolution = pointer->GetResolution(); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartStatusMessage") == 0) { igtl::StartStatusMessage::Pointer pointer = static_cast<igtl::StartStatusMessage *>(m_message.GetPointer()); m_resolution = pointer->GetResolution(); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartQuaternionTrackingDataMessage") == 0) { igtl::StartQuaternionTrackingDataMessage::Pointer pointer = static_cast<igtl::StartQuaternionTrackingDataMessage *>(m_message.GetPointer()); m_resolution = pointer->GetResolution(); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartPositionMessage") == 0) { igtl::StartPositionMessage::Pointer pointer = static_cast<igtl::StartPositionMessage *>(m_message.GetPointer()); m_resolution = pointer->GetResolution(); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartPointMessage") == 0) { igtl::StartPointMessage::Pointer pointer = static_cast<igtl::StartPointMessage *>(m_message.GetPointer()); m_resolution = pointer->GetResolution(); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartImageMessage") == 0) { igtl::StartImageMessage::Pointer pointer = static_cast<igtl::StartImageMessage *>(m_message.GetPointer()); m_resolution = pointer->GetResolution(); } else if (strcmp(m_message->GetNameOfClass(), "igtl::StartBindMessage") == 0) { igtl::StartBindMessage::Pointer pointer = static_cast<igtl::StartBindMessage *>(m_message.GetPointer()); m_resolution = pointer->GetResolution(); } m_message->Pack(); res = m_resolution; } void OIGTLMessage::update(QString hostname, igtl::TimeStamp::Pointer ts) { // Updates timestamp and hostname if (m_message.IsNull()) return; m_timeCreated.operator =(ts); m_senderHostName = hostname; m_message->Unpack(); m_message->SetTimeStamp(ts); m_message->SetDeviceName(m_senderHostName.toStdString().c_str()); m_message->Pack(); } void OIGTLMessage::update(QString hostname) { // Updates timestamp and hostname if (m_message.IsNull()) return; igtl::TimeStamp::Pointer ts; ts = igtl::TimeStamp::New(); ts->GetTime(); m_timeCreated.operator =(ts); m_senderHostName = hostname; m_id = GetTimeInNanoSeconds(ts); m_message->Unpack(); m_message->SetTimeStamp(ts); m_message->SetDeviceName(m_senderHostName.toStdString().c_str()); m_message->Pack(); } void OIGTLMessage::setOwnerName(QString str) { if (!m_ownerName.isEmpty() && !m_ownerName.isNull()) m_ownerName.clear(); m_ownerName.append(str); } <|endoftext|>
<commit_before>//===--- CFG.cpp - Defines the CFG data structure ----------------*- C++ -*-==// // // 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 // //===----------------------------------------------------------------------===// #include "swift/AST/AST.h" #include "swift/AST/ASTVisitor.h" #include "swift/CFG/CFG.h" #include "llvm/ADT/OwningPtr.h" using namespace swift; CFG::CFG() {} CFG::~CFG() { // FIXME: if all parts of BasicBlock are BumpPtrAllocated, this shouldn't // eventually be needed. for(BasicBlock &B : blocks) { B.~BasicBlock(); } } //===----------------------------------------------------------------------===// // CFG construction. //===----------------------------------------------------------------------===// static Expr *ignoreParens(Expr *Ex) { while (ParenExpr *P = dyn_cast<ParenExpr>(Ex)) { Ex = P->getSubExpr(); } return Ex; } namespace { class CFGBuilder : public ASTVisitor<CFGBuilder, CFGValue> { typedef llvm::SmallVector<BasicBlock *, 4> BlocksVector; BlocksVector BasePendingMerges; llvm::SmallVector<BlocksVector *, 4> PendingMergesStack; llvm::SmallVector<BlocksVector *, 4> BreakStack; llvm::SmallVector<BlocksVector *, 4> ContinueStack; /// Mapping from expressions to instructions. llvm::DenseMap<Expr *, Instruction *> ExprToInst; /// The current basic block being constructed. BasicBlock *Block; /// The CFG being constructed. CFG &C; public: CFGBuilder(CFG &C) : Block(0), C(C), badCFG(false) { PendingMergesStack.push_back(&BasePendingMerges); } ~CFGBuilder() {} /// A flag indicating whether or not there were problems /// constructing the CFG. bool badCFG; BlocksVector &pendingMerges() { assert(!PendingMergesStack.empty()); return *PendingMergesStack.back(); } void flushPending(BasicBlock *TargetBlock) { for (auto PredBlock : pendingMerges()) { // If the block has no terminator, we need to add an unconditional // jump to the block we are creating. if (!PredBlock->hasTerminator()) { UncondBranchInst *UB = new (C) UncondBranchInst(PredBlock); UB->setTarget(TargetBlock, ArrayRef<CFGValue>()); continue; } TermInst &Term = cast<TermInst>(PredBlock->instructions.back()); if (UncondBranchInst *UBI = dyn_cast<UncondBranchInst>(&Term)) { assert(UBI->targetBlock() == nullptr); UBI->setTarget(TargetBlock, ArrayRef<CFGValue>()); continue; } // If the block already has a CondBranch terminator, then it means // we are fixing up one of the branch targets because it wasn't // available when the instruction was created. CondBranchInst &CBI = cast<CondBranchInst>(Term); assert(CBI.branches()[0]); assert(!CBI.branches()[1]); CBI.branches()[1] = TargetBlock; TargetBlock->addPred(PredBlock); } pendingMerges().clear(); } /// The current basic block being constructed. BasicBlock *currentBlock() { if (!Block) { Block = new (C) BasicBlock(&C); // Flush out all pending merges. These are basic blocks waiting // for a successor. flushPending(Block); } return Block; } void addCurrentBlockToPending() { if (Block && !Block->hasTerminator()) { pendingMerges().push_back(Block); } Block = 0; } /// Reset the currently active basic block by creating a new one. BasicBlock *createFreshBlock() { Block = new (C) BasicBlock(&C); return Block; } CFGValue addInst(Expr *Ex, Instruction *I) { ExprToInst[Ex] = I; return I; } void finishUp() { assert(PendingMergesStack.size() == 1); if (!pendingMerges().empty()) { assert(Block == 0); new (C) ReturnInst(currentBlock()); return; } // Check if the last block has a Return. if (!Block) return; if (Block->instructions.empty() || !isa<ReturnInst>(Block->instructions.back())) { new (C) ReturnInst(Block); } } void popBreakStack(BlocksVector &BlocksThatBreak) { assert(BreakStack.back() == &BlocksThatBreak); for (auto BreakBlock : BlocksThatBreak) { pendingMerges().push_back(BreakBlock); } BreakStack.pop_back(); } void popContinueStack(BlocksVector &BlocksThatContinue, BasicBlock *TargetBlock) { assert(ContinueStack.back() == &BlocksThatContinue); for (auto ContinueBlock : BlocksThatContinue) { assert(ContinueBlock->hasTerminator()); UncondBranchInst &UB = cast<UncondBranchInst>(ContinueBlock->instructions.back()); UB.setTarget(TargetBlock, ArrayRef<CFGValue>()); } ContinueStack.pop_back(); } //===--------------------------------------------------------------------===// // Statements. //===--------------------------------------------------------------------===// /// Construct the CFG components for the given BraceStmt. void visitBraceStmt(BraceStmt *S); /// SemiStmts are ignored for CFG construction. void visitSemiStmt(SemiStmt *S) {} void visitAssignStmt(AssignStmt *S) { assert(false && "Not yet implemented"); } void visitReturnStmt(ReturnStmt *S) { CFGValue ArgV = S->hasResult() ? visit(S->getResult()) : (Instruction*) 0; (void) new (C) ReturnInst(S, ArgV, currentBlock()); // Treat the current block as "complete" with no successors. Block = 0; } void visitIfStmt(IfStmt *S); void visitWhileStmt(WhileStmt *S); void visitDoWhileStmt(DoWhileStmt *S) { assert(false && "Not yet implemented"); } void visitForStmt(ForStmt *S) { assert(false && "Not yet implemented"); } void visitForEachStmt(ForEachStmt *S) { badCFG = true; return; } void visitBreakStmt(BreakStmt *S); void visitContinueStmt(ContinueStmt *S); //===--------------------------------------------------------------------===// // Expressions. //===--------------------------------------------------------------------===// CFGValue visitExpr(Expr *E) { llvm_unreachable("Not yet implemented"); } CFGValue visitCallExpr(CallExpr *E); CFGValue visitDeclRefExpr(DeclRefExpr *E); CFGValue visitIntegerLiteralExpr(IntegerLiteralExpr *E); CFGValue visitLoadExpr(LoadExpr *E); CFGValue visitParenExpr(ParenExpr *E); CFGValue visitThisApplyExpr(ThisApplyExpr *E); CFGValue visitTupleExpr(TupleExpr *E); CFGValue visitTypeOfExpr(TypeOfExpr *E); }; } // end anonymous namespace CFG *CFG::constructCFG(Stmt *S) { // FIXME: implement CFG construction. llvm::OwningPtr<CFG> C(new CFG()); CFGBuilder builder(*C); builder.visit(S); if (!builder.badCFG) { builder.finishUp(); return C.take(); } return nullptr; } void CFGBuilder::visitBraceStmt(BraceStmt *S) { // BraceStmts do not need to be explicitly represented in the CFG. // We should consider whether or not the scopes they introduce are // represented in the CFG. for (const BraceStmt::ExprStmtOrDecl &ESD : S->elements()) { assert(!ESD.is<Decl*>() && "FIXME: Handle Decls"); if (Stmt *S = ESD.dyn_cast<Stmt*>()) visit(S); if (Expr *E = ESD.dyn_cast<Expr*>()) visit(E); } } //===--------------------------------------------------------------------===// // Control-flow. //===--------------------------------------------------------------------===// void CFGBuilder::visitBreakStmt(BreakStmt *S) { assert(!BreakStack.empty()); BasicBlock *BreakBlock = currentBlock(); BreakStack.back()->push_back(BreakBlock); // FIXME: we need to be able to include the BreakStmt in the jump. new (C) UncondBranchInst(BreakBlock); Block = 0; } void CFGBuilder::visitContinueStmt(ContinueStmt *S) { assert(!ContinueStack.empty()); BasicBlock *ContinueBlock = currentBlock(); ContinueStack.back()->push_back(ContinueBlock); // FIXME: we need to be able to include the ContinueStmt in the jump. new (C) UncondBranchInst(ContinueBlock); Block = 0; } void CFGBuilder::visitIfStmt(IfStmt *S) { // ** FIXME ** Handle the condition. We need to handle more of the // statements first. // The condition should be the last value evaluated just before the // terminator. // CFGValue CondV = visit(S->getCond()); CFGValue CondV = (Instruction*) 0; // Save the current block. We will use it to construct the // CondBranchInst. BasicBlock *IfTermBlock = currentBlock(); // Reset the state for the current block. Block = 0; // Create a new basic block for the first target. BasicBlock *Target1 = createFreshBlock(); visit(S->getThenStmt()); addCurrentBlockToPending(); // Handle an (optional) 'else'. If no 'else' is found, the false branch // will be fixed up later. BasicBlock *Target2 = nullptr; if (Stmt *Else = S->getElseStmt()) { // Create a new basic block for the second target. The first target's // blocks will get added the "pending" list. Target2 = createFreshBlock(); visit(Else); addCurrentBlockToPending(); } else { // If we have no 'else', we need to fix up the branch later. pendingMerges().push_back(IfTermBlock); } // Finally, hook up the block with the condition to the target blocks. CFGValue Branch = new (C) CondBranchInst(S, CondV, Target1, Target2 /* may be null*/, IfTermBlock); (void) Branch; } void CFGBuilder::visitWhileStmt(WhileStmt *S) { // The condition needs to be in its own basic block so that // it can be the loop-back target. We thus finish up the currently // active block. It will get linked to the new block once we // create it. addCurrentBlockToPending(); // Process the condition. This will link up the previous block // with the condition block. BasicBlock *ConditionBlock = currentBlock(); CFGValue CondV = (Instruction*) 0; // visit(S->getCond()); assert(ConditionBlock == Block); Block = 0; // Set up a vector to record blocks that 'break'. BlocksVector BlocksThatBreak; BreakStack.push_back(&BlocksThatBreak); // Set up a vector to record blocks that 'continue'. BlocksVector BlocksThatContinue; ContinueStack.push_back(&BlocksThatContinue); // Push a new context to record pending blocks. These will // get linked up the condition block. BlocksVector PendingWithinLoop; PendingMergesStack.push_back(&PendingWithinLoop); // Create a new basic block for the body. BasicBlock *BodyBlock = createFreshBlock(); visit(S->getBody()); addCurrentBlockToPending(); // Pop the pending merges. assert(PendingMergesStack.back() == &PendingWithinLoop); flushPending(ConditionBlock); PendingMergesStack.pop_back(); // Pop the 'break' context. popBreakStack(BlocksThatBreak); // Pop the 'continue' context. popContinueStack(BlocksThatContinue, ConditionBlock); // Finally, hook up the block with the condition to the target blocks. CFGValue Branch = new (C) CondBranchInst(S, CondV, BodyBlock, 0, /* will be fixed up later */ ConditionBlock); (void) Branch; pendingMerges().push_back(ConditionBlock); } //===--------------------------------------------------------------------===// // Expressions. //===--------------------------------------------------------------------===// CFGValue CFGBuilder::visitCallExpr(CallExpr *E) { Expr *Arg = ignoreParens(E->getArg()); Expr *Fn = E->getFn(); CFGValue FnV = visit(Fn); llvm::SmallVector<CFGValue, 10> ArgsV; // Special case Arg being a TupleExpr, to inline the arguments and // not create another instruction. if (TupleExpr *TU = dyn_cast<TupleExpr>(Arg)) { for (auto arg : TU->getElements()) ArgsV.push_back(visit(arg)); } else { ArgsV.push_back(visit(Arg)); } return addInst(E, CallInst::create(E, currentBlock(), FnV, ArgsV)); } CFGValue CFGBuilder::visitDeclRefExpr(DeclRefExpr *E) { return addInst(E, new (C) DeclRefInst(E, currentBlock())); } CFGValue CFGBuilder::visitThisApplyExpr(ThisApplyExpr *E) { CFGValue FnV = visit(E->getFn()); CFGValue ArgV = visit(E->getArg()); return addInst(E, new (C) ThisApplyInst(E, FnV, ArgV, currentBlock())); } CFGValue CFGBuilder::visitIntegerLiteralExpr(IntegerLiteralExpr *E) { return addInst(E, new (C) IntegerLiteralInst(E, currentBlock())); } CFGValue CFGBuilder::visitLoadExpr(LoadExpr *E) { CFGValue SubV = visit(E->getSubExpr()); return addInst(E, new (C) LoadInst(E, SubV, currentBlock())); } CFGValue CFGBuilder::visitParenExpr(ParenExpr *E) { return visit(E->getSubExpr()); } CFGValue CFGBuilder::visitTupleExpr(TupleExpr *E) { llvm::SmallVector<CFGValue, 10> ArgsV; for (auto &I : E->getElements()) { ArgsV.push_back(visit(I)); } return addInst(E, TupleInst::create(E, ArgsV, currentBlock())); } CFGValue CFGBuilder::visitTypeOfExpr(TypeOfExpr *E) { return addInst(E, new (C) TypeOfInst(E, currentBlock())); } <commit_msg>Add CFG support for do...while.<commit_after>//===--- CFG.cpp - Defines the CFG data structure ----------------*- C++ -*-==// // // 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 // //===----------------------------------------------------------------------===// #include "swift/AST/AST.h" #include "swift/AST/ASTVisitor.h" #include "swift/CFG/CFG.h" #include "llvm/ADT/OwningPtr.h" using namespace swift; CFG::CFG() {} CFG::~CFG() { // FIXME: if all parts of BasicBlock are BumpPtrAllocated, this shouldn't // eventually be needed. for(BasicBlock &B : blocks) { B.~BasicBlock(); } } //===----------------------------------------------------------------------===// // CFG construction. //===----------------------------------------------------------------------===// static Expr *ignoreParens(Expr *Ex) { while (ParenExpr *P = dyn_cast<ParenExpr>(Ex)) { Ex = P->getSubExpr(); } return Ex; } namespace { class CFGBuilder : public ASTVisitor<CFGBuilder, CFGValue> { typedef llvm::SmallVector<BasicBlock *, 4> BlocksVector; BlocksVector BasePendingMerges; llvm::SmallVector<BlocksVector *, 4> PendingMergesStack; llvm::SmallVector<BlocksVector *, 4> BreakStack; llvm::SmallVector<BlocksVector *, 4> ContinueStack; /// Mapping from expressions to instructions. llvm::DenseMap<Expr *, Instruction *> ExprToInst; /// The current basic block being constructed. BasicBlock *Block; /// The CFG being constructed. CFG &C; public: CFGBuilder(CFG &C) : Block(0), C(C), badCFG(false) { PendingMergesStack.push_back(&BasePendingMerges); } ~CFGBuilder() {} /// A flag indicating whether or not there were problems /// constructing the CFG. bool badCFG; BlocksVector &pendingMerges() { assert(!PendingMergesStack.empty()); return *PendingMergesStack.back(); } void flushPending(BasicBlock *TargetBlock) { for (auto PredBlock : pendingMerges()) { // If the block has no terminator, we need to add an unconditional // jump to the block we are creating. if (!PredBlock->hasTerminator()) { UncondBranchInst *UB = new (C) UncondBranchInst(PredBlock); UB->setTarget(TargetBlock, ArrayRef<CFGValue>()); continue; } TermInst &Term = cast<TermInst>(PredBlock->instructions.back()); if (UncondBranchInst *UBI = dyn_cast<UncondBranchInst>(&Term)) { assert(UBI->targetBlock() == nullptr); UBI->setTarget(TargetBlock, ArrayRef<CFGValue>()); continue; } // If the block already has a CondBranch terminator, then it means // we are fixing up one of the branch targets because it wasn't // available when the instruction was created. CondBranchInst &CBI = cast<CondBranchInst>(Term); assert(CBI.branches()[0]); assert(!CBI.branches()[1]); CBI.branches()[1] = TargetBlock; TargetBlock->addPred(PredBlock); } pendingMerges().clear(); } /// The current basic block being constructed. BasicBlock *currentBlock() { if (!Block) { Block = new (C) BasicBlock(&C); // Flush out all pending merges. These are basic blocks waiting // for a successor. flushPending(Block); } return Block; } void addCurrentBlockToPending() { if (Block && !Block->hasTerminator()) { pendingMerges().push_back(Block); } Block = 0; } /// Reset the currently active basic block by creating a new one. BasicBlock *createFreshBlock() { Block = new (C) BasicBlock(&C); return Block; } CFGValue addInst(Expr *Ex, Instruction *I) { ExprToInst[Ex] = I; return I; } void finishUp() { assert(PendingMergesStack.size() == 1); if (!pendingMerges().empty()) { assert(Block == 0); new (C) ReturnInst(currentBlock()); return; } // Check if the last block has a Return. if (!Block) return; if (Block->instructions.empty() || !isa<ReturnInst>(Block->instructions.back())) { new (C) ReturnInst(Block); } } void popBreakStack(BlocksVector &BlocksThatBreak) { assert(BreakStack.back() == &BlocksThatBreak); for (auto BreakBlock : BlocksThatBreak) { pendingMerges().push_back(BreakBlock); } BreakStack.pop_back(); } void popContinueStack(BlocksVector &BlocksThatContinue, BasicBlock *TargetBlock) { assert(ContinueStack.back() == &BlocksThatContinue); for (auto ContinueBlock : BlocksThatContinue) { assert(ContinueBlock->hasTerminator()); UncondBranchInst &UB = cast<UncondBranchInst>(ContinueBlock->instructions.back()); UB.setTarget(TargetBlock, ArrayRef<CFGValue>()); } ContinueStack.pop_back(); } //===--------------------------------------------------------------------===// // Statements. //===--------------------------------------------------------------------===// /// Construct the CFG components for the given BraceStmt. void visitBraceStmt(BraceStmt *S); /// SemiStmts are ignored for CFG construction. void visitSemiStmt(SemiStmt *S) {} void visitAssignStmt(AssignStmt *S) { assert(false && "Not yet implemented"); } void visitReturnStmt(ReturnStmt *S) { CFGValue ArgV = S->hasResult() ? visit(S->getResult()) : (Instruction*) 0; (void) new (C) ReturnInst(S, ArgV, currentBlock()); // Treat the current block as "complete" with no successors. Block = 0; } void visitIfStmt(IfStmt *S); void visitWhileStmt(WhileStmt *S); void visitDoWhileStmt(DoWhileStmt *S); void visitForStmt(ForStmt *S) { assert(false && "Not yet implemented"); } void visitForEachStmt(ForEachStmt *S) { badCFG = true; return; } void visitBreakStmt(BreakStmt *S); void visitContinueStmt(ContinueStmt *S); //===--------------------------------------------------------------------===// // Expressions. //===--------------------------------------------------------------------===// CFGValue visitExpr(Expr *E) { llvm_unreachable("Not yet implemented"); } CFGValue visitCallExpr(CallExpr *E); CFGValue visitDeclRefExpr(DeclRefExpr *E); CFGValue visitIntegerLiteralExpr(IntegerLiteralExpr *E); CFGValue visitLoadExpr(LoadExpr *E); CFGValue visitParenExpr(ParenExpr *E); CFGValue visitThisApplyExpr(ThisApplyExpr *E); CFGValue visitTupleExpr(TupleExpr *E); CFGValue visitTypeOfExpr(TypeOfExpr *E); }; } // end anonymous namespace CFG *CFG::constructCFG(Stmt *S) { // FIXME: implement CFG construction. llvm::OwningPtr<CFG> C(new CFG()); CFGBuilder builder(*C); builder.visit(S); if (!builder.badCFG) { builder.finishUp(); return C.take(); } return nullptr; } void CFGBuilder::visitBraceStmt(BraceStmt *S) { // BraceStmts do not need to be explicitly represented in the CFG. // We should consider whether or not the scopes they introduce are // represented in the CFG. for (const BraceStmt::ExprStmtOrDecl &ESD : S->elements()) { assert(!ESD.is<Decl*>() && "FIXME: Handle Decls"); if (Stmt *S = ESD.dyn_cast<Stmt*>()) visit(S); if (Expr *E = ESD.dyn_cast<Expr*>()) visit(E); } } //===--------------------------------------------------------------------===// // Control-flow. //===--------------------------------------------------------------------===// void CFGBuilder::visitBreakStmt(BreakStmt *S) { assert(!BreakStack.empty()); BasicBlock *BreakBlock = currentBlock(); BreakStack.back()->push_back(BreakBlock); // FIXME: we need to be able to include the BreakStmt in the jump. new (C) UncondBranchInst(BreakBlock); Block = 0; } void CFGBuilder::visitContinueStmt(ContinueStmt *S) { assert(!ContinueStack.empty()); BasicBlock *ContinueBlock = currentBlock(); ContinueStack.back()->push_back(ContinueBlock); // FIXME: we need to be able to include the ContinueStmt in the jump. new (C) UncondBranchInst(ContinueBlock); Block = 0; } void CFGBuilder::visitDoWhileStmt(DoWhileStmt *S) { // Set up a vector to record blocks that 'break'. BlocksVector BlocksThatBreak; BreakStack.push_back(&BlocksThatBreak); // Set up a vector to record blocks that 'continue'. BlocksVector BlocksThatContinue; ContinueStack.push_back(&BlocksThatContinue); // Create a new basic block for the body. addCurrentBlockToPending(); BasicBlock *BodyBlock = currentBlock(); // Push a new context to record pending blocks. These will // get linked up the condition block. BlocksVector PendingWithinLoop; PendingMergesStack.push_back(&PendingWithinLoop); // Now visit the loop body. visit(S->getBody()); addCurrentBlockToPending(); // Create the condition block. BasicBlock *ConditionBlock = currentBlock(); CFGValue CondV = (Instruction*) 0; // visit(S->getCond()); assert(ConditionBlock == Block); Block = 0; // Pop the pending merges. assert(PendingMergesStack.back() == &PendingWithinLoop); flushPending(ConditionBlock); PendingMergesStack.pop_back(); // Pop the 'break' context. popBreakStack(BlocksThatBreak); // Pop the 'continue' context. popContinueStack(BlocksThatContinue, ConditionBlock); // Finally, hook up the block with the condition to the target blocks. CFGValue Branch = new (C) CondBranchInst(S, CondV, BodyBlock, 0, /* will be fixed up later */ ConditionBlock); (void) Branch; pendingMerges().push_back(ConditionBlock); } void CFGBuilder::visitIfStmt(IfStmt *S) { // ** FIXME ** Handle the condition. We need to handle more of the // statements first. // The condition should be the last value evaluated just before the // terminator. // CFGValue CondV = visit(S->getCond()); CFGValue CondV = (Instruction*) 0; // Save the current block. We will use it to construct the // CondBranchInst. BasicBlock *IfTermBlock = currentBlock(); // Reset the state for the current block. Block = 0; // Create a new basic block for the first target. BasicBlock *Target1 = createFreshBlock(); visit(S->getThenStmt()); addCurrentBlockToPending(); // Handle an (optional) 'else'. If no 'else' is found, the false branch // will be fixed up later. BasicBlock *Target2 = nullptr; if (Stmt *Else = S->getElseStmt()) { // Create a new basic block for the second target. The first target's // blocks will get added the "pending" list. Target2 = createFreshBlock(); visit(Else); addCurrentBlockToPending(); } else { // If we have no 'else', we need to fix up the branch later. pendingMerges().push_back(IfTermBlock); } // Finally, hook up the block with the condition to the target blocks. CFGValue Branch = new (C) CondBranchInst(S, CondV, Target1, Target2 /* may be null*/, IfTermBlock); (void) Branch; } void CFGBuilder::visitWhileStmt(WhileStmt *S) { // The condition needs to be in its own basic block so that // it can be the loop-back target. We thus finish up the currently // active block. It will get linked to the new block once we // create it. addCurrentBlockToPending(); // Process the condition. This will link up the previous block // with the condition block. BasicBlock *ConditionBlock = currentBlock(); CFGValue CondV = (Instruction*) 0; // visit(S->getCond()); assert(ConditionBlock == Block); Block = 0; // Set up a vector to record blocks that 'break'. BlocksVector BlocksThatBreak; BreakStack.push_back(&BlocksThatBreak); // Set up a vector to record blocks that 'continue'. BlocksVector BlocksThatContinue; ContinueStack.push_back(&BlocksThatContinue); // Push a new context to record pending blocks. These will // get linked up the condition block. BlocksVector PendingWithinLoop; PendingMergesStack.push_back(&PendingWithinLoop); // Create a new basic block for the body. BasicBlock *BodyBlock = createFreshBlock(); visit(S->getBody()); addCurrentBlockToPending(); // Pop the pending merges. assert(PendingMergesStack.back() == &PendingWithinLoop); flushPending(ConditionBlock); PendingMergesStack.pop_back(); // Pop the 'break' context. popBreakStack(BlocksThatBreak); // Pop the 'continue' context. popContinueStack(BlocksThatContinue, ConditionBlock); // Finally, hook up the block with the condition to the target blocks. CFGValue Branch = new (C) CondBranchInst(S, CondV, BodyBlock, 0, /* will be fixed up later */ ConditionBlock); (void) Branch; pendingMerges().push_back(ConditionBlock); } //===--------------------------------------------------------------------===// // Expressions. //===--------------------------------------------------------------------===// CFGValue CFGBuilder::visitCallExpr(CallExpr *E) { Expr *Arg = ignoreParens(E->getArg()); Expr *Fn = E->getFn(); CFGValue FnV = visit(Fn); llvm::SmallVector<CFGValue, 10> ArgsV; // Special case Arg being a TupleExpr, to inline the arguments and // not create another instruction. if (TupleExpr *TU = dyn_cast<TupleExpr>(Arg)) { for (auto arg : TU->getElements()) ArgsV.push_back(visit(arg)); } else { ArgsV.push_back(visit(Arg)); } return addInst(E, CallInst::create(E, currentBlock(), FnV, ArgsV)); } CFGValue CFGBuilder::visitDeclRefExpr(DeclRefExpr *E) { return addInst(E, new (C) DeclRefInst(E, currentBlock())); } CFGValue CFGBuilder::visitThisApplyExpr(ThisApplyExpr *E) { CFGValue FnV = visit(E->getFn()); CFGValue ArgV = visit(E->getArg()); return addInst(E, new (C) ThisApplyInst(E, FnV, ArgV, currentBlock())); } CFGValue CFGBuilder::visitIntegerLiteralExpr(IntegerLiteralExpr *E) { return addInst(E, new (C) IntegerLiteralInst(E, currentBlock())); } CFGValue CFGBuilder::visitLoadExpr(LoadExpr *E) { CFGValue SubV = visit(E->getSubExpr()); return addInst(E, new (C) LoadInst(E, SubV, currentBlock())); } CFGValue CFGBuilder::visitParenExpr(ParenExpr *E) { return visit(E->getSubExpr()); } CFGValue CFGBuilder::visitTupleExpr(TupleExpr *E) { llvm::SmallVector<CFGValue, 10> ArgsV; for (auto &I : E->getElements()) { ArgsV.push_back(visit(I)); } return addInst(E, TupleInst::create(E, ArgsV, currentBlock())); } CFGValue CFGBuilder::visitTypeOfExpr(TypeOfExpr *E) { return addInst(E, new (C) TypeOfInst(E, currentBlock())); } <|endoftext|>
<commit_before>/* * Copyright (C) 2018 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "tests/test-utils.hh" #include "tests/cql_test_env.hh" #include "tests/cql_assertions.hh" SEASTAR_TEST_CASE(test_secondary_index_regular_column_query) { return do_with_cql_env([] (cql_test_env& e) { return e.execute_cql("CREATE TABLE users (userid int, name text, email text, country text, PRIMARY KEY (userid));").discard_result().then([&e] { return e.execute_cql("CREATE INDEX ON users (email);").discard_result(); }).then([&e] { return e.execute_cql("CREATE INDEX ON users (country);").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (0, 'Bondie Easseby', 'beassebyv@house.gov', 'France');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (1, 'Demetri Curror', 'dcurrorw@techcrunch.com', 'France');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (2, 'Langston Paulisch', 'lpaulischm@reverbnation.com', 'United States');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (3, 'Channa Devote', 'cdevote14@marriott.com', 'Denmark');").discard_result(); }).then([&e] { return e.execute_cql("SELECT email FROM users WHERE country = 'France';"); }).then([&e] (shared_ptr<cql_transport::messages::result_message> msg) { assert_that(msg).is_rows().with_rows({ { utf8_type->decompose(sstring("beassebyv@house.gov")) }, { utf8_type->decompose(sstring("dcurrorw@techcrunch.com")) }, }); }); }); } SEASTAR_TEST_CASE(test_secondary_index_clustering_key_query) { return do_with_cql_env([] (cql_test_env& e) { return e.execute_cql("CREATE TABLE users (userid int, name text, email text, country text, PRIMARY KEY (userid, country));").discard_result().then([&e] { return e.execute_cql("CREATE INDEX ON users (country);").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (0, 'Bondie Easseby', 'beassebyv@house.gov', 'France');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (1, 'Demetri Curror', 'dcurrorw@techcrunch.com', 'France');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (2, 'Langston Paulisch', 'lpaulischm@reverbnation.com', 'United States');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (3, 'Channa Devote', 'cdevote14@marriott.com', 'Denmark');").discard_result(); }).then([&e] { return e.execute_cql("SELECT email FROM users WHERE country = 'France';"); }).then([&e] (auto msg) { assert_that(msg).is_rows().with_rows({ { utf8_type->decompose(sstring("beassebyv@house.gov")) }, { utf8_type->decompose(sstring("dcurrorw@techcrunch.com")) }, }); }); }); } // CQL usually folds identifier names - keyspace, table and column names - // to lowercase. That is, unless the identifier is enclosed in double // quotation marks ("). Let's test that case-sensitive (quoted) column // names can be indexed. This reproduces issue #3154. SEASTAR_TEST_CASE(test_secondary_index_case_sensitive) { return do_with_cql_env_thread([] (auto& e) { // Test case-sensitive *table* name. e.execute_cql("CREATE TABLE \"FooBar\" (a int PRIMARY KEY, b int, c int)").get(); e.execute_cql("CREATE INDEX ON \"FooBar\" (b)").get(); e.execute_cql("SELECT * from \"FooBar\" WHERE b = 1").get(); // Test case-sensitive *indexed column* name. // This not working was issue #3154. The symptom was that the SELECT // below threw a "No index found." runtime error. e.execute_cql("CREATE TABLE tab (a int PRIMARY KEY, \"FooBar\" int, c int)").get(); e.execute_cql("CREATE INDEX ON tab (\"FooBar\")").get(); e.execute_cql("SELECT * from tab WHERE \"FooBar\" = 1").get(); }); } SEASTAR_TEST_CASE(test_cannot_drop_secondary_index_backing_mv) { return do_with_cql_env_thread([] (cql_test_env& e) { e.execute_cql("create table cf (p int primary key, a int)").get(); e.execute_cql("create index on cf (a)").get(); auto s = e.local_db().find_schema(sstring("ks"), sstring("cf")); auto index_name = s->index_names().front(); assert_that_failed(e.execute_cql(sprint("drop materialized view %s_index", index_name))); }); } // Issue #3210 is about searching the secondary index not working properly // when the *partition key* has multiple columns (a compound partition key), // and this is what we test here. SEASTAR_TEST_CASE(test_secondary_index_case_compound_partition_key) { return do_with_cql_env_thread([] (auto& e) { // Test case-sensitive *table* name. e.execute_cql("CREATE TABLE tab (a int, b int, c int, PRIMARY KEY ((a, b)))").get(); e.execute_cql("CREATE INDEX ON tab (c)").get(); e.execute_cql("INSERT INTO tab (a, b, c) VALUES (1, 2, 3)").get(); eventually([&] { // We expect this search to find the single row, with the compound // partition key (a, b) = (1, 2). auto res = e.execute_cql("SELECT * from tab WHERE c = 3").get0(); assert_that(res).is_rows() .with_size(1) .with_row({ {int32_type->decompose(1)}, {int32_type->decompose(2)}, {int32_type->decompose(3)}, }); }); }); } <commit_msg>secondary index: improve testing of case-sensitive column names<commit_after>/* * Copyright (C) 2018 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include "tests/test-utils.hh" #include "tests/cql_test_env.hh" #include "tests/cql_assertions.hh" SEASTAR_TEST_CASE(test_secondary_index_regular_column_query) { return do_with_cql_env([] (cql_test_env& e) { return e.execute_cql("CREATE TABLE users (userid int, name text, email text, country text, PRIMARY KEY (userid));").discard_result().then([&e] { return e.execute_cql("CREATE INDEX ON users (email);").discard_result(); }).then([&e] { return e.execute_cql("CREATE INDEX ON users (country);").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (0, 'Bondie Easseby', 'beassebyv@house.gov', 'France');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (1, 'Demetri Curror', 'dcurrorw@techcrunch.com', 'France');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (2, 'Langston Paulisch', 'lpaulischm@reverbnation.com', 'United States');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (3, 'Channa Devote', 'cdevote14@marriott.com', 'Denmark');").discard_result(); }).then([&e] { return e.execute_cql("SELECT email FROM users WHERE country = 'France';"); }).then([&e] (shared_ptr<cql_transport::messages::result_message> msg) { assert_that(msg).is_rows().with_rows({ { utf8_type->decompose(sstring("beassebyv@house.gov")) }, { utf8_type->decompose(sstring("dcurrorw@techcrunch.com")) }, }); }); }); } SEASTAR_TEST_CASE(test_secondary_index_clustering_key_query) { return do_with_cql_env([] (cql_test_env& e) { return e.execute_cql("CREATE TABLE users (userid int, name text, email text, country text, PRIMARY KEY (userid, country));").discard_result().then([&e] { return e.execute_cql("CREATE INDEX ON users (country);").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (0, 'Bondie Easseby', 'beassebyv@house.gov', 'France');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (1, 'Demetri Curror', 'dcurrorw@techcrunch.com', 'France');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (2, 'Langston Paulisch', 'lpaulischm@reverbnation.com', 'United States');").discard_result(); }).then([&e] { return e.execute_cql("INSERT INTO users (userid, name, email, country) VALUES (3, 'Channa Devote', 'cdevote14@marriott.com', 'Denmark');").discard_result(); }).then([&e] { return e.execute_cql("SELECT email FROM users WHERE country = 'France';"); }).then([&e] (auto msg) { assert_that(msg).is_rows().with_rows({ { utf8_type->decompose(sstring("beassebyv@house.gov")) }, { utf8_type->decompose(sstring("dcurrorw@techcrunch.com")) }, }); }); }); } // CQL usually folds identifier names - keyspace, table and column names - // to lowercase. That is, unless the identifier is enclosed in double // quotation marks ("). Let's test that case-sensitive (quoted) column // names can be indexed. This reproduces issues #3154, #3388, #3391, #3401. SEASTAR_TEST_CASE(test_secondary_index_case_sensitive) { return do_with_cql_env_thread([] (auto& e) { // Test case-sensitive *table* name. e.execute_cql("CREATE TABLE \"FooBar\" (a int PRIMARY KEY, b int, c int)").get(); e.execute_cql("CREATE INDEX ON \"FooBar\" (b)").get(); e.execute_cql("INSERT INTO \"FooBar\" (a, b, c) VALUES (1, 2, 3)").get(); e.execute_cql("SELECT * from \"FooBar\" WHERE b = 1").get(); // Test case-sensitive *indexed column* name. // This not working was issue #3154. The symptom was that the SELECT // below threw a "No index found." runtime error. e.execute_cql("CREATE TABLE tab (a int PRIMARY KEY, \"FooBar\" int, c int)").get(); e.execute_cql("CREATE INDEX ON tab (\"FooBar\")").get(); // This INSERT also had problems (issue #3401) e.execute_cql("INSERT INTO tab (a, \"FooBar\", c) VALUES (1, 2, 3)").get(); e.execute_cql("SELECT * from tab WHERE \"FooBar\" = 2").get(); // Test case-sensitive *partition column* name. // This used to have multiple bugs in SI and MV code, detailed below: e.execute_cql("CREATE TABLE tab2 (\"FooBar\" int PRIMARY KEY, b int, c int)").get(); e.execute_cql("CREATE INDEX ON tab2 (b)").get(); // The following INSERT didn't work because of issues #3388 and #3391. e.execute_cql("INSERT INTO tab2 (\"FooBar\", b, c) VALUES (1, 2, 3)").get(); // After the insert works, add the SELECT and see it works. It used // to fail before the patch to #3210 fixed this incidentally. e.execute_cql("SELECT * from tab2 WHERE b = 2").get(); }); } SEASTAR_TEST_CASE(test_cannot_drop_secondary_index_backing_mv) { return do_with_cql_env_thread([] (cql_test_env& e) { e.execute_cql("create table cf (p int primary key, a int)").get(); e.execute_cql("create index on cf (a)").get(); auto s = e.local_db().find_schema(sstring("ks"), sstring("cf")); auto index_name = s->index_names().front(); assert_that_failed(e.execute_cql(sprint("drop materialized view %s_index", index_name))); }); } // Issue #3210 is about searching the secondary index not working properly // when the *partition key* has multiple columns (a compound partition key), // and this is what we test here. SEASTAR_TEST_CASE(test_secondary_index_case_compound_partition_key) { return do_with_cql_env_thread([] (auto& e) { // Test case-sensitive *table* name. e.execute_cql("CREATE TABLE tab (a int, b int, c int, PRIMARY KEY ((a, b)))").get(); e.execute_cql("CREATE INDEX ON tab (c)").get(); e.execute_cql("INSERT INTO tab (a, b, c) VALUES (1, 2, 3)").get(); eventually([&] { // We expect this search to find the single row, with the compound // partition key (a, b) = (1, 2). auto res = e.execute_cql("SELECT * from tab WHERE c = 3").get0(); assert_that(res).is_rows() .with_size(1) .with_row({ {int32_type->decompose(1)}, {int32_type->decompose(2)}, {int32_type->decompose(3)}, }); }); }); } <|endoftext|>
<commit_before> #include "opencv2/objdetect/objdetect.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <sstream> #include <iostream> #include <stdio.h> using namespace std; using namespace cv; bool save_large = false; void classifierDetect(CascadeClassifier classifier, Mat frame, int frameNum); int main(int argc, const char** argv ) { string video_path = argv[1]; string classifier_name = argv[2]; VideoCapture video_in(video_path); Mat frame; CascadeClassifier detector; if( !detector.load( classifier_name ) ) { cout << "Error loading classifier."; return -1; } if(argv[3] == "--save-large") { save_large = true; } int frameNum = 0; while (true) { video_in >> frame; frameNum++; if(frame.empty()) { cout << "No frame! Exiting..." << endl; break; } classifierDetect(detector,frame,frameNum); } return 0; } void classifierDetect(CascadeClassifier &classifier,Mat &frame, int frameNum) { cvtColor(frame,frame,CV_BGR2GRAY); vector<Rect> objects; equalizeHist(frame,frame); classifier.detectMultiScale(frame,objects); for(int i = 0; i < objects.size(); i++) { Mat subImg = frame(objects[i]); Mat sample; subImg.copyTo(sample); stringstream name; stringstream name_small; Mat sample_small; name << "./negative_"; name << frameNum; name << "_"; name << i; name_small << name; name_small << "-s"; name << ".png"; name_small << ".png"; resize(sample,sample_small,Size(20,20)); imwrite(name_small.str(),sample_small); if(save_large) { imwrite(name.str(),sample); } } }<commit_msg>Fixed things!<commit_after> #include "opencv2/objdetect/objdetect.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <sstream> #include <iostream> #include <stdio.h> using namespace std; using namespace cv; bool save_large = false; void classifierDetect(const CascadeClassifier &classifier, Mat frame, int frameNum); int main(int argc, const char** argv ) { string video_path = argv[1]; string classifier_name = argv[2]; VideoCapture video_in(video_path); Mat frame; CascadeClassifier detector; if( !detector.load( classifier_name ) ) { cout << "Error loading classifier."; return -1; } if(argv[3] == "--save-large") { save_large = true; } int frameNum = 0; while (true) { video_in >> frame; frameNum++; if(frame.empty()) { cout << "No frame! Exiting..." << endl; break; } classifierDetect(detector,frame,frameNum); } return 0; } void classifierDetect(const CascadeClassifier &classifier,Mat &frame, int frameNum) { cvtColor(frame,frame,CV_BGR2GRAY); vector<Rect> objects; equalizeHist(frame,frame); classifier.detectMultiScale(frame,objects); for(int i = 0; i < objects.size(); i++) { Mat subImg = frame(objects[i]); Mat sample; subImg.copyTo(sample); stringstream name; stringstream name_small; Mat sample_small; name << "./negative_"; name << frameNum; name << "_"; name << i; name_small << name; name_small << "-s"; name << ".png"; name_small << ".png"; resize(sample,sample_small,Size(20,20)); imwrite(name_small.str(),sample_small); if(save_large) { imwrite(name.str(),sample); } } }<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ucb.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: sb $ $Date: 2001-11-28 09:42:39 $ * * 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): Kai Sommerfeld ( kso@sun.com ) * * ************************************************************************/ #ifndef _UCB_HXX #define _UCB_HXX #ifndef _COM_SUN_STAR_UCB_XCOMMANDPROCESSOR_HPP_ #include <com/sun/star/ucb/XCommandProcessor.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDER_HPP_ #include <com/sun/star/ucb/XContentProvider.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENTIDENTIFIERFACTORY_HPP_ #include <com/sun/star/ucb/XContentIdentifierFactory.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDERMANAGER_HPP_ #include <com/sun/star/ucb/XContentProviderManager.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_ #include <com/sun/star/lang/XTypeProvider.hpp> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _OSL_INTERLOCK_H_ //@@@ see initialize() method #include <osl/interlck.h> #endif #ifndef _UCBHELPER_MACROS_HXX #include <ucbhelper/macros.hxx> #endif #ifndef _UCB_PROVIDERMAP_HXX_ #include "providermap.hxx" #endif //========================================================================= #define UCB_SERVICE_NAME "com.sun.star.ucb.UniversalContentBroker" //========================================================================= namespace cppu { class OInterfaceContainerHelper; } namespace com { namespace sun { namespace star { namespace ucb { class XCommandInfo; struct GlobalTransferCommandArgument; } } } } class UniversalContentBroker : public cppu::OWeakObject, public com::sun::star::lang::XTypeProvider, public com::sun::star::lang::XComponent, public com::sun::star::lang::XServiceInfo, public com::sun::star::lang::XInitialization, public com::sun::star::ucb::XContentProviderManager, public com::sun::star::ucb::XContentProvider, public com::sun::star::ucb::XContentIdentifierFactory, public com::sun::star::ucb::XCommandProcessor { public: UniversalContentBroker( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rXSMgr ); virtual ~UniversalContentBroker(); // XInterface XINTERFACE_DECL() // XTypeProvider XTYPEPROVIDER_DECL() // XServiceInfo XSERVICEINFO_DECL() // XComponent virtual void SAL_CALL dispose() throw( com::sun::star::uno::RuntimeException ); virtual void SAL_CALL addEventListener( const com::sun::star::uno::Reference< com::sun::star::lang::XEventListener >& Listener ) throw( com::sun::star::uno::RuntimeException ); virtual void SAL_CALL removeEventListener( const com::sun::star::uno::Reference< com::sun::star::lang::XEventListener >& Listener ) throw( com::sun::star::uno::RuntimeException ); // XInitialization virtual void SAL_CALL initialize( const com::sun::star::uno::Sequence< com::sun::star::uno::Any >& aArguments ) throw( com::sun::star::uno::Exception, com::sun::star::uno::RuntimeException ); // XContentProviderManager virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContentProvider > SAL_CALL registerContentProvider( const com::sun::star::uno::Reference< com::sun::star::ucb::XContentProvider >& Provider, const rtl::OUString& Scheme, sal_Bool ReplaceExisting ) throw( com::sun::star::ucb::DuplicateProviderException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL deregisterContentProvider( const com::sun::star::uno::Reference< com::sun::star::ucb::XContentProvider >& Provider, const rtl::OUString& Scheme ) throw( com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Sequence< com::sun::star::ucb::ContentProviderInfo > SAL_CALL queryContentProviders() throw( com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContentProvider > SAL_CALL queryContentProvider( const rtl::OUString& Identifier ) throw( com::sun::star::uno::RuntimeException ); // XContentProvider virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContent > SAL_CALL queryContent( const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Identifier ) throw( com::sun::star::ucb::IllegalIdentifierException, com::sun::star::uno::RuntimeException ); virtual sal_Int32 SAL_CALL compareContentIds( const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Id1, const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Id2 ) throw( com::sun::star::uno::RuntimeException ); // XContentIdentifierFactory virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier > SAL_CALL createContentIdentifier( const rtl::OUString& ContentId ) throw( com::sun::star::uno::RuntimeException ); // XCommandProcessor virtual sal_Int32 SAL_CALL createCommandIdentifier() throw( com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Any SAL_CALL execute( const com::sun::star::ucb::Command& aCommand, sal_Int32 CommandId, const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >& Environment ) throw( com::sun::star::uno::Exception, com::sun::star::ucb::CommandAbortedException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL abort( sal_Int32 CommandId ) throw( com::sun::star::uno::RuntimeException ); private: com::sun::star::uno::Reference< com::sun::star::ucb::XContentProvider > queryContentProvider( const rtl::OUString& Identifier, sal_Bool bResolved ); com::sun::star::uno::Reference< com::sun::star::ucb::XCommandInfo > getCommandInfo(); void globalTransfer( const com::sun::star::ucb::GlobalTransferCommandArgument & rArg, const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >& xEnv ) throw( com::sun::star::uno::Exception ); com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > m_xSMgr; ProviderMap_Impl m_aProviders; osl::Mutex m_aMutex; cppu::OInterfaceContainerHelper* m_pDisposeEventListeners; oslInterlockedCount m_nInitCount; //@@@ see initialize() method sal_Int32 m_nCommandId; }; #endif /* !_UCB_HXX */ <commit_msg>INTEGRATION: CWS ooo19126 (1.3.268); FILE MERGED 2005/09/05 18:44:54 rt 1.3.268.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ucb.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 15:16:06 $ * * 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 _UCB_HXX #define _UCB_HXX #ifndef _COM_SUN_STAR_UCB_XCOMMANDPROCESSOR_HPP_ #include <com/sun/star/ucb/XCommandProcessor.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDER_HPP_ #include <com/sun/star/ucb/XContentProvider.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENTIDENTIFIERFACTORY_HPP_ #include <com/sun/star/ucb/XContentIdentifierFactory.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDERMANAGER_HPP_ #include <com/sun/star/ucb/XContentProviderManager.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_ #include <com/sun/star/lang/XComponent.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XTYPEPROVIDER_HPP_ #include <com/sun/star/lang/XTypeProvider.hpp> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _OSL_MUTEX_HXX_ #include <osl/mutex.hxx> #endif #ifndef _OSL_INTERLOCK_H_ //@@@ see initialize() method #include <osl/interlck.h> #endif #ifndef _UCBHELPER_MACROS_HXX #include <ucbhelper/macros.hxx> #endif #ifndef _UCB_PROVIDERMAP_HXX_ #include "providermap.hxx" #endif //========================================================================= #define UCB_SERVICE_NAME "com.sun.star.ucb.UniversalContentBroker" //========================================================================= namespace cppu { class OInterfaceContainerHelper; } namespace com { namespace sun { namespace star { namespace ucb { class XCommandInfo; struct GlobalTransferCommandArgument; } } } } class UniversalContentBroker : public cppu::OWeakObject, public com::sun::star::lang::XTypeProvider, public com::sun::star::lang::XComponent, public com::sun::star::lang::XServiceInfo, public com::sun::star::lang::XInitialization, public com::sun::star::ucb::XContentProviderManager, public com::sun::star::ucb::XContentProvider, public com::sun::star::ucb::XContentIdentifierFactory, public com::sun::star::ucb::XCommandProcessor { public: UniversalContentBroker( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rXSMgr ); virtual ~UniversalContentBroker(); // XInterface XINTERFACE_DECL() // XTypeProvider XTYPEPROVIDER_DECL() // XServiceInfo XSERVICEINFO_DECL() // XComponent virtual void SAL_CALL dispose() throw( com::sun::star::uno::RuntimeException ); virtual void SAL_CALL addEventListener( const com::sun::star::uno::Reference< com::sun::star::lang::XEventListener >& Listener ) throw( com::sun::star::uno::RuntimeException ); virtual void SAL_CALL removeEventListener( const com::sun::star::uno::Reference< com::sun::star::lang::XEventListener >& Listener ) throw( com::sun::star::uno::RuntimeException ); // XInitialization virtual void SAL_CALL initialize( const com::sun::star::uno::Sequence< com::sun::star::uno::Any >& aArguments ) throw( com::sun::star::uno::Exception, com::sun::star::uno::RuntimeException ); // XContentProviderManager virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContentProvider > SAL_CALL registerContentProvider( const com::sun::star::uno::Reference< com::sun::star::ucb::XContentProvider >& Provider, const rtl::OUString& Scheme, sal_Bool ReplaceExisting ) throw( com::sun::star::ucb::DuplicateProviderException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL deregisterContentProvider( const com::sun::star::uno::Reference< com::sun::star::ucb::XContentProvider >& Provider, const rtl::OUString& Scheme ) throw( com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Sequence< com::sun::star::ucb::ContentProviderInfo > SAL_CALL queryContentProviders() throw( com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContentProvider > SAL_CALL queryContentProvider( const rtl::OUString& Identifier ) throw( com::sun::star::uno::RuntimeException ); // XContentProvider virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContent > SAL_CALL queryContent( const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Identifier ) throw( com::sun::star::ucb::IllegalIdentifierException, com::sun::star::uno::RuntimeException ); virtual sal_Int32 SAL_CALL compareContentIds( const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Id1, const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Id2 ) throw( com::sun::star::uno::RuntimeException ); // XContentIdentifierFactory virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier > SAL_CALL createContentIdentifier( const rtl::OUString& ContentId ) throw( com::sun::star::uno::RuntimeException ); // XCommandProcessor virtual sal_Int32 SAL_CALL createCommandIdentifier() throw( com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Any SAL_CALL execute( const com::sun::star::ucb::Command& aCommand, sal_Int32 CommandId, const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >& Environment ) throw( com::sun::star::uno::Exception, com::sun::star::ucb::CommandAbortedException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL abort( sal_Int32 CommandId ) throw( com::sun::star::uno::RuntimeException ); private: com::sun::star::uno::Reference< com::sun::star::ucb::XContentProvider > queryContentProvider( const rtl::OUString& Identifier, sal_Bool bResolved ); com::sun::star::uno::Reference< com::sun::star::ucb::XCommandInfo > getCommandInfo(); void globalTransfer( const com::sun::star::ucb::GlobalTransferCommandArgument & rArg, const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >& xEnv ) throw( com::sun::star::uno::Exception ); com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory > m_xSMgr; ProviderMap_Impl m_aProviders; osl::Mutex m_aMutex; cppu::OInterfaceContainerHelper* m_pDisposeEventListeners; oslInterlockedCount m_nInitCount; //@@@ see initialize() method sal_Int32 m_nCommandId; }; #endif /* !_UCB_HXX */ <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/webstore_standalone_installer.h" #include "base/values.h" #include "chrome/browser/extensions/crx_installer.h" #include "chrome/browser/extensions/extension_install_prompt.h" #include "chrome/browser/extensions/extension_install_ui.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/webstore_data_fetcher.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/extensions/extension.h" #include "content/public/browser/web_contents.h" #include "url/gurl.h" using content::WebContents; namespace extensions { const char kManifestKey[] = "manifest"; const char kIconUrlKey[] = "icon_url"; const char kLocalizedNameKey[] = "localized_name"; const char kLocalizedDescriptionKey[] = "localized_description"; const char kUsersKey[] = "users"; const char kShowUserCountKey[] = "show_user_count"; const char kAverageRatingKey[] = "average_rating"; const char kRatingCountKey[] = "rating_count"; const char kRedirectUrlKey[] = "redirect_url"; const char kInvalidWebstoreItemId[] = "Invalid Chrome Web Store item ID"; const char kWebstoreRequestError[] = "Could not fetch data from the Chrome Web Store"; const char kInvalidWebstoreResponseError[] = "Invalid Chrome Web Store reponse"; const char kInvalidManifestError[] = "Invalid manifest"; const char kUserCancelledError[] = "User cancelled install"; WebstoreStandaloneInstaller::WebstoreStandaloneInstaller( const std::string& webstore_item_id, Profile* profile, const Callback& callback) : id_(webstore_item_id), callback_(callback), profile_(profile), show_user_count_(true), average_rating_(0.0), rating_count_(0) { CHECK(!callback_.is_null()); } WebstoreStandaloneInstaller::~WebstoreStandaloneInstaller() {} // // Private interface implementation. // void WebstoreStandaloneInstaller::BeginInstall() { AddRef(); // Balanced in CompleteInstall or WebContentsDestroyed. if (!Extension::IdIsValid(id_)) { CompleteInstall(kInvalidWebstoreItemId); return; } // Use the requesting page as the referrer both since that is more correct // (it is the page that caused this request to happen) and so that we can // track top sites that trigger inline install requests. webstore_data_fetcher_.reset(new WebstoreDataFetcher( this, profile_->GetRequestContext(), GetRequestorURL(), id_)); webstore_data_fetcher_->Start(); } scoped_ptr<ExtensionInstallPrompt> WebstoreStandaloneInstaller::CreateInstallUI() { return make_scoped_ptr(new ExtensionInstallPrompt(GetWebContents())); } void WebstoreStandaloneInstaller::OnWebstoreRequestFailure() { CompleteInstall(kWebstoreRequestError); } void WebstoreStandaloneInstaller::OnWebstoreResponseParseSuccess( DictionaryValue* webstore_data) { if (!CheckRequestorAlive()) { CompleteInstall(std::string()); return; } std::string error; if (!CheckInlineInstallPermitted(*webstore_data, &error)) { CompleteInstall(error); return; } if (!CheckRequestorPermitted(*webstore_data, &error)) { CompleteInstall(error); return; } // Manifest, number of users, average rating and rating count are required. std::string manifest; if (!webstore_data->GetString(kManifestKey, &manifest) || !webstore_data->GetString(kUsersKey, &localized_user_count_) || !webstore_data->GetDouble(kAverageRatingKey, &average_rating_) || !webstore_data->GetInteger(kRatingCountKey, &rating_count_)) { CompleteInstall(kInvalidWebstoreResponseError); return; } // Optional. show_user_count_ = true; webstore_data->GetBoolean(kShowUserCountKey, &show_user_count_); if (average_rating_ < ExtensionInstallPrompt::kMinExtensionRating || average_rating_ > ExtensionInstallPrompt::kMaxExtensionRating) { CompleteInstall(kInvalidWebstoreResponseError); return; } // Localized name and description are optional. if ((webstore_data->HasKey(kLocalizedNameKey) && !webstore_data->GetString(kLocalizedNameKey, &localized_name_)) || (webstore_data->HasKey(kLocalizedDescriptionKey) && !webstore_data->GetString( kLocalizedDescriptionKey, &localized_description_))) { CompleteInstall(kInvalidWebstoreResponseError); return; } // Icon URL is optional. GURL icon_url; if (webstore_data->HasKey(kIconUrlKey)) { std::string icon_url_string; if (!webstore_data->GetString(kIconUrlKey, &icon_url_string)) { CompleteInstall(kInvalidWebstoreResponseError); return; } icon_url = GURL(extension_urls::GetWebstoreLaunchURL()).Resolve( icon_url_string); if (!icon_url.is_valid()) { CompleteInstall(kInvalidWebstoreResponseError); return; } } // Assume ownership of webstore_data. webstore_data_.reset(webstore_data); scoped_refptr<WebstoreInstallHelper> helper = new WebstoreInstallHelper(this, id_, manifest, std::string(), // We don't have any icon data. icon_url, profile_->GetRequestContext()); // The helper will call us back via OnWebstoreParseSucces or // OnWebstoreParseFailure. helper->Start(); } void WebstoreStandaloneInstaller::OnWebstoreResponseParseFailure( const std::string& error) { CompleteInstall(error); } void WebstoreStandaloneInstaller::OnWebstoreParseSuccess( const std::string& id, const SkBitmap& icon, base::DictionaryValue* manifest) { CHECK_EQ(id_, id); if (!CheckRequestorAlive()) { CompleteInstall(std::string()); return; } manifest_.reset(manifest); icon_ = icon; install_prompt_ = CreateInstallPrompt(); if (install_prompt_) { ShowInstallUI(); // Control flow finishes up in InstallUIProceed or InstallUIAbort. } else { InstallUIProceed(); } } void WebstoreStandaloneInstaller::OnWebstoreParseFailure( const std::string& id, InstallHelperResultCode result_code, const std::string& error_message) { CompleteInstall(error_message); } void WebstoreStandaloneInstaller::InstallUIProceed() { if (!CheckRequestorAlive()) { CompleteInstall(std::string()); return; } scoped_ptr<WebstoreInstaller::Approval> approval( WebstoreInstaller::Approval::CreateWithNoInstallPrompt( profile_, id_, scoped_ptr<base::DictionaryValue>(manifest_.get()->DeepCopy()))); approval->skip_post_install_ui = !ShouldShowPostInstallUI(); approval->use_app_installed_bubble = ShouldShowAppInstalledBubble(); scoped_refptr<WebstoreInstaller> installer = new WebstoreInstaller( profile_, this, &(GetWebContents()->GetController()), id_, approval.Pass(), WebstoreInstaller::FLAG_INLINE_INSTALL); installer->Start(); } void WebstoreStandaloneInstaller::InstallUIAbort(bool user_initiated) { CompleteInstall(kUserCancelledError); } void WebstoreStandaloneInstaller::OnExtensionInstallSuccess( const std::string& id) { CHECK_EQ(id_, id); CompleteInstall(std::string()); } void WebstoreStandaloneInstaller::OnExtensionInstallFailure( const std::string& id, const std::string& error, WebstoreInstaller::FailureReason cancelled) { CHECK_EQ(id_, id); CompleteInstall(error); } void WebstoreStandaloneInstaller::AbortInstall() { callback_.Reset(); // Abort any in-progress fetches. if (webstore_data_fetcher_) { webstore_data_fetcher_.reset(); Release(); // Matches the AddRef in BeginInstall. } } void WebstoreStandaloneInstaller::CompleteInstall(const std::string& error) { // Clear webstore_data_fetcher_ so that WebContentsDestroyed will no longer // call Release in case the WebContents is destroyed before this object. scoped_ptr<WebstoreDataFetcher> webstore_data_fetcher( webstore_data_fetcher_.Pass()); if (!callback_.is_null()) callback_.Run(error.empty(), error); Release(); // Matches the AddRef in BeginInstall. } void WebstoreStandaloneInstaller::ShowInstallUI() { std::string error; localized_extension_for_display_ = ExtensionInstallPrompt::GetLocalizedExtensionForDisplay( manifest_.get(), Extension::REQUIRE_KEY | Extension::FROM_WEBSTORE, id_, localized_name_, localized_description_, &error); if (!localized_extension_for_display_.get()) { CompleteInstall(kInvalidManifestError); return; } install_ui_ = CreateInstallUI(); install_ui_->ConfirmStandaloneInstall( this, localized_extension_for_display_.get(), &icon_, *install_prompt_); } } // namespace extensions <commit_msg>Add app icon to approval in WebstoreStandaloneInstaller<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/webstore_standalone_installer.h" #include "base/values.h" #include "chrome/browser/extensions/crx_installer.h" #include "chrome/browser/extensions/extension_install_prompt.h" #include "chrome/browser/extensions/extension_install_ui.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/webstore_data_fetcher.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/extensions/extension.h" #include "content/public/browser/web_contents.h" #include "url/gurl.h" using content::WebContents; namespace extensions { const char kManifestKey[] = "manifest"; const char kIconUrlKey[] = "icon_url"; const char kLocalizedNameKey[] = "localized_name"; const char kLocalizedDescriptionKey[] = "localized_description"; const char kUsersKey[] = "users"; const char kShowUserCountKey[] = "show_user_count"; const char kAverageRatingKey[] = "average_rating"; const char kRatingCountKey[] = "rating_count"; const char kRedirectUrlKey[] = "redirect_url"; const char kInvalidWebstoreItemId[] = "Invalid Chrome Web Store item ID"; const char kWebstoreRequestError[] = "Could not fetch data from the Chrome Web Store"; const char kInvalidWebstoreResponseError[] = "Invalid Chrome Web Store reponse"; const char kInvalidManifestError[] = "Invalid manifest"; const char kUserCancelledError[] = "User cancelled install"; WebstoreStandaloneInstaller::WebstoreStandaloneInstaller( const std::string& webstore_item_id, Profile* profile, const Callback& callback) : id_(webstore_item_id), callback_(callback), profile_(profile), show_user_count_(true), average_rating_(0.0), rating_count_(0) { CHECK(!callback_.is_null()); } WebstoreStandaloneInstaller::~WebstoreStandaloneInstaller() {} // // Private interface implementation. // void WebstoreStandaloneInstaller::BeginInstall() { AddRef(); // Balanced in CompleteInstall or WebContentsDestroyed. if (!Extension::IdIsValid(id_)) { CompleteInstall(kInvalidWebstoreItemId); return; } // Use the requesting page as the referrer both since that is more correct // (it is the page that caused this request to happen) and so that we can // track top sites that trigger inline install requests. webstore_data_fetcher_.reset(new WebstoreDataFetcher( this, profile_->GetRequestContext(), GetRequestorURL(), id_)); webstore_data_fetcher_->Start(); } scoped_ptr<ExtensionInstallPrompt> WebstoreStandaloneInstaller::CreateInstallUI() { return make_scoped_ptr(new ExtensionInstallPrompt(GetWebContents())); } void WebstoreStandaloneInstaller::OnWebstoreRequestFailure() { CompleteInstall(kWebstoreRequestError); } void WebstoreStandaloneInstaller::OnWebstoreResponseParseSuccess( DictionaryValue* webstore_data) { if (!CheckRequestorAlive()) { CompleteInstall(std::string()); return; } std::string error; if (!CheckInlineInstallPermitted(*webstore_data, &error)) { CompleteInstall(error); return; } if (!CheckRequestorPermitted(*webstore_data, &error)) { CompleteInstall(error); return; } // Manifest, number of users, average rating and rating count are required. std::string manifest; if (!webstore_data->GetString(kManifestKey, &manifest) || !webstore_data->GetString(kUsersKey, &localized_user_count_) || !webstore_data->GetDouble(kAverageRatingKey, &average_rating_) || !webstore_data->GetInteger(kRatingCountKey, &rating_count_)) { CompleteInstall(kInvalidWebstoreResponseError); return; } // Optional. show_user_count_ = true; webstore_data->GetBoolean(kShowUserCountKey, &show_user_count_); if (average_rating_ < ExtensionInstallPrompt::kMinExtensionRating || average_rating_ > ExtensionInstallPrompt::kMaxExtensionRating) { CompleteInstall(kInvalidWebstoreResponseError); return; } // Localized name and description are optional. if ((webstore_data->HasKey(kLocalizedNameKey) && !webstore_data->GetString(kLocalizedNameKey, &localized_name_)) || (webstore_data->HasKey(kLocalizedDescriptionKey) && !webstore_data->GetString( kLocalizedDescriptionKey, &localized_description_))) { CompleteInstall(kInvalidWebstoreResponseError); return; } // Icon URL is optional. GURL icon_url; if (webstore_data->HasKey(kIconUrlKey)) { std::string icon_url_string; if (!webstore_data->GetString(kIconUrlKey, &icon_url_string)) { CompleteInstall(kInvalidWebstoreResponseError); return; } icon_url = GURL(extension_urls::GetWebstoreLaunchURL()).Resolve( icon_url_string); if (!icon_url.is_valid()) { CompleteInstall(kInvalidWebstoreResponseError); return; } } // Assume ownership of webstore_data. webstore_data_.reset(webstore_data); scoped_refptr<WebstoreInstallHelper> helper = new WebstoreInstallHelper(this, id_, manifest, std::string(), // We don't have any icon data. icon_url, profile_->GetRequestContext()); // The helper will call us back via OnWebstoreParseSucces or // OnWebstoreParseFailure. helper->Start(); } void WebstoreStandaloneInstaller::OnWebstoreResponseParseFailure( const std::string& error) { CompleteInstall(error); } void WebstoreStandaloneInstaller::OnWebstoreParseSuccess( const std::string& id, const SkBitmap& icon, base::DictionaryValue* manifest) { CHECK_EQ(id_, id); if (!CheckRequestorAlive()) { CompleteInstall(std::string()); return; } manifest_.reset(manifest); icon_ = icon; install_prompt_ = CreateInstallPrompt(); if (install_prompt_) { ShowInstallUI(); // Control flow finishes up in InstallUIProceed or InstallUIAbort. } else { InstallUIProceed(); } } void WebstoreStandaloneInstaller::OnWebstoreParseFailure( const std::string& id, InstallHelperResultCode result_code, const std::string& error_message) { CompleteInstall(error_message); } void WebstoreStandaloneInstaller::InstallUIProceed() { if (!CheckRequestorAlive()) { CompleteInstall(std::string()); return; } scoped_ptr<WebstoreInstaller::Approval> approval( WebstoreInstaller::Approval::CreateWithNoInstallPrompt( profile_, id_, scoped_ptr<base::DictionaryValue>(manifest_.get()->DeepCopy()))); approval->skip_post_install_ui = !ShouldShowPostInstallUI(); approval->use_app_installed_bubble = ShouldShowAppInstalledBubble(); approval->installing_icon = gfx::ImageSkia::CreateFrom1xBitmap(icon_); scoped_refptr<WebstoreInstaller> installer = new WebstoreInstaller( profile_, this, &(GetWebContents()->GetController()), id_, approval.Pass(), WebstoreInstaller::FLAG_INLINE_INSTALL); installer->Start(); } void WebstoreStandaloneInstaller::InstallUIAbort(bool user_initiated) { CompleteInstall(kUserCancelledError); } void WebstoreStandaloneInstaller::OnExtensionInstallSuccess( const std::string& id) { CHECK_EQ(id_, id); CompleteInstall(std::string()); } void WebstoreStandaloneInstaller::OnExtensionInstallFailure( const std::string& id, const std::string& error, WebstoreInstaller::FailureReason cancelled) { CHECK_EQ(id_, id); CompleteInstall(error); } void WebstoreStandaloneInstaller::AbortInstall() { callback_.Reset(); // Abort any in-progress fetches. if (webstore_data_fetcher_) { webstore_data_fetcher_.reset(); Release(); // Matches the AddRef in BeginInstall. } } void WebstoreStandaloneInstaller::CompleteInstall(const std::string& error) { // Clear webstore_data_fetcher_ so that WebContentsDestroyed will no longer // call Release in case the WebContents is destroyed before this object. scoped_ptr<WebstoreDataFetcher> webstore_data_fetcher( webstore_data_fetcher_.Pass()); if (!callback_.is_null()) callback_.Run(error.empty(), error); Release(); // Matches the AddRef in BeginInstall. } void WebstoreStandaloneInstaller::ShowInstallUI() { std::string error; localized_extension_for_display_ = ExtensionInstallPrompt::GetLocalizedExtensionForDisplay( manifest_.get(), Extension::REQUIRE_KEY | Extension::FROM_WEBSTORE, id_, localized_name_, localized_description_, &error); if (!localized_extension_for_display_.get()) { CompleteInstall(kInvalidManifestError); return; } install_ui_ = CreateInstallUI(); install_ui_->ConfirmStandaloneInstall( this, localized_extension_for_display_.get(), &icon_, *install_prompt_); } } // namespace extensions <|endoftext|>
<commit_before>// Copyright (c) 2010 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 "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/ref_counted.h" #include "base/scoped_temp_dir.h" #include "base/utf_string_conversions.h" #include "chrome/browser/in_process_webkit/indexed_db_context.h" #include "chrome/browser/in_process_webkit/webkit_context.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/testing_profile.h" #include "chrome/test/thread_test_helper.h" #include "chrome/test/ui_test_utils.h" // This browser test is aimed towards exercising the IndexedDB bindings and // the actual implementation that lives in the browser side (in_process_webkit). class IndexedDBBrowserTest : public InProcessBrowserTest { public: IndexedDBBrowserTest() { EnableDOMAutomation(); } GURL testUrl(const FilePath& file_path) { const FilePath kTestDir(FILE_PATH_LITERAL("indexeddb")); return ui_test_utils::GetTestUrl(kTestDir, file_path); } void SimpleTest(const GURL& test_url) { // The test page will perform tests on IndexedDB, then navigate to either // a #pass or #fail ref. LOG(INFO) << "Navigating to URL and blocking."; ui_test_utils::NavigateToURLBlockUntilNavigationsComplete( browser(), test_url, 2); LOG(INFO) << "Navigation done."; std::string result = browser()->GetSelectedTabContents()->GetURL().ref(); if (result != "pass") { std::string js_result; ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(getLog())", &js_result)); FAIL() << "Failed: " << js_result; } } }; IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html")))); } // Flaky. See http://crbug.com/70643. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_IndexTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("index_test.html")))); } // Flaky on windows, see http://crbug.com/67422 and http://crbug.com/69293. #if defined(OS_WIN) #define MAYBE_KeyPathTest FLAKY_KeyPathTest #else #define MAYBE_KeyPathTest KeyPathTest #endif IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, MAYBE_KeyPathTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("key_path_test.html")))); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionGetTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_get_test.html")))); } // Flaky. See http://crbug.com/70643. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_ObjectStoreTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("object_store_test.html")))); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DatabaseTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("database_test.html")))); } // Flaky. See http://crbug.com/70643. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_TransactionTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html")))); } // Flaky. See http://crbug.com/70643. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_DoesntHangTest) { SimpleTest(testUrl(FilePath( FILE_PATH_LITERAL("transaction_run_forever.html")))); ui_test_utils::CrashTab(browser()->GetSelectedTabContents()); SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html")))); } // In proc browser test is needed here because ClearLocalState indirectly calls // WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ClearLocalState) { // Create test files. ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath indexeddb_dir = temp_dir.path().Append( IndexedDBContext::kIndexedDBDirectory); ASSERT_TRUE(file_util::CreateDirectory(indexeddb_dir)); FilePath::StringType file_name_1(FILE_PATH_LITERAL("http_foo_0")); file_name_1.append(IndexedDBContext::kIndexedDBExtension); FilePath::StringType file_name_2(FILE_PATH_LITERAL("chrome-extension_foo_0")); file_name_2.append(IndexedDBContext::kIndexedDBExtension); FilePath temp_file_path_1 = indexeddb_dir.Append(file_name_1); FilePath temp_file_path_2 = indexeddb_dir.Append(file_name_2); ASSERT_EQ(1, file_util::WriteFile(temp_file_path_1, ".", 1)); ASSERT_EQ(1, file_util::WriteFile(temp_file_path_2, "o", 1)); // Create the scope which will ensure we run the destructor of the webkit // context which should trigger the clean up. { TestingProfile profile; WebKitContext *webkit_context = profile.GetWebKitContext(); webkit_context->indexed_db_context()->set_data_path(indexeddb_dir); webkit_context->set_clear_local_state_on_exit(true); } // Make sure we wait until the destructor has run. scoped_refptr<ThreadTestHelper> helper( new ThreadTestHelper(BrowserThread::WEBKIT)); ASSERT_TRUE(helper->Run()); // Because we specified https for scheme to be skipped the second file // should survive and the first go into vanity. ASSERT_FALSE(file_util::PathExists(temp_file_path_1)); ASSERT_TRUE(file_util::PathExists(temp_file_path_2)); } <commit_msg>Disable IndexedDBBrowserTest.KeyPathTest per WebKit revision 76531.<commit_after>// Copyright (c) 2010 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 "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/ref_counted.h" #include "base/scoped_temp_dir.h" #include "base/utf_string_conversions.h" #include "chrome/browser/in_process_webkit/indexed_db_context.h" #include "chrome/browser/in_process_webkit/webkit_context.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/testing_profile.h" #include "chrome/test/thread_test_helper.h" #include "chrome/test/ui_test_utils.h" // This browser test is aimed towards exercising the IndexedDB bindings and // the actual implementation that lives in the browser side (in_process_webkit). class IndexedDBBrowserTest : public InProcessBrowserTest { public: IndexedDBBrowserTest() { EnableDOMAutomation(); } GURL testUrl(const FilePath& file_path) { const FilePath kTestDir(FILE_PATH_LITERAL("indexeddb")); return ui_test_utils::GetTestUrl(kTestDir, file_path); } void SimpleTest(const GURL& test_url) { // The test page will perform tests on IndexedDB, then navigate to either // a #pass or #fail ref. LOG(INFO) << "Navigating to URL and blocking."; ui_test_utils::NavigateToURLBlockUntilNavigationsComplete( browser(), test_url, 2); LOG(INFO) << "Navigation done."; std::string result = browser()->GetSelectedTabContents()->GetURL().ref(); if (result != "pass") { std::string js_result; ASSERT_TRUE(ui_test_utils::ExecuteJavaScriptAndExtractString( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(getLog())", &js_result)); FAIL() << "Failed: " << js_result; } } }; IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, CursorTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("cursor_test.html")))); } // Flaky. See http://crbug.com/70643. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_IndexTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("index_test.html")))); } // Flaky on windows, see http://crbug.com/67422 and http://crbug.com/69293. //#if defined(OS_WIN) //#define MAYBE_KeyPathTest FLAKY_KeyPathTest //#else //#define MAYBE_KeyPathTest KeyPathTest //#endif // Disabled per http://trac.webkit.org/changeset/76531. See http://crbug.com/70665. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DISABLED_KeyPathTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("key_path_test.html")))); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, TransactionGetTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_get_test.html")))); } // Flaky. See http://crbug.com/70643. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_ObjectStoreTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("object_store_test.html")))); } IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, DatabaseTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("database_test.html")))); } // Flaky. See http://crbug.com/70643. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_TransactionTest) { SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html")))); } // Flaky. See http://crbug.com/70643. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, FLAKY_DoesntHangTest) { SimpleTest(testUrl(FilePath( FILE_PATH_LITERAL("transaction_run_forever.html")))); ui_test_utils::CrashTab(browser()->GetSelectedTabContents()); SimpleTest(testUrl(FilePath(FILE_PATH_LITERAL("transaction_test.html")))); } // In proc browser test is needed here because ClearLocalState indirectly calls // WebKit's isMainThread through WebSecurityOrigin->SecurityOrigin. IN_PROC_BROWSER_TEST_F(IndexedDBBrowserTest, ClearLocalState) { // Create test files. ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); FilePath indexeddb_dir = temp_dir.path().Append( IndexedDBContext::kIndexedDBDirectory); ASSERT_TRUE(file_util::CreateDirectory(indexeddb_dir)); FilePath::StringType file_name_1(FILE_PATH_LITERAL("http_foo_0")); file_name_1.append(IndexedDBContext::kIndexedDBExtension); FilePath::StringType file_name_2(FILE_PATH_LITERAL("chrome-extension_foo_0")); file_name_2.append(IndexedDBContext::kIndexedDBExtension); FilePath temp_file_path_1 = indexeddb_dir.Append(file_name_1); FilePath temp_file_path_2 = indexeddb_dir.Append(file_name_2); ASSERT_EQ(1, file_util::WriteFile(temp_file_path_1, ".", 1)); ASSERT_EQ(1, file_util::WriteFile(temp_file_path_2, "o", 1)); // Create the scope which will ensure we run the destructor of the webkit // context which should trigger the clean up. { TestingProfile profile; WebKitContext *webkit_context = profile.GetWebKitContext(); webkit_context->indexed_db_context()->set_data_path(indexeddb_dir); webkit_context->set_clear_local_state_on_exit(true); } // Make sure we wait until the destructor has run. scoped_refptr<ThreadTestHelper> helper( new ThreadTestHelper(BrowserThread::WEBKIT)); ASSERT_TRUE(helper->Run()); // Because we specified https for scheme to be skipped the second file // should survive and the first go into vanity. ASSERT_FALSE(file_util::PathExists(temp_file_path_1)); ASSERT_TRUE(file_util::PathExists(temp_file_path_2)); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/policy/configuration_policy_provider_win.h" #include <userenv.h> #include <algorithm> #include "base/logging.h" #include "base/object_watcher.h" #include "base/scoped_ptr.h" #include "base/string_number_conversions.h" #include "base/string_piece.h" #include "base/string_util.h" #include "base/sys_string_conversions.h" #include "base/thread_restrictions.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "base/win/registry.h" #include "chrome/common/policy_constants.h" using base::win::RegKey; namespace policy { namespace { bool ReadRegistryStringValue(RegKey* key, const string16& name, string16* result) { DWORD value_size = 0; DWORD key_type = 0; scoped_array<uint8> buffer; if (!key->ReadValue(name.c_str(), 0, &value_size, &key_type)) return false; if (key_type != REG_SZ) return false; // According to the Microsoft documentation, the string // buffer may not be explicitly 0-terminated. Allocate a // slightly larger buffer and pre-fill to zeros to guarantee // the 0-termination. buffer.reset(new uint8[value_size + 2]); memset(buffer.get(), 0, value_size + 2); key->ReadValue(name.c_str(), buffer.get(), &value_size, NULL); result->assign(reinterpret_cast<const wchar_t*>(buffer.get())); return true; } } // namespace // Period at which to run the reload task in case the group policy change // watchers fail. const int kReloadIntervalMinutes = 15; ConfigurationPolicyProviderWin::GroupPolicyChangeWatcher:: GroupPolicyChangeWatcher( base::WeakPtr<ConfigurationPolicyProviderWin> provider, int reload_interval_minutes) : provider_(provider), user_policy_changed_event_(false, false), machine_policy_changed_event_(false, false), user_policy_watcher_failed_(false), machine_policy_watcher_failed_(false), reload_interval_minutes_(reload_interval_minutes), reload_task_(NULL) { if (!RegisterGPNotification(user_policy_changed_event_.handle(), false)) { PLOG(WARNING) << "Failed to register user group policy notification"; user_policy_watcher_failed_ = true; } if (!RegisterGPNotification(machine_policy_changed_event_.handle(), true)) { PLOG(WARNING) << "Failed to register machine group policy notification."; machine_policy_watcher_failed_ = true; } } ConfigurationPolicyProviderWin::GroupPolicyChangeWatcher:: ~GroupPolicyChangeWatcher() { if (MessageLoop::current()) MessageLoop::current()->RemoveDestructionObserver(this); DCHECK(!reload_task_); } void ConfigurationPolicyProviderWin::GroupPolicyChangeWatcher::Start() { MessageLoop::current()->AddDestructionObserver(this); SetupWatches(); } void ConfigurationPolicyProviderWin::GroupPolicyChangeWatcher::Stop() { user_policy_watcher_.StopWatching(); machine_policy_watcher_.StopWatching(); if (reload_task_) { reload_task_->Cancel(); reload_task_ = NULL; } } void ConfigurationPolicyProviderWin::GroupPolicyChangeWatcher::SetupWatches() { if (reload_task_) { reload_task_->Cancel(); reload_task_ = NULL; } if (!user_policy_watcher_failed_) { if (!user_policy_watcher_.GetWatchedObject() && !user_policy_watcher_.StartWatching( user_policy_changed_event_.handle(), this)) { LOG(WARNING) << "Failed to start watch for user policy change event"; user_policy_watcher_failed_ = true; } } if (!machine_policy_watcher_failed_) { if (!machine_policy_watcher_.GetWatchedObject() && !machine_policy_watcher_.StartWatching( machine_policy_changed_event_.handle(), this)) { LOG(WARNING) << "Failed to start watch for machine policy change event"; machine_policy_watcher_failed_ = true; } } if (user_policy_watcher_failed_ || machine_policy_watcher_failed_) { reload_task_ = NewRunnableMethod(this, &GroupPolicyChangeWatcher::ReloadFromTask); int64 delay = base::TimeDelta::FromMinutes(reload_interval_minutes_).InMilliseconds(); MessageLoop::current()->PostDelayedTask(FROM_HERE, reload_task_, delay); } } void ConfigurationPolicyProviderWin::GroupPolicyChangeWatcher::Reload() { if (provider_.get()) provider_->NotifyStoreOfPolicyChange(); SetupWatches(); } void ConfigurationPolicyProviderWin::GroupPolicyChangeWatcher:: ReloadFromTask() { // Make sure to not call Cancel() on the task, since it might hold the last // reference that keeps this object alive. reload_task_ = NULL; Reload(); } void ConfigurationPolicyProviderWin::GroupPolicyChangeWatcher:: OnObjectSignaled(HANDLE object) { DCHECK(object == user_policy_changed_event_.handle() || object == machine_policy_changed_event_.handle()) << "unexpected object signaled policy reload, obj = " << std::showbase << std::hex << object; Reload(); } void ConfigurationPolicyProviderWin::GroupPolicyChangeWatcher:: WillDestroyCurrentMessageLoop() { reload_task_ = NULL; MessageLoop::current()->RemoveDestructionObserver(this); } ConfigurationPolicyProviderWin::ConfigurationPolicyProviderWin( const PolicyDefinitionList* policy_list) : ConfigurationPolicyProvider(policy_list) { watcher_ = new GroupPolicyChangeWatcher(this->AsWeakPtr(), kReloadIntervalMinutes); watcher_->Start(); } ConfigurationPolicyProviderWin::~ConfigurationPolicyProviderWin() { watcher_->Stop(); } bool ConfigurationPolicyProviderWin::GetRegistryPolicyString( const string16& name, string16* result) const { string16 path = string16(kRegistrySubKey); RegKey policy_key; // First try the global policy. if (policy_key.Open(HKEY_LOCAL_MACHINE, path.c_str(), KEY_READ)) { if (ReadRegistryStringValue(&policy_key, name, result)) return true; policy_key.Close(); } // Fall back on user-specific policy. if (!policy_key.Open(HKEY_CURRENT_USER, path.c_str(), KEY_READ)) return false; return ReadRegistryStringValue(&policy_key, name, result); } bool ConfigurationPolicyProviderWin::GetRegistryPolicyStringList( const string16& key, ListValue* result) const { string16 path = string16(kRegistrySubKey); path += ASCIIToUTF16("\\") + key; RegKey policy_key; if (!policy_key.Open(HKEY_LOCAL_MACHINE, path.c_str(), KEY_READ)) { policy_key.Close(); // Fall back on user-specific policy. if (!policy_key.Open(HKEY_CURRENT_USER, path.c_str(), KEY_READ)) return false; } string16 policy_string; int index = 0; while (ReadRegistryStringValue(&policy_key, base::IntToString16(++index), &policy_string)) { result->Append(Value::CreateStringValue(policy_string)); } return true; } bool ConfigurationPolicyProviderWin::GetRegistryPolicyBoolean( const string16& value_name, bool* result) const { DWORD value; RegKey hkcu_policy_key(HKEY_LOCAL_MACHINE, kRegistrySubKey, KEY_READ); if (hkcu_policy_key.ReadValueDW(value_name.c_str(), &value)) { *result = value != 0; return true; } RegKey hklm_policy_key(HKEY_CURRENT_USER, kRegistrySubKey, KEY_READ); if (hklm_policy_key.ReadValueDW(value_name.c_str(), &value)) { *result = value != 0; return true; } return false; } bool ConfigurationPolicyProviderWin::GetRegistryPolicyInteger( const string16& value_name, uint32* result) const { DWORD value; RegKey hkcu_policy_key(HKEY_LOCAL_MACHINE, kRegistrySubKey, KEY_READ); if (hkcu_policy_key.ReadValueDW(value_name.c_str(), &value)) { *result = value; return true; } RegKey hklm_policy_key(HKEY_CURRENT_USER, kRegistrySubKey, KEY_READ); if (hklm_policy_key.ReadValueDW(value_name.c_str(), &value)) { *result = value; return true; } return false; } bool ConfigurationPolicyProviderWin::Provide( ConfigurationPolicyStoreInterface* store) { // This function calls GetRegistryPolicy* which hit up the registry. Those // are I/O functions not allowed to be called on the main thread. // http://crbug.com/66453 // base::ThreadRestrictions::ScopedAllowIO allow_io; const PolicyDefinitionList* policy_list(policy_definition_list()); for (const PolicyDefinitionList::Entry* current = policy_list->begin; current != policy_list->end; ++current) { std::wstring name = UTF8ToWide(current->name); switch (current->value_type) { case Value::TYPE_STRING: { std::wstring string_value; if (GetRegistryPolicyString(name.c_str(), &string_value)) { store->Apply(current->policy_type, Value::CreateStringValue(string_value)); } break; } case Value::TYPE_LIST: { scoped_ptr<ListValue> list_value(new ListValue); if (GetRegistryPolicyStringList(name.c_str(), list_value.get())) store->Apply(current->policy_type, list_value.release()); break; } case Value::TYPE_BOOLEAN: { bool bool_value; if (GetRegistryPolicyBoolean(name.c_str(), &bool_value)) { store->Apply(current->policy_type, Value::CreateBooleanValue(bool_value)); } break; } case Value::TYPE_INTEGER: { uint32 int_value; if (GetRegistryPolicyInteger(name.c_str(), &int_value)) { store->Apply(current->policy_type, Value::CreateIntegerValue(int_value)); } break; } default: NOTREACHED(); return false; } } return true; } } // namespace policy <commit_msg>Really apply the temp fix for hitting I/O on the main thread. Already approved.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/policy/configuration_policy_provider_win.h" #include <userenv.h> #include <algorithm> #include "base/logging.h" #include "base/object_watcher.h" #include "base/scoped_ptr.h" #include "base/string_number_conversions.h" #include "base/string_piece.h" #include "base/string_util.h" #include "base/sys_string_conversions.h" #include "base/thread_restrictions.h" #include "base/utf_string_conversions.h" #include "base/values.h" #include "base/win/registry.h" #include "chrome/common/policy_constants.h" using base::win::RegKey; namespace policy { namespace { bool ReadRegistryStringValue(RegKey* key, const string16& name, string16* result) { DWORD value_size = 0; DWORD key_type = 0; scoped_array<uint8> buffer; if (!key->ReadValue(name.c_str(), 0, &value_size, &key_type)) return false; if (key_type != REG_SZ) return false; // According to the Microsoft documentation, the string // buffer may not be explicitly 0-terminated. Allocate a // slightly larger buffer and pre-fill to zeros to guarantee // the 0-termination. buffer.reset(new uint8[value_size + 2]); memset(buffer.get(), 0, value_size + 2); key->ReadValue(name.c_str(), buffer.get(), &value_size, NULL); result->assign(reinterpret_cast<const wchar_t*>(buffer.get())); return true; } } // namespace // Period at which to run the reload task in case the group policy change // watchers fail. const int kReloadIntervalMinutes = 15; ConfigurationPolicyProviderWin::GroupPolicyChangeWatcher:: GroupPolicyChangeWatcher( base::WeakPtr<ConfigurationPolicyProviderWin> provider, int reload_interval_minutes) : provider_(provider), user_policy_changed_event_(false, false), machine_policy_changed_event_(false, false), user_policy_watcher_failed_(false), machine_policy_watcher_failed_(false), reload_interval_minutes_(reload_interval_minutes), reload_task_(NULL) { if (!RegisterGPNotification(user_policy_changed_event_.handle(), false)) { PLOG(WARNING) << "Failed to register user group policy notification"; user_policy_watcher_failed_ = true; } if (!RegisterGPNotification(machine_policy_changed_event_.handle(), true)) { PLOG(WARNING) << "Failed to register machine group policy notification."; machine_policy_watcher_failed_ = true; } } ConfigurationPolicyProviderWin::GroupPolicyChangeWatcher:: ~GroupPolicyChangeWatcher() { if (MessageLoop::current()) MessageLoop::current()->RemoveDestructionObserver(this); DCHECK(!reload_task_); } void ConfigurationPolicyProviderWin::GroupPolicyChangeWatcher::Start() { MessageLoop::current()->AddDestructionObserver(this); SetupWatches(); } void ConfigurationPolicyProviderWin::GroupPolicyChangeWatcher::Stop() { user_policy_watcher_.StopWatching(); machine_policy_watcher_.StopWatching(); if (reload_task_) { reload_task_->Cancel(); reload_task_ = NULL; } } void ConfigurationPolicyProviderWin::GroupPolicyChangeWatcher::SetupWatches() { if (reload_task_) { reload_task_->Cancel(); reload_task_ = NULL; } if (!user_policy_watcher_failed_) { if (!user_policy_watcher_.GetWatchedObject() && !user_policy_watcher_.StartWatching( user_policy_changed_event_.handle(), this)) { LOG(WARNING) << "Failed to start watch for user policy change event"; user_policy_watcher_failed_ = true; } } if (!machine_policy_watcher_failed_) { if (!machine_policy_watcher_.GetWatchedObject() && !machine_policy_watcher_.StartWatching( machine_policy_changed_event_.handle(), this)) { LOG(WARNING) << "Failed to start watch for machine policy change event"; machine_policy_watcher_failed_ = true; } } if (user_policy_watcher_failed_ || machine_policy_watcher_failed_) { reload_task_ = NewRunnableMethod(this, &GroupPolicyChangeWatcher::ReloadFromTask); int64 delay = base::TimeDelta::FromMinutes(reload_interval_minutes_).InMilliseconds(); MessageLoop::current()->PostDelayedTask(FROM_HERE, reload_task_, delay); } } void ConfigurationPolicyProviderWin::GroupPolicyChangeWatcher::Reload() { if (provider_.get()) provider_->NotifyStoreOfPolicyChange(); SetupWatches(); } void ConfigurationPolicyProviderWin::GroupPolicyChangeWatcher:: ReloadFromTask() { // Make sure to not call Cancel() on the task, since it might hold the last // reference that keeps this object alive. reload_task_ = NULL; Reload(); } void ConfigurationPolicyProviderWin::GroupPolicyChangeWatcher:: OnObjectSignaled(HANDLE object) { DCHECK(object == user_policy_changed_event_.handle() || object == machine_policy_changed_event_.handle()) << "unexpected object signaled policy reload, obj = " << std::showbase << std::hex << object; Reload(); } void ConfigurationPolicyProviderWin::GroupPolicyChangeWatcher:: WillDestroyCurrentMessageLoop() { reload_task_ = NULL; MessageLoop::current()->RemoveDestructionObserver(this); } ConfigurationPolicyProviderWin::ConfigurationPolicyProviderWin( const PolicyDefinitionList* policy_list) : ConfigurationPolicyProvider(policy_list) { watcher_ = new GroupPolicyChangeWatcher(this->AsWeakPtr(), kReloadIntervalMinutes); watcher_->Start(); } ConfigurationPolicyProviderWin::~ConfigurationPolicyProviderWin() { watcher_->Stop(); } bool ConfigurationPolicyProviderWin::GetRegistryPolicyString( const string16& name, string16* result) const { string16 path = string16(kRegistrySubKey); RegKey policy_key; // First try the global policy. if (policy_key.Open(HKEY_LOCAL_MACHINE, path.c_str(), KEY_READ)) { if (ReadRegistryStringValue(&policy_key, name, result)) return true; policy_key.Close(); } // Fall back on user-specific policy. if (!policy_key.Open(HKEY_CURRENT_USER, path.c_str(), KEY_READ)) return false; return ReadRegistryStringValue(&policy_key, name, result); } bool ConfigurationPolicyProviderWin::GetRegistryPolicyStringList( const string16& key, ListValue* result) const { string16 path = string16(kRegistrySubKey); path += ASCIIToUTF16("\\") + key; RegKey policy_key; if (!policy_key.Open(HKEY_LOCAL_MACHINE, path.c_str(), KEY_READ)) { policy_key.Close(); // Fall back on user-specific policy. if (!policy_key.Open(HKEY_CURRENT_USER, path.c_str(), KEY_READ)) return false; } string16 policy_string; int index = 0; while (ReadRegistryStringValue(&policy_key, base::IntToString16(++index), &policy_string)) { result->Append(Value::CreateStringValue(policy_string)); } return true; } bool ConfigurationPolicyProviderWin::GetRegistryPolicyBoolean( const string16& value_name, bool* result) const { DWORD value; RegKey hkcu_policy_key(HKEY_LOCAL_MACHINE, kRegistrySubKey, KEY_READ); if (hkcu_policy_key.ReadValueDW(value_name.c_str(), &value)) { *result = value != 0; return true; } RegKey hklm_policy_key(HKEY_CURRENT_USER, kRegistrySubKey, KEY_READ); if (hklm_policy_key.ReadValueDW(value_name.c_str(), &value)) { *result = value != 0; return true; } return false; } bool ConfigurationPolicyProviderWin::GetRegistryPolicyInteger( const string16& value_name, uint32* result) const { DWORD value; RegKey hkcu_policy_key(HKEY_LOCAL_MACHINE, kRegistrySubKey, KEY_READ); if (hkcu_policy_key.ReadValueDW(value_name.c_str(), &value)) { *result = value; return true; } RegKey hklm_policy_key(HKEY_CURRENT_USER, kRegistrySubKey, KEY_READ); if (hklm_policy_key.ReadValueDW(value_name.c_str(), &value)) { *result = value; return true; } return false; } bool ConfigurationPolicyProviderWin::Provide( ConfigurationPolicyStoreInterface* store) { // This function calls GetRegistryPolicy* which hit up the registry. Those // are I/O functions not allowed to be called on the main thread. // http://crbug.com/66453 base::ThreadRestrictions::ScopedAllowIO allow_io; const PolicyDefinitionList* policy_list(policy_definition_list()); for (const PolicyDefinitionList::Entry* current = policy_list->begin; current != policy_list->end; ++current) { std::wstring name = UTF8ToWide(current->name); switch (current->value_type) { case Value::TYPE_STRING: { std::wstring string_value; if (GetRegistryPolicyString(name.c_str(), &string_value)) { store->Apply(current->policy_type, Value::CreateStringValue(string_value)); } break; } case Value::TYPE_LIST: { scoped_ptr<ListValue> list_value(new ListValue); if (GetRegistryPolicyStringList(name.c_str(), list_value.get())) store->Apply(current->policy_type, list_value.release()); break; } case Value::TYPE_BOOLEAN: { bool bool_value; if (GetRegistryPolicyBoolean(name.c_str(), &bool_value)) { store->Apply(current->policy_type, Value::CreateBooleanValue(bool_value)); } break; } case Value::TYPE_INTEGER: { uint32 int_value; if (GetRegistryPolicyInteger(name.c_str(), &int_value)) { store->Apply(current->policy_type, Value::CreateIntegerValue(int_value)); } break; } default: NOTREACHED(); return false; } } return true; } } // namespace policy <|endoftext|>
<commit_before>/* <src/Pipe.cpp> * * This file is part of the x0 web server project and is released under GPL-3. * http://www.xzero.io/ * * (c) 2009-2013 Christian Parpart <trapni@gmail.com> */ #include <x0/io/Pipe.h> #include <x0/Socket.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> namespace x0 { /* creates a pipe * * \param flags an OR'ed value of O_NONBLOCK and O_CLOEXEC */ Pipe::Pipe(int flags) : size_(0) { if (::pipe2(pipe_, flags) < 0) { pipe_[0] = -errno; pipe_[1] = -1; } } void Pipe::clear() { char buf[4096]; ssize_t rv; do rv = ::read(readFd(), buf, sizeof(buf)); while (rv > 0); size_ = 0; } ssize_t Pipe::write(const void* buf, size_t size) { ssize_t rv = ::write(writeFd(), buf, size); if (rv > 0) size_ += rv; return rv; } ssize_t Pipe::write(Socket* socket, size_t size) { return socket->write(this, size); } ssize_t Pipe::write(Pipe* pipe, size_t size) { ssize_t rv = splice(pipe->readFd(), NULL, writeFd(), NULL, pipe->size_, SPLICE_F_MOVE | SPLICE_F_NONBLOCK); if (rv > 0) { pipe->size_ -= rv; size_ += rv; } return rv; } ssize_t Pipe::write(int fd, off_t* fd_off, size_t size) { ssize_t rv = splice(fd, fd_off, writeFd(), NULL, size, SPLICE_F_MOVE | SPLICE_F_NONBLOCK); if (rv > 0) size_ += rv; return rv; } ssize_t Pipe::read(void* buf, size_t size) { ssize_t rv = ::read(readFd(), buf, size); if (rv > 0) size_ -= rv; return rv; } ssize_t Pipe::read(Socket* socket, size_t size) { return socket->read(this, size); } ssize_t Pipe::read(Pipe* pipe, size_t size) { return pipe->write(this, size); } ssize_t Pipe::read(int fd, off_t* fd_off, size_t size) { ssize_t rv = splice(readFd(), fd_off, fd, NULL, size, SPLICE_F_MOVE | SPLICE_F_NONBLOCK); if (rv > 0) size_ -= rv; return rv; } } // namespace x0 <commit_msg>do not compile Pipe on osx<commit_after>/* <src/Pipe.cpp> * * This file is part of the x0 web server project and is released under GPL-3. * http://www.xzero.io/ * * (c) 2009-2013 Christian Parpart <trapni@gmail.com> */ #include <x0/io/Pipe.h> #include <x0/Socket.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #ifndef __APPLE__ namespace x0 { /* creates a pipe * * \param flags an OR'ed value of O_NONBLOCK and O_CLOEXEC */ Pipe::Pipe(int flags) : size_(0) { if (::pipe2(pipe_, flags) < 0) { pipe_[0] = -errno; pipe_[1] = -1; } } void Pipe::clear() { char buf[4096]; ssize_t rv; do rv = ::read(readFd(), buf, sizeof(buf)); while (rv > 0); size_ = 0; } ssize_t Pipe::write(const void* buf, size_t size) { ssize_t rv = ::write(writeFd(), buf, size); if (rv > 0) size_ += rv; return rv; } ssize_t Pipe::write(Socket* socket, size_t size) { return socket->write(this, size); } ssize_t Pipe::write(Pipe* pipe, size_t size) { ssize_t rv = splice(pipe->readFd(), NULL, writeFd(), NULL, pipe->size_, SPLICE_F_MOVE | SPLICE_F_NONBLOCK); if (rv > 0) { pipe->size_ -= rv; size_ += rv; } return rv; } ssize_t Pipe::write(int fd, off_t* fd_off, size_t size) { ssize_t rv = splice(fd, fd_off, writeFd(), NULL, size, SPLICE_F_MOVE | SPLICE_F_NONBLOCK); if (rv > 0) size_ += rv; return rv; } ssize_t Pipe::read(void* buf, size_t size) { ssize_t rv = ::read(readFd(), buf, size); if (rv > 0) size_ -= rv; return rv; } ssize_t Pipe::read(Socket* socket, size_t size) { return socket->read(this, size); } ssize_t Pipe::read(Pipe* pipe, size_t size) { return pipe->write(this, size); } ssize_t Pipe::read(int fd, off_t* fd_off, size_t size) { ssize_t rv = splice(readFd(), fd_off, fd, NULL, size, SPLICE_F_MOVE | SPLICE_F_NONBLOCK); if (rv > 0) size_ -= rv; return rv; } } // namespace x0 #endif <|endoftext|>
<commit_before>// // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #include "swift/AST/Builtins.h" #include "swift/SIL/MemAccessUtils.h" #include "swift/SIL/OwnershipUtils.h" #include "swift/SIL/SILBasicBlock.h" #include "swift/SILOptimizer/Utils/CanonicalizeBorrowScope.h" #include "swift/SILOptimizer/Utils/InstOptUtils.h" #include "swift/SILOptimizer/Utils/InstructionDeleter.h" #define DEBUG_TYPE "copy-propagation" using namespace swift; //===----------------------------------------------------------------------===// // MARK: ShrinkBorrowScope //===----------------------------------------------------------------------===// class ShrinkBorrowScope { // The instruction that begins this borrow scope. BeginBorrowInst *introducer; InstructionDeleter &deleter; SmallVectorImpl<CopyValueInst *> &modifiedCopyValueInsts; /// Instructions which are users of the simple (i.e. not reborrowed) extended /// i.e. copied lifetime of the introducer. SmallPtrSet<SILInstruction *, 16> users; /// Deinit barriers that obstruct hoisting end_borrow instructions. llvm::SmallVector<std::pair<SILBasicBlock *, SILInstruction *>> barrierInstructions; /// Blocks above which the borrow scope cannot be hoisted. /// /// Consequently, these blocks must begin with end_borrow %borrow. /// /// Note: These blocks aren't barrier blocks. Rather the borrow scope is /// barred from being hoisted out of them. That could happen because /// one of its predecessors is a barrier block (i.e. has a successor /// which is live) or because one of its predecessors has a terminator /// which is itself a deinit barrier. SmallPtrSet<SILBasicBlock *, 8> barredBlocks; llvm::SmallDenseMap<ApplySite, size_t> transitiveUsesPerApplySite; // The list of blocks to look for new points at which to insert end_borrows // in. A block must not be processed if all of its successors have not yet // been. For that reason, it is necessary to allow the same block to be // visited multiple times, at most once for each successor. SmallVector<SILBasicBlock *, 8> worklist; // The instructions from which the shrinking starts, the scope ending // instructions, keyed off the block in which they appear. llvm::SmallDenseMap<SILBasicBlock *, SILInstruction *> startingInstructions; // The end _borrow instructions for this borrow scope that existed before // ShrinkBorrowScope ran and which were not modified. llvm::SmallPtrSet<SILInstruction *, 8> reusedEndBorrowInsts; // Whether ShrinkBorrowScope made any changes to the function. // // It could have made one of the following sorts of changes: // - deleted an end_borrow // - created an end_borrow // - rewrote the operand of an instruction // - ApplySite // - begin_borrow // - copy_value bool madeChange; public: ShrinkBorrowScope(BeginBorrowInst *bbi, InstructionDeleter &deleter, SmallVectorImpl<CopyValueInst *> &modifiedCopyValueInsts) : introducer(bbi), deleter(deleter), modifiedCopyValueInsts(modifiedCopyValueInsts), madeChange(false) {} bool run(); bool populateUsers(); bool initializeWorklist(); void findBarriers(); bool rewrite(); bool createEndBorrow(SILInstruction *insertionPoint); bool isBarrierApply(SILInstruction *instruction) { // For now, treat every apply (that doesn't use the borrowed value) as a // barrier. return isa<ApplySite>(instruction); } bool mayAccessPointer(SILInstruction *instruction) { if (!instruction->mayReadOrWriteMemory()) return false; bool fail = false; visitAccessedAddress(instruction, [&fail](Operand *operand) { auto accessStorage = AccessStorage::compute(operand->get()); if (accessStorage.getKind() != AccessRepresentation::Kind::Unidentified) fail = true; }); return fail; } bool mayLoadWeakOrUnowned(SILInstruction *instruction) { // TODO: It is possible to do better here by looking at the address that is // being loaded. return isa<LoadWeakInst>(instruction) || isa<LoadUnownedInst>(instruction); } bool isDeinitBarrier(SILInstruction *instruction) { return isBarrierApply(instruction) || instruction->maySynchronize() || mayAccessPointer(instruction) || mayLoadWeakOrUnowned(instruction); } bool canReplaceValueWithBorrowedValue(SILValue value) { while (true) { auto *instruction = value.getDefiningInstruction(); if (!instruction) return false; if (auto *cvi = dyn_cast<CopyValueInst>(instruction)) { value = cvi->getOperand(); continue; } else if (auto *bbi = dyn_cast<BeginBorrowInst>(instruction)) { if (bbi == introducer) { return true; } } return false; } } size_t usesInApply(ApplySite apply) { if (auto count = transitiveUsesPerApplySite.lookup(apply)) return count; return 0; } bool canHoistOverInstruction(SILInstruction *instruction) { return tryHoistOverInstruction(instruction, /*rewrite=*/false); } bool tryHoistOverInstruction(SILInstruction *instruction, bool rewrite = true) { if (users.contains(instruction)) { if (auto apply = ApplySite::isa(instruction)) { SmallVector<int, 2> rewritableArgumentIndices; auto count = apply.getNumArguments(); for (unsigned index = 0; index < count; ++index) { auto argument = apply.getArgument(index); if (canReplaceValueWithBorrowedValue(argument)) { rewritableArgumentIndices.push_back(index); } } if (rewritableArgumentIndices.size() != usesInApply(apply)) { return false; } if (rewrite) { // We can rewrite all the arguments which are transitive uses of the // borrow. for (auto index : rewritableArgumentIndices) { auto argument = apply.getArgument(index); auto borrowee = introducer->getOperand(); if (auto *cvi = dyn_cast<CopyValueInst>(argument)) { cvi->setOperand(borrowee); modifiedCopyValueInsts.push_back(cvi); madeChange = true; } else { apply.setArgument(index, borrowee); madeChange = true; } } } return true; } else if (auto *bbi = dyn_cast<BeginBorrowInst>(instruction)) { if (bbi->isLexical() && canReplaceValueWithBorrowedValue(bbi->getOperand())) { if (rewrite) { auto borrowee = introducer->getOperand(); bbi->setOperand(borrowee); madeChange = true; } return true; } } else if (auto *cvi = dyn_cast<CopyValueInst>(instruction)) { if (canReplaceValueWithBorrowedValue(cvi->getOperand())) { if (rewrite) { auto borrowee = introducer->getOperand(); cvi->setOperand(borrowee); madeChange = true; modifiedCopyValueInsts.push_back(cvi); } return true; } } return false; } return !isDeinitBarrier(instruction); } }; //===----------------------------------------------------------------------===// // MARK: Rewrite borrow scopes //===----------------------------------------------------------------------===// bool ShrinkBorrowScope::run() { if (!BorrowedValue(introducer).isLocalScope()) return false; if (!populateUsers()) return false; if (!initializeWorklist()) return false; findBarriers(); madeChange |= rewrite(); return madeChange; } bool ShrinkBorrowScope::populateUsers() { SmallVector<Operand *, 16> uses; if (!findExtendedUsesOfSimpleBorrowedValue(BorrowedValue(introducer), &uses)) { // If the value produced by begin_borrow escapes, don't shrink the borrow // scope. return false; } for (auto *use : uses) { auto *user = use->getUser(); users.insert(user); if (auto apply = ApplySite::isa(user)) { ++transitiveUsesPerApplySite[apply]; } } return true; } bool ShrinkBorrowScope::initializeWorklist() { llvm::SmallVector<SILInstruction *, 16> scopeEndingInsts; BorrowedValue(introducer).getLocalScopeEndingInstructions(scopeEndingInsts); // Form a map of the scopeEndingInsts, keyed off the block they occur in. If // a scope ending instruction is not an end_borrow, bail out. for (auto *instruction : scopeEndingInsts) { if (!isa<EndBorrowInst>(instruction)) return false; auto *block = instruction->getParent(); worklist.push_back(block); startingInstructions[block] = instruction; } return true; } void ShrinkBorrowScope::findBarriers() { // Walk the cfg backwards from the blocks containing scope ending // instructions, visiting only the initial blocks (which contained those // instructions) and those blocks all of whose successors have already been // visited. // // TODO: Handle loops. // Blocks to the top of which the borrow scope has been shrunk. SmallPtrSet<SILBasicBlock *, 8> deadBlocks; auto hasOnlyDeadSuccessors = [&deadBlocks](SILBasicBlock *block) -> bool { return llvm::all_of(block->getSuccessorBlocks(), [=](auto *successor) { return deadBlocks.contains(successor); }); }; while (!worklist.empty()) { auto *block = worklist.pop_back_val(); auto *startingInstruction = startingInstructions.lookup(block); if (!startingInstruction && !hasOnlyDeadSuccessors(block)) { continue; } for (auto *successor : block->getSuccessorBlocks()) { barredBlocks.erase(successor); } // We either have processed all successors of block or else it is a block // which contained one of the original scope-ending instructions. Scan the // block backwards, looking for the first deinit barrier. If we've visited // all successors, start scanning from the terminator. If the block // contained an original scope-ending instruction, start scanning from it. SILInstruction *instruction = startingInstruction ? startingInstruction : block->getTerminator(); if (!startingInstruction) { // That there's no starting instruction means that this this block did not // contain an original introducer. It was added to the worklist later. // At that time, it was checked that this block (along with all that // successor's other predecessors) had a terminator over which the borrow // scope could be shrunk. Shrink it now. #ifndef NDEBUG bool hoisted = #endif tryHoistOverInstruction(block->getTerminator()); #ifndef NDEBUG assert(hoisted); #endif } SILInstruction *barrier = nullptr; while ((instruction = instruction->getPreviousInstruction())) { if (instruction == introducer) { barrier = instruction; break; } if (!tryHoistOverInstruction(instruction)) { barrier = instruction; break; } } if (barrier) { barrierInstructions.push_back({block, barrier}); } else { deadBlocks.insert(block); barredBlocks.insert(block); // If any of block's predecessor has a terminator over which the scope // can't be shrunk, the scope is barred from shrinking out of this block. if (llvm::all_of(block->getPredecessorBlocks(), [&](auto *block) { return canHoistOverInstruction(block->getTerminator()); })) { // Otherwise, add all predecessors to the worklist and attempt to shrink // the borrow scope through them. for (auto *predecessor : block->getPredecessorBlocks()) { worklist.push_back(predecessor); } } } } } bool ShrinkBorrowScope::rewrite() { bool createdBorrow = false; // Insert the new end_borrow instructions that occur after deinit barriers. for (auto pair : barrierInstructions) { auto *insertionPoint = pair.second->getNextInstruction(); createdBorrow |= createEndBorrow(insertionPoint); } // Insert the new end_borrow instructions that occur at the beginning of // blocks which we couldn't hoist out of. for (auto *block : barredBlocks) { auto *insertionPoint = &*block->begin(); createdBorrow |= createEndBorrow(insertionPoint); } if (createdBorrow) { // Remove all the original end_borrow instructions. for (auto pair : startingInstructions) { if (reusedEndBorrowInsts.contains(pair.second)) { continue; } deleter.forceDelete(pair.getSecond()); } } return createdBorrow; } bool ShrinkBorrowScope::createEndBorrow(SILInstruction *insertionPoint) { if (auto *ebi = dyn_cast<EndBorrowInst>(insertionPoint)) { llvm::SmallDenseMap<SILBasicBlock *, SILInstruction *>::iterator location; if ((location = llvm::find_if(startingInstructions, [&](auto pair) -> bool { return pair.second == insertionPoint; })) != startingInstructions.end()) { reusedEndBorrowInsts.insert(location->second); return false; } } auto builder = SILBuilderWithScope(insertionPoint); builder.createEndBorrow( RegularLocation::getAutoGeneratedLocation(insertionPoint->getLoc()), introducer); return true; } bool swift::shrinkBorrowScope( BeginBorrowInst *bbi, InstructionDeleter &deleter, SmallVectorImpl<CopyValueInst *> &modifiedCopyValueInsts) { ShrinkBorrowScope borrowShrinker(bbi, deleter, modifiedCopyValueInsts); return borrowShrinker.run(); } <commit_msg>[NFC] [ShrinkBorrowScope] Moved check.<commit_after>// // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #include "swift/AST/Builtins.h" #include "swift/SIL/MemAccessUtils.h" #include "swift/SIL/OwnershipUtils.h" #include "swift/SIL/SILBasicBlock.h" #include "swift/SILOptimizer/Utils/CanonicalizeBorrowScope.h" #include "swift/SILOptimizer/Utils/InstOptUtils.h" #include "swift/SILOptimizer/Utils/InstructionDeleter.h" #define DEBUG_TYPE "copy-propagation" using namespace swift; //===----------------------------------------------------------------------===// // MARK: ShrinkBorrowScope //===----------------------------------------------------------------------===// class ShrinkBorrowScope { // The instruction that begins this borrow scope. BeginBorrowInst *introducer; InstructionDeleter &deleter; SmallVectorImpl<CopyValueInst *> &modifiedCopyValueInsts; /// Instructions which are users of the simple (i.e. not reborrowed) extended /// i.e. copied lifetime of the introducer. SmallPtrSet<SILInstruction *, 16> users; /// Deinit barriers that obstruct hoisting end_borrow instructions. llvm::SmallVector<std::pair<SILBasicBlock *, SILInstruction *>> barrierInstructions; /// Blocks above which the borrow scope cannot be hoisted. /// /// Consequently, these blocks must begin with end_borrow %borrow. /// /// Note: These blocks aren't barrier blocks. Rather the borrow scope is /// barred from being hoisted out of them. That could happen because /// one of its predecessors is a barrier block (i.e. has a successor /// which is live) or because one of its predecessors has a terminator /// which is itself a deinit barrier. SmallPtrSet<SILBasicBlock *, 8> barredBlocks; llvm::SmallDenseMap<ApplySite, size_t> transitiveUsesPerApplySite; // The list of blocks to look for new points at which to insert end_borrows // in. A block must not be processed if all of its successors have not yet // been. For that reason, it is necessary to allow the same block to be // visited multiple times, at most once for each successor. SmallVector<SILBasicBlock *, 8> worklist; // The instructions from which the shrinking starts, the scope ending // instructions, keyed off the block in which they appear. llvm::SmallDenseMap<SILBasicBlock *, SILInstruction *> startingInstructions; // The end _borrow instructions for this borrow scope that existed before // ShrinkBorrowScope ran and which were not modified. llvm::SmallPtrSet<SILInstruction *, 8> reusedEndBorrowInsts; // Whether ShrinkBorrowScope made any changes to the function. // // It could have made one of the following sorts of changes: // - deleted an end_borrow // - created an end_borrow // - rewrote the operand of an instruction // - ApplySite // - begin_borrow // - copy_value bool madeChange; public: ShrinkBorrowScope(BeginBorrowInst *bbi, InstructionDeleter &deleter, SmallVectorImpl<CopyValueInst *> &modifiedCopyValueInsts) : introducer(bbi), deleter(deleter), modifiedCopyValueInsts(modifiedCopyValueInsts), madeChange(false) {} bool run(); bool populateUsers(); bool initializeWorklist(); void findBarriers(); bool rewrite(); bool createEndBorrow(SILInstruction *insertionPoint); bool isBarrierApply(SILInstruction *instruction) { // For now, treat every apply (that doesn't use the borrowed value) as a // barrier. return isa<ApplySite>(instruction); } bool mayAccessPointer(SILInstruction *instruction) { if (!instruction->mayReadOrWriteMemory()) return false; bool fail = false; visitAccessedAddress(instruction, [&fail](Operand *operand) { auto accessStorage = AccessStorage::compute(operand->get()); if (accessStorage.getKind() != AccessRepresentation::Kind::Unidentified) fail = true; }); return fail; } bool mayLoadWeakOrUnowned(SILInstruction *instruction) { // TODO: It is possible to do better here by looking at the address that is // being loaded. return isa<LoadWeakInst>(instruction) || isa<LoadUnownedInst>(instruction); } bool isDeinitBarrier(SILInstruction *instruction) { return isBarrierApply(instruction) || instruction->maySynchronize() || mayAccessPointer(instruction) || mayLoadWeakOrUnowned(instruction); } bool canReplaceValueWithBorrowedValue(SILValue value) { while (true) { auto *instruction = value.getDefiningInstruction(); if (!instruction) return false; if (auto *cvi = dyn_cast<CopyValueInst>(instruction)) { value = cvi->getOperand(); continue; } else if (auto *bbi = dyn_cast<BeginBorrowInst>(instruction)) { if (bbi == introducer) { return true; } } return false; } } size_t usesInApply(ApplySite apply) { if (auto count = transitiveUsesPerApplySite.lookup(apply)) return count; return 0; } bool canHoistOverInstruction(SILInstruction *instruction) { return tryHoistOverInstruction(instruction, /*rewrite=*/false); } bool tryHoistOverInstruction(SILInstruction *instruction, bool rewrite = true) { if (instruction == introducer) { return false; } if (users.contains(instruction)) { if (auto apply = ApplySite::isa(instruction)) { SmallVector<int, 2> rewritableArgumentIndices; auto count = apply.getNumArguments(); for (unsigned index = 0; index < count; ++index) { auto argument = apply.getArgument(index); if (canReplaceValueWithBorrowedValue(argument)) { rewritableArgumentIndices.push_back(index); } } if (rewritableArgumentIndices.size() != usesInApply(apply)) { return false; } if (rewrite) { // We can rewrite all the arguments which are transitive uses of the // borrow. for (auto index : rewritableArgumentIndices) { auto argument = apply.getArgument(index); auto borrowee = introducer->getOperand(); if (auto *cvi = dyn_cast<CopyValueInst>(argument)) { cvi->setOperand(borrowee); modifiedCopyValueInsts.push_back(cvi); madeChange = true; } else { apply.setArgument(index, borrowee); madeChange = true; } } } return true; } else if (auto *bbi = dyn_cast<BeginBorrowInst>(instruction)) { if (bbi->isLexical() && canReplaceValueWithBorrowedValue(bbi->getOperand())) { if (rewrite) { auto borrowee = introducer->getOperand(); bbi->setOperand(borrowee); madeChange = true; } return true; } } else if (auto *cvi = dyn_cast<CopyValueInst>(instruction)) { if (canReplaceValueWithBorrowedValue(cvi->getOperand())) { if (rewrite) { auto borrowee = introducer->getOperand(); cvi->setOperand(borrowee); madeChange = true; modifiedCopyValueInsts.push_back(cvi); } return true; } } return false; } return !isDeinitBarrier(instruction); } }; //===----------------------------------------------------------------------===// // MARK: Rewrite borrow scopes //===----------------------------------------------------------------------===// bool ShrinkBorrowScope::run() { if (!BorrowedValue(introducer).isLocalScope()) return false; if (!populateUsers()) return false; if (!initializeWorklist()) return false; findBarriers(); madeChange |= rewrite(); return madeChange; } bool ShrinkBorrowScope::populateUsers() { SmallVector<Operand *, 16> uses; if (!findExtendedUsesOfSimpleBorrowedValue(BorrowedValue(introducer), &uses)) { // If the value produced by begin_borrow escapes, don't shrink the borrow // scope. return false; } for (auto *use : uses) { auto *user = use->getUser(); users.insert(user); if (auto apply = ApplySite::isa(user)) { ++transitiveUsesPerApplySite[apply]; } } return true; } bool ShrinkBorrowScope::initializeWorklist() { llvm::SmallVector<SILInstruction *, 16> scopeEndingInsts; BorrowedValue(introducer).getLocalScopeEndingInstructions(scopeEndingInsts); // Form a map of the scopeEndingInsts, keyed off the block they occur in. If // a scope ending instruction is not an end_borrow, bail out. for (auto *instruction : scopeEndingInsts) { if (!isa<EndBorrowInst>(instruction)) return false; auto *block = instruction->getParent(); worklist.push_back(block); startingInstructions[block] = instruction; } return true; } void ShrinkBorrowScope::findBarriers() { // Walk the cfg backwards from the blocks containing scope ending // instructions, visiting only the initial blocks (which contained those // instructions) and those blocks all of whose successors have already been // visited. // // TODO: Handle loops. // Blocks to the top of which the borrow scope has been shrunk. SmallPtrSet<SILBasicBlock *, 8> deadBlocks; auto hasOnlyDeadSuccessors = [&deadBlocks](SILBasicBlock *block) -> bool { return llvm::all_of(block->getSuccessorBlocks(), [=](auto *successor) { return deadBlocks.contains(successor); }); }; while (!worklist.empty()) { auto *block = worklist.pop_back_val(); auto *startingInstruction = startingInstructions.lookup(block); if (!startingInstruction && !hasOnlyDeadSuccessors(block)) { continue; } for (auto *successor : block->getSuccessorBlocks()) { barredBlocks.erase(successor); } // We either have processed all successors of block or else it is a block // which contained one of the original scope-ending instructions. Scan the // block backwards, looking for the first deinit barrier. If we've visited // all successors, start scanning from the terminator. If the block // contained an original scope-ending instruction, start scanning from it. SILInstruction *instruction = startingInstruction ? startingInstruction : block->getTerminator(); if (!startingInstruction) { // That there's no starting instruction means that this this block did not // contain an original introducer. It was added to the worklist later. // At that time, it was checked that this block (along with all that // successor's other predecessors) had a terminator over which the borrow // scope could be shrunk. Shrink it now. #ifndef NDEBUG bool hoisted = #endif tryHoistOverInstruction(block->getTerminator()); #ifndef NDEBUG assert(hoisted); #endif } SILInstruction *barrier = nullptr; while ((instruction = instruction->getPreviousInstruction())) { if (!tryHoistOverInstruction(instruction)) { barrier = instruction; break; } } if (barrier) { barrierInstructions.push_back({block, barrier}); } else { deadBlocks.insert(block); barredBlocks.insert(block); // If any of block's predecessor has a terminator over which the scope // can't be shrunk, the scope is barred from shrinking out of this block. if (llvm::all_of(block->getPredecessorBlocks(), [&](auto *block) { return canHoistOverInstruction(block->getTerminator()); })) { // Otherwise, add all predecessors to the worklist and attempt to shrink // the borrow scope through them. for (auto *predecessor : block->getPredecessorBlocks()) { worklist.push_back(predecessor); } } } } } bool ShrinkBorrowScope::rewrite() { bool createdBorrow = false; // Insert the new end_borrow instructions that occur after deinit barriers. for (auto pair : barrierInstructions) { auto *insertionPoint = pair.second->getNextInstruction(); createdBorrow |= createEndBorrow(insertionPoint); } // Insert the new end_borrow instructions that occur at the beginning of // blocks which we couldn't hoist out of. for (auto *block : barredBlocks) { auto *insertionPoint = &*block->begin(); createdBorrow |= createEndBorrow(insertionPoint); } if (createdBorrow) { // Remove all the original end_borrow instructions. for (auto pair : startingInstructions) { if (reusedEndBorrowInsts.contains(pair.second)) { continue; } deleter.forceDelete(pair.getSecond()); } } return createdBorrow; } bool ShrinkBorrowScope::createEndBorrow(SILInstruction *insertionPoint) { if (auto *ebi = dyn_cast<EndBorrowInst>(insertionPoint)) { llvm::SmallDenseMap<SILBasicBlock *, SILInstruction *>::iterator location; if ((location = llvm::find_if(startingInstructions, [&](auto pair) -> bool { return pair.second == insertionPoint; })) != startingInstructions.end()) { reusedEndBorrowInsts.insert(location->second); return false; } } auto builder = SILBuilderWithScope(insertionPoint); builder.createEndBorrow( RegularLocation::getAutoGeneratedLocation(insertionPoint->getLoc()), introducer); return true; } bool swift::shrinkBorrowScope( BeginBorrowInst *bbi, InstructionDeleter &deleter, SmallVectorImpl<CopyValueInst *> &modifiedCopyValueInsts) { ShrinkBorrowScope borrowShrinker(bbi, deleter, modifiedCopyValueInsts); return borrowShrinker.run(); } <|endoftext|>
<commit_before>// // pfilter.cpp // EpiGenMCMC // // Created by Lucy Li on 05/05/2016. // Copyright (c) 2016 Lucy Li, Imperial College London. All rights reserved. // #include "pfilter.h" #include <iostream> namespace EpiGenPfilter { double pfilter(Model & sim_model, Parameter & model_params, MCMCoptions & options, Particle &particles, Trajectory & output_traj, TimeSeriesData &epi_data, TreeData &tree_data, MultiTreeData &multitree_data) { double loglik = 0.0; int num_groups = options.num_groups; int num_particles = options.particles; int init_seed = options.seed; int total_dt = options.total_dt; double sim_dt = options.sim_dt; int total_steps = ceil((double)total_dt/(double)options.pfilter_every); int add_dt = 0; double ESS_threshold = options.pfilter_threshold*(double)num_particles; Likelihood likelihood_calc; // std::vector <Parameter> values;// (options.num_threads, model_params); // for (int i=0; i!=options.num_threads; ++i) values.push_back(model_params); // for (int i=0; i!=model_params.get_total_params(); ++i) values.push_back(model_params.get(i)); std::vector <std::vector<double> > values(options.num_threads, std::vector<double>(model_params.get_total_params(), 0.0)); for (int i=0; i!=options.num_threads; ++i) { for (int j=0; j!=model_params.get_total_params(); ++j) { values[i][j] = model_params.get(j); } } // printf("Size of values = %d\n",values.size()); double reporting_rate = 1.0; if (model_params.param_exists("reporting")) { reporting_rate = model_params.get("reporting"); } std::vector <std::string> param_names = model_params.get_names_vector(); std::vector <std::vector<std::string> > param_names_threads (options.num_threads); if (model_params.param_exists("time_before_data")) { add_dt = model_params.get("time_before_data"); } if (options.save_traj) { if (add_dt > 0) { particles.start_particle_tracing(add_dt+total_dt, num_groups); } else if (add_dt < 0) { particles.start_particle_tracing(add_dt+total_dt, num_groups); total_steps = ceil((double)(total_dt+add_dt)/(double)options.pfilter_every); } else { particles.start_particle_tracing(total_dt, num_groups); } } std::vector <Model> models; for (int i=0; i<options.num_threads; ++i) { models.push_back(sim_model); } std::vector <int> add_dt_threads (options.num_threads, add_dt); std::vector <int> start_dt_threads (options.num_threads, 0); std::vector <int> end_dt_threads (options.num_threads, add_dt); std::vector <double> dt_threads (options.num_threads, sim_dt); std::vector <int> total_dt_threads(options.num_threads, total_dt); std::vector <double> reporting_rate_threads(options.num_threads, reporting_rate); std::vector <int> num_groups_threads(options.num_threads, num_groups); // Simulate model and calculate likelihood assuming no observed data if (model_params.param_exists("time_before_data")) { if (add_dt > 0) { omp_set_num_threads(options.num_threads); // std::vector <Trajectory *> curr_trajs; // for (int i=0; i!=num_particles; ++i) { // curr_trajs.push_back(particles.get_traj(i)); // } #pragma omp parallel for shared(particles, values) for (int i=0; i<num_particles; i++) { int tn = omp_get_thread_num(); gsl_rng* r = gsl_rng_alloc( gsl_rng_mt19937 ); gsl_rng_set( r, omp_get_thread_num() + i ); // Adjust length of trajectory particles.get_traj(i)->resize(add_dt, num_groups); models[tn].simulate(values[tn], param_names_threads[tn], particles.get_traj(i), 0, add_dt_threads[tn], dt_threads[tn], total_dt_threads[tn], r); if (options.which_likelihood<2) { double w = likelihood_calc.binomial_lik(reporting_rate_threads[tn], particles.get_traj(i)->get_total_traj(), add_dt_threads[tn]+total_dt_threads[tn], 0, add_dt_threads[tn], num_groups_threads[tn], false); particles.set_weight(w, i, false); } if (options.save_traj) { particles.save_traj_to_matrix(i, 0, add_dt); particles.save_ancestry(i, 0, add_dt); } } } } init_seed += num_particles; int t=0; int start_dt; int end_dt; for (t=0; t!=total_steps; ++t) { // std::vector<double> we(options.particles, 0.0), wg(options.particles, 0.0); start_dt = t*options.pfilter_every; end_dt = std::min(total_dt, (t+1)*options.pfilter_every); std::fill(start_dt_threads.begin(), start_dt_threads.end(), start_dt); std::fill(end_dt_threads.begin(), end_dt_threads.end(), end_dt); omp_set_num_threads(options.num_threads); #pragma omp parallel for shared (particles, values) for (int i=0; i<num_particles; i++) { int tn = omp_get_thread_num(); gsl_rng* r = gsl_rng_alloc( gsl_rng_mt19937 ); gsl_rng_set( r, omp_get_thread_num() + i ); // Adjust length of trajectory // if (tn==0) std::cout << i << ' ' << std::endl; particles.get_traj(i)->resize(end_dt-start_dt, options.num_groups); models[tn].simulate(values[tn], param_names_threads[tn], particles.get_traj(i), start_dt_threads[tn], end_dt_threads[tn], dt_threads[tn], total_dt_threads[tn], r); double w = 1.0; double temp = 0.0; if (options.which_likelihood<2) { double A = particles.get_traj(i)->get_total_traj(); temp = likelihood_calc.binomial_lik(reporting_rate_threads[tn], A, epi_data.get_data_ptr(0), add_dt_threads[tn]+total_dt_threads[tn], start_dt_threads[tn], end_dt_threads[tn], add_dt_threads[tn], num_groups_threads[tn], false); w *= temp; // we[i] = log(temp); } if (options.which_likelihood != 1) { temp = likelihood_calc.coalescent_lik(particles.get_traj(i)->get_traj_ptr(1, 0), particles.get_traj(i)->get_traj_ptr(2, 0), tree_data.get_binomial_ptr(0), tree_data.get_interval_ptr(0), tree_data.get_ends_ptr(0), start_dt_threads[tn], end_dt_threads[tn], add_dt_threads[tn], false); w *= temp; // wg[i] = log(temp); } particles.set_weight(w, i, true); if (options.save_traj) { particles.save_traj_to_matrix(i, start_dt_threads[tn]+add_dt_threads[tn], end_dt_threads[tn]+add_dt_threads[tn]); particles.save_ancestry(i, start_dt_threads[tn]+add_dt_threads[tn], end_dt_threads[tn]+add_dt_threads[tn]); } } // std::cout << "Epi Weight: " << std::accumulate(we.begin(), we.end(), 0.0) << " Gen Weight: " << std::accumulate(wg.begin(), wg.end(), 0.0) << " Total: " << particles.get_total_weight() << std::endl; double curr_ESS = particles.get_ESS(); if (curr_ESS < ESS_threshold) { double total_weight = particles.get_total_weight(); if (total_weight == 0.0) { loglik += -0.1*std::numeric_limits<double>::max(); // std::cout << std::accumulate(epi_data.get_data_ptr(0)+start_dt, epi_data.get_data_ptr(0)+end_dt, 0.0) << " : " << particles.get_traj(0)->get_traj(0) << std::endl; std::cout << "stop time: " << end_dt << std::endl; break; } else { loglik += log(total_weight) - log(num_particles); } particles.resample(options.rng[0]); } else { particles.reset_parents(); } } if (options.save_traj) { output_traj.resize((total_dt+add_dt), num_groups); //if (loglik > -0.1*std::numeric_limits<double>::max()) { particles.retrace_traj(output_traj, options.rng[0]); //} } for (int i=0; i!=num_particles; ++i) { particles.get_traj(i)->reset(); } std::vector < std::vector<double> >().swap(values); return (loglik); } } <commit_msg>use the correct trajectory pointer<commit_after>// // pfilter.cpp // EpiGenMCMC // // Created by Lucy Li on 05/05/2016. // Copyright (c) 2016 Lucy Li, Imperial College London. All rights reserved. // #include "pfilter.h" #include <iostream> namespace EpiGenPfilter { double pfilter(Model & sim_model, Parameter & model_params, MCMCoptions & options, Particle &particles, Trajectory & output_traj, TimeSeriesData &epi_data, TreeData &tree_data, MultiTreeData &multitree_data) { double loglik = 0.0; int num_groups = options.num_groups; int num_particles = options.particles; int init_seed = options.seed; int total_dt = options.total_dt; double sim_dt = options.sim_dt; int total_steps = ceil((double)total_dt/(double)options.pfilter_every); int add_dt = 0; double ESS_threshold = options.pfilter_threshold*(double)num_particles; Likelihood likelihood_calc; // std::vector <Parameter> values;// (options.num_threads, model_params); // for (int i=0; i!=options.num_threads; ++i) values.push_back(model_params); // for (int i=0; i!=model_params.get_total_params(); ++i) values.push_back(model_params.get(i)); std::vector <std::vector<double> > values(options.num_threads, std::vector<double>(model_params.get_total_params(), 0.0)); for (int i=0; i!=options.num_threads; ++i) { for (int j=0; j!=model_params.get_total_params(); ++j) { values[i][j] = model_params.get(j); } } // printf("Size of values = %d\n",values.size()); double reporting_rate = 1.0; if (model_params.param_exists("reporting")) { reporting_rate = model_params.get("reporting"); } std::vector <std::string> param_names = model_params.get_names_vector(); std::vector <std::vector<std::string> > param_names_threads (options.num_threads); if (model_params.param_exists("time_before_data")) { add_dt = model_params.get("time_before_data"); } if (options.save_traj) { if (add_dt > 0) { particles.start_particle_tracing(add_dt+total_dt, num_groups); } else if (add_dt < 0) { particles.start_particle_tracing(add_dt+total_dt, num_groups); total_steps = ceil((double)(total_dt+add_dt)/(double)options.pfilter_every); } else { particles.start_particle_tracing(total_dt, num_groups); } } std::vector <Model> models; for (int i=0; i<options.num_threads; ++i) { models.push_back(sim_model); } std::vector <int> add_dt_threads (options.num_threads, add_dt); std::vector <int> start_dt_threads (options.num_threads, 0); std::vector <int> end_dt_threads (options.num_threads, add_dt); std::vector <double> dt_threads (options.num_threads, sim_dt); std::vector <int> total_dt_threads(options.num_threads, total_dt); std::vector <double> reporting_rate_threads(options.num_threads, reporting_rate); std::vector <int> num_groups_threads(options.num_threads, num_groups); // Simulate model and calculate likelihood assuming no observed data if (model_params.param_exists("time_before_data")) { if (add_dt > 0) { omp_set_num_threads(options.num_threads); // std::vector <Trajectory *> curr_trajs; // for (int i=0; i!=num_particles; ++i) { // curr_trajs.push_back(particles.get_traj(i)); // } #pragma omp parallel for shared(particles, values) for (int i=0; i<num_particles; i++) { int tn = omp_get_thread_num(); gsl_rng* r = gsl_rng_alloc( gsl_rng_mt19937 ); gsl_rng_set( r, omp_get_thread_num() + i ); // Adjust length of trajectory particles.get_traj(i)->resize(add_dt, num_groups); models[tn].simulate(values[tn], param_names_threads[tn], particles.get_traj(i), 0, add_dt_threads[tn], dt_threads[tn], total_dt_threads[tn], r); if (options.which_likelihood<2) { double w = likelihood_calc.binomial_lik(reporting_rate_threads[tn], particles.get_traj(i)->get_total_traj(), add_dt_threads[tn]+total_dt_threads[tn], 0, add_dt_threads[tn], num_groups_threads[tn], false); particles.set_weight(w, i, false); } if (options.save_traj) { particles.save_traj_to_matrix(i, 0, add_dt); particles.save_ancestry(i, 0, add_dt); } } } } init_seed += num_particles; int t=0; int start_dt; int end_dt; for (t=0; t!=total_steps; ++t) { // std::vector<double> we(options.particles, 0.0), wg(options.particles, 0.0); start_dt = t*options.pfilter_every; end_dt = std::min(total_dt, (t+1)*options.pfilter_every); std::fill(start_dt_threads.begin(), start_dt_threads.end(), start_dt); std::fill(end_dt_threads.begin(), end_dt_threads.end(), end_dt); omp_set_num_threads(options.num_threads); #pragma omp parallel for shared (particles, values) for (int i=0; i<num_particles; i++) { int tn = omp_get_thread_num(); gsl_rng* r = gsl_rng_alloc( gsl_rng_mt19937 ); gsl_rng_set( r, omp_get_thread_num() + i ); // Adjust length of trajectory // if (tn==0) std::cout << i << ' ' << std::endl; particles.get_traj(i)->resize(end_dt-start_dt, options.num_groups); models[tn].simulate(values[tn], param_names_threads[tn], particles.get_traj(i), start_dt_threads[tn], end_dt_threads[tn], dt_threads[tn], total_dt_threads[tn], r); double w = 1.0; double temp = 0.0; if (options.which_likelihood<2) { double A = particles.get_traj(i)->get_total_traj(); temp = likelihood_calc.binomial_lik(reporting_rate_threads[tn], A, epi_data.get_data_ptr(0), add_dt_threads[tn]+total_dt_threads[tn], start_dt_threads[tn], end_dt_threads[tn], add_dt_threads[tn], num_groups_threads[tn], false); w *= temp; // we[i] = log(temp); } if (options.which_likelihood != 1) { temp = likelihood_calc.coalescent_lik(particles.get_traj(i)->get_traj_ptr(0, 0), particles.get_traj(i)->get_traj_ptr(1, 0), tree_data.get_binomial_ptr(0), tree_data.get_interval_ptr(0), tree_data.get_ends_ptr(0), start_dt_threads[tn], end_dt_threads[tn], add_dt_threads[tn], false); w *= temp; // wg[i] = log(temp); } particles.set_weight(w, i, true); if (options.save_traj) { particles.save_traj_to_matrix(i, start_dt_threads[tn]+add_dt_threads[tn], end_dt_threads[tn]+add_dt_threads[tn]); particles.save_ancestry(i, start_dt_threads[tn]+add_dt_threads[tn], end_dt_threads[tn]+add_dt_threads[tn]); } } // std::cout << "Epi Weight: " << std::accumulate(we.begin(), we.end(), 0.0) << " Gen Weight: " << std::accumulate(wg.begin(), wg.end(), 0.0) << " Total: " << particles.get_total_weight() << std::endl; double curr_ESS = particles.get_ESS(); if (curr_ESS < ESS_threshold) { double total_weight = particles.get_total_weight(); if (total_weight == 0.0) { loglik += -0.1*std::numeric_limits<double>::max(); // std::cout << std::accumulate(epi_data.get_data_ptr(0)+start_dt, epi_data.get_data_ptr(0)+end_dt, 0.0) << " : " << particles.get_traj(0)->get_traj(0) << std::endl; std::cout << "stop time: " << end_dt << std::endl; break; } else { loglik += log(total_weight) - log(num_particles); } particles.resample(options.rng[0]); } else { particles.reset_parents(); } } if (options.save_traj) { output_traj.resize((total_dt+add_dt), num_groups); //if (loglik > -0.1*std::numeric_limits<double>::max()) { particles.retrace_traj(output_traj, options.rng[0]); //} } for (int i=0; i!=num_particles; ++i) { particles.get_traj(i)->reset(); } std::vector < std::vector<double> >().swap(values); return (loglik); } } <|endoftext|>
<commit_before>#include "mmd/pmx/mesh.hpp" #include "../stream.hpp" namespace mmd { namespace pmx { void Vertex::load(Fs *fs, Header *header) { Stream *stream = (Stream *)fs; position = stream->readVec3(); normal = stream->readVec3(); uv = stream->readVec2(); for (int i = 0; i < header->additional; ++i) { addition[i] = stream->readVec4(); } boneType = stream->readByte(); switch (boneType) { case 0: BDEF.bone[0] = stream->readIndex(header->bone); break; case 1: BDEF.bone[0] = stream->readIndex(header->bone); BDEF.bone[1] = stream->readIndex(header->bone); BDEF.weight[0] = stream->readFloat(); BDEF.weight[1] = 1.0f - BDEF.weight[0]; break; case 2: case 4: for (int i = 0; i < 4; ++i) { BDEF.bone[i] = stream->readIndex(header->bone); } for (int i = 0; i < 4; ++i) { BDEF.weight[i] = stream->readFloat(); } break; case 3: SDEF.bone[0] = stream->readIndex(header->bone); SDEF.bone[1] = stream->readIndex(header->bone); SDEF.weight[0] = stream->readFloat(); SDEF.weight[1] = 1.0f - SDEF.weight[0]; SDEF.C = stream->readVec3(); SDEF.R0 = stream->readVec3(); SDEF.R1 = stream->readVec3(); break; default: FAIL << "Invalid bone type!"; } edge = stream->readFloat(); } void Surface::load(Fs *fs, Header *header) { Stream *stream = (Stream *)fs; A = stream->readUIndex(header->vertex); B = stream->readUIndex(header->vertex); C = stream->readUIndex(header->vertex); } void Mesh::load(Fs *fs, Header *header) { LOG << "load Mesh"; Stream *stream = (Stream *)fs; int n = stream->readInt(); vertex.resize(n); for (int i = 0; i < n; ++i) { vertex[i].load(fs, header); } n = stream->readInt(); surface.resize(n); for (int i = 0; i < n; ++i) { surface[i].load(fs, header); } LOG << "---------------------"; LOG << "Mesh infomation"; LOG << "---------------------"; LOG << "vertices: " << vertex.size(); LOG << "surfaces: " << surface.size(); } } /* pmx */ } /* mmd */ <commit_msg>solve a bug<commit_after>#include "mmd/pmx/mesh.hpp" #include "../stream.hpp" namespace mmd { namespace pmx { void Vertex::load(Fs *fs, Header *header) { Stream *stream = (Stream *)fs; position = stream->readVec3(); normal = stream->readVec3(); uv = stream->readVec2(); for (int i = 0; i < header->additional; ++i) { addition[i] = stream->readVec4(); } boneType = stream->readByte(); switch (boneType) { case 0: BDEF.bone[0] = stream->readIndex(header->bone); break; case 1: BDEF.bone[0] = stream->readIndex(header->bone); BDEF.bone[1] = stream->readIndex(header->bone); BDEF.weight[0] = stream->readFloat(); BDEF.weight[1] = 1.0f - BDEF.weight[0]; break; case 2: case 4: for (int i = 0; i < 4; ++i) { BDEF.bone[i] = stream->readIndex(header->bone); } for (int i = 0; i < 4; ++i) { BDEF.weight[i] = stream->readFloat(); } break; case 3: SDEF.bone[0] = stream->readIndex(header->bone); SDEF.bone[1] = stream->readIndex(header->bone); SDEF.weight[0] = stream->readFloat(); SDEF.weight[1] = 1.0f - SDEF.weight[0]; SDEF.C = stream->readVec3(); SDEF.R0 = stream->readVec3(); SDEF.R1 = stream->readVec3(); break; default: FAIL << "Invalid bone type!"; } edge = stream->readFloat(); } void Surface::load(Fs *fs, Header *header) { Stream *stream = (Stream *)fs; A = stream->readUIndex(header->vertex); B = stream->readUIndex(header->vertex); C = stream->readUIndex(header->vertex); } void Mesh::load(Fs *fs, Header *header) { LOG << "load Mesh"; Stream *stream = (Stream *)fs; int n = stream->readInt(); vertex.resize(n); for (int i = 0; i < n; ++i) { vertex[i].load(fs, header); } n = stream->readInt() / 3; surface.resize(n); for (int i = 0; i < n; ++i) { surface[i].load(fs, header); } LOG << "---------------------"; LOG << "Mesh infomation"; LOG << "---------------------"; LOG << "vertices: " << vertex.size(); LOG << "surfaces: " << surface.size(); } } /* pmx */ } /* mmd */ <|endoftext|>
<commit_before>/* * Simka2ComputeKmerSpectrum.hpp * * Created on: 4 nov. 2016 * Author: gbenoit */ #include <gatb/gatb_core.hpp> //#include "../core/SimkaUtils.hpp" #include "../simka2/Simka2Utils.hpp" #include "SimkaDistanceMatrixBinary.hpp" //#include "../core/SimkaUtils.hpp" //#include "Simka2Database.hpp" //#include "../minikc/MiniKC.hpp" //#include <gatb/kmer/impl/RepartitionAlgorithm.hpp> //#include <gatb/kmer/impl/ConfigurationAlgorithm.hpp> //#include "SimkaAlgorithm.hpp" //#include "SimkaAlgorithm.hpp" /********************************************************************* * ** SimkaAlgorithm *********************************************************************/ class SimkaDistanceExporterAlgorithm : public Algorithm { public: string _dirBinaryMatrices; string _inputFilenameIds; string _outputDir; vector<string> _ids; vector<string> _wantedIds; vector<size_t> _wantedIdsIndex; map<string, size_t> _idToIndex; size_t _matrixSize; SimkaDistanceExporterAlgorithm(IProperties* options): Algorithm("simkaDistanceExporter", -1, options) { _inputFilenameIds = ""; } void execute(){ parseArgs(); createWantedIds(); createIdsIndex(); writeMatrices(); } void parseArgs(){ _dirBinaryMatrices = getInput()->getStr(STR_URI_INPUT); _outputDir = getInput()->getStr(STR_URI_OUTPUT); if(getInput()->get(STR_SIMKA2_INPUT_IDS)){ _inputFilenameIds = getInput()->getStr(STR_SIMKA2_INPUT_IDS); } if(!System::file().doesExist(_outputDir)){ System::file().mkdir(_outputDir, -1); } } void createWantedIds(){ SimkaDistanceMatrixBinary::loadMatrixIds(_dirBinaryMatrices, _ids); if(_inputFilenameIds.empty()){ _wantedIds = vector<string>(_ids); } else{ string line; ifstream inputFile(_inputFilenameIds.c_str()); while(getline(inputFile, line)){ line.erase(std::remove(line.begin(),line.end(),' '),line.end()); if(line == "") continue; _wantedIds.push_back(line); } } _matrixSize = _wantedIds.size(); cout << "matrix size: " << _matrixSize << endl; } void createIdsIndex(){ for(size_t i=0; i<_ids.size(); i++){ _idToIndex[_ids[i]] = i; } _wantedIdsIndex.resize(_matrixSize); for(size_t i=0; i<_matrixSize; i++){ _wantedIdsIndex[i] = _idToIndex[_wantedIds[i]]; } } void writeMatrices(){ vector<string> matrixFilenames = System::file().listdir(_dirBinaryMatrices); for(size_t i=0; i<matrixFilenames.size(); i++){ string matrixFilename = _dirBinaryMatrices + "/" + matrixFilenames[i]; if(matrixFilename.find("mat_") == string::npos) continue; string distanceName = matrixFilenames[i]; string ext = ".bin"; std::string::size_type it = distanceName.find(ext); distanceName.erase(it, ext.length()); cout << distanceName << endl; writeMatrixASCII(distanceName, matrixFilename); } } void writeMatrixASCII(const string& distanceName, const string& binaryMatrixFilename){ vector<float> rowData(_matrixSize, 0); ifstream binaryMatrixFile(binaryMatrixFilename.c_str(), ios::binary); string filename = _outputDir + "/" + distanceName + ".csv"; gzFile out = gzopen((filename + ".gz").c_str(),"wb"); string str = ""; for(size_t i=0; i<_matrixSize; i++){ str += ";" + _wantedIds[i]; } str += '\n'; gzwrite(out, str.c_str(), str.size()); for(size_t i=0; i<_matrixSize; i++){ str = ""; str += _wantedIds[i] + ";"; size_t rowIndex = _wantedIdsIndex[i]; SimkaDistanceMatrixBinary::loadRow(rowIndex, binaryMatrixFile, rowData); for(size_t j=0; j<_matrixSize; j++){ str += Stringify::format("%f", rowData[_wantedIdsIndex[j]]) + ";"; } str.erase(str.size()-1); str += '\n'; gzwrite(out, str.c_str(), str.size()); } gzclose(out); binaryMatrixFile.close(); } /* void outputMatrixToAscii(){ string filename = outputDir + "/" + outputFilename + _outputFilenameSuffix + ".csv"; //IFile* file = gatb::core::system::impl::System::file().newFile(filename, "wb"); Bag<string>* bag = new BagGzFile<string>(outputDir + "/" + outputFilename + _outputFilenameSuffix + ".csv.gz"); //Bag<string>* cachedBag = new BagCache<string>(bag, 10000); gzFile out = gzopen((filename + ".gz").c_str(),"wb"); //char buf[BUFSIZ] = { 0 }; //char buffer[200]; string str; for(size_t i=0; i<matrix.size(); i++){ str += ";" + bankNames[i]; //str += ";" + datasetInfos[i]._name; } str += '\n'; gzwrite(out, str.c_str(), str.size()); //cachedBag->insert(str); //file->fwrite(str.c_str(), str.size(), 1); str = ""; for(size_t i=0; i<matrix.size(); i++){ str = ""; str += bankNames[i] + ";"; //str += datasetInfos[i]._name + ";"; for(size_t j=0; j<matrix.size(); j++){ //snprintf(buffer,200,"%.2f", matrix[i][j]); //snprintf(buffer,200,"%f", matrix[i][j]); str += Stringify::format("%f", matrix[i][j]) + ";"; //str += to_string(matrix[i][j]) + ";"; } //matrixNormalizedStr.erase(matrixNormalizedStr.end()-1); str.erase(str.size()-1); //str.pop_back(); //remove ; at the end of the line str += '\n'; //cout << str << endl; //file->fwrite(str.c_str(), str.size(), 1); gzwrite(out, str.c_str(), str.size()); //cachedBag->insert(str); } //gatb::core::system::IFile* file = gatb::core::system::impl::System::file().newFile(outputDir + "/" + outputFilename + _outputFilenameSuffix + ".csv", "wb"); //file->flush(); //delete file; gzclose(out); //delete cachedBag; }*/ }; class SimkaDistanceExporter: public Tool{ public: string _execFilename; SimkaDistanceExporter(string execFilename): Tool ("Simka-DistanceMatrixWriter"){ _execFilename = execFilename; IOptionsParser* parser = getParser();//new OptionsParser ("Simka2 - Compute Kmer Spectrum"); parser->push_front (new OptionOneParam (STR_URI_INPUT, "path to a dir of binary matrices", true)); parser->push_front (new OptionOneParam (STR_SIMKA2_INPUT_IDS, "filename of ids in the result matrix (one id per line). Do not used this option to used all ids.", false)); parser->push_front (new OptionOneParam (STR_URI_OUTPUT, "output dir for distance matrices", true)); //parser->push_front (new OptionOneParam (STR_URI_OUTPUT, "output directory for merged kmer spectrum", true)); // parser->push_front (new OptionOneParam (STR_SIMKA2_DATABASE_DIR, "dir path to a simka database", true)); //parser->push_front (new OptionOneParam (STR_SIMKA2_NB_PARTITION, "number of partitions", true)); //parser->push_front (new OptionOneParam (STR_SIMKA2_PARTITION_ID, "number of the partition", true)); //parser->push_front (new OptionOneParam (STR_SIMKA2_DISTANCE_MATRIX_DIR, "input filename of k-mer spectrums for which distances has to be computed", true)); // IOptionsParser* kmerParser = new OptionsParser ("kmer"); //kmerParser->push_back (new OptionOneParam (STR_KMER_SIZE, "size of a kmer", true)); //parser->getParser(STR_NB_CORES)->setVisible(false); //parser->push_back(kmerParser); } void execute () { IProperties* input = getInput(); //Parameter params(*this, getInput()); //Parameter params(input, _execFilename); //size_t kmerSize = getInput()->getInt (STR_KMER_SIZE); //Integer::apply<Functor,Parameter> (kmerSize, params); SimkaDistanceExporterAlgorithm* algo = new SimkaDistanceExporterAlgorithm(input); algo->execute(); delete algo; } }; int main (int argc, char* argv[]) { try { SimkaDistanceExporter(string(argv[0])).run (argc, argv); } catch (Exception& e) { std::cout << "EXCEPTION: " << e.getMessage() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>fix bug in distance exporter<commit_after>/* * Simka2ComputeKmerSpectrum.hpp * * Created on: 4 nov. 2016 * Author: gbenoit */ #include <gatb/gatb_core.hpp> //#include "../core/SimkaUtils.hpp" #include "../simka2/Simka2Utils.hpp" #include "SimkaDistanceMatrixBinary.hpp" //#include "../core/SimkaUtils.hpp" //#include "Simka2Database.hpp" //#include "../minikc/MiniKC.hpp" //#include <gatb/kmer/impl/RepartitionAlgorithm.hpp> //#include <gatb/kmer/impl/ConfigurationAlgorithm.hpp> //#include "SimkaAlgorithm.hpp" //#include "SimkaAlgorithm.hpp" /********************************************************************* * ** SimkaAlgorithm *********************************************************************/ class SimkaDistanceExporterAlgorithm : public Algorithm { public: string _dirBinaryMatrices; string _inputFilenameIds; string _outputDir; vector<string> _ids; vector<string> _wantedIds; vector<size_t> _wantedIdsIndex; map<string, size_t> _idToIndex; size_t _inputMatrixSize; size_t _outputMatrixSize; SimkaDistanceExporterAlgorithm(IProperties* options): Algorithm("simkaDistanceExporter", -1, options) { _inputFilenameIds = ""; } void execute(){ parseArgs(); createWantedIds(); createIdsIndex(); writeMatrices(); } void parseArgs(){ _dirBinaryMatrices = getInput()->getStr(STR_URI_INPUT); _outputDir = getInput()->getStr(STR_URI_OUTPUT); if(getInput()->get(STR_SIMKA2_INPUT_IDS)){ _inputFilenameIds = getInput()->getStr(STR_SIMKA2_INPUT_IDS); } if(!System::file().doesExist(_outputDir)){ System::file().mkdir(_outputDir, -1); } } void createWantedIds(){ SimkaDistanceMatrixBinary::loadMatrixIds(_dirBinaryMatrices, _ids); if(_inputFilenameIds.empty()){ _wantedIds = vector<string>(_ids); } else{ string line; ifstream inputFile(_inputFilenameIds.c_str()); while(getline(inputFile, line)){ line.erase(std::remove(line.begin(),line.end(),' '),line.end()); if(line == "") continue; _wantedIds.push_back(line); } } _inputMatrixSize = _ids.size(); _outputMatrixSize = _wantedIds.size(); cout << "original matrix size: " << _inputMatrixSize << endl; cout << "output matrix size: " << _outputMatrixSize << endl; } void createIdsIndex(){ for(size_t i=0; i<_ids.size(); i++){ _idToIndex[_ids[i]] = i; } _wantedIdsIndex.resize(_outputMatrixSize); for(size_t i=0; i<_outputMatrixSize; i++){ _wantedIdsIndex[i] = _idToIndex[_wantedIds[i]]; } } void writeMatrices(){ vector<string> matrixFilenames = System::file().listdir(_dirBinaryMatrices); for(size_t i=0; i<matrixFilenames.size(); i++){ string matrixFilename = _dirBinaryMatrices + "/" + matrixFilenames[i]; if(matrixFilename.find("mat_") == string::npos) continue; string distanceName = matrixFilenames[i]; string ext = ".bin"; std::string::size_type it = distanceName.find(ext); distanceName.erase(it, ext.length()); cout << distanceName << endl; writeMatrixASCII(distanceName, matrixFilename); } } void writeMatrixASCII(const string& distanceName, const string& binaryMatrixFilename){ vector<float> rowData(_inputMatrixSize, 0); ifstream binaryMatrixFile(binaryMatrixFilename.c_str(), ios::binary); string filename = _outputDir + "/" + distanceName + ".csv"; gzFile out = gzopen((filename + ".gz").c_str(),"wb"); string str = ""; for(size_t i=0; i<_outputMatrixSize; i++){ str += ";" + _wantedIds[i]; } str += '\n'; gzwrite(out, str.c_str(), str.size()); for(size_t i=0; i<_outputMatrixSize; i++){ str = ""; str += _wantedIds[i] + ";"; size_t rowIndex = _wantedIdsIndex[i]; SimkaDistanceMatrixBinary::loadRow(rowIndex, binaryMatrixFile, rowData); for(size_t j=0; j<_outputMatrixSize; j++){ str += Stringify::format("%f", rowData[_wantedIdsIndex[j]]) + ";"; } str.erase(str.size()-1); str += '\n'; gzwrite(out, str.c_str(), str.size()); } gzclose(out); binaryMatrixFile.close(); } /* void outputMatrixToAscii(){ string filename = outputDir + "/" + outputFilename + _outputFilenameSuffix + ".csv"; //IFile* file = gatb::core::system::impl::System::file().newFile(filename, "wb"); Bag<string>* bag = new BagGzFile<string>(outputDir + "/" + outputFilename + _outputFilenameSuffix + ".csv.gz"); //Bag<string>* cachedBag = new BagCache<string>(bag, 10000); gzFile out = gzopen((filename + ".gz").c_str(),"wb"); //char buf[BUFSIZ] = { 0 }; //char buffer[200]; string str; for(size_t i=0; i<matrix.size(); i++){ str += ";" + bankNames[i]; //str += ";" + datasetInfos[i]._name; } str += '\n'; gzwrite(out, str.c_str(), str.size()); //cachedBag->insert(str); //file->fwrite(str.c_str(), str.size(), 1); str = ""; for(size_t i=0; i<matrix.size(); i++){ str = ""; str += bankNames[i] + ";"; //str += datasetInfos[i]._name + ";"; for(size_t j=0; j<matrix.size(); j++){ //snprintf(buffer,200,"%.2f", matrix[i][j]); //snprintf(buffer,200,"%f", matrix[i][j]); str += Stringify::format("%f", matrix[i][j]) + ";"; //str += to_string(matrix[i][j]) + ";"; } //matrixNormalizedStr.erase(matrixNormalizedStr.end()-1); str.erase(str.size()-1); //str.pop_back(); //remove ; at the end of the line str += '\n'; //cout << str << endl; //file->fwrite(str.c_str(), str.size(), 1); gzwrite(out, str.c_str(), str.size()); //cachedBag->insert(str); } //gatb::core::system::IFile* file = gatb::core::system::impl::System::file().newFile(outputDir + "/" + outputFilename + _outputFilenameSuffix + ".csv", "wb"); //file->flush(); //delete file; gzclose(out); //delete cachedBag; }*/ }; class SimkaDistanceExporter: public Tool{ public: string _execFilename; SimkaDistanceExporter(string execFilename): Tool ("Simka-DistanceMatrixWriter"){ _execFilename = execFilename; IOptionsParser* parser = getParser();//new OptionsParser ("Simka2 - Compute Kmer Spectrum"); parser->push_front (new OptionOneParam (STR_URI_INPUT, "path to a dir of binary matrices", true)); parser->push_front (new OptionOneParam (STR_SIMKA2_INPUT_IDS, "filename of ids in the result matrix (one id per line). Do not used this option to used all ids.", false)); parser->push_front (new OptionOneParam (STR_URI_OUTPUT, "output dir for distance matrices", true)); //parser->push_front (new OptionOneParam (STR_URI_OUTPUT, "output directory for merged kmer spectrum", true)); // parser->push_front (new OptionOneParam (STR_SIMKA2_DATABASE_DIR, "dir path to a simka database", true)); //parser->push_front (new OptionOneParam (STR_SIMKA2_NB_PARTITION, "number of partitions", true)); //parser->push_front (new OptionOneParam (STR_SIMKA2_PARTITION_ID, "number of the partition", true)); //parser->push_front (new OptionOneParam (STR_SIMKA2_DISTANCE_MATRIX_DIR, "input filename of k-mer spectrums for which distances has to be computed", true)); // IOptionsParser* kmerParser = new OptionsParser ("kmer"); //kmerParser->push_back (new OptionOneParam (STR_KMER_SIZE, "size of a kmer", true)); //parser->getParser(STR_NB_CORES)->setVisible(false); //parser->push_back(kmerParser); } void execute () { IProperties* input = getInput(); //Parameter params(*this, getInput()); //Parameter params(input, _execFilename); //size_t kmerSize = getInput()->getInt (STR_KMER_SIZE); //Integer::apply<Functor,Parameter> (kmerSize, params); SimkaDistanceExporterAlgorithm* algo = new SimkaDistanceExporterAlgorithm(input); algo->execute(); delete algo; } }; int main (int argc, char* argv[]) { try { SimkaDistanceExporter(string(argv[0])).run (argc, argv); } catch (Exception& e) { std::cout << "EXCEPTION: " << e.getMessage() << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #ifndef HAVE_LIBVLC # error This file requires libvlc #endif #include "Directory.h" #include "File.h" #include "utils/Filename.h" #include "utils/VLCInstance.h" #include "compat/ConditionVariable.h" #include "compat/Mutex.h" #include <vlcpp/vlc.hpp> namespace medialibrary { namespace fs { NetworkDirectory::NetworkDirectory( const std::string& mrl, fs::IFileSystemFactory& fsFactory ) : CommonDirectory( fsFactory ) , m_mrl( utils::file::toFolderPath( mrl ) ) { } const std::string& NetworkDirectory::mrl() const { return m_mrl; } void NetworkDirectory::read() const { VLC::Media media( VLCInstance::get(), m_mrl, VLC::Media::FromLocation ); assert( media.parsedStatus() != VLC::Media::ParsedStatus::Done ); compat::Mutex mutex; compat::ConditionVariable cond; VLC::Media::ParsedStatus res = VLC::Media::ParsedStatus::Skipped; auto eventHandler = media.eventManager().onParsedChanged( [&mutex, &cond, &res]( VLC::Media::ParsedStatus status) { std::lock_guard<compat::Mutex> lock( mutex ); res = status; cond.notify_all(); }); std::unique_lock<compat::Mutex> lock( mutex ); media.parseWithOptions( VLC::Media::ParseFlags::Network | VLC::Media::ParseFlags::Local, -1 ); bool timeout = cond.wait_for( lock, std::chrono::seconds{ 5 }, [&res]() { return res != VLC::Media::ParsedStatus::Skipped; }); eventHandler->unregister(); if ( timeout == true ) throw std::system_error( ETIMEDOUT, std::generic_category(), "Failed to browse network directory: Network is too slow" ); if ( res == VLC::Media::ParsedStatus::Failed ) throw std::system_error( EIO, std::generic_category(), "Failed to browse network directory: Unknown error" ); auto subItems = media.subitems(); for ( auto i = 0; i < subItems->count(); ++i ) { auto m = subItems->itemAtIndex( i ); if ( m->type() == VLC::Media::Type::Directory ) m_dirs.push_back( std::make_shared<fs::NetworkDirectory>( m->mrl(), m_fsFactory ) ); else m_files.push_back( std::make_shared<fs::NetworkFile>( m->mrl() ) ); } } } } <commit_msg>fs: Network: Directory: Fix inverted logic<commit_after>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015 Hugo Beauzée-Luyssen, Videolabs * * Authors: Hugo Beauzée-Luyssen<hugo@beauzee.fr> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. *****************************************************************************/ #if HAVE_CONFIG_H # include "config.h" #endif #ifndef HAVE_LIBVLC # error This file requires libvlc #endif #include "Directory.h" #include "File.h" #include "utils/Filename.h" #include "utils/VLCInstance.h" #include "compat/ConditionVariable.h" #include "compat/Mutex.h" #include <vlcpp/vlc.hpp> namespace medialibrary { namespace fs { NetworkDirectory::NetworkDirectory( const std::string& mrl, fs::IFileSystemFactory& fsFactory ) : CommonDirectory( fsFactory ) , m_mrl( utils::file::toFolderPath( mrl ) ) { } const std::string& NetworkDirectory::mrl() const { return m_mrl; } void NetworkDirectory::read() const { VLC::Media media( VLCInstance::get(), m_mrl, VLC::Media::FromLocation ); assert( media.parsedStatus() != VLC::Media::ParsedStatus::Done ); compat::Mutex mutex; compat::ConditionVariable cond; VLC::Media::ParsedStatus res = VLC::Media::ParsedStatus::Skipped; auto eventHandler = media.eventManager().onParsedChanged( [&mutex, &cond, &res]( VLC::Media::ParsedStatus status) { std::lock_guard<compat::Mutex> lock( mutex ); res = status; cond.notify_all(); }); std::unique_lock<compat::Mutex> lock( mutex ); media.parseWithOptions( VLC::Media::ParseFlags::Network | VLC::Media::ParseFlags::Local, -1 ); bool success = cond.wait_for( lock, std::chrono::seconds{ 5 }, [&res]() { return res != VLC::Media::ParsedStatus::Skipped; }); eventHandler->unregister(); if ( success == false ) throw std::system_error( ETIMEDOUT, std::generic_category(), "Failed to browse network directory: Network is too slow" ); if ( res == VLC::Media::ParsedStatus::Failed ) throw std::system_error( EIO, std::generic_category(), "Failed to browse network directory: Unknown error" ); auto subItems = media.subitems(); for ( auto i = 0; i < subItems->count(); ++i ) { auto m = subItems->itemAtIndex( i ); if ( m->type() == VLC::Media::Type::Directory ) m_dirs.push_back( std::make_shared<fs::NetworkDirectory>( m->mrl(), m_fsFactory ) ); else m_files.push_back( std::make_shared<fs::NetworkFile>( m->mrl() ) ); } } } } <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3 * * (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include <sofa/component/topology/DynamicSparseGridTopologyContainer.h> #include <sofa/core/ObjectFactory.h> #include <sofa/component/container/VoxelGridLoader.h> namespace sofa { namespace component { namespace topology { using namespace std; using namespace sofa::defaulttype; SOFA_DECL_CLASS ( DynamicSparseGridTopologyContainer ); int DynamicSparseGridTopologyContainerClass = core::RegisterObject ( "Hexahedron set topology container" ) .add< DynamicSparseGridTopologyContainer >() ; DynamicSparseGridTopologyContainer::DynamicSparseGridTopologyContainer() : HexahedronSetTopologyContainer() , resolution ( initData ( &resolution, Vec3i ( 0, 0, 0 ), "resolution", "voxel grid resolution" ) ) { } DynamicSparseGridTopologyContainer::DynamicSparseGridTopologyContainer ( const sofa::helper::vector< Hexahedron > &hexahedra ) : HexahedronSetTopologyContainer ( hexahedra ) , resolution ( initData ( &resolution, Vec3i ( 0, 0, 0 ), "resolution", "voxel grid resolution" ) ) { } void DynamicSparseGridTopologyContainer::loadFromMeshLoader ( sofa::component::MeshLoader* loader ) { HexahedronSetTopologyContainer::loadFromMeshLoader( loader); sofa::component::VoxelGridLoader* voxelGridLoader = dynamic_cast< sofa::component::VoxelGridLoader*> ( loader ); if ( !voxelGridLoader ) { cerr << "DynamicSparseGridTopologyContainer::loadFromMeshLoader(): The loader used is not a VoxelGridLoader ! You must use it for this topology." << endl; exit(0); } // Init regular/topo mapping helper::vector<BaseMeshTopology::HexaID>& iirg = *(idxInRegularGrid.beginEdit()); voxelGridLoader->getIndicesInRegularGrid( iirg); for( unsigned int i = 0; i < iirg.size(); i++) { idInRegularGrid2IndexInTopo.insert( make_pair( iirg[i], i )); } idxInRegularGrid.endEdit(); // Init values int dataSize = voxelGridLoader->getDataSize(); unsigned char* data = voxelGridLoader->getData(); // init values in regular grid. (dense). valuesIndexedInRegularGrid.resize( dataSize); for( int i = 0; i < dataSize; i++) valuesIndexedInRegularGrid[i] = data[i]; // init values in topo. (pas dense). helper::vector<unsigned char>& viit = *(valuesIndexedInTopology.beginEdit()); viit.resize( iirg.size()); for( int i = 0; i < iirg.size(); i++) { viit[i] = data[iirg[i]]; } valuesIndexedInTopology.endEdit(); // init resolution & voxelSize. Vec3i& res = *resolution.beginEdit(); voxelGridLoader->getResolution ( res ); resolution.endEdit(); voxelGridLoader->getVoxelSize ( voxelSize ); } } // namespace topology } // namespace component } // namespace sofa <commit_msg>r4096/sofa-dev : FIX: compilation warnings<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 3 * * (c) 2006-2008 MGH, INRIA, USTL, UJF, CNRS * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Lesser General Public License as published by * * the Free Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT * * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this library; if not, write to the Free Software Foundation, * * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: contact@sofa-framework.org * ******************************************************************************/ #include <sofa/component/topology/DynamicSparseGridTopologyContainer.h> #include <sofa/core/ObjectFactory.h> #include <sofa/component/container/VoxelGridLoader.h> namespace sofa { namespace component { namespace topology { using namespace std; using namespace sofa::defaulttype; SOFA_DECL_CLASS ( DynamicSparseGridTopologyContainer ); int DynamicSparseGridTopologyContainerClass = core::RegisterObject ( "Hexahedron set topology container" ) .add< DynamicSparseGridTopologyContainer >() ; DynamicSparseGridTopologyContainer::DynamicSparseGridTopologyContainer() : HexahedronSetTopologyContainer() , resolution ( initData ( &resolution, Vec3i ( 0, 0, 0 ), "resolution", "voxel grid resolution" ) ) { } DynamicSparseGridTopologyContainer::DynamicSparseGridTopologyContainer ( const sofa::helper::vector< Hexahedron > &hexahedra ) : HexahedronSetTopologyContainer ( hexahedra ) , resolution ( initData ( &resolution, Vec3i ( 0, 0, 0 ), "resolution", "voxel grid resolution" ) ) { } void DynamicSparseGridTopologyContainer::loadFromMeshLoader ( sofa::component::MeshLoader* loader ) { HexahedronSetTopologyContainer::loadFromMeshLoader( loader); sofa::component::VoxelGridLoader* voxelGridLoader = dynamic_cast< sofa::component::VoxelGridLoader*> ( loader ); if ( !voxelGridLoader ) { cerr << "DynamicSparseGridTopologyContainer::loadFromMeshLoader(): The loader used is not a VoxelGridLoader ! You must use it for this topology." << endl; exit(0); } // Init regular/topo mapping helper::vector<BaseMeshTopology::HexaID>& iirg = *(idxInRegularGrid.beginEdit()); voxelGridLoader->getIndicesInRegularGrid( iirg); for( unsigned int i = 0; i < iirg.size(); i++) { idInRegularGrid2IndexInTopo.insert( make_pair( iirg[i], i )); } idxInRegularGrid.endEdit(); // Init values int dataSize = voxelGridLoader->getDataSize(); unsigned char* data = voxelGridLoader->getData(); // init values in regular grid. (dense). valuesIndexedInRegularGrid.resize( dataSize); for( int i = 0; i < dataSize; i++) valuesIndexedInRegularGrid[i] = data[i]; // init values in topo. (pas dense). helper::vector<unsigned char>& viit = *(valuesIndexedInTopology.beginEdit()); viit.resize( iirg.size()); for(unsigned int i = 0; i < iirg.size(); i++) { viit[i] = data[iirg[i]]; } valuesIndexedInTopology.endEdit(); // init resolution & voxelSize. Vec3i& res = *resolution.beginEdit(); voxelGridLoader->getResolution ( res ); resolution.endEdit(); voxelGridLoader->getVoxelSize ( voxelSize ); } } // namespace topology } // namespace component } // namespace sofa <|endoftext|>
<commit_before>// Reverse order of vector<int> #include "../../std_lib_facilities.h" int main() { return 0; }<commit_msg>Reversing order of vector<commit_after>// Reverse order of vector<int> #include "../../std_lib_facilities.h" #include <exception> // std::exception void reverseOrder(vector<int> t, vector<int> &res) { while (!t.empty()) { res.push_back(t.back()); t.pop_back(); } } void print(const string &outputLabel, const vector<int> &vec) { cout << outputLabel << " "; for (auto i : vec) { cout << i << " "; } cout << endl; } int main() { try { vector<int> normal = {1,2,3,4,5,6,7,8,9}; vector<int> reversed; reverseOrder(normal, reversed); cout << "We'll try to reverse order of vector "; print(">> ", normal); print("res >> ", reversed); print("normal >> ", normal); } catch (std::exception& e) { cerr << e.what() << endl; return 1; } return 0; }<|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/searchlib/attribute/attributefactory.h> #include <vespa/searchlib/fef/test/ftlib.h> #include <vespa/searchlib/features/max_reduce_prod_join_feature.h> #include <vespa/searchlib/attribute/attribute.h> using search::feature_t; using namespace search::fef; using namespace search::fef::test; using namespace search::features; using search::AttributeFactory; using search::IntegerAttribute; using CollectionType = FieldInfo::CollectionType; typedef search::attribute::Config AVC; typedef search::attribute::BasicType AVBT; typedef search::attribute::CollectionType AVCT; typedef search::AttributeVector::SP AttributePtr; typedef FtTestApp FTA; struct SetupFixture { InternalMaxReduceProdJoinBlueprint blueprint; IndexEnvironment indexEnv; SetupFixture(const vespalib::string &attr) : blueprint(), indexEnv() { FieldInfo attr_info(FieldType::ATTRIBUTE, CollectionType::ARRAY, attr, 0); indexEnv.getFields().push_back(attr_info); } }; TEST_F("require that blueprint can be created", SetupFixture("attribute(foo)")) { EXPECT_TRUE(FTA::assertCreateInstance(f.blueprint, "internalMaxReduceProdJoin")); } TEST_F("require that setup fails if source spec is invalid", SetupFixture("attribute(foo)")) { FTA::FT_SETUP_FAIL(f.blueprint, f.indexEnv, StringList().add("source(foo)")); } TEST_F("require that setup fails if attribute does not exist", SetupFixture("attribute(foo)")) { FTA::FT_SETUP_FAIL(f.blueprint, f.indexEnv, StringList().add("attribute(bar)").add("query(baz)")); } TEST_F("require that setup succeeds with attribute and query parameters", SetupFixture("attribute(foo)")) { FTA::FT_SETUP_OK(f.blueprint, f.indexEnv, StringList().add("attribute(foo)").add("query(bar)"), StringList(), StringList().add("scalar")); } struct ExecFixture { BlueprintFactory factory; FtFeatureTest test; vespalib::string feature; ExecFixture(const vespalib::string &f) : factory(), test(factory, f), feature(f) { factory.addPrototype(std::make_shared<InternalMaxReduceProdJoinBlueprint>()); setupAttributeVectors(); setupQueryEnvironment(); ASSERT_TRUE(test.setup()); } void setupAttributeVectors() { vespalib::string attrIntArray = "attribute(intarray)"; vespalib::string attrLongArray = "attribute(longarray)"; test.getIndexEnv().getBuilder().addField(FieldType::ATTRIBUTE, CollectionType::ARRAY, attrLongArray); test.getIndexEnv().getBuilder().addField(FieldType::ATTRIBUTE, CollectionType::ARRAY, attrIntArray); std::vector<AttributePtr> attrs; attrs.push_back(AttributeFactory::createAttribute(attrLongArray, AVC(AVBT::INT64, AVCT::ARRAY))); attrs.push_back(AttributeFactory::createAttribute(attrIntArray, AVC(AVBT::INT32, AVCT::ARRAY))); for (const auto &attr : attrs) { attr->addReservedDoc(); attr->addDocs(1); test.getIndexEnv().getAttributeMap().add(attr); } IntegerAttribute *longArray = static_cast<IntegerAttribute *>(attrs[0].get()); longArray->append(1, 1111, 0); longArray->append(1, 2222, 0); longArray->append(1, 78, 0); IntegerAttribute *intArray = static_cast<IntegerAttribute *>(attrs[1].get()); intArray->append(1, 78, 0); intArray->append(1, 1111, 0); for (const auto &attr : attrs) { attr->commit(); } } void setupQueryEnvironment() { test.getQueryEnv().getProperties().add("query(wset)", "{1111:1234, 2222:2245}"); test.getQueryEnv().getProperties().add("query(wsetnomatch)", "{1:1000, 2:2000}"); test.getQueryEnv().getProperties().add("query(array)", "[1111,2222]"); } bool evaluatesTo(feature_t expected) { return test.execute(expected); } }; TEST_F("require that executor returns correct result for long array", ExecFixture("internalMaxReduceProdJoin(attribute(longarray),query(wset))")) { EXPECT_TRUE(f.evaluatesTo(2245)); } TEST_F("require that executor returns correct result for int array", ExecFixture("internalMaxReduceProdJoin(attribute(intarray),query(wset))")) { EXPECT_TRUE(f.evaluatesTo(1234)); } TEST_F("require that executor returns 0 if no items match", ExecFixture("internalMaxReduceProdJoin(attribute(longarray),query(wsetnomatch))")) { EXPECT_TRUE(f.evaluatesTo(0.0)); } TEST_F("require that executor return 0 if query is not a weighted set", ExecFixture("internalMaxReduceProdJoin(attribute(longarray),query(array))")) { EXPECT_TRUE(f.evaluatesTo(0.0)); } TEST_MAIN() { TEST_RUN_ALL(); } <commit_msg>Remove unnecessary feature name in test fixture<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/searchlib/attribute/attributefactory.h> #include <vespa/searchlib/fef/test/ftlib.h> #include <vespa/searchlib/features/max_reduce_prod_join_feature.h> #include <vespa/searchlib/attribute/attribute.h> using search::feature_t; using namespace search::fef; using namespace search::fef::test; using namespace search::features; using search::AttributeFactory; using search::IntegerAttribute; using CollectionType = FieldInfo::CollectionType; typedef search::attribute::Config AVC; typedef search::attribute::BasicType AVBT; typedef search::attribute::CollectionType AVCT; typedef search::AttributeVector::SP AttributePtr; typedef FtTestApp FTA; struct SetupFixture { InternalMaxReduceProdJoinBlueprint blueprint; IndexEnvironment indexEnv; SetupFixture(const vespalib::string &attr) : blueprint(), indexEnv() { FieldInfo attr_info(FieldType::ATTRIBUTE, CollectionType::ARRAY, attr, 0); indexEnv.getFields().push_back(attr_info); } }; TEST_F("require that blueprint can be created", SetupFixture("attribute(foo)")) { EXPECT_TRUE(FTA::assertCreateInstance(f.blueprint, "internalMaxReduceProdJoin")); } TEST_F("require that setup fails if source spec is invalid", SetupFixture("attribute(foo)")) { FTA::FT_SETUP_FAIL(f.blueprint, f.indexEnv, StringList().add("source(foo)")); } TEST_F("require that setup fails if attribute does not exist", SetupFixture("attribute(foo)")) { FTA::FT_SETUP_FAIL(f.blueprint, f.indexEnv, StringList().add("attribute(bar)").add("query(baz)")); } TEST_F("require that setup succeeds with attribute and query parameters", SetupFixture("attribute(foo)")) { FTA::FT_SETUP_OK(f.blueprint, f.indexEnv, StringList().add("attribute(foo)").add("query(bar)"), StringList(), StringList().add("scalar")); } struct ExecFixture { BlueprintFactory factory; FtFeatureTest test; ExecFixture(const vespalib::string &feature) : factory(), test(factory, feature) { factory.addPrototype(std::make_shared<InternalMaxReduceProdJoinBlueprint>()); setupAttributeVectors(); setupQueryEnvironment(); ASSERT_TRUE(test.setup()); } void setupAttributeVectors() { vespalib::string attrIntArray = "attribute(intarray)"; vespalib::string attrLongArray = "attribute(longarray)"; test.getIndexEnv().getBuilder().addField(FieldType::ATTRIBUTE, CollectionType::ARRAY, attrLongArray); test.getIndexEnv().getBuilder().addField(FieldType::ATTRIBUTE, CollectionType::ARRAY, attrIntArray); std::vector<AttributePtr> attrs; attrs.push_back(AttributeFactory::createAttribute(attrLongArray, AVC(AVBT::INT64, AVCT::ARRAY))); attrs.push_back(AttributeFactory::createAttribute(attrIntArray, AVC(AVBT::INT32, AVCT::ARRAY))); for (const auto &attr : attrs) { attr->addReservedDoc(); attr->addDocs(1); test.getIndexEnv().getAttributeMap().add(attr); } IntegerAttribute *longArray = static_cast<IntegerAttribute *>(attrs[0].get()); longArray->append(1, 1111, 0); longArray->append(1, 2222, 0); longArray->append(1, 78, 0); IntegerAttribute *intArray = static_cast<IntegerAttribute *>(attrs[1].get()); intArray->append(1, 78, 0); intArray->append(1, 1111, 0); for (const auto &attr : attrs) { attr->commit(); } } void setupQueryEnvironment() { test.getQueryEnv().getProperties().add("query(wset)", "{1111:1234, 2222:2245}"); test.getQueryEnv().getProperties().add("query(wsetnomatch)", "{1:1000, 2:2000}"); test.getQueryEnv().getProperties().add("query(array)", "[1111,2222]"); } bool evaluatesTo(feature_t expected) { return test.execute(expected); } }; TEST_F("require that executor returns correct result for long array", ExecFixture("internalMaxReduceProdJoin(attribute(longarray),query(wset))")) { EXPECT_TRUE(f.evaluatesTo(2245)); } TEST_F("require that executor returns correct result for int array", ExecFixture("internalMaxReduceProdJoin(attribute(intarray),query(wset))")) { EXPECT_TRUE(f.evaluatesTo(1234)); } TEST_F("require that executor returns 0 if no items match", ExecFixture("internalMaxReduceProdJoin(attribute(longarray),query(wsetnomatch))")) { EXPECT_TRUE(f.evaluatesTo(0.0)); } TEST_F("require that executor return 0 if query is not a weighted set", ExecFixture("internalMaxReduceProdJoin(attribute(longarray),query(array))")) { EXPECT_TRUE(f.evaluatesTo(0.0)); } TEST_MAIN() { TEST_RUN_ALL(); } <|endoftext|>
<commit_before>#include <fstream> #include "gtest.h" #include <common_types.hpp> #include <cell.hpp> #include <fvm_multicell.hpp> #include <util/rangeutil.hpp> #include "../test_util.hpp" #include "../test_common_cells.hpp" TEST(fvm_multi, cable) { using namespace nest::mc; nest::mc::cell cell=make_cell_ball_and_3sticks(); using fvm_cell = fvm::fvm_multicell<double, cell_lid_type>; std::vector<fvm_cell::target_handle> targets; std::vector<fvm_cell::detector_handle> detectors; std::vector<fvm_cell::probe_handle> probes; fvm_cell fvcell; fvcell.initialize(util::singleton_view(cell), detectors, targets, probes); auto& J = fvcell.jacobian(); // 1 (soma) + 3 (dendritic segments) × 4 compartments EXPECT_EQ(cell.num_compartments(), 13u); // assert that the matrix has one row for each compartment EXPECT_EQ(J.size(), cell.num_compartments()); fvcell.setup_matrix(0.02); // assert that the number of cv areas is the same as the matrix size // i.e. both should equal the number of compartments EXPECT_EQ(fvcell.cv_areas().size(), J.size()); } TEST(fvm_multi, init) { using namespace nest::mc; nest::mc::cell cell = make_cell_ball_and_stick(); const auto m = cell.model(); EXPECT_EQ(m.tree.num_segments(), 2u); auto& soma_hh = cell.soma()->mechanism("hh"); soma_hh.set("gnabar", 0.12); soma_hh.set("gkbar", 0.036); soma_hh.set("gl", 0.0003); soma_hh.set("el", -54.3); // check that parameter values were set correctly EXPECT_EQ(cell.soma()->mechanism("hh").get("gnabar").value, 0.12); EXPECT_EQ(cell.soma()->mechanism("hh").get("gkbar").value, 0.036); EXPECT_EQ(cell.soma()->mechanism("hh").get("gl").value, 0.0003); EXPECT_EQ(cell.soma()->mechanism("hh").get("el").value, -54.3); cell.segment(1)->set_compartments(10); using fvm_cell = fvm::fvm_multicell<double, cell_lid_type>; std::vector<fvm_cell::target_handle> targets; std::vector<fvm_cell::detector_handle> detectors; std::vector<fvm_cell::probe_handle> probes; fvm_cell fvcell; fvcell.initialize(util::singleton_view(cell), detectors, targets, probes); auto& J = fvcell.jacobian(); EXPECT_EQ(J.size(), 11u); fvcell.setup_matrix(0.01); } TEST(fvm_multi, multi_init) { using namespace nest::mc; nest::mc::cell cells[] = { make_cell_ball_and_stick(), make_cell_ball_and_3sticks() }; EXPECT_EQ(cells[0].num_segments(), 2u); EXPECT_EQ(cells[0].segment(1)->num_compartments(), 4u); EXPECT_EQ(cells[1].num_segments(), 4u); EXPECT_EQ(cells[1].segment(1)->num_compartments(), 4u); EXPECT_EQ(cells[1].segment(2)->num_compartments(), 4u); EXPECT_EQ(cells[1].segment(3)->num_compartments(), 4u); cells[0].add_synapse({1, 0.4}, parameter_list("expsyn")); cells[0].add_synapse({1, 0.4}, parameter_list("expsyn")); cells[1].add_synapse({2, 0.4}, parameter_list("exp2syn")); cells[1].add_synapse({3, 0.4}, parameter_list("expsyn")); cells[1].add_detector({0, 0}, 3.3); using fvm_cell = fvm::fvm_multicell<double, cell_lid_type>; std::vector<fvm_cell::target_handle> targets(4); std::vector<fvm_cell::detector_handle> detectors(1); std::vector<fvm_cell::probe_handle> probes; fvm_cell fvcell; fvcell.initialize(cells, detectors, targets, probes); auto& J = fvcell.jacobian(); EXPECT_EQ(J.size(), 5u+13u); // check indices in instantiated mechanisms for (const auto& mech: fvcell.mechanisms()) { if (mech->name()=="hh") { // HH on somas of two cells, with group compartment indices // 0 and 5. ASSERT_EQ(mech->node_index().size(), 2u); EXPECT_EQ(mech->node_index()[0], 0u); EXPECT_EQ(mech->node_index()[1], 5u); } if (mech->name()=="expsyn") { // Three expsyn synapses, two in second compartment // of dendrite segment of first cell, one in second compartment // of last segment of second cell. ASSERT_EQ(mech->node_index().size(), 3u); EXPECT_EQ(mech->node_index()[0], 2u); EXPECT_EQ(mech->node_index()[1], 2u); EXPECT_EQ(mech->node_index()[2], 15u); } if (mech->name()=="exp2syn") { // One exp2syn synapse, in second compartment // of penultimate segment of second cell. ASSERT_EQ(mech->node_index().size(), 1u); EXPECT_EQ(mech->node_index()[0], 11u); } } fvcell.setup_matrix(0.01); } // test that stimuli are added correctly TEST(fvm_multi, stimulus) { using namespace nest::mc; using util::singleton_view; // the default ball and stick has one stimulus at the terminal end of the dendrite auto cell = make_cell_ball_and_stick(); // ... so add a second at the soma to make things more interesting cell.add_stimulus({0,0.5}, {1., 2., 0.1}); // now we have two stims : // // |stim0 |stim1 // ----------------------- // delay | 5 | 1 // duration | 80 | 2 // amplitude | 0.3 | 0.1 // compmnt | 4 | 0 using fvm_cell = fvm::fvm_multicell<double, cell_lid_type>; std::vector<fvm_cell::target_handle> targets; std::vector<fvm_cell::detector_handle> detectors; std::vector<fvm_cell::probe_handle> probes; fvm_cell fvcell; fvcell.initialize(singleton_view(cell), detectors, targets, probes); auto& stim = fvcell.stimuli(); EXPECT_EQ(stim.size(), 2u); EXPECT_EQ(stim[0].first, 4u); EXPECT_EQ(stim[1].first, 0u); EXPECT_EQ(stim[0].second.delay(), 5.); EXPECT_EQ(stim[1].second.delay(), 1.); EXPECT_EQ(stim[0].second.duration(), 80.); EXPECT_EQ(stim[1].second.duration(), 2.); EXPECT_EQ(stim[0].second.amplitude(), 0.3); EXPECT_EQ(stim[1].second.amplitude(), 0.1); } // test that mechanism indexes are computed correctly TEST(fvm_multi, mechanism_indexes) { using namespace nest::mc; // create a cell with 4 sements: // a soma with a branching dendrite // - hh on soma and first branch of dendrite (segs 0 and 2) // - pas on main dendrite and second branch (segs 1 and 3) // // / // pas // / // hh---pas--. // \. // hh // \. cell c; auto soma = c.add_soma(12.6157/2.0); soma->add_mechanism(hh_parameters()); // add dendrite of length 200 um and diameter 1 um with passive channel c.add_cable(0, segmentKind::dendrite, 0.5, 0.5, 100); c.add_cable(1, segmentKind::dendrite, 0.5, 0.5, 100); c.add_cable(1, segmentKind::dendrite, 0.5, 0.5, 100); auto& segs = c.segments(); segs[1]->add_mechanism(pas_parameters()); segs[2]->add_mechanism(hh_parameters()); segs[3]->add_mechanism(pas_parameters()); for (auto& seg: segs) { if (seg->is_dendrite()) { seg->mechanism("membrane").set("r_L", 100); seg->set_compartments(4); } } // generate the lowered fvm cell using fvm_cell = fvm::fvm_multicell<double, cell_lid_type>; std::vector<fvm_cell::target_handle> targets; std::vector<fvm_cell::detector_handle> detectors; std::vector<fvm_cell::probe_handle> probes; fvm_cell fvcell; fvcell.initialize(util::singleton_view(c), detectors, targets, probes); // make vectors with the expected CV indexes for each mechanism std::vector<unsigned> hh_index = {0u, 4u, 5u, 6u, 7u, 8u}; std::vector<unsigned> pas_index = {0u, 1u, 2u, 3u, 4u, 9u, 10u, 11u, 12u}; // iterate over mechanisms and test whether they were assigned to the correct CVs // TODO : this fails because we do not handle CVs at branching points (including soma) correctly for(auto& mech : fvcell.mechanisms()) { auto const& ni = mech->node_index(); if(mech->name()=="hh") { EXPECT_EQ(ni.size(), hh_index.size()); // only check index by index if size of index arrays match if(ni.size()==hh_index.size()) { for(auto i : util::make_span(0u, ni.size())) EXPECT_EQ(ni[i], hh_index[i]); } } else if(mech->name()=="pas") { EXPECT_EQ(ni.size(), pas_index.size()); // only check index by index if size of index arrays match if(ni.size()==pas_index.size()) { for(auto i : util::make_span(0u, ni.size())) EXPECT_EQ(ni[i], pas_index[i]); } } } } <commit_msg>address review comments for PR #22<commit_after>#include <fstream> #include "gtest.h" #include <common_types.hpp> #include <cell.hpp> #include <fvm_multicell.hpp> #include <util/rangeutil.hpp> #include "../test_util.hpp" #include "../test_common_cells.hpp" TEST(fvm_multi, cable) { using namespace nest::mc; nest::mc::cell cell=make_cell_ball_and_3sticks(); using fvm_cell = fvm::fvm_multicell<double, cell_lid_type>; std::vector<fvm_cell::target_handle> targets; std::vector<fvm_cell::detector_handle> detectors; std::vector<fvm_cell::probe_handle> probes; fvm_cell fvcell; fvcell.initialize(util::singleton_view(cell), detectors, targets, probes); auto& J = fvcell.jacobian(); // 1 (soma) + 3 (dendritic segments) × 4 compartments EXPECT_EQ(cell.num_compartments(), 13u); // assert that the matrix has one row for each compartment EXPECT_EQ(J.size(), cell.num_compartments()); fvcell.setup_matrix(0.02); // assert that the number of cv areas is the same as the matrix size // i.e. both should equal the number of compartments EXPECT_EQ(fvcell.cv_areas().size(), J.size()); } TEST(fvm_multi, init) { using namespace nest::mc; nest::mc::cell cell = make_cell_ball_and_stick(); const auto m = cell.model(); EXPECT_EQ(m.tree.num_segments(), 2u); auto& soma_hh = cell.soma()->mechanism("hh"); soma_hh.set("gnabar", 0.12); soma_hh.set("gkbar", 0.036); soma_hh.set("gl", 0.0003); soma_hh.set("el", -54.3); // check that parameter values were set correctly EXPECT_EQ(cell.soma()->mechanism("hh").get("gnabar").value, 0.12); EXPECT_EQ(cell.soma()->mechanism("hh").get("gkbar").value, 0.036); EXPECT_EQ(cell.soma()->mechanism("hh").get("gl").value, 0.0003); EXPECT_EQ(cell.soma()->mechanism("hh").get("el").value, -54.3); cell.segment(1)->set_compartments(10); using fvm_cell = fvm::fvm_multicell<double, cell_lid_type>; std::vector<fvm_cell::target_handle> targets; std::vector<fvm_cell::detector_handle> detectors; std::vector<fvm_cell::probe_handle> probes; fvm_cell fvcell; fvcell.initialize(util::singleton_view(cell), detectors, targets, probes); auto& J = fvcell.jacobian(); EXPECT_EQ(J.size(), 11u); fvcell.setup_matrix(0.01); } TEST(fvm_multi, multi_init) { using namespace nest::mc; nest::mc::cell cells[] = { make_cell_ball_and_stick(), make_cell_ball_and_3sticks() }; EXPECT_EQ(cells[0].num_segments(), 2u); EXPECT_EQ(cells[0].segment(1)->num_compartments(), 4u); EXPECT_EQ(cells[1].num_segments(), 4u); EXPECT_EQ(cells[1].segment(1)->num_compartments(), 4u); EXPECT_EQ(cells[1].segment(2)->num_compartments(), 4u); EXPECT_EQ(cells[1].segment(3)->num_compartments(), 4u); cells[0].add_synapse({1, 0.4}, parameter_list("expsyn")); cells[0].add_synapse({1, 0.4}, parameter_list("expsyn")); cells[1].add_synapse({2, 0.4}, parameter_list("exp2syn")); cells[1].add_synapse({3, 0.4}, parameter_list("expsyn")); cells[1].add_detector({0, 0}, 3.3); using fvm_cell = fvm::fvm_multicell<double, cell_lid_type>; std::vector<fvm_cell::target_handle> targets(4); std::vector<fvm_cell::detector_handle> detectors(1); std::vector<fvm_cell::probe_handle> probes; fvm_cell fvcell; fvcell.initialize(cells, detectors, targets, probes); auto& J = fvcell.jacobian(); EXPECT_EQ(J.size(), 5u+13u); // check indices in instantiated mechanisms for (const auto& mech: fvcell.mechanisms()) { if (mech->name()=="hh") { // HH on somas of two cells, with group compartment indices // 0 and 5. ASSERT_EQ(mech->node_index().size(), 2u); EXPECT_EQ(mech->node_index()[0], 0u); EXPECT_EQ(mech->node_index()[1], 5u); } if (mech->name()=="expsyn") { // Three expsyn synapses, two in second compartment // of dendrite segment of first cell, one in second compartment // of last segment of second cell. ASSERT_EQ(mech->node_index().size(), 3u); EXPECT_EQ(mech->node_index()[0], 2u); EXPECT_EQ(mech->node_index()[1], 2u); EXPECT_EQ(mech->node_index()[2], 15u); } if (mech->name()=="exp2syn") { // One exp2syn synapse, in second compartment // of penultimate segment of second cell. ASSERT_EQ(mech->node_index().size(), 1u); EXPECT_EQ(mech->node_index()[0], 11u); } } fvcell.setup_matrix(0.01); } // test that stimuli are added correctly TEST(fvm_multi, stimulus) { using namespace nest::mc; using util::singleton_view; // the default ball and stick has one stimulus at the terminal end of the dendrite auto cell = make_cell_ball_and_stick(); // ... so add a second at the soma to make things more interesting cell.add_stimulus({0,0.5}, {1., 2., 0.1}); // now we have two stims : // // |stim0 |stim1 // ----------------------- // delay | 5 | 1 // duration | 80 | 2 // amplitude | 0.3 | 0.1 // compmnt | 4 | 0 using fvm_cell = fvm::fvm_multicell<double, cell_lid_type>; std::vector<fvm_cell::target_handle> targets; std::vector<fvm_cell::detector_handle> detectors; std::vector<fvm_cell::probe_handle> probes; fvm_cell fvcell; fvcell.initialize(singleton_view(cell), detectors, targets, probes); auto& stim = fvcell.stimuli(); EXPECT_EQ(stim.size(), 2u); EXPECT_EQ(stim[0].first, 4u); EXPECT_EQ(stim[1].first, 0u); EXPECT_EQ(stim[0].second.delay(), 5.); EXPECT_EQ(stim[1].second.delay(), 1.); EXPECT_EQ(stim[0].second.duration(), 80.); EXPECT_EQ(stim[1].second.duration(), 2.); EXPECT_EQ(stim[0].second.amplitude(), 0.3); EXPECT_EQ(stim[1].second.amplitude(), 0.1); } // test that mechanism indexes are computed correctly TEST(fvm_multi, mechanism_indexes) { using namespace nest::mc; // create a cell with 4 sements: // a soma with a branching dendrite // - hh on soma and first branch of dendrite (segs 0 and 2) // - pas on main dendrite and second branch (segs 1 and 3) // // / // pas // / // hh---pas--. // \. // hh // \. cell c; auto soma = c.add_soma(12.6157/2.0); soma->add_mechanism(hh_parameters()); // add dendrite of length 200 um and diameter 1 um with passive channel c.add_cable(0, segmentKind::dendrite, 0.5, 0.5, 100); c.add_cable(1, segmentKind::dendrite, 0.5, 0.5, 100); c.add_cable(1, segmentKind::dendrite, 0.5, 0.5, 100); auto& segs = c.segments(); segs[1]->add_mechanism(pas_parameters()); segs[2]->add_mechanism(hh_parameters()); segs[3]->add_mechanism(pas_parameters()); for (auto& seg: segs) { if (seg->is_dendrite()) { seg->mechanism("membrane").set("r_L", 100); seg->set_compartments(4); } } // generate the lowered fvm cell using fvm_cell = fvm::fvm_multicell<double, cell_lid_type>; std::vector<fvm_cell::target_handle> targets; std::vector<fvm_cell::detector_handle> detectors; std::vector<fvm_cell::probe_handle> probes; fvm_cell fvcell; fvcell.initialize(util::singleton_view(c), detectors, targets, probes); // make vectors with the expected CV indexes for each mechanism std::vector<unsigned> hh_index = {0u, 4u, 5u, 6u, 7u, 8u}; std::vector<unsigned> pas_index = {0u, 1u, 2u, 3u, 4u, 9u, 10u, 11u, 12u}; // iterate over mechanisms and test whether they were assigned to the correct CVs // TODO : this fails because we do not handle CVs at branching points (including soma) correctly for(auto& mech : fvcell.mechanisms()) { auto const& n = mech->node_index(); std::vector<unsigned> ni(n.begin(), n.end()); if(mech->name()=="hh") { EXPECT_EQ(ni, hh_index); } else if(mech->name()=="pas") { EXPECT_EQ(ni, pas_index); } } } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkOverlayController.h" #include "QmitkRenderWindow.h" #include "QmitkOverlay.h" #include <QHBoxLayout> #include <QVBoxLayout> #include <algorithm> QmitkOverlayController::QmitkOverlayController( QmitkRenderWindow* rw, mitk::PropertyList* pl ) : QObject(), m_RenderWindow( rw ), m_PropertyList( pl ) { if ( m_RenderWindow == NULL ) { MITK_ERROR << "invalid QmitkRenderWindow"; return; } connect( rw, SIGNAL( moved() ), this, SLOT( AdjustOverlayPosition() ) ); this->InitializeOverlayLayout(); this->AdjustOverlayPosition(); this->SetOverlayVisibility( true ); if ( m_PropertyList.IsNull() ) m_PropertyList = mitk::PropertyList::New(); } QmitkOverlayController::~QmitkOverlayController() { } void QmitkOverlayController::InitializeOverlayLayout() { // setup widget for each position this->InitializeWidget( QmitkOverlay::top_Left ); this->InitializeWidget( QmitkOverlay::top_Center ); this->InitializeWidget( QmitkOverlay::top_Right ); this->InitializeWidget( QmitkOverlay::middle_Left ); this->InitializeWidget( QmitkOverlay::middle_Right ); this->InitializeWidget( QmitkOverlay::bottom_Left ); this->InitializeWidget( QmitkOverlay::bottom_Center ); this->InitializeWidget( QmitkOverlay::bottom_Right ); } void QmitkOverlayController::InitializeWidget( QmitkOverlay::DisplayPosition pos ) { // create a new QWidget as Tool & FramelessWindowHint m_PositionedOverlays[ pos ] = new QWidget( m_RenderWindow, Qt::Tool | Qt::FramelessWindowHint ); // autoFillBackGround(false) and WA_TranslucentBackground = true are needed to have a translucent background // transparency does NOT work under Win-XP 32-Bit --> paint black background #if !defined(_WIN32) || defined(_WIN64) m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_TranslucentBackground, true ); #else m_PositionedOverlays[ pos ]->setStyleSheet( "QWidget { background: black }" ); m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_TranslucentBackground, false ); #endif // X11 specific attributes m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_X11NetWmWindowTypeUtility, true ); // mac-specific attributes: // making sure overlays are even visible if RenderWindow does not have the focus (not default for Qt::Tool on mac) m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_MacAlwaysShowToolWindow, true ); // testing something m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_MacShowFocusRect, false ); // overlays should not get the focus m_PositionedOverlays[ pos ]->setFocusPolicy( Qt::NoFocus ); // setting the color of the background to transparent - not sure it's needed after the attributes have been set above QPalette p = QPalette(); p.setColor( QPalette::Window, Qt::transparent ); m_PositionedOverlays[ pos ]->setPalette( p ); // setting position-specific properties switch ( pos ) { case QmitkOverlay::top_Left : { // adding left-aligned top-to-bottom layout QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::TopToBottom ); layout->setAlignment( Qt::AlignLeft ); m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 ); break; } case QmitkOverlay::top_Center : { // adding center-aligned top-to-bottom layout QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::TopToBottom ); layout->setAlignment( Qt::AlignCenter ); layout->setAlignment( Qt::AlignLeft ); m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 ); break; } case QmitkOverlay::top_Right : { // adding right-aligned top-to-bottom layout QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::TopToBottom ); layout->setAlignment( Qt::AlignRight ); m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 ); break; } case QmitkOverlay::middle_Left : { // adding left-aligned left-to-right layout QHBoxLayout* layout = new QHBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::LeftToRight ); layout->setAlignment( Qt::AlignLeft ); layout->setSpacing( 3 ); break; } case QmitkOverlay::middle_Right : { // adding right-aligned right-to-left layout QHBoxLayout* layout = new QHBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::RightToLeft ); layout->setAlignment( Qt::AlignRight ); layout->setSpacing( 3 ); break; } case QmitkOverlay::bottom_Left : { // adding left-aligned bottom-to-top layout QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::BottomToTop ); layout->setAlignment( Qt::AlignLeft ); m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 ); break; } case QmitkOverlay::bottom_Center : { QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::BottomToTop ); layout->setAlignment( Qt::AlignCenter ); m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 ); break; } case QmitkOverlay::bottom_Right : { QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::BottomToTop ); layout->setAlignment( Qt::AlignRight ); m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 ); break; } } } void QmitkOverlayController::AdjustOverlayPosition() { QWidget* widget; QPoint pos; // setting position of top-left overlay-container pos = m_RenderWindow->mapToGlobal( QPoint(0,0) ); m_PositionedOverlays[ QmitkOverlay::top_Left ]->move( pos.x(), pos.y() ); // setting position of top-center overlay-container widget = m_PositionedOverlays[ QmitkOverlay::top_Center ]; pos = m_RenderWindow->mapToGlobal( QPoint( m_RenderWindow->size().width()/2, 0 ) ) ; widget->move( pos.x() - widget->size().width()/2, pos.y() ); // setting position of top-right overlay-container widget = m_PositionedOverlays[ QmitkOverlay::top_Right ]; pos = m_RenderWindow->mapToGlobal( QPoint( m_RenderWindow->size().width(), 0 ) ) ; widget->move( pos.x() - widget->size().width(), pos.y() ); // setting position of middle-left overlay-container widget = m_PositionedOverlays[ QmitkOverlay::middle_Left ]; pos = m_RenderWindow->mapToGlobal( QPoint( 0, m_RenderWindow->size().height()/2 ) ) ; widget->move( pos.x(), pos.y() - widget->size().height()/2 ); // setting position of middle-right overlay-container widget = m_PositionedOverlays[ QmitkOverlay::middle_Right ]; pos = m_RenderWindow->mapToGlobal( QPoint( m_RenderWindow->size().width(), m_RenderWindow->size().height()/2 ) ) ; widget->move( pos.x() - widget->size().width(), pos.y() - widget->size().height()/2 ); // setting position of bottom-left overlay-container widget = m_PositionedOverlays[ QmitkOverlay::bottom_Left ]; pos = m_RenderWindow->mapToGlobal( QPoint( 0, m_RenderWindow->size().height() ) ) ; widget->move( pos.x(), pos.y() - widget->size().height() ); // setting position of bottom-center overlay-container widget = m_PositionedOverlays[ QmitkOverlay::bottom_Center ]; pos = m_RenderWindow->mapToGlobal( QPoint( m_RenderWindow->size().width()/2, m_RenderWindow->size().height() ) ) ; widget->move( pos.x() - widget->size().width()/2, pos.y() - widget->size().height() ); // setting position of bottom-right overlay-container widget = m_PositionedOverlays[ QmitkOverlay::bottom_Right ]; pos = m_RenderWindow->mapToGlobal( QPoint( m_RenderWindow->size().width(), m_RenderWindow->size().height() ) ) ; widget->move( pos.x() - widget->size().width(), pos.y() - widget->size().height() ); } void QmitkOverlayController::SetOverlayVisibility( bool visible ) { OverlayPositionMap::iterator overlayIter; for ( overlayIter=m_PositionedOverlays.begin(); overlayIter!=m_PositionedOverlays.end(); overlayIter++ ) { if ( visible ) { (overlayIter->second)->show(); } else { (overlayIter->second)->hide(); } } } void QmitkOverlayController::AddOverlay( QmitkOverlay* overlay ) { // if no renderwindow has been set, it's not possible to add overlays... if ( m_RenderWindow == NULL ) { MITK_ERROR << "invalid QmitkRenderWindow"; return; } if ( overlay != NULL ) { // get desired position and layer of the overlay QmitkOverlay::DisplayPosition pos = overlay->GetPosition(); // concatenate local propertyList and propertyList of the RenderingManager // local properties have priority as they are not overwritten if preset in both m_PropertyList->ConcatenatePropertyList( m_RenderWindow->GetRenderer()->GetRenderingManager()->GetPropertyList(), false ); // add the overlay to the OverlayContainer in the RenderWindow ... overlay->GetWidget()->setParent( m_PositionedOverlays[ pos ] ); // ... and set it up with the correct properties this->UpdateOverlayData( overlay ); // add overlay to list of all overlays and correctly put it into the layering m_AllOverlays.push_back( overlay ); this->RestackOverlays( pos ); // make sure the widget containing the added overlay is shown ... m_PositionedOverlays[ pos ]->show(); // ... and reset the position of the widgets this->AdjustOverlayPosition(); } } void QmitkOverlayController::UpdateOverlayData( QmitkOverlay* overlay ) { overlay->GenerateData( m_PropertyList ); } void QmitkOverlayController::RemoveOverlay( QmitkOverlay* overlay ) { if ( overlay != NULL ) { // get desired position and layer of the overlay QmitkOverlay::DisplayPosition pos = overlay->GetPosition(); OverlayVector::iterator iter = std::find( m_AllOverlays.begin(), m_AllOverlays.end(), overlay ); if ( iter != m_AllOverlays.end() ) { m_AllOverlays.erase( iter ); overlay->GetWidget()->setParent( NULL ); overlay->GetWidget()->hide(); if ( m_PositionedOverlays[ pos ]->layout()->isEmpty() ) { m_PositionedOverlays[ pos ]->hide(); } else { this->RestackOverlays( pos ); // reset the position of the widgets this->AdjustOverlayPosition(); } } overlay->deleteLater(); } } void QmitkOverlayController::AlignOverlays() { //OverlayVector::iterator overlayIter; //for ( overlayIter=m_AllOverlays.begin(); overlayIter!=m_AllOverlays.end(); overlayIter++ ) //{ // int stackLayer = dynamic_cast<QBoxLayout*>( m_PositionedOverlays[ (*overlayIter)->GetPosition() ]->layout() )->isEmpty() ? 0 : layer; // dynamic_cast<QBoxLayout*>( m_PositionedOverlays[ (*overlayIter)->GetPosition() ]->layout() )->addWidget( (*overlayIter)->GetWidget(), stackLayer, Qt::AlignLeft ); //} } void QmitkOverlayController::RestackOverlays( QmitkOverlay::DisplayPosition pos ) { OverlayVector::iterator overlayIter; QBoxLayout* layout = dynamic_cast<QBoxLayout*>( m_PositionedOverlays[ pos ]->layout() ); std::sort( m_AllOverlays.begin(), m_AllOverlays.end() ); for ( overlayIter=m_AllOverlays.begin(); overlayIter!=m_AllOverlays.end(); overlayIter++ ) { // do nothing if the overlay is not in the right position if ( (*overlayIter)->GetPosition() != pos ) { continue; } // determine the desired stacking layer // if the overlay-container is empty, simply append the overlay to the list // if it's not empty, use the layer of the overlay unsigned int layer = (*overlayIter)->GetLayer(); int stackLayer = 0; if ( !layout->isEmpty() ) { stackLayer = layer; } switch ( pos ) { // same alignment for all lefts, ... case QmitkOverlay::top_Left : {} case QmitkOverlay::middle_Left : {} case QmitkOverlay::bottom_Left : { layout->insertWidget( stackLayer, (*overlayIter)->GetWidget(), 0, Qt::AlignLeft ); break; } // ... for all centers, ... case QmitkOverlay::top_Center : {} case QmitkOverlay::bottom_Center : { layout->insertWidget( stackLayer, (*overlayIter)->GetWidget(), 0, Qt::AlignCenter ); break; } // ... and for all rights case QmitkOverlay::top_Right : {} case QmitkOverlay::middle_Right : {} case QmitkOverlay::bottom_Right : { layout->insertWidget( stackLayer, (*overlayIter)->GetWidget(), 0, Qt::AlignRight ); break; } } } } void QmitkOverlayController::UpdateAllOverlays() { foreach( QmitkOverlay* overlay, m_AllOverlays ) { this->UpdateOverlayData( overlay ); } }<commit_msg>no longer call show in the AddOverlay method<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkOverlayController.h" #include "QmitkRenderWindow.h" #include "QmitkOverlay.h" #include <QHBoxLayout> #include <QVBoxLayout> #include <algorithm> QmitkOverlayController::QmitkOverlayController( QmitkRenderWindow* rw, mitk::PropertyList* pl ) : QObject(), m_RenderWindow( rw ), m_PropertyList( pl ) { if ( m_RenderWindow == NULL ) { MITK_ERROR << "invalid QmitkRenderWindow"; return; } connect( rw, SIGNAL( moved() ), this, SLOT( AdjustOverlayPosition() ) ); this->InitializeOverlayLayout(); this->AdjustOverlayPosition(); this->SetOverlayVisibility( true ); if ( m_PropertyList.IsNull() ) m_PropertyList = mitk::PropertyList::New(); } QmitkOverlayController::~QmitkOverlayController() { } void QmitkOverlayController::InitializeOverlayLayout() { // setup widget for each position this->InitializeWidget( QmitkOverlay::top_Left ); this->InitializeWidget( QmitkOverlay::top_Center ); this->InitializeWidget( QmitkOverlay::top_Right ); this->InitializeWidget( QmitkOverlay::middle_Left ); this->InitializeWidget( QmitkOverlay::middle_Right ); this->InitializeWidget( QmitkOverlay::bottom_Left ); this->InitializeWidget( QmitkOverlay::bottom_Center ); this->InitializeWidget( QmitkOverlay::bottom_Right ); } void QmitkOverlayController::InitializeWidget( QmitkOverlay::DisplayPosition pos ) { // create a new QWidget as Tool & FramelessWindowHint m_PositionedOverlays[ pos ] = new QWidget( m_RenderWindow, Qt::Tool | Qt::FramelessWindowHint ); // autoFillBackGround(false) and WA_TranslucentBackground = true are needed to have a translucent background // transparency does NOT work under Win-XP 32-Bit --> paint black background #if !defined(_WIN32) || defined(_WIN64) m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_TranslucentBackground, true ); #else m_PositionedOverlays[ pos ]->setStyleSheet( "QWidget { background: black }" ); m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_TranslucentBackground, false ); #endif // X11 specific attributes m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_X11NetWmWindowTypeUtility, true ); // mac-specific attributes: // making sure overlays are even visible if RenderWindow does not have the focus (not default for Qt::Tool on mac) m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_MacAlwaysShowToolWindow, true ); // testing something m_PositionedOverlays[ pos ]->setAttribute( Qt::WA_MacShowFocusRect, false ); // overlays should not get the focus m_PositionedOverlays[ pos ]->setFocusPolicy( Qt::NoFocus ); // setting the color of the background to transparent - not sure it's needed after the attributes have been set above QPalette p = QPalette(); p.setColor( QPalette::Window, Qt::transparent ); m_PositionedOverlays[ pos ]->setPalette( p ); // setting position-specific properties switch ( pos ) { case QmitkOverlay::top_Left : { // adding left-aligned top-to-bottom layout QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::TopToBottom ); layout->setAlignment( Qt::AlignLeft ); m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 ); break; } case QmitkOverlay::top_Center : { // adding center-aligned top-to-bottom layout QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::TopToBottom ); layout->setAlignment( Qt::AlignCenter ); layout->setAlignment( Qt::AlignLeft ); m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 ); break; } case QmitkOverlay::top_Right : { // adding right-aligned top-to-bottom layout QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::TopToBottom ); layout->setAlignment( Qt::AlignRight ); m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 ); break; } case QmitkOverlay::middle_Left : { // adding left-aligned left-to-right layout QHBoxLayout* layout = new QHBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::LeftToRight ); layout->setAlignment( Qt::AlignLeft ); layout->setSpacing( 3 ); break; } case QmitkOverlay::middle_Right : { // adding right-aligned right-to-left layout QHBoxLayout* layout = new QHBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::RightToLeft ); layout->setAlignment( Qt::AlignRight ); layout->setSpacing( 3 ); break; } case QmitkOverlay::bottom_Left : { // adding left-aligned bottom-to-top layout QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::BottomToTop ); layout->setAlignment( Qt::AlignLeft ); m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 ); break; } case QmitkOverlay::bottom_Center : { QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::BottomToTop ); layout->setAlignment( Qt::AlignCenter ); m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 ); break; } case QmitkOverlay::bottom_Right : { QVBoxLayout* layout = new QVBoxLayout( m_PositionedOverlays[ pos ] ); layout->setDirection( QBoxLayout::BottomToTop ); layout->setAlignment( Qt::AlignRight ); m_PositionedOverlays[ pos ]->layout()->setSpacing( 0 ); break; } } } void QmitkOverlayController::AdjustOverlayPosition() { QWidget* widget; QPoint pos; // setting position of top-left overlay-container pos = m_RenderWindow->mapToGlobal( QPoint(0,0) ); m_PositionedOverlays[ QmitkOverlay::top_Left ]->move( pos.x(), pos.y() ); // setting position of top-center overlay-container widget = m_PositionedOverlays[ QmitkOverlay::top_Center ]; pos = m_RenderWindow->mapToGlobal( QPoint( m_RenderWindow->size().width()/2, 0 ) ) ; widget->move( pos.x() - widget->size().width()/2, pos.y() ); // setting position of top-right overlay-container widget = m_PositionedOverlays[ QmitkOverlay::top_Right ]; pos = m_RenderWindow->mapToGlobal( QPoint( m_RenderWindow->size().width(), 0 ) ) ; widget->move( pos.x() - widget->size().width(), pos.y() ); // setting position of middle-left overlay-container widget = m_PositionedOverlays[ QmitkOverlay::middle_Left ]; pos = m_RenderWindow->mapToGlobal( QPoint( 0, m_RenderWindow->size().height()/2 ) ) ; widget->move( pos.x(), pos.y() - widget->size().height()/2 ); // setting position of middle-right overlay-container widget = m_PositionedOverlays[ QmitkOverlay::middle_Right ]; pos = m_RenderWindow->mapToGlobal( QPoint( m_RenderWindow->size().width(), m_RenderWindow->size().height()/2 ) ) ; widget->move( pos.x() - widget->size().width(), pos.y() - widget->size().height()/2 ); // setting position of bottom-left overlay-container widget = m_PositionedOverlays[ QmitkOverlay::bottom_Left ]; pos = m_RenderWindow->mapToGlobal( QPoint( 0, m_RenderWindow->size().height() ) ) ; widget->move( pos.x(), pos.y() - widget->size().height() ); // setting position of bottom-center overlay-container widget = m_PositionedOverlays[ QmitkOverlay::bottom_Center ]; pos = m_RenderWindow->mapToGlobal( QPoint( m_RenderWindow->size().width()/2, m_RenderWindow->size().height() ) ) ; widget->move( pos.x() - widget->size().width()/2, pos.y() - widget->size().height() ); // setting position of bottom-right overlay-container widget = m_PositionedOverlays[ QmitkOverlay::bottom_Right ]; pos = m_RenderWindow->mapToGlobal( QPoint( m_RenderWindow->size().width(), m_RenderWindow->size().height() ) ) ; widget->move( pos.x() - widget->size().width(), pos.y() - widget->size().height() ); } void QmitkOverlayController::SetOverlayVisibility( bool visible ) { OverlayPositionMap::iterator overlayIter; for ( overlayIter=m_PositionedOverlays.begin(); overlayIter!=m_PositionedOverlays.end(); overlayIter++ ) { if ( visible ) { (overlayIter->second)->show(); } else { (overlayIter->second)->hide(); } } } void QmitkOverlayController::AddOverlay( QmitkOverlay* overlay ) { // if no renderwindow has been set, it's not possible to add overlays... if ( m_RenderWindow == NULL ) { MITK_ERROR << "invalid QmitkRenderWindow"; return; } if ( overlay != NULL ) { // get desired position and layer of the overlay QmitkOverlay::DisplayPosition pos = overlay->GetPosition(); // concatenate local propertyList and propertyList of the RenderingManager // local properties have priority as they are not overwritten if preset in both m_PropertyList->ConcatenatePropertyList( m_RenderWindow->GetRenderer()->GetRenderingManager()->GetPropertyList(), false ); // add the overlay to the OverlayContainer in the RenderWindow ... overlay->GetWidget()->setParent( m_PositionedOverlays[ pos ] ); // ... and set it up with the correct properties this->UpdateOverlayData( overlay ); // add overlay to list of all overlays and correctly put it into the layering m_AllOverlays.push_back( overlay ); this->RestackOverlays( pos ); // ... and reset the position of the widgets this->AdjustOverlayPosition(); } } void QmitkOverlayController::UpdateOverlayData( QmitkOverlay* overlay ) { overlay->GenerateData( m_PropertyList ); } void QmitkOverlayController::RemoveOverlay( QmitkOverlay* overlay ) { if ( overlay != NULL ) { // get desired position and layer of the overlay QmitkOverlay::DisplayPosition pos = overlay->GetPosition(); OverlayVector::iterator iter = std::find( m_AllOverlays.begin(), m_AllOverlays.end(), overlay ); if ( iter != m_AllOverlays.end() ) { m_AllOverlays.erase( iter ); overlay->GetWidget()->setParent( NULL ); overlay->GetWidget()->hide(); if ( m_PositionedOverlays[ pos ]->layout()->isEmpty() ) { m_PositionedOverlays[ pos ]->hide(); } else { this->RestackOverlays( pos ); // reset the position of the widgets this->AdjustOverlayPosition(); } } overlay->deleteLater(); } } void QmitkOverlayController::AlignOverlays() { //OverlayVector::iterator overlayIter; //for ( overlayIter=m_AllOverlays.begin(); overlayIter!=m_AllOverlays.end(); overlayIter++ ) //{ // int stackLayer = dynamic_cast<QBoxLayout*>( m_PositionedOverlays[ (*overlayIter)->GetPosition() ]->layout() )->isEmpty() ? 0 : layer; // dynamic_cast<QBoxLayout*>( m_PositionedOverlays[ (*overlayIter)->GetPosition() ]->layout() )->addWidget( (*overlayIter)->GetWidget(), stackLayer, Qt::AlignLeft ); //} } void QmitkOverlayController::RestackOverlays( QmitkOverlay::DisplayPosition pos ) { OverlayVector::iterator overlayIter; QBoxLayout* layout = dynamic_cast<QBoxLayout*>( m_PositionedOverlays[ pos ]->layout() ); std::sort( m_AllOverlays.begin(), m_AllOverlays.end() ); for ( overlayIter=m_AllOverlays.begin(); overlayIter!=m_AllOverlays.end(); overlayIter++ ) { // do nothing if the overlay is not in the right position if ( (*overlayIter)->GetPosition() != pos ) { continue; } // determine the desired stacking layer // if the overlay-container is empty, simply append the overlay to the list // if it's not empty, use the layer of the overlay unsigned int layer = (*overlayIter)->GetLayer(); int stackLayer = 0; if ( !layout->isEmpty() ) { stackLayer = layer; } switch ( pos ) { // same alignment for all lefts, ... case QmitkOverlay::top_Left : {} case QmitkOverlay::middle_Left : {} case QmitkOverlay::bottom_Left : { layout->insertWidget( stackLayer, (*overlayIter)->GetWidget(), 0, Qt::AlignLeft ); break; } // ... for all centers, ... case QmitkOverlay::top_Center : {} case QmitkOverlay::bottom_Center : { layout->insertWidget( stackLayer, (*overlayIter)->GetWidget(), 0, Qt::AlignCenter ); break; } // ... and for all rights case QmitkOverlay::top_Right : {} case QmitkOverlay::middle_Right : {} case QmitkOverlay::bottom_Right : { layout->insertWidget( stackLayer, (*overlayIter)->GetWidget(), 0, Qt::AlignRight ); break; } } } } void QmitkOverlayController::UpdateAllOverlays() { foreach( QmitkOverlay* overlay, m_AllOverlays ) { this->UpdateOverlayData( overlay ); } }<|endoftext|>
<commit_before>// Copyright 2014 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 "content/browser/android/system_ui_resource_manager_impl.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/debug/trace_event.h" #include "base/location.h" #include "base/observer_list.h" #include "base/threading/worker_pool.h" #include "cc/resources/ui_resource_bitmap.h" #include "content/public/browser/android/ui_resource_client_android.h" #include "content/public/browser/android/ui_resource_provider.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkPaint.h" #include "third_party/skia/include/effects/SkPorterDuff.h" #include "ui/gfx/android/java_bitmap.h" #include "ui/gfx/screen.h" namespace content { namespace { SkBitmap CreateOverscrollGlowLBitmap(const gfx::Size& screen_size) { const float kSin = 0.5f; // sin(PI / 6) const float kCos = 0.866f; // cos(PI / 6); SkPaint paint; paint.setAntiAlias(true); paint.setAlpha(0x33); paint.setStyle(SkPaint::kFill_Style); const float arc_width = std::min(screen_size.width(), screen_size.height()) * 0.5f / kSin; const float y = kCos * arc_width; const float height = arc_width - y; gfx::Size bounds(arc_width, height); SkRect arc_rect = SkRect::MakeXYWH( -arc_width / 2.f, -arc_width - y, arc_width * 2.f, arc_width * 2.f); SkBitmap glow_bitmap; if (!glow_bitmap.allocPixels( SkImageInfo::MakeA8(bounds.width(), bounds.height()))) { LOG(FATAL) << " Failed to allocate bitmap of size " << bounds.width() << "x" << bounds.height(); } SkCanvas canvas(glow_bitmap); canvas.clipRect(SkRect::MakeXYWH(0, 0, bounds.width(), bounds.height())); canvas.drawArc(arc_rect, 45, 90, true, paint); return glow_bitmap; } void LoadBitmap(ui::SystemUIResourceManager::ResourceType type, SkBitmap* bitmap_holder, const gfx::Size& screen_size) { TRACE_EVENT1( "browser", "SystemUIResourceManagerImpl::LoadBitmap", "type", type); SkBitmap bitmap; switch (type) { case ui::SystemUIResourceManager::OVERSCROLL_EDGE: bitmap = gfx::CreateSkBitmapFromAndroidResource( "android:drawable/overscroll_edge", gfx::Size(128, 12)); break; case ui::SystemUIResourceManager::OVERSCROLL_GLOW: bitmap = gfx::CreateSkBitmapFromAndroidResource( "android:drawable/overscroll_glow", gfx::Size(128, 64)); break; case ui::SystemUIResourceManager::OVERSCROLL_GLOW_L: bitmap = CreateOverscrollGlowLBitmap(screen_size); break; } bitmap.setImmutable(); *bitmap_holder = bitmap; } } // namespace class SystemUIResourceManagerImpl::Entry : public content::UIResourceClientAndroid { public: explicit Entry(UIResourceProvider* provider) : id_(0), provider_(provider) { DCHECK(provider); } virtual ~Entry() { if (id_) provider_->DeleteUIResource(id_); id_ = 0; } void SetBitmap(const SkBitmap& bitmap) { DCHECK(!bitmap.empty()); DCHECK(bitmap_.empty()); DCHECK(!id_); bitmap_ = bitmap; } cc::UIResourceId GetUIResourceId() { if (bitmap_.empty()) return 0; if (!id_) id_ = provider_->CreateUIResource(this); return id_; } // content::UIResourceClient implementation. virtual cc::UIResourceBitmap GetBitmap(cc::UIResourceId uid, bool resource_lost) OVERRIDE { DCHECK(!bitmap_.empty()); return cc::UIResourceBitmap(bitmap_); } // content::UIResourceClientAndroid implementation. virtual void UIResourceIsInvalid() OVERRIDE { id_ = 0; } const SkBitmap& bitmap() const { return bitmap_; } private: SkBitmap bitmap_; cc::UIResourceId id_; UIResourceProvider* provider_; DISALLOW_COPY_AND_ASSIGN(Entry); }; SystemUIResourceManagerImpl::SystemUIResourceManagerImpl( UIResourceProvider* ui_resource_provider) : ui_resource_provider_(ui_resource_provider), weak_factory_(this) { } SystemUIResourceManagerImpl::~SystemUIResourceManagerImpl() { } void SystemUIResourceManagerImpl::PreloadResource(ResourceType type) { GetEntry(type); } cc::UIResourceId SystemUIResourceManagerImpl::GetUIResourceId( ResourceType type) { return GetEntry(type)->GetUIResourceId(); } SystemUIResourceManagerImpl::Entry* SystemUIResourceManagerImpl::GetEntry( ResourceType type) { DCHECK_GE(type, RESOURCE_TYPE_FIRST); DCHECK_LE(type, RESOURCE_TYPE_LAST); if (!resource_map_[type]) { resource_map_[type].reset(new Entry(ui_resource_provider_)); // Lazily build the resource. BuildResource(type); } return resource_map_[type].get(); } void SystemUIResourceManagerImpl::BuildResource(ResourceType type) { DCHECK(GetEntry(type)->bitmap().empty()); // Instead of blocking the main thread, we post a task to load the bitmap. SkBitmap* bitmap = new SkBitmap(); gfx::Size screen_size = gfx::Screen::GetNativeScreen()->GetPrimaryDisplay().GetSizeInPixel(); base::Closure load_bitmap = base::Bind(&LoadBitmap, type, bitmap, screen_size); base::Closure finished_load = base::Bind(&SystemUIResourceManagerImpl::OnFinishedLoadBitmap, weak_factory_.GetWeakPtr(), type, base::Owned(bitmap)); base::WorkerPool::PostTaskAndReply( FROM_HERE, load_bitmap, finished_load, true); } void SystemUIResourceManagerImpl::OnFinishedLoadBitmap( ResourceType type, SkBitmap* bitmap_holder) { DCHECK(bitmap_holder); GetEntry(type)->SetBitmap(*bitmap_holder); } } // namespace content <commit_msg>[Android] Clear backing SkBitmap before rendering the overscroll effect<commit_after>// Copyright 2014 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 "content/browser/android/system_ui_resource_manager_impl.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/debug/trace_event.h" #include "base/location.h" #include "base/observer_list.h" #include "base/threading/worker_pool.h" #include "cc/resources/ui_resource_bitmap.h" #include "content/public/browser/android/ui_resource_client_android.h" #include "content/public/browser/android/ui_resource_provider.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkPaint.h" #include "third_party/skia/include/effects/SkPorterDuff.h" #include "ui/gfx/android/java_bitmap.h" #include "ui/gfx/screen.h" namespace content { namespace { SkBitmap CreateOverscrollGlowLBitmap(const gfx::Size& screen_size) { const float kSin = 0.5f; // sin(PI / 6) const float kCos = 0.866f; // cos(PI / 6); SkPaint paint; paint.setAntiAlias(true); paint.setAlpha(0x33); paint.setStyle(SkPaint::kFill_Style); const float arc_width = std::min(screen_size.width(), screen_size.height()) * 0.5f / kSin; const float y = kCos * arc_width; const float height = arc_width - y; gfx::Size bounds(arc_width, height); SkRect arc_rect = SkRect::MakeXYWH( -arc_width / 2.f, -arc_width - y, arc_width * 2.f, arc_width * 2.f); SkBitmap glow_bitmap; if (!glow_bitmap.allocPixels( SkImageInfo::MakeA8(bounds.width(), bounds.height()))) { LOG(FATAL) << " Failed to allocate bitmap of size " << bounds.width() << "x" << bounds.height(); } glow_bitmap.eraseColor(SK_ColorTRANSPARENT); SkCanvas canvas(glow_bitmap); canvas.clipRect(SkRect::MakeXYWH(0, 0, bounds.width(), bounds.height())); canvas.drawArc(arc_rect, 45, 90, true, paint); return glow_bitmap; } void LoadBitmap(ui::SystemUIResourceManager::ResourceType type, SkBitmap* bitmap_holder, const gfx::Size& screen_size) { TRACE_EVENT1( "browser", "SystemUIResourceManagerImpl::LoadBitmap", "type", type); SkBitmap bitmap; switch (type) { case ui::SystemUIResourceManager::OVERSCROLL_EDGE: bitmap = gfx::CreateSkBitmapFromAndroidResource( "android:drawable/overscroll_edge", gfx::Size(128, 12)); break; case ui::SystemUIResourceManager::OVERSCROLL_GLOW: bitmap = gfx::CreateSkBitmapFromAndroidResource( "android:drawable/overscroll_glow", gfx::Size(128, 64)); break; case ui::SystemUIResourceManager::OVERSCROLL_GLOW_L: bitmap = CreateOverscrollGlowLBitmap(screen_size); break; } bitmap.setImmutable(); *bitmap_holder = bitmap; } } // namespace class SystemUIResourceManagerImpl::Entry : public content::UIResourceClientAndroid { public: explicit Entry(UIResourceProvider* provider) : id_(0), provider_(provider) { DCHECK(provider); } virtual ~Entry() { if (id_) provider_->DeleteUIResource(id_); id_ = 0; } void SetBitmap(const SkBitmap& bitmap) { DCHECK(!bitmap.empty()); DCHECK(bitmap_.empty()); DCHECK(!id_); bitmap_ = bitmap; } cc::UIResourceId GetUIResourceId() { if (bitmap_.empty()) return 0; if (!id_) id_ = provider_->CreateUIResource(this); return id_; } // content::UIResourceClient implementation. virtual cc::UIResourceBitmap GetBitmap(cc::UIResourceId uid, bool resource_lost) OVERRIDE { DCHECK(!bitmap_.empty()); return cc::UIResourceBitmap(bitmap_); } // content::UIResourceClientAndroid implementation. virtual void UIResourceIsInvalid() OVERRIDE { id_ = 0; } const SkBitmap& bitmap() const { return bitmap_; } private: SkBitmap bitmap_; cc::UIResourceId id_; UIResourceProvider* provider_; DISALLOW_COPY_AND_ASSIGN(Entry); }; SystemUIResourceManagerImpl::SystemUIResourceManagerImpl( UIResourceProvider* ui_resource_provider) : ui_resource_provider_(ui_resource_provider), weak_factory_(this) { } SystemUIResourceManagerImpl::~SystemUIResourceManagerImpl() { } void SystemUIResourceManagerImpl::PreloadResource(ResourceType type) { GetEntry(type); } cc::UIResourceId SystemUIResourceManagerImpl::GetUIResourceId( ResourceType type) { return GetEntry(type)->GetUIResourceId(); } SystemUIResourceManagerImpl::Entry* SystemUIResourceManagerImpl::GetEntry( ResourceType type) { DCHECK_GE(type, RESOURCE_TYPE_FIRST); DCHECK_LE(type, RESOURCE_TYPE_LAST); if (!resource_map_[type]) { resource_map_[type].reset(new Entry(ui_resource_provider_)); // Lazily build the resource. BuildResource(type); } return resource_map_[type].get(); } void SystemUIResourceManagerImpl::BuildResource(ResourceType type) { DCHECK(GetEntry(type)->bitmap().empty()); // Instead of blocking the main thread, we post a task to load the bitmap. SkBitmap* bitmap = new SkBitmap(); gfx::Size screen_size = gfx::Screen::GetNativeScreen()->GetPrimaryDisplay().GetSizeInPixel(); base::Closure load_bitmap = base::Bind(&LoadBitmap, type, bitmap, screen_size); base::Closure finished_load = base::Bind(&SystemUIResourceManagerImpl::OnFinishedLoadBitmap, weak_factory_.GetWeakPtr(), type, base::Owned(bitmap)); base::WorkerPool::PostTaskAndReply( FROM_HERE, load_bitmap, finished_load, true); } void SystemUIResourceManagerImpl::OnFinishedLoadBitmap( ResourceType type, SkBitmap* bitmap_holder) { DCHECK(bitmap_holder); GetEntry(type)->SetBitmap(*bitmap_holder); } } // namespace content <|endoftext|>
<commit_before>#include "generated/cpp/RhoFileBase.h" #include "common/RhodesApp.h" #include "common/RhoConf.h" #include "common/RhoFile.h" #include "common/RhoFilePath.h" #include "logging/RhoLog.h" namespace rho { using namespace apiGenerator; using namespace common; class CFileSingletonImpl: public CRhoFileSingletonBase { public: CFileSingletonImpl(): CRhoFileSingletonBase(){} virtual void copy( const rho::String& from, const rho::String& to, rho::apiGenerator::CMethodResult& oResult) { oResult.set( (int)CRhoFile::copyFile(from.c_str(),to.c_str()) ); } virtual void rename( const rho::String& from, const rho::String& to, rho::apiGenerator::CMethodResult& oResult) { oResult.set( (int)CRhoFile::renameFile(from.c_str(), to.c_str() ) ); } virtual void makeDir( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { oResult.set( (int)CRhoFile::createFolder( path.c_str() ) ); } virtual void exists( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { oResult.set( CRhoFile::isFileExist( path.c_str() ) ); } virtual void getFileSize( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { oResult.set( (int)CRhoFile::getFileSize( path.c_str() ) ); } virtual void isDir( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { oResult.set( CRhoFile::isDirectory( path.c_str() ) ); } virtual void isFile( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { oResult.set( CRhoFile::isFile( path.c_str() ) ); } virtual void deleteFile( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { oResult.set( (int)CRhoFile::deleteFile( path.c_str() ) ); } virtual void deleteDir( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { oResult.set( (int)CRhoFile::deleteEmptyFolder( path.c_str() ) ); } virtual void makeDirs( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { CRhoFile::recursiveCreateDir( path.c_str(), "" ); } virtual void deleteRecursive( const rho::String& path, bool leaveRoot, rho::apiGenerator::CMethodResult& oResult) { oResult.set( (int)CRhoFile::deleteFolder( path.c_str() ) ); } virtual void listDir( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { Vector<String> entries; if (CRhoFile::listFolderEntries(path,entries)) { oResult.set(entries); } } virtual void basename( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { CFilePath oPath(path); oResult.set( oPath.getBaseName() ); } virtual void dirname( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { CFilePath oPath(path); oResult.set( oPath.getFolderName() ); } virtual void join( const rho::String& p1, const rho::String& p2, rho::apiGenerator::CMethodResult& oResult) { oResult.set( CFilePath::join(p1,p2) ); } virtual void read( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { String data; CRhoFile::loadTextFile( path.c_str(), data ); oResult.set(data); } }; class CRhoFileImpl : public CRhoFileBase { CRhoFile m_oFile; public: virtual ~CRhoFileImpl() {} virtual void open( const rho::String& path, int mode, rho::apiGenerator::CMethodResult& oResult) { m_oFile.open(path.c_str(), (CRhoFile::EOpenModes)mode); } virtual void close(rho::apiGenerator::CMethodResult& oResult) { m_oFile.close(); } virtual void isOpened(rho::apiGenerator::CMethodResult& oResult) { oResult.set(m_oFile.isOpened()); } virtual void read( int size, rho::apiGenerator::CMethodResult& oResult) { char* buf = 0; if ( size > 0 ) { buf = new char[size + 1]; m_oFile.readData((void*)buf,0,size); buf[size] = 0; String data(buf); oResult.set(data); } else { oResult.set(""); } } virtual void readAll(rho::apiGenerator::CMethodResult& oResult) { String data; m_oFile.readString(data); oResult.set(data); } virtual void write( const rho::String& val, rho::apiGenerator::CMethodResult& oResult) { oResult.set( (int)m_oFile.write((void*)val.c_str(),val.size()) ); } virtual void flush(rho::apiGenerator::CMethodResult& oResult) { m_oFile.flush(); } virtual void seek( int pos, rho::apiGenerator::CMethodResult& oResult) { m_oFile.setPosTo(pos); } virtual void size(rho::apiGenerator::CMethodResult& oResult) { oResult.set( (int)m_oFile.size() ); } }; //////////////////////////////////////////////////////////////////////// class CRhoFileFactory: public CRhoFileFactoryBase { public: CRhoFileFactory(){} IRhoFileSingleton* createModuleSingleton() { return new CFileSingletonImpl(); } virtual IRhoFile* createModuleByID(const rho::String& strID){ return new CRhoFileImpl(); }; }; } extern "C" void Init_RhoFile() { rho::CRhoFileFactory::setInstance( new rho::CRhoFileFactory() ); rho::Init_RhoFile_API(); } <commit_msg>coreAPI: create new folder after it was deleted if leaveRoot is set to true; set \0 symbol at actual read position, delete allocated array after read.<commit_after>#include "generated/cpp/RhoFileBase.h" #include "common/RhodesApp.h" #include "common/RhoConf.h" #include "common/RhoFile.h" #include "common/RhoFilePath.h" #include "logging/RhoLog.h" namespace rho { using namespace apiGenerator; using namespace common; class CFileSingletonImpl: public CRhoFileSingletonBase { public: CFileSingletonImpl(): CRhoFileSingletonBase(){} virtual void copy( const rho::String& from, const rho::String& to, rho::apiGenerator::CMethodResult& oResult) { oResult.set( (int)CRhoFile::copyFile(from.c_str(),to.c_str()) ); } virtual void rename( const rho::String& from, const rho::String& to, rho::apiGenerator::CMethodResult& oResult) { oResult.set( (int)CRhoFile::renameFile(from.c_str(), to.c_str() ) ); } virtual void makeDir( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { oResult.set( (int)CRhoFile::createFolder( path.c_str() ) ); } virtual void exists( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { oResult.set( CRhoFile::isFileExist( path.c_str() ) ); } virtual void getFileSize( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { oResult.set( (int)CRhoFile::getFileSize( path.c_str() ) ); } virtual void isDir( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { oResult.set( CRhoFile::isDirectory( path.c_str() ) ); } virtual void isFile( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { oResult.set( CRhoFile::isFile( path.c_str() ) ); } virtual void deleteFile( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { oResult.set( (int)CRhoFile::deleteFile( path.c_str() ) ); } virtual void deleteDir( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { oResult.set( (int)CRhoFile::deleteEmptyFolder( path.c_str() ) ); } virtual void makeDirs( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { CRhoFile::recursiveCreateDir( path.c_str(), "" ); } virtual void deleteRecursive( const rho::String& path, bool leaveRoot, rho::apiGenerator::CMethodResult& oResult) { int result = (int)CRhoFile::deleteFolder( path.c_str() ); if (leaveRoot && result == 0 ) { result = (int)CRhoFile::createFolder( path.c_str() ); } oResult.set( result ); } virtual void listDir( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { Vector<String> entries; if (CRhoFile::listFolderEntries(path,entries)) { oResult.set(entries); } } virtual void basename( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { CFilePath oPath(path); oResult.set( oPath.getBaseName() ); } virtual void dirname( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { CFilePath oPath(path); oResult.set( oPath.getFolderName() ); } virtual void join( const rho::String& p1, const rho::String& p2, rho::apiGenerator::CMethodResult& oResult) { oResult.set( CFilePath::join(p1,p2) ); } virtual void read( const rho::String& path, rho::apiGenerator::CMethodResult& oResult) { String data; CRhoFile::loadTextFile( path.c_str(), data ); oResult.set(data); } }; class CRhoFileImpl : public CRhoFileBase { CRhoFile m_oFile; public: virtual ~CRhoFileImpl() {} virtual void open( const rho::String& path, int mode, rho::apiGenerator::CMethodResult& oResult) { m_oFile.open(path.c_str(), (CRhoFile::EOpenModes)mode); } virtual void close(rho::apiGenerator::CMethodResult& oResult) { m_oFile.close(); } virtual void isOpened(rho::apiGenerator::CMethodResult& oResult) { oResult.set(m_oFile.isOpened()); } virtual void read( int size, rho::apiGenerator::CMethodResult& oResult) { char* buf = 0; if ( size > 0 ) { buf = new char[size + 1]; } if (buf) { int actualsize = m_oFile.readData((void*)buf,0,size); buf[actualsize] = 0; String data(buf); oResult.set(data); delete[] buf; } else { oResult.set(""); } } virtual void readAll(rho::apiGenerator::CMethodResult& oResult) { String data; m_oFile.readString(data); oResult.set(data); } virtual void write( const rho::String& val, rho::apiGenerator::CMethodResult& oResult) { oResult.set( (int)m_oFile.write((void*)val.c_str(),val.size()) ); } virtual void flush(rho::apiGenerator::CMethodResult& oResult) { m_oFile.flush(); } virtual void seek( int pos, rho::apiGenerator::CMethodResult& oResult) { m_oFile.setPosTo(pos); } virtual void size(rho::apiGenerator::CMethodResult& oResult) { oResult.set( (int)m_oFile.size() ); } }; //////////////////////////////////////////////////////////////////////// class CRhoFileFactory: public CRhoFileFactoryBase { public: CRhoFileFactory(){} IRhoFileSingleton* createModuleSingleton() { return new CFileSingletonImpl(); } virtual IRhoFile* createModuleByID(const rho::String& strID){ return new CRhoFileImpl(); }; }; } extern "C" void Init_RhoFile() { rho::CRhoFileFactory::setInstance( new rho::CRhoFileFactory() ); rho::Init_RhoFile_API(); } <|endoftext|>
<commit_before><commit_msg>Cleanups<commit_after><|endoftext|>
<commit_before>// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <windows.h> #include <string> #include "base/icu_util.h" #include "base/logging.h" #include "base/file_util.h" #include "base/path_service.h" #include "unicode/udata.h" namespace icu_util { bool Initialize() { // Assert that we are not called more than once. Even though calling this // function isn't harmful (ICU can handle it), being called twice probably // indicates a programming error. #ifndef DEBUG static bool called_once = false; DCHECK(!called_once); called_once = true; #endif // We expect to find the ICU data module alongside the current module. std::wstring data_path; PathService::Get(base::DIR_MODULE, &data_path); file_util::AppendToPath(&data_path, L"icudt38.dll"); HMODULE module = LoadLibrary(data_path.c_str()); if (!module) return false; FARPROC addr = GetProcAddress(module, "icudt38_dat"); if (!addr) return false; UErrorCode err = U_ZERO_ERROR; udata_setCommonData(reinterpret_cast<void*>(addr), &err); return err == U_ZERO_ERROR; } } // namespace icu_util <commit_msg>ICU isn't packaged on the Mac as it is on Windows. Review URL: http://chrome-reviews.prom.corp.google.com/1092<commit_after>// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. 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 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "build/build_config.h" #ifdef OS_WIN #include <windows.h> #endif #include <string> #include "base/icu_util.h" #include "base/logging.h" #include "base/file_util.h" #include "base/path_service.h" #include "unicode/udata.h" namespace icu_util { bool Initialize() { #ifdef OS_WIN // Assert that we are not called more than once. Even though calling this // function isn't harmful (ICU can handle it), being called twice probably // indicates a programming error. #ifndef NDEBUG static bool called_once = false; DCHECK(!called_once); called_once = true; #endif // We expect to find the ICU data module alongside the current module. std::wstring data_path; PathService::Get(base::DIR_MODULE, &data_path); file_util::AppendToPath(&data_path, L"icudt38.dll"); HMODULE module = LoadLibrary(data_path.c_str()); if (!module) return false; FARPROC addr = GetProcAddress(module, "icudt38_dat"); if (!addr) return false; UErrorCode err = U_ZERO_ERROR; udata_setCommonData(reinterpret_cast<void*>(addr), &err); return err == U_ZERO_ERROR; #else // Windows ships ICU's data separate, so it needs to link the code to data // here. Other platforms don't need this. return true; #endif // OS_WIN } } // namespace icu_util <|endoftext|>