text
stringlengths
54
60.6k
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/cache/p9_hcd_l2_stopclocks.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_hcd_l2_stopclocks.C /// @brief Quad Clock Stop /// /// Procedure Summary: // *HWP HWP Owner : David Du <[email protected]> // *HWP Backup HWP Owner : Greg Still <[email protected]> // *HWP FW Owner : Sangeetha T S <[email protected]> // *HWP Team : PM // *HWP Consumed by : HB:PERV // *HWP Level : 2 //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <p9_misc_scom_addresses.H> #include <p9_quad_scom_addresses.H> #include <p9_hcd_common.H> #include "p9_hcd_l2_stopclocks.H" //------------------------------------------------------------------------------ // Constant Definitions //------------------------------------------------------------------------------ enum P9_HCD_L2_STOPCLOCKS_CONSTANTS { L2_CLK_SYNC_TIMEOUT_IN_MS = 1, L2_CLK_STOP_TIMEOUT_IN_MS = 1 }; //------------------------------------------------------------------------------ // Procedure: Quad Clock Stop //------------------------------------------------------------------------------ fapi2::ReturnCode p9_hcd_l2_stopclocks( const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target, const p9hcd::P9_HCD_EX_CTRL_CONSTANTS i_select_ex) { FAPI_INF(">>p9_hcd_l2_stopclocks: ex[%d]", i_select_ex); fapi2::buffer<uint64_t> l_data64; uint32_t l_timeout; uint64_t l_region_clock = 0; uint64_t l_l2sync_clock = 0; uint64_t l_l2mask_pscom = 0; uint8_t l_attr_chip_unit_pos = 0; auto l_perv = i_target.getParent<fapi2::TARGET_TYPE_PERV>(); auto l_chip = i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>(); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_perv, l_attr_chip_unit_pos)); l_attr_chip_unit_pos = l_attr_chip_unit_pos - p9hcd::PERV_TO_QUAD_POS_OFFSET; if (i_select_ex & p9hcd::EVEN_EX) { l_region_clock |= p9hcd::CLK_REGION_EX0_L2; l_l2sync_clock |= BIT64(36); l_l2mask_pscom |= BIT64(2) | BIT64(10); } if (i_select_ex & p9hcd::ODD_EX) { l_region_clock |= p9hcd::CLK_REGION_EX1_L2; l_l2sync_clock |= BIT64(37); l_l2mask_pscom |= BIT64(3) | BIT64(11); } // ------------------------- // Prepare to stop L2 clocks // ------------------------- FAPI_DBG("Assert L2 pscom masks via RING_FENCE_MASK_LATCH_REG[2/3,10/11]"); FAPI_TRY(putScom(i_target, EQ_RING_FENCE_MASK_LATCH_REG, l_l2mask_pscom)); // ------------------------------- // Stop L2 clocks // ------------------------------- FAPI_DBG("Clear all SCAN_REGION_TYPE bits"); FAPI_TRY(putScom(i_target, EQ_SCAN_REGION_TYPE, MASK_ZERO)); FAPI_DBG("Stop L2 clocks via CLK_REGION"); l_data64 = (p9hcd::CLK_STOP_CMD | l_region_clock | p9hcd::CLK_THOLD_ALL); FAPI_TRY(putScom(i_target, EQ_CLK_REGION, l_data64)); FAPI_DBG("Poll for L2 clocks stopped via CPLT_STAT0[8]"); l_timeout = (p9hcd::CYCLES_PER_MS / p9hcd::INSTS_PER_POLL_LOOP) * L2_CLK_STOP_TIMEOUT_IN_MS; do { FAPI_TRY(getScom(i_target, EQ_CPLT_STAT0, l_data64)); } while((l_data64.getBit<8>() != 1) && ((--l_timeout) != 0)); FAPI_ASSERT((l_timeout != 0), fapi2::PMPROC_L2CLKSTOP_TIMEOUT() .set_EQ_TARGET(i_target) .set_EQCPLTSTAT(l_data64), "L2 Clock Stop Timeout"); FAPI_DBG("Check L2 clocks stopped"); FAPI_TRY(getScom(i_target, EQ_CLOCK_STAT_SL, l_data64)); FAPI_ASSERT((((~l_data64) & l_region_clock) == 0), fapi2::PMPROC_L2CLKSTOP_FAILED() .set_EQ_TARGET(i_target) .set_EQCLKSTAT(l_data64), "L2 Clock Stop Failed"); FAPI_DBG("L2 clocks stopped now"); // ------------------------------- // Disable L2 clock sync // ------------------------------- FAPI_DBG("Drop L2 clock sync enables via QPPM_EXCGCR[36,37]"); FAPI_TRY(putScom(i_target, EQ_QPPM_EXCGCR_CLEAR, l_l2sync_clock)); FAPI_DBG("Poll for L2 clock sync dones to drop via QPPM_QACSR[36,37]"); l_timeout = (p9hcd::CYCLES_PER_MS / p9hcd::INSTS_PER_POLL_LOOP) * L2_CLK_SYNC_TIMEOUT_IN_MS; do { FAPI_TRY(getScom(i_target, EQ_QPPM_QACSR, l_data64)); } while(((l_data64 & l_l2sync_clock)) && ((--l_timeout) != 0)); FAPI_ASSERT((l_timeout != 0), fapi2::PMPROC_CACHECLKSYNCDROP_TIMEOUT().set_EQPPMQACSR(l_data64), "L2 Clock Sync Drop Timeout"); FAPI_DBG("L2 clock sync dones dropped"); // ------------------------------- // Fence up // ------------------------------- FAPI_DBG("Assert regional fences via CPLT_CTRL1[8/9]"); FAPI_TRY(putScom(i_target, EQ_CPLT_CTRL1_OR, l_region_clock)); // ------------------------------- // Update QSSR // ------------------------------- FAPI_DBG("Set EX as stopped in QSSR"); FAPI_TRY(putScom(l_chip, PU_OCB_OCI_QSSR_OR, ((uint64_t)i_select_ex << SHIFT64((l_attr_chip_unit_pos << 1) + 1)))); fapi_try_exit: FAPI_INF("<<p9_hcd_l2_stopclocks"); return fapi2::current_err; } <commit_msg>Fix for the EKB build failure caused by hcd constant<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/cache/p9_hcd_l2_stopclocks.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p9_hcd_l2_stopclocks.C /// @brief Quad Clock Stop /// /// Procedure Summary: // *HWP HWP Owner : David Du <[email protected]> // *HWP Backup HWP Owner : Greg Still <[email protected]> // *HWP FW Owner : Sangeetha T S <[email protected]> // *HWP Team : PM // *HWP Consumed by : HB:PERV // *HWP Level : 2 //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <p9_misc_scom_addresses.H> #include <p9_quad_scom_addresses.H> #include <p9_hcd_common.H> #include "p9_hcd_l2_stopclocks.H" //------------------------------------------------------------------------------ // Constant Definitions //------------------------------------------------------------------------------ enum P9_HCD_L2_STOPCLOCKS_CONSTANTS { L2_CLK_SYNC_TIMEOUT_IN_MS = 1, L2_CLK_STOP_TIMEOUT_IN_MS = 1 }; //------------------------------------------------------------------------------ // Procedure: Quad Clock Stop //------------------------------------------------------------------------------ fapi2::ReturnCode p9_hcd_l2_stopclocks( const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target, const p9hcd::P9_HCD_EX_CTRL_CONSTANTS i_select_ex) { FAPI_INF(">>p9_hcd_l2_stopclocks: ex[%d]", i_select_ex); fapi2::buffer<uint64_t> l_data64; uint32_t l_timeout; uint64_t l_region_clock = 0; uint64_t l_l2sync_clock = 0; uint64_t l_l2mask_pscom = 0; uint8_t l_attr_chip_unit_pos = 0; auto l_perv = i_target.getParent<fapi2::TARGET_TYPE_PERV>(); auto l_chip = i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>(); FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_perv, l_attr_chip_unit_pos)); // l_attr_chip_unit_pos = l_attr_chip_unit_pos - p9hcd::PERV_TO_QUAD_POS_OFFSET; l_attr_chip_unit_pos = l_attr_chip_unit_pos - 0x10; if (i_select_ex & p9hcd::EVEN_EX) { l_region_clock |= p9hcd::CLK_REGION_EX0_L2; l_l2sync_clock |= BIT64(36); l_l2mask_pscom |= BIT64(2) | BIT64(10); } if (i_select_ex & p9hcd::ODD_EX) { l_region_clock |= p9hcd::CLK_REGION_EX1_L2; l_l2sync_clock |= BIT64(37); l_l2mask_pscom |= BIT64(3) | BIT64(11); } // ------------------------- // Prepare to stop L2 clocks // ------------------------- FAPI_DBG("Assert L2 pscom masks via RING_FENCE_MASK_LATCH_REG[2/3,10/11]"); FAPI_TRY(putScom(i_target, EQ_RING_FENCE_MASK_LATCH_REG, l_l2mask_pscom)); // ------------------------------- // Stop L2 clocks // ------------------------------- FAPI_DBG("Clear all SCAN_REGION_TYPE bits"); FAPI_TRY(putScom(i_target, EQ_SCAN_REGION_TYPE, MASK_ZERO)); FAPI_DBG("Stop L2 clocks via CLK_REGION"); l_data64 = (p9hcd::CLK_STOP_CMD | l_region_clock | p9hcd::CLK_THOLD_ALL); FAPI_TRY(putScom(i_target, EQ_CLK_REGION, l_data64)); FAPI_DBG("Poll for L2 clocks stopped via CPLT_STAT0[8]"); l_timeout = (p9hcd::CYCLES_PER_MS / p9hcd::INSTS_PER_POLL_LOOP) * L2_CLK_STOP_TIMEOUT_IN_MS; do { FAPI_TRY(getScom(i_target, EQ_CPLT_STAT0, l_data64)); } while((l_data64.getBit<8>() != 1) && ((--l_timeout) != 0)); FAPI_ASSERT((l_timeout != 0), fapi2::PMPROC_L2CLKSTOP_TIMEOUT() .set_EQ_TARGET(i_target) .set_EQCPLTSTAT(l_data64), "L2 Clock Stop Timeout"); FAPI_DBG("Check L2 clocks stopped"); FAPI_TRY(getScom(i_target, EQ_CLOCK_STAT_SL, l_data64)); FAPI_ASSERT((((~l_data64) & l_region_clock) == 0), fapi2::PMPROC_L2CLKSTOP_FAILED() .set_EQ_TARGET(i_target) .set_EQCLKSTAT(l_data64), "L2 Clock Stop Failed"); FAPI_DBG("L2 clocks stopped now"); // ------------------------------- // Disable L2 clock sync // ------------------------------- FAPI_DBG("Drop L2 clock sync enables via QPPM_EXCGCR[36,37]"); FAPI_TRY(putScom(i_target, EQ_QPPM_EXCGCR_CLEAR, l_l2sync_clock)); FAPI_DBG("Poll for L2 clock sync dones to drop via QPPM_QACSR[36,37]"); l_timeout = (p9hcd::CYCLES_PER_MS / p9hcd::INSTS_PER_POLL_LOOP) * L2_CLK_SYNC_TIMEOUT_IN_MS; do { FAPI_TRY(getScom(i_target, EQ_QPPM_QACSR, l_data64)); } while(((l_data64 & l_l2sync_clock)) && ((--l_timeout) != 0)); FAPI_ASSERT((l_timeout != 0), fapi2::PMPROC_CACHECLKSYNCDROP_TIMEOUT().set_EQPPMQACSR(l_data64), "L2 Clock Sync Drop Timeout"); FAPI_DBG("L2 clock sync dones dropped"); // ------------------------------- // Fence up // ------------------------------- FAPI_DBG("Assert regional fences via CPLT_CTRL1[8/9]"); FAPI_TRY(putScom(i_target, EQ_CPLT_CTRL1_OR, l_region_clock)); // ------------------------------- // Update QSSR // ------------------------------- FAPI_DBG("Set EX as stopped in QSSR"); FAPI_TRY(putScom(l_chip, PU_OCB_OCI_QSSR_OR, ((uint64_t)i_select_ex << SHIFT64((l_attr_chip_unit_pos << 1) + 1)))); fapi_try_exit: FAPI_INF("<<p9_hcd_l2_stopclocks"); return fapi2::current_err; } <|endoftext|>
<commit_before>/* This file is part of VROOM. Copyright (c) 2015-2017, Julien Coupey. All rights reserved (see LICENSE). */ #include "tsp.h" #include "../../structures/vroom/input/input.h" <<<<<<< HEAD tsp::tsp(const input& input, index_t vehicle_rank): vrp(input), _vehicle_rank(vehicle_rank), _matrix(_input._matrix), // TODO avoid this copy! _symmetrized_matrix(_input._matrix.size()), _is_symmetric(true), _force_start(_input._vehicles[_vehicle_rank].has_start()), _force_end(_input._vehicles[_vehicle_rank].has_end()) { if(_force_start){ if( _input._vehicles[_vehicle_rank].start_id != boost::none ){ _start = _input._vehicles[_vehicle_rank].start_id.get(); }else{ _start = _input._vehicles[_vehicle_rank].start.get().index; } assert(_start < _matrix.size()); } if(_force_end){ if( _input._vehicles[_vehicle_rank].end_id != boost::none ){ _end = _input._vehicles[_vehicle_rank].end_id.get(); }else{ _end = _input._vehicles[_vehicle_rank].end.get().index; } assert(_end < _matrix.size()); } // Dealing with open tour cases. At most one of the following // occurs. if (_force_start and !_force_end) { // Forcing first location as start, end location decided during // optimization. for (index_t i = 0; i < _matrix.size(); ++i) { if (i != _start) { _matrix[i][_start] = 0; } } } if (!_force_start and _force_end) { // Forcing last location as end, start location decided during // optimization. for (index_t j = 0; j < _matrix.size(); ++j) { if (j != _end) { _matrix[_end][j] = 0; } } } if (_force_start and _force_end) { // Forcing first location as start, last location as end to // produce an open tour. assert(_start != _end); _matrix[_end][_start] = 0; for (index_t j = 0; j < _matrix.size(); ++j) { if ((j != _start) and (j != _end)) { _matrix[_end][j] = INFINITE_DISTANCE; } } } // Compute symmetrized matrix and update _is_symmetric flag. const distance_t& (*sym_f) (const distance_t&, const distance_t&) = std::min<distance_t>; if ((_force_start and !_force_end) or (!_force_start and _force_end)) { // Using symmetrization with max as when only start or only end is // forced, the matrix has a line or a column filled with zeros. sym_f = std::max<distance_t>; } for (index_t i = 0; i < _matrix.size(); ++i) { _symmetrized_matrix[i][i] = _matrix[i][i]; for (index_t j = i + 1; j < _matrix.size(); ++j) { _is_symmetric &= (_matrix[i][j] == _matrix[j][i]); distance_t val = sym_f(_matrix[i][j], _matrix[j][i]); _symmetrized_matrix[i][j] = val; _symmetrized_matrix[j][i] = val; } } } distance_t tsp::cost(const std::list<index_t>& tour) const { distance_t cost = 0; index_t init_step = 0; // Initialization actually never used. auto step = tour.cbegin(); if (tour.size() > 0) { init_step = *step; } index_t previous_step = init_step; ++step; for (; step != tour.cend(); ++step) { cost += _matrix[previous_step][*step]; previous_step = *step; } if (tour.size() > 0) { cost += _matrix[previous_step][init_step]; } return cost; } distance_t tsp::symmetrized_cost(const std::list<index_t>& tour) const { distance_t cost = 0; index_t init_step = 0; // Initialization actually never used. auto step = tour.cbegin(); if (tour.size() > 0) { init_step = *step; } index_t previous_step = init_step; ++step; for (; step != tour.cend(); ++step) { cost += _symmetrized_matrix[previous_step][*step]; previous_step = *step; } if (tour.size() > 0) { cost += _symmetrized_matrix[previous_step][init_step]; } return cost; } solution tsp::solve(unsigned nb_threads) const { // Applying heuristic. auto start_heuristic = std::chrono::high_resolution_clock::now(); BOOST_LOG_TRIVIAL(info) << "[Heuristic] Start heuristic on symmetrized problem."; std::list<index_t> christo_sol = christofides(_symmetrized_matrix); distance_t christo_cost = this->symmetrized_cost(christo_sol); auto end_heuristic = std::chrono::high_resolution_clock::now(); auto heuristic_computing_time = std::chrono::duration_cast<std::chrono::milliseconds>(end_heuristic - start_heuristic) .count(); BOOST_LOG_TRIVIAL(info) << "[Heuristic] Done, took " << heuristic_computing_time << " ms."; BOOST_LOG_TRIVIAL(info) << "[Heuristic] Symmetric solution cost is " << christo_cost << "."; // Local search on symmetric problem. // Applying deterministic, fast local search to improve the current // solution in a small amount of time. All possible moves for the // different neighbourhoods are performed, stopping when reaching a // local minima. auto start_sym_local_search = std::chrono::high_resolution_clock::now(); BOOST_LOG_TRIVIAL(info) << "[Local search] Start local search on symmetrized problem."; BOOST_LOG_TRIVIAL(info) << "[Local search] Using " << nb_threads << " thread(s)."; local_search sym_ls(_symmetrized_matrix, true, // Symmetrized problem. christo_sol, nb_threads); distance_t sym_two_opt_gain = 0; distance_t sym_relocate_gain = 0; distance_t sym_or_opt_gain = 0; do { // All possible 2-opt moves. sym_two_opt_gain = sym_ls.perform_all_two_opt_steps(); // All relocate moves. sym_relocate_gain = sym_ls.perform_all_relocate_steps(); // All or-opt moves. sym_or_opt_gain = sym_ls.perform_all_or_opt_steps(); } while ((sym_two_opt_gain > 0) or (sym_relocate_gain > 0) or (sym_or_opt_gain > 0)); index_t first_loc_index; if (_force_start) { // Use start value set in constructor from vehicle input. first_loc_index = _start; } else { assert(_force_end); // Requiring the tour to be described from the "forced" end // location. first_loc_index = _end; } std::list<index_t> current_sol = sym_ls.get_tour(first_loc_index); auto current_cost = this->symmetrized_cost(current_sol); auto end_sym_local_search = std::chrono::high_resolution_clock::now(); auto sym_local_search_duration = std::chrono::duration_cast<std::chrono::milliseconds> (end_sym_local_search - start_sym_local_search) .count(); BOOST_LOG_TRIVIAL(info) << "[Local search] Done, took " << sym_local_search_duration << " ms."; BOOST_LOG_TRIVIAL(info) << "[Local search] Symmetric solution cost is now " << current_cost << " (" << std::fixed << std::setprecision(2) << 100 *(((double) current_cost) / christo_cost - 1) << "%)."; auto asym_local_search_duration = 0; if (!_is_symmetric) { auto start_asym_local_search = std::chrono::high_resolution_clock::now(); // Back to the asymmetric problem, picking the best way. std::list<index_t> reverse_current_sol(current_sol); reverse_current_sol.reverse(); distance_t direct_cost = this->cost(current_sol); distance_t reverse_cost = this->cost(reverse_current_sol); // Cost reference after symmetric local search. distance_t sym_ls_cost = std::min(direct_cost, reverse_cost); // Local search on asymmetric problem. local_search asym_ls(_matrix, false, // Not the symmetrized problem. (direct_cost <= reverse_cost) ? current_sol: reverse_current_sol, nb_threads); BOOST_LOG_TRIVIAL(info) << "[Asym. local search] Back to asymmetric problem, initial solution cost is " << sym_ls_cost << "."; BOOST_LOG_TRIVIAL(info) << "[Asym. local search] Start local search on asymmetric problem."; BOOST_LOG_TRIVIAL(info) << "[Asym. local search] Using " << nb_threads << " thread(s)."; distance_t asym_two_opt_gain = 0; distance_t asym_relocate_gain = 0; distance_t asym_or_opt_gain = 0; distance_t asym_avoid_loops_gain = 0; do { // All avoid-loops moves. asym_avoid_loops_gain = asym_ls.perform_all_avoid_loop_steps(); // All possible 2-opt moves. asym_two_opt_gain = asym_ls.perform_all_asym_two_opt_steps(); // All relocate moves. asym_relocate_gain = asym_ls.perform_all_relocate_steps(); // All or-opt moves. asym_or_opt_gain = asym_ls.perform_all_or_opt_steps(); } while ((asym_two_opt_gain > 0) or (asym_relocate_gain > 0) or (asym_or_opt_gain > 0) or (asym_avoid_loops_gain > 0)); current_sol = asym_ls.get_tour(first_loc_index); current_cost = this->cost(current_sol); auto end_asym_local_search = std::chrono::high_resolution_clock::now(); asym_local_search_duration = std::chrono::duration_cast<std::chrono::milliseconds> (end_asym_local_search - start_asym_local_search) .count(); BOOST_LOG_TRIVIAL(info) << "[Asym. local search] Done, took " << asym_local_search_duration << " ms."; BOOST_LOG_TRIVIAL(info) << "[Asym. local search] Asymmetric solution cost is now " << current_cost << " (" << std::fixed << std::setprecision(2) << 100 *(((double) current_cost) / sym_ls_cost - 1) << "%)."; } // Deal with open tour cases requiring adaptation. if (!_force_start and _force_end) { // The tour has been listed starting with the "forced" end. This // index has to be popped and put back, the next element being the // chosen start resulting from the optimization. current_sol.push_back(current_sol.front()); current_sol.pop_front(); } // current_sol; // Steps for the one route. std::vector<step> steps; // Handle start. auto job_start = current_sol.cbegin(); if (_force_start) { // Add start step. if(_input._json_matrix_provided){ index_t start_id = _input._vehicles[_vehicle_rank].start_id.get(); steps.emplace_back(TYPE::START, _input._jobs[start_id], start_id ); }else{ steps.emplace_back(TYPE::START, _input.get_location_at(current_sol.front())); } // Remember that jobs start further away in the list. ++job_start; } // Determine where to stop for last job. auto job_end = current_sol.cend(); if (_force_end) { --job_end; } // Handle jobs. for (auto job = job_start; job != job_end; ++job) { auto current_rank = _input.get_job_rank_from_index(*job); steps.emplace_back(TYPE::JOB, _input._jobs[current_rank], _input._jobs[current_rank].id); } // Handle end. if (_force_end) { // Add end step. if(_input._json_matrix_provided){ index_t end_id = _input._vehicles[_vehicle_rank].end_id.get(); steps.emplace_back(TYPE::END, _input._jobs[end_id], end_id ); }else{ steps.emplace_back(TYPE::END, _input.get_location_at(current_sol.back())); } } // Route. std::vector<route_t> routes; routes.emplace_back(_input._vehicles[_vehicle_rank].id, steps, current_cost); solution sol(0, std::move(routes), current_cost); return sol; } <commit_msg>removed forgotten HEAD flag<commit_after>/* This file is part of VROOM. Copyright (c) 2015-2017, Julien Coupey. All rights reserved (see LICENSE). */ #include "tsp.h" #include "../../structures/vroom/input/input.h" tsp::tsp(const input& input, index_t vehicle_rank): vrp(input), _vehicle_rank(vehicle_rank), _matrix(_input._matrix), // TODO avoid this copy! _symmetrized_matrix(_input._matrix.size()), _is_symmetric(true), _force_start(_input._vehicles[_vehicle_rank].has_start()), _force_end(_input._vehicles[_vehicle_rank].has_end()) { if(_force_start){ if( _input._vehicles[_vehicle_rank].start_id != boost::none ){ _start = _input._vehicles[_vehicle_rank].start_id.get(); }else{ _start = _input._vehicles[_vehicle_rank].start.get().index; } assert(_start < _matrix.size()); } if(_force_end){ if( _input._vehicles[_vehicle_rank].end_id != boost::none ){ _end = _input._vehicles[_vehicle_rank].end_id.get(); }else{ _end = _input._vehicles[_vehicle_rank].end.get().index; } assert(_end < _matrix.size()); } // Dealing with open tour cases. At most one of the following // occurs. if (_force_start and !_force_end) { // Forcing first location as start, end location decided during // optimization. for (index_t i = 0; i < _matrix.size(); ++i) { if (i != _start) { _matrix[i][_start] = 0; } } } if (!_force_start and _force_end) { // Forcing last location as end, start location decided during // optimization. for (index_t j = 0; j < _matrix.size(); ++j) { if (j != _end) { _matrix[_end][j] = 0; } } } if (_force_start and _force_end) { // Forcing first location as start, last location as end to // produce an open tour. assert(_start != _end); _matrix[_end][_start] = 0; for (index_t j = 0; j < _matrix.size(); ++j) { if ((j != _start) and (j != _end)) { _matrix[_end][j] = INFINITE_DISTANCE; } } } // Compute symmetrized matrix and update _is_symmetric flag. const distance_t& (*sym_f) (const distance_t&, const distance_t&) = std::min<distance_t>; if ((_force_start and !_force_end) or (!_force_start and _force_end)) { // Using symmetrization with max as when only start or only end is // forced, the matrix has a line or a column filled with zeros. sym_f = std::max<distance_t>; } for (index_t i = 0; i < _matrix.size(); ++i) { _symmetrized_matrix[i][i] = _matrix[i][i]; for (index_t j = i + 1; j < _matrix.size(); ++j) { _is_symmetric &= (_matrix[i][j] == _matrix[j][i]); distance_t val = sym_f(_matrix[i][j], _matrix[j][i]); _symmetrized_matrix[i][j] = val; _symmetrized_matrix[j][i] = val; } } } distance_t tsp::cost(const std::list<index_t>& tour) const { distance_t cost = 0; index_t init_step = 0; // Initialization actually never used. auto step = tour.cbegin(); if (tour.size() > 0) { init_step = *step; } index_t previous_step = init_step; ++step; for (; step != tour.cend(); ++step) { cost += _matrix[previous_step][*step]; previous_step = *step; } if (tour.size() > 0) { cost += _matrix[previous_step][init_step]; } return cost; } distance_t tsp::symmetrized_cost(const std::list<index_t>& tour) const { distance_t cost = 0; index_t init_step = 0; // Initialization actually never used. auto step = tour.cbegin(); if (tour.size() > 0) { init_step = *step; } index_t previous_step = init_step; ++step; for (; step != tour.cend(); ++step) { cost += _symmetrized_matrix[previous_step][*step]; previous_step = *step; } if (tour.size() > 0) { cost += _symmetrized_matrix[previous_step][init_step]; } return cost; } solution tsp::solve(unsigned nb_threads) const { // Applying heuristic. auto start_heuristic = std::chrono::high_resolution_clock::now(); BOOST_LOG_TRIVIAL(info) << "[Heuristic] Start heuristic on symmetrized problem."; std::list<index_t> christo_sol = christofides(_symmetrized_matrix); distance_t christo_cost = this->symmetrized_cost(christo_sol); auto end_heuristic = std::chrono::high_resolution_clock::now(); auto heuristic_computing_time = std::chrono::duration_cast<std::chrono::milliseconds>(end_heuristic - start_heuristic) .count(); BOOST_LOG_TRIVIAL(info) << "[Heuristic] Done, took " << heuristic_computing_time << " ms."; BOOST_LOG_TRIVIAL(info) << "[Heuristic] Symmetric solution cost is " << christo_cost << "."; // Local search on symmetric problem. // Applying deterministic, fast local search to improve the current // solution in a small amount of time. All possible moves for the // different neighbourhoods are performed, stopping when reaching a // local minima. auto start_sym_local_search = std::chrono::high_resolution_clock::now(); BOOST_LOG_TRIVIAL(info) << "[Local search] Start local search on symmetrized problem."; BOOST_LOG_TRIVIAL(info) << "[Local search] Using " << nb_threads << " thread(s)."; local_search sym_ls(_symmetrized_matrix, true, // Symmetrized problem. christo_sol, nb_threads); distance_t sym_two_opt_gain = 0; distance_t sym_relocate_gain = 0; distance_t sym_or_opt_gain = 0; do { // All possible 2-opt moves. sym_two_opt_gain = sym_ls.perform_all_two_opt_steps(); // All relocate moves. sym_relocate_gain = sym_ls.perform_all_relocate_steps(); // All or-opt moves. sym_or_opt_gain = sym_ls.perform_all_or_opt_steps(); } while ((sym_two_opt_gain > 0) or (sym_relocate_gain > 0) or (sym_or_opt_gain > 0)); index_t first_loc_index; if (_force_start) { // Use start value set in constructor from vehicle input. first_loc_index = _start; } else { assert(_force_end); // Requiring the tour to be described from the "forced" end // location. first_loc_index = _end; } std::list<index_t> current_sol = sym_ls.get_tour(first_loc_index); auto current_cost = this->symmetrized_cost(current_sol); auto end_sym_local_search = std::chrono::high_resolution_clock::now(); auto sym_local_search_duration = std::chrono::duration_cast<std::chrono::milliseconds> (end_sym_local_search - start_sym_local_search) .count(); BOOST_LOG_TRIVIAL(info) << "[Local search] Done, took " << sym_local_search_duration << " ms."; BOOST_LOG_TRIVIAL(info) << "[Local search] Symmetric solution cost is now " << current_cost << " (" << std::fixed << std::setprecision(2) << 100 *(((double) current_cost) / christo_cost - 1) << "%)."; auto asym_local_search_duration = 0; if (!_is_symmetric) { auto start_asym_local_search = std::chrono::high_resolution_clock::now(); // Back to the asymmetric problem, picking the best way. std::list<index_t> reverse_current_sol(current_sol); reverse_current_sol.reverse(); distance_t direct_cost = this->cost(current_sol); distance_t reverse_cost = this->cost(reverse_current_sol); // Cost reference after symmetric local search. distance_t sym_ls_cost = std::min(direct_cost, reverse_cost); // Local search on asymmetric problem. local_search asym_ls(_matrix, false, // Not the symmetrized problem. (direct_cost <= reverse_cost) ? current_sol: reverse_current_sol, nb_threads); BOOST_LOG_TRIVIAL(info) << "[Asym. local search] Back to asymmetric problem, initial solution cost is " << sym_ls_cost << "."; BOOST_LOG_TRIVIAL(info) << "[Asym. local search] Start local search on asymmetric problem."; BOOST_LOG_TRIVIAL(info) << "[Asym. local search] Using " << nb_threads << " thread(s)."; distance_t asym_two_opt_gain = 0; distance_t asym_relocate_gain = 0; distance_t asym_or_opt_gain = 0; distance_t asym_avoid_loops_gain = 0; do { // All avoid-loops moves. asym_avoid_loops_gain = asym_ls.perform_all_avoid_loop_steps(); // All possible 2-opt moves. asym_two_opt_gain = asym_ls.perform_all_asym_two_opt_steps(); // All relocate moves. asym_relocate_gain = asym_ls.perform_all_relocate_steps(); // All or-opt moves. asym_or_opt_gain = asym_ls.perform_all_or_opt_steps(); } while ((asym_two_opt_gain > 0) or (asym_relocate_gain > 0) or (asym_or_opt_gain > 0) or (asym_avoid_loops_gain > 0)); current_sol = asym_ls.get_tour(first_loc_index); current_cost = this->cost(current_sol); auto end_asym_local_search = std::chrono::high_resolution_clock::now(); asym_local_search_duration = std::chrono::duration_cast<std::chrono::milliseconds> (end_asym_local_search - start_asym_local_search) .count(); BOOST_LOG_TRIVIAL(info) << "[Asym. local search] Done, took " << asym_local_search_duration << " ms."; BOOST_LOG_TRIVIAL(info) << "[Asym. local search] Asymmetric solution cost is now " << current_cost << " (" << std::fixed << std::setprecision(2) << 100 *(((double) current_cost) / sym_ls_cost - 1) << "%)."; } // Deal with open tour cases requiring adaptation. if (!_force_start and _force_end) { // The tour has been listed starting with the "forced" end. This // index has to be popped and put back, the next element being the // chosen start resulting from the optimization. current_sol.push_back(current_sol.front()); current_sol.pop_front(); } // current_sol; // Steps for the one route. std::vector<step> steps; // Handle start. auto job_start = current_sol.cbegin(); if (_force_start) { // Add start step. if(_input._json_matrix_provided){ index_t start_id = _input._vehicles[_vehicle_rank].start_id.get(); steps.emplace_back(TYPE::START, _input._jobs[start_id], start_id ); }else{ steps.emplace_back(TYPE::START, _input.get_location_at(current_sol.front())); } // Remember that jobs start further away in the list. ++job_start; } // Determine where to stop for last job. auto job_end = current_sol.cend(); if (_force_end) { --job_end; } // Handle jobs. for (auto job = job_start; job != job_end; ++job) { auto current_rank = _input.get_job_rank_from_index(*job); steps.emplace_back(TYPE::JOB, _input._jobs[current_rank], _input._jobs[current_rank].id); } // Handle end. if (_force_end) { // Add end step. if(_input._json_matrix_provided){ index_t end_id = _input._vehicles[_vehicle_rank].end_id.get(); steps.emplace_back(TYPE::END, _input._jobs[end_id], end_id ); }else{ steps.emplace_back(TYPE::END, _input.get_location_at(current_sol.back())); } } // Route. std::vector<route_t> routes; routes.emplace_back(_input._vehicles[_vehicle_rank].id, steps, current_cost); solution sol(0, std::move(routes), current_cost); return sol; } <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/zqcal.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file zqcal.C /// @brief Subroutines to send ZQCL commands /// // *HWP HWP Owner: Andre Marin <[email protected]> // *HWP HWP Backup: Jacob Harvey <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <vector> #include <fapi2.H> #include <lib/dimm/ddr4/zqcal.H> #include <lib/dimm/ddr4/data_buffer_ddr4.H> #include <lib/ccs/ccs.H> #include <lib/eff_config/timing.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_MCA; using fapi2::TARGET_TYPE_DIMM; namespace mss { /// /// @brief Setup DRAM ZQCL /// Specializaton for TARGET_TYPE_DIMM /// @param[in] i_target the target associated with this cal /// @param[in] i_rank the current rank /// @param[in,out] io_inst a vector of CCS instructions we should add to /// @return FAPI2_RC_SUCCESS iff setup was successful /// template<> fapi2::ReturnCode setup_dram_zqcal( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, const uint64_t i_rank, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst) { ccs::instruction_t<TARGET_TYPE_MCBIST> l_inst; uint64_t tDLLK = 0; FAPI_TRY( mss::tdllk(i_target, tDLLK) ); // Note: this isn't general - assumes Nimbus via MCBIST instruction here BRS l_inst = ccs::zqcl_command<TARGET_TYPE_MCBIST>(i_target, i_rank); l_inst.arr1.insertFromRight<MCBIST_CCS_INST_ARR1_00_IDLES, MCBIST_CCS_INST_ARR1_00_IDLES_LEN>(tDLLK + mss::tzqinit()); // There's nothing to decode here. FAPI_INF("ZQCL 0x%016llx:0x%016llx %s:rank %d", l_inst.arr0, l_inst.arr1, mss::c_str(i_target), i_rank); // Add both to the CCS program io_inst.push_back(l_inst); fapi_try_exit: return fapi2::current_err; } /// /// @brief Setup LRDIMM data buffer ZQCL /// Specializaton for TARGET_TYPE_DIMM /// @param[in] i_target the target associated with this cal /// @param[in,out] io_inst a vector of CCS instructions we should add to /// @return FAPI2_RC_SUCCESS iff setup was successful /// template<> fapi2::ReturnCode setup_data_buffer_zqcal( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst) { // For LRDIMMs, program BCW to send ZQCal Long command to all data buffers // in broadcast mode uint8_t l_dimm_type = 0; FAPI_TRY( eff_dimm_type(i_target, l_dimm_type) ); if( l_dimm_type != fapi2::ENUM_ATTR_EFF_DIMM_TYPE_LRDIMM ) { FAPI_INF("%s Skipping LRDIMM data buffer ZQCL, only done on LRDIMMs", mss::c_str(i_target)); return fapi2::FAPI2_RC_SUCCESS; } FAPI_TRY( ddr4::set_command_space(i_target, ddr4::command::ZQCL, io_inst) ); fapi_try_exit: return fapi2::current_err; } /// /// @brief Setup and execute DRAM ZQCL /// Specializaton for TARGET_TYPE_MCA /// @param[in] i_target the target associated with this cal /// @param[in] i_cal_steps_enabled fapi2::buffer<uint16_t> representing the cal steps to enable /// @return FAPI2_RC_SUCCESS iff setup was successful /// template<> fapi2::ReturnCode setup_and_execute_zqcal( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target, const fapi2::buffer<uint32_t>& i_cal_steps_enabled) { mss::ccs::program<TARGET_TYPE_MCBIST> l_program; for ( const auto& d : mss::find_targets<fapi2::TARGET_TYPE_DIMM>(i_target) ) { // If this bit isn't set, nothing to do here... if ( i_cal_steps_enabled.getBit<DRAM_ZQCAL>() ) { std::vector<uint64_t> l_ranks; FAPI_TRY( mss::rank::ranks(d, l_ranks) ); for( const auto& r : l_ranks) { FAPI_TRY( mss::setup_dram_zqcal(d, r, l_program.iv_instructions) ); }// ranks } // If this bit isn't set, nothing to do here... if ( i_cal_steps_enabled.getBit<DB_ZQCAL>() ) { FAPI_TRY( mss::setup_data_buffer_zqcal(d, l_program.iv_instructions) ); } }// dimm // execute ZQCAL instructions FAPI_TRY( mss::ccs::execute(mss::find_target<fapi2::TARGET_TYPE_MCBIST>(i_target), l_program, i_target) ); fapi_try_exit: return fapi2::current_err; } } // ns mss <commit_msg>Double POR timings (tMOD, tMRD, and tZQ) for more margin per lab<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/ddr4/zqcal.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2017,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file zqcal.C /// @brief Subroutines to send ZQCL commands /// // *HWP HWP Owner: Andre Marin <[email protected]> // *HWP HWP Backup: Jacob Harvey <[email protected]> // *HWP Team: Memory // *HWP Level: 2 // *HWP Consumed by: FSP:HB #include <vector> #include <fapi2.H> #include <lib/dimm/ddr4/zqcal.H> #include <lib/dimm/ddr4/data_buffer_ddr4.H> #include <lib/ccs/ccs.H> #include <lib/eff_config/timing.H> using fapi2::TARGET_TYPE_MCBIST; using fapi2::TARGET_TYPE_MCA; using fapi2::TARGET_TYPE_DIMM; namespace mss { /// /// @brief Setup DRAM ZQCL /// Specializaton for TARGET_TYPE_DIMM /// @param[in] i_target the target associated with this cal /// @param[in] i_rank the current rank /// @param[in,out] io_inst a vector of CCS instructions we should add to /// @return FAPI2_RC_SUCCESS iff setup was successful /// template<> fapi2::ReturnCode setup_dram_zqcal( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, const uint64_t i_rank, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst) { ccs::instruction_t<TARGET_TYPE_MCBIST> l_inst; uint64_t tDLLK = 0; FAPI_TRY( mss::tdllk(i_target, tDLLK) ); // Note: this isn't general - assumes Nimbus via MCBIST instruction here BRS l_inst = ccs::zqcl_command<TARGET_TYPE_MCBIST>(i_target, i_rank); // Doubling tZQ to better margin per lab request { const size_t DELAY = 2 * (tDLLK + mss::tzqinit()); l_inst.arr1.insertFromRight<MCBIST_CCS_INST_ARR1_00_IDLES, MCBIST_CCS_INST_ARR1_00_IDLES_LEN>(DELAY); } // There's nothing to decode here. FAPI_INF("ZQCL 0x%016llx:0x%016llx %s:rank %d", l_inst.arr0, l_inst.arr1, mss::c_str(i_target), i_rank); // Add both to the CCS program io_inst.push_back(l_inst); fapi_try_exit: return fapi2::current_err; } /// /// @brief Setup LRDIMM data buffer ZQCL /// Specializaton for TARGET_TYPE_DIMM /// @param[in] i_target the target associated with this cal /// @param[in,out] io_inst a vector of CCS instructions we should add to /// @return FAPI2_RC_SUCCESS iff setup was successful /// template<> fapi2::ReturnCode setup_data_buffer_zqcal( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target, std::vector< ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST> >& io_inst) { // For LRDIMMs, program BCW to send ZQCal Long command to all data buffers // in broadcast mode uint8_t l_dimm_type = 0; FAPI_TRY( eff_dimm_type(i_target, l_dimm_type) ); if( l_dimm_type != fapi2::ENUM_ATTR_EFF_DIMM_TYPE_LRDIMM ) { FAPI_INF("%s Skipping LRDIMM data buffer ZQCL, only done on LRDIMMs", mss::c_str(i_target)); return fapi2::FAPI2_RC_SUCCESS; } FAPI_TRY( ddr4::set_command_space(i_target, ddr4::command::ZQCL, io_inst) ); fapi_try_exit: return fapi2::current_err; } /// /// @brief Setup and execute DRAM ZQCL /// Specializaton for TARGET_TYPE_MCA /// @param[in] i_target the target associated with this cal /// @param[in] i_cal_steps_enabled fapi2::buffer<uint16_t> representing the cal steps to enable /// @return FAPI2_RC_SUCCESS iff setup was successful /// template<> fapi2::ReturnCode setup_and_execute_zqcal( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target, const fapi2::buffer<uint32_t>& i_cal_steps_enabled) { mss::ccs::program<TARGET_TYPE_MCBIST> l_program; for ( const auto& d : mss::find_targets<fapi2::TARGET_TYPE_DIMM>(i_target) ) { // If this bit isn't set, nothing to do here... if ( i_cal_steps_enabled.getBit<DRAM_ZQCAL>() ) { std::vector<uint64_t> l_ranks; FAPI_TRY( mss::rank::ranks(d, l_ranks) ); for( const auto& r : l_ranks) { FAPI_TRY( mss::setup_dram_zqcal(d, r, l_program.iv_instructions) ); }// ranks } // If this bit isn't set, nothing to do here... if ( i_cal_steps_enabled.getBit<DB_ZQCAL>() ) { FAPI_TRY( mss::setup_data_buffer_zqcal(d, l_program.iv_instructions) ); } }// dimm // execute ZQCAL instructions FAPI_TRY( mss::ccs::execute(mss::find_target<fapi2::TARGET_TYPE_MCBIST>(i_target), l_program, i_target) ); fapi_try_exit: return fapi2::current_err; } } // ns mss <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_occ.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PM_RECOVERY_FFDC_OCC_ #define __PM_RECOVERY_FFDC_OCC_ /// /// @file p9_pm_recovery_ffdc_occ.H /// @brief Models OCC platform for the FFDC collection of PM complex /// /// *HWP HWP Owner: Greg Still <[email protected]> /// *HWP FW Owner: Amit Tendolkar <[email protected]> /// *HWP Team: PM /// *HWP Level: 2 /// *HWP Consumed by: Hostboot // // *INDENT-OFF* //-------------------------------------------------------------------------- // Includes //-------------------------------------------------------------------------- #include <fapi2.H> #include <stdint.h> #include <p9_pm_recovery_ffdc_base.H> namespace p9_stop_recov_ffdc { class PlatOcc : public PlatPmComplex { public: /// @brief constructor PlatOcc ( const fapi2::Target <fapi2::TARGET_TYPE_PROC_CHIP> i_procChipTgt ); /// @brief destructor virtual ~PlatOcc() { }; /// @brief collects FFDC of the OCC 405, GPE0 and GPE1. /// @param[in] i_pHomerBuf points to base of P9 HOMER. /// @return fapi2 return code. fapi2::ReturnCode collectFfdc( void* i_pHomerBuf ); private: /// @brief collects trace info from OCC SRAM buffer. /// @param[in] i_pHomerBuf location in HOMER to write at /// @param[in] i_sramAddress location in OCC SRAM to read from /// @return fapi2 return code. fapi2::ReturnCode collectTrace( uint8_t * i_pHomerBuf, uint32_t i_sramAddress ); /// @brief updates the OCC FFDC Header /// @param[in] i_pHomerBuf points to a location in HOMER meant for /// OCC FFDC Header ///@param[in] i_ffdcValid Indicates what fields in OCC FFDC are /// valid. See OccFfdcValidStatus ///@return fapi2 return code. fapi2::ReturnCode updateOccFfdcHeader ( uint8_t* i_pHomerBuf, uint8_t i_ffdcValid ); }; extern "C" { typedef fapi2::ReturnCode( *p9_pm_recovery_ffdc_occ_FP_t ) ( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> & i_procChipTgt, void* i_occFfdcBuf ); } } //namespace p9_stop_recov_ffdc ends #endif //__PM_RECOVERY_FFDC_OCC_ <commit_msg>STOP Recovery: Misc infra. updates to enable PM FFDC in HOMER<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_occ.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef __PM_RECOVERY_FFDC_OCC_ #define __PM_RECOVERY_FFDC_OCC_ /// /// @file p9_pm_recovery_ffdc_occ.H /// @brief Models OCC platform for the FFDC collection of PM complex /// /// *HWP HWP Owner: Greg Still <[email protected]> /// *HWP FW Owner: Amit Tendolkar <[email protected]> /// *HWP Team: PM /// *HWP Level: 2 /// *HWP Consumed by: Hostboot // // *INDENT-OFF* //-------------------------------------------------------------------------- // Includes //-------------------------------------------------------------------------- #include <fapi2.H> #include <stdint.h> #include <p9_pm_recovery_ffdc_base.H> namespace p9_stop_recov_ffdc { class PlatOcc : public PlatPmComplex { public: /// @brief constructor PlatOcc ( const fapi2::Target <fapi2::TARGET_TYPE_PROC_CHIP> i_procChipTgt ); /// @brief destructor virtual ~PlatOcc() { }; /// @brief Initializes the OCC FFDC Sub-Sections in HOMER with default header /// @param[in] i_pHomerBuf points to base of P9 HOMER. /// @return fapi2 return code fapi2::ReturnCode init ( void* i_pHomerBuf ); /// @brief collects FFDC of the OCC 405, GPE0 and GPE1. /// @param[in] i_pHomerBuf points to base of P9 HOMER. /// @param[in] i_ffdcType indicates the content type to collect /// @return fapi2 return code. fapi2::ReturnCode collectFfdc ( void* i_pHomerBuf, uint8_t i_ffdcType = ALL ); private: /// @brief collects trace info from a known region OCC SRAM /// @param[in] i_pHomerBuf location in HOMER to write at /// @param[in] i_occSramRegion See OccFfdcValidStatus, /// Indicates OCC SRAM Region to read /// @return fapi2 return code. fapi2::ReturnCode collectTrace( uint8_t* i_pHomerBuf, uint8_t i_occSramRegion ); /// @brief reads OCC SRAM to find out the region extent and /// then collects info from that region /// @param[in] i_pHomerBuf location in HOMER to write at /// @param[in] i_occSramRegion See OccFfdcValidStatus. /// Indicates OCC SRAM Region to read /// @return fapi2 return code. fapi2::ReturnCode readSramRegion ( uint8_t* i_pHomerBuf, uint8_t i_occSramRegion ); /// @brief updates the OCC FFDC Header /// @param[in] i_pHomerBuf points to a location in HOMER meant for /// OCC FFDC Header ///@param[in] i_ffdcValid Indicates what fields in OCC FFDC are /// valid. See OccFfdcValidStatus ///@return fapi2 return code. fapi2::ReturnCode updateOccFfdcHeader ( uint8_t* i_pHomerBuf, uint16_t i_ffdcValid ); /// @brief collects register info for a given OCC /// @param[in] i_pHomerBuf points to location of HOMER meant for OCC internal register. ///@return fapi2 return code. fapi2::ReturnCode collectOccReg( uint8_t * i_pHomerBuf); }; extern "C" { typedef fapi2::ReturnCode( *p9_pm_recovery_ffdc_occ_FP_t ) ( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> & i_procChipTgt, void* i_occFfdcBuf ); } } //namespace p9_stop_recov_ffdc ends #endif //__PM_RECOVERY_FFDC_OCC_ <|endoftext|>
<commit_before><commit_msg>Replace gmock's EXPECT_THAT by an explicit check when comparing proxy config in PrefProxyConfigServiceTest.Fallback. This should avoid having gtest print the objects, which results in uninitialized memory accesses.<commit_after><|endoftext|>
<commit_before>#include <string> #include <vector> #include "lms/argumenthandler.h" #include "lms/extra/os.h" #include "lms/extra/string.h" #include "tclap/CmdLine.h" namespace lms { bool runLevelByName(const std::string &str, RunLevel &runLevel) { if (str == "CONFIG" || str == "0") { runLevel = RunLevel::CONFIG; return true; } else if (str == "ENABLE" || str == "1") { runLevel = RunLevel::ENABLE; return true; } else if (str == "CYCLE" || str == "2") { runLevel = RunLevel::CYCLE; return true; } return false; } std::ostream& operator << (std::ostream &out, RunLevel runLevel) { switch(runLevel) { case RunLevel::CONFIG: out << "CONFIG"; break; case RunLevel::ENABLE: out << "ENABLE"; break; case RunLevel::CYCLE: out << "CYCLE"; break; } return out; } ArgumentHandler::ArgumentHandler() : argLoadConfiguration(""), argRunLevel(RunLevel::CYCLE), argLoggingMinLevel(logging::Level::ALL), argQuiet(false), argUser(""), argProfiling(false), argConfigMonitor(false), argMultithreaded(false), argThreadsAuto(false), argThreads(1) { argUser = lms::extra::username(); } void ArgumentHandler::parseArguments(int argc, char* const*argv) { #ifdef _WIN32 #define USER_ENV "$USERNAME on Windows" #elif __APPLE__ #define USER_ENV "$USER on OSX" #else #define USER_ENV "$LOGNAME on Unix" #endif std::vector<std::string> debugLevels = {"DEBUG", "INFO", "WARN", "ERROR"}; TCLAP::ValuesConstraint<std::string> debugConstraint(debugLevels); std::vector<std::string> runLevels = {"0", "1", "2", "CONFIG", "ENABLE", "CYCLE"}; TCLAP::ValuesConstraint<std::string> runLevelsConstraint(runLevels); ThreadsConstraint threadsConstraint; TCLAP::CmdLine cmd("LMS - Lightweight Modular System", ' ', "1.0"); TCLAP::ValueArg<std::string> runLevelArg("r", "run-level", "Execute until a certain run level", false, "CYCLE", &runLevelsConstraint, cmd); TCLAP::ValueArg<std::string> loggingMinLevelArg("", "logging-min-level", "Filter logging by minimum logging level", false, "DEBUG", &debugConstraint, cmd); TCLAP::MultiArg<std::string> loggingPrefixArg("", "logging-prefix", "Filter logging by prefix of logging tags", false, "string", cmd); TCLAP::ValueArg<std::string> userArg("", "user", "Set the username, used for config loading, defaults to " USER_ENV, false, lms::extra::username(), "string", cmd); TCLAP::ValueArg<std::string> configArg("c", "config", "Load XML configuration file", false, "framework_conf", "string", cmd); TCLAP::ValueArg<std::string> logFileArg("", "log-file", "Log to the given file", false, "", "path", cmd); TCLAP::SwitchArg quietSwitch("q", "quiet", "Do not log anything to stdout", cmd, false); TCLAP::ValueArg<std::string> flagsArg("", "flags", "Config flags, can be used in <if> tags", false, "", "string-list", cmd); TCLAP::SwitchArg profilingSwitch("", "profiling", "Measure execution time of all modules", cmd, false); TCLAP::SwitchArg configMonitorSwitch("", "config-monitor", "Enable live config monitoring", cmd, false); TCLAP::ValueArg<std::string> threadsArg("", "threads", "Enable multithreading, number of threads or auto", false, "", &threadsConstraint, cmd); cmd.parse(argc, argv); argLoadConfiguration = configArg.getValue(); logging::levelFromName(loggingMinLevelArg.getValue(), argLoggingMinLevel); argLoggingPrefixes = loggingPrefixArg.getValue(); argUser = userArg.getValue(); argLogFile = logFileArg.getValue(); argQuiet = quietSwitch.getValue(); argFlags = lms::extra::split(flagsArg.getValue(), ','); argProfiling = profilingSwitch.getValue(); argConfigMonitor = configMonitorSwitch.getValue(); runLevelByName(runLevelArg.getValue(), argRunLevel); if(threadsArg.isSet()) { argMultithreaded = true; if(threadsArg.getValue() == std::string("auto")) { argThreadsAuto = true; } else { argThreads = atoi(threadsArg.getValue().c_str()); } } #undef USER_ENV } } // namespace lms <commit_msg>Rename --logging-min-level -> --logging-threshold<commit_after>#include <string> #include <vector> #include "lms/argumenthandler.h" #include "lms/extra/os.h" #include "lms/extra/string.h" #include "tclap/CmdLine.h" namespace lms { bool runLevelByName(const std::string &str, RunLevel &runLevel) { if (str == "CONFIG" || str == "0") { runLevel = RunLevel::CONFIG; return true; } else if (str == "ENABLE" || str == "1") { runLevel = RunLevel::ENABLE; return true; } else if (str == "CYCLE" || str == "2") { runLevel = RunLevel::CYCLE; return true; } return false; } std::ostream& operator << (std::ostream &out, RunLevel runLevel) { switch(runLevel) { case RunLevel::CONFIG: out << "CONFIG"; break; case RunLevel::ENABLE: out << "ENABLE"; break; case RunLevel::CYCLE: out << "CYCLE"; break; } return out; } ArgumentHandler::ArgumentHandler() : argLoadConfiguration(""), argRunLevel(RunLevel::CYCLE), argLoggingMinLevel(logging::Level::ALL), argQuiet(false), argUser(""), argProfiling(false), argConfigMonitor(false), argMultithreaded(false), argThreadsAuto(false), argThreads(1) { argUser = lms::extra::username(); } void ArgumentHandler::parseArguments(int argc, char* const*argv) { #ifdef _WIN32 #define USER_ENV "$USERNAME on Windows" #elif __APPLE__ #define USER_ENV "$USER on OSX" #else #define USER_ENV "$LOGNAME on Unix" #endif std::vector<std::string> debugLevels = {"ALL", "DEBUG", "INFO", "WARN", "ERROR", "OFF"}; TCLAP::ValuesConstraint<std::string> debugConstraint(debugLevels); std::vector<std::string> runLevels = {"0", "1", "2", "CONFIG", "ENABLE", "CYCLE"}; TCLAP::ValuesConstraint<std::string> runLevelsConstraint(runLevels); ThreadsConstraint threadsConstraint; TCLAP::CmdLine cmd("LMS - Lightweight Modular System", ' ', "1.0"); TCLAP::ValueArg<std::string> runLevelArg("r", "run-level", "Execute until a certain run level", false, "CYCLE", &runLevelsConstraint, cmd); TCLAP::ValueArg<std::string> loggingMinLevelArg("", "logging-threshold", "Filter logging by minimum logging level", false, "ALL", &debugConstraint, cmd); TCLAP::MultiArg<std::string> loggingPrefixArg("", "logging-prefix", "Filter logging by prefix of logging tags", false, "string", cmd); TCLAP::ValueArg<std::string> userArg("", "user", "Set the username, used for config loading, defaults to " USER_ENV, false, lms::extra::username(), "string", cmd); TCLAP::ValueArg<std::string> configArg("c", "config", "Load XML configuration file", false, "framework_conf", "string", cmd); TCLAP::ValueArg<std::string> logFileArg("", "log-file", "Log to the given file", false, "", "path", cmd); TCLAP::SwitchArg quietSwitch("q", "quiet", "Do not log anything to stdout", cmd, false); TCLAP::ValueArg<std::string> flagsArg("", "flags", "Config flags, can be used in <if> tags", false, "", "string-list", cmd); TCLAP::SwitchArg profilingSwitch("", "profiling", "Measure execution time of all modules", cmd, false); TCLAP::SwitchArg configMonitorSwitch("", "config-monitor", "Enable live config monitoring", cmd, false); TCLAP::ValueArg<std::string> threadsArg("", "threads", "Enable multithreading, number of threads or auto", false, "", &threadsConstraint, cmd); cmd.parse(argc, argv); argLoadConfiguration = configArg.getValue(); logging::levelFromName(loggingMinLevelArg.getValue(), argLoggingMinLevel); argLoggingPrefixes = loggingPrefixArg.getValue(); argUser = userArg.getValue(); argLogFile = logFileArg.getValue(); argQuiet = quietSwitch.getValue(); argFlags = lms::extra::split(flagsArg.getValue(), ','); argProfiling = profilingSwitch.getValue(); argConfigMonitor = configMonitorSwitch.getValue(); runLevelByName(runLevelArg.getValue(), argRunLevel); if(threadsArg.isSet()) { argMultithreaded = true; if(threadsArg.getValue() == std::string("auto")) { argThreadsAuto = true; } else { argThreads = atoi(threadsArg.getValue().c_str()); } } #undef USER_ENV } } // namespace lms <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "genericlinuxdeviceconfigurationwizardpages.h" #include "ui_genericlinuxdeviceconfigurationwizardsetuppage.h" #include "linuxdeviceconfiguration.h" namespace RemoteLinux { namespace Internal { class GenericLinuxDeviceConfigurationWizardSetupPagePrivate { public: Ui::GenericLinuxDeviceConfigurationWizardSetupPage ui; }; } // namespace Internal using namespace Utils; GenericLinuxDeviceConfigurationWizardSetupPage::GenericLinuxDeviceConfigurationWizardSetupPage(QWidget *parent) : QWizardPage(parent), m_d(new Internal::GenericLinuxDeviceConfigurationWizardSetupPagePrivate) { m_d->ui.setupUi(this); setTitle(tr("Connection Data")); setSubTitle(QLatin1String(" ")); // For Qt bug (background color) m_d->ui.privateKeyPathChooser->setExpectedKind(PathChooser::File); connect(m_d->ui.nameLineEdit, SIGNAL(textChanged(QString)), SIGNAL(completeChanged())); connect(m_d->ui.hostNameLineEdit, SIGNAL(textChanged(QString)), SIGNAL(completeChanged())); connect(m_d->ui.userNameLineEdit, SIGNAL(textChanged(QString)), SIGNAL(completeChanged())); connect(m_d->ui.privateKeyPathChooser, SIGNAL(validChanged()), SIGNAL(completeChanged())); connect(m_d->ui.passwordButton, SIGNAL(toggled(bool)), SLOT(handleAuthTypeChanged())); } GenericLinuxDeviceConfigurationWizardSetupPage::~GenericLinuxDeviceConfigurationWizardSetupPage() { delete m_d; } void GenericLinuxDeviceConfigurationWizardSetupPage::initializePage() { m_d->ui.nameLineEdit->setText(QLatin1String("(New Configuration)")); m_d->ui.hostNameLineEdit->setText(defaultHostName()); m_d->ui.userNameLineEdit->setText(defaultUserName()); m_d->ui.passwordButton->setChecked(true); m_d->ui.passwordLineEdit->setText(defaultPassWord()); m_d->ui.privateKeyPathChooser->setPath(LinuxDeviceConfiguration::defaultPrivateKeyFilePath()); handleAuthTypeChanged(); } bool GenericLinuxDeviceConfigurationWizardSetupPage::isComplete() const { return !configurationName().isEmpty() && !hostName().isEmpty() && !userName().isEmpty() && (authenticationType() == SshConnectionParameters::AuthenticationByPassword || !m_d->ui.privateKeyPathChooser->isValid()); } QString GenericLinuxDeviceConfigurationWizardSetupPage::configurationName() const { return m_d->ui.nameLineEdit->text().trimmed(); } QString GenericLinuxDeviceConfigurationWizardSetupPage::hostName() const { return m_d->ui.hostNameLineEdit->text().trimmed(); } QString GenericLinuxDeviceConfigurationWizardSetupPage::userName() const { return m_d->ui.userNameLineEdit->text().trimmed(); } SshConnectionParameters::AuthenticationType GenericLinuxDeviceConfigurationWizardSetupPage::authenticationType() const { return m_d->ui.passwordButton->isChecked() ? SshConnectionParameters::AuthenticationByPassword : SshConnectionParameters::AuthenticationByKey; } QString GenericLinuxDeviceConfigurationWizardSetupPage::password() const { return m_d->ui.passwordLineEdit->text(); } QString GenericLinuxDeviceConfigurationWizardSetupPage::privateKeyFilePath() const { return m_d->ui.privateKeyPathChooser->path(); } QString GenericLinuxDeviceConfigurationWizardSetupPage::defaultHostName() const { return QString(); } QString GenericLinuxDeviceConfigurationWizardSetupPage::defaultUserName() const { return QString(); } QString GenericLinuxDeviceConfigurationWizardSetupPage::defaultPassWord() const { return QString(); } void GenericLinuxDeviceConfigurationWizardSetupPage::handleAuthTypeChanged() { m_d->ui.passwordLineEdit->setEnabled(authenticationType() == SshConnectionParameters::AuthenticationByPassword); m_d->ui.privateKeyPathChooser->setEnabled(authenticationType() == SshConnectionParameters::AuthenticationByKey); emit completeChanged(); } GenericLinuxDeviceConfigurationWizardFinalPage::GenericLinuxDeviceConfigurationWizardFinalPage(QWidget *parent) : QWizardPage(parent), m_infoLabel(new QLabel(this)) { setTitle(tr("Setup Finished")); setSubTitle(QLatin1String(" ")); // For Qt bug (background color) m_infoLabel->setWordWrap(true); QVBoxLayout * const layout = new QVBoxLayout(this); layout->addWidget(m_infoLabel); } void GenericLinuxDeviceConfigurationWizardFinalPage::initializePage() { m_infoLabel->setText(infoText()); } QString GenericLinuxDeviceConfigurationWizardFinalPage::infoText() const { return tr("The new device configuration will now be created.\n" "In addition, device connectivity will be tested."); } } // namespace RemoteLinux <commit_msg>RemoteLinux: Fix wizard bug.<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "genericlinuxdeviceconfigurationwizardpages.h" #include "ui_genericlinuxdeviceconfigurationwizardsetuppage.h" #include "linuxdeviceconfiguration.h" namespace RemoteLinux { namespace Internal { class GenericLinuxDeviceConfigurationWizardSetupPagePrivate { public: Ui::GenericLinuxDeviceConfigurationWizardSetupPage ui; }; } // namespace Internal using namespace Utils; GenericLinuxDeviceConfigurationWizardSetupPage::GenericLinuxDeviceConfigurationWizardSetupPage(QWidget *parent) : QWizardPage(parent), m_d(new Internal::GenericLinuxDeviceConfigurationWizardSetupPagePrivate) { m_d->ui.setupUi(this); setTitle(tr("Connection Data")); setSubTitle(QLatin1String(" ")); // For Qt bug (background color) m_d->ui.privateKeyPathChooser->setExpectedKind(PathChooser::File); connect(m_d->ui.nameLineEdit, SIGNAL(textChanged(QString)), SIGNAL(completeChanged())); connect(m_d->ui.hostNameLineEdit, SIGNAL(textChanged(QString)), SIGNAL(completeChanged())); connect(m_d->ui.userNameLineEdit, SIGNAL(textChanged(QString)), SIGNAL(completeChanged())); connect(m_d->ui.privateKeyPathChooser, SIGNAL(validChanged()), SIGNAL(completeChanged())); connect(m_d->ui.passwordButton, SIGNAL(toggled(bool)), SLOT(handleAuthTypeChanged())); } GenericLinuxDeviceConfigurationWizardSetupPage::~GenericLinuxDeviceConfigurationWizardSetupPage() { delete m_d; } void GenericLinuxDeviceConfigurationWizardSetupPage::initializePage() { m_d->ui.nameLineEdit->setText(QLatin1String("(New Configuration)")); m_d->ui.hostNameLineEdit->setText(defaultHostName()); m_d->ui.userNameLineEdit->setText(defaultUserName()); m_d->ui.passwordButton->setChecked(true); m_d->ui.passwordLineEdit->setText(defaultPassWord()); m_d->ui.privateKeyPathChooser->setPath(LinuxDeviceConfiguration::defaultPrivateKeyFilePath()); handleAuthTypeChanged(); } bool GenericLinuxDeviceConfigurationWizardSetupPage::isComplete() const { return !configurationName().isEmpty() && !hostName().isEmpty() && !userName().isEmpty() && (authenticationType() == SshConnectionParameters::AuthenticationByPassword || m_d->ui.privateKeyPathChooser->isValid()); } QString GenericLinuxDeviceConfigurationWizardSetupPage::configurationName() const { return m_d->ui.nameLineEdit->text().trimmed(); } QString GenericLinuxDeviceConfigurationWizardSetupPage::hostName() const { return m_d->ui.hostNameLineEdit->text().trimmed(); } QString GenericLinuxDeviceConfigurationWizardSetupPage::userName() const { return m_d->ui.userNameLineEdit->text().trimmed(); } SshConnectionParameters::AuthenticationType GenericLinuxDeviceConfigurationWizardSetupPage::authenticationType() const { return m_d->ui.passwordButton->isChecked() ? SshConnectionParameters::AuthenticationByPassword : SshConnectionParameters::AuthenticationByKey; } QString GenericLinuxDeviceConfigurationWizardSetupPage::password() const { return m_d->ui.passwordLineEdit->text(); } QString GenericLinuxDeviceConfigurationWizardSetupPage::privateKeyFilePath() const { return m_d->ui.privateKeyPathChooser->path(); } QString GenericLinuxDeviceConfigurationWizardSetupPage::defaultHostName() const { return QString(); } QString GenericLinuxDeviceConfigurationWizardSetupPage::defaultUserName() const { return QString(); } QString GenericLinuxDeviceConfigurationWizardSetupPage::defaultPassWord() const { return QString(); } void GenericLinuxDeviceConfigurationWizardSetupPage::handleAuthTypeChanged() { m_d->ui.passwordLineEdit->setEnabled(authenticationType() == SshConnectionParameters::AuthenticationByPassword); m_d->ui.privateKeyPathChooser->setEnabled(authenticationType() == SshConnectionParameters::AuthenticationByKey); emit completeChanged(); } GenericLinuxDeviceConfigurationWizardFinalPage::GenericLinuxDeviceConfigurationWizardFinalPage(QWidget *parent) : QWizardPage(parent), m_infoLabel(new QLabel(this)) { setTitle(tr("Setup Finished")); setSubTitle(QLatin1String(" ")); // For Qt bug (background color) m_infoLabel->setWordWrap(true); QVBoxLayout * const layout = new QVBoxLayout(this); layout->addWidget(m_infoLabel); } void GenericLinuxDeviceConfigurationWizardFinalPage::initializePage() { m_infoLabel->setText(infoText()); } QString GenericLinuxDeviceConfigurationWizardFinalPage::infoText() const { return tr("The new device configuration will now be created.\n" "In addition, device connectivity will be tested."); } } // namespace RemoteLinux <|endoftext|>
<commit_before>/*************************************************************************/ /* multi_node_edit.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* 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 "multi_node_edit.h" #include "editor_node.h" bool MultiNodeEdit::_set(const StringName& p_name, const Variant& p_value){ Node *es = EditorNode::get_singleton()->get_edited_scene(); if (!es) return false; String name = p_name; if (name=="scripts/script") { // script/script set is intercepted at object level (check Variant Object::get() ) ,so use a different name name="script/script"; } UndoRedo *ur=EditorNode::get_singleton()->get_undo_redo(); ur->create_action(TTR("MultiNode Set")+" "+String(name)); for (const List<NodePath>::Element *E=nodes.front();E;E=E->next()) { if (!es->has_node(E->get())) continue; Node*n=es->get_node(E->get()); if (!n) continue; ur->add_do_property(n,name,p_value); ur->add_undo_property(n,name,n->get(name)); } ur->add_do_method(EditorNode::get_singleton()->get_property_editor(),"refresh"); ur->add_undo_method(EditorNode::get_singleton()->get_property_editor(),"refresh"); ur->commit_action(); return true; } bool MultiNodeEdit::_get(const StringName& p_name,Variant &r_ret) const { Node *es = EditorNode::get_singleton()->get_edited_scene(); if (!es) return false; String name=p_name; if (name=="scripts/script") { // script/script set is intercepted at object level (check Variant Object::get() ) ,so use a different name name="script/script"; } for (const List<NodePath>::Element *E=nodes.front();E;E=E->next()) { if (!es->has_node(E->get())) continue; const Node*n=es->get_node(E->get()); if (!n) continue; bool found; r_ret=n->get(name,&found); if (found) return true; } return false; } void MultiNodeEdit::_get_property_list( List<PropertyInfo> *p_list) const{ HashMap<String,PLData> usage; Node *es = EditorNode::get_singleton()->get_edited_scene(); if (!es) return; int nc=0; List<PLData*> datas; for (const List<NodePath>::Element *E=nodes.front();E;E=E->next()) { if (!es->has_node(E->get())) continue; Node*n=es->get_node(E->get()); if (!n) continue; List<PropertyInfo> plist; n->get_property_list(&plist,true); for(List<PropertyInfo>::Element *F=plist.front();F;F=F->next()) { if (F->get().name=="script/script") continue; //added later manually, since this is intercepted before being set (check Variant Object::get() ) if (!usage.has(F->get().name)) { PLData pld; pld.uses=0; pld.info=F->get(); usage[F->get().name]=pld; datas.push_back(usage.getptr(F->get().name)); } usage[F->get().name].uses++; } nc++; } for (List<PLData*>::Element *E=datas.front();E;E=E->next()) { if (nc==E->get()->uses) { p_list->push_back(E->get()->info); } } p_list->push_back(PropertyInfo(Variant::OBJECT,"scripts/script",PROPERTY_HINT_RESOURCE_TYPE,"Script")); } void MultiNodeEdit::clear_nodes() { nodes.clear(); } void MultiNodeEdit::add_node(const NodePath& p_node){ nodes.push_back(p_node); } MultiNodeEdit::MultiNodeEdit() { } <commit_msg>fixes #6695 - MultiNodeEdit edit path in exported NodePath<commit_after>/*************************************************************************/ /* multi_node_edit.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur. */ /* */ /* 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 "multi_node_edit.h" #include "editor_node.h" bool MultiNodeEdit::_set(const StringName& p_name, const Variant& p_value){ Node *es = EditorNode::get_singleton()->get_edited_scene(); if (!es) return false; String name = p_name; if (name=="scripts/script") { // script/script set is intercepted at object level (check Variant Object::get() ) ,so use a different name name="script/script"; } UndoRedo *ur=EditorNode::get_singleton()->get_undo_redo(); ur->create_action(TTR("MultiNode Set")+" "+String(name)); for (const List<NodePath>::Element *E=nodes.front();E;E=E->next()) { if (!es->has_node(E->get())) continue; Node*n=es->get_node(E->get()); if (!n) continue; if (p_value.get_type() == Variant::NODE_PATH) { Node *tonode = n->get_node(p_value); NodePath p_path = n->get_path_to(tonode); ur->add_do_property(n,name,p_path); } else { ur->add_do_property(n,name,p_value); } ur->add_undo_property(n,name,n->get(name)); } ur->add_do_method(EditorNode::get_singleton()->get_property_editor(),"refresh"); ur->add_undo_method(EditorNode::get_singleton()->get_property_editor(),"refresh"); ur->commit_action(); return true; } bool MultiNodeEdit::_get(const StringName& p_name,Variant &r_ret) const { Node *es = EditorNode::get_singleton()->get_edited_scene(); if (!es) return false; String name=p_name; if (name=="scripts/script") { // script/script set is intercepted at object level (check Variant Object::get() ) ,so use a different name name="script/script"; } for (const List<NodePath>::Element *E=nodes.front();E;E=E->next()) { if (!es->has_node(E->get())) continue; const Node*n=es->get_node(E->get()); if (!n) continue; bool found; r_ret=n->get(name,&found); if (found) return true; } return false; } void MultiNodeEdit::_get_property_list( List<PropertyInfo> *p_list) const{ HashMap<String,PLData> usage; Node *es = EditorNode::get_singleton()->get_edited_scene(); if (!es) return; int nc=0; List<PLData*> datas; for (const List<NodePath>::Element *E=nodes.front();E;E=E->next()) { if (!es->has_node(E->get())) continue; Node*n=es->get_node(E->get()); if (!n) continue; List<PropertyInfo> plist; n->get_property_list(&plist,true); for(List<PropertyInfo>::Element *F=plist.front();F;F=F->next()) { if (F->get().name=="script/script") continue; //added later manually, since this is intercepted before being set (check Variant Object::get() ) if (!usage.has(F->get().name)) { PLData pld; pld.uses=0; pld.info=F->get(); usage[F->get().name]=pld; datas.push_back(usage.getptr(F->get().name)); } usage[F->get().name].uses++; } nc++; } for (List<PLData*>::Element *E=datas.front();E;E=E->next()) { if (nc==E->get()->uses) { p_list->push_back(E->get()->info); } } p_list->push_back(PropertyInfo(Variant::OBJECT,"scripts/script",PROPERTY_HINT_RESOURCE_TYPE,"Script")); } void MultiNodeEdit::clear_nodes() { nodes.clear(); } void MultiNodeEdit::add_node(const NodePath& p_node){ nodes.push_back(p_node); } MultiNodeEdit::MultiNodeEdit() { } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "basetextblockselection.h" using namespace TextEditor; BaseTextBlockSelection::BaseTextBlockSelection() :firstVisualColumn(0), lastVisualColumn(0), anchor(BottomRight) { } void BaseTextBlockSelection::moveAnchor(int blockNumber, int visualColumn) { if (visualColumn >= 0) { if (anchor % 2) { lastVisualColumn = visualColumn; if (lastVisualColumn < firstVisualColumn) { qSwap(firstVisualColumn, lastVisualColumn); anchor = (Anchor) (anchor - 1); } } else { firstVisualColumn = visualColumn; if (firstVisualColumn > lastVisualColumn) { qSwap(firstVisualColumn, lastVisualColumn); anchor = (Anchor) (anchor + 1); } } } if (blockNumber >= 0 && blockNumber < firstBlock.document()->blockCount()) { if (anchor <= TopRight) { firstBlock.setPosition(firstBlock.document()->findBlockByNumber(blockNumber).position()); if (firstBlock.blockNumber() > lastBlock.blockNumber()) { qSwap(firstBlock, lastBlock); anchor = (Anchor) (anchor + 2); } } else { lastBlock.setPosition(firstBlock.document()->findBlockByNumber(blockNumber).position()); if (lastBlock.blockNumber() < firstBlock.blockNumber()) { qSwap(firstBlock, lastBlock); anchor = (Anchor) (anchor - 2); } } } firstBlock.movePosition(QTextCursor::StartOfBlock); lastBlock.movePosition(QTextCursor::EndOfBlock); } int BaseTextBlockSelection::position(const TabSettings &ts) const { const QTextBlock &block = anchor <= TopRight ? lastBlock.block() : firstBlock.block(); const int column = anchor % 2 ? firstVisualColumn : lastVisualColumn; return block.position() + ts.positionAtColumn(block.text(), column); } QTextCursor BaseTextBlockSelection::selection(const TabSettings &ts) const { QTextCursor cursor = firstBlock; if (anchor <= TopRight) { cursor.setPosition(lastBlock.block().position() + ts.positionAtColumn(lastBlock.block().text(), lastVisualColumn)); cursor.setPosition(firstBlock.block().position() + ts.positionAtColumn(firstBlock.block().text(), firstVisualColumn), QTextCursor::KeepAnchor); } else { cursor.setPosition(firstBlock.block().position() + ts.positionAtColumn(firstBlock.block().text(), firstVisualColumn)); cursor.setPosition(lastBlock.block().position() + ts.positionAtColumn(lastBlock.block().text(), lastVisualColumn), QTextCursor::KeepAnchor); } return cursor; } void BaseTextBlockSelection::fromSelection(const TabSettings &ts, const QTextCursor &selection) { firstBlock = selection; firstBlock.setPosition(selection.selectionStart()); firstVisualColumn = ts.columnAt(firstBlock.block().text(), firstBlock.positionInBlock()); lastBlock = selection; lastBlock.setPosition(selection.selectionEnd()); lastVisualColumn = ts.columnAt(lastBlock.block().text(), lastBlock.positionInBlock()); if (selection.anchor() > selection.position()) anchor = TopLeft; else anchor = BottomRight; firstBlock.movePosition(QTextCursor::StartOfBlock); lastBlock.movePosition(QTextCursor::EndOfBlock); } <commit_msg>fix build<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "basetextblockselection.h" #include <QTextBlock> #include <QTextCursor> using namespace TextEditor; BaseTextBlockSelection::BaseTextBlockSelection() :firstVisualColumn(0), lastVisualColumn(0), anchor(BottomRight) { } void BaseTextBlockSelection::moveAnchor(int blockNumber, int visualColumn) { if (visualColumn >= 0) { if (anchor % 2) { lastVisualColumn = visualColumn; if (lastVisualColumn < firstVisualColumn) { qSwap(firstVisualColumn, lastVisualColumn); anchor = (Anchor) (anchor - 1); } } else { firstVisualColumn = visualColumn; if (firstVisualColumn > lastVisualColumn) { qSwap(firstVisualColumn, lastVisualColumn); anchor = (Anchor) (anchor + 1); } } } if (blockNumber >= 0 && blockNumber < firstBlock.document()->blockCount()) { if (anchor <= TopRight) { firstBlock.setPosition(firstBlock.document()->findBlockByNumber(blockNumber).position()); if (firstBlock.blockNumber() > lastBlock.blockNumber()) { qSwap(firstBlock, lastBlock); anchor = (Anchor) (anchor + 2); } } else { lastBlock.setPosition(firstBlock.document()->findBlockByNumber(blockNumber).position()); if (lastBlock.blockNumber() < firstBlock.blockNumber()) { qSwap(firstBlock, lastBlock); anchor = (Anchor) (anchor - 2); } } } firstBlock.movePosition(QTextCursor::StartOfBlock); lastBlock.movePosition(QTextCursor::EndOfBlock); } int BaseTextBlockSelection::position(const TabSettings &ts) const { const QTextBlock &block = anchor <= TopRight ? lastBlock.block() : firstBlock.block(); const int column = anchor % 2 ? firstVisualColumn : lastVisualColumn; return block.position() + ts.positionAtColumn(block.text(), column); } QTextCursor BaseTextBlockSelection::selection(const TabSettings &ts) const { QTextCursor cursor = firstBlock; if (anchor <= TopRight) { cursor.setPosition(lastBlock.block().position() + ts.positionAtColumn(lastBlock.block().text(), lastVisualColumn)); cursor.setPosition(firstBlock.block().position() + ts.positionAtColumn(firstBlock.block().text(), firstVisualColumn), QTextCursor::KeepAnchor); } else { cursor.setPosition(firstBlock.block().position() + ts.positionAtColumn(firstBlock.block().text(), firstVisualColumn)); cursor.setPosition(lastBlock.block().position() + ts.positionAtColumn(lastBlock.block().text(), lastVisualColumn), QTextCursor::KeepAnchor); } return cursor; } void BaseTextBlockSelection::fromSelection(const TabSettings &ts, const QTextCursor &selection) { firstBlock = selection; firstBlock.setPosition(selection.selectionStart()); firstVisualColumn = ts.columnAt(firstBlock.block().text(), firstBlock.positionInBlock()); lastBlock = selection; lastBlock.setPosition(selection.selectionEnd()); lastVisualColumn = ts.columnAt(lastBlock.block().text(), lastBlock.positionInBlock()); if (selection.anchor() > selection.position()) anchor = TopLeft; else anchor = BottomRight; firstBlock.movePosition(QTextCursor::StartOfBlock); lastBlock.movePosition(QTextCursor::EndOfBlock); } <|endoftext|>
<commit_before>#include <plasp/Language.h> #include <boost/assign.hpp> #include <boost/bimap.hpp> namespace plasp { //////////////////////////////////////////////////////////////////////////////////////////////////// // // Language // //////////////////////////////////////////////////////////////////////////////////////////////////// using LanguageNames = boost::bimap<Language::Type, std::string>; //////////////////////////////////////////////////////////////////////////////////////////////////// const LanguageNames languageNames = boost::assign::list_of<LanguageNames::relation> (Language::Type::PDDL, "PDDL") (Language::Type::SAS, "SAS") (Language::Type::Unknown, "Unknown"); //////////////////////////////////////////////////////////////////////////////////////////////////// std::string Language::toString(Language::Type language) { const auto match = languageNames.left.find(language); if (match != languageNames.left.end()) return "Unknown"; return match->second; } //////////////////////////////////////////////////////////////////////////////////////////////////// Language::Type Language::fromString(const std::string &languageName) { const auto match = languageNames.right.find(languageName); if (match != languageNames.right.end()) return Language::Type::Unknown; return match->second; } //////////////////////////////////////////////////////////////////////////////////////////////////// } <commit_msg>Fixed wrong comparison for language detection.<commit_after>#include <plasp/Language.h> #include <boost/assign.hpp> #include <boost/bimap.hpp> namespace plasp { //////////////////////////////////////////////////////////////////////////////////////////////////// // // Language // //////////////////////////////////////////////////////////////////////////////////////////////////// using LanguageNames = boost::bimap<Language::Type, std::string>; //////////////////////////////////////////////////////////////////////////////////////////////////// const LanguageNames languageNames = boost::assign::list_of<LanguageNames::relation> (Language::Type::PDDL, "PDDL") (Language::Type::SAS, "SAS") (Language::Type::Unknown, "Unknown"); //////////////////////////////////////////////////////////////////////////////////////////////////// std::string Language::toString(Language::Type language) { const auto match = languageNames.left.find(language); if (match == languageNames.left.end()) return "Unknown"; return match->second; } //////////////////////////////////////////////////////////////////////////////////////////////////// Language::Type Language::fromString(const std::string &languageName) { const auto match = languageNames.right.find(languageName); if (match == languageNames.right.end()) return Language::Type::Unknown; return match->second; } //////////////////////////////////////////////////////////////////////////////////////////////////// } <|endoftext|>
<commit_before>///////////////////////////////////////////////////////////// // // chemical equilibrium // // $Author$ // $Revision$ // $Date$ // // copyright California Institute of Technology 2002 // ///////////////////////////////////////////////////////////// // turn off warnings under Windows #ifdef WIN32 #pragma warning(disable:4786) #pragma warning(disable:4503) #endif #include <cantera/Cantera.h> #include <time.h> #include "example_utils.h" #include <cantera/equilibrium.h> #include <cantera/IdealGasMix.h> //------------------------------------------------------------------- // utility functions for plotting template<class G, class V> void makeEquilDataLabels(const G& gas, V& names) { int nsp = gas.nSpecies(); names.resize(nsp + 2); names[0] = "Temperature (K)"; names[1] = "Pressure (Pa)"; int k; for (k = 0; k < nsp; k++) names[2+k] = gas.speciesName(k); } template<class G, class A> void plotEquilSoln(string fname, string fmt, string title, const G& gas, const A& soln) { vector<string> names; makeEquilDataLabels(gas, names); writePlotFile(fname, fmt, title, names, soln); } //----------------------------------------------------------------- // Equilibrium example. This is written as a function so that one // driver program can run multiple examples. // The action taken depends on input parameter job: // job = 0: print a one-line description of the example. // job = 1: print a longer description // job = 2: print description, then run the example. int equil_example1(int job) { cout << "Chemical equilibrium." << endl; if (job > 0) { cout << "Equilibrium composition and pressure for a " << "range of temperatures at constant density." << endl; } if (job <= 1) return 0; // header writeCanteraHeader(cout); // create a gas mixture, and set its state IdealGasMix gas("silane.cti", "silane"); int nsp = gas.nSpecies(); int ntemps = 50; // number of temperatures Array2D output(nsp+2, ntemps); // main loop doublereal temp; doublereal thigh = gas.maxTemp(); doublereal tlow = 500.0; doublereal dt = (thigh - tlow)/(ntemps); doublereal pres = 0.01*OneAtm; clock_t t0 = clock(); for (int i = 0; i < ntemps; i++) { temp = tlow + dt*i; if (temp > gas.maxTemp()) break; gas.setState_TPX(temp, pres, "SIH4:0.01, H2:0.99"); equilibrate(gas,"TP"); output(0,i) = temp; output(1,i) = gas.pressure(); gas.getMoleFractions(&output(2,i)); } clock_t t1 = clock(); // make a Tecplot data file and an Excel spreadsheet string plotTitle = "equilibrium example 1: " "chemical equilibrium"; plotEquilSoln("eq1.dat", "TEC", plotTitle, gas, output); plotEquilSoln("eq1.csv", "XL", plotTitle, gas, output); // print timing data doublereal tmm = 1.0*(t1 - t0)/CLOCKS_PER_SEC; cout << " time = " << tmm << endl << endl; cout << "Output files:" << endl << " eq1.csv (Excel CSV file)" << endl << " eq1.dat (Tecplot data file)" << endl; return 0; } <commit_msg>Replaced silane.cti with silane.xml so that it will work for python none installation.<commit_after>///////////////////////////////////////////////////////////// // // chemical equilibrium // // $Author$ // $Revision$ // $Date$ // // copyright California Institute of Technology 2002 // ///////////////////////////////////////////////////////////// // turn off warnings under Windows #ifdef WIN32 #pragma warning(disable:4786) #pragma warning(disable:4503) #endif #include <cantera/Cantera.h> #include <time.h> #include "example_utils.h" #include <cantera/equilibrium.h> #include <cantera/IdealGasMix.h> //------------------------------------------------------------------- // utility functions for plotting template<class G, class V> void makeEquilDataLabels(const G& gas, V& names) { int nsp = gas.nSpecies(); names.resize(nsp + 2); names[0] = "Temperature (K)"; names[1] = "Pressure (Pa)"; int k; for (k = 0; k < nsp; k++) names[2+k] = gas.speciesName(k); } template<class G, class A> void plotEquilSoln(string fname, string fmt, string title, const G& gas, const A& soln) { vector<string> names; makeEquilDataLabels(gas, names); writePlotFile(fname, fmt, title, names, soln); } //----------------------------------------------------------------- // Equilibrium example. This is written as a function so that one // driver program can run multiple examples. // The action taken depends on input parameter job: // job = 0: print a one-line description of the example. // job = 1: print a longer description // job = 2: print description, then run the example. int equil_example1(int job) { cout << "Chemical equilibrium." << endl; if (job > 0) { cout << "Equilibrium composition and pressure for a " << "range of temperatures at constant density." << endl; } if (job <= 1) return 0; // header writeCanteraHeader(cout); // create a gas mixture, and set its state //IdealGasMix gas("silane.cti", "silane"); IdealGasMix gas("silane.xml", "silane"); int nsp = gas.nSpecies(); int ntemps = 50; // number of temperatures Array2D output(nsp+2, ntemps); // main loop doublereal temp; doublereal thigh = gas.maxTemp(); doublereal tlow = 500.0; doublereal dt = (thigh - tlow)/(ntemps); doublereal pres = 0.01*OneAtm; clock_t t0 = clock(); for (int i = 0; i < ntemps; i++) { temp = tlow + dt*i; if (temp > gas.maxTemp()) break; gas.setState_TPX(temp, pres, "SIH4:0.01, H2:0.99"); equilibrate(gas,"TP"); output(0,i) = temp; output(1,i) = gas.pressure(); gas.getMoleFractions(&output(2,i)); } clock_t t1 = clock(); // make a Tecplot data file and an Excel spreadsheet string plotTitle = "equilibrium example 1: " "chemical equilibrium"; plotEquilSoln("eq1.dat", "TEC", plotTitle, gas, output); plotEquilSoln("eq1.csv", "XL", plotTitle, gas, output); // print timing data doublereal tmm = 1.0*(t1 - t0)/CLOCKS_PER_SEC; cout << " time = " << tmm << endl << endl; cout << "Output files:" << endl << " eq1.csv (Excel CSV file)" << endl << " eq1.dat (Tecplot data file)" << endl; return 0; } <|endoftext|>
<commit_before> #if defined(DISC_UNION_TEST_MAIN) #include <stdio.h> #include <stdlib.h> #include "disc_union.h" #include "vector.h" #include "strings.h" struct MyClass{ char name[16]; int i; float f; Vector<int> it; }; struct MyOtherClass{ void* data; int g; float h; short header[6]; }; // Define a macro that takes a macro #define DISC_LIST(mac) \ mac(MyClass) \ mac(MyOtherClass) \ mac(String) // This generates the actual struct body DEFINE_DISCRIMINATED_UNION(MyUnion, DISC_LIST) // We don't need to undef it, but it's a good idea #undef DISC_LIST void DoSomething(const MyUnion& mu) { ASSERT(mu.IsString()); } int main(int argc, char** argv){ MyClass mc; mc.it.PushBack(1); MyClass mc2; mc2.it.PushBack(2); MyOtherClass moc; MyUnion un; ASSERT(un.type == MyUnion::UE_None); ASSERT(!un.IsMyClass()); ASSERT(!un.IsMyOtherClass()); ASSERT(!un.IsString()); un = mc; ASSERT(un.type == MyUnion::UE_MyClass); ASSERT(un.IsMyClass()); ASSERT(!un.IsMyOtherClass()); ASSERT(!un.IsString()); un = moc; ASSERT(un.type == MyUnion::UE_MyOtherClass); ASSERT(!un.IsMyClass()); ASSERT(un.IsMyOtherClass()); ASSERT(!un.IsString()); un = mc; ASSERT(un.type == MyUnion::UE_MyClass); ASSERT(un.IsMyClass()); ASSERT(!un.IsMyOtherClass()); ASSERT(!un.IsString()); un = mc2; ASSERT(un.type == MyUnion::UE_MyClass); un = mc; ASSERT(un.type == MyUnion::UE_MyClass); String str1 = "LALA"; ASSERT(str1.GetRef() == 1); un = str1; ASSERT(un.type == MyUnion::UE_String); ASSERT(un.AsString() == str1); ASSERT(str1.GetRef() == 2); un = mc2; ASSERT(un.type == MyUnion::UE_MyClass); ASSERT(str1.GetRef() == 1); un = str1; ASSERT(str1.GetRef() == 2); { MyUnion un2 = un; ASSERT(un2.type == MyUnion::UE_String); ASSERT(str1.GetRef() == 3); MyUnion un3; un3 = un2; ASSERT(un3.type == MyUnion::UE_String); ASSERT(str1.GetRef() == 4); } ASSERT(str1.GetRef() == 2); { MyUnion un2 = str1; ASSERT(str1.GetRef() == 3); DoSomething(str1); ASSERT(str1.GetRef() == 3); ASSERT(un2.IsString()); const MyUnion& un2_ref = un2; ASSERT(un2_ref.IsString()); ASSERT(un2_ref.AsString().GetRef() == 3); } ASSERT(str1.GetRef() == 2); return 0; } #endif <commit_msg>Add some more disc_union tests.<commit_after> #if defined(DISC_UNION_TEST_MAIN) #include <stdio.h> #include <stdlib.h> #include "disc_union.h" #include "vector.h" #include "strings.h" struct MyClass{ char name[16]; int i; float f; Vector<int> it; }; struct MyOtherClass{ void* data; int g; float h; short header[6]; }; // Define a macro that takes a macro #define DISC_LIST(mac) \ mac(MyClass) \ mac(MyOtherClass) \ mac(String) // This generates the actual struct body DEFINE_DISCRIMINATED_UNION(MyUnion, DISC_LIST) // We don't need to undef it, but it's a good idea #undef DISC_LIST void DoSomething(const MyUnion& mu) { ASSERT(mu.IsString()); } int main(int argc, char** argv){ MyClass mc; mc.it.PushBack(1); MyClass mc2; mc2.it.PushBack(2); MyOtherClass moc; MyUnion un; ASSERT(un.type == MyUnion::UE_None); ASSERT(!un.IsMyClass()); ASSERT(!un.IsMyOtherClass()); ASSERT(!un.IsString()); un = mc; ASSERT(un.type == MyUnion::UE_MyClass); ASSERT(un.IsMyClass()); ASSERT(!un.IsMyOtherClass()); ASSERT(!un.IsString()); un = moc; ASSERT(un.type == MyUnion::UE_MyOtherClass); ASSERT(!un.IsMyClass()); ASSERT(un.IsMyOtherClass()); ASSERT(!un.IsString()); un = mc; ASSERT(un.type == MyUnion::UE_MyClass); ASSERT(un.IsMyClass()); ASSERT(!un.IsMyOtherClass()); ASSERT(!un.IsString()); un = mc2; ASSERT(un.type == MyUnion::UE_MyClass); un = mc; ASSERT(un.type == MyUnion::UE_MyClass); String str1 = "LALA"; ASSERT(str1.GetRef() == 1); un = str1; ASSERT(un.type == MyUnion::UE_String); ASSERT(un.AsString() == str1); ASSERT(str1.GetRef() == 2); un = mc2; ASSERT(un.type == MyUnion::UE_MyClass); ASSERT(str1.GetRef() == 1); un = str1; ASSERT(str1.GetRef() == 2); { MyUnion un2 = un; ASSERT(un2.type == MyUnion::UE_String); ASSERT(str1.GetRef() == 3); MyUnion un3; un3 = un2; ASSERT(un3.type == MyUnion::UE_String); ASSERT(str1.GetRef() == 4); } ASSERT(str1.GetRef() == 2); { MyUnion un2 = str1; ASSERT(str1.GetRef() == 3); DoSomething(str1); ASSERT(str1.GetRef() == 3); ASSERT(un2.IsString()); const MyUnion& un2_ref = un2; ASSERT(un2_ref.IsString()); ASSERT(un2_ref.AsString().GetRef() == 3); un2 = MyUnion(); ASSERT(!un2_ref.IsString()); ASSERT(str1.GetRef() == 2); un2 = str1; ASSERT(str1.GetRef() == 3); } ASSERT(str1.GetRef() == 2); return 0; } #endif <|endoftext|>
<commit_before>/* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #pragma once #include "bytes.hh" #include "timestamp.hh" #include "tombstone.hh" #include "gc_clock.hh" #include "utils/managed_bytes.hh" #include "net/byteorder.hh" #include <cstdint> #include <iostream> template<typename T> static inline void set_field(managed_bytes& v, unsigned offset, T val) { reinterpret_cast<net::packed<T>*>(v.begin() + offset)->raw = net::hton(val); } template<typename T> static inline T get_field(const bytes_view& v, unsigned offset) { return net::ntoh(*reinterpret_cast<const net::packed<T>*>(v.begin() + offset)); } class atomic_cell_or_collection; /* * Represents atomic cell layout. Works on serialized form. * * Layout: * * <live> := <int8_t:flags><int64_t:timestamp>(<int32_t:expiry><int32_t:ttl>)?<value> * <dead> := <int8_t: 0><int64_t:timestamp><int32_t:deletion_time> */ class atomic_cell_type final { private: static constexpr int8_t DEAD_FLAGS = 0; static constexpr int8_t LIVE_FLAG = 0x01; static constexpr int8_t EXPIRY_FLAG = 0x02; // When present, expiry field is present. Set only for live cells static constexpr unsigned flags_size = 1; static constexpr unsigned timestamp_offset = flags_size; static constexpr unsigned timestamp_size = 8; static constexpr unsigned expiry_offset = timestamp_offset + timestamp_size; static constexpr unsigned expiry_size = 4; static constexpr unsigned deletion_time_offset = timestamp_offset + timestamp_size; static constexpr unsigned deletion_time_size = 4; static constexpr unsigned ttl_offset = expiry_offset + expiry_size; static constexpr unsigned ttl_size = 4; private: static bool is_live(const bytes_view& cell) { return cell[0] != DEAD_FLAGS; } static bool is_live_and_has_ttl(const bytes_view& cell) { return cell[0] & EXPIRY_FLAG; } static bool is_dead(const bytes_view& cell) { return cell[0] == DEAD_FLAGS; } // Can be called on live and dead cells static api::timestamp_type timestamp(const bytes_view& cell) { return get_field<api::timestamp_type>(cell, timestamp_offset); } // Can be called on live cells only static bytes_view value(bytes_view cell) { auto expiry_field_size = bool(cell[0] & EXPIRY_FLAG) * (expiry_size + ttl_size); auto value_offset = flags_size + timestamp_size + expiry_field_size; cell.remove_prefix(value_offset); return cell; } // Can be called only when is_dead() is true. static gc_clock::time_point deletion_time(const bytes_view& cell) { assert(is_dead(cell)); return gc_clock::time_point(gc_clock::duration( get_field<int32_t>(cell, deletion_time_offset))); } // Can be called only when is_live_and_has_ttl() is true. static gc_clock::time_point expiry(const bytes_view& cell) { assert(is_live_and_has_ttl(cell)); auto expiry = get_field<int32_t>(cell, expiry_offset); return gc_clock::time_point(gc_clock::duration(expiry)); } // Can be called only when is_live_and_has_ttl() is true. static gc_clock::duration ttl(const bytes_view& cell) { assert(is_live_and_has_ttl(cell)); return gc_clock::duration(get_field<int32_t>(cell, ttl_offset)); } static managed_bytes make_dead(api::timestamp_type timestamp, gc_clock::time_point deletion_time) { managed_bytes b(managed_bytes::initialized_later(), flags_size + timestamp_size + deletion_time_size); b[0] = DEAD_FLAGS; set_field(b, timestamp_offset, timestamp); set_field(b, deletion_time_offset, deletion_time.time_since_epoch().count()); return b; } static managed_bytes make_live(api::timestamp_type timestamp, bytes_view value) { auto value_offset = flags_size + timestamp_size; managed_bytes b(managed_bytes::initialized_later(), value_offset + value.size()); b[0] = LIVE_FLAG; set_field(b, timestamp_offset, timestamp); std::copy_n(value.begin(), value.size(), b.begin() + value_offset); return b; } static managed_bytes make_live(api::timestamp_type timestamp, bytes_view value, gc_clock::time_point expiry, gc_clock::duration ttl) { auto value_offset = flags_size + timestamp_size + expiry_size + ttl_size; managed_bytes b(managed_bytes::initialized_later(), value_offset + value.size()); b[0] = EXPIRY_FLAG | LIVE_FLAG; set_field(b, timestamp_offset, timestamp); set_field(b, expiry_offset, expiry.time_since_epoch().count()); set_field(b, ttl_offset, ttl.count()); std::copy_n(value.begin(), value.size(), b.begin() + value_offset); return b; } template<typename ByteContainer> friend class atomic_cell_base; friend class atomic_cell; }; template<typename ByteContainer> class atomic_cell_base { protected: ByteContainer _data; protected: atomic_cell_base(ByteContainer&& data) : _data(std::forward<ByteContainer>(data)) { } atomic_cell_base(const ByteContainer& data) : _data(data) { } public: bool is_live() const { return atomic_cell_type::is_live(_data); } bool is_live(tombstone t) const { return is_live() && !is_covered_by(t); } bool is_live(tombstone t, gc_clock::time_point now) const { return is_live() && !is_covered_by(t) && !has_expired(now); } bool is_live_and_has_ttl() const { return atomic_cell_type::is_live_and_has_ttl(_data); } bool is_dead(gc_clock::time_point now) const { return atomic_cell_type::is_dead(_data) || has_expired(now); } bool is_covered_by(tombstone t) const { return timestamp() <= t.timestamp; } // Can be called on live and dead cells api::timestamp_type timestamp() const { return atomic_cell_type::timestamp(_data); } // Can be called on live cells only bytes_view value() const { return atomic_cell_type::value(_data); } // Can be called only when is_dead(gc_clock::time_point) gc_clock::time_point deletion_time() const { return !is_live() ? atomic_cell_type::deletion_time(_data) : expiry() - ttl(); } // Can be called only when is_live_and_has_ttl() gc_clock::time_point expiry() const { return atomic_cell_type::expiry(_data); } // Can be called only when is_live_and_has_ttl() gc_clock::duration ttl() const { return atomic_cell_type::ttl(_data); } // Can be called on live and dead cells bool has_expired(gc_clock::time_point now) const { return is_live_and_has_ttl() && expiry() < now; } bytes_view serialize() const { return _data; } }; class atomic_cell_view final : public atomic_cell_base<bytes_view> { atomic_cell_view(bytes_view data) : atomic_cell_base(data) {} public: static atomic_cell_view from_bytes(bytes_view data) { return atomic_cell_view(data); } friend class atomic_cell; friend std::ostream& operator<<(std::ostream& os, const atomic_cell_view& acv); }; class atomic_cell final : public atomic_cell_base<managed_bytes> { atomic_cell(managed_bytes b) : atomic_cell_base(std::move(b)) {} public: atomic_cell(const atomic_cell&) = default; atomic_cell(atomic_cell&&) = default; atomic_cell& operator=(const atomic_cell&) = default; atomic_cell& operator=(atomic_cell&&) = default; static atomic_cell from_bytes(bytes b) { return atomic_cell(std::move(b)); } atomic_cell(atomic_cell_view other) : atomic_cell_base(bytes { other._data.begin(), other._data.end() }) {} operator atomic_cell_view() const { return atomic_cell_view(_data); } static atomic_cell make_dead(api::timestamp_type timestamp, gc_clock::time_point deletion_time) { return atomic_cell_type::make_dead(timestamp, deletion_time); } static atomic_cell make_live(api::timestamp_type timestamp, bytes_view value) { return atomic_cell_type::make_live(timestamp, value); } static atomic_cell make_live(api::timestamp_type timestamp, bytes_view value, gc_clock::time_point expiry, gc_clock::duration ttl) { return atomic_cell_type::make_live(timestamp, value, expiry, ttl); } static atomic_cell make_live(api::timestamp_type timestamp, bytes_view value, ttl_opt ttl) { if (!ttl) { return atomic_cell_type::make_live(timestamp, value); } else { return atomic_cell_type::make_live(timestamp, value, gc_clock::now() + *ttl, *ttl); } } friend class atomic_cell_or_collection; friend std::ostream& operator<<(std::ostream& os, const atomic_cell& ac); }; // Represents a mutation of a collection. Actual format is determined by collection type, // and is: // set: list of atomic_cell // map: list of pair<atomic_cell, bytes> (for key/value) // list: tbd, probably ugly class collection_mutation { public: struct view { bytes_view data; bytes_view serialize() const { return data; } static view from_bytes(bytes_view v) { return { v }; } }; struct one { managed_bytes data; one() {} one(managed_bytes b) : data(std::move(b)) {} one(view v) : data(v.data) {} operator view() const { return { data }; } }; }; namespace db { template<typename T> class serializer; } // A variant type that can hold either an atomic_cell, or a serialized collection. // Which type is stored is determinied by the schema. class atomic_cell_or_collection final { managed_bytes _data; template<typename T> friend class db::serializer; private: atomic_cell_or_collection() = default; atomic_cell_or_collection(managed_bytes&& data) : _data(std::move(data)) {} public: atomic_cell_or_collection(atomic_cell ac) : _data(std::move(ac._data)) {} static atomic_cell_or_collection from_atomic_cell(atomic_cell data) { return { std::move(data._data) }; } atomic_cell_view as_atomic_cell() const { return atomic_cell_view::from_bytes(_data); } atomic_cell_or_collection(collection_mutation::one cm) : _data(std::move(cm.data)) {} static atomic_cell_or_collection from_collection_mutation(collection_mutation::one data) { return std::move(data.data); } collection_mutation::view as_collection_mutation() const { return collection_mutation::view{_data}; } bytes_view serialize() const { return _data; } friend std::ostream& operator<<(std::ostream&, const atomic_cell_or_collection&); }; class column_definition; int compare_atomic_cell_for_merge(atomic_cell_view left, atomic_cell_view right); void merge_column(const column_definition& def, atomic_cell_or_collection& old, const atomic_cell_or_collection& neww); <commit_msg>db: Avoid allocation of temporary bytes object<commit_after>/* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #pragma once #include "bytes.hh" #include "timestamp.hh" #include "tombstone.hh" #include "gc_clock.hh" #include "utils/managed_bytes.hh" #include "net/byteorder.hh" #include <cstdint> #include <iostream> template<typename T> static inline void set_field(managed_bytes& v, unsigned offset, T val) { reinterpret_cast<net::packed<T>*>(v.begin() + offset)->raw = net::hton(val); } template<typename T> static inline T get_field(const bytes_view& v, unsigned offset) { return net::ntoh(*reinterpret_cast<const net::packed<T>*>(v.begin() + offset)); } class atomic_cell_or_collection; /* * Represents atomic cell layout. Works on serialized form. * * Layout: * * <live> := <int8_t:flags><int64_t:timestamp>(<int32_t:expiry><int32_t:ttl>)?<value> * <dead> := <int8_t: 0><int64_t:timestamp><int32_t:deletion_time> */ class atomic_cell_type final { private: static constexpr int8_t DEAD_FLAGS = 0; static constexpr int8_t LIVE_FLAG = 0x01; static constexpr int8_t EXPIRY_FLAG = 0x02; // When present, expiry field is present. Set only for live cells static constexpr unsigned flags_size = 1; static constexpr unsigned timestamp_offset = flags_size; static constexpr unsigned timestamp_size = 8; static constexpr unsigned expiry_offset = timestamp_offset + timestamp_size; static constexpr unsigned expiry_size = 4; static constexpr unsigned deletion_time_offset = timestamp_offset + timestamp_size; static constexpr unsigned deletion_time_size = 4; static constexpr unsigned ttl_offset = expiry_offset + expiry_size; static constexpr unsigned ttl_size = 4; private: static bool is_live(const bytes_view& cell) { return cell[0] != DEAD_FLAGS; } static bool is_live_and_has_ttl(const bytes_view& cell) { return cell[0] & EXPIRY_FLAG; } static bool is_dead(const bytes_view& cell) { return cell[0] == DEAD_FLAGS; } // Can be called on live and dead cells static api::timestamp_type timestamp(const bytes_view& cell) { return get_field<api::timestamp_type>(cell, timestamp_offset); } // Can be called on live cells only static bytes_view value(bytes_view cell) { auto expiry_field_size = bool(cell[0] & EXPIRY_FLAG) * (expiry_size + ttl_size); auto value_offset = flags_size + timestamp_size + expiry_field_size; cell.remove_prefix(value_offset); return cell; } // Can be called only when is_dead() is true. static gc_clock::time_point deletion_time(const bytes_view& cell) { assert(is_dead(cell)); return gc_clock::time_point(gc_clock::duration( get_field<int32_t>(cell, deletion_time_offset))); } // Can be called only when is_live_and_has_ttl() is true. static gc_clock::time_point expiry(const bytes_view& cell) { assert(is_live_and_has_ttl(cell)); auto expiry = get_field<int32_t>(cell, expiry_offset); return gc_clock::time_point(gc_clock::duration(expiry)); } // Can be called only when is_live_and_has_ttl() is true. static gc_clock::duration ttl(const bytes_view& cell) { assert(is_live_and_has_ttl(cell)); return gc_clock::duration(get_field<int32_t>(cell, ttl_offset)); } static managed_bytes make_dead(api::timestamp_type timestamp, gc_clock::time_point deletion_time) { managed_bytes b(managed_bytes::initialized_later(), flags_size + timestamp_size + deletion_time_size); b[0] = DEAD_FLAGS; set_field(b, timestamp_offset, timestamp); set_field(b, deletion_time_offset, deletion_time.time_since_epoch().count()); return b; } static managed_bytes make_live(api::timestamp_type timestamp, bytes_view value) { auto value_offset = flags_size + timestamp_size; managed_bytes b(managed_bytes::initialized_later(), value_offset + value.size()); b[0] = LIVE_FLAG; set_field(b, timestamp_offset, timestamp); std::copy_n(value.begin(), value.size(), b.begin() + value_offset); return b; } static managed_bytes make_live(api::timestamp_type timestamp, bytes_view value, gc_clock::time_point expiry, gc_clock::duration ttl) { auto value_offset = flags_size + timestamp_size + expiry_size + ttl_size; managed_bytes b(managed_bytes::initialized_later(), value_offset + value.size()); b[0] = EXPIRY_FLAG | LIVE_FLAG; set_field(b, timestamp_offset, timestamp); set_field(b, expiry_offset, expiry.time_since_epoch().count()); set_field(b, ttl_offset, ttl.count()); std::copy_n(value.begin(), value.size(), b.begin() + value_offset); return b; } template<typename ByteContainer> friend class atomic_cell_base; friend class atomic_cell; }; template<typename ByteContainer> class atomic_cell_base { protected: ByteContainer _data; protected: atomic_cell_base(ByteContainer&& data) : _data(std::forward<ByteContainer>(data)) { } atomic_cell_base(const ByteContainer& data) : _data(data) { } public: bool is_live() const { return atomic_cell_type::is_live(_data); } bool is_live(tombstone t) const { return is_live() && !is_covered_by(t); } bool is_live(tombstone t, gc_clock::time_point now) const { return is_live() && !is_covered_by(t) && !has_expired(now); } bool is_live_and_has_ttl() const { return atomic_cell_type::is_live_and_has_ttl(_data); } bool is_dead(gc_clock::time_point now) const { return atomic_cell_type::is_dead(_data) || has_expired(now); } bool is_covered_by(tombstone t) const { return timestamp() <= t.timestamp; } // Can be called on live and dead cells api::timestamp_type timestamp() const { return atomic_cell_type::timestamp(_data); } // Can be called on live cells only bytes_view value() const { return atomic_cell_type::value(_data); } // Can be called only when is_dead(gc_clock::time_point) gc_clock::time_point deletion_time() const { return !is_live() ? atomic_cell_type::deletion_time(_data) : expiry() - ttl(); } // Can be called only when is_live_and_has_ttl() gc_clock::time_point expiry() const { return atomic_cell_type::expiry(_data); } // Can be called only when is_live_and_has_ttl() gc_clock::duration ttl() const { return atomic_cell_type::ttl(_data); } // Can be called on live and dead cells bool has_expired(gc_clock::time_point now) const { return is_live_and_has_ttl() && expiry() < now; } bytes_view serialize() const { return _data; } }; class atomic_cell_view final : public atomic_cell_base<bytes_view> { atomic_cell_view(bytes_view data) : atomic_cell_base(data) {} public: static atomic_cell_view from_bytes(bytes_view data) { return atomic_cell_view(data); } friend class atomic_cell; friend std::ostream& operator<<(std::ostream& os, const atomic_cell_view& acv); }; class atomic_cell final : public atomic_cell_base<managed_bytes> { atomic_cell(managed_bytes b) : atomic_cell_base(std::move(b)) {} public: atomic_cell(const atomic_cell&) = default; atomic_cell(atomic_cell&&) = default; atomic_cell& operator=(const atomic_cell&) = default; atomic_cell& operator=(atomic_cell&&) = default; static atomic_cell from_bytes(managed_bytes b) { return atomic_cell(std::move(b)); } atomic_cell(atomic_cell_view other) : atomic_cell_base(managed_bytes{other._data}) {} operator atomic_cell_view() const { return atomic_cell_view(_data); } static atomic_cell make_dead(api::timestamp_type timestamp, gc_clock::time_point deletion_time) { return atomic_cell_type::make_dead(timestamp, deletion_time); } static atomic_cell make_live(api::timestamp_type timestamp, bytes_view value) { return atomic_cell_type::make_live(timestamp, value); } static atomic_cell make_live(api::timestamp_type timestamp, bytes_view value, gc_clock::time_point expiry, gc_clock::duration ttl) { return atomic_cell_type::make_live(timestamp, value, expiry, ttl); } static atomic_cell make_live(api::timestamp_type timestamp, bytes_view value, ttl_opt ttl) { if (!ttl) { return atomic_cell_type::make_live(timestamp, value); } else { return atomic_cell_type::make_live(timestamp, value, gc_clock::now() + *ttl, *ttl); } } friend class atomic_cell_or_collection; friend std::ostream& operator<<(std::ostream& os, const atomic_cell& ac); }; // Represents a mutation of a collection. Actual format is determined by collection type, // and is: // set: list of atomic_cell // map: list of pair<atomic_cell, bytes> (for key/value) // list: tbd, probably ugly class collection_mutation { public: struct view { bytes_view data; bytes_view serialize() const { return data; } static view from_bytes(bytes_view v) { return { v }; } }; struct one { managed_bytes data; one() {} one(managed_bytes b) : data(std::move(b)) {} one(view v) : data(v.data) {} operator view() const { return { data }; } }; }; namespace db { template<typename T> class serializer; } // A variant type that can hold either an atomic_cell, or a serialized collection. // Which type is stored is determinied by the schema. class atomic_cell_or_collection final { managed_bytes _data; template<typename T> friend class db::serializer; private: atomic_cell_or_collection() = default; atomic_cell_or_collection(managed_bytes&& data) : _data(std::move(data)) {} public: atomic_cell_or_collection(atomic_cell ac) : _data(std::move(ac._data)) {} static atomic_cell_or_collection from_atomic_cell(atomic_cell data) { return { std::move(data._data) }; } atomic_cell_view as_atomic_cell() const { return atomic_cell_view::from_bytes(_data); } atomic_cell_or_collection(collection_mutation::one cm) : _data(std::move(cm.data)) {} static atomic_cell_or_collection from_collection_mutation(collection_mutation::one data) { return std::move(data.data); } collection_mutation::view as_collection_mutation() const { return collection_mutation::view{_data}; } bytes_view serialize() const { return _data; } friend std::ostream& operator<<(std::ostream&, const atomic_cell_or_collection&); }; class column_definition; int compare_atomic_cell_for_merge(atomic_cell_view left, atomic_cell_view right); void merge_column(const column_definition& def, atomic_cell_or_collection& old, const atomic_cell_or_collection& neww); <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, 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 Willow Garage, 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. * * $Id$ * */ #include <gtest/gtest.h> #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <pcl/pcl_tests.h> using namespace pcl; using namespace pcl::test; PointCloud<PointXYZ> cloud; const size_t size = 10 * 480; TEST (PointCloud, size) { EXPECT_EQ(cloud.points.size (), cloud.size ()); } TEST (PointCloud, sq_brackets_wrapper) { for (uint32_t i = 0; i < size; ++i) EXPECT_EQ_VECTORS (cloud.points[i].getVector3fMap (), cloud[i].getVector3fMap ()); } TEST (PointCloud, at) { for (uint32_t i = 0; i < size; ++i) EXPECT_EQ_VECTORS (cloud.points.at (i).getVector3fMap (), cloud.at (i).getVector3fMap ()); } TEST (PointCloud, front) { EXPECT_EQ_VECTORS (cloud.points.front ().getVector3fMap (), cloud.front ().getVector3fMap ()); } TEST (PointCloud, back) { EXPECT_EQ_VECTORS (cloud.points.back ().getVector3fMap (), cloud.back ().getVector3fMap ()); } TEST (PointCloud, constructor_with_allocation) { PointCloud<PointXYZ> cloud2 (5, 80); EXPECT_EQ (cloud2.width, 5); EXPECT_EQ (cloud2.height, 80); EXPECT_EQ (cloud2.size (), 5*80); } TEST (PointCloud, iterators) { EXPECT_EQ_VECTORS (cloud.begin ()->getVector3fMap (), cloud.points.begin ()->getVector3fMap ()); //EXPECT_EQ_VECTORS (cloud.end ()->getVector3fMap (), // cloud.points.end ()->getVector3fMap ()); PointCloud<PointXYZ>::const_iterator pit = cloud.begin (); PointCloud<PointXYZ>::VectorType::const_iterator pit2 = cloud.points.begin (); for (; pit < cloud.end (); ++pit2, ++pit) EXPECT_EQ_VECTORS (pit->getVector3fMap (), pit2->getVector3fMap ()); } TEST (PointCloud, insert_range) { PointCloud<PointXYZ> cloud2 (10, 1); for (uint32_t i = 0; i < 10; ++i) cloud2[i] = PointXYZ (5*i+0,5*i+1,5*i+2); uint32_t old_size = cloud.size (); cloud.insert (cloud.begin (), cloud2.begin (), cloud2.end ()); EXPECT_EQ (cloud.width, cloud.size ()); EXPECT_EQ (cloud.height, 1); EXPECT_EQ (cloud.width, old_size + cloud2.size ()); PointCloud<PointXYZ>::const_iterator pit = cloud.begin (); PointCloud<PointXYZ>::const_iterator pit2 = cloud2.begin (); for (; pit2 < cloud2.end (); ++pit2, ++pit) EXPECT_EQ_VECTORS (pit->getVector3fMap (), pit2->getVector3fMap ()); } int main (int argc, char** argv) { cloud.width = 10; cloud.height = 480; for (uint32_t i = 0; i < size; ++i) cloud.points.push_back (PointXYZ (3*i+0,3*i+1,3*i+2)); testing::InitGoogleTest (&argc, argv); return (RUN_ALL_TESTS ()); } <commit_msg>Add a unit test for the valued constructor with allocation<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, 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 Willow Garage, 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. * * $Id$ * */ #include <gtest/gtest.h> #include <pcl/point_types.h> #include <pcl/point_cloud.h> #include <pcl/pcl_tests.h> using namespace pcl; using namespace pcl::test; PointCloud<PointXYZ> cloud; const size_t size = 10 * 480; TEST (PointCloud, size) { EXPECT_EQ(cloud.points.size (), cloud.size ()); } TEST (PointCloud, sq_brackets_wrapper) { for (uint32_t i = 0; i < size; ++i) EXPECT_EQ_VECTORS (cloud.points[i].getVector3fMap (), cloud[i].getVector3fMap ()); } TEST (PointCloud, at) { for (uint32_t i = 0; i < size; ++i) EXPECT_EQ_VECTORS (cloud.points.at (i).getVector3fMap (), cloud.at (i).getVector3fMap ()); } TEST (PointCloud, front) { EXPECT_EQ_VECTORS (cloud.points.front ().getVector3fMap (), cloud.front ().getVector3fMap ()); } TEST (PointCloud, back) { EXPECT_EQ_VECTORS (cloud.points.back ().getVector3fMap (), cloud.back ().getVector3fMap ()); } TEST (PointCloud, constructor_with_allocation) { PointCloud<PointXYZ> cloud2 (5, 80); EXPECT_EQ (cloud2.width, 5); EXPECT_EQ (cloud2.height, 80); EXPECT_EQ (cloud2.size (), 5*80); } TEST (PointCloud, constructor_with_allocation_valued) { PointXYZ nan_point (0.1, 0.2, 0.3); PointCloud<PointXYZ> cloud2 (5, 80, nan_point); EXPECT_EQ (cloud2.width, 5); EXPECT_EQ (cloud2.height, 80); EXPECT_EQ (cloud2.size (), 5*80); for (PointCloud<PointXYZ>::const_iterator pit = cloud2.begin (); pit != cloud2.end (); ++pit) { EXPECT_NEAR (pit->x, 0.1, 1e-3); EXPECT_NEAR (pit->y, 0.2, 1e-3); EXPECT_NEAR (pit->z, 0.3, 1e-3); } } TEST (PointCloud, iterators) { EXPECT_EQ_VECTORS (cloud.begin ()->getVector3fMap (), cloud.points.begin ()->getVector3fMap ()); //EXPECT_EQ_VECTORS (cloud.end ()->getVector3fMap (), // cloud.points.end ()->getVector3fMap ()); PointCloud<PointXYZ>::const_iterator pit = cloud.begin (); PointCloud<PointXYZ>::VectorType::const_iterator pit2 = cloud.points.begin (); for (; pit < cloud.end (); ++pit2, ++pit) EXPECT_EQ_VECTORS (pit->getVector3fMap (), pit2->getVector3fMap ()); } TEST (PointCloud, insert_range) { PointCloud<PointXYZ> cloud2 (10, 1); for (uint32_t i = 0; i < 10; ++i) cloud2[i] = PointXYZ (5*i+0,5*i+1,5*i+2); uint32_t old_size = cloud.size (); cloud.insert (cloud.begin (), cloud2.begin (), cloud2.end ()); EXPECT_EQ (cloud.width, cloud.size ()); EXPECT_EQ (cloud.height, 1); EXPECT_EQ (cloud.width, old_size + cloud2.size ()); PointCloud<PointXYZ>::const_iterator pit = cloud.begin (); PointCloud<PointXYZ>::const_iterator pit2 = cloud2.begin (); for (; pit2 < cloud2.end (); ++pit2, ++pit) EXPECT_EQ_VECTORS (pit->getVector3fMap (), pit2->getVector3fMap ()); } int main (int argc, char** argv) { cloud.width = 10; cloud.height = 480; for (uint32_t i = 0; i < size; ++i) cloud.points.push_back (PointXYZ (3*i+0,3*i+1,3*i+2)); testing::InitGoogleTest (&argc, argv); return (RUN_ALL_TESTS ()); } <|endoftext|>
<commit_before>/// @file wlog_tools.cpp /// @brief Well Logs manipulation algorithms /// @author uentity /// @version 1.0 /// @date 27.02.2014 /// @copyright This source code is released under the terms of /// the BSD License. See LICENSE for more details. #ifndef WLOG_TOOLS_TMEEHO84 #define WLOG_TOOLS_TMEEHO84 #include "bs_kernel.h" #include "conf.h" #include <limits> // DEBUG //#include <iostream> namespace blue_sky { // hidden implementation namespace { typedef v_float::iterator vf_iterator; typedef v_float::const_iterator cvf_iterator; typedef v_float::reverse_iterator vf_riterator; typedef v_float::const_reverse_iterator cvf_riterator; // depth and share same iterator type template< class data_iterator, class grid_iterator, class res_iterator > void projection_impl( //const spv_float& wlog_data, const spv_float& wlog_dept, const data_iterator& p_data_begin, const data_iterator& p_data_end, const data_iterator& p_dept_begin, const data_iterator& p_dept_end, grid_iterator& p_grid, const grid_iterator& p_grid_end, res_iterator& p_res ) { // setup iterators //const cvf_iterator p_dept_begin = wlog_dept->begin(); //const cvf_iterator p_dept_end = p_dept_begin + wlog_sz; const ulong wlog_sz = std::min< ulong >(p_data_end - p_data_begin, p_dept_end - p_dept_begin); //const ulong wlog_sz = std::min(wlog_data->size(), wlog_dept->size()); if(wlog_sz == 0) return; // find starting point on well log data_iterator p_dept = std::lower_bound( p_dept_begin, p_dept_end, *p_grid ); if(p_dept == p_dept_end) // grid is fully outside of well log depths return; data_iterator p_data = p_data_begin + (p_dept - p_dept_begin); // DEBUG //std::cout << "++wlog_mean_projection:" << std::endl; //std::cout << "log_dept = [" << *p_dept << ", " << *(p_dept_end - 1) << "]" << std::endl; //std::cout << "grid = [" << *p_grid << ", " << *(p_grid_end - 1) << "]" << std::endl; // position dest grid to next boundary ++p_grid; const res_iterator p_res_end = p_res + (p_grid_end - p_grid - 1); // main cycle t_float win_sum = 0; // win_sz counts only valid numbers that fits in window // raw_sz counts all values in window, including NaNs ulong win_sz = 0, raw_sz = 0; while(p_grid != p_grid_end) { // if we reached window boundary if(*p_dept > *p_grid) { if(win_sz) *p_res = win_sum / win_sz; else if(!raw_sz && (p_dept != p_dept_begin)) { // assign prev log value only if we had no NaNs in window *p_res = *(p_data - 1); } // next step on dest grid and resulting array if(++p_res == p_res_end) break; ++p_grid; win_sum = 0; win_sz = 0; raw_sz = 0; } else { // we're inside window // check for NaN if(!(*p_data != *p_data)) { win_sum += *p_data; ++win_sz; } // count all values in raw_sz ++raw_sz; // next step in well log ++p_data; ++p_dept; if(p_dept == p_dept_end) { if(win_sz) *p_res = win_sum / win_sz; break; } } } } } // eof hidden namespace BS_API spv_float wlog_mean_projection( spv_float wlog_data, spv_float wlog_dept, spv_float dest_grid ) { // sanity spv_float res = BS_KERNEL.create_object(v_float::bs_type()); if(!wlog_data->size() || !wlog_dept->size() || dest_grid->size() < 2 || !res) return res; res->resize(dest_grid->size() - 1); // fill resulting array with NaN std::fill(res->begin(), res->end(), std::numeric_limits< double >::quiet_NaN()); // check grid ordering if(dest_grid->ss(0) < dest_grid->ss(dest_grid->size() - 1)) { // normal ordering cvf_iterator p_grid = dest_grid->begin(); const cvf_iterator p_grid_end = dest_grid->end(); vf_iterator p_res = res->begin(); // check depth ordering if(wlog_dept->ss(0) < wlog_dept->ss(wlog_dept->size() - 1)) { projection_impl( wlog_data->begin(), wlog_data->end(), wlog_dept->begin(), wlog_dept->end(), p_grid, p_grid_end, p_res ); } else { projection_impl( wlog_data->rbegin(), wlog_data->rend(), wlog_dept->rbegin(), wlog_dept->rend(), p_grid, p_grid_end, p_res ); } } else { // reversed grid ordering cvf_riterator p_grid = dest_grid->rbegin(); const cvf_riterator p_grid_end = dest_grid->rend(); vf_riterator p_res = res->rbegin(); // check depth ordering if(wlog_dept->ss(0) < wlog_dept->ss(wlog_dept->size() - 1)) { projection_impl( wlog_data->begin(), wlog_data->end(), wlog_dept->begin(), wlog_dept->end(), p_grid, p_grid_end, p_res ); } else { projection_impl( wlog_data->rbegin(), wlog_data->rend(), wlog_dept->rbegin(), wlog_dept->rend(), p_grid, p_grid_end, p_res ); } //projection_impl(wlog_data, wlog_dept, p_grid, p_grid_end, p_res); } return res; } } /* namespace blue_sky */ #endif /* end of include guard: WLOG_TOOLS_TMEEHO84 */ <commit_msg>wlog_tools: add proper BS_API_PLUGIN decorator to wlog_mean_projection()<commit_after>/// @file wlog_tools.cpp /// @brief Well Logs manipulation algorithms /// @author uentity /// @version 1.0 /// @date 27.02.2014 /// @copyright This source code is released under the terms of /// the BSD License. See LICENSE for more details. #ifndef WLOG_TOOLS_TMEEHO84 #define WLOG_TOOLS_TMEEHO84 #include "bs_kernel.h" #include "conf.h" #include <limits> // DEBUG //#include <iostream> namespace blue_sky { // hidden implementation namespace { typedef v_float::iterator vf_iterator; typedef v_float::const_iterator cvf_iterator; typedef v_float::reverse_iterator vf_riterator; typedef v_float::const_reverse_iterator cvf_riterator; // depth and share same iterator type template< class data_iterator, class grid_iterator, class res_iterator > void projection_impl( //const spv_float& wlog_data, const spv_float& wlog_dept, const data_iterator& p_data_begin, const data_iterator& p_data_end, const data_iterator& p_dept_begin, const data_iterator& p_dept_end, grid_iterator& p_grid, const grid_iterator& p_grid_end, res_iterator& p_res ) { // setup iterators //const cvf_iterator p_dept_begin = wlog_dept->begin(); //const cvf_iterator p_dept_end = p_dept_begin + wlog_sz; const ulong wlog_sz = std::min< ulong >(p_data_end - p_data_begin, p_dept_end - p_dept_begin); //const ulong wlog_sz = std::min(wlog_data->size(), wlog_dept->size()); if(wlog_sz == 0) return; // find starting point on well log data_iterator p_dept = std::lower_bound( p_dept_begin, p_dept_end, *p_grid ); if(p_dept == p_dept_end) // grid is fully outside of well log depths return; data_iterator p_data = p_data_begin + (p_dept - p_dept_begin); // DEBUG //std::cout << "++wlog_mean_projection:" << std::endl; //std::cout << "log_dept = [" << *p_dept << ", " << *(p_dept_end - 1) << "]" << std::endl; //std::cout << "grid = [" << *p_grid << ", " << *(p_grid_end - 1) << "]" << std::endl; // position dest grid to next boundary ++p_grid; const res_iterator p_res_end = p_res + (p_grid_end - p_grid - 1); // main cycle t_float win_sum = 0; // win_sz counts only valid numbers that fits in window // raw_sz counts all values in window, including NaNs ulong win_sz = 0, raw_sz = 0; while(p_grid != p_grid_end) { // if we reached window boundary if(*p_dept > *p_grid) { if(win_sz) *p_res = win_sum / win_sz; else if(!raw_sz && (p_dept != p_dept_begin)) { // assign prev log value only if we had no NaNs in window *p_res = *(p_data - 1); } // next step on dest grid and resulting array if(++p_res == p_res_end) break; ++p_grid; win_sum = 0; win_sz = 0; raw_sz = 0; } else { // we're inside window // check for NaN if(!(*p_data != *p_data)) { win_sum += *p_data; ++win_sz; } // count all values in raw_sz ++raw_sz; // next step in well log ++p_data; ++p_dept; if(p_dept == p_dept_end) { if(win_sz) *p_res = win_sum / win_sz; break; } } } } } // eof hidden namespace BS_API_PLUGIN spv_float wlog_mean_projection( spv_float wlog_data, spv_float wlog_dept, spv_float dest_grid ) { // sanity spv_float res = BS_KERNEL.create_object(v_float::bs_type()); if(!wlog_data->size() || !wlog_dept->size() || dest_grid->size() < 2 || !res) return res; res->resize(dest_grid->size() - 1); // fill resulting array with NaN std::fill(res->begin(), res->end(), std::numeric_limits< double >::quiet_NaN()); // check grid ordering if(dest_grid->ss(0) < dest_grid->ss(dest_grid->size() - 1)) { // normal ordering cvf_iterator p_grid = dest_grid->begin(); const cvf_iterator p_grid_end = dest_grid->end(); vf_iterator p_res = res->begin(); // check depth ordering if(wlog_dept->ss(0) < wlog_dept->ss(wlog_dept->size() - 1)) { projection_impl( wlog_data->begin(), wlog_data->end(), wlog_dept->begin(), wlog_dept->end(), p_grid, p_grid_end, p_res ); } else { projection_impl( wlog_data->rbegin(), wlog_data->rend(), wlog_dept->rbegin(), wlog_dept->rend(), p_grid, p_grid_end, p_res ); } } else { // reversed grid ordering cvf_riterator p_grid = dest_grid->rbegin(); const cvf_riterator p_grid_end = dest_grid->rend(); vf_riterator p_res = res->rbegin(); // check depth ordering if(wlog_dept->ss(0) < wlog_dept->ss(wlog_dept->size() - 1)) { projection_impl( wlog_data->begin(), wlog_data->end(), wlog_dept->begin(), wlog_dept->end(), p_grid, p_grid_end, p_res ); } else { projection_impl( wlog_data->rbegin(), wlog_data->rend(), wlog_dept->rbegin(), wlog_dept->rend(), p_grid, p_grid_end, p_res ); } //projection_impl(wlog_data, wlog_dept, p_grid, p_grid_end, p_res); } return res; } } /* namespace blue_sky */ #endif /* end of include guard: WLOG_TOOLS_TMEEHO84 */ <|endoftext|>
<commit_before>#include "clay.hpp" // // callableOverloads // const vector<OverloadPtr> &callableOverloads(ObjectPtr x) { switch (x->objKind) { case TYPE : { Type *y = (Type *)x.ptr(); return y->overloads; } case RECORD : { Record *y = (Record *)x.ptr(); return y->overloads; } case PROCEDURE : { Procedure *y = (Procedure *)x.ptr(); if (y->overloads.empty()) { ExprPtr target = new ObjectExpr(y); OverloadPtr z = new Overload(target, y->code, y->inlined); z->env = y->env; y->overloads.push_back(z); } return y->overloads; } case OVERLOADABLE : { Overloadable *y = (Overloadable *)x.ptr(); return y->overloads; } default : { assert(false); const vector<OverloadPtr> *ptr = NULL; return *ptr; } } } // // isStaticFlags // typedef pair<ObjectPtr, unsigned> FlagsMapKey; struct FlagsMapEntry { bool initialized; vector<bool> isStaticFlags; FlagsMapEntry() : initialized(false) {} }; static map<FlagsMapKey, FlagsMapEntry> flagsMap; static FlagsMapEntry &lookupFlagsMapEntry(ObjectPtr callable, unsigned nArgs) { return flagsMap[make_pair(callable, nArgs)]; } static void initCallable(ObjectPtr x) { switch (x->objKind) { case TYPE : { Type *y = (Type *)x.ptr(); if (!y->overloadsInitialized) initTypeOverloads(y); break; } case RECORD : { Record *y = (Record *)x.ptr(); if (!y->builtinOverloadInitialized) initBuiltinConstructor(y); break; } case PROCEDURE : case OVERLOADABLE : break; default : assert(false); } } static bool isStaticArg(FormalArgPtr farg) { switch (farg->objKind) { case VALUE_ARG : return false; case STATIC_ARG : return true; default : assert(false); return false; } } static void computeIsStaticFlags(ObjectPtr x, unsigned nArgs, vector<bool> &isStaticFlags) { initCallable(x); const vector<OverloadPtr> &overloads = callableOverloads(x); for (unsigned i = 0; i < overloads.size(); ++i) { CodePtr y = overloads[i]->code; const vector<FormalArgPtr> &fargs = y->formalArgs; if (y->hasVarArgs && (fargs.size() <= nArgs)) { for (unsigned j = 0; j < fargs.size(); ++j) isStaticFlags.push_back(isStaticArg(fargs[j])); for (unsigned j = fargs.size(); j < nArgs; ++j) isStaticFlags.push_back(false); return; } else if (fargs.size() == nArgs) { for (unsigned j = 0; j < fargs.size(); ++j) isStaticFlags.push_back(isStaticArg(fargs[j])); return; } } error("incorrect no. of arguments"); } const vector<bool> &lookupIsStaticFlags(ObjectPtr callable, unsigned nArgs) { FlagsMapEntry &entry = lookupFlagsMapEntry(callable, nArgs); if (!entry.initialized) { computeIsStaticFlags(callable, nArgs, entry.isStaticFlags); entry.initialized = true; } return entry.isStaticFlags; } bool computeArgsKey(const vector<bool> &isStaticFlags, const vector<ExprPtr> &args, EnvPtr env, vector<ObjectPtr> &argsKey, vector<ValueTempness> &argsTempness, vector<LocationPtr> &argLocations) { for (unsigned i = 0; i < args.size(); ++i) { if (isStaticFlags[i]) { ObjectPtr v = evaluateStatic(args[i], env); argsKey.push_back(v); } else { PValuePtr pv = analyzeValue(args[i], env); if (!pv) return false; argsKey.push_back(pv->type.ptr()); argsTempness.push_back(pv->isTemp ? RVALUE : LVALUE); } argLocations.push_back(args[i]->location); } return true; } // // invoke tables // static bool invokeTablesInitialized = false; static vector< vector<InvokeSetPtr> > invokeTable; static vector< vector<StaticInvokeEntryPtr> > staticInvokeTable; // // initInvokeTable // static void initInvokeTables() { assert(!invokeTablesInitialized); invokeTable.resize(16384); staticInvokeTable.resize(8192); invokeTablesInitialized = true; } // // lookupInvokeSet // InvokeSetPtr lookupInvokeSet(ObjectPtr callable, const vector<bool> &isStaticFlags, const vector<ObjectPtr> &argsKey) { if (!invokeTablesInitialized) initInvokeTables(); int h = objectHash(callable) + objectVectorHash(argsKey); h &= (invokeTable.size() - 1); vector<InvokeSetPtr> &bucket = invokeTable[h]; for (unsigned i = 0; i < bucket.size(); ++i) { InvokeSetPtr invokeSet = bucket[i]; if (objectEquals(invokeSet->callable, callable) && objectVectorEquals(invokeSet->argsKey, argsKey)) { return invokeSet; } } InvokeSetPtr invokeSet = new InvokeSet(callable, isStaticFlags, argsKey); bucket.push_back(invokeSet); return invokeSet; } StaticInvokeEntryPtr lookupStaticInvoke(ObjectPtr callable, const vector<ObjectPtr> &args) { if (!invokeTablesInitialized) initInvokeTables(); int h = objectHash(callable) + objectVectorHash(args); h &= (staticInvokeTable.size() - 1); vector<StaticInvokeEntryPtr> &bucket = staticInvokeTable[h]; for (unsigned i = 0; i < bucket.size(); ++i) { StaticInvokeEntryPtr entry = bucket[i]; if (objectEquals(entry->callable, callable) && objectVectorEquals(entry->args, args)) { return entry; } } StaticInvokeEntryPtr entry = new StaticInvokeEntry(callable, args); bucket.push_back(entry); return entry; } <commit_msg>minor improvement to error message.<commit_after>#include "clay.hpp" // // callableOverloads // const vector<OverloadPtr> &callableOverloads(ObjectPtr x) { switch (x->objKind) { case TYPE : { Type *y = (Type *)x.ptr(); return y->overloads; } case RECORD : { Record *y = (Record *)x.ptr(); return y->overloads; } case PROCEDURE : { Procedure *y = (Procedure *)x.ptr(); if (y->overloads.empty()) { ExprPtr target = new ObjectExpr(y); OverloadPtr z = new Overload(target, y->code, y->inlined); z->env = y->env; y->overloads.push_back(z); } return y->overloads; } case OVERLOADABLE : { Overloadable *y = (Overloadable *)x.ptr(); return y->overloads; } default : { assert(false); const vector<OverloadPtr> *ptr = NULL; return *ptr; } } } // // isStaticFlags // typedef pair<ObjectPtr, unsigned> FlagsMapKey; struct FlagsMapEntry { bool initialized; vector<bool> isStaticFlags; FlagsMapEntry() : initialized(false) {} }; static map<FlagsMapKey, FlagsMapEntry> flagsMap; static FlagsMapEntry &lookupFlagsMapEntry(ObjectPtr callable, unsigned nArgs) { return flagsMap[make_pair(callable, nArgs)]; } static void initCallable(ObjectPtr x) { switch (x->objKind) { case TYPE : { Type *y = (Type *)x.ptr(); if (!y->overloadsInitialized) initTypeOverloads(y); break; } case RECORD : { Record *y = (Record *)x.ptr(); if (!y->builtinOverloadInitialized) initBuiltinConstructor(y); break; } case PROCEDURE : case OVERLOADABLE : break; default : assert(false); } } static bool isStaticArg(FormalArgPtr farg) { switch (farg->objKind) { case VALUE_ARG : return false; case STATIC_ARG : return true; default : assert(false); return false; } } static void computeIsStaticFlags(ObjectPtr x, unsigned nArgs, vector<bool> &isStaticFlags) { initCallable(x); const vector<OverloadPtr> &overloads = callableOverloads(x); for (unsigned i = 0; i < overloads.size(); ++i) { CodePtr y = overloads[i]->code; const vector<FormalArgPtr> &fargs = y->formalArgs; if (y->hasVarArgs && (fargs.size() <= nArgs)) { for (unsigned j = 0; j < fargs.size(); ++j) isStaticFlags.push_back(isStaticArg(fargs[j])); for (unsigned j = fargs.size(); j < nArgs; ++j) isStaticFlags.push_back(false); return; } else if (fargs.size() == nArgs) { for (unsigned j = 0; j < fargs.size(); ++j) isStaticFlags.push_back(isStaticArg(fargs[j])); return; } } error("no matching operation"); } const vector<bool> &lookupIsStaticFlags(ObjectPtr callable, unsigned nArgs) { FlagsMapEntry &entry = lookupFlagsMapEntry(callable, nArgs); if (!entry.initialized) { computeIsStaticFlags(callable, nArgs, entry.isStaticFlags); entry.initialized = true; } return entry.isStaticFlags; } bool computeArgsKey(const vector<bool> &isStaticFlags, const vector<ExprPtr> &args, EnvPtr env, vector<ObjectPtr> &argsKey, vector<ValueTempness> &argsTempness, vector<LocationPtr> &argLocations) { for (unsigned i = 0; i < args.size(); ++i) { if (isStaticFlags[i]) { ObjectPtr v = evaluateStatic(args[i], env); argsKey.push_back(v); } else { PValuePtr pv = analyzeValue(args[i], env); if (!pv) return false; argsKey.push_back(pv->type.ptr()); argsTempness.push_back(pv->isTemp ? RVALUE : LVALUE); } argLocations.push_back(args[i]->location); } return true; } // // invoke tables // static bool invokeTablesInitialized = false; static vector< vector<InvokeSetPtr> > invokeTable; static vector< vector<StaticInvokeEntryPtr> > staticInvokeTable; // // initInvokeTable // static void initInvokeTables() { assert(!invokeTablesInitialized); invokeTable.resize(16384); staticInvokeTable.resize(8192); invokeTablesInitialized = true; } // // lookupInvokeSet // InvokeSetPtr lookupInvokeSet(ObjectPtr callable, const vector<bool> &isStaticFlags, const vector<ObjectPtr> &argsKey) { if (!invokeTablesInitialized) initInvokeTables(); int h = objectHash(callable) + objectVectorHash(argsKey); h &= (invokeTable.size() - 1); vector<InvokeSetPtr> &bucket = invokeTable[h]; for (unsigned i = 0; i < bucket.size(); ++i) { InvokeSetPtr invokeSet = bucket[i]; if (objectEquals(invokeSet->callable, callable) && objectVectorEquals(invokeSet->argsKey, argsKey)) { return invokeSet; } } InvokeSetPtr invokeSet = new InvokeSet(callable, isStaticFlags, argsKey); bucket.push_back(invokeSet); return invokeSet; } StaticInvokeEntryPtr lookupStaticInvoke(ObjectPtr callable, const vector<ObjectPtr> &args) { if (!invokeTablesInitialized) initInvokeTables(); int h = objectHash(callable) + objectVectorHash(args); h &= (staticInvokeTable.size() - 1); vector<StaticInvokeEntryPtr> &bucket = staticInvokeTable[h]; for (unsigned i = 0; i < bucket.size(); ++i) { StaticInvokeEntryPtr entry = bucket[i]; if (objectEquals(entry->callable, callable) && objectVectorEquals(entry->args, args)) { return entry; } } StaticInvokeEntryPtr entry = new StaticInvokeEntry(callable, args); bucket.push_back(entry); return entry; } <|endoftext|>
<commit_before>// // Copyright (c) 2015 CNRS // // This file is part of Pinocchio // Pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // Pinocchio 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // Pinocchio If not, see // <http://www.gnu.org/licenses/>. #ifndef __se3_python_inertia_hpp__ #define __se3_python_inertia_hpp__ #include <eigenpy/exception.hpp> #include <eigenpy/eigenpy.hpp> #include "pinocchio/spatial/inertia.hpp" namespace eigenpy { template<> struct UnalignedEquivalent<se3::Inertia> { typedef se3::InertiaTpl<double,Eigen::DontAlign> type; }; } // namespace eigenpy namespace se3 { namespace python { namespace bp = boost::python; template<typename Inertia> struct InertiaPythonVisitor : public boost::python::def_visitor< InertiaPythonVisitor<Inertia> > { typedef typename eigenpy::UnalignedEquivalent<Inertia>::type Inertia_fx; typedef typename Inertia::Matrix3 Matrix3; typedef typename Inertia::Matrix6 Matrix6; typedef typename Inertia::Vector6 Vector6; typedef typename Inertia::Vector3 Vector3; typedef typename Inertia_fx::Matrix3 Matrix3_fx; typedef typename Inertia_fx::Matrix6 Matrix6_fx; typedef typename Inertia_fx::Vector6 Vector6_fx; typedef typename Inertia_fx::Vector3 Vector3_fx; typedef typename Inertia_fx::Motion Motion_fx ; public: static PyObject* convert(Inertia const& m) { Inertia_fx m_fx = m; return bp::incref(bp::object(m_fx).ptr()); } template<class PyClass> void visit(PyClass& cl) const { cl .def("__init__", bp::make_constructor(&InertiaPythonVisitor::makeFromMCI, bp::default_call_policies(), (bp::arg("mass"),bp::arg("lever"),bp::arg("inertia"))), "Initialize from mass, lever and 3d inertia.") .add_property("mass",&Inertia_fx::mass) .add_property("lever",&InertiaPythonVisitor::lever) .add_property("inertia",&InertiaPythonVisitor::inertia) .def("matrix",&Inertia_fx::matrix) .def("se3Action",&Inertia_fx::se3Action) .def("se3ActionInverse",&Inertia_fx::se3ActionInverse) .def("__str__",&InertiaPythonVisitor::toString) .def( bp::self + bp::self) .def( bp::self * bp::other<Motion_fx>() ) .add_property("np",&Inertia_fx::matrix) .def("Identity",&Inertia_fx::Identity) .staticmethod("Identity") .def("Zero",&Inertia_fx::Zero) .staticmethod("Zero") .def("Random",&Inertia_fx::Random) .staticmethod("Random") ; } static Inertia_fx* makeFromMCI(const double & mass, const Vector3_fx & lever, const Matrix3_fx & inertia) { if(! inertia.isApprox(inertia.transpose()) ) throw eigenpy::Exception("The 3d inertia should be symmetric."); if( (Eigen::Vector3d::UnitX().transpose()*inertia*Eigen::Vector3d::UnitX()<0) || (Eigen::Vector3d::UnitY().transpose()*inertia*Eigen::Vector3d::UnitY()<0) || (Eigen::Vector3d::UnitZ().transpose()*inertia*Eigen::Vector3d::UnitZ()<0) ) throw eigenpy::Exception("The 3d inertia should be positive."); return new Inertia_fx(mass,lever,inertia); } static Matrix3_fx inertia(const Inertia_fx& Y) { return Y.inertia().matrix(); } static Vector3_fx lever(const Inertia_fx& Y) { return Y.lever(); } static std::string toString(const Inertia_fx& m) { std::ostringstream s; s << m; return s.str(); } static void expose() { bp::class_<Inertia_fx>("Inertia", "Inertia matrix, in L(se3,se3*) == R^6x6.\n\n" "Supported operations ...", bp::init<>()) .def(InertiaPythonVisitor<Inertia>()) ; bp::to_python_converter< Inertia,InertiaPythonVisitor<Inertia> >(); } }; }} // namespace se3::python #endif // ifndef __se3_python_se3_hpp__ <commit_msg>[Python] Expose new setter methods for inertia class<commit_after>// // Copyright (c) 2015 CNRS // // This file is part of Pinocchio // Pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // Pinocchio 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // Pinocchio If not, see // <http://www.gnu.org/licenses/>. #ifndef __se3_python_inertia_hpp__ #define __se3_python_inertia_hpp__ #include <eigenpy/exception.hpp> #include <eigenpy/eigenpy.hpp> #include "pinocchio/spatial/inertia.hpp" namespace eigenpy { template<> struct UnalignedEquivalent<se3::Inertia> { typedef se3::InertiaTpl<double,Eigen::DontAlign> type; }; } // namespace eigenpy namespace se3 { namespace python { namespace bp = boost::python; template<typename Inertia> struct InertiaPythonVisitor : public boost::python::def_visitor< InertiaPythonVisitor<Inertia> > { typedef typename eigenpy::UnalignedEquivalent<Inertia>::type Inertia_fx; typedef typename Inertia::Matrix3 Matrix3; typedef typename Inertia::Matrix6 Matrix6; typedef typename Inertia::Vector6 Vector6; typedef typename Inertia::Vector3 Vector3; typedef typename Inertia_fx::Matrix3 Matrix3_fx; typedef typename Inertia_fx::Matrix6 Matrix6_fx; typedef typename Inertia_fx::Vector6 Vector6_fx; typedef typename Inertia_fx::Vector3 Vector3_fx; typedef typename Inertia_fx::Motion Motion_fx ; typedef typename Inertia_fx::Scalar_t Scalar_t; public: static PyObject* convert(Inertia const& m) { Inertia_fx m_fx = m; return bp::incref(bp::object(m_fx).ptr()); } template<class PyClass> void visit(PyClass& cl) const { cl .def("__init__", bp::make_constructor(&InertiaPythonVisitor::makeFromMCI, bp::default_call_policies(), (bp::arg("mass"),bp::arg("lever"),bp::arg("inertia"))), "Initialize from mass, lever and 3d inertia.") .add_property("mass", &InertiaPythonVisitor::getMass, &InertiaPythonVisitor::setMass) .add_property("lever", &InertiaPythonVisitor::getLever, &InertiaPythonVisitor::setLever) .add_property("inertia", &InertiaPythonVisitor::getInertia, &InertiaPythonVisitor::setInertia) .def("matrix",&Inertia_fx::matrix) .def("se3Action",&Inertia_fx::se3Action) .def("se3ActionInverse",&Inertia_fx::se3ActionInverse) .def("__str__",&InertiaPythonVisitor::toString) .def( bp::self + bp::self) .def( bp::self * bp::other<Motion_fx>() ) .add_property("np",&Inertia_fx::matrix) .def("Identity",&Inertia_fx::Identity) .staticmethod("Identity") .def("Zero",&Inertia_fx::Zero) .staticmethod("Zero") .def("Random",&Inertia_fx::Random) .staticmethod("Random") ; } static Scalar_t getMass( const Inertia_fx & self ) { return self.mass(); } static void setMass( Inertia_fx & self, Scalar_t mass ) { self.mass() = mass; } static Vector3_fx getLever( const Inertia_fx & self ) { return self.lever(); } static void setLever( Inertia_fx & self, const Vector3_fx & lever ) { self.lever() = lever; } static Matrix3_fx getInertia( const Inertia_fx & self ) { return self.inertia().matrix(); } static void setInertia( Inertia_fx & self, const Vector6_fx & minimal_inertia ) { self.inertia().data() = minimal_inertia; } static Inertia_fx* makeFromMCI(const double & mass, const Vector3_fx & lever, const Matrix3_fx & inertia) { if(! inertia.isApprox(inertia.transpose()) ) throw eigenpy::Exception("The 3d inertia should be symmetric."); if( (Eigen::Vector3d::UnitX().transpose()*inertia*Eigen::Vector3d::UnitX()<0) || (Eigen::Vector3d::UnitY().transpose()*inertia*Eigen::Vector3d::UnitY()<0) || (Eigen::Vector3d::UnitZ().transpose()*inertia*Eigen::Vector3d::UnitZ()<0) ) throw eigenpy::Exception("The 3d inertia should be positive."); return new Inertia_fx(mass,lever,inertia); } static std::string toString(const Inertia_fx& m) { std::ostringstream s; s << m; return s.str(); } static void expose() { bp::class_<Inertia_fx>("Inertia", "Inertia matrix, in L(se3,se3*) == R^6x6.\n\n" "Supported operations ...", bp::init<>()) .def(InertiaPythonVisitor<Inertia>()) ; bp::to_python_converter< Inertia,InertiaPythonVisitor<Inertia> >(); } }; // struct InertiaPythonVisitor }} // namespace se3::python #endif // ifndef __se3_python_se3_hpp__ <|endoftext|>
<commit_before>#include "factory.h" #include "except.h" #ifdef USE_OPENCV #include "opencv_video_source.h" #include "opencv_video_target.h" #endif // USE_OPENCV #ifdef USE_I420 #ifdef USE_EPIPHANSDK #include "epiphansdk_video_source.h" #endif #endif #ifdef USE_FFMPEG #include "ffmpeg_video_target.h" #endif #include <boost/python.hpp> #include <boost/python/exception_translator.hpp> using namespace boost::python; class IVideoSourceWrapper : IVideoSource, wrapper<IVideoSource> { bool get_frame_dimensions(int & width, int & height) { return this->get_override("get_frame_dimensions")(width, height); } bool get_frame(VideoFrame_BGRA & frame) { return this->get_override("get_frame")(frame); } #ifdef USE_I420 bool get_frame(gg::VideoFrame_I420 & frame) { return this->get_override("get_frame")(frame); } #endif double get_frame_rate() { return this->get_override("get_frame_rate")(); } void set_sub_frame(int x, int y, int width, int height) { this->get_override("set_sub_frame")(x, y, width, height); } void get_full_frame() { this->get_override("get_full_frame")(); } }; class IVideoTargetWrapper : gg::IVideoTarget, wrapper<gg::IVideoTarget> { void init(const std::string filepath, const float framerate) { this->get_override("init")(filepath, framerate); } void append(const VideoFrame_BGRA & frame) { this->get_override("append")(frame); } void finalise() { this->get_override("finalise")(); } }; void translate_VideoSourceError(gg::VideoSourceError const & e) { std::string msg; msg.append("VideoSourceError: ").append(e.what()); PyErr_SetString(PyExc_RuntimeError, msg.c_str()); } void translate_DeviceNotFound(gg::DeviceNotFound const & e) { std::string msg; msg.append("DeviceNotFound: ").append(e.what()); PyErr_SetString(PyExc_IOError, msg.c_str()); } void translate_DeviceOffline(gg::DeviceOffline const & e) { std::string msg; msg.append("DeviceOffline: ").append(e.what()); PyErr_SetString(PyExc_IOError, msg.c_str()); } void translate_VideoTargetError(gg::VideoTargetError const & e) { std::string msg; msg.append("VideoTargetError: ").append(e.what()); PyErr_SetString(PyExc_RuntimeError, msg.c_str()); } BOOST_PYTHON_MODULE(pygiftgrab) { register_exception_translator<gg::VideoSourceError>(&translate_VideoSourceError); register_exception_translator<gg::DeviceNotFound>(&translate_DeviceNotFound); register_exception_translator<gg::DeviceOffline>(&translate_DeviceOffline); register_exception_translator<gg::VideoTargetError>(&translate_VideoTargetError); enum_<gg::Device>("Device") .value("DVI2PCIeDuo_SDI", gg::Device::DVI2PCIeDuo_SDI) .value("DVI2PCIeDuo_DVI", gg::Device::DVI2PCIeDuo_DVI) ; enum_<gg::Storage>("Storage") .value("File_HEVC", gg::Storage::File_HEVC) .value("File_XviD", gg::Storage::File_XviD) .value("File_VP9", gg::Storage::File_VP9) ; class_<VideoFrame_BGRA>("VideoFrame_BGRA", init<bool>()) .def(init<const size_t, const size_t>()) .def("rows", &VideoFrame_BGRA::rows) .def("cols", &VideoFrame_BGRA::cols) ; class_<IVideoSource, boost::noncopyable>("IVideoSource", no_init) ; #ifdef USE_OPENCV bool (VideoSourceOpenCV::*opencv_get_frame_bgra)(VideoFrame_BGRA &) = &VideoSourceOpenCV::get_frame; class_<VideoSourceOpenCV, bases<IVideoSource>, boost::noncopyable>( "VideoSourceOpenCV", init<int>()) .def(init<char *>()) .def("get_frame", opencv_get_frame_bgra) .def("get_frame_dimensions", &VideoSourceOpenCV::get_frame_dimensions) .def("get_frame_rate", &VideoSourceOpenCV::get_frame_rate) .def("set_sub_frame", &VideoSourceOpenCV::set_sub_frame) .def("get_full_frame", &VideoSourceOpenCV::get_full_frame) ; #endif // USE_OPENCV #ifdef USE_I420 class_<gg::VideoFrame_I420>("VideoFrame_I420", init<bool>()) .def(init<const size_t, const size_t>()) .def("rows", &gg::VideoFrame_I420::rows) .def("cols", &gg::VideoFrame_I420::cols) ; #ifdef USE_EPIPHANSDK bool (gg::VideoSourceEpiphanSDK::*epiphansdk_get_frame_i420)(gg::VideoFrame_I420 &) = &gg::VideoSourceEpiphanSDK::get_frame; class_<gg::VideoSourceEpiphanSDK, bases<IVideoSource>, boost::noncopyable>( "VideoSourceEpiphanSDK", init<const std::string, const V2U_INT32>()) .def("get_frame", epiphansdk_get_frame_i420) .def("get_frame_dimensions", &gg::VideoSourceEpiphanSDK::get_frame_dimensions) .def("get_frame_rate", &gg::VideoSourceEpiphanSDK::get_frame_rate) .def("set_sub_frame", &gg::VideoSourceEpiphanSDK::set_sub_frame) .def("get_full_frame", &gg::VideoSourceEpiphanSDK::get_full_frame) ; #endif #endif class_<gg::IVideoTarget, boost::noncopyable>("IVideoTarget", no_init) ; #ifdef USE_FFMPEG void (gg::VideoTargetFFmpeg::*ffmpeg_append_bgra)(const VideoFrame_BGRA &) = &gg::VideoTargetFFmpeg::append; #ifdef USE_I420 void (gg::VideoTargetFFmpeg::*ffmpeg_append_i420)(const gg::VideoFrame_I420 &) = &gg::VideoTargetFFmpeg::append; #endif class_<gg::VideoTargetFFmpeg, bases<gg::IVideoTarget>, boost::noncopyable>( "VideoTargetFFmpeg", init<std::string>()) .def("init", &gg::VideoTargetFFmpeg::init) .def("append", ffmpeg_append_bgra) #ifdef USE_I420 .def("append", ffmpeg_append_i420) #endif .def("finalise", &gg::VideoTargetFFmpeg::finalise) ; #endif #ifdef USE_OPENCV class_<gg::VideoTargetOpenCV, bases<gg::IVideoTarget>, boost::noncopyable>( "VideoTargetOpenCV", init<std::string>()) .def("init", &gg::VideoTargetOpenCV::init) .def("append", &gg::VideoTargetOpenCV::append) .def("finalise", &gg::VideoTargetOpenCV::finalise) ; #endif // USE_OPENCV class_<gg::Factory>("Factory", no_init) .def("connect", &gg::Factory::connect, /* because client should never delete returned * object on its own, but should rather call * disconnect when done */ return_value_policy<reference_existing_object>()) .staticmethod("connect") .def("disconnect", &gg::Factory::disconnect) .staticmethod("disconnect") .def("writer", &gg::Factory::writer, // because ownership is passed to client return_value_policy<manage_new_object>()) .staticmethod("writer") ; } <commit_msg>Issue #83: VLC video source exported in Python wrapper<commit_after>#include "factory.h" #include "except.h" #ifdef USE_OPENCV #include "opencv_video_source.h" #include "opencv_video_target.h" #endif // USE_OPENCV #ifdef USE_I420 #ifdef USE_EPIPHANSDK #include "epiphansdk_video_source.h" #endif #ifdef USE_LIBVLC #include "vlc_video_source.h" #endif #endif #ifdef USE_FFMPEG #include "ffmpeg_video_target.h" #endif #include <boost/python.hpp> #include <boost/python/exception_translator.hpp> using namespace boost::python; class IVideoSourceWrapper : IVideoSource, wrapper<IVideoSource> { bool get_frame_dimensions(int & width, int & height) { return this->get_override("get_frame_dimensions")(width, height); } bool get_frame(VideoFrame_BGRA & frame) { return this->get_override("get_frame")(frame); } #ifdef USE_I420 bool get_frame(gg::VideoFrame_I420 & frame) { return this->get_override("get_frame")(frame); } #endif double get_frame_rate() { return this->get_override("get_frame_rate")(); } void set_sub_frame(int x, int y, int width, int height) { this->get_override("set_sub_frame")(x, y, width, height); } void get_full_frame() { this->get_override("get_full_frame")(); } }; class IVideoTargetWrapper : gg::IVideoTarget, wrapper<gg::IVideoTarget> { void init(const std::string filepath, const float framerate) { this->get_override("init")(filepath, framerate); } void append(const VideoFrame_BGRA & frame) { this->get_override("append")(frame); } void finalise() { this->get_override("finalise")(); } }; void translate_VideoSourceError(gg::VideoSourceError const & e) { std::string msg; msg.append("VideoSourceError: ").append(e.what()); PyErr_SetString(PyExc_RuntimeError, msg.c_str()); } void translate_DeviceNotFound(gg::DeviceNotFound const & e) { std::string msg; msg.append("DeviceNotFound: ").append(e.what()); PyErr_SetString(PyExc_IOError, msg.c_str()); } void translate_DeviceOffline(gg::DeviceOffline const & e) { std::string msg; msg.append("DeviceOffline: ").append(e.what()); PyErr_SetString(PyExc_IOError, msg.c_str()); } void translate_VideoTargetError(gg::VideoTargetError const & e) { std::string msg; msg.append("VideoTargetError: ").append(e.what()); PyErr_SetString(PyExc_RuntimeError, msg.c_str()); } BOOST_PYTHON_MODULE(pygiftgrab) { register_exception_translator<gg::VideoSourceError>(&translate_VideoSourceError); register_exception_translator<gg::DeviceNotFound>(&translate_DeviceNotFound); register_exception_translator<gg::DeviceOffline>(&translate_DeviceOffline); register_exception_translator<gg::VideoTargetError>(&translate_VideoTargetError); enum_<gg::Device>("Device") .value("DVI2PCIeDuo_SDI", gg::Device::DVI2PCIeDuo_SDI) .value("DVI2PCIeDuo_DVI", gg::Device::DVI2PCIeDuo_DVI) ; enum_<gg::Storage>("Storage") .value("File_HEVC", gg::Storage::File_HEVC) .value("File_XviD", gg::Storage::File_XviD) .value("File_VP9", gg::Storage::File_VP9) ; class_<VideoFrame_BGRA>("VideoFrame_BGRA", init<bool>()) .def(init<const size_t, const size_t>()) .def("rows", &VideoFrame_BGRA::rows) .def("cols", &VideoFrame_BGRA::cols) ; class_<IVideoSource, boost::noncopyable>("IVideoSource", no_init) ; #ifdef USE_OPENCV bool (VideoSourceOpenCV::*opencv_get_frame_bgra)(VideoFrame_BGRA &) = &VideoSourceOpenCV::get_frame; class_<VideoSourceOpenCV, bases<IVideoSource>, boost::noncopyable>( "VideoSourceOpenCV", init<int>()) .def(init<char *>()) .def("get_frame", opencv_get_frame_bgra) .def("get_frame_dimensions", &VideoSourceOpenCV::get_frame_dimensions) .def("get_frame_rate", &VideoSourceOpenCV::get_frame_rate) .def("set_sub_frame", &VideoSourceOpenCV::set_sub_frame) .def("get_full_frame", &VideoSourceOpenCV::get_full_frame) ; #endif // USE_OPENCV #ifdef USE_I420 class_<gg::VideoFrame_I420>("VideoFrame_I420", init<bool>()) .def(init<const size_t, const size_t>()) .def("rows", &gg::VideoFrame_I420::rows) .def("cols", &gg::VideoFrame_I420::cols) ; #ifdef USE_EPIPHANSDK bool (gg::VideoSourceEpiphanSDK::*epiphansdk_get_frame_i420)(gg::VideoFrame_I420 &) = &gg::VideoSourceEpiphanSDK::get_frame; class_<gg::VideoSourceEpiphanSDK, bases<IVideoSource>, boost::noncopyable>( "VideoSourceEpiphanSDK", init<const std::string, const V2U_INT32>()) .def("get_frame", epiphansdk_get_frame_i420) .def("get_frame_dimensions", &gg::VideoSourceEpiphanSDK::get_frame_dimensions) .def("get_frame_rate", &gg::VideoSourceEpiphanSDK::get_frame_rate) .def("set_sub_frame", &gg::VideoSourceEpiphanSDK::set_sub_frame) .def("get_full_frame", &gg::VideoSourceEpiphanSDK::get_full_frame) ; #endif #ifdef USE_LIBVLC bool (gg::VideoSourceVLC::*vlc_get_frame_i420)(gg::VideoFrame_I420 &) = &gg::VideoSourceVLC::get_frame; class_<gg::VideoSourceVLC, bases<IVideoSource>, boost::noncopyable>( "VideoSourceVLC", init<const std::string>()) .def("get_frame", vlc_get_frame_i420) .def("get_frame_dimensions", &gg::VideoSourceVLC::get_frame_dimensions) .def("get_frame_rate", &gg::VideoSourceVLC::get_frame_rate) .def("set_sub_frame", &gg::VideoSourceVLC::set_sub_frame) .def("get_full_frame", &gg::VideoSourceVLC::get_full_frame) ; #endif #endif class_<gg::IVideoTarget, boost::noncopyable>("IVideoTarget", no_init) ; #ifdef USE_FFMPEG void (gg::VideoTargetFFmpeg::*ffmpeg_append_bgra)(const VideoFrame_BGRA &) = &gg::VideoTargetFFmpeg::append; #ifdef USE_I420 void (gg::VideoTargetFFmpeg::*ffmpeg_append_i420)(const gg::VideoFrame_I420 &) = &gg::VideoTargetFFmpeg::append; #endif class_<gg::VideoTargetFFmpeg, bases<gg::IVideoTarget>, boost::noncopyable>( "VideoTargetFFmpeg", init<std::string>()) .def("init", &gg::VideoTargetFFmpeg::init) .def("append", ffmpeg_append_bgra) #ifdef USE_I420 .def("append", ffmpeg_append_i420) #endif .def("finalise", &gg::VideoTargetFFmpeg::finalise) ; #endif #ifdef USE_OPENCV class_<gg::VideoTargetOpenCV, bases<gg::IVideoTarget>, boost::noncopyable>( "VideoTargetOpenCV", init<std::string>()) .def("init", &gg::VideoTargetOpenCV::init) .def("append", &gg::VideoTargetOpenCV::append) .def("finalise", &gg::VideoTargetOpenCV::finalise) ; #endif // USE_OPENCV class_<gg::Factory>("Factory", no_init) .def("connect", &gg::Factory::connect, /* because client should never delete returned * object on its own, but should rather call * disconnect when done */ return_value_policy<reference_existing_object>()) .staticmethod("connect") .def("disconnect", &gg::Factory::disconnect) .staticmethod("disconnect") .def("writer", &gg::Factory::writer, // because ownership is passed to client return_value_policy<manage_new_object>()) .staticmethod("writer") ; } <|endoftext|>
<commit_before>// @(#)root/tree:$Id$ // Author: Rene Brun 07/04/2001 /************************************************************************* * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TFriendElement // // // // A TFriendElement TF describes a TTree object TF in a file. // // When a TFriendElement TF is added to the the list of friends of an // // existing TTree T, any variable from TF can be referenced in a query // // to T. // // // // To add a TFriendElement to an existing TTree T, do: // // T.AddFriend("friendTreename","friendTreeFile"); // // // // See TTree::AddFriend for more information. // // // ////////////////////////////////////////////////////////////////////////// #include "TTree.h" #include "TFriendElement.h" #include "TFile.h" #include "TROOT.h" R__EXTERN TTree *gTree; ClassImp(TFriendElement) //______________________________________________________________________________ TFriendElement::TFriendElement() : TNamed() { //*-*-*-*-*-*Default constructor for a friend element*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================================= fFile = 0; fTree = 0; fOwnFile = kFALSE; fParentTree = gTree; } //______________________________________________________________________________ TFriendElement::TFriendElement(TTree *tree, const char *treename, const char *filename) :TNamed(treename,filename) { //*-*-*-*-*-*-*-*-*-*-*-*-*Create a friend element*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ====================== // // If treename is of the form "a=b", an alias called "a" is created for // treename = "b" by default the alias name is the name of the tree. fFile = 0; fTree = 0; fOwnFile = kTRUE; fParentTree = tree; fTreeName = treename; if (strchr(treename,'=')) { char *temp = Compress(treename); char *equal = strchr(temp,'='); if (!equal) return;; *equal=0; fTreeName = equal+1; SetName(temp); delete [] temp; } Connect(); } //______________________________________________________________________________ TFriendElement::TFriendElement(TTree *tree, const char *treename, TFile *file) :TNamed(treename,file?file->GetName():"") { //*-*-*-*-*-*-*-*-*-*-*-*-*Create a friend element*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ====================== // // If treename is of the form "a=b", an alias called "a" is created for // treename = "b" by default the alias name is the name of the tree. // The passed TFile is managed by the user (i.e. user must delete the TFile). fFile = file; fTree = 0; fOwnFile = kFALSE; fParentTree = tree; fTreeName = treename; if (fParentTree && fParentTree->GetDirectory() && fParentTree->GetDirectory()->GetFile() == fFile) { // The friend and the TTree are in the same file, let's not record // the filename. SetTitle(""); } if (strchr(treename,'=')) { char *temp = Compress(treename); char *equal = strchr(temp,'='); *equal=0; fTreeName = equal+1; SetName(temp); delete [] temp; } Connect(); } //______________________________________________________________________________ TFriendElement::TFriendElement(TTree *tree, TTree* friendtree, const char *alias) : TNamed(friendtree?friendtree->GetName():"", friendtree ? ( friendtree->GetDirectory() ? ( friendtree->GetDirectory()->GetFile() ? friendtree->GetDirectory()->GetFile()->GetName() : "") : "") : "") { // Create a friend element. fTree = friendtree; fTreeName = ""; fFile = 0; fOwnFile = kFALSE; fParentTree = tree; if (fTree) { fTreeName = fTree->GetName(); if (fTree->GetDirectory()) fFile = fTree->GetDirectory()->GetFile(); if (fParentTree && fParentTree->GetDirectory() && fParentTree->GetDirectory()->GetFile() == fFile) { // The friend and the TTree are in the same file, let's not record // the filename. SetTitle(""); } } if (alias && strlen(alias)) { char *temp = Compress(alias); SetName(temp); delete [] temp; } // No need to Connect. } //______________________________________________________________________________ TFriendElement::TFriendElement(const TFriendElement& tfe) : TNamed(tfe), fParentTree(tfe.fParentTree), fTree(tfe.fTree), fFile(tfe.fFile), fTreeName(tfe.fTreeName), fOwnFile(tfe.fOwnFile) { // Copy constructor } //______________________________________________________________________________ TFriendElement& TFriendElement::operator=(const TFriendElement& tfe) { // Equal operator if(this!=&tfe) { TNamed::operator=(tfe); fParentTree=tfe.fParentTree; fTree=tfe.fTree; fFile=tfe.fFile; fTreeName=tfe.fTreeName; fOwnFile=tfe.fOwnFile; } return *this; } //______________________________________________________________________________ TFriendElement::~TFriendElement() { // Destructor. Disconnect from the owning tree if needed. DisConnect(); } //_______________________________________________________________________ TTree *TFriendElement::Connect() { // Connect file and return TTree. GetFile(); return GetTree(); } //_______________________________________________________________________ TTree *TFriendElement::DisConnect() { // DisConnect file and TTree. if (fOwnFile) delete fFile; fFile = 0; fTree = 0; return 0; } //_______________________________________________________________________ TFile *TFriendElement::GetFile() { // Return pointer to TFile containing this friend TTree. if (fFile || IsZombie()) return fFile; if (strlen(GetTitle())) { TDirectory::TContext ctxt(gDirectory, 0); fFile = TFile::Open(GetTitle()); fOwnFile = kTRUE; } else { TDirectory *dir = fParentTree->GetDirectory(); if (dir) { fFile = dir->GetFile(); fOwnFile = kFALSE; } } if (fFile && fFile->IsZombie()) { MakeZombie(); delete fFile; fFile = 0; } return fFile; } //_______________________________________________________________________ TTree *TFriendElement::GetTree() { // Return pointer to friend TTree. if (fTree) return fTree; if (GetFile()) { fFile->GetObject(GetTreeName(),fTree); if (fTree) return fTree; } // This could be a memory tree or chain fTree = dynamic_cast<TTree*>( gROOT->FindObject(GetTreeName()) ); return fTree; } //_______________________________________________________________________ void TFriendElement::ls(Option_t *) const { // List this friend element. printf(" Friend Tree: %s in file: %s\n",GetName(),GetTitle()); } <commit_msg>Fix another null_return. coverity<commit_after>// @(#)root/tree:$Id$ // Author: Rene Brun 07/04/2001 /************************************************************************* * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TFriendElement // // // // A TFriendElement TF describes a TTree object TF in a file. // // When a TFriendElement TF is added to the the list of friends of an // // existing TTree T, any variable from TF can be referenced in a query // // to T. // // // // To add a TFriendElement to an existing TTree T, do: // // T.AddFriend("friendTreename","friendTreeFile"); // // // // See TTree::AddFriend for more information. // // // ////////////////////////////////////////////////////////////////////////// #include "TTree.h" #include "TFriendElement.h" #include "TFile.h" #include "TROOT.h" R__EXTERN TTree *gTree; ClassImp(TFriendElement) //______________________________________________________________________________ TFriendElement::TFriendElement() : TNamed() { //*-*-*-*-*-*Default constructor for a friend element*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ======================================= fFile = 0; fTree = 0; fOwnFile = kFALSE; fParentTree = gTree; } //______________________________________________________________________________ TFriendElement::TFriendElement(TTree *tree, const char *treename, const char *filename) :TNamed(treename,filename) { //*-*-*-*-*-*-*-*-*-*-*-*-*Create a friend element*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ====================== // // If treename is of the form "a=b", an alias called "a" is created for // treename = "b" by default the alias name is the name of the tree. fFile = 0; fTree = 0; fOwnFile = kTRUE; fParentTree = tree; fTreeName = treename; if (strchr(treename,'=')) { char *temp = Compress(treename); char *equal = strchr(temp,'='); if (!equal) return;; *equal=0; fTreeName = equal+1; SetName(temp); delete [] temp; } Connect(); } //______________________________________________________________________________ TFriendElement::TFriendElement(TTree *tree, const char *treename, TFile *file) :TNamed(treename,file?file->GetName():"") { //*-*-*-*-*-*-*-*-*-*-*-*-*Create a friend element*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ====================== // // If treename is of the form "a=b", an alias called "a" is created for // treename = "b" by default the alias name is the name of the tree. // The passed TFile is managed by the user (i.e. user must delete the TFile). fFile = file; fTree = 0; fOwnFile = kFALSE; fParentTree = tree; fTreeName = treename; if (fParentTree && fParentTree->GetDirectory() && fParentTree->GetDirectory()->GetFile() == fFile) { // The friend and the TTree are in the same file, let's not record // the filename. SetTitle(""); } if (strchr(treename,'=')) { char *temp = Compress(treename); char *equal = strchr(temp,'='); if (!equal) return;; *equal=0; fTreeName = equal+1; SetName(temp); delete [] temp; } Connect(); } //______________________________________________________________________________ TFriendElement::TFriendElement(TTree *tree, TTree* friendtree, const char *alias) : TNamed(friendtree?friendtree->GetName():"", friendtree ? ( friendtree->GetDirectory() ? ( friendtree->GetDirectory()->GetFile() ? friendtree->GetDirectory()->GetFile()->GetName() : "") : "") : "") { // Create a friend element. fTree = friendtree; fTreeName = ""; fFile = 0; fOwnFile = kFALSE; fParentTree = tree; if (fTree) { fTreeName = fTree->GetName(); if (fTree->GetDirectory()) fFile = fTree->GetDirectory()->GetFile(); if (fParentTree && fParentTree->GetDirectory() && fParentTree->GetDirectory()->GetFile() == fFile) { // The friend and the TTree are in the same file, let's not record // the filename. SetTitle(""); } } if (alias && strlen(alias)) { char *temp = Compress(alias); SetName(temp); delete [] temp; } // No need to Connect. } //______________________________________________________________________________ TFriendElement::TFriendElement(const TFriendElement& tfe) : TNamed(tfe), fParentTree(tfe.fParentTree), fTree(tfe.fTree), fFile(tfe.fFile), fTreeName(tfe.fTreeName), fOwnFile(tfe.fOwnFile) { // Copy constructor } //______________________________________________________________________________ TFriendElement& TFriendElement::operator=(const TFriendElement& tfe) { // Equal operator if(this!=&tfe) { TNamed::operator=(tfe); fParentTree=tfe.fParentTree; fTree=tfe.fTree; fFile=tfe.fFile; fTreeName=tfe.fTreeName; fOwnFile=tfe.fOwnFile; } return *this; } //______________________________________________________________________________ TFriendElement::~TFriendElement() { // Destructor. Disconnect from the owning tree if needed. DisConnect(); } //_______________________________________________________________________ TTree *TFriendElement::Connect() { // Connect file and return TTree. GetFile(); return GetTree(); } //_______________________________________________________________________ TTree *TFriendElement::DisConnect() { // DisConnect file and TTree. if (fOwnFile) delete fFile; fFile = 0; fTree = 0; return 0; } //_______________________________________________________________________ TFile *TFriendElement::GetFile() { // Return pointer to TFile containing this friend TTree. if (fFile || IsZombie()) return fFile; if (strlen(GetTitle())) { TDirectory::TContext ctxt(gDirectory, 0); fFile = TFile::Open(GetTitle()); fOwnFile = kTRUE; } else { TDirectory *dir = fParentTree->GetDirectory(); if (dir) { fFile = dir->GetFile(); fOwnFile = kFALSE; } } if (fFile && fFile->IsZombie()) { MakeZombie(); delete fFile; fFile = 0; } return fFile; } //_______________________________________________________________________ TTree *TFriendElement::GetTree() { // Return pointer to friend TTree. if (fTree) return fTree; if (GetFile()) { fFile->GetObject(GetTreeName(),fTree); if (fTree) return fTree; } // This could be a memory tree or chain fTree = dynamic_cast<TTree*>( gROOT->FindObject(GetTreeName()) ); return fTree; } //_______________________________________________________________________ void TFriendElement::ls(Option_t *) const { // List this friend element. printf(" Friend Tree: %s in file: %s\n",GetName(),GetTitle()); } <|endoftext|>
<commit_before>/******************************************************************************\ * File: appl.cpp * Purpose: Implementation of classes for syncodbcquery * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 2008-2009, Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/aboutdlg.h> #include <wx/tokenzr.h> #include <wx/extension/grid.h> #include <wx/extension/shell.h> #include <wx/extension/version.h> #include <wx/extension/report/defs.h> #include <wx/extension/report/stc.h> #include "appl.h" #ifndef __WXMSW__ #include "appl.xpm" #endif IMPLEMENT_APP(MyApp) bool MyApp::OnInit() { SetAppName("syncodbcquery"); if (!wxExApp::OnInit()) { return false; } MyFrame *frame = new MyFrame("syncodbcquery"); frame->Show(true); SetTopWindow(frame); return true; } BEGIN_EVENT_TABLE(MyFrame, wxExFrameWithHistory) EVT_CLOSE(MyFrame::OnClose) EVT_MENU(wxID_EXECUTE, MyFrame::OnCommand) EVT_MENU(wxID_PREFERENCES, MyFrame::OnCommand) EVT_MENU(ID_SHELL_COMMAND, MyFrame::OnCommand) EVT_MENU(ID_SHELL_COMMAND_STOP, MyFrame::OnCommand) EVT_MENU_RANGE(wxID_LOWEST, wxID_HIGHEST, MyFrame::OnCommand) EVT_MENU_RANGE(ID_FIRST, ID_LAST, MyFrame::OnCommand) EVT_UPDATE_UI(wxID_SAVE, MyFrame::OnUpdateUI) EVT_UPDATE_UI(wxID_SAVEAS, MyFrame::OnUpdateUI) EVT_UPDATE_UI(wxID_STOP, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_DATABASE_CLOSE, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_DATABASE_OPEN, MyFrame::OnUpdateUI) EVT_UPDATE_UI(wxID_EXECUTE, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_RECENTFILE_MENU, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_QUERY, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_RESULTS, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_STATISTICS, MyFrame::OnUpdateUI) END_EVENT_TABLE() MyFrame::MyFrame(const wxString& title) : wxExFrameWithHistory(NULL, wxID_ANY, title) , m_Running(false) , m_Stopped(false) { SetIcon(wxICON(appl)); wxExMenu* menuFile = new wxExMenu; menuFile->Append(wxID_OPEN); UseFileHistory(ID_RECENTFILE_MENU, menuFile); menuFile->AppendSeparator(); menuFile->Append(wxID_SAVE); menuFile->Append(wxID_SAVEAS); menuFile->AppendSeparator(); menuFile->Append(wxID_EXIT); wxExMenu* menuDatabase = new wxExMenu; menuDatabase->Append(ID_DATABASE_OPEN, wxExEllipsed(_("&Open"))); menuDatabase->Append(ID_DATABASE_CLOSE, _("&Close")); wxExMenu* menuQuery = new wxExMenu; menuQuery->Append(wxID_EXECUTE); menuQuery->Append(wxID_STOP); wxMenu* menuOptions = new wxMenu(); menuOptions->Append(wxID_PREFERENCES); wxMenu* menuView = new wxMenu(); menuView->AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar")); menuView->AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar")); menuView->AppendSeparator(); menuView->AppendCheckItem(ID_VIEW_QUERY, _("Query")); menuView->AppendCheckItem(ID_VIEW_RESULTS, _("Results")); menuView->AppendCheckItem(ID_VIEW_STATISTICS, _("Statistics")); wxMenu* menuHelp = new wxMenu(); menuHelp->Append(wxID_ABOUT); wxMenuBar *menubar = new wxMenuBar; menubar->Append(menuFile, _("&File")); menubar->Append(menuView, _("&View")); menubar->Append(menuDatabase, _("&Database")); menubar->Append(menuQuery, _("&Query")); menubar->Append(menuOptions, _("&Options")); menubar->Append(menuHelp, _("&Help")); SetMenuBar(menubar); m_Query = new wxExSTCWithFrame(this); m_Query->SetLexer("sql"); m_Results = new wxExGrid(this); m_Results->CreateGrid(0, 0); m_Results->EnableEditing(false); // this is a read-only grid m_Shell = new wxExSTCShell(this, ">", ";", true, 50); m_Shell->SetFocus(); GetManager().AddPane(m_Shell, wxAuiPaneInfo(). Name("CONSOLE"). CenterPane()); GetManager().AddPane(m_Results, wxAuiPaneInfo(). Name("RESULTS"). Caption(_("Results")). CloseButton(true). MaximizeButton(true)); GetManager().AddPane(m_Query, wxAuiPaneInfo(). Name("QUERY"). Caption(_("Query")). CloseButton(true). MaximizeButton(true)); GetManager().AddPane(m_Statistics.Show(this), wxAuiPaneInfo().Left(). MaximizeButton(true). Caption(_("Statistics")). Name("STATISTICS")); GetManager().LoadPerspective(wxExApp::GetConfig("Perspective")); GetManager().GetPane("QUERY").Show(false); GetManager().Update(); std::vector<wxExPane> panes; panes.push_back(wxExPane("PaneText", -3)); panes.push_back(wxExPane("PaneLines", 100, _("Lines in window"))); SetupStatusBar(panes); CreateToolBar(); m_ToolBar->AddTool(wxID_NEW); m_ToolBar->AddTool(wxID_OPEN); m_ToolBar->AddTool(wxID_SAVE); #ifdef __WXGTK__ m_ToolBar->AddTool(wxID_EXECUTE); #endif m_ToolBar->Realize(); } void MyFrame::ConfigDialogApplied(wxWindowID dialogid) { if (dialogid == wxID_PREFERENCES) { m_Query->ConfigGet(); m_Shell->ConfigGet(); } else { wxFAIL; } } void MyFrame::OnClose(wxCloseEvent& event) { if (!m_Query->Continue()) { return; } wxExApp::SetConfig("Perspective", GetManager().SavePerspective()); event.Skip(); } void MyFrame::OnCommand(wxCommandEvent& event) { switch (event.GetId()) { case wxID_ABOUT: { wxAboutDialogInfo info; info.SetIcon(GetIcon()); info.SetDescription(_("This program offers a general ODBC query.")); info.SetVersion("v1.0"); info.SetCopyright("(c) 2008-2009, Anton van Wezenbeek"); info.AddDeveloper(wxVERSION_STRING); info.AddDeveloper(wxEX_VERSION_STRING); info.AddDeveloper(wxExOTL::Version()); wxAboutBox(info); } break; case wxID_EXECUTE: m_Stopped = false; RunQueries(m_Query->GetText()); break; case wxID_EXIT: Close(true); break; case wxID_NEW: if (m_Query->FileNew()) { m_Query->SetLexer("sql"); m_Query->SetFocus(); GetManager().GetPane("QUERY").Show(); GetManager().Update(); } break; case wxID_OPEN: DialogFileOpen(wxFD_OPEN | wxFD_CHANGE_DIR, "sql files (*.sql) | *.sql", true); break; case wxID_PREFERENCES: wxExSTC::ConfigDialog(this, _("Editor Options"), wxExSTC::STC_CONFIG_MODELESS | wxExSTC::STC_CONFIG_SIMPLE | wxExSTC::STC_CONFIG_WITH_APPLY, event.GetId()); break; case wxID_SAVE: m_Query->FileSave(); break; case wxID_SAVEAS: m_Query->FileSaveAs(); break; case wxID_STOP: m_Running = false; m_Stopped = true; break; case ID_DATABASE_CLOSE: m_otl.GetConnect().logoff(); m_Shell->SetPrompt(">"); break; case ID_DATABASE_OPEN: m_otl.Logon(this, wxExApp::GetConfig()); m_Shell->SetPrompt((m_otl.IsConnected() ? wxExApp::GetConfig(_("Datasource")): "") + ">"); break; case ID_SHELL_COMMAND: if (m_otl.IsConnected()) { try { const wxString query = event.GetString().substr( 0, event.GetString().length() - 1); m_Stopped = false; RunQuery(query, true); } catch (otl_exception& p) { if (m_Results->IsShown()) { m_Results->EndBatch(); } m_Shell->AppendText(_("\nerror: ") + wxExQuoted(p.msg)); } } else { m_Shell->AppendText(_("\nnot connected")); } m_Shell->Prompt(); break; case ID_SHELL_COMMAND_STOP: m_Stopped = true; m_Shell->Prompt(_("cancelled")); break; case ID_VIEW_QUERY: TogglePane("QUERY"); break; case ID_VIEW_RESULTS: TogglePane("RESULTS"); break; case ID_VIEW_STATISTICS: TogglePane("STATISTICS"); break; default: wxFAIL; } } void MyFrame::OnUpdateUI(wxUpdateUIEvent& event) { switch (event.GetId()) { case wxID_EXECUTE: // If we have a query, you can hide it, but still run it. event.Enable(m_Query->GetLength() > 0 && m_otl.IsConnected()); break; case wxID_SAVE: event.Enable(m_Query->GetModify()); break; case wxID_SAVEAS: event.Enable(m_Query->GetLength() > 0); break; case wxID_STOP: event.Enable(m_Running); break; case ID_DATABASE_CLOSE: event.Enable(m_otl.IsConnected()); break; case ID_DATABASE_OPEN: event.Enable(!m_otl.IsConnected()); break; case ID_RECENTFILE_MENU: event.Enable(!GetRecentFile().empty()); break; case ID_VIEW_QUERY: event.Check(GetManager().GetPane("QUERY").IsShown()); break; case ID_VIEW_RESULTS: event.Check(GetManager().GetPane("RESULTS").IsShown()); break; case ID_VIEW_STATISTICS: event.Check(GetManager().GetPane("STATISTICS").IsShown()); break; default: wxFAIL; } } bool MyFrame::OpenFile( const wxExFileName& filename, int line_number, const wxString& match, long flags) { GetManager().GetPane("QUERY").Show(true); GetManager().Update(); // Take care that DialogFileOpen always results in opening in the query. // Otherwise if results are focused, the file is opened in the results. return m_Query->Open(filename, line_number, match, flags); } void MyFrame::RunQuery(const wxString& query, bool empty_results) { wxStopWatch sw; const wxString query_lower = query.Lower(); // Query functions supported by ODBC // $SQLTables, $SQLColumns, etc. // $SQLTables $1:'%' // allow you to get database schema. if (query_lower.StartsWith("select") || query_lower.StartsWith("describe") || query_lower.StartsWith("show") || query_lower.StartsWith("explain") || query_lower.StartsWith("$sql")) { long rpc; if (m_Results->IsShown()) { rpc = m_otl.Query(query, m_Results, m_Stopped, empty_results); } else { rpc = m_otl.Query(query, m_Shell, m_Stopped); } sw.Pause(); UpdateStatistics(sw, rpc); } else { const long rpc = m_otl.Query(query); sw.Pause(); UpdateStatistics(sw, rpc); } m_Shell->DocumentEnd(); } void MyFrame::RunQueries(const wxString& text) { if (m_Results->IsShown()) { m_Results->ClearGrid(); } // Skip sql comments. wxString output = text; wxRegEx("--.*$", wxRE_NEWLINE).ReplaceAll(&output, ""); // Queries are seperated by ; character. wxStringTokenizer tkz(output, ";"); int no_queries = 0; wxStopWatch sw; m_Running = true; // Run all queries. while (tkz.HasMoreTokens() && !m_Stopped) { wxString query = tkz.GetNextToken(); query.Trim(true); query.Trim(false); if (!query.empty()) { try { RunQuery(query, no_queries == 0); no_queries++; wxTheApp->Yield(); } catch (otl_exception& p) { m_Statistics.Inc(_("Number of query errors")); m_Shell->AppendText( _("\nerror: ") + wxExQuoted(p.msg) + _(" in: ") + wxExQuoted(query)); } } } m_Shell->Prompt(wxString::Format(_("\n%d queries (%.3f seconds)"), no_queries, (float)sw.Time() / (float)1000)); m_Running = false; } void MyFrame::UpdateStatistics(const wxStopWatch& sw, long rpc) { m_Shell->AppendText(wxString::Format(_("\n%d rows processed (%.3f seconds)"), rpc, (float)sw.Time() / (float)1000)); m_Statistics.Set(_("Rows processed"), rpc); m_Statistics.Set(_("Query runtime"), sw.Time()); m_Statistics.Inc(_("Total number of queries run")); m_Statistics.Inc(_("Total query runtime"), sw.Time()); m_Statistics.Inc(_("Total rows processed"), rpc); } <commit_msg>removed redundant event table entries<commit_after>/******************************************************************************\ * File: appl.cpp * Purpose: Implementation of classes for syncodbcquery * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 2008-2009, Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/aboutdlg.h> #include <wx/tokenzr.h> #include <wx/extension/grid.h> #include <wx/extension/shell.h> #include <wx/extension/version.h> #include <wx/extension/report/defs.h> #include <wx/extension/report/stc.h> #include "appl.h" #ifndef __WXMSW__ #include "appl.xpm" #endif IMPLEMENT_APP(MyApp) bool MyApp::OnInit() { SetAppName("syncodbcquery"); if (!wxExApp::OnInit()) { return false; } MyFrame *frame = new MyFrame("syncodbcquery"); frame->Show(true); SetTopWindow(frame); return true; } BEGIN_EVENT_TABLE(MyFrame, wxExFrameWithHistory) EVT_CLOSE(MyFrame::OnClose) EVT_MENU(ID_SHELL_COMMAND, MyFrame::OnCommand) EVT_MENU(ID_SHELL_COMMAND_STOP, MyFrame::OnCommand) EVT_MENU_RANGE(wxID_LOWEST, wxID_HIGHEST, MyFrame::OnCommand) EVT_MENU_RANGE(ID_FIRST, ID_LAST, MyFrame::OnCommand) EVT_UPDATE_UI(wxID_SAVE, MyFrame::OnUpdateUI) EVT_UPDATE_UI(wxID_SAVEAS, MyFrame::OnUpdateUI) EVT_UPDATE_UI(wxID_STOP, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_DATABASE_CLOSE, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_DATABASE_OPEN, MyFrame::OnUpdateUI) EVT_UPDATE_UI(wxID_EXECUTE, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_RECENTFILE_MENU, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_QUERY, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_RESULTS, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_STATISTICS, MyFrame::OnUpdateUI) END_EVENT_TABLE() MyFrame::MyFrame(const wxString& title) : wxExFrameWithHistory(NULL, wxID_ANY, title) , m_Running(false) , m_Stopped(false) { SetIcon(wxICON(appl)); wxExMenu* menuFile = new wxExMenu; menuFile->Append(wxID_OPEN); UseFileHistory(ID_RECENTFILE_MENU, menuFile); menuFile->AppendSeparator(); menuFile->Append(wxID_SAVE); menuFile->Append(wxID_SAVEAS); menuFile->AppendSeparator(); menuFile->Append(wxID_EXIT); wxExMenu* menuDatabase = new wxExMenu; menuDatabase->Append(ID_DATABASE_OPEN, wxExEllipsed(_("&Open"))); menuDatabase->Append(ID_DATABASE_CLOSE, _("&Close")); wxExMenu* menuQuery = new wxExMenu; menuQuery->Append(wxID_EXECUTE); menuQuery->Append(wxID_STOP); wxMenu* menuOptions = new wxMenu(); menuOptions->Append(wxID_PREFERENCES); wxMenu* menuView = new wxMenu(); menuView->AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar")); menuView->AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar")); menuView->AppendSeparator(); menuView->AppendCheckItem(ID_VIEW_QUERY, _("Query")); menuView->AppendCheckItem(ID_VIEW_RESULTS, _("Results")); menuView->AppendCheckItem(ID_VIEW_STATISTICS, _("Statistics")); wxMenu* menuHelp = new wxMenu(); menuHelp->Append(wxID_ABOUT); wxMenuBar *menubar = new wxMenuBar; menubar->Append(menuFile, _("&File")); menubar->Append(menuView, _("&View")); menubar->Append(menuDatabase, _("&Database")); menubar->Append(menuQuery, _("&Query")); menubar->Append(menuOptions, _("&Options")); menubar->Append(menuHelp, _("&Help")); SetMenuBar(menubar); m_Query = new wxExSTCWithFrame(this); m_Query->SetLexer("sql"); m_Results = new wxExGrid(this); m_Results->CreateGrid(0, 0); m_Results->EnableEditing(false); // this is a read-only grid m_Shell = new wxExSTCShell(this, ">", ";", true, 50); m_Shell->SetFocus(); GetManager().AddPane(m_Shell, wxAuiPaneInfo(). Name("CONSOLE"). CenterPane()); GetManager().AddPane(m_Results, wxAuiPaneInfo(). Name("RESULTS"). Caption(_("Results")). CloseButton(true). MaximizeButton(true)); GetManager().AddPane(m_Query, wxAuiPaneInfo(). Name("QUERY"). Caption(_("Query")). CloseButton(true). MaximizeButton(true)); GetManager().AddPane(m_Statistics.Show(this), wxAuiPaneInfo().Left(). MaximizeButton(true). Caption(_("Statistics")). Name("STATISTICS")); GetManager().LoadPerspective(wxExApp::GetConfig("Perspective")); GetManager().GetPane("QUERY").Show(false); GetManager().Update(); std::vector<wxExPane> panes; panes.push_back(wxExPane("PaneText", -3)); panes.push_back(wxExPane("PaneLines", 100, _("Lines in window"))); SetupStatusBar(panes); CreateToolBar(); m_ToolBar->AddTool(wxID_NEW); m_ToolBar->AddTool(wxID_OPEN); m_ToolBar->AddTool(wxID_SAVE); #ifdef __WXGTK__ m_ToolBar->AddTool(wxID_EXECUTE); #endif m_ToolBar->Realize(); } void MyFrame::ConfigDialogApplied(wxWindowID dialogid) { if (dialogid == wxID_PREFERENCES) { m_Query->ConfigGet(); m_Shell->ConfigGet(); } else { wxFAIL; } } void MyFrame::OnClose(wxCloseEvent& event) { if (!m_Query->Continue()) { return; } wxExApp::SetConfig("Perspective", GetManager().SavePerspective()); event.Skip(); } void MyFrame::OnCommand(wxCommandEvent& event) { switch (event.GetId()) { case wxID_ABOUT: { wxAboutDialogInfo info; info.SetIcon(GetIcon()); info.SetDescription(_("This program offers a general ODBC query.")); info.SetVersion("v1.0"); info.SetCopyright("(c) 2008-2009, Anton van Wezenbeek"); info.AddDeveloper(wxVERSION_STRING); info.AddDeveloper(wxEX_VERSION_STRING); info.AddDeveloper(wxExOTL::Version()); wxAboutBox(info); } break; case wxID_EXECUTE: m_Stopped = false; RunQueries(m_Query->GetText()); break; case wxID_EXIT: Close(true); break; case wxID_NEW: if (m_Query->FileNew()) { m_Query->SetLexer("sql"); m_Query->SetFocus(); GetManager().GetPane("QUERY").Show(); GetManager().Update(); } break; case wxID_OPEN: DialogFileOpen(wxFD_OPEN | wxFD_CHANGE_DIR, "sql files (*.sql) | *.sql", true); break; case wxID_PREFERENCES: wxExSTC::ConfigDialog(this, _("Editor Options"), wxExSTC::STC_CONFIG_MODELESS | wxExSTC::STC_CONFIG_SIMPLE | wxExSTC::STC_CONFIG_WITH_APPLY, event.GetId()); break; case wxID_SAVE: m_Query->FileSave(); break; case wxID_SAVEAS: m_Query->FileSaveAs(); break; case wxID_STOP: m_Running = false; m_Stopped = true; break; case ID_DATABASE_CLOSE: m_otl.GetConnect().logoff(); m_Shell->SetPrompt(">"); break; case ID_DATABASE_OPEN: m_otl.Logon(this, wxExApp::GetConfig()); m_Shell->SetPrompt((m_otl.IsConnected() ? wxExApp::GetConfig(_("Datasource")): "") + ">"); break; case ID_SHELL_COMMAND: if (m_otl.IsConnected()) { try { const wxString query = event.GetString().substr( 0, event.GetString().length() - 1); m_Stopped = false; RunQuery(query, true); } catch (otl_exception& p) { if (m_Results->IsShown()) { m_Results->EndBatch(); } m_Shell->AppendText(_("\nerror: ") + wxExQuoted(p.msg)); } } else { m_Shell->AppendText(_("\nnot connected")); } m_Shell->Prompt(); break; case ID_SHELL_COMMAND_STOP: m_Stopped = true; m_Shell->Prompt(_("cancelled")); break; case ID_VIEW_QUERY: TogglePane("QUERY"); break; case ID_VIEW_RESULTS: TogglePane("RESULTS"); break; case ID_VIEW_STATISTICS: TogglePane("STATISTICS"); break; default: wxFAIL; } } void MyFrame::OnUpdateUI(wxUpdateUIEvent& event) { switch (event.GetId()) { case wxID_EXECUTE: // If we have a query, you can hide it, but still run it. event.Enable(m_Query->GetLength() > 0 && m_otl.IsConnected()); break; case wxID_SAVE: event.Enable(m_Query->GetModify()); break; case wxID_SAVEAS: event.Enable(m_Query->GetLength() > 0); break; case wxID_STOP: event.Enable(m_Running); break; case ID_DATABASE_CLOSE: event.Enable(m_otl.IsConnected()); break; case ID_DATABASE_OPEN: event.Enable(!m_otl.IsConnected()); break; case ID_RECENTFILE_MENU: event.Enable(!GetRecentFile().empty()); break; case ID_VIEW_QUERY: event.Check(GetManager().GetPane("QUERY").IsShown()); break; case ID_VIEW_RESULTS: event.Check(GetManager().GetPane("RESULTS").IsShown()); break; case ID_VIEW_STATISTICS: event.Check(GetManager().GetPane("STATISTICS").IsShown()); break; default: wxFAIL; } } bool MyFrame::OpenFile( const wxExFileName& filename, int line_number, const wxString& match, long flags) { GetManager().GetPane("QUERY").Show(true); GetManager().Update(); // Take care that DialogFileOpen always results in opening in the query. // Otherwise if results are focused, the file is opened in the results. return m_Query->Open(filename, line_number, match, flags); } void MyFrame::RunQuery(const wxString& query, bool empty_results) { wxStopWatch sw; const wxString query_lower = query.Lower(); // Query functions supported by ODBC // $SQLTables, $SQLColumns, etc. // $SQLTables $1:'%' // allow you to get database schema. if (query_lower.StartsWith("select") || query_lower.StartsWith("describe") || query_lower.StartsWith("show") || query_lower.StartsWith("explain") || query_lower.StartsWith("$sql")) { long rpc; if (m_Results->IsShown()) { rpc = m_otl.Query(query, m_Results, m_Stopped, empty_results); } else { rpc = m_otl.Query(query, m_Shell, m_Stopped); } sw.Pause(); UpdateStatistics(sw, rpc); } else { const long rpc = m_otl.Query(query); sw.Pause(); UpdateStatistics(sw, rpc); } m_Shell->DocumentEnd(); } void MyFrame::RunQueries(const wxString& text) { if (m_Results->IsShown()) { m_Results->ClearGrid(); } // Skip sql comments. wxString output = text; wxRegEx("--.*$", wxRE_NEWLINE).ReplaceAll(&output, ""); // Queries are seperated by ; character. wxStringTokenizer tkz(output, ";"); int no_queries = 0; wxStopWatch sw; m_Running = true; // Run all queries. while (tkz.HasMoreTokens() && !m_Stopped) { wxString query = tkz.GetNextToken(); query.Trim(true); query.Trim(false); if (!query.empty()) { try { RunQuery(query, no_queries == 0); no_queries++; wxTheApp->Yield(); } catch (otl_exception& p) { m_Statistics.Inc(_("Number of query errors")); m_Shell->AppendText( _("\nerror: ") + wxExQuoted(p.msg) + _(" in: ") + wxExQuoted(query)); } } } m_Shell->Prompt(wxString::Format(_("\n%d queries (%.3f seconds)"), no_queries, (float)sw.Time() / (float)1000)); m_Running = false; } void MyFrame::UpdateStatistics(const wxStopWatch& sw, long rpc) { m_Shell->AppendText(wxString::Format(_("\n%d rows processed (%.3f seconds)"), rpc, (float)sw.Time() / (float)1000)); m_Statistics.Set(_("Rows processed"), rpc); m_Statistics.Set(_("Query runtime"), sw.Time()); m_Statistics.Inc(_("Total number of queries run")); m_Statistics.Inc(_("Total query runtime"), sw.Time()); m_Statistics.Inc(_("Total rows processed"), rpc); } <|endoftext|>
<commit_before>/******************************************************************************\ * File: appl.cpp * Purpose: Implementation of classes for syncodbcquery * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 2008-2009, Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/aboutdlg.h> #include <wx/tokenzr.h> #include <wx/extension/grid.h> #include <wx/extension/shell.h> #include <wx/extension/version.h> #include <wx/extension/report/defs.h> #include <wx/extension/report/stc.h> #include "appl.h" #include "appl.xpm" const wxString Quoted(const wxString& text) { return "'" + text + "'"; } IMPLEMENT_APP(MyApp) bool MyApp::OnInit() { SetAppName("syncodbcquery"); if (!wxExApp::OnInit()) { return false; } MyFrame *frame = new MyFrame("syncodbcquery"); frame->Show(true); SetTopWindow(frame); return true; } BEGIN_EVENT_TABLE(MyFrame, wxExFrameWithHistory) EVT_CLOSE(MyFrame::OnClose) EVT_MENU(wxID_EXECUTE, MyFrame::OnCommand) EVT_MENU(wxID_PREFERENCES, MyFrame::OnCommand) EVT_MENU(ID_SHELL_COMMAND, MyFrame::OnCommand) EVT_MENU(ID_SHELL_COMMAND_STOP, MyFrame::OnCommand) EVT_MENU_RANGE(wxID_LOWEST, wxID_HIGHEST, MyFrame::OnCommand) EVT_MENU_RANGE(ID_FIRST, ID_LAST, MyFrame::OnCommand) EVT_UPDATE_UI(wxID_SAVE, MyFrame::OnUpdateUI) EVT_UPDATE_UI(wxID_SAVEAS, MyFrame::OnUpdateUI) EVT_UPDATE_UI(wxID_STOP, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_DATABASE_CLOSE, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_DATABASE_OPEN, MyFrame::OnUpdateUI) EVT_UPDATE_UI(wxID_EXECUTE, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_RECENTFILE_MENU, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_QUERY, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_RESULTS, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_STATISTICS, MyFrame::OnUpdateUI) END_EVENT_TABLE() MyFrame::MyFrame(const wxString& title) : wxExFrameWithHistory(NULL, wxID_ANY, title) , m_Running(false) , m_Stopped(false) { SetIcon(appl_xpm); wxExMenu* menuFile = new wxExMenu; menuFile->Append(wxID_OPEN); UseFileHistory(ID_RECENTFILE_MENU, menuFile); menuFile->AppendSeparator(); menuFile->Append(wxID_SAVE); menuFile->Append(wxID_SAVEAS); menuFile->AppendSeparator(); menuFile->Append(wxID_EXIT); wxExMenu* menuDatabase = new wxExMenu; menuDatabase->Append(ID_DATABASE_OPEN, wxExEllipsed(_("&Open"))); menuDatabase->Append(ID_DATABASE_CLOSE, _("&Close")); wxExMenu* menuQuery = new wxExMenu; menuQuery->Append(wxID_EXECUTE); menuQuery->Append(wxID_STOP); wxMenu* menuOptions = new wxMenu(); menuOptions->Append(wxID_PREFERENCES); wxMenu* menuView = new wxMenu(); menuView->AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar")); menuView->AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar")); menuView->AppendSeparator(); menuView->AppendCheckItem(ID_VIEW_QUERY, _("Query")); menuView->AppendCheckItem(ID_VIEW_RESULTS, _("Results")); menuView->AppendCheckItem(ID_VIEW_STATISTICS, _("Statistics")); wxMenu* menuHelp = new wxMenu(); menuHelp->Append(wxID_ABOUT); wxMenuBar *menubar = new wxMenuBar; menubar->Append(menuFile, _("&File")); menubar->Append(menuView, _("&View")); menubar->Append(menuDatabase, _("&Database")); menubar->Append(menuQuery, _("&Query")); menubar->Append(menuOptions, _("&Options")); menubar->Append(menuHelp, _("&Help")); SetMenuBar(menubar); m_Query = new wxExSTCWithFrame(this, wxExSTC::STC_MENU_SIMPLE | wxExSTC::STC_MENU_FIND | wxExSTC::STC_MENU_REPLACE | wxExSTC::STC_MENU_INSERT); m_Query->SetLexer("sql"); m_Results = new wxExGrid(this); m_Results->CreateGrid(0, 0); m_Results->EnableEditing(false); // this is a read-only grid m_Shell = new wxExSTCShell(this, ">", ";", true, 50); m_Shell->SetFocus(); m_Shell->DocumentEnd(); m_Shell->SetLexer(); GetManager().AddPane(m_Shell, wxAuiPaneInfo(). Name("CONSOLE"). CenterPane()); GetManager().AddPane(m_Results, wxAuiPaneInfo(). Name("RESULTS"). Caption(_("Results")). CloseButton(true). MaximizeButton(true)); GetManager().AddPane(m_Query, wxAuiPaneInfo(). Name("QUERY"). Caption(_("Query")). CloseButton(true). MaximizeButton(true)); GetManager().AddPane(m_Statistics.Show(this), wxAuiPaneInfo().Left(). MaximizeButton(true). Caption(_("Statistics")). Name("STATISTICS")); GetManager().LoadPerspective(wxExApp::GetConfig("Perspective")); GetManager().GetPane("QUERY").Show(false); GetManager().Update(); std::vector<wxExPane> panes; panes.push_back(wxExPane("PaneText", -3)); panes.push_back(wxExPane("PaneLines", 100, _("Lines in window"))); SetupStatusBar(panes); CreateToolBar(); m_ToolBar->AddTool(wxID_NEW); m_ToolBar->AddTool(wxID_OPEN); m_ToolBar->AddTool(wxID_SAVE); #ifdef __WXGTK__ m_ToolBar->AddTool(wxID_EXECUTE); #endif m_ToolBar->Realize(); otl_connect::otl_initialize(); } void MyFrame::ConfigDialogApplied(wxWindowID WXUNUSED(dialogid)) { m_Query->ConfigGet(); m_Shell->ConfigGet(); } void MyFrame::OnClose(wxCloseEvent& event) { if (!m_Query->Continue()) { return; } wxExApp::SetConfig("Perspective", GetManager().SavePerspective()); m_db.logoff(); event.Skip(); } void MyFrame::OnCommand(wxCommandEvent& event) { switch (event.GetId()) { case wxID_ABOUT: { wxAboutDialogInfo info; info.SetIcon(GetIcon()); info.SetDescription(_("This program offers a general ODBC query.")); info.SetVersion("v1.0"); info.SetCopyright("(c) 2008-2009, Anton van Wezenbeek"); info.AddDeveloper(wxVERSION_STRING); info.AddDeveloper(wxEX_VERSION_STRING); info.AddDeveloper(wxExOTLVersion()); wxAboutBox(info); } break; case wxID_EXECUTE: m_Stopped = false; RunQueries(m_Query->GetText()); break; case wxID_EXIT: Close(true); break; case wxID_NEW: if (m_Query->FileNew()) { m_Query->SetLexer("sql"); m_Query->SetFocus(); GetManager().GetPane("QUERY").Show(); GetManager().Update(); } break; case wxID_OPEN: DialogFileOpen(wxFD_OPEN | wxFD_CHANGE_DIR, "sql files (*.sql) | *.sql", true); break; case wxID_PREFERENCES: wxExSTC::ConfigDialog(_("Editor Options"), wxExSTC::STC_CONFIG_SIMPLE | wxExSTC::STC_CONFIG_MODELESS); break; case wxID_SAVE: m_Query->FileSave(); break; case wxID_SAVEAS: m_Query->FileSaveAs(); break; case wxID_STOP: m_Running = false; m_Stopped = true; break; case ID_DATABASE_CLOSE: m_db.logoff(); m_Shell->SetPrompt(">"); break; case ID_DATABASE_OPEN: wxExOTLDialog(wxExApp::GetConfig(), &m_db); m_Shell->SetPrompt((m_db.connected ? wxExApp::GetConfig(_("Datasource")): "") + ">"); break; case ID_SHELL_COMMAND: if (m_db.connected) { try { const wxString query = event.GetString().substr( 0, event.GetString().length() - 1); m_Stopped = false; RunQuery(query, true); } catch (otl_exception& p) { if (m_Results->IsShown()) { m_Results->EndBatch(); } m_Shell->AppendText(_("\nerror: ") + Quoted(p.msg)); } } else { m_Shell->AppendText(_("\nnot connected")); } m_Shell->Prompt(); break; case ID_SHELL_COMMAND_STOP: m_Stopped = true; m_Shell->Prompt("Cancelled"); break; case ID_VIEW_QUERY: TogglePane("QUERY"); break; case ID_VIEW_RESULTS: TogglePane("RESULTS"); break; case ID_VIEW_STATISTICS: TogglePane("STATISTICS"); break; default: event.Skip(); } } void MyFrame::OnUpdateUI(wxUpdateUIEvent& event) { switch (event.GetId()) { case wxID_EXECUTE: // If we have a query, you can hide it, but still run it. event.Enable(m_Query->GetLength() > 0 && m_db.connected); break; case wxID_SAVE: event.Enable(m_Query->GetModify()); break; case wxID_SAVEAS: event.Enable(m_Query->GetLength() > 0); break; case wxID_STOP: event.Enable(m_Running); break; case ID_DATABASE_CLOSE: event.Enable(m_db.connected > 0); break; case ID_DATABASE_OPEN: event.Enable(!m_db.connected); break; case ID_RECENTFILE_MENU: event.Enable(!GetRecentFile().empty()); break; case ID_VIEW_QUERY: event.Check(GetManager().GetPane("QUERY").IsShown()); break; case ID_VIEW_RESULTS: event.Check(GetManager().GetPane("RESULTS").IsShown()); break; case ID_VIEW_STATISTICS: event.Check(GetManager().GetPane("STATISTICS").IsShown()); break; default: wxFAIL; } } bool MyFrame::OpenFile( const wxExFileName& filename, int line_number, const wxString& match, long flags) { GetManager().GetPane("QUERY").Show(true); GetManager().Update(); // Take care that DialogFileOpen always results in opening in the query. // Otherwise if results are focused, the file is opened in the results. return m_Query->Open(filename, line_number, match, flags); } void MyFrame::RunQuery(const wxString& query, bool empty_results) { wxStopWatch sw; const wxString query_lower = query.Lower(); // Query functions supported by ODBC // $SQLTables, $SQLColumns, etc. // $SQLTables $1:'%' // allow you to get database schema. if (query_lower.StartsWith("select") || query_lower.StartsWith("describe") || query_lower.StartsWith("show") || query_lower.StartsWith("explain") || query_lower.StartsWith("$sql")) { long rpc; if (m_Results->IsShown()) { rpc = wxExOTLQueryToGrid(&m_db, query, m_Results, m_Stopped, empty_results); } else { rpc = wxExOTLQueryToSTC(&m_db, query, m_Shell, m_Stopped); } sw.Pause(); UpdateStatistics(sw, rpc); } else { const long rpc = otl_cursor::direct_exec(m_db, query.c_str()); sw.Pause(); UpdateStatistics(sw, rpc); } m_Shell->DocumentEnd(); } void MyFrame::RunQueries(const wxString& text) { if (m_Results->IsShown()) { m_Results->ClearGrid(); } // Skip sql comments. wxString output = text; wxRegEx("--.*$", wxRE_NEWLINE).ReplaceAll(&output, ""); // Queries are seperated by ; character. wxStringTokenizer tkz(output, ";"); int no_queries = 0; wxStopWatch sw; m_Running = true; // Run all queries. while (tkz.HasMoreTokens() && !m_Stopped) { wxString query = tkz.GetNextToken(); query.Trim(true); query.Trim(false); if (!query.empty()) { try { RunQuery(query, no_queries == 0); no_queries++; wxYield(); } catch (otl_exception& p) { m_Statistics.Inc(_("Number of query errors")); m_Shell->AppendText(_("\nerror: ") + Quoted(p.msg) + _(" in: ") + Quoted(query)); } } } m_Shell->Prompt(wxString::Format(_("\n%d queries (%.3f seconds)"), no_queries, (float)sw.Time() / (float)1000)); m_Running = false; } void MyFrame::UpdateStatistics(const wxStopWatch& sw, long rpc) { m_Shell->AppendText(wxString::Format(_("\n%d rows processed (%.3f seconds)"), rpc, (float)sw.Time() / (float)1000)); m_Statistics.Set(_("Rows processed"), rpc); m_Statistics.Set(_("Query runtime"), sw.Time()); m_Statistics.Inc(_("Total number of queries run")); m_Statistics.Inc(_("Total query runtime"), sw.Time()); m_Statistics.Inc(_("Total rows processed"), rpc); } <commit_msg>made canceled translatable<commit_after>/******************************************************************************\ * File: appl.cpp * Purpose: Implementation of classes for syncodbcquery * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 2008-2009, Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/aboutdlg.h> #include <wx/tokenzr.h> #include <wx/extension/grid.h> #include <wx/extension/shell.h> #include <wx/extension/version.h> #include <wx/extension/report/defs.h> #include <wx/extension/report/stc.h> #include "appl.h" #include "appl.xpm" const wxString Quoted(const wxString& text) { return "'" + text + "'"; } IMPLEMENT_APP(MyApp) bool MyApp::OnInit() { SetAppName("syncodbcquery"); if (!wxExApp::OnInit()) { return false; } MyFrame *frame = new MyFrame("syncodbcquery"); frame->Show(true); SetTopWindow(frame); return true; } BEGIN_EVENT_TABLE(MyFrame, wxExFrameWithHistory) EVT_CLOSE(MyFrame::OnClose) EVT_MENU(wxID_EXECUTE, MyFrame::OnCommand) EVT_MENU(wxID_PREFERENCES, MyFrame::OnCommand) EVT_MENU(ID_SHELL_COMMAND, MyFrame::OnCommand) EVT_MENU(ID_SHELL_COMMAND_STOP, MyFrame::OnCommand) EVT_MENU_RANGE(wxID_LOWEST, wxID_HIGHEST, MyFrame::OnCommand) EVT_MENU_RANGE(ID_FIRST, ID_LAST, MyFrame::OnCommand) EVT_UPDATE_UI(wxID_SAVE, MyFrame::OnUpdateUI) EVT_UPDATE_UI(wxID_SAVEAS, MyFrame::OnUpdateUI) EVT_UPDATE_UI(wxID_STOP, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_DATABASE_CLOSE, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_DATABASE_OPEN, MyFrame::OnUpdateUI) EVT_UPDATE_UI(wxID_EXECUTE, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_RECENTFILE_MENU, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_QUERY, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_RESULTS, MyFrame::OnUpdateUI) EVT_UPDATE_UI(ID_VIEW_STATISTICS, MyFrame::OnUpdateUI) END_EVENT_TABLE() MyFrame::MyFrame(const wxString& title) : wxExFrameWithHistory(NULL, wxID_ANY, title) , m_Running(false) , m_Stopped(false) { SetIcon(appl_xpm); wxExMenu* menuFile = new wxExMenu; menuFile->Append(wxID_OPEN); UseFileHistory(ID_RECENTFILE_MENU, menuFile); menuFile->AppendSeparator(); menuFile->Append(wxID_SAVE); menuFile->Append(wxID_SAVEAS); menuFile->AppendSeparator(); menuFile->Append(wxID_EXIT); wxExMenu* menuDatabase = new wxExMenu; menuDatabase->Append(ID_DATABASE_OPEN, wxExEllipsed(_("&Open"))); menuDatabase->Append(ID_DATABASE_CLOSE, _("&Close")); wxExMenu* menuQuery = new wxExMenu; menuQuery->Append(wxID_EXECUTE); menuQuery->Append(wxID_STOP); wxMenu* menuOptions = new wxMenu(); menuOptions->Append(wxID_PREFERENCES); wxMenu* menuView = new wxMenu(); menuView->AppendCheckItem(ID_VIEW_STATUSBAR, _("&Statusbar")); menuView->AppendCheckItem(ID_VIEW_TOOLBAR, _("&Toolbar")); menuView->AppendSeparator(); menuView->AppendCheckItem(ID_VIEW_QUERY, _("Query")); menuView->AppendCheckItem(ID_VIEW_RESULTS, _("Results")); menuView->AppendCheckItem(ID_VIEW_STATISTICS, _("Statistics")); wxMenu* menuHelp = new wxMenu(); menuHelp->Append(wxID_ABOUT); wxMenuBar *menubar = new wxMenuBar; menubar->Append(menuFile, _("&File")); menubar->Append(menuView, _("&View")); menubar->Append(menuDatabase, _("&Database")); menubar->Append(menuQuery, _("&Query")); menubar->Append(menuOptions, _("&Options")); menubar->Append(menuHelp, _("&Help")); SetMenuBar(menubar); m_Query = new wxExSTCWithFrame(this, wxExSTC::STC_MENU_SIMPLE | wxExSTC::STC_MENU_FIND | wxExSTC::STC_MENU_REPLACE | wxExSTC::STC_MENU_INSERT); m_Query->SetLexer("sql"); m_Results = new wxExGrid(this); m_Results->CreateGrid(0, 0); m_Results->EnableEditing(false); // this is a read-only grid m_Shell = new wxExSTCShell(this, ">", ";", true, 50); m_Shell->SetFocus(); m_Shell->DocumentEnd(); m_Shell->SetLexer(); GetManager().AddPane(m_Shell, wxAuiPaneInfo(). Name("CONSOLE"). CenterPane()); GetManager().AddPane(m_Results, wxAuiPaneInfo(). Name("RESULTS"). Caption(_("Results")). CloseButton(true). MaximizeButton(true)); GetManager().AddPane(m_Query, wxAuiPaneInfo(). Name("QUERY"). Caption(_("Query")). CloseButton(true). MaximizeButton(true)); GetManager().AddPane(m_Statistics.Show(this), wxAuiPaneInfo().Left(). MaximizeButton(true). Caption(_("Statistics")). Name("STATISTICS")); GetManager().LoadPerspective(wxExApp::GetConfig("Perspective")); GetManager().GetPane("QUERY").Show(false); GetManager().Update(); std::vector<wxExPane> panes; panes.push_back(wxExPane("PaneText", -3)); panes.push_back(wxExPane("PaneLines", 100, _("Lines in window"))); SetupStatusBar(panes); CreateToolBar(); m_ToolBar->AddTool(wxID_NEW); m_ToolBar->AddTool(wxID_OPEN); m_ToolBar->AddTool(wxID_SAVE); #ifdef __WXGTK__ m_ToolBar->AddTool(wxID_EXECUTE); #endif m_ToolBar->Realize(); otl_connect::otl_initialize(); } void MyFrame::ConfigDialogApplied(wxWindowID WXUNUSED(dialogid)) { m_Query->ConfigGet(); m_Shell->ConfigGet(); } void MyFrame::OnClose(wxCloseEvent& event) { if (!m_Query->Continue()) { return; } wxExApp::SetConfig("Perspective", GetManager().SavePerspective()); m_db.logoff(); event.Skip(); } void MyFrame::OnCommand(wxCommandEvent& event) { switch (event.GetId()) { case wxID_ABOUT: { wxAboutDialogInfo info; info.SetIcon(GetIcon()); info.SetDescription(_("This program offers a general ODBC query.")); info.SetVersion("v1.0"); info.SetCopyright("(c) 2008-2009, Anton van Wezenbeek"); info.AddDeveloper(wxVERSION_STRING); info.AddDeveloper(wxEX_VERSION_STRING); info.AddDeveloper(wxExOTLVersion()); wxAboutBox(info); } break; case wxID_EXECUTE: m_Stopped = false; RunQueries(m_Query->GetText()); break; case wxID_EXIT: Close(true); break; case wxID_NEW: if (m_Query->FileNew()) { m_Query->SetLexer("sql"); m_Query->SetFocus(); GetManager().GetPane("QUERY").Show(); GetManager().Update(); } break; case wxID_OPEN: DialogFileOpen(wxFD_OPEN | wxFD_CHANGE_DIR, "sql files (*.sql) | *.sql", true); break; case wxID_PREFERENCES: wxExSTC::ConfigDialog(_("Editor Options"), wxExSTC::STC_CONFIG_SIMPLE | wxExSTC::STC_CONFIG_MODELESS); break; case wxID_SAVE: m_Query->FileSave(); break; case wxID_SAVEAS: m_Query->FileSaveAs(); break; case wxID_STOP: m_Running = false; m_Stopped = true; break; case ID_DATABASE_CLOSE: m_db.logoff(); m_Shell->SetPrompt(">"); break; case ID_DATABASE_OPEN: wxExOTLDialog(wxExApp::GetConfig(), &m_db); m_Shell->SetPrompt((m_db.connected ? wxExApp::GetConfig(_("Datasource")): "") + ">"); break; case ID_SHELL_COMMAND: if (m_db.connected) { try { const wxString query = event.GetString().substr( 0, event.GetString().length() - 1); m_Stopped = false; RunQuery(query, true); } catch (otl_exception& p) { if (m_Results->IsShown()) { m_Results->EndBatch(); } m_Shell->AppendText(_("\nerror: ") + Quoted(p.msg)); } } else { m_Shell->AppendText(_("\nnot connected")); } m_Shell->Prompt(); break; case ID_SHELL_COMMAND_STOP: m_Stopped = true; m_Shell->Prompt(_("cancelled")); break; case ID_VIEW_QUERY: TogglePane("QUERY"); break; case ID_VIEW_RESULTS: TogglePane("RESULTS"); break; case ID_VIEW_STATISTICS: TogglePane("STATISTICS"); break; default: event.Skip(); } } void MyFrame::OnUpdateUI(wxUpdateUIEvent& event) { switch (event.GetId()) { case wxID_EXECUTE: // If we have a query, you can hide it, but still run it. event.Enable(m_Query->GetLength() > 0 && m_db.connected); break; case wxID_SAVE: event.Enable(m_Query->GetModify()); break; case wxID_SAVEAS: event.Enable(m_Query->GetLength() > 0); break; case wxID_STOP: event.Enable(m_Running); break; case ID_DATABASE_CLOSE: event.Enable(m_db.connected > 0); break; case ID_DATABASE_OPEN: event.Enable(!m_db.connected); break; case ID_RECENTFILE_MENU: event.Enable(!GetRecentFile().empty()); break; case ID_VIEW_QUERY: event.Check(GetManager().GetPane("QUERY").IsShown()); break; case ID_VIEW_RESULTS: event.Check(GetManager().GetPane("RESULTS").IsShown()); break; case ID_VIEW_STATISTICS: event.Check(GetManager().GetPane("STATISTICS").IsShown()); break; default: wxFAIL; } } bool MyFrame::OpenFile( const wxExFileName& filename, int line_number, const wxString& match, long flags) { GetManager().GetPane("QUERY").Show(true); GetManager().Update(); // Take care that DialogFileOpen always results in opening in the query. // Otherwise if results are focused, the file is opened in the results. return m_Query->Open(filename, line_number, match, flags); } void MyFrame::RunQuery(const wxString& query, bool empty_results) { wxStopWatch sw; const wxString query_lower = query.Lower(); // Query functions supported by ODBC // $SQLTables, $SQLColumns, etc. // $SQLTables $1:'%' // allow you to get database schema. if (query_lower.StartsWith("select") || query_lower.StartsWith("describe") || query_lower.StartsWith("show") || query_lower.StartsWith("explain") || query_lower.StartsWith("$sql")) { long rpc; if (m_Results->IsShown()) { rpc = wxExOTLQueryToGrid(&m_db, query, m_Results, m_Stopped, empty_results); } else { rpc = wxExOTLQueryToSTC(&m_db, query, m_Shell, m_Stopped); } sw.Pause(); UpdateStatistics(sw, rpc); } else { const long rpc = otl_cursor::direct_exec(m_db, query.c_str()); sw.Pause(); UpdateStatistics(sw, rpc); } m_Shell->DocumentEnd(); } void MyFrame::RunQueries(const wxString& text) { if (m_Results->IsShown()) { m_Results->ClearGrid(); } // Skip sql comments. wxString output = text; wxRegEx("--.*$", wxRE_NEWLINE).ReplaceAll(&output, ""); // Queries are seperated by ; character. wxStringTokenizer tkz(output, ";"); int no_queries = 0; wxStopWatch sw; m_Running = true; // Run all queries. while (tkz.HasMoreTokens() && !m_Stopped) { wxString query = tkz.GetNextToken(); query.Trim(true); query.Trim(false); if (!query.empty()) { try { RunQuery(query, no_queries == 0); no_queries++; wxYield(); } catch (otl_exception& p) { m_Statistics.Inc(_("Number of query errors")); m_Shell->AppendText(_("\nerror: ") + Quoted(p.msg) + _(" in: ") + Quoted(query)); } } } m_Shell->Prompt(wxString::Format(_("\n%d queries (%.3f seconds)"), no_queries, (float)sw.Time() / (float)1000)); m_Running = false; } void MyFrame::UpdateStatistics(const wxStopWatch& sw, long rpc) { m_Shell->AppendText(wxString::Format(_("\n%d rows processed (%.3f seconds)"), rpc, (float)sw.Time() / (float)1000)); m_Statistics.Set(_("Rows processed"), rpc); m_Statistics.Set(_("Query runtime"), sw.Time()); m_Statistics.Inc(_("Total number of queries run")); m_Statistics.Inc(_("Total query runtime"), sw.Time()); m_Statistics.Inc(_("Total rows processed"), rpc); } <|endoftext|>
<commit_before>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */ /* ------------------------------------------------------------------------- ATS License: see $ATS_DIR/COPYRIGHT Author: Markus Berndt Interface for the Volumetric Deformation PK. <ParameterList name="volumetric deformation"> <Parameter name="PK model" type="string" value="Prescibed Mesh Deformation"/> <Parameter name="Deformation method" type="string" value="method name"/> </ParameterList> ------------------------------------------------------------------------- */ #include "Teuchos_XMLParameterListHelpers.hpp" #include "NKAOperator.hh" #include "composite_vector_function_factory.hh" #include "volumetric_deformation.hh" #include "porosity_evaluator.hh" namespace Amanzi { namespace Deform { using namespace Amanzi::AmanziMesh; RegisteredPKFactory<VolumetricDeformation> VolumetricDeformation::reg_("volumetric deformation"); VolumetricDeformation::VolumetricDeformation(Teuchos::ParameterList& plist, const Teuchos::RCP<TreeVector>& solution): PKDefaultBase(plist,solution), PKPhysicalBase(plist,solution) { poro_key_ = plist_.get<std::string>("porosity key","porosity"); } // -- Setup data void VolumetricDeformation::setup(const Teuchos::Ptr<State>& S) { PKPhysicalBase::setup(S); // save the meshes mesh_nc_ = Teuchos::rcp_const_cast<AmanziMesh::Mesh>(mesh_); if (S->HasMesh("surface")) { surf_mesh_ = S->GetMesh("surface"); surf3d_mesh_ = S->GetMesh("surface_3d"); surf_mesh_nc_ = Teuchos::rcp_const_cast<AmanziMesh::Mesh>(surf_mesh_); surf3d_mesh_nc_ = Teuchos::rcp_const_cast<AmanziMesh::Mesh>(surf3d_mesh_); } // create storage for primary variable, rock volume Teuchos::RCP<CompositeVectorFactory> rv_fac = S->RequireField(key_, name_); rv_fac->SetMesh(mesh_)->SetGhosted() ->SetComponent("cell", AmanziMesh::CELL, 1); // Create storage and a function for cell volume change Teuchos::RCP<CompositeVectorFactory> cv_fac = S->RequireField("dcell_volume_dtime", name_); cv_fac->Update(*rv_fac); Teuchos::ParameterList func_plist = plist_.sublist("deformation function"); deform_func_ = Functions::CreateCompositeVectorFunction(func_plist, *cv_fac); // create storage for the vertex coordinates // we need to checkpoint those to be able to create // the deformed mesh after restart int dim = mesh_->space_dimension(); S->RequireField("vertex coordinate", name_)->SetMesh(mesh_)->SetGhosted() ->SetComponent("node", AmanziMesh::NODE, dim); S->RequireFieldEvaluator("cell_volume"); S->RequireFieldEvaluator("porosity"); S->RequireField("porosity")->SetMesh(mesh_)->SetGhosted() ->AddComponent("cell",AmanziMesh::CELL,1); // solve method Teuchos::ParameterList op_plist = plist_.sublist("global solve operator"); // collect a set of the fixed nodes std::vector<std::string> bottom_regions; if (op_plist.isParameter("bottom region")) { bottom_regions.push_back(op_plist.get<std::string>("bottom region")); } else { bottom_regions = op_plist.get<Teuchos::Array<std::string> >("bottom regions").toVector(); } std::string bottom_region_type = op_plist.get<std::string>("bottom region type","node"); std::set<AmanziMesh::Entity_ID> bottom_node_set; for (std::vector<std::string>::const_iterator region=bottom_regions.begin(); region!=bottom_regions.end(); ++region) { if (bottom_region_type == "node") { AmanziMesh::Entity_ID_List region_nodes; mesh_->get_set_entities(*region, AmanziMesh::NODE, AmanziMesh::OWNED,&region_nodes); bottom_node_set.insert(region_nodes.begin(), region_nodes.end()); } else if (bottom_region_type == "face") { AmanziMesh::Entity_ID_List region_faces; mesh_->get_set_entities(*region, AmanziMesh::FACE, AmanziMesh::OWNED,&region_faces); for (AmanziMesh::Entity_ID_List::const_iterator f=region_faces.begin(); f!=region_faces.end(); ++f) { AmanziMesh::Entity_ID_List face_nodes; mesh_->face_get_nodes(*f, &face_nodes); bottom_node_set.insert(face_nodes.begin(), face_nodes.end()); } } else { Errors::Message mesg("Invalid bottom region type (must be node or face)"); Exceptions::amanzi_throw(mesg); } } // create the unique list of owned bottom nodes unsigned int nnodes_owned = mesh_->num_entities(AmanziMesh::NODE, AmanziMesh::OWNED); Teuchos::RCP<AmanziMesh::Entity_ID_List> bottom_node_list = Teuchos::rcp(new AmanziMesh::Entity_ID_List()); for (std::set<AmanziMesh::Entity_ID>::const_iterator n=bottom_node_set.begin(); n!=bottom_node_set.end(); ++n) { if (*n < nnodes_owned) bottom_node_list->push_back(*n); } // create the operator def_matrix_ = Teuchos::rcp(new Operators::MatrixVolumetricDeformation(op_plist, mesh_, bottom_node_list)); if (op_plist.isSublist("NKA Solver")) { Teuchos::ParameterList solver_plist = op_plist.sublist("NKA Solver"); operator_ = Teuchos::rcp( new NKAOperator<CompositeMatrix,CompositeVector, CompositeVectorFactory>(solver_plist,def_matrix_)); } else { operator_ = def_matrix_; } // create storage for the nodal deformation S->RequireField("nodal_dz", name_)->SetMesh(mesh_)->SetGhosted() ->SetComponent("node", AmanziMesh::NODE, 1); } // -- Initialize owned (dependent) variables. void VolumetricDeformation::initialize(const Teuchos::Ptr<State>& S) { PKPhysicalBase::initialize(S); // the PK's initial condition sets the initial porosity. From this, we // calculate the actual initial condition, which is the rock volume. Epetra_MultiVector& rock_vol = *S->GetFieldData(key_,name_) ->ViewComponent("cell",false); int ncells = rock_vol.MyLength(); for (int c=0; c!=ncells; ++c) { rock_vol[0][c] = (1.0 - rock_vol[0][c]) * mesh_->cell_volume(c); } // initialize the deformation rate to 0 S->GetFieldData("dcell_volume_dtime",name_)->PutScalar(0.); S->GetField("dcell_volume_dtime",name_)->set_initialized(); // initialize the plane displacement to be zero S->GetFieldData("nodal_dz",name_)->PutScalar(0.); S->GetField("nodal_dz",name_)->set_initialized(); { // initialize the vertex coordinate to the current mesh int dim = mesh_->space_dimension(); AmanziGeometry::Point coords; coords.init(dim); int nnodes = mesh_->num_entities(Amanzi::AmanziMesh::NODE, Amanzi::AmanziMesh::OWNED); Epetra_MultiVector& vc = *S->GetFieldData("vertex coordinate",name_) ->ViewComponent("node",false); // search the id of the mid point on the top for (int iV=0; iV!=nnodes; ++iV) { // get the coords of the node mesh_->node_get_coordinates(iV,&coords); for (int s=0; s!=dim; ++s) vc[s][iV] = coords[s]; } } S->GetField("vertex coordinate",name_)->set_initialized(); } bool VolumetricDeformation::advance(double dt) { Teuchos::OSTab tab = getOSTab(); if (out_.get() && includesVerbLevel(verbosity_, Teuchos::VERB_MEDIUM, true)) { *out_ << "Advancing deformation PK from time " << S_->time() << " to " << S_next_->time() << " with step size " << dt << std::endl; *out_ << "----------------------------------------------------------------" << std::endl; } double ss = S_next_->time(); double ss0 = S_->time(); double dT = ss - ss0; double T_mid = (ss + ss0) / 2.; const Epetra_MultiVector& cv = *S_->GetFieldData("cell_volume") ->ViewComponent("cell",false); const Epetra_MultiVector& poro = *S_->GetFieldData(poro_key_) ->ViewComponent("cell",false); // Evaluate the function at the mean time to get d(cv)/dT Teuchos::RCP<CompositeVector> dcell_vol_vec = S_next_->GetFieldData("dcell_volume_dtime", name_); dcell_vol_vec->PutScalar(0.); deform_func_->Compute(T_mid, dcell_vol_vec.ptr()); { // scale by cell volume, this is fractional loss Epetra_MultiVector& dcell_vol_c = *dcell_vol_vec->ViewComponent("cell",false); for (int c=0; c!=dcell_vol_c.MyLength(); ++c) { dcell_vol_c[0][c] *= cv[0][c] * dT; } } // calculate the nodal deformation Teuchos::RCP<CompositeVector> nodal_dz_vec = S_next_->GetFieldData("nodal_dz",name_); Teuchos::RCP<CompositeVector> rhs = Teuchos::rcp(new CompositeVector(*nodal_dz_vec)); def_matrix_->ApplyRHS(*dcell_vol_vec, rhs.ptr()); operator_->ApplyInverse(*rhs, nodal_dz_vec.ptr()); // form list of deformed nodes Entity_ID_List nodeids; AmanziGeometry::Point_List newpos; Amanzi::AmanziGeometry::Point coords, new_coords; int dim = mesh_->space_dimension(); new_coords.init(dim); nodal_dz_vec->ScatterMasterToGhosted("node",true); // WORKAROUND for non-communication in deform() by Mesh // const Epetra_MultiVector& nodal_dz_l = // *nodal_dz_vec->ViewComponent("node",false); const Epetra_MultiVector& nodal_dz_l = *nodal_dz_vec->ViewComponent("node",true); int nnodes = nodal_dz_l.MyLength(); for (int i=0; i!=nnodes; ++i) { nodeids.push_back(i); mesh_->node_get_coordinates(i,&coords); new_coords = coords; new_coords[2] += nodal_dz_l[0][i]; newpos.push_back(new_coords); } // deform the mesh AmanziGeometry::Point_List finpos; mesh_nc_->deform(nodeids, newpos, false, &finpos); if (surf_mesh_ != Teuchos::null) { // now we have to adapt the surface mesh to the new volume mesh // extract the correct new coordinates for the surface from the domain // mesh and update the surface mesh accordingly // WORKAROUND for non-communication in deform() by Mesh // int nsurfnodes = surf_mesh_->num_entities(Amanzi::AmanziMesh::NODE, // Amanzi::AmanziMesh::OWNED); int nsurfnodes = surf_mesh_->num_entities(Amanzi::AmanziMesh::NODE, Amanzi::AmanziMesh::USED); AmanziGeometry::Point coord_domain(dim); AmanziGeometry::Point coord_surface(dim-1); Entity_ID_List surface_nodeids, surface3d_nodeids; AmanziGeometry::Point_List surface_newpos, surface3d_newpos; for (int i=0; i!=nsurfnodes; ++i) { // get the coords of the node AmanziGeometry::Point coord(3); AmanziMesh::Entity_ID pnode = surf_mesh_->entity_get_parent(AmanziMesh::NODE, i); mesh_->node_get_coordinates(i, &coord_domain); // surface points are two dimensional for (int s=0; s!=dim-1; ++s) coord_surface[s] = coord_domain[s]; surface_nodeids.push_back(i); surface_newpos.push_back(coord_surface); surface3d_nodeids.push_back(i); surface3d_newpos.push_back(coord_domain); } // now deform the surface meshes, note that we set the keep_valid // flag to false, since we want the surface mesh to exactly mirror // the domain mesh AmanziGeometry::Point_List surface_finpos; surf_mesh_nc_->deform(surface_nodeids, surface_newpos, false, &surface_finpos); surf3d_mesh_nc_->deform(surface3d_nodeids, surface3d_newpos, false, &surface_finpos); } { // update vertex coordinates in state (for checkpointing) Epetra_MultiVector& vc = *S_next_->GetFieldData("vertex coordinate",name_) ->ViewComponent("node",false); int nnodes = vc.MyLength(); for (int i=0; i!=nnodes; ++i) { mesh_->node_get_coordinates(i,&coords); for (int s=0; s!=dim; ++s) vc[s][i] = coords[s]; } } // setting deformation to be rock_volume at old time, (1-poro_old)*CV_old { Epetra_MultiVector& def = *S_next_->GetFieldData(key_,name_) ->ViewComponent("cell",false); int ncells = def.MyLength(); for (int c=0; c!=ncells; ++c) { def[0][c] = (1. - poro[0][c]) * cv[0][c]; } } // mark the placeholder evaluator as changed solution_evaluator_->SetFieldAsChanged(S_next_.ptr()); // REMOVE ME --etc // update porosity and cell volumes S_next_->GetFieldEvaluator("cell_volume") ->HasFieldChanged(S_next_.ptr(), name_); S_next_->GetFieldEvaluator("porosity") ->HasFieldChanged(S_next_.ptr(), name_); return false; } } // namespace } // namespace <commit_msg>bug fix in volumetric deformation as applied to surface meshes, get correct node id<commit_after>/* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */ /* ------------------------------------------------------------------------- ATS License: see $ATS_DIR/COPYRIGHT Author: Markus Berndt Interface for the Volumetric Deformation PK. <ParameterList name="volumetric deformation"> <Parameter name="PK model" type="string" value="Prescibed Mesh Deformation"/> <Parameter name="Deformation method" type="string" value="method name"/> </ParameterList> ------------------------------------------------------------------------- */ #include "Teuchos_XMLParameterListHelpers.hpp" #include "NKAOperator.hh" #include "composite_vector_function_factory.hh" #include "volumetric_deformation.hh" #include "porosity_evaluator.hh" namespace Amanzi { namespace Deform { using namespace Amanzi::AmanziMesh; RegisteredPKFactory<VolumetricDeformation> VolumetricDeformation::reg_("volumetric deformation"); VolumetricDeformation::VolumetricDeformation(Teuchos::ParameterList& plist, const Teuchos::RCP<TreeVector>& solution): PKDefaultBase(plist,solution), PKPhysicalBase(plist,solution) { poro_key_ = plist_.get<std::string>("porosity key","porosity"); } // -- Setup data void VolumetricDeformation::setup(const Teuchos::Ptr<State>& S) { PKPhysicalBase::setup(S); // save the meshes mesh_nc_ = Teuchos::rcp_const_cast<AmanziMesh::Mesh>(mesh_); if (S->HasMesh("surface")) { surf_mesh_ = S->GetMesh("surface"); surf3d_mesh_ = S->GetMesh("surface_3d"); surf_mesh_nc_ = Teuchos::rcp_const_cast<AmanziMesh::Mesh>(surf_mesh_); surf3d_mesh_nc_ = Teuchos::rcp_const_cast<AmanziMesh::Mesh>(surf3d_mesh_); } // create storage for primary variable, rock volume Teuchos::RCP<CompositeVectorFactory> rv_fac = S->RequireField(key_, name_); rv_fac->SetMesh(mesh_)->SetGhosted() ->SetComponent("cell", AmanziMesh::CELL, 1); // Create storage and a function for cell volume change Teuchos::RCP<CompositeVectorFactory> cv_fac = S->RequireField("dcell_volume_dtime", name_); cv_fac->Update(*rv_fac); Teuchos::ParameterList func_plist = plist_.sublist("deformation function"); deform_func_ = Functions::CreateCompositeVectorFunction(func_plist, *cv_fac); // create storage for the vertex coordinates // we need to checkpoint those to be able to create // the deformed mesh after restart int dim = mesh_->space_dimension(); S->RequireField("vertex coordinate", name_)->SetMesh(mesh_)->SetGhosted() ->SetComponent("node", AmanziMesh::NODE, dim); S->RequireFieldEvaluator("cell_volume"); S->RequireFieldEvaluator("porosity"); S->RequireField("porosity")->SetMesh(mesh_)->SetGhosted() ->AddComponent("cell",AmanziMesh::CELL,1); // solve method Teuchos::ParameterList op_plist = plist_.sublist("global solve operator"); // collect a set of the fixed nodes std::vector<std::string> bottom_regions; if (op_plist.isParameter("bottom region")) { bottom_regions.push_back(op_plist.get<std::string>("bottom region")); } else { bottom_regions = op_plist.get<Teuchos::Array<std::string> >("bottom regions").toVector(); } std::string bottom_region_type = op_plist.get<std::string>("bottom region type","node"); std::set<AmanziMesh::Entity_ID> bottom_node_set; for (std::vector<std::string>::const_iterator region=bottom_regions.begin(); region!=bottom_regions.end(); ++region) { if (bottom_region_type == "node") { AmanziMesh::Entity_ID_List region_nodes; mesh_->get_set_entities(*region, AmanziMesh::NODE, AmanziMesh::OWNED,&region_nodes); bottom_node_set.insert(region_nodes.begin(), region_nodes.end()); } else if (bottom_region_type == "face") { AmanziMesh::Entity_ID_List region_faces; mesh_->get_set_entities(*region, AmanziMesh::FACE, AmanziMesh::OWNED,&region_faces); for (AmanziMesh::Entity_ID_List::const_iterator f=region_faces.begin(); f!=region_faces.end(); ++f) { AmanziMesh::Entity_ID_List face_nodes; mesh_->face_get_nodes(*f, &face_nodes); bottom_node_set.insert(face_nodes.begin(), face_nodes.end()); } } else { Errors::Message mesg("Invalid bottom region type (must be node or face)"); Exceptions::amanzi_throw(mesg); } } // create the unique list of owned bottom nodes unsigned int nnodes_owned = mesh_->num_entities(AmanziMesh::NODE, AmanziMesh::OWNED); Teuchos::RCP<AmanziMesh::Entity_ID_List> bottom_node_list = Teuchos::rcp(new AmanziMesh::Entity_ID_List()); for (std::set<AmanziMesh::Entity_ID>::const_iterator n=bottom_node_set.begin(); n!=bottom_node_set.end(); ++n) { if (*n < nnodes_owned) bottom_node_list->push_back(*n); } // create the operator def_matrix_ = Teuchos::rcp(new Operators::MatrixVolumetricDeformation(op_plist, mesh_, bottom_node_list)); if (op_plist.isSublist("NKA Solver")) { Teuchos::ParameterList solver_plist = op_plist.sublist("NKA Solver"); operator_ = Teuchos::rcp( new NKAOperator<CompositeMatrix,CompositeVector, CompositeVectorFactory>(solver_plist,def_matrix_)); } else { operator_ = def_matrix_; } // create storage for the nodal deformation S->RequireField("nodal_dz", name_)->SetMesh(mesh_)->SetGhosted() ->SetComponent("node", AmanziMesh::NODE, 1); } // -- Initialize owned (dependent) variables. void VolumetricDeformation::initialize(const Teuchos::Ptr<State>& S) { PKPhysicalBase::initialize(S); // the PK's initial condition sets the initial porosity. From this, we // calculate the actual initial condition, which is the rock volume. Epetra_MultiVector& rock_vol = *S->GetFieldData(key_,name_) ->ViewComponent("cell",false); int ncells = rock_vol.MyLength(); for (int c=0; c!=ncells; ++c) { rock_vol[0][c] = (1.0 - rock_vol[0][c]) * mesh_->cell_volume(c); } // initialize the deformation rate to 0 S->GetFieldData("dcell_volume_dtime",name_)->PutScalar(0.); S->GetField("dcell_volume_dtime",name_)->set_initialized(); // initialize the plane displacement to be zero S->GetFieldData("nodal_dz",name_)->PutScalar(0.); S->GetField("nodal_dz",name_)->set_initialized(); { // initialize the vertex coordinate to the current mesh int dim = mesh_->space_dimension(); AmanziGeometry::Point coords; coords.init(dim); int nnodes = mesh_->num_entities(Amanzi::AmanziMesh::NODE, Amanzi::AmanziMesh::OWNED); Epetra_MultiVector& vc = *S->GetFieldData("vertex coordinate",name_) ->ViewComponent("node",false); // search the id of the mid point on the top for (int iV=0; iV!=nnodes; ++iV) { // get the coords of the node mesh_->node_get_coordinates(iV,&coords); for (int s=0; s!=dim; ++s) vc[s][iV] = coords[s]; } } S->GetField("vertex coordinate",name_)->set_initialized(); } bool VolumetricDeformation::advance(double dt) { Teuchos::OSTab tab = getOSTab(); if (out_.get() && includesVerbLevel(verbosity_, Teuchos::VERB_MEDIUM, true)) { *out_ << "Advancing deformation PK from time " << S_->time() << " to " << S_next_->time() << " with step size " << dt << std::endl; *out_ << "----------------------------------------------------------------" << std::endl; } double ss = S_next_->time(); double ss0 = S_->time(); double dT = ss - ss0; double T_mid = (ss + ss0) / 2.; const Epetra_MultiVector& cv = *S_->GetFieldData("cell_volume") ->ViewComponent("cell",false); const Epetra_MultiVector& poro = *S_->GetFieldData(poro_key_) ->ViewComponent("cell",false); // Evaluate the function at the mean time to get d(cv)/dT Teuchos::RCP<CompositeVector> dcell_vol_vec = S_next_->GetFieldData("dcell_volume_dtime", name_); dcell_vol_vec->PutScalar(0.); deform_func_->Compute(T_mid, dcell_vol_vec.ptr()); { // scale by cell volume, this is fractional loss Epetra_MultiVector& dcell_vol_c = *dcell_vol_vec->ViewComponent("cell",false); for (int c=0; c!=dcell_vol_c.MyLength(); ++c) { dcell_vol_c[0][c] *= cv[0][c] * dT; } } // calculate the nodal deformation Teuchos::RCP<CompositeVector> nodal_dz_vec = S_next_->GetFieldData("nodal_dz",name_); Teuchos::RCP<CompositeVector> rhs = Teuchos::rcp(new CompositeVector(*nodal_dz_vec)); def_matrix_->ApplyRHS(*dcell_vol_vec, rhs.ptr()); operator_->ApplyInverse(*rhs, nodal_dz_vec.ptr()); // form list of deformed nodes Entity_ID_List nodeids; AmanziGeometry::Point_List newpos; Amanzi::AmanziGeometry::Point coords, new_coords; int dim = mesh_->space_dimension(); new_coords.init(dim); nodal_dz_vec->ScatterMasterToGhosted("node",true); // WORKAROUND for non-communication in deform() by Mesh // const Epetra_MultiVector& nodal_dz_l = // *nodal_dz_vec->ViewComponent("node",false); const Epetra_MultiVector& nodal_dz_l = *nodal_dz_vec->ViewComponent("node",true); int nnodes = nodal_dz_l.MyLength(); for (int i=0; i!=nnodes; ++i) { nodeids.push_back(i); mesh_->node_get_coordinates(i,&coords); new_coords = coords; new_coords[2] += nodal_dz_l[0][i]; newpos.push_back(new_coords); } // deform the mesh AmanziGeometry::Point_List finpos; mesh_nc_->deform(nodeids, newpos, false, &finpos); if (surf_mesh_ != Teuchos::null) { // now we have to adapt the surface mesh to the new volume mesh // extract the correct new coordinates for the surface from the domain // mesh and update the surface mesh accordingly // WORKAROUND for non-communication in deform() by Mesh // int nsurfnodes = surf_mesh_->num_entities(Amanzi::AmanziMesh::NODE, // Amanzi::AmanziMesh::OWNED); int nsurfnodes = surf_mesh_->num_entities(AmanziMesh::NODE, AmanziMesh::USED); Entity_ID_List surface_nodeids, surface3d_nodeids; AmanziGeometry::Point_List surface_newpos, surface3d_newpos; for (int i=0; i!=nsurfnodes; ++i) { // get the coords of the node AmanziMesh::Entity_ID pnode = surf_mesh_->entity_get_parent(AmanziMesh::NODE, i); AmanziGeometry::Point coord_domain(dim); mesh_->node_get_coordinates(pnode, &coord_domain); surface3d_nodeids.push_back(i); surface3d_newpos.push_back(coord_domain); // surface points are two dimensional AmanziGeometry::Point coord_surface(dim-1); for (int s=0; s!=dim-1; ++s) coord_surface[s] = coord_domain[s]; surface_nodeids.push_back(i); surface_newpos.push_back(coord_surface); } AmanziGeometry::Point_List surface_finpos; surf_mesh_nc_->deform(surface_nodeids, surface_newpos, false, &surface_finpos); surf3d_mesh_nc_->deform(surface3d_nodeids, surface3d_newpos, false, &surface_finpos); } { // update vertex coordinates in state (for checkpointing) Epetra_MultiVector& vc = *S_next_->GetFieldData("vertex coordinate",name_) ->ViewComponent("node",false); int nnodes = vc.MyLength(); for (int i=0; i!=nnodes; ++i) { mesh_->node_get_coordinates(i,&coords); for (int s=0; s!=dim; ++s) vc[s][i] = coords[s]; } } // setting deformation to be rock_volume at old time, (1-poro_old)*CV_old { Epetra_MultiVector& def = *S_next_->GetFieldData(key_,name_) ->ViewComponent("cell",false); int ncells = def.MyLength(); for (int c=0; c!=ncells; ++c) { def[0][c] = (1. - poro[0][c]) * cv[0][c]; } } // mark the placeholder evaluator as changed solution_evaluator_->SetFieldAsChanged(S_next_.ptr()); // REMOVE ME --etc // update porosity and cell volumes S_next_->GetFieldEvaluator("cell_volume") ->HasFieldChanged(S_next_.ptr(), name_); S_next_->GetFieldEvaluator("porosity") ->HasFieldChanged(S_next_.ptr(), name_); return false; } } // namespace } // namespace <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qmltextgenerator.h" #include <QVariant> #include <QColor> #include "bindingproperty.h" #include "signalhandlerproperty.h" #include "nodeproperty.h" #include "nodelistproperty.h" #include "variantproperty.h" #include <nodemetainfo.h> #include "model.h" using namespace QmlDesigner; using namespace QmlDesigner::Internal; inline static QString properColorName(const QColor &color) { QString s; if (color.alpha() == 255) s.sprintf("#%02x%02x%02x", color.red(), color.green(), color.blue()); else s.sprintf("#%02x%02x%02x%02x", color.alpha(), color.red(), color.green(), color.blue()); return s; } inline static QString doubleToString(double d) { QString string = QString::number(d, 'f', 3); if (string.contains(QLatin1Char('.'))) { while (string.at(string.length()- 1) == QLatin1Char('0')) string.chop(1); if (string.at(string.length()- 1) == QLatin1Char('.')) string.chop(1); } return string; } QmlTextGenerator::QmlTextGenerator(const PropertyNameList &propertyOrder, int indentDepth): m_propertyOrder(propertyOrder), m_indentDepth(indentDepth) { } QString QmlTextGenerator::toQml(const AbstractProperty &property, int indentDepth) const { if (property.isBindingProperty()) { return property.toBindingProperty().expression(); } else if (property.isSignalHandlerProperty()) { return property.toSignalHandlerProperty().source(); } else if (property.isNodeProperty()) { return toQml(property.toNodeProperty().modelNode(), indentDepth); } else if (property.isNodeListProperty()) { const QList<ModelNode> nodes = property.toNodeListProperty().toModelNodeList(); if (property.isDefaultProperty()) { QString result; for (int i = 0; i < nodes.length(); ++i) { if (i > 0) result += QLatin1String("\n\n"); result += QString(indentDepth, QLatin1Char(' ')); result += toQml(nodes.at(i), indentDepth); } return result; } else { QString result = QLatin1String("["); const int arrayContentDepth = indentDepth + 4; const QString arrayContentIndentation(arrayContentDepth, QLatin1Char(' ')); for (int i = 0; i < nodes.length(); ++i) { if (i > 0) result += QLatin1Char(','); result += QLatin1Char('\n'); result += arrayContentIndentation; result += toQml(nodes.at(i), arrayContentDepth); } return result + QLatin1Char(']'); } } else if (property.isVariantProperty()) { const VariantProperty variantProperty = property.toVariantProperty(); const QVariant value = variantProperty.value(); const QString stringValue = value.toString(); if (property.name() == "id") return stringValue; if (false) { } if (variantProperty.holdsEnumeration()) { return variantProperty.enumeration().toString(); } else { switch (value.type()) { case QVariant::Bool: if (value.value<bool>()) return QLatin1String("true"); else return QLatin1String("false"); case QVariant::Color: return QString(QLatin1String("\"%1\"")).arg(properColorName(value.value<QColor>())); case QVariant::Double: return doubleToString(value.toDouble()); case QVariant::Int: case QVariant::LongLong: case QVariant::UInt: case QVariant::ULongLong: return stringValue; default: return QString(QLatin1String("\"%1\"")).arg(escape(stringValue)); } } } else { Q_ASSERT("Unknown property type"); return QString(); } } QString QmlTextGenerator::toQml(const ModelNode &node, int indentDepth) const { QString type = node.type(); QString url; if (type.contains('.')) { QStringList nameComponents = type.split('.'); url = nameComponents.first(); type = nameComponents.last(); } QString alias; if (!url.isEmpty()) { foreach (const Import &import, node.model()->imports()) { if (import.url() == url) { alias = import.alias(); break; } if (import.file() == url) { alias = import.alias(); break; } } } QString result; if (!alias.isEmpty()) result = alias + '.'; result += type; result += QLatin1String(" {\n"); const int propertyIndentDepth = indentDepth + 4; const QString properties = propertiesToQml(node, propertyIndentDepth); return result + properties + QString(indentDepth, QLatin1Char(' ')) + QLatin1Char('}'); } QString QmlTextGenerator::propertiesToQml(const ModelNode &node, int indentDepth) const { QString topPart; QString bottomPart; PropertyNameList nodePropertyNames = node.propertyNames(); bool addToTop = true; foreach (const PropertyName &propertyName, m_propertyOrder) { if (propertyName == "id") { // the model handles the id property special, so: if (!node.id().isEmpty()) { QString idLine(indentDepth, QLatin1Char(' ')); idLine += QLatin1String("id: "); idLine += node.id(); idLine += QLatin1Char('\n'); if (addToTop) topPart.append(idLine); else bottomPart.append(idLine); } } else if (propertyName.isEmpty()) { addToTop = false; } else if (nodePropertyNames.removeAll(propertyName)) { const QString newContent = propertyToQml(node.property(propertyName), indentDepth); if (addToTop) topPart.append(newContent); else bottomPart.append(newContent); } } foreach (const PropertyName &propertyName, nodePropertyNames) { bottomPart.prepend(propertyToQml(node.property(propertyName), indentDepth)); } return topPart + bottomPart; } QString QmlTextGenerator::propertyToQml(const AbstractProperty &property, int indentDepth) const { QString result; if (property.isDefaultProperty()) { result = toQml(property, indentDepth); } else { if (property.isDynamic()) { result = QString(indentDepth, QLatin1Char(' ')) + QLatin1String("property ") + property.dynamicTypeName() + QLatin1String(" ") + property.name() + QLatin1String(": ") + toQml(property, indentDepth); } else { result = QString(indentDepth, QLatin1Char(' ')) + property.name() + QLatin1String(": ") + toQml(property, indentDepth); } } result += QLatin1Char('\n'); return result; } QString QmlTextGenerator::escape(const QString &value) { QString result = value; result.replace(QLatin1String("\\"), QLatin1String("\\\\")); result.replace(QLatin1String("\""), QLatin1String("\\\"")); result.replace(QLatin1String("\t"), QLatin1String("\\t")); result.replace(QLatin1String("\r"), QLatin1String("\\r")); result.replace(QLatin1String("\n"), QLatin1String("\\n")); return result; } <commit_msg>QmlDesigner.Rewriter: Support for float type in QVariant<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "qmltextgenerator.h" #include <QVariant> #include <QColor> #include "bindingproperty.h" #include "signalhandlerproperty.h" #include "nodeproperty.h" #include "nodelistproperty.h" #include "variantproperty.h" #include <nodemetainfo.h> #include "model.h" using namespace QmlDesigner; using namespace QmlDesigner::Internal; inline static QString properColorName(const QColor &color) { QString s; if (color.alpha() == 255) s.sprintf("#%02x%02x%02x", color.red(), color.green(), color.blue()); else s.sprintf("#%02x%02x%02x%02x", color.alpha(), color.red(), color.green(), color.blue()); return s; } inline static QString doubleToString(double d) { QString string = QString::number(d, 'f', 3); if (string.contains(QLatin1Char('.'))) { while (string.at(string.length()- 1) == QLatin1Char('0')) string.chop(1); if (string.at(string.length()- 1) == QLatin1Char('.')) string.chop(1); } return string; } QmlTextGenerator::QmlTextGenerator(const PropertyNameList &propertyOrder, int indentDepth): m_propertyOrder(propertyOrder), m_indentDepth(indentDepth) { } QString QmlTextGenerator::toQml(const AbstractProperty &property, int indentDepth) const { if (property.isBindingProperty()) { return property.toBindingProperty().expression(); } else if (property.isSignalHandlerProperty()) { return property.toSignalHandlerProperty().source(); } else if (property.isNodeProperty()) { return toQml(property.toNodeProperty().modelNode(), indentDepth); } else if (property.isNodeListProperty()) { const QList<ModelNode> nodes = property.toNodeListProperty().toModelNodeList(); if (property.isDefaultProperty()) { QString result; for (int i = 0; i < nodes.length(); ++i) { if (i > 0) result += QLatin1String("\n\n"); result += QString(indentDepth, QLatin1Char(' ')); result += toQml(nodes.at(i), indentDepth); } return result; } else { QString result = QLatin1String("["); const int arrayContentDepth = indentDepth + 4; const QString arrayContentIndentation(arrayContentDepth, QLatin1Char(' ')); for (int i = 0; i < nodes.length(); ++i) { if (i > 0) result += QLatin1Char(','); result += QLatin1Char('\n'); result += arrayContentIndentation; result += toQml(nodes.at(i), arrayContentDepth); } return result + QLatin1Char(']'); } } else if (property.isVariantProperty()) { const VariantProperty variantProperty = property.toVariantProperty(); const QVariant value = variantProperty.value(); const QString stringValue = value.toString(); if (property.name() == "id") return stringValue; if (false) { } if (variantProperty.holdsEnumeration()) { return variantProperty.enumeration().toString(); } else { switch (value.type()) { case QVariant::Bool: if (value.value<bool>()) return QLatin1String("true"); else return QLatin1String("false"); case QVariant::Color: return QString(QLatin1String("\"%1\"")).arg(properColorName(value.value<QColor>())); case QMetaType::Float: case QVariant::Double: return doubleToString(value.toDouble()); case QVariant::Int: case QVariant::LongLong: case QVariant::UInt: case QVariant::ULongLong: return stringValue; default: return QString(QLatin1String("\"%1\"")).arg(escape(stringValue)); } } } else { Q_ASSERT("Unknown property type"); return QString(); } } QString QmlTextGenerator::toQml(const ModelNode &node, int indentDepth) const { QString type = node.type(); QString url; if (type.contains('.')) { QStringList nameComponents = type.split('.'); url = nameComponents.first(); type = nameComponents.last(); } QString alias; if (!url.isEmpty()) { foreach (const Import &import, node.model()->imports()) { if (import.url() == url) { alias = import.alias(); break; } if (import.file() == url) { alias = import.alias(); break; } } } QString result; if (!alias.isEmpty()) result = alias + '.'; result += type; result += QLatin1String(" {\n"); const int propertyIndentDepth = indentDepth + 4; const QString properties = propertiesToQml(node, propertyIndentDepth); return result + properties + QString(indentDepth, QLatin1Char(' ')) + QLatin1Char('}'); } QString QmlTextGenerator::propertiesToQml(const ModelNode &node, int indentDepth) const { QString topPart; QString bottomPart; PropertyNameList nodePropertyNames = node.propertyNames(); bool addToTop = true; foreach (const PropertyName &propertyName, m_propertyOrder) { if (propertyName == "id") { // the model handles the id property special, so: if (!node.id().isEmpty()) { QString idLine(indentDepth, QLatin1Char(' ')); idLine += QLatin1String("id: "); idLine += node.id(); idLine += QLatin1Char('\n'); if (addToTop) topPart.append(idLine); else bottomPart.append(idLine); } } else if (propertyName.isEmpty()) { addToTop = false; } else if (nodePropertyNames.removeAll(propertyName)) { const QString newContent = propertyToQml(node.property(propertyName), indentDepth); if (addToTop) topPart.append(newContent); else bottomPart.append(newContent); } } foreach (const PropertyName &propertyName, nodePropertyNames) { bottomPart.prepend(propertyToQml(node.property(propertyName), indentDepth)); } return topPart + bottomPart; } QString QmlTextGenerator::propertyToQml(const AbstractProperty &property, int indentDepth) const { QString result; if (property.isDefaultProperty()) { result = toQml(property, indentDepth); } else { if (property.isDynamic()) { result = QString(indentDepth, QLatin1Char(' ')) + QLatin1String("property ") + property.dynamicTypeName() + QLatin1String(" ") + property.name() + QLatin1String(": ") + toQml(property, indentDepth); } else { result = QString(indentDepth, QLatin1Char(' ')) + property.name() + QLatin1String(": ") + toQml(property, indentDepth); } } result += QLatin1Char('\n'); return result; } QString QmlTextGenerator::escape(const QString &value) { QString result = value; result.replace(QLatin1String("\\"), QLatin1String("\\\\")); result.replace(QLatin1String("\""), QLatin1String("\\\"")); result.replace(QLatin1String("\t"), QLatin1String("\\t")); result.replace(QLatin1String("\r"), QLatin1String("\\r")); result.replace(QLatin1String("\n"), QLatin1String("\\n")); return result; } <|endoftext|>
<commit_before>/* * Copyright (C) 2006, 2007 Apple 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: * 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. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h" #include <windows.h> #include "Font.h" #include "FontFallbackList.h" #include "GlyphBuffer.h" #include "SimpleFontData.h" #include "UniscribeStateTextRun.h" #include "base/gfx/platform_canvas_win.h" #include "base/gfx/skia_utils.h" #include "graphics/SkiaUtils.h" #include "webkit/glue/webkit_glue.h" namespace WebCore { void Font::drawGlyphs(GraphicsContext* graphicsContext, const SimpleFontData* font, const GlyphBuffer& glyphBuffer, int from, int numGlyphs, const FloatPoint& point) const { PlatformGraphicsContext* context = graphicsContext->platformContext(); // Max buffer length passed to the underlying windows API. const int kMaxBufferLength = 1024; // Default size for the buffer. It should be enough for most of cases. const int kDefaultBufferLength = 256; SkColor color = context->fillColor(); unsigned char alpha = SkColorGetA(color); // Skip 100% transparent text; no need to draw anything. if (!alpha) return; // Set up our graphics context. HDC hdc = context->canvas()->beginPlatformPaint(); HGDIOBJ oldFont = SelectObject(hdc, font->platformData().hfont()); // TODO(maruel): http://b/700464 SetTextColor doesn't support transparency. // Enforce non-transparent color. color = SkColorSetRGB(SkColorGetR(color), SkColorGetG(color), SkColorGetB(color)); SetTextColor(hdc, gfx::SkColorToCOLORREF(color)); SetBkMode(hdc, TRANSPARENT); // Windows needs the characters and the advances in nice contiguous // buffers, which we build here. Vector<WORD, kDefaultBufferLength> glyphs; Vector<int, kDefaultBufferLength> advances; // We draw the glyphs in chunks to avoid having to do a heap allocation for // the arrays of characters and advances. Since ExtTextOut is the // lowest-level text output function on Windows, there should be little // penalty for splitting up the text. On the other hand, the buffer cannot // be bigger than 4094 or the function will fail. int glyphIndex = 0; int chunkX = 0; // x offset of this span from the point while (glyphIndex < numGlyphs) { // how many chars will be in this chunk? int curLen = std::min(kMaxBufferLength, numGlyphs - glyphIndex); glyphs.resize(curLen); advances.resize(curLen); int curWidth = 0; for (int i = 0; i < curLen; ++i, ++glyphIndex) { glyphs[i] = glyphBuffer.glyphAt(from + glyphIndex); advances[i] = static_cast<int>(glyphBuffer.advanceAt(from + glyphIndex)); curWidth += advances[i]; } SkPoint origin2 = point; origin2.fX += chunkX; bool success = false; for (int executions = 0; executions < 2; ++executions) { // The 'origin' represents the baseline, so we need to move it up // to the top of the bounding square by subtracting the ascent success = !!ExtTextOut(hdc, static_cast<int>(origin2.fX), static_cast<int>(origin2.fY) - ascent(), ETO_GLYPH_INDEX, NULL, reinterpret_cast<const wchar_t*>(&glyphs[0]), curLen, &advances[0]); if (!success && executions == 0) { // Ask the browser to load the font for us and retry. webkit_glue::EnsureFontLoaded(font->platformData().hfont()); continue; } break; } ASSERT(success); chunkX += curWidth; } SelectObject(hdc, oldFont); context->canvas()->endPlatformPaint(); } FloatRect Font::selectionRectForComplexText(const TextRun& run, const IntPoint& point, int h, int from, int to) const { UniscribeStateTextRun state(run, *this); float left = static_cast<float>(point.x() + state.CharacterToX(from)); float right = static_cast<float>(point.x() + state.CharacterToX(to)); // If the text is RTL, left will actually be after right. if (left < right) { return FloatRect(left, static_cast<float>(point.y()), right - left, static_cast<float>(h)); } return FloatRect(right, static_cast<float>(point.y()), left - right, static_cast<float>(h)); } void Font::drawComplexText(GraphicsContext* graphicsContext, const TextRun& run, const FloatPoint& point, int from, int to) const { PlatformGraphicsContext* context = graphicsContext->platformContext(); UniscribeStateTextRun state(run, *this); SkColor color = context->fillColor(); uint8 alpha = SkColorGetA(color); // Skip 100% transparent text; no need to draw anything. if (!alpha) return; HDC hdc = context->canvas()->beginPlatformPaint(); // TODO(maruel): http://b/700464 SetTextColor doesn't support transparency. // Enforce non-transparent color. color = SkColorSetRGB(SkColorGetR(color), SkColorGetG(color), SkColorGetB(color)); SetTextColor(hdc, gfx::SkColorToCOLORREF(color)); SetBkMode(hdc, TRANSPARENT); // Uniscribe counts the coordinates from the upper left, while WebKit uses // the baseline, so we have to subtract off the ascent. state.Draw(hdc, static_cast<int>(point.x()), static_cast<int>(point.y() - ascent()), from, to); context->canvas()->endPlatformPaint(); } float Font::floatWidthForComplexText(const TextRun& run) const { UniscribeStateTextRun state(run, *this); return static_cast<float>(state.Width()); } int Font::offsetForPositionForComplexText(const TextRun& run, int x, bool includePartialGlyphs) const { // Mac code ignores includePartialGlyphs, and they don't know what it's // supposed to do, so we just ignore it as well. UniscribeStateTextRun state(run, *this); int char_index = state.XToCharacter(x); // XToCharacter will return -1 if the position is before the first // character (we get called like this sometimes). if (char_index < 0) char_index = 0; return char_index; } } // namespace WebCore <commit_msg>Fix font regression. I was using ascent() instead of font->ascent(), which I think doesn't take into account fallback fonts and small caps, so those characters would be incorrectly vertically aligned. This also fixes an old bug I noticed where if the run is more than 1024 pixels, it will start being drawn over itself since we never used the updated x coordinate. Review URL: http://codereview.chromium.org/9206<commit_after>/* * Copyright (C) 2006, 2007 Apple 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: * 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. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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 "config.h" #include <windows.h> #include "Font.h" #include "FontFallbackList.h" #include "GlyphBuffer.h" #include "SimpleFontData.h" #include "UniscribeStateTextRun.h" #include "base/gfx/platform_canvas_win.h" #include "base/gfx/skia_utils.h" #include "graphics/SkiaUtils.h" #include "webkit/glue/webkit_glue.h" namespace WebCore { void Font::drawGlyphs(GraphicsContext* graphicsContext, const SimpleFontData* font, const GlyphBuffer& glyphBuffer, int from, int numGlyphs, const FloatPoint& point) const { PlatformGraphicsContext* context = graphicsContext->platformContext(); // Max buffer length passed to the underlying windows API. const int kMaxBufferLength = 1024; // Default size for the buffer. It should be enough for most of cases. const int kDefaultBufferLength = 256; SkColor color = context->fillColor(); unsigned char alpha = SkColorGetA(color); // Skip 100% transparent text; no need to draw anything. if (!alpha) return; // Set up our graphics context. HDC hdc = context->canvas()->beginPlatformPaint(); HGDIOBJ oldFont = SelectObject(hdc, font->platformData().hfont()); // TODO(maruel): http://b/700464 SetTextColor doesn't support transparency. // Enforce non-transparent color. color = SkColorSetRGB(SkColorGetR(color), SkColorGetG(color), SkColorGetB(color)); SetTextColor(hdc, gfx::SkColorToCOLORREF(color)); SetBkMode(hdc, TRANSPARENT); // Windows needs the characters and the advances in nice contiguous // buffers, which we build here. Vector<WORD, kDefaultBufferLength> glyphs; Vector<int, kDefaultBufferLength> advances; // Compute the coordinate. The 'origin' represents the baseline, so we need // to move it up to the top of the bounding square. int x = static_cast<int>(point.x()); int lineTop = static_cast<int>(point.y()) - font->ascent(); // We draw the glyphs in chunks to avoid having to do a heap allocation for // the arrays of characters and advances. Since ExtTextOut is the // lowest-level text output function on Windows, there should be little // penalty for splitting up the text. On the other hand, the buffer cannot // be bigger than 4094 or the function will fail. int glyphIndex = 0; while (glyphIndex < numGlyphs) { // how many chars will be in this chunk? int curLen = std::min(kMaxBufferLength, numGlyphs - glyphIndex); glyphs.resize(curLen); advances.resize(curLen); int curWidth = 0; for (int i = 0; i < curLen; ++i, ++glyphIndex) { glyphs[i] = glyphBuffer.glyphAt(from + glyphIndex); advances[i] = static_cast<int>(glyphBuffer.advanceAt(from + glyphIndex)); curWidth += advances[i]; } bool success = false; for (int executions = 0; executions < 2; ++executions) { success = !!ExtTextOut(hdc, x, lineTop, ETO_GLYPH_INDEX, NULL, reinterpret_cast<const wchar_t*>(&glyphs[0]), curLen, &advances[0]); if (!success && executions == 0) { // Ask the browser to load the font for us and retry. webkit_glue::EnsureFontLoaded(font->platformData().hfont()); continue; } break; } ASSERT(success); x += curWidth; } SelectObject(hdc, oldFont); context->canvas()->endPlatformPaint(); } FloatRect Font::selectionRectForComplexText(const TextRun& run, const IntPoint& point, int h, int from, int to) const { UniscribeStateTextRun state(run, *this); float left = static_cast<float>(point.x() + state.CharacterToX(from)); float right = static_cast<float>(point.x() + state.CharacterToX(to)); // If the text is RTL, left will actually be after right. if (left < right) { return FloatRect(left, static_cast<float>(point.y()), right - left, static_cast<float>(h)); } return FloatRect(right, static_cast<float>(point.y()), left - right, static_cast<float>(h)); } void Font::drawComplexText(GraphicsContext* graphicsContext, const TextRun& run, const FloatPoint& point, int from, int to) const { PlatformGraphicsContext* context = graphicsContext->platformContext(); UniscribeStateTextRun state(run, *this); SkColor color = context->fillColor(); uint8 alpha = SkColorGetA(color); // Skip 100% transparent text; no need to draw anything. if (!alpha) return; HDC hdc = context->canvas()->beginPlatformPaint(); // TODO(maruel): http://b/700464 SetTextColor doesn't support transparency. // Enforce non-transparent color. color = SkColorSetRGB(SkColorGetR(color), SkColorGetG(color), SkColorGetB(color)); SetTextColor(hdc, gfx::SkColorToCOLORREF(color)); SetBkMode(hdc, TRANSPARENT); // Uniscribe counts the coordinates from the upper left, while WebKit uses // the baseline, so we have to subtract off the ascent. state.Draw(hdc, static_cast<int>(point.x()), static_cast<int>(point.y() - ascent()), from, to); context->canvas()->endPlatformPaint(); } float Font::floatWidthForComplexText(const TextRun& run) const { UniscribeStateTextRun state(run, *this); return static_cast<float>(state.Width()); } int Font::offsetForPositionForComplexText(const TextRun& run, int x, bool includePartialGlyphs) const { // Mac code ignores includePartialGlyphs, and they don't know what it's // supposed to do, so we just ignore it as well. UniscribeStateTextRun state(run, *this); int char_index = state.XToCharacter(x); // XToCharacter will return -1 if the position is before the first // character (we get called like this sometimes). if (char_index < 0) char_index = 0; return char_index; } } // namespace WebCore <|endoftext|>
<commit_before><commit_msg>GTK test shell valgrind, try 3. Null out the main window before initiating shutdown.<commit_after><|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of QMime ** ** Based on Qt Creator source code ** ** Qt Creator Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** **************************************************************************/ #include "qmimemagicrule.h" #include <QtCore/QList> #include <qendian.h> QT_BEGIN_NAMESPACE // in the same order as Type! static const char magicRuleTypes_string[] = "invalid\0" "string\0" "host16\0" "host32\0" "big16\0" "big32\0" "little16\0" "little32\0" "byte\0" "\0"; static const int magicRuleTypes_indices[] = { 0, 8, 15, 22, 29, 35, 41, 50, 59, 65, 0 }; QMimeMagicRule::Type QMimeMagicRule::type(const QByteArray &type) { for (int i = String; i <= Byte; ++i) { if (type == magicRuleTypes_string + magicRuleTypes_indices[i]) return static_cast<Type>(i); } return Invalid; } QByteArray QMimeMagicRule::typeName(QMimeMagicRule::Type type) { return magicRuleTypes_string + magicRuleTypes_indices[type]; } struct QMimeMagicRulePrivate { QMimeMagicRule::Type type; QByteArray value; int startPos; int endPos; QByteArray mask; QByteArray pattern; quint32 number; quint32 numberMask; typedef bool (*MatchFunction)(QMimeMagicRulePrivate *d, const QByteArray &data); MatchFunction matchFunction; }; static bool matchString(QMimeMagicRulePrivate *d, const QByteArray &data) { const char *p = data.constData() + d->startPos; const char *e = p + qMin(data.size() - d->pattern.size(), d->endPos); for ( ; p <= e; ++p) { int i = 0; while (i < d->pattern.size() && (p[i] & d->mask.at(i)) == d->pattern.at(i)) ++i; if (i == d->pattern.size()) return true; } return false; } template <typename T> static bool matchNumber(QMimeMagicRulePrivate *d, const QByteArray &data) { const T value(d->number); const T mask(d->numberMask); const char *p = data.constData() + d->startPos; const char *e = p + qMin(data.size() - int(sizeof(T)), d->endPos); for ( ; p <= e; ++p) { if ((*reinterpret_cast<const T*>(p) & mask) == value) return true; } return false; } static inline QByteArray makePattern(const QByteArray &value) { QByteArray pattern(value.size(), Qt::Uninitialized); char *data = pattern.data(); const char *p = value.constData(); const char *e = p + value.size(); for ( ; p < e; ++p) { if (*p == '\\' && ++p < e) { if (*p == 'x') { // hex (\\xff) char c = 0; for (int i = 0; i < 2 && p + 1 < e; ++i) { ++p; if (*p >= '0' && *p <= '9') c = (c << 4) + *p - '0'; else if (*p >= 'a' && *p <= 'f') c = (c << 4) + *p - 'a' + 10; else if (*p >= 'A' && *p <= 'F') c = (c << 4) + *p - 'A' + 10; else continue; } *data++ = c; } else if (*p >= '0' && *p <= '7') { // oct (\\7, or \\77, or \\377) char c = *p - '0'; if (p + 1 < e && p[1] >= '0' && p[1] <= '7') { c = (c << 3) + *(++p) - '0'; if (p + 1 < e && p[1] >= '0' && p[1] <= '7' && p[-1] <= '3') c = (c << 3) + *(++p) - '0'; } *data++ = c; } else { // escaped *data++ = *p; } } else { *data++ = *p; } } pattern.truncate(data - pattern.data()); return pattern; } QMimeMagicRule::QMimeMagicRule(QMimeMagicRule::Type type, const QByteArray &value, int startPos, int endPos, const QByteArray &mask) : d(new QMimeMagicRulePrivate) { Q_ASSERT(!value.isEmpty()); d->type = type; d->value = value; d->startPos = startPos; d->endPos = endPos; d->mask = mask; d->matchFunction = 0; if (d->type >= Host16 && d->type <= Byte) { bool ok; d->number = d->value.toUInt(&ok, 0); // autodetect Q_ASSERT(ok); d->numberMask = !d->mask.isEmpty() ? d->mask.toUInt(&ok, 0) : 0; // autodetect } switch (d->type) { case String: d->pattern = makePattern(d->value); d->pattern.squeeze(); if (!d->mask.isEmpty()) { Q_ASSERT(d->mask.size() >= 4 && d->mask.startsWith("0x")); d->mask = QByteArray::fromHex(QByteArray::fromRawData(d->mask.constData() + 2, d->mask.size() - 2)); Q_ASSERT(d->mask.size() == d->pattern.size()); // apply mask to pattern const char *m = d->mask.constData(); char *p = d->pattern.data(); const char *e = p + d->pattern.size(); while (p < e) *p++ &= *m++; } else { d->mask.fill(0xff, d->pattern.size()); } d->mask.squeeze(); d->matchFunction = matchString; break; case Byte: if (d->number <= quint8(-1)) { if (d->numberMask == 0) d->numberMask = quint8(-1); d->matchFunction = matchNumber<quint8>; } break; case Big16: case Host16: case Little16: if (d->number <= quint16(-1)) { d->number = d->type == Little16 ? qFromLittleEndian<quint16>(d->number) : qFromBigEndian<quint16>(d->number); if (d->numberMask == 0) d->numberMask = quint16(-1); d->matchFunction = matchNumber<quint16>; } break; case Big32: case Host32: case Little32: if (d->number <= quint32(-1)) { d->number = d->type == Little32 ? qFromLittleEndian<quint32>(d->number) : qFromBigEndian<quint32>(d->number); if (d->numberMask == 0) d->numberMask = quint32(-1); d->matchFunction = matchNumber<quint32>; } break; default: break; } } QMimeMagicRule::QMimeMagicRule(const QMimeMagicRule &other) : d(new QMimeMagicRulePrivate(*other.d)) { } QMimeMagicRule::~QMimeMagicRule() { } QMimeMagicRule& QMimeMagicRule::operator=(const QMimeMagicRule &other) { *d = *other.d; return *this; } QMimeMagicRule::Type QMimeMagicRule::type() const { return d->type; } QByteArray QMimeMagicRule::value() const { return d->value; } int QMimeMagicRule::startPos() const { return d->startPos; } int QMimeMagicRule::endPos() const { return d->endPos; } QByteArray QMimeMagicRule::mask() const { QByteArray mask = d->mask; if (d->type == String) { // restore '0x' mask = "0x" + mask.toHex(); } return mask; } bool QMimeMagicRule::isValid() const { return d->matchFunction; } bool QMimeMagicRule::matches(const QByteArray &data) const { return d->matchFunction && d->matchFunction(d.data(), data); } QT_END_NAMESPACE <commit_msg>fix stupid bug<commit_after>/************************************************************************** ** ** This file is part of QMime ** ** Based on Qt Creator source code ** ** Qt Creator Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** **************************************************************************/ #include "qmimemagicrule.h" #include <QtCore/QList> #include <qendian.h> QT_BEGIN_NAMESPACE // in the same order as Type! static const char magicRuleTypes_string[] = "invalid\0" "string\0" "host16\0" "host32\0" "big16\0" "big32\0" "little16\0" "little32\0" "byte\0" "\0"; static const int magicRuleTypes_indices[] = { 0, 8, 15, 22, 29, 35, 41, 50, 59, 65, 0 }; QMimeMagicRule::Type QMimeMagicRule::type(const QByteArray &type) { for (int i = String; i <= Byte; ++i) { if (type == magicRuleTypes_string + magicRuleTypes_indices[i]) return static_cast<Type>(i); } return Invalid; } QByteArray QMimeMagicRule::typeName(QMimeMagicRule::Type type) { return magicRuleTypes_string + magicRuleTypes_indices[type]; } struct QMimeMagicRulePrivate { QMimeMagicRule::Type type; QByteArray value; int startPos; int endPos; QByteArray mask; QByteArray pattern; quint32 number; quint32 numberMask; typedef bool (*MatchFunction)(QMimeMagicRulePrivate *d, const QByteArray &data); MatchFunction matchFunction; }; static bool matchString(QMimeMagicRulePrivate *d, const QByteArray &data) { const char *p = data.constData() + d->startPos; const char *e = data.constData() + qMin(data.size() - d->pattern.size(), d->endPos + 1); for ( ; p < e; ++p) { int i = 0; while (i < d->pattern.size() && (p[i] & d->mask.at(i)) == d->pattern.at(i)) ++i; if (i == d->pattern.size()) return true; } return false; } template <typename T> static bool matchNumber(QMimeMagicRulePrivate *d, const QByteArray &data) { const T value(d->number); const T mask(d->numberMask); const char *p = data.constData() + d->startPos; const char *e = data.constData() + qMin(data.size() - int(sizeof(T)), d->endPos + 1); for ( ; p < e; ++p) { if ((*reinterpret_cast<const T*>(p) & mask) == value) return true; } return false; } static inline QByteArray makePattern(const QByteArray &value) { QByteArray pattern(value.size(), Qt::Uninitialized); char *data = pattern.data(); const char *p = value.constData(); const char *e = p + value.size(); for ( ; p < e; ++p) { if (*p == '\\' && ++p < e) { if (*p == 'x') { // hex (\\xff) char c = 0; for (int i = 0; i < 2 && p + 1 < e; ++i) { ++p; if (*p >= '0' && *p <= '9') c = (c << 4) + *p - '0'; else if (*p >= 'a' && *p <= 'f') c = (c << 4) + *p - 'a' + 10; else if (*p >= 'A' && *p <= 'F') c = (c << 4) + *p - 'A' + 10; else continue; } *data++ = c; } else if (*p >= '0' && *p <= '7') { // oct (\\7, or \\77, or \\377) char c = *p - '0'; if (p + 1 < e && p[1] >= '0' && p[1] <= '7') { c = (c << 3) + *(++p) - '0'; if (p + 1 < e && p[1] >= '0' && p[1] <= '7' && p[-1] <= '3') c = (c << 3) + *(++p) - '0'; } *data++ = c; } else { // escaped *data++ = *p; } } else { *data++ = *p; } } pattern.truncate(data - pattern.data()); return pattern; } QMimeMagicRule::QMimeMagicRule(QMimeMagicRule::Type type, const QByteArray &value, int startPos, int endPos, const QByteArray &mask) : d(new QMimeMagicRulePrivate) { Q_ASSERT(!value.isEmpty()); d->type = type; d->value = value; d->startPos = startPos; d->endPos = endPos; d->mask = mask; d->matchFunction = 0; if (d->type >= Host16 && d->type <= Byte) { bool ok; d->number = d->value.toUInt(&ok, 0); // autodetect Q_ASSERT(ok); d->numberMask = !d->mask.isEmpty() ? d->mask.toUInt(&ok, 0) : 0; // autodetect } switch (d->type) { case String: d->pattern = makePattern(d->value); d->pattern.squeeze(); if (!d->mask.isEmpty()) { Q_ASSERT(d->mask.size() >= 4 && d->mask.startsWith("0x")); d->mask = QByteArray::fromHex(QByteArray::fromRawData(d->mask.constData() + 2, d->mask.size() - 2)); Q_ASSERT(d->mask.size() == d->pattern.size()); // apply mask to pattern const char *m = d->mask.constData(); char *p = d->pattern.data(); const char *e = p + d->pattern.size(); while (p < e) *p++ &= *m++; } else { d->mask.fill(0xff, d->pattern.size()); } d->mask.squeeze(); d->matchFunction = matchString; break; case Byte: if (d->number <= quint8(-1)) { if (d->numberMask == 0) d->numberMask = quint8(-1); d->matchFunction = matchNumber<quint8>; } break; case Big16: case Host16: case Little16: if (d->number <= quint16(-1)) { d->number = d->type == Little16 ? qFromLittleEndian<quint16>(d->number) : qFromBigEndian<quint16>(d->number); if (d->numberMask == 0) d->numberMask = quint16(-1); d->matchFunction = matchNumber<quint16>; } break; case Big32: case Host32: case Little32: if (d->number <= quint32(-1)) { d->number = d->type == Little32 ? qFromLittleEndian<quint32>(d->number) : qFromBigEndian<quint32>(d->number); if (d->numberMask == 0) d->numberMask = quint32(-1); d->matchFunction = matchNumber<quint32>; } break; default: break; } } QMimeMagicRule::QMimeMagicRule(const QMimeMagicRule &other) : d(new QMimeMagicRulePrivate(*other.d)) { } QMimeMagicRule::~QMimeMagicRule() { } QMimeMagicRule& QMimeMagicRule::operator=(const QMimeMagicRule &other) { *d = *other.d; return *this; } QMimeMagicRule::Type QMimeMagicRule::type() const { return d->type; } QByteArray QMimeMagicRule::value() const { return d->value; } int QMimeMagicRule::startPos() const { return d->startPos; } int QMimeMagicRule::endPos() const { return d->endPos; } QByteArray QMimeMagicRule::mask() const { QByteArray mask = d->mask; if (d->type == String) { // restore '0x' mask = "0x" + mask.toHex(); } return mask; } bool QMimeMagicRule::isValid() const { return d->matchFunction; } bool QMimeMagicRule::matches(const QByteArray &data) const { return d->matchFunction && d->matchFunction(d.data(), data); } QT_END_NAMESPACE <|endoftext|>
<commit_before>#include "aboutdialog.h" #include "ui_aboutdialog.h" #include "clientmodel.h" #include "clientversion.h" AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); // Set current copyright year ui->copyrightLabel->setText(tr("Copyright") + QString(" &copy; ") + tr("2009-%1 The Bitcoin developers").arg(COPYRIGHT_YEAR)); } void AboutDialog::setModel(ClientModel *model) { if(model) { ui->versionLabel->setText(model->formatFullVersion()); } } AboutDialog::~AboutDialog() { delete ui; } void AboutDialog::on_buttonBox_accepted() { close(); } <commit_msg>aboutdialog: use just "The Bitcoin developers" as tr()-string<commit_after>#include "aboutdialog.h" #include "ui_aboutdialog.h" #include "clientmodel.h" #include "clientversion.h" AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); // Set current copyright year ui->copyrightLabel->setText(tr("Copyright") + QString(" &copy; 2009-%1 ").arg(COPYRIGHT_YEAR) + tr("The Bitcoin developers")); } void AboutDialog::setModel(ClientModel *model) { if(model) { ui->versionLabel->setText(model->formatFullVersion()); } } AboutDialog::~AboutDialog() { delete ui; } void AboutDialog::on_buttonBox_accepted() { close(); } <|endoftext|>
<commit_before>// Copyright (c) 2011-2017 The Bitcoin developers // Copyright (c) 2015-2021 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "qt/rpcexecutor.h" #include "rpc/client.h" #ifdef ENABLE_WALLET #include "wallet/wallet.h" #endif #include <QUrlQuery> #include <univalue.h> QString RPCExecutor::categoryClass(int category) { switch (category) { case CMD_REQUEST: return "cmd-request"; break; case CMD_REPLY: return "cmd-reply"; break; case CMD_ERROR: return "cmd-error"; break; default: return "misc"; } } void RPCExecutor::request(const QString& command) { try { std::string result; std::string executableCommand = command.toStdString() + "\n"; // Catch the console-only-help command before RPC call is executed and reply with help text as-if a RPC reply. if(executableCommand == "help-console\n") { Q_EMIT reply(CMD_REPLY, QString(("\n" "This console accepts RPC commands using the standard syntax.\n" " example: getblockhash 0\n\n" "This console can also accept RPC commands using parenthesized syntax.\n" " example: getblockhash(0)\n\n" "Commands may be nested when specified with the parenthesized syntax.\n" " example: getblock(getblockhash(0) true)\n\n" "A space or a comma can be used to delimit arguments for either syntax.\n" " example: getblockhash 0\n" " getblockhash,0\n\n" "Named results can be queried with a non-quoted key string in brackets.\n" " example: getblock(getblockhash(0) true)[tx]\n\n" "Results without keys can be queried using an integer in brackets.\n" " example: getblock(getblockhash(0),true)[tx][0]\n\n"))); return; } if(!ExecuteCommandLine(result, executableCommand)) { Q_EMIT reply(CMD_ERROR, QString("Parse error: unbalanced ' or \"")); return; } Q_EMIT reply(CMD_REPLY, QString::fromStdString(result)); } catch (UniValue& objError) { try { // Nice formatting for standard-format error int code = find_value(objError, "code").get_int(); std::string message = find_value(objError, "message").get_str(); Q_EMIT reply(CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")"); } catch (const std::runtime_error&) { // raised when converting to invalid type, i.e. missing code or message // Show raw JSON object Q_EMIT reply(CMD_ERROR, QString::fromStdString(objError.write())); } } catch (const std::exception& e) { Q_EMIT reply(CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what())); } } /** * Split shell command line into a list of arguments and execute the command(s). * Aims to emulate \c bash and friends. * * - Command nesting is possible with brackets [example: validateaddress(getnewaddress())] * - Arguments are delimited with whitespace or comma * - Extra whitespace at the beginning and end and between arguments will be ignored * - Text can be "double" or 'single' quoted * - The backslash \c \ is used as escape character * - Outside quotes, any character can be escaped * - Within double quotes, only escape \c " and backslashes before a \c " or another backslash * - Within single quotes, no escaping is possible and no special interpretation takes place * * @param[out] result stringified Result from the executed command(chain) * @param[in] strCommand Command line to split */ bool RPCExecutor::ExecuteCommandLine(std::string& strResult, const std::string& strCommand) { std::vector< std::vector<std::string> > stack; stack.push_back(std::vector<std::string>()); enum CmdParseState { STATE_EATING_SPACES, STATE_EATING_SPACES_IN_ARG, STATE_ARGUMENT, STATE_SINGLEQUOTED, STATE_DOUBLEQUOTED, STATE_ESCAPE_OUTER, STATE_ESCAPE_DOUBLEQUOTED, STATE_COMMAND_EXECUTED, STATE_COMMAND_EXECUTED_INNER } state = STATE_EATING_SPACES; std::string curarg; UniValue lastResult; std::string strCommandTerminated = strCommand; if (strCommandTerminated.back() != '\n') strCommandTerminated += "\n"; for(char ch: strCommandTerminated) { switch(state) { case STATE_COMMAND_EXECUTED_INNER: case STATE_COMMAND_EXECUTED: { bool breakParsing = true; switch(ch) { case '[': curarg.clear(); state = STATE_COMMAND_EXECUTED_INNER; break; default: if (state == STATE_COMMAND_EXECUTED_INNER) { if (ch != ']') { // append char to the current argument (which is also used for the query command) curarg += ch; break; } if (curarg.size()) { // if we have a value query, query arrays with index and objects with a string key UniValue subelement; if (lastResult.isArray()) { for(char argch: curarg) if (!std::isdigit(argch)) throw std::runtime_error("Invalid result query"); subelement = lastResult[atoi(curarg.c_str())]; } else if (lastResult.isObject()) subelement = find_value(lastResult, curarg); else throw std::runtime_error("Invalid result query"); //no array or object: abort lastResult = subelement; } state = STATE_COMMAND_EXECUTED; break; } // don't break parsing when the char is required for the next argument breakParsing = false; // pop the stack and return the result to the current command arguments stack.pop_back(); // don't stringify the json in case of a string to avoid doublequotes if (lastResult.isStr()) curarg = lastResult.get_str(); else curarg = lastResult.write(2); // if we have a non empty result, use it as stack argument otherwise as general result if (curarg.size()) { if (stack.size()) stack.back().push_back(curarg); else strResult = curarg; } curarg.clear(); // assume eating space state state = STATE_EATING_SPACES; } if (breakParsing) break; } case STATE_ARGUMENT: // In or after argument case STATE_EATING_SPACES_IN_ARG: case STATE_EATING_SPACES: // Handle runs of whitespace switch(ch) { case '"': state = STATE_DOUBLEQUOTED; break; case '\'': state = STATE_SINGLEQUOTED; break; case '\\': state = STATE_ESCAPE_OUTER; break; case '(': case ')': case '\n': if (state == STATE_ARGUMENT) { if (ch == '(' && stack.size() && stack.back().size() > 0) stack.push_back(std::vector<std::string>()); // don't allow commands after executed commands on baselevel if (!stack.size()) throw std::runtime_error("Invalid Syntax"); stack.back().push_back(curarg); curarg.clear(); state = STATE_EATING_SPACES; } if ((ch == ')' || ch == '\n') && stack.size() > 0) { std::string strPrint; // Convert argument list to JSON objects in method-dependent way, // and pass it along with the method name to the dispatcher. JSONRPCRequest req; req.params = RPCConvertValues(stack.back()[0], std::vector<std::string>(stack.back().begin() + 1, stack.back().end())); req.strMethod = stack.back()[0]; #ifdef ENABLE_WALLET // TODO: Move this logic to WalletModel if (!vpwallets.empty()) { // in Qt, use always the wallet with index 0 when running with multiple wallets QByteArray encodedName = QUrl::toPercentEncoding(QString::fromStdString(vpwallets[0]->GetName())); req.URI = "/wallet/"+std::string(encodedName.constData(), encodedName.length()); } #endif lastResult = tableRPC.execute(req); state = STATE_COMMAND_EXECUTED; curarg.clear(); } break; case ' ': case ',': case '\t': if(state == STATE_ARGUMENT || (state == STATE_EATING_SPACES_IN_ARG && ch == ',')) // Space ends argument { stack.back().push_back(curarg); curarg.clear(); } state = (ch == ',' ? STATE_EATING_SPACES_IN_ARG : STATE_EATING_SPACES); break; default: curarg += ch; state = STATE_ARGUMENT; } break; case STATE_SINGLEQUOTED: // Single-quoted string switch(ch) { case '\'': state = STATE_ARGUMENT; break; default: curarg += ch; } break; case STATE_DOUBLEQUOTED: // Double-quoted string switch(ch) { case '"': state = STATE_ARGUMENT; break; case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break; default: curarg += ch; } break; case STATE_ESCAPE_OUTER: // '\' outside quotes curarg += ch; state = STATE_ARGUMENT; break; case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself curarg += ch; state = STATE_DOUBLEQUOTED; break; } } switch (state) // final state { case STATE_COMMAND_EXECUTED: if (lastResult.isStr()) strResult = lastResult.get_str(); else strResult = lastResult.write(2); case STATE_ARGUMENT: case STATE_EATING_SPACES: return true; default: // ERROR to end in one of the other states return false; } } <commit_msg>[Qt] Console: don't allow empty arguments when using the comma-syntax<commit_after>// Copyright (c) 2011-2017 The Bitcoin developers // Copyright (c) 2015-2021 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "qt/rpcexecutor.h" #include "rpc/client.h" #ifdef ENABLE_WALLET #include "wallet/wallet.h" #endif #include <QUrlQuery> #include <univalue.h> QString RPCExecutor::categoryClass(int category) { switch (category) { case CMD_REQUEST: return "cmd-request"; break; case CMD_REPLY: return "cmd-reply"; break; case CMD_ERROR: return "cmd-error"; break; default: return "misc"; } } void RPCExecutor::request(const QString& command) { try { std::string result; std::string executableCommand = command.toStdString() + "\n"; // Catch the console-only-help command before RPC call is executed and reply with help text as-if a RPC reply. if(executableCommand == "help-console\n") { Q_EMIT reply(CMD_REPLY, QString(("\n" "This console accepts RPC commands using the standard syntax.\n" " example: getblockhash 0\n\n" "This console can also accept RPC commands using parenthesized syntax.\n" " example: getblockhash(0)\n\n" "Commands may be nested when specified with the parenthesized syntax.\n" " example: getblock(getblockhash(0) true)\n\n" "A space or a comma can be used to delimit arguments for either syntax.\n" " example: getblockhash 0\n" " getblockhash,0\n\n" "Named results can be queried with a non-quoted key string in brackets.\n" " example: getblock(getblockhash(0) true)[tx]\n\n" "Results without keys can be queried using an integer in brackets.\n" " example: getblock(getblockhash(0),true)[tx][0]\n\n"))); return; } if(!ExecuteCommandLine(result, executableCommand)) { Q_EMIT reply(CMD_ERROR, QString("Parse error: unbalanced ' or \"")); return; } Q_EMIT reply(CMD_REPLY, QString::fromStdString(result)); } catch (UniValue& objError) { try { // Nice formatting for standard-format error int code = find_value(objError, "code").get_int(); std::string message = find_value(objError, "message").get_str(); Q_EMIT reply(CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")"); } catch (const std::runtime_error&) { // raised when converting to invalid type, i.e. missing code or message // Show raw JSON object Q_EMIT reply(CMD_ERROR, QString::fromStdString(objError.write())); } } catch (const std::exception& e) { Q_EMIT reply(CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what())); } } /** * Split shell command line into a list of arguments and execute the command(s). * Aims to emulate \c bash and friends. * * - Command nesting is possible with brackets [example: validateaddress(getnewaddress())] * - Arguments are delimited with whitespace or comma * - Extra whitespace at the beginning and end and between arguments will be ignored * - Text can be "double" or 'single' quoted * - The backslash \c \ is used as escape character * - Outside quotes, any character can be escaped * - Within double quotes, only escape \c " and backslashes before a \c " or another backslash * - Within single quotes, no escaping is possible and no special interpretation takes place * * @param[out] result stringified Result from the executed command(chain) * @param[in] strCommand Command line to split */ bool RPCExecutor::ExecuteCommandLine(std::string& strResult, const std::string& strCommand) { std::vector< std::vector<std::string> > stack; stack.push_back(std::vector<std::string>()); enum CmdParseState { STATE_EATING_SPACES, STATE_EATING_SPACES_IN_ARG, STATE_EATING_SPACES_IN_BRACKETS, STATE_ARGUMENT, STATE_SINGLEQUOTED, STATE_DOUBLEQUOTED, STATE_ESCAPE_OUTER, STATE_ESCAPE_DOUBLEQUOTED, STATE_COMMAND_EXECUTED, STATE_COMMAND_EXECUTED_INNER } state = STATE_EATING_SPACES; std::string curarg; UniValue lastResult; std::string strCommandTerminated = strCommand; if (strCommandTerminated.back() != '\n') strCommandTerminated += "\n"; for(char ch: strCommandTerminated) { switch(state) { case STATE_COMMAND_EXECUTED_INNER: case STATE_COMMAND_EXECUTED: { bool breakParsing = true; switch(ch) { case '[': curarg.clear(); state = STATE_COMMAND_EXECUTED_INNER; break; default: if (state == STATE_COMMAND_EXECUTED_INNER) { if (ch != ']') { // append char to the current argument (which is also used for the query command) curarg += ch; break; } if (curarg.size()) { // if we have a value query, query arrays with index and objects with a string key UniValue subelement; if (lastResult.isArray()) { for(char argch: curarg) if (!std::isdigit(argch)) throw std::runtime_error("Invalid result query"); subelement = lastResult[atoi(curarg.c_str())]; } else if (lastResult.isObject()) subelement = find_value(lastResult, curarg); else throw std::runtime_error("Invalid result query"); //no array or object: abort lastResult = subelement; } state = STATE_COMMAND_EXECUTED; break; } // don't break parsing when the char is required for the next argument breakParsing = false; // pop the stack and return the result to the current command arguments stack.pop_back(); // don't stringify the json in case of a string to avoid doublequotes if (lastResult.isStr()) curarg = lastResult.get_str(); else curarg = lastResult.write(2); // if we have a non empty result, use it as stack argument otherwise as general result if (curarg.size()) { if (stack.size()) stack.back().push_back(curarg); else strResult = curarg; } curarg.clear(); // assume eating space state state = STATE_EATING_SPACES; } if (breakParsing) break; } case STATE_ARGUMENT: // In or after argument case STATE_EATING_SPACES_IN_ARG: case STATE_EATING_SPACES_IN_BRACKETS: case STATE_EATING_SPACES: // Handle runs of whitespace switch(ch) { case '"': state = STATE_DOUBLEQUOTED; break; case '\'': state = STATE_SINGLEQUOTED; break; case '\\': state = STATE_ESCAPE_OUTER; break; case '(': case ')': case '\n': if (state == STATE_EATING_SPACES_IN_ARG) throw std::runtime_error("Invalid Syntax"); if (state == STATE_ARGUMENT) { if (ch == '(' && stack.size() && stack.back().size() > 0) stack.push_back(std::vector<std::string>()); // don't allow commands after executed commands on baselevel if (!stack.size()) throw std::runtime_error("Invalid Syntax"); stack.back().push_back(curarg); curarg.clear(); state = STATE_EATING_SPACES_IN_BRACKETS; } if ((ch == ')' || ch == '\n') && stack.size() > 0) { std::string strPrint; // Convert argument list to JSON objects in method-dependent way, // and pass it along with the method name to the dispatcher. JSONRPCRequest req; req.params = RPCConvertValues(stack.back()[0], std::vector<std::string>(stack.back().begin() + 1, stack.back().end())); req.strMethod = stack.back()[0]; #ifdef ENABLE_WALLET // TODO: Move this logic to WalletModel if (!vpwallets.empty()) { // in Qt, use always the wallet with index 0 when running with multiple wallets QByteArray encodedName = QUrl::toPercentEncoding(QString::fromStdString(vpwallets[0]->GetName())); req.URI = "/wallet/"+std::string(encodedName.constData(), encodedName.length()); } #endif lastResult = tableRPC.execute(req); state = STATE_COMMAND_EXECUTED; curarg.clear(); } break; case ' ': case ',': case '\t': if(state == STATE_EATING_SPACES_IN_ARG && curarg.empty() && ch == ',') throw std::runtime_error("Invalid Syntax"); else if(state == STATE_ARGUMENT) // Space ends argument { stack.back().push_back(curarg); curarg.clear(); } if ((state == STATE_EATING_SPACES_IN_BRACKETS || state == STATE_ARGUMENT) && ch == ',') { state = STATE_EATING_SPACES_IN_ARG; break; } state = STATE_EATING_SPACES; break; default: curarg += ch; state = STATE_ARGUMENT; } break; case STATE_SINGLEQUOTED: // Single-quoted string switch(ch) { case '\'': state = STATE_ARGUMENT; break; default: curarg += ch; } break; case STATE_DOUBLEQUOTED: // Double-quoted string switch(ch) { case '"': state = STATE_ARGUMENT; break; case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break; default: curarg += ch; } break; case STATE_ESCAPE_OUTER: // '\' outside quotes curarg += ch; state = STATE_ARGUMENT; break; case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself curarg += ch; state = STATE_DOUBLEQUOTED; break; } } switch (state) // final state { case STATE_COMMAND_EXECUTED: if (lastResult.isStr()) strResult = lastResult.get_str(); else strResult = lastResult.write(2); case STATE_ARGUMENT: case STATE_EATING_SPACES: return true; default: // ERROR to end in one of the other states return false; } } <|endoftext|>
<commit_before>#ifdef HAVE_CONFIG_H #include "../../config.h" #endif #include "xplugin.h" #include "ltr_gui_prefs.h" #include "utils.h" #include <QMessageBox> #include <QFile> #include <QFileInfo> #include <QFileDialog> #include <QRegExp> static QMessageBox::StandardButton warningMessage(const QString &message) { ltr_int_log_message("XPlanr plugin install - %s\n", message.toUtf8().constData()); return QMessageBox::warning(NULL, QString::fromUtf8("Linuxtrack"), message, QMessageBox::Ok); } static void warn(const QString baseMsg, const QString explanation) { ltr_int_log_message("XPlanr plugin install - %s(%s)\n", baseMsg.toUtf8().constData(), explanation.toUtf8().constData()); warningMessage(QString::fromUtf8("%1\nSystem says: %2").arg(baseMsg).arg(explanation)); } static bool removePlugin(const QString targetName) { QFile target(targetName); if(target.exists()){ if(!target.remove()){ warn(QString::fromUtf8("Can't remove old plugin '%1'!").arg(targetName), target.errorString()); return false; } } return true; } static bool installPlugin(const QString sourceFile, const QString destFile) { ltr_int_log_message("Going to install '%s' to '%s'...\n", sourceFile.toUtf8().constData(), destFile.toUtf8().constData()); //Create destination path QFile src(sourceFile); QFile dest(destFile); if(!src.exists()){ warningMessage(QString::fromUtf8("Source file '%1' doesn't exist!").arg(sourceFile)); return false; } QFileInfo destInfo(destFile); QDir destDir = destInfo.dir(); //make sure the destination path exists if(!destDir.exists()){ if(!destDir.mkpath(destDir.path())){ warningMessage(QString::fromUtf8("Can't create output directory '%1'!").arg(destDir.path())); return false; } } //check if the file exists already if(dest.exists()){ if(!removePlugin(destFile)){ return false; } } //copy the new file if(!src.copy(destFile)){ warn(QString::fromUtf8("Can't copy file '%1' to '%2'!").arg(destFile).arg(destDir.path()), src.errorString()); return false; } return true; } void XPluginInstall::on_BrowseXPlane_pressed() { QString fileName = QFileDialog::getOpenFileName(this, QString::fromUtf8("Find XPlane executable"), QDir::homePath(), QString::fromUtf8("All Files (*)")); QRegExp pathRexp(QString::fromUtf8("^(.*/)[^/]+$")); if(pathRexp.indexIn(fileName) == -1){ reject(); return; } QString sourceFile32 = PrefProxy::getLibPath(QString::fromUtf8("xlinuxtrack9_32")); QString sourceFile = PrefProxy::getLibPath(QString::fromUtf8("xlinuxtrack9")); QString destPath = pathRexp.cap(1) + QString::fromUtf8("/Resources/plugins"); if(!QFile::exists(destPath)){ warningMessage(QString(QString::fromUtf8("Can't install XPlane plugin there:'") + fileName + QString::fromUtf8("'"))); reject(); return; } //Check for the old plugin and remove it if exists QString oldPlugin = destPath + QString::fromUtf8("/xlinuxtrack.xpl"); QFileInfo old(oldPlugin); if(old.exists()){ if(!removePlugin(oldPlugin)){ reject(); return; } } destPath += QString::fromUtf8("/xlinuxtrack/"); #ifndef DARWIN if(installPlugin(sourceFile32, destPath + QString::fromUtf8("/lin.xpl")) && installPlugin(sourceFile, destPath + QString::fromUtf8("/64/lin.xpl"))){ #else if(installPlugin(sourceFile, destPath + QString::fromUtf8("/mac.xpl"))){ #endif QMessageBox::information(NULL, QString::fromUtf8("Linuxtrack"), QString::fromUtf8("XPlane plugin installed successfuly!")); }else{ warningMessage(QString::fromUtf8("XPlane plugin installation failed!")); reject(); } accept(); } <commit_msg>Fixed a typo.<commit_after>#ifdef HAVE_CONFIG_H #include "../../config.h" #endif #include "xplugin.h" #include "ltr_gui_prefs.h" #include "utils.h" #include <QMessageBox> #include <QFile> #include <QFileInfo> #include <QFileDialog> #include <QRegExp> static QMessageBox::StandardButton warningMessage(const QString &message) { ltr_int_log_message("XPlane plugin install - %s\n", message.toUtf8().constData()); return QMessageBox::warning(NULL, QString::fromUtf8("Linuxtrack"), message, QMessageBox::Ok); } static void warn(const QString baseMsg, const QString explanation) { ltr_int_log_message("XPlane plugin install - %s(%s)\n", baseMsg.toUtf8().constData(), explanation.toUtf8().constData()); warningMessage(QString::fromUtf8("%1\nSystem says: %2").arg(baseMsg).arg(explanation)); } static bool removePlugin(const QString targetName) { QFile target(targetName); if(target.exists()){ if(!target.remove()){ warn(QString::fromUtf8("Can't remove old plugin '%1'!").arg(targetName), target.errorString()); return false; } } return true; } static bool installPlugin(const QString sourceFile, const QString destFile) { ltr_int_log_message("Going to install '%s' to '%s'...\n", sourceFile.toUtf8().constData(), destFile.toUtf8().constData()); //Create destination path QFile src(sourceFile); QFile dest(destFile); if(!src.exists()){ warningMessage(QString::fromUtf8("Source file '%1' doesn't exist!").arg(sourceFile)); return false; } QFileInfo destInfo(destFile); QDir destDir = destInfo.dir(); //make sure the destination path exists if(!destDir.exists()){ if(!destDir.mkpath(destDir.path())){ warningMessage(QString::fromUtf8("Can't create output directory '%1'!").arg(destDir.path())); return false; } } //check if the file exists already if(dest.exists()){ if(!removePlugin(destFile)){ return false; } } //copy the new file if(!src.copy(destFile)){ warn(QString::fromUtf8("Can't copy file '%1' to '%2'!").arg(destFile).arg(destDir.path()), src.errorString()); return false; } return true; } void XPluginInstall::on_BrowseXPlane_pressed() { QString fileName = QFileDialog::getOpenFileName(this, QString::fromUtf8("Find XPlane executable"), QDir::homePath(), QString::fromUtf8("All Files (*)")); QRegExp pathRexp(QString::fromUtf8("^(.*/)[^/]+$")); if(pathRexp.indexIn(fileName) == -1){ reject(); return; } QString sourceFile32 = PrefProxy::getLibPath(QString::fromUtf8("xlinuxtrack9_32")); QString sourceFile = PrefProxy::getLibPath(QString::fromUtf8("xlinuxtrack9")); QString destPath = pathRexp.cap(1) + QString::fromUtf8("/Resources/plugins"); if(!QFile::exists(destPath)){ warningMessage(QString(QString::fromUtf8("Can't install XPlane plugin there:'") + fileName + QString::fromUtf8("'"))); reject(); return; } //Check for the old plugin and remove it if exists QString oldPlugin = destPath + QString::fromUtf8("/xlinuxtrack.xpl"); QFileInfo old(oldPlugin); if(old.exists()){ if(!removePlugin(oldPlugin)){ reject(); return; } } destPath += QString::fromUtf8("/xlinuxtrack/"); #ifndef DARWIN if(installPlugin(sourceFile32, destPath + QString::fromUtf8("/lin.xpl")) && installPlugin(sourceFile, destPath + QString::fromUtf8("/64/lin.xpl"))){ #else if(installPlugin(sourceFile, destPath + QString::fromUtf8("/mac.xpl"))){ #endif QMessageBox::information(NULL, QString::fromUtf8("Linuxtrack"), QString::fromUtf8("XPlane plugin installed successfuly!")); }else{ warningMessage(QString::fromUtf8("XPlane plugin installation failed!")); reject(); } accept(); } <|endoftext|>
<commit_before>#include <stan/math/rev.hpp> #include <gtest/gtest.h> #include <stan/math/rev/functor/gradient.hpp> #include <iostream> #include <sstream> #include <vector> #include <stdexcept> #define TEST_CVODES_ADAMS 1 #define TEST_CVODES_BDF 2 using std::cos; using std::sin; double y1(double t, double omega, double chi) { return chi * cos(omega * t); } double dy1_domega(double t, double omega, double chi) { return -t * chi * sin(omega * t); } double dy1_dchi(double t, double omega, double chi) { return cos(omega * t); } double y2(double t, double omega, double chi) { return -omega * chi * sin(omega * t); } double dy2_domega(double t, double omega, double chi) { return -chi * (sin(omega * t) + omega * t * cos(omega * t)); } double dy2_dchi(double t, double omega, double chi) { return -omega * sin(omega * t); } struct sho_functor { template <typename T0, typename T1, typename T2> inline Eigen::Matrix<stan::return_type_t<T1, T2>, Eigen::Dynamic, 1> operator()(const T0& t, const Eigen::Matrix<T1, Eigen::Dynamic, 1>& y, std::ostream* msgs, const T2& omega) const { Eigen::Matrix<stan::return_type_t<T1, T2>, Eigen::Dynamic, 1> out(2); out << y.coeff(1), -omega * omega * y.coeff(0); return out; } }; /* template <int state> class test_functor_double_var { int lmm_; public: explicit test_functor_double_var(int lmm) : lmm_(lmm) {} template <typename T> inline T operator()(Eigen::Matrix<T, Eigen::Dynamic, 1>& x) const { sho_functor sho; T omega = x(0); Eigen::VectorXd y0(2); y0 << 1.25, 0.0; double t0 = 0.0; std::vector<double> ts{2.5, 5.0}; std::vector<Eigen::Matrix<T, Eigen::Dynamic, 1>> ys = (lmm_ == TEST_CVODES_ADAMS) ? stan::math::ode_adjoint(sho, y0, t0, ts, nullptr, omega) : stan::math::ode_bdf(sho, y0, t0, ts, nullptr, omega); return ys[1](state); } }; TEST(StanMathOdeIntegrateODEGradMat, double_var) { double omega = 0.5; double chi = 1.25; double t = 5; Eigen::VectorXd x(1); x(0) = omega; double f; Eigen::VectorXd grad(1); stan::math::nested_rev_autodiff nested; { // Adams test_functor_double_var<0> func1(TEST_CVODES_ADAMS); stan::math::gradient(func1, x, f, grad); EXPECT_NEAR(y1(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy1_domega(t, omega, chi), grad(0), 1e-6); test_functor_double_var<1> func2(TEST_CVODES_ADAMS); stan::math::gradient(func2, x, f, grad); EXPECT_NEAR(y2(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy2_domega(t, omega, chi), grad(0), 1e-6); } { // bdf test_functor_double_var<0> func1(TEST_CVODES_BDF); stan::math::gradient(func1, x, f, grad); EXPECT_NEAR(y1(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy1_domega(t, omega, chi), grad(0), 1e-7); test_functor_double_var<1> func2(TEST_CVODES_BDF); stan::math::gradient(func2, x, f, grad); EXPECT_NEAR(y2(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy2_domega(t, omega, chi), grad(0), 1e-7); } } */ template <int state> class test_functor_var_double { int lmm_; public: explicit test_functor_var_double(int lmm) : lmm_(lmm) {} template <typename T> inline T operator()(Eigen::Matrix<T, Eigen::Dynamic, 1>& x) const { sho_functor sho; double omega = 0.5; Eigen::Matrix<T, Eigen::Dynamic, 1> y0(2); y0 << x(0), 0.0; double t0 = 0.0; std::vector<double> ts{5.0}; std::vector<Eigen::Matrix<T, Eigen::Dynamic, 1>> ys = (lmm_ == TEST_CVODES_ADAMS) ? stan::math::ode_adjoint_tol(sho, y0, t0, ts, 1E-10, 1E-10, 10000, nullptr, omega) : stan::math::ode_bdf(sho, y0, t0, ts, nullptr, omega); return ys[0](state); } }; TEST(StanMathOdeIntegrateODEGradMat, var_double) { double omega = 0.5; double chi = 1.25; double t = 5; Eigen::VectorXd x(1); x(0) = chi; double f; Eigen::VectorXd grad(1); stan::math::nested_rev_autodiff nested; { // adams test_functor_var_double<0> func1(TEST_CVODES_ADAMS); stan::math::gradient(func1, x, f, grad); EXPECT_NEAR(y1(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy1_dchi(t, omega, chi), grad(0), 1e-7); test_functor_var_double<1> func2(TEST_CVODES_ADAMS); stan::math::gradient(func2, x, f, grad); EXPECT_NEAR(y2(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy2_dchi(t, omega, chi), grad(0), 1e-7); } { // bdf test_functor_var_double<0> func1(TEST_CVODES_BDF); stan::math::gradient(func1, x, f, grad); EXPECT_NEAR(y1(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy1_dchi(t, omega, chi), grad(0), 1e-7); test_functor_var_double<1> func2(TEST_CVODES_BDF); stan::math::gradient(func2, x, f, grad); EXPECT_NEAR(y2(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy2_dchi(t, omega, chi), grad(0), 1e-7); } } template <int state> class test_functor_var_var { int lmm_; public: explicit test_functor_var_var(int lmm) : lmm_(lmm) {} template <typename T> inline T operator()(Eigen::Matrix<T, Eigen::Dynamic, 1>& x) const { sho_functor sho; T omega = x(0); Eigen::Matrix<T, Eigen::Dynamic, 1> y0(2); y0 << x(1), 0.0; double t0 = 0.0; std::vector<double> ts{2.0, 5.0}; std::vector<Eigen::Matrix<T, Eigen::Dynamic, 1>> ys = (lmm_ == TEST_CVODES_ADAMS) ? stan::math::ode_adjoint_tol(sho, y0, t0, ts, 1E-10, 1E-10, 10000, nullptr, omega) : stan::math::ode_bdf(sho, y0, t0, ts, nullptr, omega); return ys[1](state); } }; TEST(StanMathOdeIntegrateODEGradMat, var_var) { double omega = 0.5; double chi = 1.25; double t = 5; Eigen::VectorXd x(2); x(0) = omega; x(1) = chi; double f; Eigen::VectorXd grad(2); { stan::math::nested_rev_autodiff nested; test_functor_var_var<0> func1(TEST_CVODES_ADAMS); stan::math::gradient(func1, x, f, grad); EXPECT_NEAR(y1(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy1_domega(t, omega, chi), grad(0), 1e-7); EXPECT_NEAR(dy1_dchi(t, omega, chi), grad(1), 1e-7); test_functor_var_var<1> func2(TEST_CVODES_ADAMS); stan::math::gradient(func2, x, f, grad); EXPECT_NEAR(y2(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy2_domega(t, omega, chi), grad(0), 1e-6); EXPECT_NEAR(dy2_dchi(t, omega, chi), grad(1), 1e-7); } { stan::math::nested_rev_autodiff nested; test_functor_var_var<0> func1(TEST_CVODES_BDF); stan::math::gradient(func1, x, f, grad); EXPECT_NEAR(y1(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy1_domega(t, omega, chi), grad(0), 1e-7); EXPECT_NEAR(dy1_dchi(t, omega, chi), grad(1), 1e-7); test_functor_var_var<1> func2(TEST_CVODES_BDF); stan::math::gradient(func2, x, f, grad); EXPECT_NEAR(y2(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy2_domega(t, omega, chi), grad(0), 1e-6); EXPECT_NEAR(dy2_dchi(t, omega, chi), grad(1), 1e-7); } } template <int state> class test_functor_sum_var_var { int lmm_; public: explicit test_functor_sum_var_var(int lmm) : lmm_(lmm) {} template <typename T> inline T operator()(Eigen::Matrix<T, Eigen::Dynamic, 1>& x) const { sho_functor sho; T omega = x(0); Eigen::Matrix<T, Eigen::Dynamic, 1> y0(2); y0 << x(1), 0.0; double t0 = 0.0; std::vector<double> ts{2.0, 5.0}; Eigen::VectorXd abs_tol_f(2); abs_tol_f << 1E-10, 1E-10; std::vector<Eigen::Matrix<T, Eigen::Dynamic, 1>> ys = (lmm_ == TEST_CVODES_ADAMS) ? stan::math::ode_adjoint_tol(sho, y0, t0, ts, 1E-10, 1E-10, 10000, nullptr, omega) : stan::math::ode_bdf(sho, y0, t0, ts, nullptr, omega); return stan::math::sum(ys[0](state) + ys[1](state)); } }; TEST(StanMathOdeIntegrateODEGradMat, sum_var_var) { double omega = 0.5; double chi = 1.25; double t1 = 2.0; double t2 = 5; Eigen::VectorXd x(2); x(0) = omega; x(1) = chi; double f; Eigen::VectorXd grad(2); { stan::math::nested_rev_autodiff nested; test_functor_sum_var_var<0> func1(TEST_CVODES_ADAMS); stan::math::gradient(func1, x, f, grad); EXPECT_NEAR(y1(t1, omega, chi) + y1(t2, omega, chi), f, 1e-8); EXPECT_NEAR(dy1_domega(t1, omega, chi) + dy1_domega(t2, omega, chi), grad(0), 1e-7); EXPECT_NEAR(dy1_dchi(t1, omega, chi) + dy1_dchi(t2, omega, chi), grad(1), 1e-7); test_functor_sum_var_var<1> func2(TEST_CVODES_ADAMS); stan::math::gradient(func2, x, f, grad); EXPECT_NEAR(y2(t1, omega, chi) + y2(t2, omega, chi), f, 1e-8); EXPECT_NEAR(dy2_domega(t1, omega, chi) + dy2_domega(t2, omega, chi), grad(0), 1e-6); EXPECT_NEAR(dy2_dchi(t1, omega, chi) + dy2_dchi(t2, omega, chi), grad(1), 1e-7); } { stan::math::nested_rev_autodiff nested; test_functor_sum_var_var<0> func1(TEST_CVODES_BDF); stan::math::gradient(func1, x, f, grad); EXPECT_NEAR(y1(t1, omega, chi) + y1(t2, omega, chi), f, 1e-8); EXPECT_NEAR(dy1_domega(t1, omega, chi) + dy1_domega(t2, omega, chi), grad(0), 1e-7); EXPECT_NEAR(dy1_dchi(t1, omega, chi) + dy1_dchi(t2, omega, chi), grad(1), 1e-7); test_functor_sum_var_var<1> func2(TEST_CVODES_BDF); stan::math::gradient(func2, x, f, grad); EXPECT_NEAR(y2(t1, omega, chi) + y2(t2, omega, chi), f, 1e-8); EXPECT_NEAR(dy2_domega(t1, omega, chi) + dy2_domega(t2, omega, chi), grad(0), 1e-6); EXPECT_NEAR(dy2_dchi(t1, omega, chi) + dy2_dchi(t2, omega, chi), grad(1), 1e-7); } } <commit_msg>enable more tests<commit_after>#include <stan/math/rev.hpp> #include <gtest/gtest.h> #include <stan/math/rev/functor/gradient.hpp> #include <iostream> #include <sstream> #include <vector> #include <stdexcept> #define TEST_CVODES_ADAMS 1 #define TEST_CVODES_BDF 2 using std::cos; using std::sin; double y1(double t, double omega, double chi) { return chi * cos(omega * t); } double dy1_domega(double t, double omega, double chi) { return -t * chi * sin(omega * t); } double dy1_dchi(double t, double omega, double chi) { return cos(omega * t); } double y2(double t, double omega, double chi) { return -omega * chi * sin(omega * t); } double dy2_domega(double t, double omega, double chi) { return -chi * (sin(omega * t) + omega * t * cos(omega * t)); } double dy2_dchi(double t, double omega, double chi) { return -omega * sin(omega * t); } struct sho_functor { template <typename T0, typename T1, typename T2> inline Eigen::Matrix<stan::return_type_t<T1, T2>, Eigen::Dynamic, 1> operator()(const T0& t, const Eigen::Matrix<T1, Eigen::Dynamic, 1>& y, std::ostream* msgs, const T2& omega) const { Eigen::Matrix<stan::return_type_t<T1, T2>, Eigen::Dynamic, 1> out(2); out << y.coeff(1), -omega * omega * y.coeff(0); return out; } }; template <int state> class test_functor_double_var { int lmm_; public: explicit test_functor_double_var(int lmm) : lmm_(lmm) {} template <typename T> inline T operator()(Eigen::Matrix<T, Eigen::Dynamic, 1>& x) const { sho_functor sho; T omega = x(0); Eigen::VectorXd y0(2); y0 << 1.25, 0.0; double t0 = 0.0; std::vector<double> ts{2.5, 5.0}; std::vector<Eigen::Matrix<T, Eigen::Dynamic, 1>> ys = (lmm_ == TEST_CVODES_ADAMS) ? stan::math::ode_adjoint_tol(sho, y0, t0, ts, 1E-10, 1E-10, 10000, nullptr, omega) : stan::math::ode_bdf(sho, y0, t0, ts, nullptr, omega); return ys[1](state); } }; TEST(StanMathOdeIntegrateODEGradMat, double_var) { double omega = 0.5; double chi = 1.25; double t = 5; Eigen::VectorXd x(1); x(0) = omega; double f; Eigen::VectorXd grad(1); stan::math::nested_rev_autodiff nested; { // Adams test_functor_double_var<0> func1(TEST_CVODES_ADAMS); stan::math::gradient(func1, x, f, grad); EXPECT_NEAR(y1(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy1_domega(t, omega, chi), grad(0), 1e-6); test_functor_double_var<1> func2(TEST_CVODES_ADAMS); stan::math::gradient(func2, x, f, grad); EXPECT_NEAR(y2(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy2_domega(t, omega, chi), grad(0), 1e-6); } { // bdf test_functor_double_var<0> func1(TEST_CVODES_BDF); stan::math::gradient(func1, x, f, grad); EXPECT_NEAR(y1(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy1_domega(t, omega, chi), grad(0), 1e-7); test_functor_double_var<1> func2(TEST_CVODES_BDF); stan::math::gradient(func2, x, f, grad); EXPECT_NEAR(y2(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy2_domega(t, omega, chi), grad(0), 1e-7); } } template <int state> class test_functor_var_double { int lmm_; public: explicit test_functor_var_double(int lmm) : lmm_(lmm) {} template <typename T> inline T operator()(Eigen::Matrix<T, Eigen::Dynamic, 1>& x) const { sho_functor sho; double omega = 0.5; Eigen::Matrix<T, Eigen::Dynamic, 1> y0(2); y0 << x(0), 0.0; double t0 = 0.0; std::vector<double> ts{5.0}; std::vector<Eigen::Matrix<T, Eigen::Dynamic, 1>> ys = (lmm_ == TEST_CVODES_ADAMS) ? stan::math::ode_adjoint_tol(sho, y0, t0, ts, 1E-10, 1E-10, 10000, nullptr, omega) : stan::math::ode_bdf(sho, y0, t0, ts, nullptr, omega); return ys[0](state); } }; TEST(StanMathOdeIntegrateODEGradMat, var_double) { double omega = 0.5; double chi = 1.25; double t = 5; Eigen::VectorXd x(1); x(0) = chi; double f; Eigen::VectorXd grad(1); stan::math::nested_rev_autodiff nested; { // adams test_functor_var_double<0> func1(TEST_CVODES_ADAMS); stan::math::gradient(func1, x, f, grad); EXPECT_NEAR(y1(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy1_dchi(t, omega, chi), grad(0), 1e-7); test_functor_var_double<1> func2(TEST_CVODES_ADAMS); stan::math::gradient(func2, x, f, grad); EXPECT_NEAR(y2(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy2_dchi(t, omega, chi), grad(0), 1e-7); } { // bdf test_functor_var_double<0> func1(TEST_CVODES_BDF); stan::math::gradient(func1, x, f, grad); EXPECT_NEAR(y1(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy1_dchi(t, omega, chi), grad(0), 1e-7); test_functor_var_double<1> func2(TEST_CVODES_BDF); stan::math::gradient(func2, x, f, grad); EXPECT_NEAR(y2(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy2_dchi(t, omega, chi), grad(0), 1e-7); } } template <int state> class test_functor_var_var { int lmm_; public: explicit test_functor_var_var(int lmm) : lmm_(lmm) {} template <typename T> inline T operator()(Eigen::Matrix<T, Eigen::Dynamic, 1>& x) const { sho_functor sho; T omega = x(0); Eigen::Matrix<T, Eigen::Dynamic, 1> y0(2); y0 << x(1), 0.0; double t0 = 0.0; std::vector<double> ts{2.0, 5.0}; std::vector<Eigen::Matrix<T, Eigen::Dynamic, 1>> ys = (lmm_ == TEST_CVODES_ADAMS) ? stan::math::ode_adjoint_tol(sho, y0, t0, ts, 1E-10, 1E-10, 10000, nullptr, omega) : stan::math::ode_bdf(sho, y0, t0, ts, nullptr, omega); return ys[1](state); } }; TEST(StanMathOdeIntegrateODEGradMat, var_var) { double omega = 0.5; double chi = 1.25; double t = 5; Eigen::VectorXd x(2); x(0) = omega; x(1) = chi; double f; Eigen::VectorXd grad(2); { stan::math::nested_rev_autodiff nested; test_functor_var_var<0> func1(TEST_CVODES_ADAMS); stan::math::gradient(func1, x, f, grad); EXPECT_NEAR(y1(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy1_domega(t, omega, chi), grad(0), 1e-7); EXPECT_NEAR(dy1_dchi(t, omega, chi), grad(1), 1e-7); test_functor_var_var<1> func2(TEST_CVODES_ADAMS); stan::math::gradient(func2, x, f, grad); EXPECT_NEAR(y2(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy2_domega(t, omega, chi), grad(0), 1e-6); EXPECT_NEAR(dy2_dchi(t, omega, chi), grad(1), 1e-7); } { stan::math::nested_rev_autodiff nested; test_functor_var_var<0> func1(TEST_CVODES_BDF); stan::math::gradient(func1, x, f, grad); EXPECT_NEAR(y1(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy1_domega(t, omega, chi), grad(0), 1e-7); EXPECT_NEAR(dy1_dchi(t, omega, chi), grad(1), 1e-7); test_functor_var_var<1> func2(TEST_CVODES_BDF); stan::math::gradient(func2, x, f, grad); EXPECT_NEAR(y2(t, omega, chi), f, 1e-8); EXPECT_NEAR(dy2_domega(t, omega, chi), grad(0), 1e-6); EXPECT_NEAR(dy2_dchi(t, omega, chi), grad(1), 1e-7); } } template <int state> class test_functor_sum_var_var { int lmm_; public: explicit test_functor_sum_var_var(int lmm) : lmm_(lmm) {} template <typename T> inline T operator()(Eigen::Matrix<T, Eigen::Dynamic, 1>& x) const { sho_functor sho; T omega = x(0); Eigen::Matrix<T, Eigen::Dynamic, 1> y0(2); y0 << x(1), 0.0; double t0 = 0.0; std::vector<double> ts{2.0, 5.0}; Eigen::VectorXd abs_tol_f(2); abs_tol_f << 1E-10, 1E-10; std::vector<Eigen::Matrix<T, Eigen::Dynamic, 1>> ys = (lmm_ == TEST_CVODES_ADAMS) ? stan::math::ode_adjoint_tol(sho, y0, t0, ts, 1E-10, 1E-10, 10000, nullptr, omega) : stan::math::ode_bdf(sho, y0, t0, ts, nullptr, omega); return stan::math::sum(ys[0](state) + ys[1](state)); } }; TEST(StanMathOdeIntegrateODEGradMat, sum_var_var) { double omega = 0.5; double chi = 1.25; double t1 = 2.0; double t2 = 5; Eigen::VectorXd x(2); x(0) = omega; x(1) = chi; double f; Eigen::VectorXd grad(2); { stan::math::nested_rev_autodiff nested; test_functor_sum_var_var<0> func1(TEST_CVODES_ADAMS); stan::math::gradient(func1, x, f, grad); EXPECT_NEAR(y1(t1, omega, chi) + y1(t2, omega, chi), f, 1e-8); EXPECT_NEAR(dy1_domega(t1, omega, chi) + dy1_domega(t2, omega, chi), grad(0), 1e-7); EXPECT_NEAR(dy1_dchi(t1, omega, chi) + dy1_dchi(t2, omega, chi), grad(1), 1e-7); test_functor_sum_var_var<1> func2(TEST_CVODES_ADAMS); stan::math::gradient(func2, x, f, grad); EXPECT_NEAR(y2(t1, omega, chi) + y2(t2, omega, chi), f, 1e-8); EXPECT_NEAR(dy2_domega(t1, omega, chi) + dy2_domega(t2, omega, chi), grad(0), 1e-6); EXPECT_NEAR(dy2_dchi(t1, omega, chi) + dy2_dchi(t2, omega, chi), grad(1), 1e-7); } { stan::math::nested_rev_autodiff nested; test_functor_sum_var_var<0> func1(TEST_CVODES_BDF); stan::math::gradient(func1, x, f, grad); EXPECT_NEAR(y1(t1, omega, chi) + y1(t2, omega, chi), f, 1e-8); EXPECT_NEAR(dy1_domega(t1, omega, chi) + dy1_domega(t2, omega, chi), grad(0), 1e-7); EXPECT_NEAR(dy1_dchi(t1, omega, chi) + dy1_dchi(t2, omega, chi), grad(1), 1e-7); test_functor_sum_var_var<1> func2(TEST_CVODES_BDF); stan::math::gradient(func2, x, f, grad); EXPECT_NEAR(y2(t1, omega, chi) + y2(t2, omega, chi), f, 1e-8); EXPECT_NEAR(dy2_domega(t1, omega, chi) + dy2_domega(t2, omega, chi), grad(0), 1e-6); EXPECT_NEAR(dy2_dchi(t1, omega, chi) + dy2_dchi(t2, omega, chi), grad(1), 1e-7); } } <|endoftext|>
<commit_before>/* * perf-timer.cpp */ #if USE_PERF_TIMER #include "perf-timer.hpp" #include <cassert> #include <stdexcept> #include <string> #include <vector> #include <iostream> #include <cstdlib> #include <linux/perf_event.h> #include <sched.h> extern "C" { #include "pmu-tools/jevents/jevents.h" #include "pmu-tools/jevents/rdpmc.h" } #include "table.hpp" #include "timers.hpp" #include "util.hpp" #include "context.hpp" using namespace std; struct PerfEvent { enum Type { RAW, PERF } type; std::string name, perf_string, desc, pmu; }; struct RunningEvent { rdpmc_ctx ctx; std::string name; std::string header; RunningEvent(const rdpmc_ctx& ctxx, const std::string& name) : ctx(ctxx), name{name}, header{make_header(name)} {} static std::string make_header(std::string name) { return name.substr(0, std::min((size_t)6, name.length())); } }; static int init_count; static vector<RunningEvent> running_events; int do_read_events() { return read_events(nullptr); } typedef int (*walker_callback_t)(void *data, char *name, char *event, char *desc); typedef int (*walker_t)(walker_callback_t callback, void *data); std::vector<PerfEvent> get_events(PerfEvent::Type type, walker_t walker) { vector<PerfEvent> events; walker([](void *data, char *name, char *event, char *desc) -> int { ((vector<PerfEvent>*)data)->push_back(PerfEvent{PerfEvent::RAW, name, event, desc}); return 0; }, &events); return events; } std::vector<PerfEvent> get_raw_events() { return get_events(PerfEvent::RAW, walk_events); } std::vector<PerfEvent> get_perf_events() { return get_events(PerfEvent::PERF, walk_perf_events); } std::vector<PerfEvent> get_all_events() { auto raw = get_raw_events(); auto perf = get_perf_events(); std::vector<PerfEvent> ret(raw.begin(), raw.end()); ret.insert(ret.end(), perf.begin(), perf.end()); return ret; } std::string to_hex_string(long l) { return string_format("%lx", l); } /** * Take a perf_event_attr objects and return a string representation suitable * for use as an event for perf, or just for display. */ std::string perf_attr_to_string(const perf_event_attr* attr) { std::string ret; char* pmu = resolve_pmu(attr->type); ret += std::string(pmu ? pmu : "???") + "/"; #define APPEND_IF_NZ1(field) APPEND_IF_NZ2(field,field) #define APPEND_IF_NZ2(name, field) if (attr->field) ret += std::string(#name) + "=0x" + to_hex_string(attr->field) + "," APPEND_IF_NZ1(config); APPEND_IF_NZ1(config1); APPEND_IF_NZ1(config2); APPEND_IF_NZ2(period, sample_period); APPEND_IF_NZ1(sample_type); APPEND_IF_NZ1(read_format); ret.at(ret.length() - 1) = '/'; return ret; } PerfTimer::PerfTimer(Context& c) : TimerInfo( "perf", "A timer which uses rdpmc and the perf_events subsystem for accurate cycle measurements", {}) {} PerfNow PerfTimer::delta(const PerfNow& a, const PerfNow& b) { PerfNow ret; for (unsigned i = 0; i < PerfNow::READING_COUNT; i++) { ret.readings[i] = a.readings[i] - b.readings[i]; } return ret; } TimingResult PerfTimer::to_result(const PerfTimer& ti, PerfNow delta) { size_t count = running_events.size(); vector<double> results; results.resize(count); for (size_t i = 0; i < count; i++) { results[i] = delta.readings[i]; } return { results }; } /** * modify the event after getting in back from resolve event, e.g., * to remove the period, exclude kernel mode if necessary, etc */ void fixup_event(perf_event_attr* attr, bool user_only) { attr->sample_period = 0; attr->pinned = 1; if (user_only) { attr->exclude_kernel = 1; } } void print_caps(ostream& os, const rdpmc_ctx& ctx) { os << "caps:" << " R:" << ctx.buf->cap_user_rdpmc << " UT:" << ctx.buf->cap_user_time << " ZT:" << ctx.buf->cap_user_time_zero << " index: 0x" << to_hex_string(ctx.buf->index) << endl; } void PerfTimer::init(Context &c) { assert(init_count++ == 0); const TimerArgs& args = c.getTimerArgs(); int res = do_read_events(); if (res) { throw std::runtime_error("jevents failed while reading events: " + errno_to_str(res)); } bool user_only = false; { // init cycles event rdpmc_ctx ctx{}; struct perf_event_attr cycles_attr = { .type = PERF_TYPE_HARDWARE, .size = PERF_ATTR_SIZE_VER0, .config = PERF_COUNT_HW_CPU_CYCLES }; if (rdpmc_open_attr(&cycles_attr, &ctx, nullptr)) { // maybe it failed because we try to get kernel cycles too, and perf_event_paranoid is >= 2 // so try again excluding kernel to see if that works cycles_attr.exclude_kernel = 1; if (rdpmc_open_attr(&cycles_attr, &ctx, nullptr)) { throw std::runtime_error("rdpmc_open cycles failed, checked stderr for more"); } else { c.out() << "Counting user-mode events only: set /proc/sys/kernel/perf_event_paranoid to 1 or less to count kernel events\n"; user_only = true; } } c.out() << "Programmed cycles event, "; print_caps(c.out(), ctx); running_events.emplace_back(ctx, "Cycles"); } for (auto&e : split_on_string(args.extra_events, "|")) { if (e.empty()) { continue; } if (running_events.size() == PerfNow::READING_COUNT) { c.err() << "Event '" << e << "' - check the available events with --list-events" << endl; continue; } perf_event_attr attr = {}; if (resolve_event(e.c_str(), &attr)) { c.out() << "Unable to resolve event '" << e << "' - check the available events with --list-events" << endl; } else { fixup_event(&attr, user_only); rdpmc_ctx ctx{}; if (rdpmc_open_attr(&attr, &ctx, nullptr)) { c.err() << "Failed to program event '" << e << "' (resolved to '" << perf_attr_to_string(&attr) << "')\n"; } else { c.out() << "Resolved and programmed event '" << e << "' to '" << perf_attr_to_string(&attr) << "', "; print_caps(c.out(), ctx); if (ctx.buf->index == 0) { c.err() << "Failed to program event '" << e << "' (index == 0, rdpmc not available)" << endl; rdpmc_close(&ctx); } else { running_events.emplace_back(ctx, e); } } } } assert(running_events.size() <= PerfNow::READING_COUNT); for (auto& e : running_events) { metric_names_.push_back(e.header); } } template <typename E> void printEvents(Context& c, E event_func) { table::Table t; auto& header_row = t.newRow().add("Name").add("Event string"); if (c.verbose()) { header_row.add("Description"); } auto events = event_func(); for (auto e : events) { auto& event_row = t.newRow().add(e.name).add(e.perf_string); if (c.verbose()) { event_row.add(e.desc); } } c.out() << t.str(); } void PerfTimer::listEvents(Context& c) { const char *dashes = "----------------------------------------------\n"; c.out() << dashes << "Generic perf HW events\n" << dashes << endl; printEvents(c, get_perf_events); c.out() << "\n\n"; c.out() << dashes << "Raw CPU-specific PMU events\n" << dashes << endl; printEvents(c, get_raw_events); } PerfTimer::now_t PerfTimer::now() { // there is an unfortunate mismatch between the one TimerInfo instance that is created, and the fact // that ::now is static, see issue #62 PerfNow ret; unsigned i = 0; for (RunningEvent& e : running_events) { ret.readings[i++] = rdpmc_read(&e.ctx); } return ret; } PerfTimer::~PerfTimer() = default; #endif // USE_PERF_TIMER <commit_msg>allow overriding of jevents event file via env var, some additional error handling<commit_after>/* * perf-timer.cpp */ #if USE_PERF_TIMER #include "perf-timer.hpp" #include <cassert> #include <stdexcept> #include <string> #include <vector> #include <iostream> #include <cstdlib> #include <linux/perf_event.h> #include <sched.h> extern "C" { #include "pmu-tools/jevents/jevents.h" #include "pmu-tools/jevents/rdpmc.h" } #include "table.hpp" #include "timers.hpp" #include "util.hpp" #include "context.hpp" using namespace std; struct PerfEvent { enum Type { RAW, PERF } type; std::string name, perf_string, desc, pmu; }; struct RunningEvent { rdpmc_ctx ctx; std::string name; std::string header; RunningEvent(const rdpmc_ctx& ctxx, const std::string& name) : ctx(ctxx), name{name}, header{make_header(name)} {} static std::string make_header(std::string name) { return name.substr(0, std::min((size_t)6, name.length())); } }; static int init_count; static vector<RunningEvent> running_events; void do_read_events(Context& c) { const char* event_file; if ((event_file = getenv("UARCH_BENCH_FORCE_EVENT_FILE"))) { c.log() << "Using forced perf events file: " << event_file << std::endl; } int res = read_events(event_file); if (res) { throw std::runtime_error(std::string("jevents failed while reading events, error ") + std::to_string(res) + ": " + jevent_error_to_string(res) + ". Details: " + jevent_get_error_details()); } } typedef int (*walker_callback_t)(void *data, char *name, char *event, char *desc); typedef int (*walker_t)(walker_callback_t callback, void *data); std::vector<PerfEvent> get_events(PerfEvent::Type type, walker_t walker) { vector<PerfEvent> events; walker([](void *data, char *name, char *event, char *desc) -> int { ((vector<PerfEvent>*)data)->push_back(PerfEvent{PerfEvent::RAW, name, event, desc}); return 0; }, &events); return events; } std::vector<PerfEvent> get_raw_events() { return get_events(PerfEvent::RAW, walk_events); } std::vector<PerfEvent> get_perf_events() { return get_events(PerfEvent::PERF, walk_perf_events); } std::vector<PerfEvent> get_all_events() { auto raw = get_raw_events(); auto perf = get_perf_events(); std::vector<PerfEvent> ret(raw.begin(), raw.end()); ret.insert(ret.end(), perf.begin(), perf.end()); return ret; } std::string to_hex_string(long l) { return string_format("%lx", l); } /** * Take a perf_event_attr objects and return a string representation suitable * for use as an event for perf, or just for display. */ std::string perf_attr_to_string(const perf_event_attr* attr) { std::string ret; char* pmu = resolve_pmu(attr->type); ret += std::string(pmu ? pmu : "???") + "/"; #define APPEND_IF_NZ1(field) APPEND_IF_NZ2(field,field) #define APPEND_IF_NZ2(name, field) if (attr->field) ret += std::string(#name) + "=0x" + to_hex_string(attr->field) + "," APPEND_IF_NZ1(config); APPEND_IF_NZ1(config1); APPEND_IF_NZ1(config2); APPEND_IF_NZ2(period, sample_period); APPEND_IF_NZ1(sample_type); APPEND_IF_NZ1(read_format); ret.at(ret.length() - 1) = '/'; return ret; } PerfTimer::PerfTimer(Context& c) : TimerInfo( "perf", "A timer which uses rdpmc and the perf_events subsystem for accurate cycle measurements", {}) {} PerfNow PerfTimer::delta(const PerfNow& a, const PerfNow& b) { PerfNow ret; for (unsigned i = 0; i < PerfNow::READING_COUNT; i++) { ret.readings[i] = a.readings[i] - b.readings[i]; } return ret; } TimingResult PerfTimer::to_result(const PerfTimer& ti, PerfNow delta) { size_t count = running_events.size(); vector<double> results; results.resize(count); for (size_t i = 0; i < count; i++) { results[i] = delta.readings[i]; } return { results }; } /** * modify the event after getting in back from resolve event, e.g., * to remove the period, exclude kernel mode if necessary, etc */ void fixup_event(perf_event_attr* attr, bool user_only) { attr->sample_period = 0; attr->pinned = 1; if (user_only) { attr->exclude_kernel = 1; } } void print_caps(ostream& os, const rdpmc_ctx& ctx) { os << "caps:" << " R:" << ctx.buf->cap_user_rdpmc << " UT:" << ctx.buf->cap_user_time << " ZT:" << ctx.buf->cap_user_time_zero << " index: 0x" << to_hex_string(ctx.buf->index) << endl; } void PerfTimer::init(Context &c) { assert(init_count++ == 0); const TimerArgs& args = c.getTimerArgs(); do_read_events(c); bool user_only = false; { // init cycles event rdpmc_ctx ctx{}; struct perf_event_attr cycles_attr = { .type = PERF_TYPE_HARDWARE, .size = PERF_ATTR_SIZE_VER0, .config = PERF_COUNT_HW_CPU_CYCLES }; if (rdpmc_open_attr(&cycles_attr, &ctx, nullptr)) { // maybe it failed because we try to get kernel cycles too, and perf_event_paranoid is >= 2 // so try again excluding kernel to see if that works cycles_attr.exclude_kernel = 1; if (rdpmc_open_attr(&cycles_attr, &ctx, nullptr)) { throw std::runtime_error("rdpmc_open cycles failed, checked stderr for more"); } else { c.out() << "Counting user-mode events only: set /proc/sys/kernel/perf_event_paranoid to 1 or less to count kernel events\n"; user_only = true; } } c.out() << "Programmed cycles event, "; print_caps(c.out(), ctx); running_events.emplace_back(ctx, "Cycles"); } for (auto&e : split_on_string(args.extra_events, "|")) { if (e.empty()) { continue; } if (running_events.size() == PerfNow::READING_COUNT) { c.err() << "Event '" << e << "' - check the available events with --list-events" << endl; continue; } perf_event_attr attr = {}; if (resolve_event(e.c_str(), &attr)) { c.out() << "Unable to resolve event '" << e << "' - check the available events with --list-events" << endl; } else { fixup_event(&attr, user_only); rdpmc_ctx ctx{}; if (rdpmc_open_attr(&attr, &ctx, nullptr)) { c.err() << "Failed to program event '" << e << "' (resolved to '" << perf_attr_to_string(&attr) << "')\n"; } else { c.out() << "Resolved and programmed event '" << e << "' to '" << perf_attr_to_string(&attr) << "', "; print_caps(c.out(), ctx); if (ctx.buf->index == 0) { c.err() << "Failed to program event '" << e << "' (index == 0, rdpmc not available)" << endl; rdpmc_close(&ctx); } else { running_events.emplace_back(ctx, e); } } } } assert(running_events.size() <= PerfNow::READING_COUNT); for (auto& e : running_events) { metric_names_.push_back(e.header); } } template <typename E> void printEvents(Context& c, E event_func) { table::Table t; auto& header_row = t.newRow().add("Name").add("Event string"); if (c.verbose()) { header_row.add("Description"); } auto events = event_func(); for (auto e : events) { auto& event_row = t.newRow().add(e.name).add(e.perf_string); if (c.verbose()) { event_row.add(e.desc); } } c.out() << t.str(); } void PerfTimer::listEvents(Context& c) { do_read_events(c); // need this before walking events or else the default lists will be used, not accounting for forced lists const char *dashes = "----------------------------------------------\n"; c.out() << dashes << "Generic perf HW events\n" << dashes << endl; printEvents(c, get_perf_events); c.out() << "\n\n"; c.out() << dashes << "Raw CPU-specific PMU events\n" << dashes << endl; printEvents(c, get_raw_events); } PerfTimer::now_t PerfTimer::now() { // there is an unfortunate mismatch between the one TimerInfo instance that is created, and the fact // that ::now is static, see issue #62 PerfNow ret; unsigned i = 0; for (RunningEvent& e : running_events) { ret.readings[i++] = rdpmc_read(&e.ctx); } return ret; } PerfTimer::~PerfTimer() = default; #endif // USE_PERF_TIMER <|endoftext|>
<commit_before>/*! * This file is part of CameraPlus. * * Copyright (C) 2012-2014 Mohammed Sameer <[email protected]> * * 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 "qtcamgstsample.h" #include <gst/gst.h> #include <QDebug> class QtCamGstSamplePrivate { public: GstBuffer *buffer; GstCaps *caps; #if GST_CHECK_VERSION(1,0,0) GstMapInfo info; bool mapped; #endif }; QtCamGstSample::QtCamGstSample(GstBuffer *buffer, GstCaps *caps) : d_ptr(new QtCamGstSamplePrivate) { d_ptr->buffer = gst_buffer_ref(buffer); d_ptr->caps = gst_caps_ref(caps); #if GST_CHECK_VERSION(1,0,0) d_ptr->mapped = false; #endif } QtCamGstSample::~QtCamGstSample() { #if GST_CHECK_VERSION(1,0,0) if (d_ptr->mapped) { gst_buffer_unmap (d_ptr->buffer, &d_ptr->info); d_ptr->mapped = false; } #endif gst_caps_unref(d_ptr->caps); gst_buffer_unref(d_ptr->buffer); delete d_ptr; d_ptr = 0; } GstBuffer *QtCamGstSample::buffer() const { return d_ptr->buffer; } GstCaps *QtCamGstSample::caps() const { return d_ptr->caps; } qint32 QtCamGstSample::width() const { const GstStructure *s = gst_caps_get_structure (d_ptr->caps, 0); qint32 w = -1; gst_structure_get_int (s, "width", &w); return w; } qint32 QtCamGstSample::height() const { const GstStructure *s = gst_caps_get_structure (d_ptr->caps, 0); qint32 h = -1; gst_structure_get_int (s, "height", &h); return h; } const uchar *QtCamGstSample::data() { #if GST_CHECK_VERSION(1,0,0) if (!d_ptr->mapped) { if (!gst_buffer_map (d_ptr->buffer, &d_ptr->info, GST_MAP_READ)) { qCritical() << "Failed to map buffer"; return NULL; } d_ptr->mapped = true; } return d_ptr->info.data; #else return GST_BUFFER_DATA (d_ptr->buffer); #endif } qint64 QtCamGstSample::size() { #if GST_CHECK_VERSION(1,0,0) return gst_buffer_get_size (d_ptr->buffer); #else return GST_BUFFER_SIZE (d_ptr->buffer); #endif } <commit_msg>qtcamera: parse width and height when we create QtCamGstSample<commit_after>/*! * This file is part of CameraPlus. * * Copyright (C) 2012-2014 Mohammed Sameer <[email protected]> * * 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 "qtcamgstsample.h" #include <gst/gst.h> #include <QDebug> class QtCamGstSamplePrivate { public: GstBuffer *buffer; GstCaps *caps; qint32 width; qint32 height; GstVideoFormat format; #if GST_CHECK_VERSION(1,0,0) GstMapInfo info; bool mapped; #endif }; QtCamGstSample::QtCamGstSample(GstBuffer *buffer, GstCaps *caps) : d_ptr(new QtCamGstSamplePrivate) { d_ptr->buffer = gst_buffer_ref(buffer); d_ptr->caps = gst_caps_ref(caps); #if GST_CHECK_VERSION(1,0,0) d_ptr->mapped = false; #endif d_ptr->width = -1; d_ptr->height = -1; d_ptr->format = GST_VIDEO_FORMAT_UNKNOWN; #if GST_CHECK_VERSION(1,0,0) GstVideoInfo info; if (!gst_video_info_from_caps (&info, d_ptr->caps)) { qCritical() << "Failed to parse GStreamer caps"; } else { d_ptr->width = info.width; d_ptr->height = info.height; d_ptr->format = info.finfo->format; } #else if (!gst_video_format_parse_caps (d_ptr->caps, &d_ptr->format, &d_ptr->width, &d_ptr->height)) { qCritical() << "Failed to parse GStreamer caps"; } #endif } QtCamGstSample::~QtCamGstSample() { #if GST_CHECK_VERSION(1,0,0) if (d_ptr->mapped) { gst_buffer_unmap (d_ptr->buffer, &d_ptr->info); d_ptr->mapped = false; } #endif gst_caps_unref(d_ptr->caps); gst_buffer_unref(d_ptr->buffer); delete d_ptr; d_ptr = 0; } GstBuffer *QtCamGstSample::buffer() const { return d_ptr->buffer; } GstCaps *QtCamGstSample::caps() const { return d_ptr->caps; } qint32 QtCamGstSample::width() const { return d_ptr->width; } qint32 QtCamGstSample::height() const { return d_ptr->height; } const uchar *QtCamGstSample::data() { #if GST_CHECK_VERSION(1,0,0) if (!d_ptr->mapped) { if (!gst_buffer_map (d_ptr->buffer, &d_ptr->info, GST_MAP_READ)) { qCritical() << "Failed to map buffer"; return NULL; } d_ptr->mapped = true; } return d_ptr->info.data; #else return GST_BUFFER_DATA (d_ptr->buffer); #endif } qint64 QtCamGstSample::size() { #if GST_CHECK_VERSION(1,0,0) return gst_buffer_get_size (d_ptr->buffer); #else return GST_BUFFER_SIZE (d_ptr->buffer); #endif } <|endoftext|>
<commit_before>/*! @file @copyright Edouard Alligand and Joel Falcou 2015-2017 (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_BRIGAND_FUNCTIONS_ARITHMETIC_MIN_HPP #define BOOST_BRIGAND_FUNCTIONS_ARITHMETIC_MIN_HPP #include <brigand/types/integral_constant.hpp> namespace brigand { template <typename A, typename B> struct min : brigand::integral_constant< typename std::decay<decltype((A::value < B::value) ? A::value : B::value)>::type, (A::value < B::value) ? A::value : B::value> { }; } #endif <commit_msg>Delete min.hpp<commit_after><|endoftext|>
<commit_before>/* * Copyright (C) 2013 midnightBITS * * 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 "pch.h" #include <dbconn.hpp> #include <crypt.hpp> namespace Crypt { namespace algorithm { struct SHA512 { bool m_inited; SHA512_CTX m_ctx; public: SHA512() { m_inited = SHA512_Init(&m_ctx) != 0; } ~SHA512() { if (m_inited) OPENSSL_cleanse(&m_ctx, sizeof(m_ctx)); } bool Update(const void* msg, size_t len) { if (!m_inited) return false; return SHA512_Update(&m_ctx, msg, len) != 0; } bool Final(SHA512Hash::digest_t& digest) { if (!m_inited) return false; return SHA512_Final(digest, &m_ctx) != 0; } }; struct MD5 { bool m_inited; MD5_CTX m_ctx; public: MD5() { m_inited = MD5_Init(&m_ctx) != 0; } ~MD5() { if (m_inited) OPENSSL_cleanse(&m_ctx, sizeof(m_ctx)); } bool Update(const void* msg, size_t len) { if (!m_inited) return false; return MD5_Update(&m_ctx, msg, len) != 0; } bool Final(MD5Hash::digest_t& digest) { if (!m_inited) return false; return MD5_Final(digest, &m_ctx) != 0; } }; }; bool SHA512Hash::__crypt(const char* salt, const char* message, size_t len, digest_t &digest) { algorithm::SHA512 alg; if (!alg.Update(salt, SALT_LENGTH)) return false; if (!alg.Update(message, len)) return false; return alg.Final(digest); } bool MD5Hash::__crypt(const char* salt, const char* message, size_t len, digest_t &digest) { algorithm::MD5 alg; if (!alg.Update(salt, SALT_LENGTH)) return false; if (!alg.Update(message, len)) return false; return alg.Final(digest); } bool verify(const char* message, const char* hash) { if (!hash) return false; char alg = hash[strlen(hash) - 1]; if (alg == SHA512Hash::ALG_ID) return SHA512Hash::verify(message, hash); if (alg == MD5Hash::ALG_ID) return MD5Hash::verify(message, hash); return false; } static char alphabet(size_t id) { static char alph[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; return alph[id]; } template <class T> T sslrand() { T ret; RAND_bytes((unsigned char*)&ret, sizeof(ret)); return ret; } static char randomChar() { return alphabet(sslrand<unsigned char>() >> 2); } void newSalt(char* salt, size_t len) { salt[--len] = 0; for (size_t i = 0; i < len; ++i) salt[i] = randomChar(); } void base64_encode(const void* data, size_t len, char* output) { const unsigned char* p = (const unsigned char*)data; size_t pos = 0; unsigned int bits = 0; unsigned int accu = 0; for (size_t i = 0; i < len; ++i) { accu = (accu << 8) | (p[i] & 0xFF); bits += 8; while (bits >= 6) { bits -= 6; output[pos++] = alphabet((accu >> bits) & 0x3F); } } if (bits > 0) { accu <<= 6 - bits; output[pos++] = alphabet(accu & 0x3F); } } };<commit_msg>Using more than 6 consecutive bits of randomness<commit_after>/* * Copyright (C) 2013 midnightBITS * * 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 "pch.h" #include <dbconn.hpp> #include <crypt.hpp> namespace Crypt { namespace algorithm { struct SHA512 { bool m_inited; SHA512_CTX m_ctx; public: SHA512() { m_inited = SHA512_Init(&m_ctx) != 0; } ~SHA512() { if (m_inited) OPENSSL_cleanse(&m_ctx, sizeof(m_ctx)); } bool Update(const void* msg, size_t len) { if (!m_inited) return false; return SHA512_Update(&m_ctx, msg, len) != 0; } bool Final(SHA512Hash::digest_t& digest) { if (!m_inited) return false; return SHA512_Final(digest, &m_ctx) != 0; } }; struct MD5 { bool m_inited; MD5_CTX m_ctx; public: MD5() { m_inited = MD5_Init(&m_ctx) != 0; } ~MD5() { if (m_inited) OPENSSL_cleanse(&m_ctx, sizeof(m_ctx)); } bool Update(const void* msg, size_t len) { if (!m_inited) return false; return MD5_Update(&m_ctx, msg, len) != 0; } bool Final(MD5Hash::digest_t& digest) { if (!m_inited) return false; return MD5_Final(digest, &m_ctx) != 0; } }; }; bool SHA512Hash::__crypt(const char* salt, const char* message, size_t len, digest_t &digest) { algorithm::SHA512 alg; if (!alg.Update(salt, SALT_LENGTH)) return false; if (!alg.Update(message, len)) return false; return alg.Final(digest); } bool MD5Hash::__crypt(const char* salt, const char* message, size_t len, digest_t &digest) { algorithm::MD5 alg; if (!alg.Update(salt, SALT_LENGTH)) return false; if (!alg.Update(message, len)) return false; return alg.Final(digest); } bool verify(const char* message, const char* hash) { if (!hash) return false; char alg = hash[strlen(hash) - 1]; if (alg == SHA512Hash::ALG_ID) return SHA512Hash::verify(message, hash); if (alg == MD5Hash::ALG_ID) return MD5Hash::verify(message, hash); return false; } static char alphabet(size_t id) { static char alph[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; return alph[id]; } template <class T> T sslrand() { T ret; RAND_bytes((unsigned char*)&ret, sizeof(ret)); return ret; } static char randomChar() { // TODO : fixme! return alphabet(sslrand<unsigned char>() >> 2); } static void randomU32(char (&out)[4]) { unsigned char ent[3]; RAND_bytes(ent, sizeof(ent)); out[0] = alphabet(ent[0] >> 2); out[1] = alphabet((ent[0] & 0x3) | (ent[1] >> 4)); out[2] = alphabet((ent[1] & 0xF) | (ent[2] >> 6)); out[3] = alphabet(ent[2] & 0x3F); } void newSalt(char* salt, size_t len) { char sample[4]; salt[--len] = 0; size_t tmp = len / 4; for (size_t i = 0; i < tmp; ++i) { randomU32(sample); memcpy(salt, sample, 4); salt += 4; } tmp = len % 4; if (!tmp) return; randomU32(sample); memcpy(salt, sample, tmp); } void base64_encode(const void* data, size_t len, char* output) { const unsigned char* p = (const unsigned char*)data; size_t pos = 0; unsigned int bits = 0; unsigned int accu = 0; for (size_t i = 0; i < len; ++i) { accu = (accu << 8) | (p[i] & 0xFF); bits += 8; while (bits >= 6) { bits -= 6; output[pos++] = alphabet((accu >> bits) & 0x3F); } } if (bits > 0) { accu <<= 6 - bits; output[pos++] = alphabet(accu & 0x3F); } } };<|endoftext|>
<commit_before>/* This file is part of libkdepim. Copyright (c) 2004 Tobias Koenig <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <libkdepim/diffalgo.h> #include <QList> using namespace KPIM; void DiffAlgo::begin() { QList<DiffAlgoDisplay*>::Iterator it; for ( it = mDisplays.begin(); it != mDisplays.end(); ++it ) (*it)->begin(); } void DiffAlgo::end() { QList<DiffAlgoDisplay*>::Iterator it; for ( it = mDisplays.begin(); it != mDisplays.end(); ++it ) (*it)->end(); } void DiffAlgo::setLeftSourceTitle( const QString &title ) { QList<DiffAlgoDisplay*>::Iterator it; for ( it = mDisplays.begin(); it != mDisplays.end(); ++it ) (*it)->setLeftSourceTitle( title ); } void DiffAlgo::setRightSourceTitle( const QString &title ) { QList<DiffAlgoDisplay*>::Iterator it; for ( it = mDisplays.begin(); it != mDisplays.end(); ++it ) (*it)->setRightSourceTitle( title ); } void DiffAlgo::additionalLeftField( const QString &id, const QString &value ) { QList<DiffAlgoDisplay*>::Iterator it; for ( it = mDisplays.begin(); it != mDisplays.end(); ++it ) (*it)->additionalLeftField( id, value ); } void DiffAlgo::additionalRightField( const QString &id, const QString &value ) { QList<DiffAlgoDisplay*>::Iterator it; for ( it = mDisplays.begin(); it != mDisplays.end(); ++it ) (*it)->additionalRightField( id, value ); } void DiffAlgo::conflictField( const QString &id, const QString &leftValue, const QString &rightValue ) { QList<DiffAlgoDisplay*>::Iterator it; for ( it = mDisplays.begin(); it != mDisplays.end(); ++it ) (*it)->conflictField( id, leftValue, rightValue ); } void DiffAlgo::addDisplay( DiffAlgoDisplay *display ) { if ( !mDisplays.contains( display ) ) mDisplays.append( display ); } void DiffAlgo::removeDisplay( DiffAlgoDisplay *display ) { mDisplays.removeAll( display ); } <commit_msg>Need memcpy. Missing include header<commit_after>/* This file is part of libkdepim. Copyright (c) 2004 Tobias Koenig <[email protected]> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <libkdepim/diffalgo.h> #include <QList> #include <string.h> using namespace KPIM; void DiffAlgo::begin() { QList<DiffAlgoDisplay*>::Iterator it; for ( it = mDisplays.begin(); it != mDisplays.end(); ++it ) (*it)->begin(); } void DiffAlgo::end() { QList<DiffAlgoDisplay*>::Iterator it; for ( it = mDisplays.begin(); it != mDisplays.end(); ++it ) (*it)->end(); } void DiffAlgo::setLeftSourceTitle( const QString &title ) { QList<DiffAlgoDisplay*>::Iterator it; for ( it = mDisplays.begin(); it != mDisplays.end(); ++it ) (*it)->setLeftSourceTitle( title ); } void DiffAlgo::setRightSourceTitle( const QString &title ) { QList<DiffAlgoDisplay*>::Iterator it; for ( it = mDisplays.begin(); it != mDisplays.end(); ++it ) (*it)->setRightSourceTitle( title ); } void DiffAlgo::additionalLeftField( const QString &id, const QString &value ) { QList<DiffAlgoDisplay*>::Iterator it; for ( it = mDisplays.begin(); it != mDisplays.end(); ++it ) (*it)->additionalLeftField( id, value ); } void DiffAlgo::additionalRightField( const QString &id, const QString &value ) { QList<DiffAlgoDisplay*>::Iterator it; for ( it = mDisplays.begin(); it != mDisplays.end(); ++it ) (*it)->additionalRightField( id, value ); } void DiffAlgo::conflictField( const QString &id, const QString &leftValue, const QString &rightValue ) { QList<DiffAlgoDisplay*>::Iterator it; for ( it = mDisplays.begin(); it != mDisplays.end(); ++it ) (*it)->conflictField( id, leftValue, rightValue ); } void DiffAlgo::addDisplay( DiffAlgoDisplay *display ) { if ( !mDisplays.contains( display ) ) mDisplays.append( display ); } void DiffAlgo::removeDisplay( DiffAlgoDisplay *display ) { mDisplays.removeAll( display ); } <|endoftext|>
<commit_before>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM 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) version 2.1 dated February 1999. #ifndef MFEM_BLOCKVECTOR #define MFEM_BLOCKVECTOR #include "../config/config.hpp" #include "../general/array.hpp" #include "vector.hpp" namespace mfem { //! @class BlockVector /* * \brief A class to handle Vectors in a block fashion * * All data is contained in Vector::data, while blockVector is just a viewer for this data * */ class BlockVector: public Vector { protected: //! Number of blocks in the blockVector int numBlocks; //! Offset for each block start. (length numBlocks+1) /** * blockOffsets[i+1] - blockOffsets[i] is the size of block i. */ const int *blockOffsets; //! array of Vector objects used to extract blocks without allocating memory. Vector *blocks; void SetBlocks(); public: //! empty constructor BlockVector(); //! Constructor /** * bOffsets is an array of integers (length nBlocks+1) that tells the offsets * of each block start. */ BlockVector(const Array<int> & bOffsets); //! Copy constructor BlockVector(const BlockVector & block); //! View constructor /* * data is an array of double of length at least blockOffsets[numBlocks] that * contain all the values of the monolithic vector. bOffsets is an array of * integers (length nBlocks+1) that tells the offsets of each block start. * nBlocks is the number of blocks. */ BlockVector(double *data, const Array<int> & bOffsets); //! Assignment operator. this and original must have the same block structure. BlockVector & operator=(const BlockVector & original); //! Set each entry of this equal to val BlockVector & operator=(double val); //! Destructor ~BlockVector(); //! Get the i-th vector in the block. Vector & GetBlock(int i) { return blocks[i]; } //! Get the i-th vector in the block (const version). const Vector & GetBlock(int i) const { return blocks[i]; } //! Get the i-th vector in the block void GetBlockView(int i, Vector & blockView); int BlockSize(int i) { return blockOffsets[i+1] - blockOffsets[i];} //! Update method /** * data is an array of double of length at least blockOffsets[numBlocks] that * contain all the values of the monolithic vector. bOffsets is an array of * integers (length nBlocks+1) that tells the offsets of each block start. * nBlocks is the number of blocks. */ void Update(double *data, const Array<int> & bOffsets); /// Update a BlockVector with new @a bOffsets and make sure it owns its data. /** The block-vector will be re-allocated if either: - the offsets @a bOffsets are different from the current offsets, or - currently, the block-vector does not own its data, or - @a force is set to true. */ void Update(const Array<int> &bOffsets, bool force = false); }; } #endif /* MFEM_BLOCKVECTOR */ <commit_msg>Update a few comments in class BlockVector.<commit_after>// Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at // the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights // reserved. See file COPYRIGHT for details. // // This file is part of the MFEM library. For more information and source code // availability see http://mfem.org. // // MFEM 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) version 2.1 dated February 1999. #ifndef MFEM_BLOCKVECTOR #define MFEM_BLOCKVECTOR #include "../config/config.hpp" #include "../general/array.hpp" #include "vector.hpp" namespace mfem { //! @class BlockVector /** * \brief A class to handle Vectors in a block fashion * * All data is contained in Vector::data, while blockVector is just a viewer for * this data. * */ class BlockVector: public Vector { protected: //! Number of blocks in the blockVector int numBlocks; //! Offset for each block start. (length numBlocks+1) /** * blockOffsets[i+1] - blockOffsets[i] is the size of block i. * * This array is not owned. */ const int *blockOffsets; //! array of Vector objects used to extract blocks without allocating memory. /** This array is owned. */ Vector *blocks; void SetBlocks(); public: //! empty constructor BlockVector(); //! Constructor /** * bOffsets is an array of integers (length nBlocks+1) that tells the offsets * of each block start. */ BlockVector(const Array<int> & bOffsets); //! Copy constructor BlockVector(const BlockVector & block); //! View constructor /* * data is an array of double of length at least blockOffsets[numBlocks] that * contain all the values of the monolithic vector. bOffsets is an array of * integers (length nBlocks+1) that tells the offsets of each block start. * nBlocks is the number of blocks. */ BlockVector(double *data, const Array<int> & bOffsets); //! Assignment operator. this and original must have the same block structure. BlockVector & operator=(const BlockVector & original); //! Set each entry of this equal to val BlockVector & operator=(double val); //! Destructor ~BlockVector(); //! Get the i-th vector in the block. Vector & GetBlock(int i) { return blocks[i]; } //! Get the i-th vector in the block (const version). const Vector & GetBlock(int i) const { return blocks[i]; } //! Get the i-th vector in the block void GetBlockView(int i, Vector & blockView); int BlockSize(int i) { return blockOffsets[i+1] - blockOffsets[i];} //! Update method /** * data is an array of double of length at least blockOffsets[numBlocks] that * contain all the values of the monolithic vector. bOffsets is an array of * integers (length nBlocks+1) that tells the offsets of each block start. * nBlocks is the number of blocks. */ void Update(double *data, const Array<int> & bOffsets); /// Update a BlockVector with new @a bOffsets and make sure it owns its data. /** The block-vector will be re-allocated if either: - the offsets @a bOffsets are different from the current offsets, or - currently, the block-vector does not own its data, or - @a force is set to true. */ void Update(const Array<int> &bOffsets, bool force = false); }; } #endif /* MFEM_BLOCKVECTOR */ <|endoftext|>
<commit_before>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2015-2019 Baldur Karlsson * * 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 "d3d11_test.h" struct Binding_Hazards : D3D11GraphicsTest { static constexpr const char *Description = "Test of D3D11 hazard tracking write/read bindings"; std::string compute = R"EOSHADER( Texture2D<uint> texin : register(t0); Buffer<uint> bufin : register(t1); RWTexture2D<uint> texout1 : register(u0); RWBuffer<uint> bufout1 : register(u1); RWTexture2D<uint> texout2 : register(u2); RWBuffer<uint> bufout2 : register(u3); [numthreads(1,1,1)] void main() { texout1[uint2(3,4)] = bufin[3]; texout2[uint2(4,4)] = texin[uint2(3,3)]; bufout1[4] = bufin[4]; bufout2[3] = texin[uint2(4,4)]; } )EOSHADER"; int main(int argc, char **argv) { // so that running individually we get errors debugDevice = true; // initialise, create window, create device, etc if(!Init(argc, argv)) return 3; ID3D11ComputeShaderPtr cs = CreateCS(Compile(compute, "main", "cs_5_0")); ID3D11Texture2DPtr tex0 = MakeTexture(DXGI_FORMAT_R32_UINT, 8, 8).UAV().RTV(); ID3D11UnorderedAccessViewPtr uav0 = MakeUAV(tex0); ID3D11RenderTargetViewPtr rtv0 = MakeRTV(tex0); ID3D11Texture2DPtr tex1 = MakeTexture(DXGI_FORMAT_R32_UINT, 8, 8).UAV().RTV(); ID3D11UnorderedAccessViewPtr uav1 = MakeUAV(tex1); ID3D11RenderTargetViewPtr rtv1 = MakeRTV(tex1); ID3D11BufferPtr buf1 = MakeBuffer().Size(65536).SRV().UAV(); ID3D11BufferPtr buf2 = MakeBuffer().Size(65536).SRV(); ID3D11ShaderResourceViewPtr buf1SRV = MakeSRV(buf1).Format(DXGI_FORMAT_R32_UINT); ID3D11UnorderedAccessViewPtr buf1UAV = MakeUAV(buf1).Format(DXGI_FORMAT_R32_UINT); while(Running()) { ctx->ClearState(); ctx->CSSetShader(cs, NULL, 0); ID3D11ShaderResourceViewPtr tempSRV = MakeSRV(buf2).Format(DXGI_FORMAT_R32_UINT).NumElements(128); ctx->CSSetShaderResources(1, 1, &tempSRV.GetInterfacePtr()); ULONG refcount = tempSRV->Release(); ID3D11ShaderResourceView *srvs[2] = {NULL, tempSRV.GetInterfacePtr()}; ctx->CSSetShaderResources(1, 2, srvs); refcount = tempSRV->AddRef(); refcount = tempSRV->Release(); ctx->CSSetShaderResources(3, 2, srvs); refcount = tempSRV->AddRef(); refcount = tempSRV->Release(); ctx->CSSetUnorderedAccessViews(0, 1, &uav0.GetInterfacePtr(), NULL); ctx->CSSetUnorderedAccessViews(2, 1, &uav1.GetInterfacePtr(), NULL); // try to bind the buffer to two slots, find it gets unbound ctx->CSSetUnorderedAccessViews(1, 1, &buf1UAV.GetInterfacePtr(), NULL); ctx->CSSetUnorderedAccessViews(3, 1, &buf1UAV.GetInterfacePtr(), NULL); ID3D11UnorderedAccessView *getCSUAVs[4] = {}; ID3D11RenderTargetView *getOMRTV = NULL; ID3D11RenderTargetView *getOMRTVs[2] = {}; ID3D11UnorderedAccessView *getOMUAV = NULL; // Dispatch each time so we can also check state in UI ctx->Dispatch(1, 1, 1); ctx->CSGetUnorderedAccessViews(0, 4, getCSUAVs); TEST_ASSERT(getCSUAVs[0] == uav0, "Unexpected binding"); TEST_ASSERT(getCSUAVs[1] == NULL, "Unexpected binding"); TEST_ASSERT(getCSUAVs[2] == uav1, "Unexpected binding"); TEST_ASSERT(getCSUAVs[3] == buf1UAV, "Unexpected binding"); // this should unbind uav0 because it's re-bound as rtv0, then unbind uav1 because it's // rebound on another UAV slot ctx->OMSetRenderTargetsAndUnorderedAccessViews(1, &rtv0.GetInterfacePtr(), NULL, 1, 1, &uav1.GetInterfacePtr(), NULL); ctx->Dispatch(1, 1, 1); ctx->OMGetRenderTargetsAndUnorderedAccessViews(1, &getOMRTV, NULL, 1, 1, &getOMUAV); ctx->CSGetUnorderedAccessViews(0, 4, getCSUAVs); TEST_ASSERT(getOMRTV == rtv0, "Unexpected binding"); TEST_ASSERT(getOMUAV == uav1, "Unexpected binding"); TEST_ASSERT(getCSUAVs[0] == NULL, "Unexpected binding"); TEST_ASSERT(getCSUAVs[1] == NULL, "Unexpected binding"); TEST_ASSERT(getCSUAVs[2] == NULL, "Unexpected binding"); TEST_ASSERT(getCSUAVs[3] == buf1UAV, "Unexpected binding"); ctx->OMSetRenderTargetsAndUnorderedAccessViews(D3D11_KEEP_RENDER_TARGETS_AND_DEPTH_STENCIL, NULL, NULL, 1, 0, NULL, NULL); ctx->OMGetRenderTargetsAndUnorderedAccessViews(1, &getOMRTV, NULL, 1, 1, &getOMUAV); TEST_ASSERT(getOMRTV == rtv0, "Unexpected binding"); TEST_ASSERT(getOMUAV == NULL, "Unexpected binding"); ctx->OMSetRenderTargetsAndUnorderedAccessViews(1, &rtv0.GetInterfacePtr(), NULL, 1, 1, &uav1.GetInterfacePtr(), NULL); ctx->OMSetRenderTargetsAndUnorderedAccessViews(D3D11_KEEP_RENDER_TARGETS_AND_DEPTH_STENCIL, &rtv1.GetInterfacePtr(), NULL, 1, 0, NULL, NULL); ctx->OMGetRenderTargetsAndUnorderedAccessViews(1, &getOMRTV, NULL, 1, 1, &getOMUAV); TEST_ASSERT(getOMRTV == rtv0, "Unexpected binding"); TEST_ASSERT(getOMUAV == NULL, "Unexpected binding"); ctx->OMSetRenderTargetsAndUnorderedAccessViews(1, &rtv0.GetInterfacePtr(), NULL, 1, 1, &uav1.GetInterfacePtr(), NULL); ID3D11RenderTargetView *empty = NULL; ctx->OMSetRenderTargetsAndUnorderedAccessViews(1, &empty, NULL, 1, D3D11_KEEP_UNORDERED_ACCESS_VIEWS, NULL, NULL); ctx->OMGetRenderTargetsAndUnorderedAccessViews(1, &getOMRTV, NULL, 1, 1, &getOMUAV); TEST_ASSERT(getOMRTV == empty, "Unexpected binding"); TEST_ASSERT(getOMUAV == uav1, "Unexpected binding"); ctx->OMSetRenderTargetsAndUnorderedAccessViews(1, &rtv0.GetInterfacePtr(), NULL, 1, 1, &uav1.GetInterfacePtr(), NULL); ctx->OMSetRenderTargetsAndUnorderedAccessViews( 1, &empty, NULL, 1, D3D11_KEEP_UNORDERED_ACCESS_VIEWS, &uav0.GetInterfacePtr(), NULL); ctx->OMGetRenderTargetsAndUnorderedAccessViews(1, &getOMRTV, NULL, 1, 1, &getOMUAV); TEST_ASSERT(getOMRTV == empty, "Unexpected binding"); TEST_ASSERT(getOMUAV == uav1, "Unexpected binding"); // finally this should unbind both OM views, and rebind back on the CS ctx->CSSetUnorderedAccessViews(0, 1, &uav0.GetInterfacePtr(), NULL); ctx->CSSetUnorderedAccessViews(2, 1, &uav1.GetInterfacePtr(), NULL); ctx->Dispatch(1, 1, 1); ctx->OMGetRenderTargetsAndUnorderedAccessViews(1, &getOMRTV, NULL, 1, 1, &getOMUAV); ctx->CSGetUnorderedAccessViews(0, 4, getCSUAVs); TEST_ASSERT(getOMRTV == NULL, "Unexpected binding"); TEST_ASSERT(getOMUAV == NULL, "Unexpected binding"); TEST_ASSERT(getCSUAVs[0] == uav0, "Unexpected binding"); TEST_ASSERT(getCSUAVs[1] == NULL, "Unexpected binding"); TEST_ASSERT(getCSUAVs[2] == uav1, "Unexpected binding"); TEST_ASSERT(getCSUAVs[3] == buf1UAV, "Unexpected binding"); ctx->ClearState(); ctx->CSSetShader(cs, NULL, 0); ID3D11RenderTargetView *RTVs[] = { rtv0, rtv0, }; // can't bind the same RTV to two slots ctx->OMSetRenderTargets(2, RTVs, NULL); ctx->Dispatch(1, 1, 1); ctx->OMGetRenderTargetsAndUnorderedAccessViews(2, getOMRTVs, NULL, 2, 1, &getOMUAV); TEST_ASSERT(getOMRTVs[0] == NULL, "Unexpected binding"); TEST_ASSERT(getOMRTVs[1] == NULL, "Unexpected binding"); TEST_ASSERT(getOMUAV == NULL, "Unexpected binding"); RTVs[0] = rtv1; RTVs[1] = rtv0; // this bind is fine, no overlapping state ctx->OMSetRenderTargetsAndUnorderedAccessViews(2, RTVs, NULL, 2, 1, &buf1UAV.GetInterfacePtr(), NULL); ctx->Dispatch(1, 1, 1); ctx->OMGetRenderTargetsAndUnorderedAccessViews(2, getOMRTVs, NULL, 2, 1, &getOMUAV); TEST_ASSERT(getOMRTVs[0] == rtv1, "Unexpected binding"); TEST_ASSERT(getOMRTVs[1] == rtv0, "Unexpected binding"); TEST_ASSERT(getOMUAV == buf1UAV, "Unexpected binding"); RTVs[0] = rtv0; RTVs[1] = rtv1; // this bind is discarded, because rtv0 overlaps uav0. ctx->OMSetRenderTargetsAndUnorderedAccessViews(2, RTVs, NULL, 2, 1, &uav0.GetInterfacePtr(), NULL); ctx->Dispatch(1, 1, 1); ctx->OMGetRenderTargetsAndUnorderedAccessViews(2, getOMRTVs, NULL, 2, 1, &getOMUAV); TEST_ASSERT(getOMRTVs[0] == rtv1, "Unexpected binding"); TEST_ASSERT(getOMRTVs[1] == rtv0, "Unexpected binding"); TEST_ASSERT(getOMUAV == buf1UAV, "Unexpected binding"); Present(); } return 0; } }; REGISTER_TEST(Binding_Hazards);<commit_msg>Fix D3D11_Binding_Hazards test<commit_after>/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2015-2019 Baldur Karlsson * * 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 "d3d11_test.h" struct Binding_Hazards : D3D11GraphicsTest { static constexpr const char *Description = "Test of D3D11 hazard tracking write/read bindings"; std::string compute = R"EOSHADER( Texture2D<uint> texin : register(t0); Buffer<uint> bufin : register(t1); RWTexture2D<uint> texout1 : register(u0); RWBuffer<uint> bufout1 : register(u1); RWTexture2D<uint> texout2 : register(u2); RWBuffer<uint> bufout2 : register(u3); [numthreads(1,1,1)] void main() { texout1[uint2(3,4)] = bufin[3]; texout2[uint2(4,4)] = texin[uint2(3,3)]; bufout1[4] = bufin[4]; bufout2[3] = texin[uint2(4,4)]; } )EOSHADER"; int main(int argc, char **argv) { // so that running individually we get errors debugDevice = true; // initialise, create window, create device, etc if(!Init(argc, argv)) return 3; ID3D11ComputeShaderPtr cs = CreateCS(Compile(compute, "main", "cs_5_0")); ID3D11Texture2DPtr tex0 = MakeTexture(DXGI_FORMAT_R32_UINT, 8, 8).UAV().RTV(); ID3D11UnorderedAccessViewPtr uav0 = MakeUAV(tex0); ID3D11RenderTargetViewPtr rtv0 = MakeRTV(tex0); ID3D11Texture2DPtr tex1 = MakeTexture(DXGI_FORMAT_R32_UINT, 8, 8).UAV().RTV(); ID3D11UnorderedAccessViewPtr uav1 = MakeUAV(tex1); ID3D11RenderTargetViewPtr rtv1 = MakeRTV(tex1); ID3D11BufferPtr buf1 = MakeBuffer().Size(65536).SRV().UAV(); ID3D11BufferPtr buf2 = MakeBuffer().Size(65536).SRV(); ID3D11ShaderResourceViewPtr buf1SRV = MakeSRV(buf1).Format(DXGI_FORMAT_R32_UINT); ID3D11UnorderedAccessViewPtr buf1UAV = MakeUAV(buf1).Format(DXGI_FORMAT_R32_UINT); while(Running()) { ctx->ClearState(); ctx->CSSetShader(cs, NULL, 0); ID3D11ShaderResourceViewPtr tempSRV = MakeSRV(buf2).Format(DXGI_FORMAT_R32_UINT).NumElements(128); ctx->CSSetShaderResources(1, 1, &tempSRV.GetInterfacePtr()); tempSRV->AddRef(); ULONG refcount = tempSRV->Release(); ID3D11ShaderResourceView *srvs[2] = {NULL, tempSRV.GetInterfacePtr()}; ctx->CSSetShaderResources(1, 2, srvs); refcount = tempSRV->AddRef(); refcount = tempSRV->Release(); ctx->CSSetShaderResources(3, 2, srvs); refcount = tempSRV->AddRef(); refcount = tempSRV->Release(); ctx->CSSetUnorderedAccessViews(0, 1, &uav0.GetInterfacePtr(), NULL); ctx->CSSetUnorderedAccessViews(2, 1, &uav1.GetInterfacePtr(), NULL); // try to bind the buffer to two slots, find it gets unbound ctx->CSSetUnorderedAccessViews(1, 1, &buf1UAV.GetInterfacePtr(), NULL); ctx->CSSetUnorderedAccessViews(3, 1, &buf1UAV.GetInterfacePtr(), NULL); ID3D11UnorderedAccessView *getCSUAVs[4] = {}; ID3D11RenderTargetView *getOMRTV = NULL; ID3D11RenderTargetView *getOMRTVs[2] = {}; ID3D11UnorderedAccessView *getOMUAV = NULL; // Dispatch each time so we can also check state in UI ctx->Dispatch(1, 1, 1); ctx->CSGetUnorderedAccessViews(0, 4, getCSUAVs); TEST_ASSERT(getCSUAVs[0] == uav0, "Unexpected binding"); TEST_ASSERT(getCSUAVs[1] == NULL, "Unexpected binding"); TEST_ASSERT(getCSUAVs[2] == uav1, "Unexpected binding"); TEST_ASSERT(getCSUAVs[3] == buf1UAV, "Unexpected binding"); // this should unbind uav0 because it's re-bound as rtv0, then unbind uav1 because it's // rebound on another UAV slot ctx->OMSetRenderTargetsAndUnorderedAccessViews(1, &rtv0.GetInterfacePtr(), NULL, 1, 1, &uav1.GetInterfacePtr(), NULL); ctx->Dispatch(1, 1, 1); ctx->OMGetRenderTargetsAndUnorderedAccessViews(1, &getOMRTV, NULL, 1, 1, &getOMUAV); ctx->CSGetUnorderedAccessViews(0, 4, getCSUAVs); TEST_ASSERT(getOMRTV == rtv0, "Unexpected binding"); TEST_ASSERT(getOMUAV == uav1, "Unexpected binding"); TEST_ASSERT(getCSUAVs[0] == NULL, "Unexpected binding"); TEST_ASSERT(getCSUAVs[1] == NULL, "Unexpected binding"); TEST_ASSERT(getCSUAVs[2] == NULL, "Unexpected binding"); TEST_ASSERT(getCSUAVs[3] == buf1UAV, "Unexpected binding"); ctx->OMSetRenderTargetsAndUnorderedAccessViews(D3D11_KEEP_RENDER_TARGETS_AND_DEPTH_STENCIL, NULL, NULL, 1, 0, NULL, NULL); ctx->OMGetRenderTargetsAndUnorderedAccessViews(1, &getOMRTV, NULL, 1, 1, &getOMUAV); TEST_ASSERT(getOMRTV == rtv0, "Unexpected binding"); TEST_ASSERT(getOMUAV == NULL, "Unexpected binding"); ctx->OMSetRenderTargetsAndUnorderedAccessViews(1, &rtv0.GetInterfacePtr(), NULL, 1, 1, &uav1.GetInterfacePtr(), NULL); ctx->OMSetRenderTargetsAndUnorderedAccessViews(D3D11_KEEP_RENDER_TARGETS_AND_DEPTH_STENCIL, &rtv1.GetInterfacePtr(), NULL, 1, 0, NULL, NULL); ctx->OMGetRenderTargetsAndUnorderedAccessViews(1, &getOMRTV, NULL, 1, 1, &getOMUAV); TEST_ASSERT(getOMRTV == rtv0, "Unexpected binding"); TEST_ASSERT(getOMUAV == NULL, "Unexpected binding"); ctx->OMSetRenderTargetsAndUnorderedAccessViews(1, &rtv0.GetInterfacePtr(), NULL, 1, 1, &uav1.GetInterfacePtr(), NULL); ID3D11RenderTargetView *empty = NULL; ctx->OMSetRenderTargetsAndUnorderedAccessViews(1, &empty, NULL, 1, D3D11_KEEP_UNORDERED_ACCESS_VIEWS, NULL, NULL); ctx->OMGetRenderTargetsAndUnorderedAccessViews(1, &getOMRTV, NULL, 1, 1, &getOMUAV); TEST_ASSERT(getOMRTV == empty, "Unexpected binding"); TEST_ASSERT(getOMUAV == uav1, "Unexpected binding"); ctx->OMSetRenderTargetsAndUnorderedAccessViews(1, &rtv0.GetInterfacePtr(), NULL, 1, 1, &uav1.GetInterfacePtr(), NULL); ctx->OMSetRenderTargetsAndUnorderedAccessViews( 1, &empty, NULL, 1, D3D11_KEEP_UNORDERED_ACCESS_VIEWS, &uav0.GetInterfacePtr(), NULL); ctx->OMGetRenderTargetsAndUnorderedAccessViews(1, &getOMRTV, NULL, 1, 1, &getOMUAV); TEST_ASSERT(getOMRTV == empty, "Unexpected binding"); TEST_ASSERT(getOMUAV == uav1, "Unexpected binding"); // finally this should unbind both OM views, and rebind back on the CS ctx->CSSetUnorderedAccessViews(0, 1, &uav0.GetInterfacePtr(), NULL); ctx->CSSetUnorderedAccessViews(2, 1, &uav1.GetInterfacePtr(), NULL); ctx->Dispatch(1, 1, 1); ctx->OMGetRenderTargetsAndUnorderedAccessViews(1, &getOMRTV, NULL, 1, 1, &getOMUAV); ctx->CSGetUnorderedAccessViews(0, 4, getCSUAVs); TEST_ASSERT(getOMRTV == NULL, "Unexpected binding"); TEST_ASSERT(getOMUAV == NULL, "Unexpected binding"); TEST_ASSERT(getCSUAVs[0] == uav0, "Unexpected binding"); TEST_ASSERT(getCSUAVs[1] == NULL, "Unexpected binding"); TEST_ASSERT(getCSUAVs[2] == uav1, "Unexpected binding"); TEST_ASSERT(getCSUAVs[3] == buf1UAV, "Unexpected binding"); ctx->ClearState(); ctx->CSSetShader(cs, NULL, 0); ID3D11RenderTargetView *RTVs[] = { rtv0, rtv0, }; // can't bind the same RTV to two slots ctx->OMSetRenderTargets(2, RTVs, NULL); ctx->Dispatch(1, 1, 1); ctx->OMGetRenderTargetsAndUnorderedAccessViews(2, getOMRTVs, NULL, 2, 1, &getOMUAV); TEST_ASSERT(getOMRTVs[0] == NULL, "Unexpected binding"); TEST_ASSERT(getOMRTVs[1] == NULL, "Unexpected binding"); TEST_ASSERT(getOMUAV == NULL, "Unexpected binding"); RTVs[0] = rtv1; RTVs[1] = rtv0; // this bind is fine, no overlapping state ctx->OMSetRenderTargetsAndUnorderedAccessViews(2, RTVs, NULL, 2, 1, &buf1UAV.GetInterfacePtr(), NULL); ctx->Dispatch(1, 1, 1); ctx->OMGetRenderTargetsAndUnorderedAccessViews(2, getOMRTVs, NULL, 2, 1, &getOMUAV); TEST_ASSERT(getOMRTVs[0] == rtv1, "Unexpected binding"); TEST_ASSERT(getOMRTVs[1] == rtv0, "Unexpected binding"); TEST_ASSERT(getOMUAV == buf1UAV, "Unexpected binding"); RTVs[0] = rtv0; RTVs[1] = rtv1; // this bind is discarded, because rtv0 overlaps uav0. ctx->OMSetRenderTargetsAndUnorderedAccessViews(2, RTVs, NULL, 2, 1, &uav0.GetInterfacePtr(), NULL); ctx->Dispatch(1, 1, 1); ctx->OMGetRenderTargetsAndUnorderedAccessViews(2, getOMRTVs, NULL, 2, 1, &getOMUAV); TEST_ASSERT(getOMRTVs[0] == rtv1, "Unexpected binding"); TEST_ASSERT(getOMRTVs[1] == rtv0, "Unexpected binding"); TEST_ASSERT(getOMUAV == buf1UAV, "Unexpected binding"); Present(); } return 0; } }; REGISTER_TEST(Binding_Hazards);<|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/gpu_process_host.h" #include "app/app_switches.h" #include "base/command_line.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/gpu_process_host_ui_shim.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/render_widget_host_view.h" #include "chrome/common/child_process_logging.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/gpu_info.h" #include "chrome/common/gpu_messages.h" #include "chrome/common/render_messages.h" #include "ipc/ipc_channel_handle.h" #include "ipc/ipc_switches.h" #if defined(OS_LINUX) #include "gfx/gtk_native_view_id_manager.h" #endif namespace { // Tasks used by this file class RouteOnUIThreadTask : public Task { public: explicit RouteOnUIThreadTask(const IPC::Message& msg) : msg_(msg) { } private: void Run() { GpuProcessHostUIShim::Get()->OnMessageReceived(msg_); } IPC::Message msg_; }; // Global GpuProcessHost instance. // We can not use Singleton<GpuProcessHost> because that gets // terminated on the wrong thread (main thread). We need the // GpuProcessHost to be terminated on the same thread on which it is // initialized, the IO thread. static GpuProcessHost* sole_instance_ = NULL; } // anonymous namespace GpuProcessHost::GpuProcessHost() : BrowserChildProcessHost(GPU_PROCESS, NULL), initialized_(false), initialized_successfully_(false) { DCHECK_EQ(sole_instance_, static_cast<GpuProcessHost*>(NULL)); } GpuProcessHost::~GpuProcessHost() { while (!queued_synchronization_replies_.empty()) { delete queued_synchronization_replies_.front().reply; queued_synchronization_replies_.pop(); } DCHECK_EQ(sole_instance_, this); sole_instance_ = NULL; } bool GpuProcessHost::EnsureInitialized() { if (!initialized_) { initialized_ = true; initialized_successfully_ = Init(); } return initialized_successfully_; } bool GpuProcessHost::Init() { if (!CreateChannel()) return false; const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess(); CommandLine::StringType gpu_launcher = browser_command_line.GetSwitchValueNative(switches::kGpuLauncher); FilePath exe_path = ChildProcessHost::GetChildPath(gpu_launcher.empty()); if (exe_path.empty()) return false; CommandLine* cmd_line = new CommandLine(exe_path); cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kGpuProcess); cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id()); // Propagate relevant command line switches. static const char* const kSwitchNames[] = { switches::kUseGL, switches::kDisableGpuVsync, switches::kDisableLogging, switches::kEnableLogging, switches::kGpuStartupDialog, switches::kLoggingLevel, }; cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames, arraysize(kSwitchNames)); // If specified, prepend a launcher program to the command line. if (!gpu_launcher.empty()) cmd_line->PrependWrapper(gpu_launcher); Launch( #if defined(OS_WIN) FilePath(), #elif defined(OS_POSIX) false, // Never use the zygote (GPU plugin can't be sandboxed). base::environment_vector(), #endif cmd_line); return true; } // static GpuProcessHost* GpuProcessHost::Get() { if (sole_instance_ == NULL) sole_instance_ = new GpuProcessHost(); return sole_instance_; } // static void GpuProcessHost::SendAboutGpuCrash() { Get()->Send(new GpuMsg_Crash()); } // static void GpuProcessHost::SendAboutGpuHang() { Get()->Send(new GpuMsg_Hang()); } bool GpuProcessHost::Send(IPC::Message* msg) { if (!EnsureInitialized()) return false; return BrowserChildProcessHost::Send(msg); } void GpuProcessHost::OnMessageReceived(const IPC::Message& message) { if (message.routing_id() == MSG_ROUTING_CONTROL) { OnControlMessageReceived(message); } else { // Need to transfer this message to the UI thread and the // GpuProcessHostUIShim for dispatching via its message router. ChromeThread::PostTask(ChromeThread::UI, FROM_HERE, new RouteOnUIThreadTask(message)); } } void GpuProcessHost::EstablishGpuChannel(int renderer_id, ResourceMessageFilter* filter) { if (Send(new GpuMsg_EstablishChannel(renderer_id))) { sent_requests_.push(ChannelRequest(filter)); } else { ReplyToRenderer(IPC::ChannelHandle(), GPUInfo(), filter); } } void GpuProcessHost::Synchronize(IPC::Message* reply, ResourceMessageFilter* filter) { queued_synchronization_replies_.push(SynchronizationRequest(reply, filter)); Send(new GpuMsg_Synchronize()); } GPUInfo GpuProcessHost::gpu_info() const { return gpu_info_; } void GpuProcessHost::OnControlMessageReceived(const IPC::Message& message) { IPC_BEGIN_MESSAGE_MAP(GpuProcessHost, message) IPC_MESSAGE_HANDLER(GpuHostMsg_ChannelEstablished, OnChannelEstablished) IPC_MESSAGE_HANDLER(GpuHostMsg_SynchronizeReply, OnSynchronizeReply) IPC_MESSAGE_HANDLER(GpuHostMsg_GraphicsInfoCollected, OnGraphicsInfoCollected) #if defined(OS_LINUX) IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuHostMsg_GetViewXID, OnGetViewXID) #elif defined(OS_MACOSX) IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceSetIOSurface, OnAcceleratedSurfaceSetIOSurface) IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceBuffersSwapped, OnAcceleratedSurfaceBuffersSwapped) #endif IPC_MESSAGE_UNHANDLED_ERROR() IPC_END_MESSAGE_MAP() } void GpuProcessHost::OnChannelEstablished( const IPC::ChannelHandle& channel_handle, const GPUInfo& gpu_info) { const ChannelRequest& request = sent_requests_.front(); ReplyToRenderer(channel_handle, gpu_info, request.filter); sent_requests_.pop(); gpu_info_ = gpu_info; child_process_logging::SetGpuInfo(gpu_info); } void GpuProcessHost::OnSynchronizeReply() { const SynchronizationRequest& request = queued_synchronization_replies_.front(); request.filter->Send(request.reply); queued_synchronization_replies_.pop(); } void GpuProcessHost::OnGraphicsInfoCollected(const GPUInfo& gpu_info) { gpu_info_ = gpu_info; } #if defined(OS_LINUX) namespace { void SendDelayedReply(IPC::Message* reply_msg) { GpuProcessHost::Get()->Send(reply_msg); } void GetViewXIDDispatcher(gfx::NativeViewId id, IPC::Message* reply_msg) { unsigned long xid; GtkNativeViewManager* manager = Singleton<GtkNativeViewManager>::get(); if (!manager->GetPermanentXIDForId(&xid, id)) { DLOG(ERROR) << "Can't find XID for view id " << id; xid = 0; } GpuHostMsg_GetViewXID::WriteReplyParams(reply_msg, xid); // Have to reply from IO thread. ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableFunction(&SendDelayedReply, reply_msg)); } } void GpuProcessHost::OnGetViewXID(gfx::NativeViewId id, IPC::Message *reply_msg) { // Have to request a permanent overlay from UI thread. ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(&GetViewXIDDispatcher, id, reply_msg)); } #elif defined(OS_MACOSX) namespace { class SetIOSurfaceDispatcher : public Task { public: SetIOSurfaceDispatcher( const GpuHostMsg_AcceleratedSurfaceSetIOSurface_Params& params) : params_(params) { } void Run() { RenderViewHost* host = RenderViewHost::FromID(params_.renderer_id, params_.render_view_id); if (!host) return; RenderWidgetHostView* view = host->view(); if (!view) return; view->AcceleratedSurfaceSetIOSurface(params_.window, params_.width, params_.height, params_.identifier); } private: GpuHostMsg_AcceleratedSurfaceSetIOSurface_Params params_; DISALLOW_COPY_AND_ASSIGN(SetIOSurfaceDispatcher); }; } // namespace void GpuProcessHost::OnAcceleratedSurfaceSetIOSurface( const GpuHostMsg_AcceleratedSurfaceSetIOSurface_Params& params) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, new SetIOSurfaceDispatcher(params)); } namespace { class BuffersSwappedDispatcher : public Task { public: BuffersSwappedDispatcher( int32 renderer_id, int32 render_view_id, gfx::PluginWindowHandle window) : renderer_id_(renderer_id), render_view_id_(render_view_id), window_(window) { } void Run() { RenderViewHost* host = RenderViewHost::FromID(renderer_id_, render_view_id_); if (!host) return; RenderWidgetHostView* view = host->view(); if (!view) return; view->AcceleratedSurfaceBuffersSwapped(window_); } private: int32 renderer_id_; int32 render_view_id_; gfx::PluginWindowHandle window_; DISALLOW_COPY_AND_ASSIGN(BuffersSwappedDispatcher); }; } // namespace void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped( int32 renderer_id, int32 render_view_id, gfx::PluginWindowHandle window) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, new BuffersSwappedDispatcher(renderer_id, render_view_id, window)); } #endif void GpuProcessHost::ReplyToRenderer( const IPC::ChannelHandle& channel, const GPUInfo& gpu_info, ResourceMessageFilter* filter) { ViewMsg_GpuChannelEstablished* message = new ViewMsg_GpuChannelEstablished(channel, gpu_info); // If the renderer process is performing synchronous initialization, // it needs to handle this message before receiving the reply for // the synchronous ViewHostMsg_SynchronizeGpu message. message->set_unblock(true); filter->Send(message); } URLRequestContext* GpuProcessHost::GetRequestContext( uint32 request_id, const ViewHostMsg_Resource_Request& request_data) { return NULL; } bool GpuProcessHost::CanShutdown() { return true; } <commit_msg>Pass --enable-accelerated-decoding to the GPU process<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/gpu_process_host.h" #include "app/app_switches.h" #include "base/command_line.h" #include "base/thread.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_thread.h" #include "chrome/browser/gpu_process_host_ui_shim.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/render_widget_host_view.h" #include "chrome/common/child_process_logging.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/gpu_info.h" #include "chrome/common/gpu_messages.h" #include "chrome/common/render_messages.h" #include "ipc/ipc_channel_handle.h" #include "ipc/ipc_switches.h" #include "media/base/media_switches.h" #if defined(OS_LINUX) #include "gfx/gtk_native_view_id_manager.h" #endif namespace { // Tasks used by this file class RouteOnUIThreadTask : public Task { public: explicit RouteOnUIThreadTask(const IPC::Message& msg) : msg_(msg) { } private: void Run() { GpuProcessHostUIShim::Get()->OnMessageReceived(msg_); } IPC::Message msg_; }; // Global GpuProcessHost instance. // We can not use Singleton<GpuProcessHost> because that gets // terminated on the wrong thread (main thread). We need the // GpuProcessHost to be terminated on the same thread on which it is // initialized, the IO thread. static GpuProcessHost* sole_instance_ = NULL; } // anonymous namespace GpuProcessHost::GpuProcessHost() : BrowserChildProcessHost(GPU_PROCESS, NULL), initialized_(false), initialized_successfully_(false) { DCHECK_EQ(sole_instance_, static_cast<GpuProcessHost*>(NULL)); } GpuProcessHost::~GpuProcessHost() { while (!queued_synchronization_replies_.empty()) { delete queued_synchronization_replies_.front().reply; queued_synchronization_replies_.pop(); } DCHECK_EQ(sole_instance_, this); sole_instance_ = NULL; } bool GpuProcessHost::EnsureInitialized() { if (!initialized_) { initialized_ = true; initialized_successfully_ = Init(); } return initialized_successfully_; } bool GpuProcessHost::Init() { if (!CreateChannel()) return false; const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess(); CommandLine::StringType gpu_launcher = browser_command_line.GetSwitchValueNative(switches::kGpuLauncher); FilePath exe_path = ChildProcessHost::GetChildPath(gpu_launcher.empty()); if (exe_path.empty()) return false; CommandLine* cmd_line = new CommandLine(exe_path); cmd_line->AppendSwitchASCII(switches::kProcessType, switches::kGpuProcess); cmd_line->AppendSwitchASCII(switches::kProcessChannelID, channel_id()); // Propagate relevant command line switches. static const char* const kSwitchNames[] = { switches::kUseGL, switches::kDisableGpuVsync, switches::kDisableLogging, switches::kEnableAcceleratedDecoding, switches::kEnableLogging, switches::kGpuStartupDialog, switches::kLoggingLevel, }; cmd_line->CopySwitchesFrom(browser_command_line, kSwitchNames, arraysize(kSwitchNames)); // If specified, prepend a launcher program to the command line. if (!gpu_launcher.empty()) cmd_line->PrependWrapper(gpu_launcher); Launch( #if defined(OS_WIN) FilePath(), #elif defined(OS_POSIX) false, // Never use the zygote (GPU plugin can't be sandboxed). base::environment_vector(), #endif cmd_line); return true; } // static GpuProcessHost* GpuProcessHost::Get() { if (sole_instance_ == NULL) sole_instance_ = new GpuProcessHost(); return sole_instance_; } // static void GpuProcessHost::SendAboutGpuCrash() { Get()->Send(new GpuMsg_Crash()); } // static void GpuProcessHost::SendAboutGpuHang() { Get()->Send(new GpuMsg_Hang()); } bool GpuProcessHost::Send(IPC::Message* msg) { if (!EnsureInitialized()) return false; return BrowserChildProcessHost::Send(msg); } void GpuProcessHost::OnMessageReceived(const IPC::Message& message) { if (message.routing_id() == MSG_ROUTING_CONTROL) { OnControlMessageReceived(message); } else { // Need to transfer this message to the UI thread and the // GpuProcessHostUIShim for dispatching via its message router. ChromeThread::PostTask(ChromeThread::UI, FROM_HERE, new RouteOnUIThreadTask(message)); } } void GpuProcessHost::EstablishGpuChannel(int renderer_id, ResourceMessageFilter* filter) { if (Send(new GpuMsg_EstablishChannel(renderer_id))) { sent_requests_.push(ChannelRequest(filter)); } else { ReplyToRenderer(IPC::ChannelHandle(), GPUInfo(), filter); } } void GpuProcessHost::Synchronize(IPC::Message* reply, ResourceMessageFilter* filter) { queued_synchronization_replies_.push(SynchronizationRequest(reply, filter)); Send(new GpuMsg_Synchronize()); } GPUInfo GpuProcessHost::gpu_info() const { return gpu_info_; } void GpuProcessHost::OnControlMessageReceived(const IPC::Message& message) { IPC_BEGIN_MESSAGE_MAP(GpuProcessHost, message) IPC_MESSAGE_HANDLER(GpuHostMsg_ChannelEstablished, OnChannelEstablished) IPC_MESSAGE_HANDLER(GpuHostMsg_SynchronizeReply, OnSynchronizeReply) IPC_MESSAGE_HANDLER(GpuHostMsg_GraphicsInfoCollected, OnGraphicsInfoCollected) #if defined(OS_LINUX) IPC_MESSAGE_HANDLER_DELAY_REPLY(GpuHostMsg_GetViewXID, OnGetViewXID) #elif defined(OS_MACOSX) IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceSetIOSurface, OnAcceleratedSurfaceSetIOSurface) IPC_MESSAGE_HANDLER(GpuHostMsg_AcceleratedSurfaceBuffersSwapped, OnAcceleratedSurfaceBuffersSwapped) #endif IPC_MESSAGE_UNHANDLED_ERROR() IPC_END_MESSAGE_MAP() } void GpuProcessHost::OnChannelEstablished( const IPC::ChannelHandle& channel_handle, const GPUInfo& gpu_info) { const ChannelRequest& request = sent_requests_.front(); ReplyToRenderer(channel_handle, gpu_info, request.filter); sent_requests_.pop(); gpu_info_ = gpu_info; child_process_logging::SetGpuInfo(gpu_info); } void GpuProcessHost::OnSynchronizeReply() { const SynchronizationRequest& request = queued_synchronization_replies_.front(); request.filter->Send(request.reply); queued_synchronization_replies_.pop(); } void GpuProcessHost::OnGraphicsInfoCollected(const GPUInfo& gpu_info) { gpu_info_ = gpu_info; } #if defined(OS_LINUX) namespace { void SendDelayedReply(IPC::Message* reply_msg) { GpuProcessHost::Get()->Send(reply_msg); } void GetViewXIDDispatcher(gfx::NativeViewId id, IPC::Message* reply_msg) { unsigned long xid; GtkNativeViewManager* manager = Singleton<GtkNativeViewManager>::get(); if (!manager->GetPermanentXIDForId(&xid, id)) { DLOG(ERROR) << "Can't find XID for view id " << id; xid = 0; } GpuHostMsg_GetViewXID::WriteReplyParams(reply_msg, xid); // Have to reply from IO thread. ChromeThread::PostTask( ChromeThread::IO, FROM_HERE, NewRunnableFunction(&SendDelayedReply, reply_msg)); } } void GpuProcessHost::OnGetViewXID(gfx::NativeViewId id, IPC::Message *reply_msg) { // Have to request a permanent overlay from UI thread. ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, NewRunnableFunction(&GetViewXIDDispatcher, id, reply_msg)); } #elif defined(OS_MACOSX) namespace { class SetIOSurfaceDispatcher : public Task { public: SetIOSurfaceDispatcher( const GpuHostMsg_AcceleratedSurfaceSetIOSurface_Params& params) : params_(params) { } void Run() { RenderViewHost* host = RenderViewHost::FromID(params_.renderer_id, params_.render_view_id); if (!host) return; RenderWidgetHostView* view = host->view(); if (!view) return; view->AcceleratedSurfaceSetIOSurface(params_.window, params_.width, params_.height, params_.identifier); } private: GpuHostMsg_AcceleratedSurfaceSetIOSurface_Params params_; DISALLOW_COPY_AND_ASSIGN(SetIOSurfaceDispatcher); }; } // namespace void GpuProcessHost::OnAcceleratedSurfaceSetIOSurface( const GpuHostMsg_AcceleratedSurfaceSetIOSurface_Params& params) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, new SetIOSurfaceDispatcher(params)); } namespace { class BuffersSwappedDispatcher : public Task { public: BuffersSwappedDispatcher( int32 renderer_id, int32 render_view_id, gfx::PluginWindowHandle window) : renderer_id_(renderer_id), render_view_id_(render_view_id), window_(window) { } void Run() { RenderViewHost* host = RenderViewHost::FromID(renderer_id_, render_view_id_); if (!host) return; RenderWidgetHostView* view = host->view(); if (!view) return; view->AcceleratedSurfaceBuffersSwapped(window_); } private: int32 renderer_id_; int32 render_view_id_; gfx::PluginWindowHandle window_; DISALLOW_COPY_AND_ASSIGN(BuffersSwappedDispatcher); }; } // namespace void GpuProcessHost::OnAcceleratedSurfaceBuffersSwapped( int32 renderer_id, int32 render_view_id, gfx::PluginWindowHandle window) { ChromeThread::PostTask( ChromeThread::UI, FROM_HERE, new BuffersSwappedDispatcher(renderer_id, render_view_id, window)); } #endif void GpuProcessHost::ReplyToRenderer( const IPC::ChannelHandle& channel, const GPUInfo& gpu_info, ResourceMessageFilter* filter) { ViewMsg_GpuChannelEstablished* message = new ViewMsg_GpuChannelEstablished(channel, gpu_info); // If the renderer process is performing synchronous initialization, // it needs to handle this message before receiving the reply for // the synchronous ViewHostMsg_SynchronizeGpu message. message->set_unblock(true); filter->Send(message); } URLRequestContext* GpuProcessHost::GetRequestContext( uint32 request_id, const ViewHostMsg_Resource_Request& request_data) { return NULL; } bool GpuProcessHost::CanShutdown() { return true; } <|endoftext|>
<commit_before>#include <BALL/PLUGIN/pluginManager.h> #include <BALL/PLUGIN/BALLPlugin.h> #include <BALL/PLUGIN/pluginHandler.h> #include <QtCore/QPluginLoader> #include <QtCore/QDir> #include <QtCore/QReadLocker> #include <QtCore/QWriteLocker> #include <BALL/COMMON/logStream.h> #if defined(BALL_OS_WINDOWS) # define PLUGIN_MASK "plugin*.dll" #elif defined(BALL_OS_DARWIN) # define PLUGIN_MASK "plugin*.dylib" #else # define PLUGIN_MASK "plugin*.so" #endif namespace BALL { const char* PluginManager::BETWEEN_PLUGINDIR_SEPERATOR = "?"; boost::shared_ptr<PluginManager> PluginManager::manager_; QMutex PluginManager::mutex_; PluginManager::PluginManager() { } PluginManager::~PluginManager() { unloadAllPlugins(); } PluginManager& PluginManager::instance() { //Make the PluginManager creation thread safe if (!manager_) { //Another thread could have taken over control right now //so lock a mutex to ensure the PluginManager is created only once. mutex_.lock(); //Check that the manager has not been created by a concurring thread if(!manager_) { manager_ = boost::shared_ptr<PluginManager>(new PluginManager()); } mutex_.unlock(); } return *manager_; } bool PluginManager::addPluginDirectory(const QString& dir) { std::map<QString, vector<BALLPlugin*> >::iterator to_load_it = loaded_plugin_dirs_.find(dir); if (to_load_it == loaded_plugin_dirs_.end()) { vector<BALLPlugin*> loaded_plugins; QDir plugin_dir(dir, PLUGIN_MASK, QDir::Name | QDir::IgnoreCase, QDir::Files); if(!plugin_dir.exists()) { return false; } // collect the loaded plugins in this dir foreach(QString it, plugin_dir.entryList()) { BALLPlugin* new_plugin = loadPlugin(plugin_dir.absoluteFilePath(it)); if (new_plugin) { loaded_plugins.push_back(new_plugin); } } // and store the entry loaded_plugin_dirs_[dir]=loaded_plugins; return true; } return false; } bool PluginManager::unloadDirectoryPlugins_(PluginDirMap::iterator it) { if(it == loaded_plugin_dirs_.end()) { return false; } vector<BALLPlugin*>::iterator to_unload = it->second.begin(); for (; to_unload != it->second.end(); ++to_unload) { unloadPlugin((*to_unload)->getName()); } // and the directory itself loaded_plugin_dirs_.erase(it); return true; } bool PluginManager::removePluginDirectory(const QString& dir) { std::map<QString, vector<BALLPlugin*> >::iterator to_unload_it = loaded_plugin_dirs_.find(dir); return unloadDirectoryPlugins_(to_unload_it); } vector<QString> PluginManager::getPluginDirectories() const { vector<QString> result; std::map<QString, vector<BALLPlugin*> >::const_iterator it = loaded_plugin_dirs_.begin(); for (; it!=loaded_plugin_dirs_.end(); ++it) result.push_back(it->first); return result; } BALLPlugin* PluginManager::loadPlugin(const QString& plugin_name) { BALLPlugin* plugin = 0; QPluginLoader* loader = new QPluginLoader(plugin_name); Log.info() << "Trying to load plugin: " << plugin_name.toStdString() << std::endl; if (loader->load()) { plugin = qobject_cast<BALLPlugin*>(loader->instance()); } else { Log.info() << "Error:" << loader->errorString().toStdString() << std::endl; } if (plugin) { QHash<QString, QPluginLoader*>::iterator it = loaders_.find(plugin->getName()); if(it != loaders_.end()) { Log.info() << "Plugin was already loaded." << std::endl; delete loader; return qobject_cast<BALLPlugin*>(*it); } Log.info() << "Loaded plugin " << plugin_name.toStdString() << "." << std::endl; loader_mutex_.lockForWrite(); loaders_.insert(plugin->getName(), loader); loader_mutex_.unlock(); if(autoactivate_plugins_.contains(plugin->getName())) { startPlugin(plugin); plugin->activate(); } } return plugin; } bool PluginManager::unloadPlugin(const QString& plugin) { QWriteLocker locker(&loader_mutex_); QHash<QString, QPluginLoader*>::iterator it = loaders_.find(plugin); if (it != loaders_.end()) { //Shutdown the plugin stopPlugin(qobject_cast<BALLPlugin*>(it.value()->instance())); // NOTE: unloading crashes BALLView, for some reason! // it is not really crucial to unload the plugins, but we should have // a look at this anyhow //Delete the loader // it.value()->unload(); // delete it.value(); loaders_.erase(it); return true; } return false; } void PluginManager::unloadAllPlugins() { loader_mutex_.lockForWrite(); QHash<QString, QPluginLoader*>::iterator it = loaders_.begin(); for (; it != loaders_.end(); ++it) { //Shutdown the plugin stopPlugin(qobject_cast<BALLPlugin*>(it.value()->instance())); //Delete the loader it.value()->unload(); delete it.value(); } loaders_.clear(); loader_mutex_.unlock(); } QObject* PluginManager::getPluginInstance(const QString& plugin) { QReadLocker locker(&loader_mutex_); QHash<QString, QPluginLoader*>::iterator it = loaders_.find(plugin); if(it != loaders_.end()) { return (it.value()->instance()); } return NULL; } QObject* PluginManager::getPluginInstance(int pos) { QReadLocker locker(&loader_mutex_); if(pos < 0 || pos >= getPluginCount()) { return NULL; } QHash<QString, QPluginLoader*>::const_iterator it = loaders_.begin(); for(int i = 0; i < pos; ++i, ++it) {} return it.value()->instance(); } void PluginManager::registerHandler(const boost::shared_ptr<PluginHandler>& h) { handler_mutex_.lockForWrite(); shared_handlers_.push_back(h); handlers_.push_back(h.get()); handler_mutex_.unlock(); } void PluginManager::registerHandler(PluginHandler* h) { handler_mutex_.lockForWrite(); handlers_.push_back(h); handler_mutex_.unlock(); } bool PluginManager::unregisterHandler(PluginHandler* h) { // First remove the handler from the list of PluginHandlers handler_mutex_.lockForRead(); std::list<PluginHandler*>::iterator ht = std::find(handlers_.begin(), handlers_.end(), h); handler_mutex_.unlock(); if(ht == handlers_.end()) { return true; } handler_mutex_.lockForWrite(); handlers_.erase(ht); handler_mutex_.unlock(); // Now stop all plugins that are run by this handler QWriteLocker locker(&loader_mutex_); QHash<QString, QPluginLoader*>::iterator it = loaders_.begin(); while(it != loaders_.end()) { if (!it.value()->isLoaded()) { ++it; continue; } BALLPlugin* plugin = qobject_cast<BALLPlugin*>(it.value()->instance()); if(!plugin || !h->isRunning(plugin)) { ++it; continue; } if(!h->stopPlugin(plugin) || !stopPlugin(plugin)) { return false; } //Delete the loader it.value()->unload(); delete it.value(); it = loaders_.erase(it); } return true; } bool PluginManager::startPlugin(int plugin) { return startPlugin(qobject_cast<BALLPlugin*>(getPluginInstance(plugin))); } bool PluginManager::startPlugin(const QString& plugin) { return startPlugin(qobject_cast<BALLPlugin*>(getPluginInstance(plugin))); } bool PluginManager::startPlugin(BALLPlugin* plugin) { if (!plugin) { return true; } bool started = false; handler_mutex_.lockForRead(); std::list<PluginHandler*>::iterator it = handlers_.begin(); for (; it != handlers_.end(); ++it) { if ((*it)->canHandle(plugin)) { started = (*it)->startPlugin(plugin) && !started; } } handler_mutex_.unlock(); return started; } bool PluginManager::stopPlugin(int plugin) { return stopPlugin(qobject_cast<BALLPlugin*>(getPluginInstance(plugin))); } bool PluginManager::stopPlugin(const QString& plugin) { return stopPlugin(qobject_cast<BALLPlugin*>(getPluginInstance(plugin))); } bool PluginManager::stopPlugin(BALLPlugin* plugin) { if (!plugin) { return true; } bool all_stopped = true; handler_mutex_.lockForRead(); std::list<PluginHandler*>::iterator it = handlers_.begin(); for (; it != handlers_.end(); ++it) { if ((*it)->isRunning(plugin)) { all_stopped = (*it)->stopPlugin(plugin) && all_stopped; } } handler_mutex_.unlock(); return all_stopped; } int PluginManager::getPluginCount() const { QReadLocker locker(&loader_mutex_); return loaders_.size(); } bool PluginManager::getPluginDirectories(String& value) const { if (!loaded_plugin_dirs_.empty()) { std::map<QString, vector<BALLPlugin*> >::const_iterator it = loaded_plugin_dirs_.begin(); if ( it != loaded_plugin_dirs_.end()) { value += it->first.toLatin1().toPercentEncoding().data(); for (++it; it != loaded_plugin_dirs_.end(); ++it) { value += BETWEEN_PLUGINDIR_SEPERATOR; value += it->first.toLatin1().toPercentEncoding().data(); } } } return true; } bool PluginManager::setPluginDirectories(const String& value) { std::vector<String> plugin_directories; String tmp(QByteArray::fromPercentEncoding(QByteArray(value.c_str())).data()); tmp.split(plugin_directories, BETWEEN_PLUGINDIR_SEPERATOR, 0); for (size_t i = 0; i < plugin_directories.size(); ++i) { addPluginDirectory(plugin_directories[i].c_str()); } return true; } QString PluginManager::getAutoActivatePlugins() const { return autoactivate_plugins_.join(";"); } bool PluginManager::setAutoActivatePlugins(const QString& value) { autoactivate_plugins_ = value.split(";", QString::SkipEmptyParts); return true; } void PluginManager::autoActivatePlugin(const QString& str) { if(!autoactivate_plugins_.contains(str)) { autoactivate_plugins_.append(str); } } void PluginManager::doNotAutoActivatePlugin(const QString& str) { autoactivate_plugins_.removeOne(str); } } <commit_msg>[VIEW] Fix: Incorrect return value in PluginManager::startPlugin In the case of multiple handlers for any given plugin, the return value would have been false most of the time, regardless of the handlers' actual success.<commit_after>#include <BALL/PLUGIN/pluginManager.h> #include <BALL/PLUGIN/BALLPlugin.h> #include <BALL/PLUGIN/pluginHandler.h> #include <QtCore/QPluginLoader> #include <QtCore/QDir> #include <QtCore/QReadLocker> #include <QtCore/QWriteLocker> #include <BALL/COMMON/logStream.h> #if defined(BALL_OS_WINDOWS) # define PLUGIN_MASK "plugin*.dll" #elif defined(BALL_OS_DARWIN) # define PLUGIN_MASK "plugin*.dylib" #else # define PLUGIN_MASK "plugin*.so" #endif namespace BALL { const char* PluginManager::BETWEEN_PLUGINDIR_SEPERATOR = "?"; boost::shared_ptr<PluginManager> PluginManager::manager_; QMutex PluginManager::mutex_; PluginManager::PluginManager() { } PluginManager::~PluginManager() { unloadAllPlugins(); } PluginManager& PluginManager::instance() { //Make the PluginManager creation thread safe if (!manager_) { //Another thread could have taken over control right now //so lock a mutex to ensure the PluginManager is created only once. mutex_.lock(); //Check that the manager has not been created by a concurring thread if(!manager_) { manager_ = boost::shared_ptr<PluginManager>(new PluginManager()); } mutex_.unlock(); } return *manager_; } bool PluginManager::addPluginDirectory(const QString& dir) { std::map<QString, vector<BALLPlugin*> >::iterator to_load_it = loaded_plugin_dirs_.find(dir); if (to_load_it == loaded_plugin_dirs_.end()) { vector<BALLPlugin*> loaded_plugins; QDir plugin_dir(dir, PLUGIN_MASK, QDir::Name | QDir::IgnoreCase, QDir::Files); if(!plugin_dir.exists()) { return false; } // collect the loaded plugins in this dir foreach(QString it, plugin_dir.entryList()) { BALLPlugin* new_plugin = loadPlugin(plugin_dir.absoluteFilePath(it)); if (new_plugin) { loaded_plugins.push_back(new_plugin); } } // and store the entry loaded_plugin_dirs_[dir]=loaded_plugins; return true; } return false; } bool PluginManager::unloadDirectoryPlugins_(PluginDirMap::iterator it) { if(it == loaded_plugin_dirs_.end()) { return false; } vector<BALLPlugin*>::iterator to_unload = it->second.begin(); for (; to_unload != it->second.end(); ++to_unload) { unloadPlugin((*to_unload)->getName()); } // and the directory itself loaded_plugin_dirs_.erase(it); return true; } bool PluginManager::removePluginDirectory(const QString& dir) { std::map<QString, vector<BALLPlugin*> >::iterator to_unload_it = loaded_plugin_dirs_.find(dir); return unloadDirectoryPlugins_(to_unload_it); } vector<QString> PluginManager::getPluginDirectories() const { vector<QString> result; std::map<QString, vector<BALLPlugin*> >::const_iterator it = loaded_plugin_dirs_.begin(); for (; it!=loaded_plugin_dirs_.end(); ++it) result.push_back(it->first); return result; } BALLPlugin* PluginManager::loadPlugin(const QString& plugin_name) { BALLPlugin* plugin = 0; QPluginLoader* loader = new QPluginLoader(plugin_name); Log.info() << "Trying to load plugin: " << plugin_name.toStdString() << std::endl; if (loader->load()) { plugin = qobject_cast<BALLPlugin*>(loader->instance()); } else { Log.info() << "Error:" << loader->errorString().toStdString() << std::endl; } if (plugin) { QHash<QString, QPluginLoader*>::iterator it = loaders_.find(plugin->getName()); if(it != loaders_.end()) { Log.info() << "Plugin was already loaded." << std::endl; delete loader; return qobject_cast<BALLPlugin*>(*it); } Log.info() << "Loaded plugin " << plugin_name.toStdString() << "." << std::endl; loader_mutex_.lockForWrite(); loaders_.insert(plugin->getName(), loader); loader_mutex_.unlock(); if(autoactivate_plugins_.contains(plugin->getName())) { startPlugin(plugin); plugin->activate(); } } return plugin; } bool PluginManager::unloadPlugin(const QString& plugin) { QWriteLocker locker(&loader_mutex_); QHash<QString, QPluginLoader*>::iterator it = loaders_.find(plugin); if (it != loaders_.end()) { //Shutdown the plugin stopPlugin(qobject_cast<BALLPlugin*>(it.value()->instance())); // NOTE: unloading crashes BALLView, for some reason! // it is not really crucial to unload the plugins, but we should have // a look at this anyhow //Delete the loader // it.value()->unload(); // delete it.value(); loaders_.erase(it); return true; } return false; } void PluginManager::unloadAllPlugins() { loader_mutex_.lockForWrite(); QHash<QString, QPluginLoader*>::iterator it = loaders_.begin(); for (; it != loaders_.end(); ++it) { //Shutdown the plugin stopPlugin(qobject_cast<BALLPlugin*>(it.value()->instance())); //Delete the loader it.value()->unload(); delete it.value(); } loaders_.clear(); loader_mutex_.unlock(); } QObject* PluginManager::getPluginInstance(const QString& plugin) { QReadLocker locker(&loader_mutex_); QHash<QString, QPluginLoader*>::iterator it = loaders_.find(plugin); if(it != loaders_.end()) { return (it.value()->instance()); } return NULL; } QObject* PluginManager::getPluginInstance(int pos) { QReadLocker locker(&loader_mutex_); if(pos < 0 || pos >= getPluginCount()) { return NULL; } QHash<QString, QPluginLoader*>::const_iterator it = loaders_.begin(); for(int i = 0; i < pos; ++i, ++it) {} return it.value()->instance(); } void PluginManager::registerHandler(const boost::shared_ptr<PluginHandler>& h) { handler_mutex_.lockForWrite(); shared_handlers_.push_back(h); handlers_.push_back(h.get()); handler_mutex_.unlock(); } void PluginManager::registerHandler(PluginHandler* h) { handler_mutex_.lockForWrite(); handlers_.push_back(h); handler_mutex_.unlock(); } bool PluginManager::unregisterHandler(PluginHandler* h) { // First remove the handler from the list of PluginHandlers handler_mutex_.lockForRead(); std::list<PluginHandler*>::iterator ht = std::find(handlers_.begin(), handlers_.end(), h); handler_mutex_.unlock(); if(ht == handlers_.end()) { return true; } handler_mutex_.lockForWrite(); handlers_.erase(ht); handler_mutex_.unlock(); // Now stop all plugins that are run by this handler QWriteLocker locker(&loader_mutex_); QHash<QString, QPluginLoader*>::iterator it = loaders_.begin(); while(it != loaders_.end()) { if (!it.value()->isLoaded()) { ++it; continue; } BALLPlugin* plugin = qobject_cast<BALLPlugin*>(it.value()->instance()); if(!plugin || !h->isRunning(plugin)) { ++it; continue; } if(!h->stopPlugin(plugin) || !stopPlugin(plugin)) { return false; } //Delete the loader it.value()->unload(); delete it.value(); it = loaders_.erase(it); } return true; } bool PluginManager::startPlugin(int plugin) { return startPlugin(qobject_cast<BALLPlugin*>(getPluginInstance(plugin))); } bool PluginManager::startPlugin(const QString& plugin) { return startPlugin(qobject_cast<BALLPlugin*>(getPluginInstance(plugin))); } bool PluginManager::startPlugin(BALLPlugin* plugin) { if (!plugin) { return true; } bool started = false; handler_mutex_.lockForRead(); std::list<PluginHandler*>::iterator it = handlers_.begin(); for (; it != handlers_.end(); ++it) { if ((*it)->canHandle(plugin)) { started |= (*it)->startPlugin(plugin); } } handler_mutex_.unlock(); return started; } bool PluginManager::stopPlugin(int plugin) { return stopPlugin(qobject_cast<BALLPlugin*>(getPluginInstance(plugin))); } bool PluginManager::stopPlugin(const QString& plugin) { return stopPlugin(qobject_cast<BALLPlugin*>(getPluginInstance(plugin))); } bool PluginManager::stopPlugin(BALLPlugin* plugin) { if (!plugin) { return true; } bool all_stopped = true; handler_mutex_.lockForRead(); std::list<PluginHandler*>::iterator it = handlers_.begin(); for (; it != handlers_.end(); ++it) { if ((*it)->isRunning(plugin)) { all_stopped = (*it)->stopPlugin(plugin) && all_stopped; } } handler_mutex_.unlock(); return all_stopped; } int PluginManager::getPluginCount() const { QReadLocker locker(&loader_mutex_); return loaders_.size(); } bool PluginManager::getPluginDirectories(String& value) const { if (!loaded_plugin_dirs_.empty()) { std::map<QString, vector<BALLPlugin*> >::const_iterator it = loaded_plugin_dirs_.begin(); if ( it != loaded_plugin_dirs_.end()) { value += it->first.toLatin1().toPercentEncoding().data(); for (++it; it != loaded_plugin_dirs_.end(); ++it) { value += BETWEEN_PLUGINDIR_SEPERATOR; value += it->first.toLatin1().toPercentEncoding().data(); } } } return true; } bool PluginManager::setPluginDirectories(const String& value) { std::vector<String> plugin_directories; String tmp(QByteArray::fromPercentEncoding(QByteArray(value.c_str())).data()); tmp.split(plugin_directories, BETWEEN_PLUGINDIR_SEPERATOR, 0); for (size_t i = 0; i < plugin_directories.size(); ++i) { addPluginDirectory(plugin_directories[i].c_str()); } return true; } QString PluginManager::getAutoActivatePlugins() const { return autoactivate_plugins_.join(";"); } bool PluginManager::setAutoActivatePlugins(const QString& value) { autoactivate_plugins_ = value.split(";", QString::SkipEmptyParts); return true; } void PluginManager::autoActivatePlugin(const QString& str) { if(!autoactivate_plugins_.contains(str)) { autoactivate_plugins_.append(str); } } void PluginManager::doNotAutoActivatePlugin(const QString& str) { autoactivate_plugins_.removeOne(str); } } <|endoftext|>
<commit_before>// $Id: ShiftModel_test.C,v 1.4 2000/09/22 11:21:20 amoll Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/NMR/shiftModel.h> /////////////////////////// START_TEST(ShiftModel, "$Id: ShiftModel_test.C,v 1.4 2000/09/22 11:21:20 amoll Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; ShiftModel* sm = 0; CHECK(ShiftModel::ShiftModel() throw()) sm = new ShiftModel; TEST_NOT_EQUAL(sm, 0) RESULT CHECK(ShiftModel::~ShiftModel() throw()) delete sm; RESULT CHECK(ShiftModel::isValid() const throw()) ShiftModel sm; TEST_EQUAL(sm.isValid(), false) RESULT CHECK(ShiftModel::isRegistered(const String& name) const throw()) ShiftModel sm; TEST_EQUAL(sm.isRegistered("UNNAMED MODULE X"), false) TEST_EQUAL(sm.isRegistered(""), false) TEST_EQUAL(sm.isRegistered("JohnsonBovey"), true) TEST_EQUAL(sm.isRegistered("HaighMallion"), true) TEST_EQUAL(sm.isRegistered("JohnsonBovey"), true) TEST_EQUAL(sm.isRegistered("Anisotropy"), true) TEST_EQUAL(sm.isRegistered("RandomCoil"), true) TEST_EQUAL(sm.isRegistered("ElectricField"), true) RESULT CHECK(ShiftModel::getParameters() throw()) ShiftModel sm; TEST_NOT_EQUAL(&sm.getParameters(), 0) TEST_EQUAL(sm.getParameters().isValid(), false) RESULT CHECK(ShiftModel::setFilename(const String& filename) throw(Exception::FileNotFound)) ShiftModel sm; TEST_EXCEPTION(Exception::FileNotFound, sm.setFilename("XXXXXX")) TEST_EQUAL(sm.isValid(), false) TEST_EQUAL(sm.getParameters().isValid(), false) sm.setFilename("data/ShiftModel_test.ini"); TEST_EQUAL(sm.isValid(), true) TEST_EQUAL(sm.getParameters().isValid(), true) RESULT CHECK(ShiftModel::getFilename() const throw()) ShiftModel sm; TEST_EXCEPTION(Exception::FileNotFound, sm.setFilename("XXXXXX")) TEST_EQUAL(sm.isValid(), false) TEST_EQUAL(sm.getFilename(), "XXXXXX") sm.setFilename("data/ShiftModel_test.ini"); TEST_EQUAL(sm.isValid(), true) TEST_EQUAL(sm.getFilename(), "data/ShiftModel_test.ini") RESULT CHECK(ShiftModel::getModuleList() throw()) ShiftModel sm; TEST_EQUAL(sm.getModuleList().size(), 0) sm.setFilename("data/ShiftModel_test.ini"); TEST_EQUAL(sm.getModuleList().size(), 2) RESULT CHECK(ShiftModel::registerModule(const String& name, CreateMethod method) throw(Exception::NullPointer)) ShiftModel sm; using namespace RTTI; ShiftModel::CreateMethod m = getNew<ShiftModule>; TEST_EQUAL(sm.isRegistered("TEST"), false) sm.registerModule("TEST", m); TEST_EQUAL(sm.isRegistered("TEST"), true) TEST_EQUAL(sm.isRegistered("TEST2"), false) TEST_EXCEPTION(Exception::NullPointer, sm.registerModule("TEST2", 0)) TEST_EQUAL(sm.isRegistered("TEST2"), false) RESULT CHECK(ShiftModel::unregisterModule(const String& name) throw()) ShiftModel sm; using namespace RTTI; ShiftModel::CreateMethod m = getNew<ShiftModule>; TEST_EQUAL(sm.isRegistered("TEST"), false) sm.registerModule("TEST", m); TEST_EQUAL(sm.isRegistered("TEST"), true) sm.unregisterModule("TEST"); TEST_EQUAL(sm.isRegistered("TEST"), false) sm.unregisterModule("TEST"); TEST_EQUAL(sm.isRegistered("TEST"), false) RESULT CHECK(ShiftModel::ShiftModel(const String& filename) throw()) ShiftModel sm("data/ShiftModel_test.ini"); TEST_EQUAL(sm.isValid(), true) ShiftModel::ModuleList mod_list = sm.getModuleList(); TEST_EQUAL(mod_list.size(), 2) if (mod_list.size() > 0) { TEST_EQUAL((*mod_list.begin())->getName(), "JB_ring_current") } RESULT CHECK(ShiftModel::clear() throw()) ShiftModel sm("data/ShiftModel_test.ini"); sm.clear(); TEST_EQUAL(sm.isValid(), false) TEST_EQUAL(sm.getFilename(), "") TEST_EQUAL(sm.getModuleList().size(), 0) RESULT const ShiftModel smx("data/ShiftModel_test.ini"); CHECK(ShiftModel::ShiftModel(const ShiftModel& model) throw()) ShiftModel sm(smx); TEST_EQUAL(sm.isValid(), true) ShiftModel::ModuleList mod_list = sm.getModuleList(); TEST_EQUAL(mod_list.size(), 2) if (mod_list.size() > 0) { TEST_EQUAL((*mod_list.begin())->getName(), "JB_ring_current") } RESULT CHECK(ShiftModel::ShiftModel& operator = (const ShiftModel& model) throw()) ShiftModel sm = smx; TEST_EQUAL(sm.isValid(), true) ShiftModel::ModuleList mod_list = sm.getModuleList(); TEST_EQUAL(mod_list.size(), 2) if (mod_list.size() > 0) { TEST_EQUAL((*mod_list.begin())->getName(), "JB_ring_current") } RESULT CHECK(ShiftModel::ShiftModel& operator = (const String& filename) throw()) ShiftModel sm = String("data/ShiftModel_test.ini"); TEST_EQUAL(sm.isValid(), true) ShiftModel::ModuleList mod_list = sm.getModuleList(); TEST_EQUAL(mod_list.size(), 2) if (mod_list.size() > 0) { TEST_EQUAL((*mod_list.begin())->getName(), "JB_ring_current") } RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <commit_msg>cosmetic changes<commit_after>// $Id: ShiftModel_test.C,v 1.5 2000/09/22 12:17:08 amoll Exp $ #include <BALL/CONCEPT/classTest.h> /////////////////////////// #include <BALL/NMR/shiftModel.h> /////////////////////////// START_TEST(ShiftModel, "$Id: ShiftModel_test.C,v 1.5 2000/09/22 12:17:08 amoll Exp $") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace BALL; ShiftModel* sm = 0; CHECK(ShiftModel::ShiftModel() throw()) sm = new ShiftModel; TEST_NOT_EQUAL(sm, 0) RESULT CHECK(ShiftModel::~ShiftModel() throw()) delete sm; RESULT CHECK(ShiftModel::isValid() const throw()) ShiftModel sm; TEST_EQUAL(sm.isValid(), false) RESULT CHECK(ShiftModel::isRegistered(const String& name) const throw()) ShiftModel sm; TEST_EQUAL(sm.isRegistered("UNNAMED MODULE X"), false) TEST_EQUAL(sm.isRegistered(""), false) TEST_EQUAL(sm.isRegistered("JohnsonBovey"), true) TEST_EQUAL(sm.isRegistered("HaighMallion"), true) TEST_EQUAL(sm.isRegistered("JohnsonBovey"), true) TEST_EQUAL(sm.isRegistered("Anisotropy"), true) TEST_EQUAL(sm.isRegistered("RandomCoil"), true) TEST_EQUAL(sm.isRegistered("ElectricField"), true) RESULT CHECK(ShiftModel::getParameters() throw()) ShiftModel sm; TEST_NOT_EQUAL(&sm.getParameters(), 0) TEST_EQUAL(sm.getParameters().isValid(), false) RESULT CHECK(ShiftModel::setFilename(const String& filename) throw(Exception::FileNotFound)) ShiftModel sm; TEST_EXCEPTION(Exception::FileNotFound, sm.setFilename("XXXXXX")) TEST_EQUAL(sm.isValid(), false) TEST_EQUAL(sm.getParameters().isValid(), false) sm.setFilename("data/ShiftModel_test.ini"); TEST_EQUAL(sm.isValid(), true) TEST_EQUAL(sm.getParameters().isValid(), true) RESULT CHECK(ShiftModel::getFilename() const throw()) ShiftModel sm; TEST_EXCEPTION(Exception::FileNotFound, sm.setFilename("XXXXXX")) TEST_EQUAL(sm.isValid(), false) TEST_EQUAL(sm.getFilename(), "XXXXXX") sm.setFilename("data/ShiftModel_test.ini"); TEST_EQUAL(sm.isValid(), true) TEST_EQUAL(sm.getFilename(), "data/ShiftModel_test.ini") RESULT CHECK(ShiftModel::getModuleList() throw()) ShiftModel sm; TEST_EQUAL(sm.getModuleList().size(), 0) sm.setFilename("data/ShiftModel_test.ini"); TEST_EQUAL(sm.getModuleList().size(), 2) RESULT CHECK(ShiftModel::registerModule(const String& name, CreateMethod method) throw(Exception::NullPointer)) ShiftModel sm; using namespace RTTI; ShiftModel::CreateMethod m = getNew<ShiftModule>; TEST_EQUAL(sm.isRegistered("TEST"), false) sm.registerModule("TEST", m); TEST_EQUAL(sm.isRegistered("TEST"), true) TEST_EQUAL(sm.isRegistered("TEST2"), false) TEST_EXCEPTION(Exception::NullPointer, sm.registerModule("TEST2", 0)) TEST_EQUAL(sm.isRegistered("TEST2"), false) RESULT CHECK(ShiftModel::unregisterModule(const String& name) throw()) ShiftModel sm; using namespace RTTI; ShiftModel::CreateMethod m = getNew<ShiftModule>; TEST_EQUAL(sm.isRegistered("TEST"), false) sm.registerModule("TEST", m); TEST_EQUAL(sm.isRegistered("TEST"), true) sm.unregisterModule("TEST"); TEST_EQUAL(sm.isRegistered("TEST"), false) sm.unregisterModule("TEST"); TEST_EQUAL(sm.isRegistered("TEST"), false) RESULT CHECK(ShiftModel::ShiftModel(const String& filename) throw()) ShiftModel sm("data/ShiftModel_test.ini"); TEST_EQUAL(sm.isValid(), true) ShiftModel::ModuleList mod_list = sm.getModuleList(); TEST_EQUAL(mod_list.size(), 2) if (mod_list.size() > 0) { TEST_EQUAL((*mod_list.begin())->getName(), "JB_ring_current") } RESULT CHECK(ShiftModel::clear() throw()) ShiftModel sm("data/ShiftModel_test.ini"); sm.clear(); TEST_EQUAL(sm.isValid(), false) TEST_EQUAL(sm.getFilename(), "") TEST_EQUAL(sm.getModuleList().size(), 0) RESULT const ShiftModel smx("data/ShiftModel_test.ini"); CHECK(ShiftModel::ShiftModel(const ShiftModel& model) throw()) ShiftModel sm(smx); TEST_EQUAL(sm.isValid(), true) ShiftModel::ModuleList mod_list = sm.getModuleList(); TEST_EQUAL(mod_list.size(), 2) if (mod_list.size() > 0) { TEST_EQUAL((*mod_list.begin())->getName(), "JB_ring_current") } RESULT CHECK(ShiftModel::ShiftModel& operator = (const ShiftModel& model) throw()) ShiftModel sm = smx; TEST_EQUAL(sm.isValid(), true) ShiftModel::ModuleList mod_list = sm.getModuleList(); TEST_EQUAL(mod_list.size(), 2) if (mod_list.size() > 0) { TEST_EQUAL((*mod_list.begin())->getName(), "JB_ring_current") } RESULT CHECK(ShiftModel::ShiftModel& operator = (const String& filename) throw()) ShiftModel sm = String("data/ShiftModel_test.ini"); TEST_EQUAL(sm.isValid(), true) ShiftModel::ModuleList mod_list = sm.getModuleList(); TEST_EQUAL(mod_list.size(), 2) if (mod_list.size() > 0) { TEST_EQUAL((*mod_list.begin())->getName(), "JB_ring_current") } RESULT ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST <|endoftext|>
<commit_before>//===--------------------- LLDBAssert.cpp ------------------------*- C++-*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "lldb/Utility/LLDBAssert.h" #include "llvm/Support/Format.h" #include "llvm/Support/Signals.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; using namespace lldb_private; void lldb_private::lldb_assert(bool expression, const char *expr_text, const char *func, const char *file, unsigned int line) { if (LLVM_LIKELY(expression)) return; errs() << format("Assertion failed: (%s), function %s, file %s, line %u\n", expr_text, func, file, line); errs() << "backtrace leading to the failure:\n"; llvm::sys::PrintStackTrace(errs()); errs() << "please file a bug report against lldb reporting this failure " "log, and as many details as possible\n"; } <commit_msg>lldb_assert: abort when assertions are enabled.<commit_after>//===--------------------- LLDBAssert.cpp ------------------------*- C++-*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "lldb/Utility/LLDBAssert.h" #include "llvm/Support/Format.h" #include "llvm/Support/Signals.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; using namespace lldb_private; void lldb_private::lldb_assert(bool expression, const char *expr_text, const char *func, const char *file, unsigned int line) { if (LLVM_LIKELY(expression)) return; // In a Debug configuration lldb_assert() behaves like assert(). assert(false && "lldb_assert failed"); // In a Release configuration it will print a warning and encourage the user // to file a bug report, similar to LLVM’s crash handler, and then return // execution. errs() << format("Assertion failed: (%s), function %s, file %s, line %u\n", expr_text, func, file, line); errs() << "backtrace leading to the failure:\n"; llvm::sys::PrintStackTrace(errs()); errs() << "please file a bug report against lldb reporting this failure " "log, and as many details as possible\n"; } <|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 <stdint.h> #include <windows.h> #include <algorithm> #include <vector> #include "base/base_paths.h" #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/files/file_path.h" #include "base/files/memory_mapped_file.h" #include "base/path_service.h" #include "base/strings/string_util.h" #include "base/win/pe_image.h" #include "testing/gtest/include/gtest/gtest.h" namespace { class ELFImportsTest : public testing::Test { protected: static bool ImportsCallback(const base::win::PEImage &image, LPCSTR module, PIMAGE_THUNK_DATA name_table, PIMAGE_THUNK_DATA iat, PVOID cookie) { std::vector<std::string>* import_list = reinterpret_cast<std::vector<std::string>*>(cookie); import_list->push_back(module); return true; } void GetImports(const base::FilePath& module_path, std::vector<std::string>* imports) { ASSERT_TRUE(imports != NULL); base::MemoryMappedFile module_mmap; ASSERT_TRUE(module_mmap.Initialize(module_path)); base::win::PEImageAsData pe_image_data( reinterpret_cast<HMODULE>(const_cast<uint8*>(module_mmap.data()))); pe_image_data.EnumImportChunks(ELFImportsTest::ImportsCallback, imports); } }; TEST_F(ELFImportsTest, ChromeElfSanityCheck) { std::vector<std::string> elf_imports; base::FilePath dll; ASSERT_TRUE(PathService::Get(base::DIR_EXE, &dll)); dll = dll.Append(L"chrome_elf.dll"); GetImports(dll, &elf_imports); // Check that ELF has imports. ASSERT_LT(0u, elf_imports.size()); std::vector<std::string>::iterator it(elf_imports.begin()); static const char* const kValidFilePatterns[] = { "KERNEL32.dll", "MSVC*", #if defined(ADDRESS_SANITIZER) "syzyasan_rtl.dll", #endif "ADVAPI32.dll"}; // Make sure all of ELF's imports are in the valid imports list. for (; it != elf_imports.end(); it++) { bool match = false; for (int i = 0; i < arraysize(kValidFilePatterns); ++i) { if (MatchPattern(*it, kValidFilePatterns[i])) match = true; } ASSERT_TRUE(match) << "Illegal import in chrome_elf.dll."; } } #if defined(ARCH_CPU_64_BITS) #define MAYBE_ChromeExeSanityCheck DISABLED_ChromeExeSanityCheck #else #define MAYBE_ChromeExeSanityCheck ChromeExeSanityCheck #endif // Fails on 64-bit Windows, see http://crbug.com/335173. TEST_F(ELFImportsTest, MAYBE_ChromeExeSanityCheck) { std::vector<std::string> exe_imports; base::FilePath exe; ASSERT_TRUE(PathService::Get(base::DIR_EXE, &exe)); exe = exe.Append(L"chrome.exe"); GetImports(exe, &exe_imports); // Check that chrome.exe has imports. ASSERT_LT(0u, exe_imports.size()); // Chrome.exe's first import must be ELF. EXPECT_EQ("chrome_elf.dll", exe_imports[0]) << "Illegal import order in chrome.exe"; } } // namespace <commit_msg>Add logs to chrome_elf_unittests to ensure the correct target is built.<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 <stdint.h> #include <windows.h> #include <algorithm> #include <vector> #include "base/base_paths.h" #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/files/file_path.h" #include "base/files/memory_mapped_file.h" #include "base/path_service.h" #include "base/strings/string_util.h" #include "base/win/pe_image.h" #include "testing/gtest/include/gtest/gtest.h" namespace { class ELFImportsTest : public testing::Test { protected: static bool ImportsCallback(const base::win::PEImage &image, LPCSTR module, PIMAGE_THUNK_DATA name_table, PIMAGE_THUNK_DATA iat, PVOID cookie) { std::vector<std::string>* import_list = reinterpret_cast<std::vector<std::string>*>(cookie); import_list->push_back(module); return true; } void GetImports(const base::FilePath& module_path, std::vector<std::string>* imports) { ASSERT_TRUE(imports != NULL); base::MemoryMappedFile module_mmap; ASSERT_TRUE(module_mmap.Initialize(module_path)); base::win::PEImageAsData pe_image_data( reinterpret_cast<HMODULE>(const_cast<uint8*>(module_mmap.data()))); pe_image_data.EnumImportChunks(ELFImportsTest::ImportsCallback, imports); } }; TEST_F(ELFImportsTest, ChromeElfSanityCheck) { std::vector<std::string> elf_imports; base::FilePath dll; ASSERT_TRUE(PathService::Get(base::DIR_EXE, &dll)); dll = dll.Append(L"chrome_elf.dll"); GetImports(dll, &elf_imports); // Check that ELF has imports. ASSERT_LT(0u, elf_imports.size()) << "Ensure the chrome_elf_unittests " "target was built, instead of chrome_elf_unittests.exe"; std::vector<std::string>::iterator it(elf_imports.begin()); static const char* const kValidFilePatterns[] = { "KERNEL32.dll", "MSVC*", #if defined(ADDRESS_SANITIZER) "syzyasan_rtl.dll", #endif "ADVAPI32.dll"}; // Make sure all of ELF's imports are in the valid imports list. for (; it != elf_imports.end(); it++) { bool match = false; for (int i = 0; i < arraysize(kValidFilePatterns); ++i) { if (MatchPattern(*it, kValidFilePatterns[i])) match = true; } ASSERT_TRUE(match) << "Illegal import in chrome_elf.dll."; } } #if defined(ARCH_CPU_64_BITS) #define MAYBE_ChromeExeSanityCheck DISABLED_ChromeExeSanityCheck #else #define MAYBE_ChromeExeSanityCheck ChromeExeSanityCheck #endif // Fails on 64-bit Windows, see http://crbug.com/335173. TEST_F(ELFImportsTest, MAYBE_ChromeExeSanityCheck) { std::vector<std::string> exe_imports; base::FilePath exe; ASSERT_TRUE(PathService::Get(base::DIR_EXE, &exe)); exe = exe.Append(L"chrome.exe"); GetImports(exe, &exe_imports); // Check that chrome.exe has imports. ASSERT_LT(0u, exe_imports.size()) << "Ensure the chrome_elf_unittests " "target was built, instead of chrome_elf_unittests.exe"; // Chrome.exe's first import must be ELF. EXPECT_EQ("chrome_elf.dll", exe_imports[0]) << "Illegal import order in chrome.exe (ensure the chrome_elf_unittest " "target was built, instead of just chrome_elf_unittests.exe)"; } } // namespace <|endoftext|>
<commit_before>#include "raptor_api.h" #include "type/pb_converter.h" #include "boost/date_time/posix_time/posix_time.hpp" namespace navitia { namespace routing { namespace raptor { std::string iso_string(const nt::Data & d, int date, int hour){ boost::posix_time::ptime date_time(d.meta.production_date.begin() + boost::gregorian::days(date)); date_time += boost::posix_time::seconds(hour); return boost::posix_time::to_iso_string(date_time); } pbnavitia::Response make_pathes(const std::vector<navitia::routing::Path> &paths, const nt::Data & d) { pbnavitia::Response pb_response; pb_response.set_requested_api(pbnavitia::PLANNER); for(Path path : paths) { pbnavitia::Journey * pb_journey = pb_response.mutable_planner()->add_journey(); pb_journey->set_duration(path.duration); pb_journey->set_nb_transfers(path.nb_changes); for(PathItem & item : path.items){ pbnavitia::Section * pb_section = pb_journey->add_section(); pb_section->set_arrival_date_time(iso_string(d, item.arrival.date(), item.arrival.hour())); pb_section->set_departure_date_time(iso_string(d, item.departure.date(), item.departure.hour())); if(item.type == public_transport) pb_section->set_type(pbnavitia::PUBLIC_TRANSPORT); else pb_section->set_type(pbnavitia::TRANSFER); if(item.type == public_transport && item.vj_idx != type::invalid_idx){ const type::VehicleJourney & vj = d.pt_data.vehicle_journeys[item.vj_idx]; const type::Route & route = d.pt_data.routes[vj.route_idx]; const type::Line & line = d.pt_data.lines[route.line_idx]; fill_pb_object(line.idx, d, pb_section->mutable_line()); } for(navitia::type::idx_t stop_point : item.stop_points){ fill_pb_object(stop_point, d, pb_section->add_stop_point()); } if(item.stop_points.size() >= 2) { pbnavitia::PlaceMark * origin_place_mark = pb_section->mutable_origin(); origin_place_mark->set_type(pbnavitia::STOPAREA); fill_pb_object(d.pt_data.stop_points[item.stop_points.front()].stop_area_idx, d, origin_place_mark->mutable_stop_area()); pbnavitia::PlaceMark * destination_place_mark = pb_section->mutable_destination(); destination_place_mark->set_type(pbnavitia::STOPAREA); fill_pb_object(d.pt_data.stop_points[item.stop_points.back()].stop_area_idx, d, destination_place_mark->mutable_stop_area()); } } } return pb_response; } std::vector<std::pair<type::idx_t, double> > get_stop_points(const type::EntryPoint &ep, const type::Data & data, streetnetwork::StreetNetworkWorker & worker){ std::vector<std::pair<type::idx_t, double> > result; switch(ep.type) { case navitia::type::Type_e::eStopArea: { auto it = data.pt_data.stop_area_map.find(ep.external_code); if(it!= data.pt_data.stop_area_map.end()) { for(auto spidx : data.pt_data.stop_areas[it->second].stop_point_list) { result.push_back(std::make_pair(spidx, 0)); } } } break; case type::Type_e::eStopPoint: { auto it = data.pt_data.stop_point_map.find(ep.external_code); if(it != data.pt_data.stop_point_map.end()){ result.push_back(std::make_pair(data.pt_data.stop_points[it->second].idx, 0)); } } break; case type::Type_e::eCoord: { result = worker.find_nearest(ep.coordinates, data.pt_data.stop_point_proximity_list, 300); } break; default: break; } return result; } vector_idxretour to_idxretour(std::vector<std::pair<type::idx_t, double> > elements, int hour, int day){ vector_idxretour result; for(auto item : elements) { int temps = hour + (item.second / 80); int jour; if(temps > 86400) { temps = temps % 86400; jour = day + 1; } else { jour = day; } result.push_back(std::make_pair(item.first, type_retour(navitia::type::invalid_idx, DateTime(jour, temps), 0, (item.second / 80)))); } return result; } pbnavitia::Response make_response(RAPTOR &raptor, const type::EntryPoint &origin, const type::EntryPoint &destination, const boost::posix_time::ptime &datetime, bool clockwise, streetnetwork::StreetNetworkWorker & worker) { pbnavitia::Response response; if(!raptor.data.meta.production_date.contains(datetime.date())) { response.set_error("Date not in the production period"); return response; } auto departures = get_stop_points(origin, raptor.data, worker); if(departures.size() == 0){ response.set_error("Departure point not found"); return response; } auto destinations = get_stop_points(destination, raptor.data, worker); if(destinations.size() == 0){ response.set_error("Destination point not found"); return response; } std::vector<Path> result; int day = (datetime.date() - raptor.data.meta.production_date.begin()).days(); int time = datetime.time_of_day().total_seconds(); if(clockwise) result = raptor.compute_all(to_idxretour(departures, time, day), to_idxretour(destinations, time, day)); else result = raptor.compute_reverse_all(to_idxretour(departures, time, day), to_idxretour(destinations, time, day)); return make_pathes(result, raptor.data); } pbnavitia::Response make_response(RAPTOR &raptor, const type::EntryPoint &origin, const type::EntryPoint &destination, const std::vector<std::string> &datetimes_str, bool clockwise, streetnetwork::StreetNetworkWorker & worker) { pbnavitia::Response response; std::vector<boost::posix_time::ptime> datetimes; for(std::string datetime: datetimes_str){ try { boost::posix_time::ptime ptime; ptime = boost::posix_time::from_iso_string(datetime); if(!raptor.data.meta.production_date.contains(ptime.date())) { response.set_error("Date not in the production period"); return response; } datetimes.push_back(ptime); } catch(...){ response.set_error("Impossible to parse date " + datetime); return response; } } auto departures = get_stop_points(origin, raptor.data, worker); if(departures.size() == 0){ response.set_error("Departure point not found"); return response; } auto destinations = get_stop_points(destination, raptor.data, worker); if(destinations.size() == 0){ response.set_error("Destination point not found"); return response; } std::vector<Path> result; for(boost::posix_time::ptime datetime : datetimes){ std::vector<Path> tmp; int day = (datetime.date() - raptor.data.meta.production_date.begin()).days(); int time = datetime.time_of_day().total_seconds(); if(clockwise) tmp = raptor.compute_all(to_idxretour(departures, time, day), to_idxretour(destinations, time, day)); else tmp = raptor.compute_reverse_all(to_idxretour(departures, time, day), to_idxretour(destinations, time, day)); if(tmp.size() > 0) result.push_back(tmp.front()); else result.push_back(Path()); } return make_pathes(result, raptor.data); } }}} <commit_msg>RaptorAPI : meilleur retour des messages d'erreur<commit_after>#include "raptor_api.h" #include "type/pb_converter.h" #include "boost/date_time/posix_time/posix_time.hpp" namespace navitia { namespace routing { namespace raptor { std::string iso_string(const nt::Data & d, int date, int hour){ boost::posix_time::ptime date_time(d.meta.production_date.begin() + boost::gregorian::days(date)); date_time += boost::posix_time::seconds(hour); return boost::posix_time::to_iso_string(date_time); } pbnavitia::Response make_pathes(const std::vector<navitia::routing::Path> &paths, const nt::Data & d) { pbnavitia::Response pb_response; pb_response.set_requested_api(pbnavitia::PLANNER); pbnavitia::Planner * planner = pb_response.mutable_planner(); planner->set_response_type(pbnavitia::ITINERARY_FOUND); for(Path path : paths) { pbnavitia::Journey * pb_journey = planner->add_journey(); pb_journey->set_duration(path.duration); pb_journey->set_nb_transfers(path.nb_changes); for(PathItem & item : path.items){ pbnavitia::Section * pb_section = pb_journey->add_section(); pb_section->set_arrival_date_time(iso_string(d, item.arrival.date(), item.arrival.hour())); pb_section->set_departure_date_time(iso_string(d, item.departure.date(), item.departure.hour())); if(item.type == public_transport) pb_section->set_type(pbnavitia::PUBLIC_TRANSPORT); else pb_section->set_type(pbnavitia::TRANSFER); if(item.type == public_transport && item.vj_idx != type::invalid_idx){ const type::VehicleJourney & vj = d.pt_data.vehicle_journeys[item.vj_idx]; const type::Route & route = d.pt_data.routes[vj.route_idx]; const type::Line & line = d.pt_data.lines[route.line_idx]; fill_pb_object(line.idx, d, pb_section->mutable_line()); } for(navitia::type::idx_t stop_point : item.stop_points){ fill_pb_object(stop_point, d, pb_section->add_stop_point()); } if(item.stop_points.size() >= 2) { pbnavitia::PlaceMark * origin_place_mark = pb_section->mutable_origin(); origin_place_mark->set_type(pbnavitia::STOPAREA); fill_pb_object(d.pt_data.stop_points[item.stop_points.front()].stop_area_idx, d, origin_place_mark->mutable_stop_area()); pbnavitia::PlaceMark * destination_place_mark = pb_section->mutable_destination(); destination_place_mark->set_type(pbnavitia::STOPAREA); fill_pb_object(d.pt_data.stop_points[item.stop_points.back()].stop_area_idx, d, destination_place_mark->mutable_stop_area()); } } } return pb_response; } std::vector<std::pair<type::idx_t, double> > get_stop_points(const type::EntryPoint &ep, const type::Data & data, streetnetwork::StreetNetworkWorker & worker){ std::vector<std::pair<type::idx_t, double> > result; switch(ep.type) { case navitia::type::Type_e::eStopArea: { auto it = data.pt_data.stop_area_map.find(ep.external_code); if(it!= data.pt_data.stop_area_map.end()) { for(auto spidx : data.pt_data.stop_areas[it->second].stop_point_list) { result.push_back(std::make_pair(spidx, 0)); } } } break; case type::Type_e::eStopPoint: { auto it = data.pt_data.stop_point_map.find(ep.external_code); if(it != data.pt_data.stop_point_map.end()){ result.push_back(std::make_pair(data.pt_data.stop_points[it->second].idx, 0)); } } break; case type::Type_e::eCoord: { result = worker.find_nearest(ep.coordinates, data.pt_data.stop_point_proximity_list, 300); } break; default: break; } return result; } vector_idxretour to_idxretour(std::vector<std::pair<type::idx_t, double> > elements, int hour, int day){ vector_idxretour result; for(auto item : elements) { int temps = hour + (item.second / 80); int jour; if(temps > 86400) { temps = temps % 86400; jour = day + 1; } else { jour = day; } result.push_back(std::make_pair(item.first, type_retour(navitia::type::invalid_idx, DateTime(jour, temps), 0, (item.second / 80)))); } return result; } pbnavitia::Response make_response(RAPTOR &raptor, const type::EntryPoint &origin, const type::EntryPoint &destination, const boost::posix_time::ptime &datetime, bool clockwise, streetnetwork::StreetNetworkWorker & worker) { pbnavitia::Response response; response.set_requested_api(pbnavitia::PLANNER); if(!raptor.data.meta.production_date.contains(datetime.date())) { response.mutable_planner()->set_response_type(pbnavitia::DATE_OUT_OF_BOUNDS); return response; } auto departures = get_stop_points(origin, raptor.data, worker); auto destinations = get_stop_points(destination, raptor.data, worker); if(departures.size() == 0 && destinations.size() == 0){ response.mutable_planner()->set_response_type(pbnavitia::NO_DEPARTURE_NOR_DESTINATION_POINT); return response; } if(departures.size() == 0){ response.mutable_planner()->set_response_type(pbnavitia::NO_DEPARTURE_NOR_DESTINATION_POINT); return response; } if(destinations.size() == 0){ response.mutable_planner()->set_response_type(pbnavitia::NO_DEPARTURE_POINT); return response; } std::vector<Path> result; int day = (datetime.date() - raptor.data.meta.production_date.begin()).days(); int time = datetime.time_of_day().total_seconds(); if(clockwise) result = raptor.compute_all(to_idxretour(departures, time, day), to_idxretour(destinations, time, day)); else result = raptor.compute_reverse_all(to_idxretour(departures, time, day), to_idxretour(destinations, time, day)); if(result.size() == 0){ response.mutable_planner()->set_response_type(pbnavitia::NO_SOLUTION); return response; } return make_pathes(result, raptor.data); } pbnavitia::Response make_response(RAPTOR &raptor, const type::EntryPoint &origin, const type::EntryPoint &destination, const std::vector<std::string> &datetimes_str, bool clockwise, streetnetwork::StreetNetworkWorker & worker) { pbnavitia::Response response; response.set_requested_api(pbnavitia::PLANNER); std::vector<boost::posix_time::ptime> datetimes; for(std::string datetime: datetimes_str){ try { boost::posix_time::ptime ptime; ptime = boost::posix_time::from_iso_string(datetime); if(!raptor.data.meta.production_date.contains(ptime.date())) { response.mutable_planner()->set_response_type(pbnavitia::DATE_OUT_OF_BOUNDS); response.set_info("Example of invalid date: " + datetime); return response; } datetimes.push_back(ptime); } catch(...){ response.set_error("Impossible to parse date " + datetime); return response; } } auto departures = get_stop_points(origin, raptor.data, worker); auto destinations = get_stop_points(destination, raptor.data, worker); if(departures.size() == 0 && destinations.size() == 0){ response.mutable_planner()->set_response_type(pbnavitia::NO_DEPARTURE_NOR_DESTINATION_POINT); return response; } if(departures.size() == 0){ response.mutable_planner()->set_response_type(pbnavitia::NO_DEPARTURE_NOR_DESTINATION_POINT); return response; } if(destinations.size() == 0){ response.mutable_planner()->set_response_type(pbnavitia::NO_DEPARTURE_POINT); return response; } std::vector<Path> result; for(boost::posix_time::ptime datetime : datetimes){ std::vector<Path> tmp; int day = (datetime.date() - raptor.data.meta.production_date.begin()).days(); int time = datetime.time_of_day().total_seconds(); if(clockwise) tmp = raptor.compute_all(to_idxretour(departures, time, day), to_idxretour(destinations, time, day)); else tmp = raptor.compute_reverse_all(to_idxretour(departures, time, day), to_idxretour(destinations, time, day)); if(tmp.size() > 0) result.push_back(tmp.front()); else result.push_back(Path()); } return make_pathes(result, raptor.data); } }}} <|endoftext|>
<commit_before>#pragma once namespace { namespace bitnodeNS { template <typename A> class bitnode final { template<typename B> using conref = const B &; using byte = unsigned char; using bit = bool; template <typename B> static inline void killPtr(B* &a) noexcept { if (a != nullptr) { delete a; a = nullptr; } } public: inline explicit bitnode(void) noexcept : zero{nullptr}, one{nullptr}, data{nullptr} {} template <typename... B> explicit bitnode(B... b) = delete; inline ~bitnode(void) noexcept { if (data != nullptr) { delete data; } } inline void dump(void) noexcept { bitnode<A>::killPtr<A>(data); } inline A* getData(void) const noexcept { return data; } inline void setData(conref<A> a) noexcept { this->dump(); data = new A{a}; } inline void setData(A* a) noexcept { this->dump(); data = a; } inline void dumpZero(void) noexcept { bitnode<A>::killPtr<bitnode<A>>(zero); } inline bitnode<A>* getZero(void) const noexcept { return zero; } inline void setZero(bitnode<A>* a) noexcept { this->dumpZero(); zero = a; } inline void dumpOne(void) noexcept { bitnode<A>::killPtr<bitnode<A>>(one); } inline bitnode<A>* getOne(void) const noexcept { return one; } inline void setOne(bitnode<A>* a) noexcept { this->dumpOne(); one = a; } inline void dumpAll(void) noexcept { this->dump(); this->dumpZero(); this->dumpOne(); } inline bool isEmpty(void) const noexcept { return data == nullptr; } inline bool isNotEmpty(void) const noexcept { return !this->isEmpty(); } inline bool haveZero(void) const noexcept { return zero != nullptr; } inline bool noZero(void) const noexcept { return !this->haveZero(); } inline bool haveOne(void) const noexcept { return one != nullptr; } inline bool noOne(void) const noexcept { return !this->haveOne(); } inline bool isBarren(void) const noexcept { return this->noZero() && this->noOne(); } inline bool isNotBarren(void) const noexcept { return !this->isBarren(); } private: bitnode<A>* zero; bitnode<A>* one; A* data; }; } } <commit_msg>no need for var name<commit_after>#pragma once namespace { namespace bitnodeNS { template <typename A> class bitnode final { template<typename B> using conref = const B &; using byte = unsigned char; using bit = bool; template <typename B> static inline void killPtr(B* &a) noexcept { if (a != nullptr) { delete a; a = nullptr; } } public: inline explicit bitnode(void) noexcept : zero{nullptr}, one{nullptr}, data{nullptr} {} template <typename... B> explicit bitnode(B...) = delete; inline ~bitnode(void) noexcept { if (data != nullptr) { delete data; } } inline void dump(void) noexcept { bitnode<A>::killPtr<A>(data); } inline A* getData(void) const noexcept { return data; } inline void setData(conref<A> a) noexcept { this->dump(); data = new A{a}; } inline void setData(A* a) noexcept { this->dump(); data = a; } inline void dumpZero(void) noexcept { bitnode<A>::killPtr<bitnode<A>>(zero); } inline bitnode<A>* getZero(void) const noexcept { return zero; } inline void setZero(bitnode<A>* a) noexcept { this->dumpZero(); zero = a; } inline void dumpOne(void) noexcept { bitnode<A>::killPtr<bitnode<A>>(one); } inline bitnode<A>* getOne(void) const noexcept { return one; } inline void setOne(bitnode<A>* a) noexcept { this->dumpOne(); one = a; } inline void dumpAll(void) noexcept { this->dump(); this->dumpZero(); this->dumpOne(); } inline bool isEmpty(void) const noexcept { return data == nullptr; } inline bool isNotEmpty(void) const noexcept { return !this->isEmpty(); } inline bool haveZero(void) const noexcept { return zero != nullptr; } inline bool noZero(void) const noexcept { return !this->haveZero(); } inline bool haveOne(void) const noexcept { return one != nullptr; } inline bool noOne(void) const noexcept { return !this->haveOne(); } inline bool isBarren(void) const noexcept { return this->noZero() && this->noOne(); } inline bool isNotBarren(void) const noexcept { return !this->isBarren(); } private: bitnode<A>* zero; bitnode<A>* one; A* data; }; } } <|endoftext|>
<commit_before>#include <cstdlib> #include <iostream> #include <cmath> #include <tuple> #include <mpl/mpl.hpp> typedef std::tuple<double, double> double_2; template<std::size_t dim, typename T, typename A> void update_overlap(const mpl::cart_communicator &C, mpl::distributed_grid<dim, T, A> &G, int tag=0) { mpl::shift_ranks ranks; mpl::irequest_pool r; for (std::size_t i=0; i<dim; ++i) { // send to left ranks=C.shift(i, -1); r.push(C.isend(G.data(), G.left_border_layout(i), ranks.dest, tag)); r.push(C.irecv(G.data(), G.right_mirror_layout(i), ranks.source, tag)); // send to right ranks=C.shift(i, +1); r.push(C.isend(G.data(), G.right_border_layout(i), ranks.dest, tag)); r.push(C.irecv(G.data(), G.left_mirror_layout(i), ranks.source, tag)); } r.waitall(); } template<std::size_t dim, typename T, typename A> void scatter(const mpl::cart_communicator &C, int root, const mpl::local_grid<dim, T, A> &L, mpl::distributed_grid<dim, T, A> &G) { mpl::irequest r(C.irecv(G.data(), G.interior_layout(), root)); if (C.rank()==root) for (int i=0; i<C.size(); ++i) C.send(L.data(), L.sub_layout(i), i); r.wait(); } template<std::size_t dim, typename T, typename A> void scatter(const mpl::cart_communicator &C, int root, mpl::distributed_grid<dim, T, A> &G) { C.recv(G.data(), G.interior_layout(), root); } template<std::size_t dim, typename T, typename A> void gather(const mpl::cart_communicator &C, int root, const mpl::distributed_grid<dim, T, A> &G, mpl::local_grid<dim, T, A> &L) { mpl::irequest r(C.isend(G.data(), G.interior_layout(), root)); if (C.rank()==root) for (int i=0; i<C.size(); ++i) C.recv(L.data(), L.sub_layout(i), i); r.wait(); } template<std::size_t dim, typename T, typename A> void gather(const mpl::cart_communicator &C, int root, const mpl::distributed_grid<dim, T, A> &G) { C.send(G.data(), G.interior_layout(), root); } int main() { // world communicator const mpl::communicator & comm_world(mpl::environment::comm_world()); // construct a two-dimensional Cartesian communicator with no periodic boundary conditions mpl::cart_communicator::sizes sizes( {{0, false}, {0, false}} ); mpl::cart_communicator comm_c(comm_world, mpl::dims_create(comm_world.size(), sizes)); // total number of inner grid points int Nx=768, Ny=512; // grid points with extremal indices (-1, Nx or Ny) hold fixed boundary data // grid lengths and grid spacings double l_x=1.5, l_y=1, dx=l_x/(Nx+1), dy=l_y/(Ny+1); // distributed grid that holds each processor's subgrid plus one row and // one collumn of neighboring data mpl::distributed_grid<2, double> u_d(comm_c, {{Nx, 1}, {Ny, 1}}); // rank 0 inializes with some random data if (comm_c.rank()==0) { // local grid to store the whole set of inner grid points mpl::local_grid<2, double> u(comm_c, {Nx, Ny}); for (auto j=u.begin(1), j_end=u.end(1); j<j_end; ++j) for (auto i=u.begin(0), i_end=u.end(0); i<i_end; ++i) u(i, j)=std::rand()/static_cast<double>(RAND_MAX); // scater data to each processors subgrid scatter(comm_c, 0, u, u_d); } else scatter(comm_c, 0, u_d); // initiallize boundary data, loop with obegin and oend over all // data including the overlap for (auto j : { u_d.obegin(1), u_d.oend(1)-1 } ) for (auto i=u_d.obegin(0), i_end=u_d.oend(0); i<i_end; ++i) { if (u_d.gindex(0, i)<0 or u_d.gindex(1, j)<0) u_d(i, j)=1; if (u_d.gindex(0, i)>=Nx or u_d.gindex(1, j)>=Ny) u_d(i, j)=0; } for (auto i : { u_d.obegin(0), u_d.oend(0)-1 } ) for (auto j=u_d.obegin(1), j_end=u_d.oend(1); j<j_end; ++j) { if (u_d.gindex(0, i)<0 or u_d.gindex(1, j)<0) u_d(i, j)=1; if (u_d.gindex(0, i)>=Nx or u_d.gindex(1, j)>=Ny) u_d(i, j)=0; } double w=1.875, // the over-relaxation parameter dx2=dx*dx, dy2=dy*dy; // loop until converged bool converged=false; while (not converged) { // exchange overlap data update_overlap(comm_c, u_d); // apply one successive over-relaxation step double Delta_u=0, sum_u=0; for (auto j=u_d.begin(1), j_end=u_d.end(1); j<j_end; ++j) for (auto i=u_d.begin(0), i_end=u_d.end(0); i<i_end; ++i) { double du=-w*u_d(i, j)+ w*(dy2*(u_d(i-1, j)+u_d(i+1, j)) + dx2*(u_d(i, j-1)+u_d(i, j+1)))/(2*(dx2+dy2)); u_d(i, j)+=du; Delta_u+=std::abs(du); sum_u+=std::abs(u_d(i, j)); } // determine global sum of Delta_u and sum_u and distribute to all processors double_2 Delta_sum_u{ Delta_u, sum_u }; // pack into pair // use a lambda function for global reduction comm_c.allreduce([](double_2 a, double_2 b) { // reduction adds component-by-component return double_2{ std::get<0>(a)+std::get<0>(b), std::get<1>(a)+std::get<1>(b) }; }, Delta_sum_u); std::tie(Delta_u, sum_u)=Delta_sum_u; // unpack from pair converged=Delta_u/sum_u<1e-6; // check for convergence } if (comm_c.rank()==0) { // local grid to store the whole set of inner grid points mpl::local_grid<2, double> u(comm_c, {Nx, Ny}); // gather data and print result gather(comm_c, 0, u_d, u); for (auto j=u.begin(1), j_end=u.end(1); j<j_end; ++j) { for (auto i=u.begin(0), i_end=u.end(0); i<i_end; ++i) std::cout << u(i, j) << '\t'; std::cout << '\n'; } } else gather(comm_c, 0, u_d); return EXIT_SUCCESS; } <commit_msg>gatherv/scatterv for collective operations<commit_after>#include <cstdlib> #include <iostream> #include <cmath> #include <tuple> #include <mpl/mpl.hpp> typedef std::tuple<double, double> double_2; template<std::size_t dim, typename T, typename A> void update_overlap(const mpl::cart_communicator &C, mpl::distributed_grid<dim, T, A> &G, int tag=0) { mpl::shift_ranks ranks; mpl::irequest_pool r; for (std::size_t i=0; i<dim; ++i) { // send to left ranks=C.shift(i, -1); r.push(C.isend(G.data(), G.left_border_layout(i), ranks.dest, tag)); r.push(C.irecv(G.data(), G.right_mirror_layout(i), ranks.source, tag)); // send to right ranks=C.shift(i, +1); r.push(C.isend(G.data(), G.right_border_layout(i), ranks.dest, tag)); r.push(C.irecv(G.data(), G.left_mirror_layout(i), ranks.source, tag)); } r.waitall(); } template<std::size_t dim, typename T, typename A> void scatter(const mpl::cart_communicator &C, int root, const mpl::local_grid<dim, T, A> &L, mpl::distributed_grid<dim, T, A> &G) { C.scatterv(root, L.data(), L.sub_layouts(), mpl::displacements(C.size()), G.data(), G.interior_layout()); } template<std::size_t dim, typename T, typename A> void scatter(const mpl::cart_communicator &C, int root, mpl::distributed_grid<dim, T, A> &G) { C.scatterv(root, G.data(), G.interior_layout()); } template<std::size_t dim, typename T, typename A> void gather(const mpl::cart_communicator &C, int root, const mpl::distributed_grid<dim, T, A> &G, mpl::local_grid<dim, T, A> &L) { C.gatherv(root, G.data(), G.interior_layout(), L.data(), L.sub_layouts(), mpl::displacements(C.size())); } template<std::size_t dim, typename T, typename A> void gather(const mpl::cart_communicator &C, int root, const mpl::distributed_grid<dim, T, A> &G) { C.gatherv(root, G.data(), G.interior_layout()); } int main() { // world communicator const mpl::communicator & comm_world(mpl::environment::comm_world()); // construct a two-dimensional Cartesian communicator with no periodic boundary conditions mpl::cart_communicator::sizes sizes( {{0, false}, {0, false}} ); mpl::cart_communicator comm_c(comm_world, mpl::dims_create(comm_world.size(), sizes)); // total number of inner grid points int Nx=768, Ny=512; // grid points with extremal indices (-1, Nx or Ny) hold fixed boundary data // grid lengths and grid spacings double l_x=1.5, l_y=1, dx=l_x/(Nx+1), dy=l_y/(Ny+1); // distributed grid that holds each processor's subgrid plus one row and // one collumn of neighboring data mpl::distributed_grid<2, double> u_d(comm_c, {{Nx, 1}, {Ny, 1}}); // rank 0 inializes with some random data if (comm_c.rank()==0) { // local grid to store the whole set of inner grid points mpl::local_grid<2, double> u(comm_c, {Nx, Ny}); for (auto j=u.begin(1), j_end=u.end(1); j<j_end; ++j) for (auto i=u.begin(0), i_end=u.end(0); i<i_end; ++i) u(i, j)=std::rand()/static_cast<double>(RAND_MAX); // scater data to each processors subgrid scatter(comm_c, 0, u, u_d); } else scatter(comm_c, 0, u_d); // initiallize boundary data, loop with obegin and oend over all // data including the overlap for (auto j : { u_d1.obegin(1), u_d1.oend(1)-1 } ) for (auto i=u_d1.obegin(0), i_end=u_d1.oend(0); i<i_end; ++i) { if (u_d1.gindex(0, i)<0 or u_d1.gindex(1, j)<0) u_d1(i, j)=u_d2(i, j)=1; // left boundary condition if (u_d1.gindex(0, i)>=Nx or u_d1.gindex(1, j)>=Ny) u_d1(i, j)=u_d2(i, j)=0; // right boundary condition } for (auto i : { u_d1.obegin(0), u_d1.oend(0)-1 } ) for (auto j=u_d1.obegin(1), j_end=u_d1.oend(1); j<j_end; ++j) { if (u_d1.gindex(0, i)<0 or u_d1.gindex(1, j)<0) u_d1(i, j)=u_d2(i, j)=1; // lower boundary condition if (u_d1.gindex(0, i)>=Nx or u_d1.gindex(1, j)>=Ny) u_d1(i, j)=u_d2(i, j)=0; // upper boundary condition } double w=1.875, // the over-relaxation parameter dx2=dx*dx, dy2=dy*dy; // loop until converged bool converged=false; while (not converged) { // exchange overlap data update_overlap(comm_c, u_d); // apply one successive over-relaxation step double Delta_u=0, sum_u=0; for (auto j=u_d.begin(1), j_end=u_d.end(1); j<j_end; ++j) for (auto i=u_d.begin(0), i_end=u_d.end(0); i<i_end; ++i) { double du=-w*u_d(i, j)+ w*(dy2*(u_d(i-1, j)+u_d(i+1, j)) + dx2*(u_d(i, j-1)+u_d(i, j+1)))/(2*(dx2+dy2)); u_d(i, j)+=du; Delta_u+=std::abs(du); sum_u+=std::abs(u_d(i, j)); } // determine global sum of Delta_u and sum_u and distribute to all processors double_2 Delta_sum_u{ Delta_u, sum_u }; // pack into pair // use a lambda function for global reduction comm_c.allreduce([](double_2 a, double_2 b) { // reduction adds component-by-component return double_2{ std::get<0>(a)+std::get<0>(b), std::get<1>(a)+std::get<1>(b) }; }, Delta_sum_u); std::tie(Delta_u, sum_u)=Delta_sum_u; // unpack from pair converged=Delta_u/sum_u<1e-6; // check for convergence } if (comm_c.rank()==0) { // local grid to store the whole set of inner grid points mpl::local_grid<2, double> u(comm_c, {Nx, Ny}); // gather data and print result gather(comm_c, 0, u_d, u); for (auto j=u.begin(1), j_end=u.end(1); j<j_end; ++j) { for (auto i=u.begin(0), i_end=u.end(0); i<i_end; ++i) std::cout << u(i, j) << '\t'; std::cout << '\n'; } } else gather(comm_c, 0, u_d); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * * Copyright 2015-2016 gRPC authors. * * 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 <fstream> #include <iostream> #include <memory> #include <set> #include <grpcpp/impl/codegen/config_protobuf.h> #include <gflags/gflags.h> #include <grpc/support/log.h> #include "test/cpp/qps/benchmark_config.h" #include "test/cpp/qps/driver.h" #include "test/cpp/qps/parse_json.h" #include "test/cpp/qps/report.h" #include "test/cpp/qps/server.h" #include "test/cpp/util/test_config.h" #include "test/cpp/util/test_credentials_provider.h" DEFINE_string(scenarios_file, "", "JSON file containing an array of Scenario objects"); DEFINE_string(scenarios_json, "", "JSON string containing an array of Scenario objects"); DEFINE_bool(quit, false, "Quit the workers"); DEFINE_string(search_param, "", "The parameter, whose value is to be searched for to achieve " "targeted cpu load. For now, we have 'offered_load'. Later, " "'num_channels', 'num_outstanding_requests', etc. shall be " "added."); DEFINE_double( initial_search_value, 0.0, "initial parameter value to start the search with (i.e. lower bound)"); DEFINE_double(targeted_cpu_load, 70.0, "Targeted cpu load (unit: %, range [0,100])"); DEFINE_double(stride, 1, "Defines each stride of the search. The larger the stride is, " "the coarser the result will be, but will also be faster."); DEFINE_double(error_tolerance, 0.01, "Defines threshold for stopping the search. When current search " "range is narrower than the error_tolerance computed range, we " "stop the search."); DEFINE_string(qps_server_target_override, "", "Override QPS server target to configure in client configs." "Only applicable if there is a single benchmark server."); DEFINE_string(json_file_out, "", "File to write the JSON output to."); DEFINE_string(credential_type, grpc::testing::kInsecureCredentialsType, "Credential type for communication with workers"); DEFINE_string( per_worker_credential_types, "", "A map of QPS worker addresses to credential types. When creating a " "channel to a QPS worker's driver port, the qps_json_driver first checks " "if the 'name:port' string is in the map, and it uses the corresponding " "credential type if so. If the QPS worker's 'name:port' string is not " "in the map, then the driver -> worker channel will be created with " "the credentials specified in --credential_type. The value of this flag " "is a semicolon-separated list of map entries, where each map entry is " "a comma-separated pair."); DEFINE_bool(run_inproc, false, "Perform an in-process transport test"); DEFINE_int32( median_latency_collection_interval_millis, 0, "Specifies the period between gathering latency medians in " "milliseconds. The medians will be logged out on the client at the " "end of the benchmark run. If 0, this periodic collection is disabled."); namespace grpc { namespace testing { static std::map<std::string, std::string> ConstructPerWorkerCredentialTypesMap() { // Parse a list of the form: "addr1,cred_type1;addr2,cred_type2;..." into // a map. std::string remaining = FLAGS_per_worker_credential_types; std::map<std::string, std::string> out; while (remaining.size() > 0) { size_t next_semicolon = remaining.find(';'); std::string next_entry = remaining.substr(0, next_semicolon); if (next_semicolon == std::string::npos) { remaining = ""; } else { remaining = remaining.substr(next_semicolon + 1, std::string::npos); } size_t comma = next_entry.find(','); if (comma == std::string::npos) { gpr_log(GPR_ERROR, "Expectd --per_worker_credential_types to be a list " "of the form: 'addr1,cred_type1;addr2,cred_type2;...' " "into."); abort(); } std::string addr = next_entry.substr(0, comma); std::string cred_type = next_entry.substr(comma + 1, std::string::npos); if (out.find(addr) != out.end()) { gpr_log(GPR_ERROR, "Found duplicate addr in per_worker_credential_types."); abort(); } out[addr] = cred_type; } return out; } static std::unique_ptr<ScenarioResult> RunAndReport( const Scenario& scenario, const std::map<std::string, std::string>& per_worker_credential_types, bool* success) { std::cerr << "RUNNING SCENARIO: " << scenario.name() << "\n"; auto result = RunScenario(scenario.client_config(), scenario.num_clients(), scenario.server_config(), scenario.num_servers(), scenario.warmup_seconds(), scenario.benchmark_seconds(), !FLAGS_run_inproc ? scenario.spawn_local_worker_count() : -2, FLAGS_qps_server_target_override, FLAGS_credential_type, per_worker_credential_types, FLAGS_run_inproc, FLAGS_median_latency_collection_interval_millis); // Amend the result with scenario config. Eventually we should adjust // RunScenario contract so we don't need to touch the result here. result->mutable_scenario()->CopyFrom(scenario); GetReporter()->ReportQPS(*result); GetReporter()->ReportQPSPerCore(*result); GetReporter()->ReportLatency(*result); GetReporter()->ReportTimes(*result); GetReporter()->ReportCpuUsage(*result); GetReporter()->ReportPollCount(*result); GetReporter()->ReportQueriesPerCpuSec(*result); for (int i = 0; *success && i < result->client_success_size(); i++) { *success = result->client_success(i); } for (int i = 0; *success && i < result->server_success_size(); i++) { *success = result->server_success(i); } if (FLAGS_json_file_out != "") { std::ofstream json_outfile; json_outfile.open(FLAGS_json_file_out); json_outfile << "{\"qps\": " << result->summary().qps() << "}\n"; json_outfile.close(); } return result; } static double GetCpuLoad( Scenario* scenario, double offered_load, const std::map<std::string, std::string>& per_worker_credential_types, bool* success) { scenario->mutable_client_config() ->mutable_load_params() ->mutable_poisson() ->set_offered_load(offered_load); auto result = RunAndReport(*scenario, per_worker_credential_types, success); return result->summary().server_cpu_usage(); } static double BinarySearch( Scenario* scenario, double targeted_cpu_load, double low, double high, const std::map<std::string, std::string>& per_worker_credential_types, bool* success) { while (low <= high * (1 - FLAGS_error_tolerance)) { double mid = low + (high - low) / 2; double current_cpu_load = GetCpuLoad(scenario, mid, per_worker_credential_types, success); gpr_log(GPR_DEBUG, "Binary Search: current_offered_load %.0f", mid); if (!*success) { gpr_log(GPR_ERROR, "Client/Server Failure"); break; } if (targeted_cpu_load <= current_cpu_load) { high = mid - FLAGS_stride; } else { low = mid + FLAGS_stride; } } return low; } static double SearchOfferedLoad( double initial_offered_load, double targeted_cpu_load, Scenario* scenario, const std::map<std::string, std::string>& per_worker_credential_types, bool* success) { std::cerr << "RUNNING SCENARIO: " << scenario->name() << "\n"; double current_offered_load = initial_offered_load; double current_cpu_load = GetCpuLoad(scenario, current_offered_load, per_worker_credential_types, success); if (current_cpu_load > targeted_cpu_load) { gpr_log(GPR_ERROR, "Initial offered load too high"); return -1; } while (*success && (current_cpu_load < targeted_cpu_load)) { current_offered_load *= 2; current_cpu_load = GetCpuLoad(scenario, current_offered_load, per_worker_credential_types, success); gpr_log(GPR_DEBUG, "Binary Search: current_offered_load %.0f", current_offered_load); } double targeted_offered_load = BinarySearch(scenario, targeted_cpu_load, current_offered_load / 2, current_offered_load, per_worker_credential_types, success); return targeted_offered_load; } static bool QpsDriver() { grpc::string json; bool scfile = (FLAGS_scenarios_file != ""); bool scjson = (FLAGS_scenarios_json != ""); if ((!scfile && !scjson && !FLAGS_quit) || (scfile && (scjson || FLAGS_quit)) || (scjson && FLAGS_quit)) { gpr_log(GPR_ERROR, "Exactly one of --scenarios_file, --scenarios_json, " "or --quit must be set"); abort(); } auto per_worker_credential_types = ConstructPerWorkerCredentialTypesMap(); if (scfile) { // Read the json data from disk FILE* json_file = fopen(FLAGS_scenarios_file.c_str(), "r"); GPR_ASSERT(json_file != nullptr); fseek(json_file, 0, SEEK_END); long len = ftell(json_file); char* data = new char[len]; fseek(json_file, 0, SEEK_SET); GPR_ASSERT(len == (long)fread(data, 1, len, json_file)); fclose(json_file); json = grpc::string(data, data + len); delete[] data; } else if (scjson) { json = FLAGS_scenarios_json.c_str(); } else if (FLAGS_quit) { return RunQuit(FLAGS_credential_type, per_worker_credential_types); } // Parse into an array of scenarios Scenarios scenarios; ParseJson(json.c_str(), "grpc.testing.Scenarios", &scenarios); bool success = true; // Make sure that there is at least some valid scenario here GPR_ASSERT(scenarios.scenarios_size() > 0); for (int i = 0; i < scenarios.scenarios_size(); i++) { if (FLAGS_search_param == "") { const Scenario& scenario = scenarios.scenarios(i); RunAndReport(scenario, per_worker_credential_types, &success); } else { if (FLAGS_search_param == "offered_load") { Scenario* scenario = scenarios.mutable_scenarios(i); double targeted_offered_load = SearchOfferedLoad( FLAGS_initial_search_value, FLAGS_targeted_cpu_load, scenario, per_worker_credential_types, &success); gpr_log(GPR_INFO, "targeted_offered_load %f", targeted_offered_load); GetCpuLoad(scenario, targeted_offered_load, per_worker_credential_types, &success); } else { gpr_log(GPR_ERROR, "Unimplemented search param"); } } } return success; } } // namespace testing } // namespace grpc int main(int argc, char** argv) { grpc::testing::InitTest(&argc, &argv, true); bool ok = grpc::testing::QpsDriver(); return ok ? 0 : 1; } <commit_msg>fix clang tidy<commit_after>/* * * Copyright 2015-2016 gRPC authors. * * 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 <fstream> #include <iostream> #include <memory> #include <set> #include <grpcpp/impl/codegen/config_protobuf.h> #include <gflags/gflags.h> #include <grpc/support/log.h> #include "test/cpp/qps/benchmark_config.h" #include "test/cpp/qps/driver.h" #include "test/cpp/qps/parse_json.h" #include "test/cpp/qps/report.h" #include "test/cpp/qps/server.h" #include "test/cpp/util/test_config.h" #include "test/cpp/util/test_credentials_provider.h" DEFINE_string(scenarios_file, "", "JSON file containing an array of Scenario objects"); DEFINE_string(scenarios_json, "", "JSON string containing an array of Scenario objects"); DEFINE_bool(quit, false, "Quit the workers"); DEFINE_string(search_param, "", "The parameter, whose value is to be searched for to achieve " "targeted cpu load. For now, we have 'offered_load'. Later, " "'num_channels', 'num_outstanding_requests', etc. shall be " "added."); DEFINE_double( initial_search_value, 0.0, "initial parameter value to start the search with (i.e. lower bound)"); DEFINE_double(targeted_cpu_load, 70.0, "Targeted cpu load (unit: %, range [0,100])"); DEFINE_double(stride, 1, "Defines each stride of the search. The larger the stride is, " "the coarser the result will be, but will also be faster."); DEFINE_double(error_tolerance, 0.01, "Defines threshold for stopping the search. When current search " "range is narrower than the error_tolerance computed range, we " "stop the search."); DEFINE_string(qps_server_target_override, "", "Override QPS server target to configure in client configs." "Only applicable if there is a single benchmark server."); DEFINE_string(json_file_out, "", "File to write the JSON output to."); DEFINE_string(credential_type, grpc::testing::kInsecureCredentialsType, "Credential type for communication with workers"); DEFINE_string( per_worker_credential_types, "", "A map of QPS worker addresses to credential types. When creating a " "channel to a QPS worker's driver port, the qps_json_driver first checks " "if the 'name:port' string is in the map, and it uses the corresponding " "credential type if so. If the QPS worker's 'name:port' string is not " "in the map, then the driver -> worker channel will be created with " "the credentials specified in --credential_type. The value of this flag " "is a semicolon-separated list of map entries, where each map entry is " "a comma-separated pair."); DEFINE_bool(run_inproc, false, "Perform an in-process transport test"); DEFINE_int32( median_latency_collection_interval_millis, 0, "Specifies the period between gathering latency medians in " "milliseconds. The medians will be logged out on the client at the " "end of the benchmark run. If 0, this periodic collection is disabled."); namespace grpc { namespace testing { static std::map<std::string, std::string> ConstructPerWorkerCredentialTypesMap() { // Parse a list of the form: "addr1,cred_type1;addr2,cred_type2;..." into // a map. std::string remaining = FLAGS_per_worker_credential_types; std::map<std::string, std::string> out; while (!remaining.empty()) { size_t next_semicolon = remaining.find(';'); std::string next_entry = remaining.substr(0, next_semicolon); if (next_semicolon == std::string::npos) { remaining = ""; } else { remaining = remaining.substr(next_semicolon + 1, std::string::npos); } size_t comma = next_entry.find(','); if (comma == std::string::npos) { gpr_log(GPR_ERROR, "Expectd --per_worker_credential_types to be a list " "of the form: 'addr1,cred_type1;addr2,cred_type2;...' " "into."); abort(); } std::string addr = next_entry.substr(0, comma); std::string cred_type = next_entry.substr(comma + 1, std::string::npos); if (out.find(addr) != out.end()) { gpr_log(GPR_ERROR, "Found duplicate addr in per_worker_credential_types."); abort(); } out[addr] = cred_type; } return out; } static std::unique_ptr<ScenarioResult> RunAndReport( const Scenario& scenario, const std::map<std::string, std::string>& per_worker_credential_types, bool* success) { std::cerr << "RUNNING SCENARIO: " << scenario.name() << "\n"; auto result = RunScenario(scenario.client_config(), scenario.num_clients(), scenario.server_config(), scenario.num_servers(), scenario.warmup_seconds(), scenario.benchmark_seconds(), !FLAGS_run_inproc ? scenario.spawn_local_worker_count() : -2, FLAGS_qps_server_target_override, FLAGS_credential_type, per_worker_credential_types, FLAGS_run_inproc, FLAGS_median_latency_collection_interval_millis); // Amend the result with scenario config. Eventually we should adjust // RunScenario contract so we don't need to touch the result here. result->mutable_scenario()->CopyFrom(scenario); GetReporter()->ReportQPS(*result); GetReporter()->ReportQPSPerCore(*result); GetReporter()->ReportLatency(*result); GetReporter()->ReportTimes(*result); GetReporter()->ReportCpuUsage(*result); GetReporter()->ReportPollCount(*result); GetReporter()->ReportQueriesPerCpuSec(*result); for (int i = 0; *success && i < result->client_success_size(); i++) { *success = result->client_success(i); } for (int i = 0; *success && i < result->server_success_size(); i++) { *success = result->server_success(i); } if (FLAGS_json_file_out != "") { std::ofstream json_outfile; json_outfile.open(FLAGS_json_file_out); json_outfile << "{\"qps\": " << result->summary().qps() << "}\n"; json_outfile.close(); } return result; } static double GetCpuLoad( Scenario* scenario, double offered_load, const std::map<std::string, std::string>& per_worker_credential_types, bool* success) { scenario->mutable_client_config() ->mutable_load_params() ->mutable_poisson() ->set_offered_load(offered_load); auto result = RunAndReport(*scenario, per_worker_credential_types, success); return result->summary().server_cpu_usage(); } static double BinarySearch( Scenario* scenario, double targeted_cpu_load, double low, double high, const std::map<std::string, std::string>& per_worker_credential_types, bool* success) { while (low <= high * (1 - FLAGS_error_tolerance)) { double mid = low + (high - low) / 2; double current_cpu_load = GetCpuLoad(scenario, mid, per_worker_credential_types, success); gpr_log(GPR_DEBUG, "Binary Search: current_offered_load %.0f", mid); if (!*success) { gpr_log(GPR_ERROR, "Client/Server Failure"); break; } if (targeted_cpu_load <= current_cpu_load) { high = mid - FLAGS_stride; } else { low = mid + FLAGS_stride; } } return low; } static double SearchOfferedLoad( double initial_offered_load, double targeted_cpu_load, Scenario* scenario, const std::map<std::string, std::string>& per_worker_credential_types, bool* success) { std::cerr << "RUNNING SCENARIO: " << scenario->name() << "\n"; double current_offered_load = initial_offered_load; double current_cpu_load = GetCpuLoad(scenario, current_offered_load, per_worker_credential_types, success); if (current_cpu_load > targeted_cpu_load) { gpr_log(GPR_ERROR, "Initial offered load too high"); return -1; } while (*success && (current_cpu_load < targeted_cpu_load)) { current_offered_load *= 2; current_cpu_load = GetCpuLoad(scenario, current_offered_load, per_worker_credential_types, success); gpr_log(GPR_DEBUG, "Binary Search: current_offered_load %.0f", current_offered_load); } double targeted_offered_load = BinarySearch(scenario, targeted_cpu_load, current_offered_load / 2, current_offered_load, per_worker_credential_types, success); return targeted_offered_load; } static bool QpsDriver() { grpc::string json; bool scfile = (FLAGS_scenarios_file != ""); bool scjson = (FLAGS_scenarios_json != ""); if ((!scfile && !scjson && !FLAGS_quit) || (scfile && (scjson || FLAGS_quit)) || (scjson && FLAGS_quit)) { gpr_log(GPR_ERROR, "Exactly one of --scenarios_file, --scenarios_json, " "or --quit must be set"); abort(); } auto per_worker_credential_types = ConstructPerWorkerCredentialTypesMap(); if (scfile) { // Read the json data from disk FILE* json_file = fopen(FLAGS_scenarios_file.c_str(), "r"); GPR_ASSERT(json_file != nullptr); fseek(json_file, 0, SEEK_END); long len = ftell(json_file); char* data = new char[len]; fseek(json_file, 0, SEEK_SET); GPR_ASSERT(len == (long)fread(data, 1, len, json_file)); fclose(json_file); json = grpc::string(data, data + len); delete[] data; } else if (scjson) { json = FLAGS_scenarios_json.c_str(); } else if (FLAGS_quit) { return RunQuit(FLAGS_credential_type, per_worker_credential_types); } // Parse into an array of scenarios Scenarios scenarios; ParseJson(json.c_str(), "grpc.testing.Scenarios", &scenarios); bool success = true; // Make sure that there is at least some valid scenario here GPR_ASSERT(scenarios.scenarios_size() > 0); for (int i = 0; i < scenarios.scenarios_size(); i++) { if (FLAGS_search_param == "") { const Scenario& scenario = scenarios.scenarios(i); RunAndReport(scenario, per_worker_credential_types, &success); } else { if (FLAGS_search_param == "offered_load") { Scenario* scenario = scenarios.mutable_scenarios(i); double targeted_offered_load = SearchOfferedLoad( FLAGS_initial_search_value, FLAGS_targeted_cpu_load, scenario, per_worker_credential_types, &success); gpr_log(GPR_INFO, "targeted_offered_load %f", targeted_offered_load); GetCpuLoad(scenario, targeted_offered_load, per_worker_credential_types, &success); } else { gpr_log(GPR_ERROR, "Unimplemented search param"); } } } return success; } } // namespace testing } // namespace grpc int main(int argc, char** argv) { grpc::testing::InitTest(&argc, &argv, true); bool ok = grpc::testing::QpsDriver(); return ok ? 0 : 1; } <|endoftext|>
<commit_before>#pragma once #include <bts/blockchain/types.hpp> namespace bts { namespace blockchain { static std::unordered_map<uint32_t, bts::blockchain::block_id_type> CHECKPOINT_BLOCKS { { 1, bts::blockchain::block_id_type( "8523e28fde6eed4eb749a84e28c9c7b56870c9cc" ) }, { 172718, bts::blockchain::block_id_type( "e452dd44902bc86110923285da03ac12e8cfbe6f" ) }, { 173585, bts::blockchain::block_id_type( "1d1695bc8ebd3ebae0168007afb2912269adbef1" ) }, { 192000, bts::blockchain::block_id_type( "80910335f384f420930351deac69debd007f74c0" ) }, { 236000, bts::blockchain::block_id_type( "049b5a56e3431c5020817d84ef56fbf22c1ac634" ) } }; // Initialized in load_checkpoints() static uint32_t LAST_CHECKPOINT_BLOCK_NUM = 0; } } // bts::blockchain <commit_msg>Update checkpoints<commit_after>#pragma once #include <bts/blockchain/types.hpp> namespace bts { namespace blockchain { static std::unordered_map<uint32_t, bts::blockchain::block_id_type> CHECKPOINT_BLOCKS { { 1, bts::blockchain::block_id_type( "8523e28fde6eed4eb749a84e28c9c7b56870c9cc" ) }, { 25001, bts::blockchain::block_id_type( "f5bbb4c5728d809e3d0877354964ea24e9961904" ) }, { 120001, bts::blockchain::block_id_type( "1557fee97884c893aaebba9a1fed803e7fd005d9" ) }, { 129601, bts::blockchain::block_id_type( "18bcec3430d35538470d7fddc2a51a28cb71fcde" ) }, { 172718, bts::blockchain::block_id_type( "e452dd44902bc86110923285da03ac12e8cfbe6f" ) }, { 173585, bts::blockchain::block_id_type( "1d1695bc8ebd3ebae0168007afb2912269adbef1" ) }, { 187001, bts::blockchain::block_id_type( "72d06a6ba3e79c02327d8048852f9e51b6c8ea71" ) }, { 237501, bts::blockchain::block_id_type( "42d7bb317f51082f7faffee3f7c79bf59f47acac" ) }, { 253000, bts::blockchain::block_id_type( "39ac82bf60cb8455c9d648da18616668d4f0d5ca" ) } }; // Initialized in load_checkpoints() static uint32_t LAST_CHECKPOINT_BLOCK_NUM = 0; } } // bts::blockchain <|endoftext|>
<commit_before>#pragma once #include <bts/blockchain/types.hpp> namespace bts { namespace blockchain { static std::map<uint32_t, bts::blockchain::block_id_type> CHECKPOINT_BLOCKS { { 1, bts::blockchain::block_id_type( "8523e28fde6eed4eb749a84e28c9c7b56870c9cc" ) }, { 25001, bts::blockchain::block_id_type( "f5bbb4c5728d809e3d0877354964ea24e9961904" ) }, { 120001, bts::blockchain::block_id_type( "1557fee97884c893aaebba9a1fed803e7fd005d9" ) }, { 129601, bts::blockchain::block_id_type( "18bcec3430d35538470d7fddc2a51a28cb71fcde" ) }, { 172718, bts::blockchain::block_id_type( "e452dd44902bc86110923285da03ac12e8cfbe6f" ) }, { 173585, bts::blockchain::block_id_type( "1d1695bc8ebd3ebae0168007afb2912269adbef1" ) }, { 187001, bts::blockchain::block_id_type( "72d06a6ba3e79c02327d8048852f9e51b6c8ea71" ) }, { 237501, bts::blockchain::block_id_type( "42d7bb317f51082f7faffee3f7c79bf59f47acac" ) }, { 650001, bts::blockchain::block_id_type( "f5d74cc87e68adf44af8c7b5528d3716e70f7102" ) }, { 799900, bts::blockchain::block_id_type( "cab248195b20f9b8f93488fe666a7ead86e91156" ) } }; // Initialized in load_checkpoints() static uint32_t LAST_CHECKPOINT_BLOCK_NUM = 0; } } // bts::blockchain <commit_msg>Update checkpoint<commit_after>#pragma once #include <bts/blockchain/types.hpp> namespace bts { namespace blockchain { static std::map<uint32_t, bts::blockchain::block_id_type> CHECKPOINT_BLOCKS { { 1, bts::blockchain::block_id_type( "8523e28fde6eed4eb749a84e28c9c7b56870c9cc" ) }, { 25001, bts::blockchain::block_id_type( "f5bbb4c5728d809e3d0877354964ea24e9961904" ) }, { 120001, bts::blockchain::block_id_type( "1557fee97884c893aaebba9a1fed803e7fd005d9" ) }, { 129601, bts::blockchain::block_id_type( "18bcec3430d35538470d7fddc2a51a28cb71fcde" ) }, { 172718, bts::blockchain::block_id_type( "e452dd44902bc86110923285da03ac12e8cfbe6f" ) }, { 173585, bts::blockchain::block_id_type( "1d1695bc8ebd3ebae0168007afb2912269adbef1" ) }, { 187001, bts::blockchain::block_id_type( "72d06a6ba3e79c02327d8048852f9e51b6c8ea71" ) }, { 237501, bts::blockchain::block_id_type( "42d7bb317f51082f7faffee3f7c79bf59f47acac" ) }, { 650001, bts::blockchain::block_id_type( "f5d74cc87e68adf44af8c7b5528d3716e70f7102" ) }, { 1275700, bts::blockchain::block_id_type( "d9dec580e5797b607065615c289dd866f5c647f6" ) } }; // Initialized in load_checkpoints() static uint32_t LAST_CHECKPOINT_BLOCK_NUM = 0; } } // bts::blockchain <|endoftext|>
<commit_before>#include <memory> #include <type_traits> #include <gtest/gtest.h> #include <entt/core/hashed_string.hpp> #include <entt/meta/meta.hpp> #include <entt/meta/pointer.hpp> #include <entt/meta/resolve.hpp> template<typename Type> struct wrapped_shared_ptr { wrapped_shared_ptr(Type init): ptr{new Type {init}} {} Type & deref() const { return *ptr; } private: std::shared_ptr<Type> ptr; }; template<typename Type> struct adl_wrapped_shared_ptr: wrapped_shared_ptr<Type> {}; template<typename Type> struct spec_wrapped_shared_ptr: wrapped_shared_ptr<Type> {}; template<typename Type> struct entt::is_meta_pointer_like<adl_wrapped_shared_ptr<Type>>: std::true_type {}; template<typename Type> struct entt::is_meta_pointer_like<spec_wrapped_shared_ptr<Type>>: std::true_type {}; template<typename Type> Type & dereference_meta_pointer_like(const adl_wrapped_shared_ptr<Type> &ptr) { return ptr.deref(); } template<typename Type> struct entt::adl_meta_pointer_like<spec_wrapped_shared_ptr<Type>> { static decltype(auto) dereference(const spec_wrapped_shared_ptr<Type> &ptr) { return ptr.deref(); } }; void test_function() {} struct not_copyable_t { not_copyable_t() = default; not_copyable_t(const not_copyable_t &) = delete; not_copyable_t(not_copyable_t &&) = default; not_copyable_t & operator=(const not_copyable_t &) = delete; not_copyable_t & operator=(not_copyable_t &&) = default; }; TEST(MetaPointerLike, DereferenceOperatorInvalidType) { int value = 0; entt::meta_any any{value}; ASSERT_FALSE(any.type().is_pointer()); ASSERT_FALSE(any.type().is_pointer_like()); ASSERT_EQ(any.type(), entt::resolve<int>()); auto deref = *any; ASSERT_FALSE(deref); } TEST(MetaPointerLike, DereferenceOperatorConstType) { const int value = 42; entt::meta_any any{&value}; ASSERT_TRUE(any.type().is_pointer()); ASSERT_TRUE(any.type().is_pointer_like()); ASSERT_EQ(any.type(), entt::resolve<const int *>()); auto deref = *any; ASSERT_TRUE(deref); ASSERT_FALSE(deref.type().is_pointer()); ASSERT_FALSE(deref.type().is_pointer_like()); ASSERT_EQ(deref.type(), entt::resolve<int>()); ASSERT_EQ(deref.try_cast<int>(), nullptr); ASSERT_EQ(deref.try_cast<const int>(), &value); ASSERT_DEATH(deref.cast<int &>() = 0, ".*"); ASSERT_EQ(deref.cast<const int &>(), 42); } TEST(MetaPointerLike, DereferenceOperatorConstAny) { auto test = [](const entt::meta_any any) { auto deref = *any; ASSERT_TRUE(deref); ASSERT_FALSE(deref.type().is_pointer()); ASSERT_FALSE(deref.type().is_pointer_like()); ASSERT_EQ(deref.type(), entt::resolve<int>()); ASSERT_EQ(deref.try_cast<int>(), nullptr); ASSERT_NE(deref.try_cast<const int>(), nullptr); ASSERT_DEATH(deref.cast<int &>() = 0, ".*"); ASSERT_EQ(deref.cast<const int &>(), 42); }; int value = 42; test(&value); test(&std::as_const(value)); } TEST(MetaPointerLike, DereferenceOperatorRawPointer) { int value = 0; entt::meta_any any{&value}; ASSERT_TRUE(any.type().is_pointer()); ASSERT_TRUE(any.type().is_pointer_like()); ASSERT_EQ(any.type(), entt::resolve<int *>()); auto deref = *any; ASSERT_TRUE(deref); ASSERT_FALSE(deref.type().is_pointer()); ASSERT_FALSE(deref.type().is_pointer_like()); ASSERT_EQ(deref.type(), entt::resolve<int>()); deref.cast<int &>() = 42; ASSERT_EQ(*any.cast<int *>(), 42); ASSERT_EQ(value, 42); } TEST(MetaPointerLike, DereferenceOperatorSmartPointer) { auto value = std::make_shared<int>(0); entt::meta_any any{value}; ASSERT_FALSE(any.type().is_pointer()); ASSERT_TRUE(any.type().is_pointer_like()); ASSERT_EQ(any.type(), entt::resolve<std::shared_ptr<int>>()); auto deref = *any; ASSERT_TRUE(deref); ASSERT_FALSE(deref.type().is_pointer()); ASSERT_FALSE(deref.type().is_pointer_like()); ASSERT_EQ(deref.type(), entt::resolve<int>()); deref.cast<int &>() = 42; ASSERT_EQ(*any.cast<std::shared_ptr<int>>(), 42); ASSERT_EQ(*value, 42); } TEST(MetaPointerLike, PointerToConstMoveOnlyType) { const not_copyable_t instance; entt::meta_any any{&instance}; auto deref = *any; ASSERT_TRUE(any); ASSERT_TRUE(deref); ASSERT_DEATH(deref.cast<not_copyable_t &>() = {}, ".*"); ASSERT_EQ(deref.try_cast<not_copyable_t>(), nullptr); ASSERT_NE(deref.try_cast<const not_copyable_t>(), nullptr); } TEST(MetaPointerLike, AsRef) { int value = 0; int * ptr = &value; entt::meta_any any{std::ref(ptr)}; ASSERT_TRUE(any.type().is_pointer()); ASSERT_TRUE(any.type().is_pointer_like()); ASSERT_EQ(any.type(), entt::resolve<int *>()); auto deref = *any; ASSERT_TRUE(deref); ASSERT_FALSE(deref.type().is_pointer()); ASSERT_FALSE(deref.type().is_pointer_like()); ASSERT_EQ(deref.type(), entt::resolve<int>()); deref.cast<int &>() = 42; ASSERT_EQ(*any.cast<int *>(), 42); ASSERT_EQ(value, 42); } TEST(MetaPointerLike, AsConstRef) { int value = 42; int * ptr = &value; entt::meta_any any{std::cref(ptr)}; ASSERT_TRUE(any.type().is_pointer()); ASSERT_TRUE(any.type().is_pointer_like()); ASSERT_EQ(any.type(), entt::resolve<int *>()); auto deref = *any; ASSERT_TRUE(deref); ASSERT_FALSE(deref.type().is_pointer()); ASSERT_FALSE(deref.type().is_pointer_like()); ASSERT_EQ(deref.type(), entt::resolve<int>()); deref.cast<int &>() = 42; ASSERT_EQ(*any.cast<int *>(), 42); ASSERT_EQ(value, 42); } TEST(MetaPointerLike, DereferenceOverload) { auto test = [](entt::meta_any any) { ASSERT_FALSE(any.type().is_pointer()); ASSERT_TRUE(any.type().is_pointer_like()); auto deref = *any; ASSERT_TRUE(deref); ASSERT_FALSE(deref.type().is_pointer()); ASSERT_FALSE(deref.type().is_pointer_like()); ASSERT_EQ(deref.type(), entt::resolve<int>()); ASSERT_EQ(deref.cast<int &>(), 42); ASSERT_EQ(deref.cast<const int &>(), 42); }; test(adl_wrapped_shared_ptr<int>{42}); test(spec_wrapped_shared_ptr<int>{42}); } TEST(MetaPointerLike, DereferencePointerToConstOverload) { auto test = [](entt::meta_any any) { ASSERT_FALSE(any.type().is_pointer()); ASSERT_TRUE(any.type().is_pointer_like()); auto deref = *any; ASSERT_TRUE(deref); ASSERT_FALSE(deref.type().is_pointer()); ASSERT_FALSE(deref.type().is_pointer_like()); ASSERT_EQ(deref.type(), entt::resolve<int>()); ASSERT_DEATH(deref.cast<int &>() = 42, ".*"); ASSERT_EQ(deref.cast<const int &>(), 42); }; test(adl_wrapped_shared_ptr<const int>{42}); test(spec_wrapped_shared_ptr<const int>{42}); } TEST(MetaPointerLike, DereferencePointerToVoid) { auto test = [](entt::meta_any any) { ASSERT_TRUE(any.type().is_pointer()); ASSERT_TRUE(any.type().is_pointer_like()); ASSERT_EQ(any.type().remove_pointer(), entt::resolve<void>()); auto deref = *any; ASSERT_FALSE(deref); }; test(static_cast<void *>(nullptr)); test(static_cast<const void *>(nullptr)); } TEST(MetaPointerLike, DereferenceSmartPointerToVoid) { auto test = [](entt::meta_any any) { ASSERT_TRUE(any.type().is_class()); ASSERT_FALSE(any.type().is_pointer()); ASSERT_TRUE(any.type().is_pointer_like()); auto deref = *any; ASSERT_FALSE(deref); }; test(std::shared_ptr<void>{}); test(std::unique_ptr<void, void(*)(void *)>{nullptr, nullptr}); } TEST(MetaPointerLike, DereferencePointerToFunction) { entt::meta_any any{&test_function}; ASSERT_TRUE(any.type().is_pointer()); ASSERT_TRUE(any.type().is_pointer_like()); ASSERT_EQ(any.type().remove_pointer(), entt::resolve<void()>()); auto deref = *any; ASSERT_TRUE(deref.type().is_pointer()); ASSERT_TRUE(deref.type().is_pointer_like()); ASSERT_EQ(deref.type().remove_pointer(), entt::resolve<void()>()); } <commit_msg>meta: more tests for meta pointers (code coverage)<commit_after>#include <memory> #include <type_traits> #include <gtest/gtest.h> #include <entt/core/hashed_string.hpp> #include <entt/meta/meta.hpp> #include <entt/meta/pointer.hpp> #include <entt/meta/resolve.hpp> template<typename Type> struct wrapped_shared_ptr { wrapped_shared_ptr(Type init): ptr{new Type {init}} {} Type & deref() const { return *ptr; } private: std::shared_ptr<Type> ptr; }; template<typename Type> struct adl_wrapped_shared_ptr: wrapped_shared_ptr<Type> {}; template<typename Type> struct spec_wrapped_shared_ptr: wrapped_shared_ptr<Type> {}; template<typename Type> struct entt::is_meta_pointer_like<adl_wrapped_shared_ptr<Type>>: std::true_type {}; template<typename Type> struct entt::is_meta_pointer_like<spec_wrapped_shared_ptr<Type>>: std::true_type {}; template<typename Type> Type & dereference_meta_pointer_like(const adl_wrapped_shared_ptr<Type> &ptr) { return ptr.deref(); } template<typename Type> struct entt::adl_meta_pointer_like<spec_wrapped_shared_ptr<Type>> { static decltype(auto) dereference(const spec_wrapped_shared_ptr<Type> &ptr) { return ptr.deref(); } }; int test_function() { return 42; } struct not_copyable_t { not_copyable_t() = default; not_copyable_t(const not_copyable_t &) = delete; not_copyable_t(not_copyable_t &&) = default; not_copyable_t & operator=(const not_copyable_t &) = delete; not_copyable_t & operator=(not_copyable_t &&) = default; }; TEST(MetaPointerLike, DereferenceOperatorInvalidType) { int value = 0; entt::meta_any any{value}; ASSERT_FALSE(any.type().is_pointer()); ASSERT_FALSE(any.type().is_pointer_like()); ASSERT_EQ(any.type(), entt::resolve<int>()); auto deref = *any; ASSERT_FALSE(deref); } TEST(MetaPointerLike, DereferenceOperatorConstType) { const int value = 42; entt::meta_any any{&value}; ASSERT_TRUE(any.type().is_pointer()); ASSERT_TRUE(any.type().is_pointer_like()); ASSERT_EQ(any.type(), entt::resolve<const int *>()); auto deref = *any; ASSERT_TRUE(deref); ASSERT_FALSE(deref.type().is_pointer()); ASSERT_FALSE(deref.type().is_pointer_like()); ASSERT_EQ(deref.type(), entt::resolve<int>()); ASSERT_EQ(deref.try_cast<int>(), nullptr); ASSERT_EQ(deref.try_cast<const int>(), &value); ASSERT_DEATH(deref.cast<int &>() = 0, ".*"); ASSERT_EQ(deref.cast<const int &>(), 42); } TEST(MetaPointerLike, DereferenceOperatorConstAny) { auto test = [](const entt::meta_any any) { auto deref = *any; ASSERT_TRUE(deref); ASSERT_FALSE(deref.type().is_pointer()); ASSERT_FALSE(deref.type().is_pointer_like()); ASSERT_EQ(deref.type(), entt::resolve<int>()); ASSERT_EQ(deref.try_cast<int>(), nullptr); ASSERT_NE(deref.try_cast<const int>(), nullptr); ASSERT_DEATH(deref.cast<int &>() = 0, ".*"); ASSERT_EQ(deref.cast<const int &>(), 42); }; int value = 42; test(&value); test(&std::as_const(value)); } TEST(MetaPointerLike, DereferenceOperatorRawPointer) { int value = 0; entt::meta_any any{&value}; ASSERT_TRUE(any.type().is_pointer()); ASSERT_TRUE(any.type().is_pointer_like()); ASSERT_EQ(any.type(), entt::resolve<int *>()); auto deref = *any; ASSERT_TRUE(deref); ASSERT_FALSE(deref.type().is_pointer()); ASSERT_FALSE(deref.type().is_pointer_like()); ASSERT_EQ(deref.type(), entt::resolve<int>()); deref.cast<int &>() = 42; ASSERT_EQ(*any.cast<int *>(), 42); ASSERT_EQ(value, 42); } TEST(MetaPointerLike, DereferenceOperatorSmartPointer) { auto value = std::make_shared<int>(0); entt::meta_any any{value}; ASSERT_FALSE(any.type().is_pointer()); ASSERT_TRUE(any.type().is_pointer_like()); ASSERT_EQ(any.type(), entt::resolve<std::shared_ptr<int>>()); auto deref = *any; ASSERT_TRUE(deref); ASSERT_FALSE(deref.type().is_pointer()); ASSERT_FALSE(deref.type().is_pointer_like()); ASSERT_EQ(deref.type(), entt::resolve<int>()); deref.cast<int &>() = 42; ASSERT_EQ(*any.cast<std::shared_ptr<int>>(), 42); ASSERT_EQ(*value, 42); } TEST(MetaPointerLike, PointerToConstMoveOnlyType) { const not_copyable_t instance; entt::meta_any any{&instance}; auto deref = *any; ASSERT_TRUE(any); ASSERT_TRUE(deref); ASSERT_DEATH(deref.cast<not_copyable_t &>() = {}, ".*"); ASSERT_EQ(deref.try_cast<not_copyable_t>(), nullptr); ASSERT_NE(deref.try_cast<const not_copyable_t>(), nullptr); } TEST(MetaPointerLike, AsRef) { int value = 0; int * ptr = &value; entt::meta_any any{std::ref(ptr)}; ASSERT_TRUE(any.type().is_pointer()); ASSERT_TRUE(any.type().is_pointer_like()); ASSERT_EQ(any.type(), entt::resolve<int *>()); auto deref = *any; ASSERT_TRUE(deref); ASSERT_FALSE(deref.type().is_pointer()); ASSERT_FALSE(deref.type().is_pointer_like()); ASSERT_EQ(deref.type(), entt::resolve<int>()); deref.cast<int &>() = 42; ASSERT_EQ(*any.cast<int *>(), 42); ASSERT_EQ(value, 42); } TEST(MetaPointerLike, AsConstRef) { int value = 42; int * ptr = &value; entt::meta_any any{std::cref(ptr)}; ASSERT_TRUE(any.type().is_pointer()); ASSERT_TRUE(any.type().is_pointer_like()); ASSERT_EQ(any.type(), entt::resolve<int *>()); auto deref = *any; ASSERT_TRUE(deref); ASSERT_FALSE(deref.type().is_pointer()); ASSERT_FALSE(deref.type().is_pointer_like()); ASSERT_EQ(deref.type(), entt::resolve<int>()); deref.cast<int &>() = 42; ASSERT_EQ(*any.cast<int *>(), 42); ASSERT_EQ(value, 42); } TEST(MetaPointerLike, DereferenceOverload) { auto test = [](entt::meta_any any) { ASSERT_FALSE(any.type().is_pointer()); ASSERT_TRUE(any.type().is_pointer_like()); auto deref = *any; ASSERT_TRUE(deref); ASSERT_FALSE(deref.type().is_pointer()); ASSERT_FALSE(deref.type().is_pointer_like()); ASSERT_EQ(deref.type(), entt::resolve<int>()); ASSERT_EQ(deref.cast<int &>(), 42); ASSERT_EQ(deref.cast<const int &>(), 42); }; test(adl_wrapped_shared_ptr<int>{42}); test(spec_wrapped_shared_ptr<int>{42}); } TEST(MetaPointerLike, DereferencePointerToConstOverload) { auto test = [](entt::meta_any any) { ASSERT_FALSE(any.type().is_pointer()); ASSERT_TRUE(any.type().is_pointer_like()); auto deref = *any; ASSERT_TRUE(deref); ASSERT_FALSE(deref.type().is_pointer()); ASSERT_FALSE(deref.type().is_pointer_like()); ASSERT_EQ(deref.type(), entt::resolve<int>()); ASSERT_DEATH(deref.cast<int &>() = 42, ".*"); ASSERT_EQ(deref.cast<const int &>(), 42); }; test(adl_wrapped_shared_ptr<const int>{42}); test(spec_wrapped_shared_ptr<const int>{42}); } TEST(MetaPointerLike, DereferencePointerToVoid) { auto test = [](entt::meta_any any) { ASSERT_TRUE(any.type().is_pointer()); ASSERT_TRUE(any.type().is_pointer_like()); ASSERT_EQ(any.type().remove_pointer(), entt::resolve<void>()); auto deref = *any; ASSERT_FALSE(deref); }; test(static_cast<void *>(nullptr)); test(static_cast<const void *>(nullptr)); } TEST(MetaPointerLike, DereferenceSmartPointerToVoid) { auto test = [](entt::meta_any any) { ASSERT_TRUE(any.type().is_class()); ASSERT_FALSE(any.type().is_pointer()); ASSERT_TRUE(any.type().is_pointer_like()); auto deref = *any; ASSERT_FALSE(deref); }; test(std::shared_ptr<void>{}); test(std::unique_ptr<void, void(*)(void *)>{nullptr, nullptr}); } TEST(MetaPointerLike, DereferencePointerToFunction) { auto test = [](entt::meta_any any) { ASSERT_TRUE(any.type().is_pointer()); ASSERT_TRUE(any.type().is_pointer_like()); ASSERT_EQ(any.type().remove_pointer(), entt::resolve<int()>()); ASSERT_NE(any.try_cast<int(*)()>(), nullptr); ASSERT_EQ(any.cast<int(*)()>()(), 42); }; test(entt::meta_any{&test_function}); test(*entt::meta_any{&test_function}); test(**entt::meta_any{&test_function}); } <|endoftext|>
<commit_before>/** @file A brief file description @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // This is total BS, because our libraries are riddled with cross dependencies. // TODO: Clean up the dependency mess, and get rid of this. #include "libts.h" #include "LogObject.h" #if defined(solaris) #include <sys/types.h> #include <unistd.h> #endif #include "P_Net.h" int fds_limit = 8000; UDPNetProcessor &udpNet; ClassAllocator<UDPPacketInternal> udpPacketAllocator("udpPacketAllocator"); void UDPConnection::Release() { ink_release_assert(false); } void UDPNetProcessor::FreeBandwidth(Continuation * udpConn) { ink_release_assert(false); } NetProcessor& netProcessor; Action * UnixNetProcessor::connect_re_internal(Continuation * cont, unsigned int ip, int port, NetVCOptions * opt) { ink_release_assert(false); return NULL; } #include "InkAPIInternal.h" ConfigUpdateCbTable *global_config_cbs = NULL; void ConfigUpdateCbTable::invoke(const char *name) { ink_release_assert(false); } const char * event_int_to_string(int event, int blen, char *buffer) { ink_release_assert(false); return NULL; } struct Machine; Machine * this_machine() { ink_release_assert(false); return NULL; } #include "LogConfig.h" void LogConfig::setup_collation(LogConfig * prev_config) { ink_release_assert(false); } void LogConfig::create_pre_defined_objects_with_filter(const PreDefinedFormatInfoList & pre_def_info_list, size_t num_filters, LogFilter ** filter, const char *filt_name, bool force_extension) { ink_release_assert(false); } int LogHost::write(LogBuffer * lb, size_t * to_disk, size_t * to_net, size_t * to_pipe) { ink_release_assert(false); return 0; } NetVCOptions const Connection::DEFAULT_OPTIONS; NetProcessor::AcceptOptions const NetProcessor::DEFAULT_ACCEPT_OPTIONS; NetProcessor::AcceptOptions& NetProcessor::AcceptOptions::reset() { ink_release_assert(false); return *this; } <commit_msg>TS-655 More fixes for Solaris<commit_after>/** @file A brief file description @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // This is total BS, because our libraries are riddled with cross dependencies. // TODO: Clean up the dependency mess, and get rid of this. #include "libts.h" #include "LogObject.h" #if defined(solaris) #include <sys/types.h> #include <unistd.h> #endif #include "P_Net.h" int fds_limit = 8000; UDPNetProcessor &udpNet; ClassAllocator<UDPPacketInternal> udpPacketAllocator("udpPacketAllocator"); void UDPConnection::Release() { ink_release_assert(false); } void UDPNetProcessor::FreeBandwidth(Continuation * udpConn) { ink_release_assert(false); } NetProcessor& netProcessor; Action * UnixNetProcessor::connect_re_internal(Continuation * cont, unsigned int ip, int port, NetVCOptions * opt) { ink_release_assert(false); return NULL; } #include "InkAPIInternal.h" ConfigUpdateCbTable *global_config_cbs = NULL; void ConfigUpdateCbTable::invoke(const char *name) { ink_release_assert(false); } const char * event_int_to_string(int event, int blen, char *buffer) { ink_release_assert(false); return NULL; } struct Machine; Machine * this_machine() { ink_release_assert(false); return NULL; } #include "LogConfig.h" void LogConfig::setup_collation(LogConfig * prev_config) { ink_release_assert(false); } void LogConfig::create_pre_defined_objects_with_filter(const PreDefinedFormatInfoList & pre_def_info_list, size_t num_filters, LogFilter ** filter, const char *filt_name, bool force_extension) { ink_release_assert(false); } int LogHost::write(LogBuffer * lb, size_t * to_disk, size_t * to_net, size_t * to_pipe) { ink_release_assert(false); return 0; } NetVCOptions const Connection::DEFAULT_OPTIONS; NetProcessor::AcceptOptions const NetProcessor::DEFAULT_ACCEPT_OPTIONS; NetProcessor::AcceptOptions& NetProcessor::AcceptOptions::reset() { ink_release_assert(false); return *this; } int net_accept(NetAccept * na, void *ep, bool blockable) { ink_release_assert(false); return 0; } <|endoftext|>
<commit_before>//===- SparcV9PreSelection.cpp - Specialize LLVM code for SparcV9 ---------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the PreSelection pass which specializes LLVM code for // the SparcV9 instruction selector, while remaining in legal portable LLVM // form and preserving type information and type safety. This is meant to enable // dataflow optimizations on SparcV9-specific operations such as accesses to // constants, globals, and array indexing. // //===----------------------------------------------------------------------===// #include "SparcV9Internals.h" #include "SparcV9BurgISel.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Instructions.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Support/InstVisitor.h" #include "llvm/Support/GetElementPtrTypeIterator.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Transforms/Scalar.h" #include <algorithm> using namespace llvm; namespace { //===--------------------------------------------------------------------===// // PreSelection Pass - Specialize LLVM code for the SparcV9 instr. selector. // class PreSelection : public FunctionPass, public InstVisitor<PreSelection> { const TargetInstrInfo &instrInfo; public: PreSelection(const TargetMachine &T) : instrInfo(*T.getInstrInfo()) {} // runOnFunction - apply this pass to each Function bool runOnFunction(Function &F) { visit(F); return true; } const char *getPassName() const { return "SparcV9 Instr. Pre-selection"; } // These methods do the actual work of specializing code void visitInstruction(Instruction &I); // common work for every instr. void visitGetElementPtrInst(GetElementPtrInst &I); void visitCallInst(CallInst &I); void visitPHINode(PHINode &PN); void visitBasicBlock(BasicBlock &BB) { if (isa<UnreachableInst>(BB.getTerminator())) { BB.getInstList().pop_back(); const Type *RetTy = BB.getParent()->getReturnType(); Value *RetVal = RetTy == Type::VoidTy ? 0 : UndefValue::get(RetTy); new ReturnInst(RetVal, &BB); } } // Helper functions for visiting operands of every instruction // // visitOperands() works on every operand in [firstOp, lastOp-1]. // If lastOp==0, lastOp defaults to #operands or #incoming Phi values. // // visitOneOperand() does all the work for one operand. // void visitOperands(Instruction &I, int firstOp=0); void visitOneOperand(Instruction &I, Value* Op, unsigned opNum, Instruction& insertBefore); }; #if 0 // Register the pass... RegisterPass<PreSelection> X("preselect", "Specialize LLVM code for a target machine" createPreselectionPass); #endif } // end anonymous namespace //------------------------------------------------------------------------------ // Helper functions used by methods of class PreSelection //------------------------------------------------------------------------------ // getGlobalAddr(): Put address of a global into a v. register. static GetElementPtrInst* getGlobalAddr(Value* ptr, Instruction& insertBefore) { return (isa<GlobalVariable>(ptr)) ? new GetElementPtrInst(ptr, std::vector<Value*>(1, ConstantSInt::get(Type::LongTy, 0U)), "addrOfGlobal:" + ptr->getName(), &insertBefore) : NULL; } // Wrapper on Constant::classof to use in find_if inline static bool nonConstant(const Use& U) { return ! isa<Constant>(U); } static Instruction* DecomposeConstantExpr(ConstantExpr* CE, Instruction& insertBefore) { Value *getArg1, *getArg2; switch(CE->getOpcode()) { case Instruction::Cast: getArg1 = CE->getOperand(0); if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1)) getArg1 = DecomposeConstantExpr(CEarg, insertBefore); return new CastInst(getArg1, CE->getType(), "constantCast",&insertBefore); case Instruction::GetElementPtr: assert(std::find_if(CE->op_begin()+1, CE->op_end(), nonConstant) == CE->op_end() && "All indices in ConstantExpr getelementptr must be constant!"); getArg1 = CE->getOperand(0); if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1)) getArg1 = DecomposeConstantExpr(CEarg, insertBefore); else if (GetElementPtrInst* gep = getGlobalAddr(getArg1, insertBefore)) getArg1 = gep; return new GetElementPtrInst(getArg1, std::vector<Value*>(CE->op_begin()+1, CE->op_end()), "constantGEP:" + getArg1->getName(), &insertBefore); case Instruction::Select: { Value *C, *S1, *S2; C = CE->getOperand (0); if (ConstantExpr* CEarg = dyn_cast<ConstantExpr> (C)) C = DecomposeConstantExpr (CEarg, insertBefore); S1 = CE->getOperand (1); if (ConstantExpr* CEarg = dyn_cast<ConstantExpr> (S1)) S1 = DecomposeConstantExpr (CEarg, insertBefore); S2 = CE->getOperand (2); if (ConstantExpr* CEarg = dyn_cast<ConstantExpr> (S2)) S2 = DecomposeConstantExpr (CEarg, insertBefore); return new SelectInst (C, S1, S2, "constantSelect", &insertBefore); } default: // must be a binary operator assert(CE->getOpcode() >= Instruction::BinaryOpsBegin && CE->getOpcode() < Instruction::BinaryOpsEnd && "Unhandled opcode in ConstantExpr"); getArg1 = CE->getOperand(0); if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1)) getArg1 = DecomposeConstantExpr(CEarg, insertBefore); getArg2 = CE->getOperand(1); if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg2)) getArg2 = DecomposeConstantExpr(CEarg, insertBefore); return BinaryOperator::create((Instruction::BinaryOps) CE->getOpcode(), getArg1, getArg2, "constantBinaryOp", &insertBefore); } } static inline bool ConstantTypeMustBeLoaded(const Type* CVT) { assert(CVT->isPrimitiveType() || isa<PointerType>(CVT)); return !(CVT->isIntegral() || isa<PointerType>(CVT)); } //------------------------------------------------------------------------------ // Instruction visitor methods to perform instruction-specific operations //------------------------------------------------------------------------------ inline void PreSelection::visitOneOperand(Instruction &I, Value* Op, unsigned opNum, Instruction& insertBefore) { assert(&insertBefore != NULL && "Must have instruction to insert before."); if (GetElementPtrInst* gep = getGlobalAddr(Op, insertBefore)) { I.setOperand(opNum, gep); // replace global operand return; // nothing more to do for this op. } Constant* CV = dyn_cast<Constant>(Op); if (CV == NULL) return; if (ConstantExpr* CE = dyn_cast<ConstantExpr>(CV)) { // load-time constant: factor it out so we optimize as best we can Instruction* computeConst = DecomposeConstantExpr(CE, insertBefore); I.setOperand(opNum, computeConst); // replace expr operand with result } else if (ConstantTypeMustBeLoaded(CV->getType())) { // load address of constant into a register, then load the constant // this is now done during instruction selection // the constant will live in the MachineConstantPool later on } else if (ConstantMayNotFitInImmedField(CV, &I)) { // put the constant into a virtual register using a cast CastInst* castI = new CastInst(CV, CV->getType(), "copyConst", &insertBefore); I.setOperand(opNum, castI); // replace operand with copy in v.reg. } } /// visitOperands - transform individual operands of all instructions: /// -- Load "large" int constants into a virtual register. What is large /// depends on the type of instruction and on the target architecture. /// -- For any constants that cannot be put in an immediate field, /// load address into virtual register first, and then load the constant. /// /// firstOp and lastOp can be used to skip leading and trailing operands. /// If lastOp is 0, it defaults to #operands or #incoming Phi values. /// inline void PreSelection::visitOperands(Instruction &I, int firstOp) { // For any instruction other than PHI, copies go just before the instr. for (unsigned i = firstOp, e = I.getNumOperands(); i != e; ++i) visitOneOperand(I, I.getOperand(i), i, I); } void PreSelection::visitPHINode(PHINode &PN) { // For a PHI, operand copies must be before the terminator of the // appropriate predecessor basic block. Remaining logic is simple // so just handle PHIs and other instructions separately. // for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) visitOneOperand(PN, PN.getIncomingValue(i), PN.getOperandNumForIncomingValue(i), *PN.getIncomingBlock(i)->getTerminator()); // do not call visitOperands! } // Common work for *all* instructions. This needs to be called explicitly // by other visit<InstructionType> functions. inline void PreSelection::visitInstruction(Instruction &I) { visitOperands(I); // Perform operand transformations } // GetElementPtr instructions: check if pointer is a global void PreSelection::visitGetElementPtrInst(GetElementPtrInst &I) { Instruction* curI = &I; // The Sparc backend doesn't handle array indexes that are not long types, so // insert a cast from whatever it is to long, if the sequential type index is // not a long already. unsigned Idx = 1; for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I); TI != E; ++TI, ++Idx) if (isa<SequentialType>(*TI) && I.getOperand(Idx)->getType() != Type::LongTy) { Value *Op = I.getOperand(Idx); if (Op->getType()->isUnsigned()) // Must sign extend! Op = new CastInst(Op, Op->getType()->getSignedVersion(), "v9", &I); if (Op->getType() != Type::LongTy) Op = new CastInst(Op, Type::LongTy, "v9", &I); I.setOperand(Idx, Op); } // Decompose multidimensional array references if (I.getNumIndices() >= 2) { // DecomposeArrayRef() replaces I and deletes it, if successful, // so remember predecessor in order to find the replacement instruction. // Also remember the basic block in case there is no predecessor. Instruction* prevI = I.getPrev(); BasicBlock* bb = I.getParent(); if (DecomposeArrayRef(&I)) // first instr. replacing I curI = cast<GetElementPtrInst>(prevI? prevI->getNext() : &bb->front()); } // Perform other transformations common to all instructions visitInstruction(*curI); } void PreSelection::visitCallInst(CallInst &I) { // Tell visitOperands to ignore the function name if this is a direct call. visitOperands(I, (/*firstOp=*/ I.getCalledFunction()? 1 : 0)); } /// createPreSelectionPass - Public entry point for the PreSelection pass /// FunctionPass* llvm::createPreSelectionPass(const TargetMachine &TM) { return new PreSelection(TM); } <commit_msg>Added support for decomposing constant expressions containing shr and shl instructions. Review of this commit would be greatly appreciated.<commit_after>//===- SparcV9PreSelection.cpp - Specialize LLVM code for SparcV9 ---------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the PreSelection pass which specializes LLVM code for // the SparcV9 instruction selector, while remaining in legal portable LLVM // form and preserving type information and type safety. This is meant to enable // dataflow optimizations on SparcV9-specific operations such as accesses to // constants, globals, and array indexing. // //===----------------------------------------------------------------------===// #include "SparcV9Internals.h" #include "SparcV9BurgISel.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Instructions.h" #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/Support/InstVisitor.h" #include "llvm/Support/GetElementPtrTypeIterator.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Transforms/Scalar.h" #include <algorithm> using namespace llvm; namespace { //===--------------------------------------------------------------------===// // PreSelection Pass - Specialize LLVM code for the SparcV9 instr. selector. // class PreSelection : public FunctionPass, public InstVisitor<PreSelection> { const TargetInstrInfo &instrInfo; public: PreSelection(const TargetMachine &T) : instrInfo(*T.getInstrInfo()) {} // runOnFunction - apply this pass to each Function bool runOnFunction(Function &F) { visit(F); return true; } const char *getPassName() const { return "SparcV9 Instr. Pre-selection"; } // These methods do the actual work of specializing code void visitInstruction(Instruction &I); // common work for every instr. void visitGetElementPtrInst(GetElementPtrInst &I); void visitCallInst(CallInst &I); void visitPHINode(PHINode &PN); void visitBasicBlock(BasicBlock &BB) { if (isa<UnreachableInst>(BB.getTerminator())) { BB.getInstList().pop_back(); const Type *RetTy = BB.getParent()->getReturnType(); Value *RetVal = RetTy == Type::VoidTy ? 0 : UndefValue::get(RetTy); new ReturnInst(RetVal, &BB); } } // Helper functions for visiting operands of every instruction // // visitOperands() works on every operand in [firstOp, lastOp-1]. // If lastOp==0, lastOp defaults to #operands or #incoming Phi values. // // visitOneOperand() does all the work for one operand. // void visitOperands(Instruction &I, int firstOp=0); void visitOneOperand(Instruction &I, Value* Op, unsigned opNum, Instruction& insertBefore); }; #if 0 // Register the pass... RegisterPass<PreSelection> X("preselect", "Specialize LLVM code for a target machine" createPreselectionPass); #endif } // end anonymous namespace //------------------------------------------------------------------------------ // Helper functions used by methods of class PreSelection //------------------------------------------------------------------------------ // getGlobalAddr(): Put address of a global into a v. register. static GetElementPtrInst* getGlobalAddr(Value* ptr, Instruction& insertBefore) { return (isa<GlobalVariable>(ptr)) ? new GetElementPtrInst(ptr, std::vector<Value*>(1, ConstantSInt::get(Type::LongTy, 0U)), "addrOfGlobal:" + ptr->getName(), &insertBefore) : NULL; } // Wrapper on Constant::classof to use in find_if inline static bool nonConstant(const Use& U) { return ! isa<Constant>(U); } static Instruction* DecomposeConstantExpr(ConstantExpr* CE, Instruction& insertBefore) { Value *getArg1, *getArg2; switch(CE->getOpcode()) { case Instruction::Cast: getArg1 = CE->getOperand(0); if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1)) getArg1 = DecomposeConstantExpr(CEarg, insertBefore); return new CastInst(getArg1, CE->getType(), "constantCast",&insertBefore); case Instruction::GetElementPtr: assert(std::find_if(CE->op_begin()+1, CE->op_end(), nonConstant) == CE->op_end() && "All indices in ConstantExpr getelementptr must be constant!"); getArg1 = CE->getOperand(0); if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1)) getArg1 = DecomposeConstantExpr(CEarg, insertBefore); else if (GetElementPtrInst* gep = getGlobalAddr(getArg1, insertBefore)) getArg1 = gep; return new GetElementPtrInst(getArg1, std::vector<Value*>(CE->op_begin()+1, CE->op_end()), "constantGEP:" + getArg1->getName(), &insertBefore); case Instruction::Select: { Value *C, *S1, *S2; C = CE->getOperand (0); if (ConstantExpr* CEarg = dyn_cast<ConstantExpr> (C)) C = DecomposeConstantExpr (CEarg, insertBefore); S1 = CE->getOperand (1); if (ConstantExpr* CEarg = dyn_cast<ConstantExpr> (S1)) S1 = DecomposeConstantExpr (CEarg, insertBefore); S2 = CE->getOperand (2); if (ConstantExpr* CEarg = dyn_cast<ConstantExpr> (S2)) S2 = DecomposeConstantExpr (CEarg, insertBefore); return new SelectInst (C, S1, S2, "constantSelect", &insertBefore); } case Instruction::Shr: { getArg1 = CE->getOperand(0); if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1)) getArg1 = DecomposeConstantExpr(CEarg, insertBefore); getArg2 = CE->getOperand(1); if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg2)) getArg2 = DecomposeConstantExpr(CEarg, insertBefore); return new ShiftInst (static_cast<Instruction::OtherOps>(CE->getOpcode()), getArg1, getArg2, "constantShr:" + getArg1->getName(), &insertBefore); } case Instruction::Shl: { getArg1 = CE->getOperand(0); if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1)) getArg1 = DecomposeConstantExpr(CEarg, insertBefore); getArg2 = CE->getOperand(1); if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg2)) getArg2 = DecomposeConstantExpr(CEarg, insertBefore); return new ShiftInst (static_cast<Instruction::OtherOps>(CE->getOpcode()), getArg1, getArg2, "constantShl:" + getArg1->getName(), &insertBefore); } default: // must be a binary operator assert(CE->getOpcode() >= Instruction::BinaryOpsBegin && CE->getOpcode() < Instruction::BinaryOpsEnd && "Unhandled opcode in ConstantExpr"); getArg1 = CE->getOperand(0); if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg1)) getArg1 = DecomposeConstantExpr(CEarg, insertBefore); getArg2 = CE->getOperand(1); if (ConstantExpr* CEarg = dyn_cast<ConstantExpr>(getArg2)) getArg2 = DecomposeConstantExpr(CEarg, insertBefore); return BinaryOperator::create((Instruction::BinaryOps) CE->getOpcode(), getArg1, getArg2, "constantBinaryOp", &insertBefore); } } static inline bool ConstantTypeMustBeLoaded(const Type* CVT) { assert(CVT->isPrimitiveType() || isa<PointerType>(CVT)); return !(CVT->isIntegral() || isa<PointerType>(CVT)); } //------------------------------------------------------------------------------ // Instruction visitor methods to perform instruction-specific operations //------------------------------------------------------------------------------ inline void PreSelection::visitOneOperand(Instruction &I, Value* Op, unsigned opNum, Instruction& insertBefore) { assert(&insertBefore != NULL && "Must have instruction to insert before."); if (GetElementPtrInst* gep = getGlobalAddr(Op, insertBefore)) { I.setOperand(opNum, gep); // replace global operand return; // nothing more to do for this op. } Constant* CV = dyn_cast<Constant>(Op); if (CV == NULL) return; if (ConstantExpr* CE = dyn_cast<ConstantExpr>(CV)) { // load-time constant: factor it out so we optimize as best we can Instruction* computeConst = DecomposeConstantExpr(CE, insertBefore); I.setOperand(opNum, computeConst); // replace expr operand with result } else if (ConstantTypeMustBeLoaded(CV->getType())) { // load address of constant into a register, then load the constant // this is now done during instruction selection // the constant will live in the MachineConstantPool later on } else if (ConstantMayNotFitInImmedField(CV, &I)) { // put the constant into a virtual register using a cast CastInst* castI = new CastInst(CV, CV->getType(), "copyConst", &insertBefore); I.setOperand(opNum, castI); // replace operand with copy in v.reg. } } /// visitOperands - transform individual operands of all instructions: /// -- Load "large" int constants into a virtual register. What is large /// depends on the type of instruction and on the target architecture. /// -- For any constants that cannot be put in an immediate field, /// load address into virtual register first, and then load the constant. /// /// firstOp and lastOp can be used to skip leading and trailing operands. /// If lastOp is 0, it defaults to #operands or #incoming Phi values. /// inline void PreSelection::visitOperands(Instruction &I, int firstOp) { // For any instruction other than PHI, copies go just before the instr. for (unsigned i = firstOp, e = I.getNumOperands(); i != e; ++i) visitOneOperand(I, I.getOperand(i), i, I); } void PreSelection::visitPHINode(PHINode &PN) { // For a PHI, operand copies must be before the terminator of the // appropriate predecessor basic block. Remaining logic is simple // so just handle PHIs and other instructions separately. // for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) visitOneOperand(PN, PN.getIncomingValue(i), PN.getOperandNumForIncomingValue(i), *PN.getIncomingBlock(i)->getTerminator()); // do not call visitOperands! } // Common work for *all* instructions. This needs to be called explicitly // by other visit<InstructionType> functions. inline void PreSelection::visitInstruction(Instruction &I) { visitOperands(I); // Perform operand transformations } // GetElementPtr instructions: check if pointer is a global void PreSelection::visitGetElementPtrInst(GetElementPtrInst &I) { Instruction* curI = &I; // The Sparc backend doesn't handle array indexes that are not long types, so // insert a cast from whatever it is to long, if the sequential type index is // not a long already. unsigned Idx = 1; for (gep_type_iterator TI = gep_type_begin(I), E = gep_type_end(I); TI != E; ++TI, ++Idx) if (isa<SequentialType>(*TI) && I.getOperand(Idx)->getType() != Type::LongTy) { Value *Op = I.getOperand(Idx); if (Op->getType()->isUnsigned()) // Must sign extend! Op = new CastInst(Op, Op->getType()->getSignedVersion(), "v9", &I); if (Op->getType() != Type::LongTy) Op = new CastInst(Op, Type::LongTy, "v9", &I); I.setOperand(Idx, Op); } // Decompose multidimensional array references if (I.getNumIndices() >= 2) { // DecomposeArrayRef() replaces I and deletes it, if successful, // so remember predecessor in order to find the replacement instruction. // Also remember the basic block in case there is no predecessor. Instruction* prevI = I.getPrev(); BasicBlock* bb = I.getParent(); if (DecomposeArrayRef(&I)) // first instr. replacing I curI = cast<GetElementPtrInst>(prevI? prevI->getNext() : &bb->front()); } // Perform other transformations common to all instructions visitInstruction(*curI); } void PreSelection::visitCallInst(CallInst &I) { // Tell visitOperands to ignore the function name if this is a direct call. visitOperands(I, (/*firstOp=*/ I.getCalledFunction()? 1 : 0)); } /// createPreSelectionPass - Public entry point for the PreSelection pass /// FunctionPass* llvm::createPreSelectionPass(const TargetMachine &TM) { return new PreSelection(TM); } <|endoftext|>
<commit_before>/* Copyright 2022 The TensorFlow Authors. 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. ==============================================================================*/ /// This files contains a pipeline which converts HLO operations to GPU kernels /// written in a combination of LLVM and NVVM dialects. #include "mlir-hlo/Dialect/gml_st/transforms/passes.h" #include "mlir-hlo/Dialect/mhlo/transforms/passes.h" #include "mlir-hlo/Transforms/gpu_passes.h" #include "mlir-hlo/Transforms/passes.h" #include "mlir/Conversion/AffineToStandard/AffineToStandard.h" #include "mlir/Conversion/SCFToControlFlow/SCFToControlFlow.h" #include "mlir/Conversion/ShapeToStandard/ShapeToStandard.h" #include "mlir/Dialect/Arith/Transforms/Passes.h" #include "mlir/Dialect/Bufferization/Transforms/Passes.h" #include "mlir/Dialect/Func/IR/FuncOps.h" #include "mlir/Dialect/GPU/Transforms/Passes.h" #include "mlir/Dialect/Linalg/Passes.h" #include "mlir/Dialect/SCF/Transforms/Passes.h" #include "mlir/Pass/Pass.h" #include "mlir/Pass/PassManager.h" #include "mlir/Transforms/Passes.h" using namespace mlir; using ::mlir::func::FuncOp; using ::mlir::gpu::GPUModuleOp; // TODO(b/233761238): We only want to have this pipeline temporarily, as it is // not yet clear how exactly it will look like. The goal is to merge this with // the unified kernel generator + autofusion + XLA Next pipeline once we have // it, and once this code stabilizes. void mlir::createHloToGpuPipeline(OpPassManager& pm, const HloToGpuPipelineOptions& options) { pm.addNestedPass<FuncOp>(hlo::createUnbufferizePass()); // HLO -> Linalg pm.addNestedPass<FuncOp>(mhlo::createChloLegalizeToHloPass()); pm.addPass(createCanonicalizerPass()); // Clean up shape.assuming ops. pm.addNestedPass<FuncOp>(mhlo::createLegalizeHloToLinalgPass()); // Perform tiling either for softmax or for element-wise. if (options.experimentalSoftmax) { // Simplify unit dimension. pm.addPass(mlir::createLinalgFoldUnitExtentDimsPass()); // Tile parallel dimensions of the softmax-like patterns and distribute them // across warps. Warps remain independant of each other. pm.addNestedPass<FuncOp>(gml_st::createTilingSoftmaxPass( /*distribute=*/true, options.blockTileDim, "block")); pm.addNestedPass<FuncOp>(gml_st::createTilingSoftmaxPass( /*distribute=*/true, options.warpTileDim, "warp")); // GPU-specific tiling for ops on the warp level. pm.addNestedPass<FuncOp>(gml_st::createTilingGPUWarpPass()); pm.addNestedPass<FuncOp>(createScalarizationPass()); // Clean unit dims. pm.addPass(mlir::createLinalgFoldUnitExtentDimsPass()); // GPU-specific tiling for cwise ops on the warp level. // TODO(frgossen): This should be merged with the above tiling-reduction // pass. pm.addNestedPass<FuncOp>(gml_st::createTilingGPUWarpPass()); pm.addNestedPass<FuncOp>(createScalarizationPass()); pm.addNestedPass<FuncOp>(gml_st::createVectorizeGmlStLoopsPass( /*vectorizeGmlStOps=*/true, /*distributionLabels=*/{"warp", "thread"})); } else { // TODO(b/244313563): This is a workaround to avoid temporary allocs within // threads. It works for as long as all of our operations are cwise. // Vectorize the inner loops instead. // TODO(frgossen): We should not have to skip this pass for softmax. pm.addNestedPass<FuncOp>(createLinalgElementwiseOpFusionPass()); // Tiling pm.addNestedPass<FuncOp>(gml_st::createTilingCwisePass( /*distribute=*/true, options.blockTileDim, "block")); pm.addNestedPass<FuncOp>(gml_st::createTilingCwisePass( /*distribute=*/true, options.warpTileDim, "warp")); pm.addNestedPass<FuncOp>(gml_st::createTilingCwisePass( /*distribute=*/true, options.threadTileDim, "thread")); pm.addNestedPass<FuncOp>(createScalarizationPass()); } pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); // Bufferization-related passes. pm.addNestedPass<FuncOp>(bufferization::createEmptyTensorToAllocTensorPass()); pm.addPass(hlo::createOneShotBufferizePass()); // We do not deallocate buffers, since grid-level buffers get converted into // functions arguments, while block- (and lower-)level buffers become shared // memory. None of which have to be deallocated. pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); // Canonicalize away memory copies into itself pm.addPass(createCanonicalizerPass()); // Linalg + GmlSt -> GPU pm.addNestedPass<FuncOp>(createGmlStToGpuPass()); pm.addNestedPass<FuncOp>(gml_st::createGmlStToScfPass()); pm.addNestedPass<FuncOp>(arith::createArithExpandOpsPass()); pm.addNestedPass<FuncOp>(createConvertLinalgToLoopsPass()); pm.addNestedPass<FuncOp>(createCanonicalizerPass()); pm.addPass(createGpuLauchSinkIndexComputationsPass()); constexpr llvm::StringRef kGpuDataLayoutSpec = "#dlti.dl_spec<#dlti.dl_entry<index,32:i32>>"; pm.addPass(createGpuKernelOutliningPass(kGpuDataLayoutSpec)); pm.addNestedPass<GPUModuleOp>(createForLoopSpecializationPass()); pm.addNestedPass<GPUModuleOp>(hlo::createUnrollLoopsPass()); pm.addNestedPass<GPUModuleOp>(createLowerAffinePass()); pm.addNestedPass<GPUModuleOp>(createCanonicalizerPass()); pm.addNestedPass<GPUModuleOp>(createConvertSCFToCFPass()); // GPU -> low-level IR #if TENSORFLOW_USE_ROCM pm.addNestedPass<GPUModuleOp>(createGpuKernelToRocdlPass()); #else pm.addNestedPass<GPUModuleOp>(createGpuKernelToNvvmPass()); #endif pm.addPass(createPropagateStaticShapesToKernelPass()); pm.addNestedPass<GPUModuleOp>(createCSEPass()); // Some instructions crash ptxas down the line if they have debug info // attached. pm.addNestedPass<GPUModuleOp>(createStripDebugInfoPass()); pm.addNestedPass<FuncOp>(hlo::createAllocToArgPass()); } <commit_msg>[GML][Softmax] Clean up warp-level tilng in the GPU pipeline<commit_after>/* Copyright 2022 The TensorFlow Authors. 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. ==============================================================================*/ /// This files contains a pipeline which converts HLO operations to GPU kernels /// written in a combination of LLVM and NVVM dialects. #include "mlir-hlo/Dialect/gml_st/transforms/passes.h" #include "mlir-hlo/Dialect/mhlo/transforms/passes.h" #include "mlir-hlo/Transforms/gpu_passes.h" #include "mlir-hlo/Transforms/passes.h" #include "mlir/Conversion/AffineToStandard/AffineToStandard.h" #include "mlir/Conversion/SCFToControlFlow/SCFToControlFlow.h" #include "mlir/Conversion/ShapeToStandard/ShapeToStandard.h" #include "mlir/Dialect/Arith/Transforms/Passes.h" #include "mlir/Dialect/Bufferization/Transforms/Passes.h" #include "mlir/Dialect/Func/IR/FuncOps.h" #include "mlir/Dialect/GPU/Transforms/Passes.h" #include "mlir/Dialect/Linalg/Passes.h" #include "mlir/Dialect/SCF/Transforms/Passes.h" #include "mlir/Pass/Pass.h" #include "mlir/Pass/PassManager.h" #include "mlir/Transforms/Passes.h" using namespace mlir; using ::mlir::func::FuncOp; using ::mlir::gpu::GPUModuleOp; // TODO(b/233761238): We only want to have this pipeline temporarily, as it is // not yet clear how exactly it will look like. The goal is to merge this with // the unified kernel generator + autofusion + XLA Next pipeline once we have // it, and once this code stabilizes. void mlir::createHloToGpuPipeline(OpPassManager& pm, const HloToGpuPipelineOptions& options) { pm.addNestedPass<FuncOp>(hlo::createUnbufferizePass()); // HLO -> Linalg pm.addNestedPass<FuncOp>(mhlo::createChloLegalizeToHloPass()); pm.addPass(createCanonicalizerPass()); // Clean up shape.assuming ops. pm.addNestedPass<FuncOp>(mhlo::createLegalizeHloToLinalgPass()); // Perform tiling either for softmax or for element-wise. if (options.experimentalSoftmax) { // Simplify unit dimension. pm.addPass(mlir::createLinalgFoldUnitExtentDimsPass()); // Tile parallel dimensions of the softmax-like patterns and distribute them // across warps. Warps remain independant of each other. pm.addNestedPass<FuncOp>(gml_st::createTilingSoftmaxPass( /*distribute=*/true, options.blockTileDim, "block")); pm.addNestedPass<FuncOp>(gml_st::createTilingSoftmaxPass( /*distribute=*/true, options.warpTileDim, "warp")); // GPU-specific tiling for ops on the warp level. pm.addNestedPass<FuncOp>(gml_st::createTilingGPUWarpPass()); pm.addNestedPass<FuncOp>(createScalarizationPass()); pm.addNestedPass<FuncOp>(gml_st::createVectorizeGmlStLoopsPass( /*vectorizeGmlStOps=*/true, /*distributionLabels=*/{"warp", "thread"})); } else { // TODO(b/244313563): This is a workaround to avoid temporary allocs within // threads. It works for as long as all of our operations are cwise. // Vectorize the inner loops instead. // TODO(frgossen): We should not have to skip this pass for softmax. pm.addNestedPass<FuncOp>(createLinalgElementwiseOpFusionPass()); // Tiling pm.addNestedPass<FuncOp>(gml_st::createTilingCwisePass( /*distribute=*/true, options.blockTileDim, "block")); pm.addNestedPass<FuncOp>(gml_st::createTilingCwisePass( /*distribute=*/true, options.warpTileDim, "warp")); pm.addNestedPass<FuncOp>(gml_st::createTilingCwisePass( /*distribute=*/true, options.threadTileDim, "thread")); pm.addNestedPass<FuncOp>(createScalarizationPass()); } pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); // Bufferization-related passes. pm.addNestedPass<FuncOp>(bufferization::createEmptyTensorToAllocTensorPass()); pm.addPass(hlo::createOneShotBufferizePass()); // We do not deallocate buffers, since grid-level buffers get converted into // functions arguments, while block- (and lower-)level buffers become shared // memory. None of which have to be deallocated. pm.addPass(createCanonicalizerPass()); pm.addPass(createCSEPass()); // Canonicalize away memory copies into itself pm.addPass(createCanonicalizerPass()); // Linalg + GmlSt -> GPU pm.addNestedPass<FuncOp>(createGmlStToGpuPass()); pm.addNestedPass<FuncOp>(gml_st::createGmlStToScfPass()); pm.addNestedPass<FuncOp>(arith::createArithExpandOpsPass()); pm.addNestedPass<FuncOp>(createConvertLinalgToLoopsPass()); pm.addNestedPass<FuncOp>(createCanonicalizerPass()); pm.addPass(createGpuLauchSinkIndexComputationsPass()); constexpr llvm::StringRef kGpuDataLayoutSpec = "#dlti.dl_spec<#dlti.dl_entry<index,32:i32>>"; pm.addPass(createGpuKernelOutliningPass(kGpuDataLayoutSpec)); pm.addNestedPass<GPUModuleOp>(createForLoopSpecializationPass()); pm.addNestedPass<GPUModuleOp>(hlo::createUnrollLoopsPass()); pm.addNestedPass<GPUModuleOp>(createLowerAffinePass()); pm.addNestedPass<GPUModuleOp>(createCanonicalizerPass()); pm.addNestedPass<GPUModuleOp>(createConvertSCFToCFPass()); // GPU -> low-level IR #if TENSORFLOW_USE_ROCM pm.addNestedPass<GPUModuleOp>(createGpuKernelToRocdlPass()); #else pm.addNestedPass<GPUModuleOp>(createGpuKernelToNvvmPass()); #endif pm.addPass(createPropagateStaticShapesToKernelPass()); pm.addNestedPass<GPUModuleOp>(createCSEPass()); // Some instructions crash ptxas down the line if they have debug info // attached. pm.addNestedPass<GPUModuleOp>(createStripDebugInfoPass()); pm.addNestedPass<FuncOp>(hlo::createAllocToArgPass()); } <|endoftext|>
<commit_before>/* * qlibxmlnodemodel - A QAbstractXmlNodeModel that uses libxml2 library * Copyright (C) 2012 Alexey Torkhov * Copyright (C) 2011 Jonas Gehring * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * * Based on qhtmlnodemodel by Jonas Gehring and QT examples * * 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 HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <QDebug> #include <libxml/HTMLparser.h> #include <libxml/tree.h> #include "qlibxmlnodemodel.h" // Internal private data class QLibXmlNodeModelPrivate { public: QLibXmlNodeModel *model; QUrl uri; xmlDoc *doc; xmlNode *root_element; QLibXmlNodeModelPrivate(QLibXmlNodeModel *model) : model(model), doc(NULL), root_element(NULL) { } // Parses the given source tree void parse(const QByteArray &source) { doc = htmlReadMemory(source.data(), source.size(), uri.toString().toUtf8(), "utf-8", 0); if (doc == NULL) { qDebug() << "could not parse source" << source; } root_element = xmlDocGetRootElement(doc); } // Converts a model index to a HTML node xmlNode *toNode(const QXmlNodeModelIndex &index) const { return (xmlNode *)index.internalPointer(); } // Converts a HTML node to a model index QXmlNodeModelIndex toNodeIndex(xmlNode *node) const { return model->createIndex((void *)node); } QXmlNodeModelIndex toNodeIndex(xmlDoc *node) const { return model->createIndex((void *)node); } QXmlNodeModelIndex toNodeIndex(xmlAttr *node) const { return model->createIndex((void *)node); } }; void libXmlErrorFunc(void *ctx, const char *msg, ...) { char buf[1024]; va_list args; va_start(args, msg); vsnprintf(buf, 1024, msg, args); va_end(args); qDebug() << buf; return; } /*! * Constructor passes \a pool to the base class */ QLibXmlNodeModel::QLibXmlNodeModel(const QXmlNamePool& namePool, const QByteArray &source, const QUrl &uri) : QSimpleXmlNodeModel(namePool), d(new QLibXmlNodeModelPrivate(this)) { xmlSetGenericErrorFunc(NULL, libXmlErrorFunc); d->uri = uri; d->parse(source); } /*! * Destructor */ QLibXmlNodeModel::~QLibXmlNodeModel() { delete d; } /*! * This function is called by the QtXmlPatterns query engine when it * wants to move to the next node in the model. It moves along an \a * axis, \e from the node specified by \a nodeIndex. */ QXmlNodeModelIndex QLibXmlNodeModel::nextFromSimpleAxis(SimpleAxis axis, const QXmlNodeModelIndex &nodeIndex) const { xmlNode *node = d->toNode(nodeIndex); qDebug() << "nextFromSimpleAxis()" << node << axis; if (!node) { qDebug() << "Invalid node"; return QXmlNodeModelIndex(); } switch (axis) { case Parent: qDebug() << "Parent " << node->parent; if (!node->parent) { return QXmlNodeModelIndex(); } return d->toNodeIndex(node->parent); case FirstChild: qDebug() << "Child " << node->children; if (!node->children) { return QXmlNodeModelIndex(); } return d->toNodeIndex(node->children); case PreviousSibling: qDebug() << "Prev " << node->prev; if (!node->prev) { return QXmlNodeModelIndex(); } return d->toNodeIndex(node->prev); case NextSibling: qDebug() << "Next " << node->next; if (!node->next) { return QXmlNodeModelIndex(); } return d->toNodeIndex(node->next); } Q_ASSERT_X(false, Q_FUNC_INFO, "Invalid axis!"); return QXmlNodeModelIndex(); } /*! * Returns the document URI of \a n. The document URI identifies the * resource which is the document. For example, the document could be a * regular file, e.g., \c{file:/}, or it could be the \c{http://} URL of * the location of a file. The document URI is used for resolving URIs * and to simply know where the document is. */ QUrl QLibXmlNodeModel::documentUri(const QXmlNodeModelIndex &node) const { Q_UNUSED(node); return d->uri; } /*! * Returns a value indicating the kind of node identified by \a ni. * The caller guarantees that \a ni is not null and that it identifies * a node in this node model. This function maps to the \c * dm:node-kind() accessor. */ QXmlNodeModelIndex::NodeKind QLibXmlNodeModel::kind(const QXmlNodeModelIndex &nodeIndex) const { xmlNode *node = d->toNode(nodeIndex); qDebug() << "kind()" << node; if (!node) { qDebug() << "Invalid node"; return QXmlNodeModelIndex::Element; } qDebug() << "Node type" << node->type; switch (node->type) { case XML_ELEMENT_NODE: return QXmlNodeModelIndex::Element; case XML_ATTRIBUTE_NODE: return QXmlNodeModelIndex::Attribute; case XML_TEXT_NODE: return QXmlNodeModelIndex::Text; case XML_COMMENT_NODE: return QXmlNodeModelIndex::Comment; case XML_DOCUMENT_NODE: case XML_HTML_DOCUMENT_NODE: return QXmlNodeModelIndex::Document; case XML_NAMESPACE_DECL: return QXmlNodeModelIndex::Namespace; case XML_PI_NODE: return QXmlNodeModelIndex::ProcessingInstruction; } qDebug() << "Invalid node type" << node->type; return QXmlNodeModelIndex::Element; } /*! * This function returns the relative document order for the * nodes indexed by \a ni1 and \a ni2. It is used for the \c Is * operator and for sorting nodes in document order. */ QXmlNodeModelIndex::DocumentOrder QLibXmlNodeModel::compareOrder(const QXmlNodeModelIndex &nodeIndex1, const QXmlNodeModelIndex &nodeIndex2) const { xmlNode *node1 = d->toNode(nodeIndex1); xmlNode *node2 = d->toNode(nodeIndex2); qDebug() << "compareOrder()" << node1 << node2; return QXmlNodeModelIndex::Precedes; } /*! * Returns the name of \a node. The caller guarantees that \a node is * not null and that it is contained in this node model. */ QXmlName QLibXmlNodeModel::name(const QXmlNodeModelIndex &nodeIndex) const { xmlNode *node = d->toNode(nodeIndex); qDebug() << "name()" << node; if (!node) { qDebug() << "Invalid node"; return QXmlName(namePool(), QString()); } qDebug() << "Node name" << (const char *)node->name; return QXmlName(namePool(), QString((const char *)node->name)); } /*! * Returns the root node of the tree that contains the node whose index * is \a n. The caller guarantees that \a n is not \c null and that it * identifies a node in this node model. */ QXmlNodeModelIndex QLibXmlNodeModel::root(const QXmlNodeModelIndex &nodeIndex) const { Q_UNUSED(nodeIndex); return d->toNodeIndex(d->doc); } /*! * Returns the typed value for \a node, which must be either an * attribute or an element. The QVariant returned represents the atomic * value of an attribute or the atomic value contained in an element. * * If the QVariant is returned as a default constructed variant, * it means that \a node has no typed value. */ QVariant QLibXmlNodeModel::typedValue(const QXmlNodeModelIndex &nodeIndex) const { xmlNode *node = d->toNode(nodeIndex); qDebug() << "typedValue()" << node; if (!node) { qDebug() << "Invalid node"; return QVariant(); } if (node->type == XML_ATTRIBUTE_NODE) { xmlChar *buf = xmlNodeListGetString(node->doc, node->children, 1); QString str = (const char *)buf; xmlFree(buf); qDebug() << "Attribute typed value" << str; return str; } qDebug() << "Node typed value" << (const char *)node->name; return QString((const char *)node->name); } /*! * Returns the attributes of \a element. The caller guarantees * that \a element is an element in this node model. */ QVector<QXmlNodeModelIndex> QLibXmlNodeModel::attributes(const QXmlNodeModelIndex &nodeIndex) const { xmlNode *node = d->toNode(nodeIndex); qDebug() << "attributes()" << node; QVector<QXmlNodeModelIndex> result; for (xmlAttr *cur = node->properties; cur != NULL; cur = cur->next) { result += d->toNodeIndex(cur); } return result; } /*! * Returns the string value for node \a n. * * The caller guarantees that \a n is not \c null and that it belong to * this QAbstractXmlNodeModel instance. * * This function maps to the \c dm:string-value() accessor, which the * specification completely specifies. Here's a summary: * * \list * \o For processing instructions, the string value is the data * section(excluding any whitespace appearing between the name and the * data). * \o For text nodes, the string value equals the text node. * \o For comments, the content of the comment * \o For elements, the concatenation of all text nodes that are * descendants. Note, this is not only the children, but the * childrens' childrens' text nodes, and so forth. * \o For document nodes, the concatenation of all text nodes in the * document. * \endlist */ QString QLibXmlNodeModel::stringValue (const QXmlNodeModelIndex &nodeIndex) const { xmlNode *node = d->toNode(nodeIndex); qDebug() << "stringValue()" << node; if (node->type == XML_TEXT_NODE) { xmlChar *buf = xmlNodeGetContent(node); QString str((const char *)buf); xmlFree(buf); return str; } return QSimpleXmlNodeModel::stringValue(nodeIndex); } <commit_msg>Various fixes.<commit_after>/* * qlibxmlnodemodel - A QAbstractXmlNodeModel that uses libxml2 library * Copyright (C) 2012 Alexey Torkhov * Copyright (C) 2011 Jonas Gehring * Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * * Based on qhtmlnodemodel by Jonas Gehring and QT examples * * 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 HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <QDebug> #include <libxml/HTMLparser.h> #include <libxml/tree.h> #include "qlibxmlnodemodel.h" // Internal private data class QLibXmlNodeModelPrivate { public: QLibXmlNodeModel *model; QUrl uri; xmlDoc *doc; QLibXmlNodeModelPrivate(QLibXmlNodeModel *model) : model(model), doc(NULL) { } ~QLibXmlNodeModelPrivate() { xmlFreeDoc(doc); doc = NULL; } // Parses the given source tree void parse(const QByteArray &source) { doc = htmlReadMemory(source.data(), source.size(), uri.toString().toUtf8(), "utf-8", 0); if (doc == NULL) { qDebug() << "could not parse source" << source; } } // Converts a model index to a HTML node xmlNode *toNode(const QXmlNodeModelIndex &index) const { return (xmlNode *)index.internalPointer(); } // Converts a HTML node to a model index QXmlNodeModelIndex toNodeIndex(xmlNode *node) const { return model->createIndex((void *)node); } QXmlNodeModelIndex toNodeIndex(xmlDoc *node) const { return model->createIndex((void *)node); } QXmlNodeModelIndex toNodeIndex(xmlAttr *node) const { return model->createIndex((void *)node); } }; void libXmlErrorFunc(void *ctx, const char *msg, ...) { char buf[1024]; va_list args; va_start(args, msg); vsnprintf(buf, 1024, msg, args); va_end(args); qDebug() << buf; return; } /*! * Constructor passes \a pool to the base class */ QLibXmlNodeModel::QLibXmlNodeModel(const QXmlNamePool& namePool, const QByteArray &source, const QUrl &uri) : QSimpleXmlNodeModel(namePool), d(new QLibXmlNodeModelPrivate(this)) { xmlSetGenericErrorFunc(NULL, libXmlErrorFunc); d->uri = uri; d->parse(source); } /*! * Destructor */ QLibXmlNodeModel::~QLibXmlNodeModel() { delete d; } /*! * This function is called by the QtXmlPatterns query engine when it * wants to move to the next node in the model. It moves along an \a * axis, \e from the node specified by \a nodeIndex. */ QXmlNodeModelIndex QLibXmlNodeModel::nextFromSimpleAxis(SimpleAxis axis, const QXmlNodeModelIndex &nodeIndex) const { xmlNode *node = d->toNode(nodeIndex); qDebug() << "nextFromSimpleAxis()" << node << axis; if (!node) { qDebug() << "Invalid node"; return QXmlNodeModelIndex(); } switch (axis) { case Parent: qDebug() << "Parent " << node->parent; if (!node->parent) { return QXmlNodeModelIndex(); } return d->toNodeIndex(node->parent); case FirstChild: qDebug() << "Child " << node->children; if (!node->children) { return QXmlNodeModelIndex(); } return d->toNodeIndex(node->children); case PreviousSibling: qDebug() << "Prev " << node->prev; if (!node->prev) { return QXmlNodeModelIndex(); } return d->toNodeIndex(node->prev); case NextSibling: qDebug() << "Next " << node->next; if (!node->next) { return QXmlNodeModelIndex(); } return d->toNodeIndex(node->next); } Q_ASSERT_X(false, Q_FUNC_INFO, "Invalid axis!"); return QXmlNodeModelIndex(); } /*! * Returns the document URI of \a n. The document URI identifies the * resource which is the document. For example, the document could be a * regular file, e.g., \c{file:/}, or it could be the \c{http://} URL of * the location of a file. The document URI is used for resolving URIs * and to simply know where the document is. */ QUrl QLibXmlNodeModel::documentUri(const QXmlNodeModelIndex &node) const { Q_UNUSED(node); return d->uri; } /*! * Returns a value indicating the kind of node identified by \a ni. * The caller guarantees that \a ni is not null and that it identifies * a node in this node model. This function maps to the \c * dm:node-kind() accessor. */ QXmlNodeModelIndex::NodeKind QLibXmlNodeModel::kind(const QXmlNodeModelIndex &nodeIndex) const { xmlNode *node = d->toNode(nodeIndex); qDebug() << "kind()" << node; if (!node) { qDebug() << "Invalid node"; return QXmlNodeModelIndex::Element; } qDebug() << "Node type" << node->type; switch (node->type) { case XML_ELEMENT_NODE: return QXmlNodeModelIndex::Element; case XML_ATTRIBUTE_NODE: return QXmlNodeModelIndex::Attribute; case XML_TEXT_NODE: case XML_CDATA_SECTION_NODE: return QXmlNodeModelIndex::Text; case XML_COMMENT_NODE: return QXmlNodeModelIndex::Comment; case XML_DOCUMENT_NODE: case XML_HTML_DOCUMENT_NODE: return QXmlNodeModelIndex::Document; case XML_NAMESPACE_DECL: return QXmlNodeModelIndex::Namespace; case XML_PI_NODE: return QXmlNodeModelIndex::ProcessingInstruction; } qDebug() << "Invalid node type" << node->type; return QXmlNodeModelIndex::Element; } /*! * This function returns the relative document order for the * nodes indexed by \a ni1 and \a ni2. It is used for the \c Is * operator and for sorting nodes in document order. */ QXmlNodeModelIndex::DocumentOrder QLibXmlNodeModel::compareOrder(const QXmlNodeModelIndex &nodeIndex1, const QXmlNodeModelIndex &nodeIndex2) const { xmlNode *node1 = d->toNode(nodeIndex1); xmlNode *node2 = d->toNode(nodeIndex2); qDebug() << "compareOrder()" << node1 << node2; return QXmlNodeModelIndex::Precedes; } /*! * Returns the name of \a node. The caller guarantees that \a node is * not null and that it is contained in this node model. */ QXmlName QLibXmlNodeModel::name(const QXmlNodeModelIndex &nodeIndex) const { xmlNode *node = d->toNode(nodeIndex); qDebug() << "name()" << node; if (!node) { qDebug() << "Invalid node"; return QXmlName(namePool(), QString()); } qDebug() << "Node name" << (const char *)node->name; return QXmlName(namePool(), QString((const char *)node->name)); } /*! * Returns the root node of the tree that contains the node whose index * is \a n. The caller guarantees that \a n is not \c null and that it * identifies a node in this node model. */ QXmlNodeModelIndex QLibXmlNodeModel::root(const QXmlNodeModelIndex &nodeIndex) const { Q_UNUSED(nodeIndex); return d->toNodeIndex(d->doc); } /*! * Returns the typed value for \a node, which must be either an * attribute or an element. The QVariant returned represents the atomic * value of an attribute or the atomic value contained in an element. * * If the QVariant is returned as a default constructed variant, * it means that \a node has no typed value. */ QVariant QLibXmlNodeModel::typedValue(const QXmlNodeModelIndex &nodeIndex) const { xmlNode *node = d->toNode(nodeIndex); qDebug() << "typedValue()" << node; if (!node) { qDebug() << "Invalid node"; return QVariant(); } if (node->type == XML_ATTRIBUTE_NODE) { xmlChar *buf = xmlNodeListGetString(node->doc, node->children, 1); QString str = (const char *)buf; xmlFree(buf); qDebug() << "Attribute typed value" << str; return str; } qDebug() << "Node typed value" << (const char *)node->name; return QString((const char *)node->name); } /*! * Returns the attributes of \a element. The caller guarantees * that \a element is an element in this node model. */ QVector<QXmlNodeModelIndex> QLibXmlNodeModel::attributes(const QXmlNodeModelIndex &nodeIndex) const { xmlNode *node = d->toNode(nodeIndex); qDebug() << "attributes()" << node; QVector<QXmlNodeModelIndex> result; for (xmlAttr *cur = node->properties; cur != NULL; cur = cur->next) { result += d->toNodeIndex(cur); } return result; } /*! * Returns the string value for node \a n. * * The caller guarantees that \a n is not \c null and that it belong to * this QAbstractXmlNodeModel instance. * * This function maps to the \c dm:string-value() accessor, which the * specification completely specifies. Here's a summary: * * \list * \o For processing instructions, the string value is the data * section(excluding any whitespace appearing between the name and the * data). * \o For text nodes, the string value equals the text node. * \o For comments, the content of the comment * \o For elements, the concatenation of all text nodes that are * descendants. Note, this is not only the children, but the * childrens' childrens' text nodes, and so forth. * \o For document nodes, the concatenation of all text nodes in the * document. * \endlist */ QString QLibXmlNodeModel::stringValue (const QXmlNodeModelIndex &nodeIndex) const { xmlNode *node = d->toNode(nodeIndex); qDebug() << "stringValue()" << node; if (node->type == XML_TEXT_NODE || node->type == XML_CDATA_SECTION_NODE || node->type == XML_COMMENT_NODE) { xmlChar *buf = xmlNodeGetContent(node); QString str((const char *)buf); xmlFree(buf); return str; } return QSimpleXmlNodeModel::stringValue(nodeIndex); } <|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 "chrome/browser/enhanced_bookmarks/android/enhanced_bookmarks_bridge.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/prefs/pref_service.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" #include "chrome/browser/enhanced_bookmarks/android/bookmark_image_service_android.h" #include "chrome/browser/enhanced_bookmarks/android/bookmark_image_service_factory.h" #include "chrome/browser/enhanced_bookmarks/chrome_bookmark_server_cluster_service.h" #include "chrome/browser/enhanced_bookmarks/chrome_bookmark_server_cluster_service_factory.h" #include "chrome/browser/enhanced_bookmarks/enhanced_bookmark_model_factory.h" #include "chrome/browser/profiles/profile_android.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/pref_names.h" #include "components/bookmarks/browser/bookmark_model.h" #include "components/bookmarks/browser/bookmark_utils.h" #include "components/bookmarks/common/android/bookmark_id.h" #include "components/bookmarks/common/android/bookmark_type.h" #include "components/enhanced_bookmarks/enhanced_bookmark_model.h" #include "components/enhanced_bookmarks/image_record.h" #include "components/signin/core/browser/signin_manager.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/web_contents.h" #include "jni/EnhancedBookmarksBridge_jni.h" #include "ui/gfx/android/java_bitmap.h" #include "ui/gfx/image/image.h" using base::android::AttachCurrentThread; using base::android::ScopedJavaGlobalRef; using bookmarks::android::JavaBookmarkIdCreateBookmarkId; using bookmarks::android::JavaBookmarkIdGetId; using bookmarks::android::JavaBookmarkIdGetType; using bookmarks::BookmarkNode; using bookmarks::BookmarkType; using content::WebContents; using content::BrowserThread; using enhanced_bookmarks::ImageRecord; namespace { void Callback(ScopedJavaGlobalRef<jobject>* j_callback, const ImageRecord& image_record) { JNIEnv* env = base::android::AttachCurrentThread(); scoped_ptr<ScopedJavaGlobalRef<jobject> > j_callback_ptr(j_callback); ScopedJavaLocalRef<jstring> j_url = base::android::ConvertUTF8ToJavaString(env, image_record.url.spec()); SkBitmap bitmap = image_record.image.AsBitmap(); ScopedJavaLocalRef<jobject> j_bitmap; if (!bitmap.isNull()) { j_bitmap = gfx::ConvertToJavaBitmap(&bitmap); } enhanced_bookmarks::android::Java_SalientImageCallback_onSalientImageReady( env, j_callback_ptr->obj(), j_bitmap.Release(), j_url.Release()); } } // namespace namespace enhanced_bookmarks { namespace android { EnhancedBookmarksBridge::EnhancedBookmarksBridge(JNIEnv* env, jobject obj, Profile* profile) : weak_java_ref_(env, obj) { profile_ = profile; enhanced_bookmark_model_ = EnhancedBookmarkModelFactory::GetForBrowserContext(profile_); enhanced_bookmark_model_->SetVersionSuffix(chrome::VersionInfo().OSType()); cluster_service_ = ChromeBookmarkServerClusterServiceFactory::GetForBrowserContext(profile_); cluster_service_->AddObserver(this); bookmark_image_service_ = static_cast<BookmarkImageServiceAndroid*>( BookmarkImageServiceFactory::GetForBrowserContext(profile_)); search_service_.reset(new BookmarkServerSearchService( profile_->GetRequestContext(), ProfileOAuth2TokenServiceFactory::GetForProfile(profile_), SigninManagerFactory::GetForProfile(profile_), EnhancedBookmarkModelFactory::GetForBrowserContext(profile_))); search_service_->AddObserver(this); } EnhancedBookmarksBridge::~EnhancedBookmarksBridge() { cluster_service_->RemoveObserver(this); search_service_->RemoveObserver(this); } void EnhancedBookmarksBridge::Destroy(JNIEnv*, jobject) { delete this; } void EnhancedBookmarksBridge::SalientImageForUrl(JNIEnv* env, jobject obj, jstring j_url, jobject j_callback) { DCHECK(j_callback); GURL url(base::android::ConvertJavaStringToUTF16(env, j_url)); scoped_ptr<ScopedJavaGlobalRef<jobject>> j_callback_ptr( new ScopedJavaGlobalRef<jobject>()); j_callback_ptr->Reset(env, j_callback); bookmark_image_service_->SalientImageForUrl( url, base::Bind(&Callback, j_callback_ptr.release())); } void EnhancedBookmarksBridge::FetchImageForTab(JNIEnv* env, jobject obj, jobject j_web_contents) { WebContents* web_contents = WebContents::FromJavaWebContents(j_web_contents); bookmark_image_service_->RetrieveSalientImageFromContext( web_contents->GetMainFrame(), web_contents->GetURL(), true); } ScopedJavaLocalRef<jstring> EnhancedBookmarksBridge::GetBookmarkDescription( JNIEnv* env, jobject obj, jlong id, jint type) { DCHECK(enhanced_bookmark_model_->loaded()); if (type != BookmarkType::BOOKMARK_TYPE_NORMAL) { return base::android::ConvertUTF8ToJavaString(env, std::string()); } const BookmarkNode* node = bookmarks::GetBookmarkNodeByID( enhanced_bookmark_model_->bookmark_model(), static_cast<int64>(id)); return node ? base::android::ConvertUTF8ToJavaString( env, enhanced_bookmark_model_->GetDescription(node)) : ScopedJavaLocalRef<jstring>(); } void EnhancedBookmarksBridge::SetBookmarkDescription(JNIEnv* env, jobject obj, jlong id, jint type, jstring description) { DCHECK(enhanced_bookmark_model_->loaded()); DCHECK_EQ(type, BookmarkType::BOOKMARK_TYPE_NORMAL); const BookmarkNode* node = bookmarks::GetBookmarkNodeByID( enhanced_bookmark_model_->bookmark_model(), static_cast<int64>(id)); enhanced_bookmark_model_->SetDescription( node, base::android::ConvertJavaStringToUTF8(env, description)); } ScopedJavaLocalRef<jobjectArray> EnhancedBookmarksBridge::GetFiltersForBookmark( JNIEnv* env, jobject obj, jlong id, jint type) { DCHECK(enhanced_bookmark_model_->loaded()); if (type != BookmarkType::BOOKMARK_TYPE_NORMAL) { return base::android::ToJavaArrayOfStrings(env, std::vector<std::string>()); } const BookmarkNode* node = bookmarks::GetBookmarkNodeByID( enhanced_bookmark_model_->bookmark_model(), static_cast<int64>(id)); std::vector<std::string> filters = cluster_service_->ClustersForBookmark(node); return base::android::ToJavaArrayOfStrings(env, filters); } void EnhancedBookmarksBridge::GetBookmarksForFilter(JNIEnv* env, jobject obj, jstring j_filter, jobject j_result_obj) { DCHECK(enhanced_bookmark_model_->loaded()); const std::string title = base::android::ConvertJavaStringToUTF8(env, j_filter); const std::vector<const BookmarkNode*> bookmarks = cluster_service_->BookmarksForClusterNamed(title); for (const BookmarkNode* node : bookmarks) { Java_EnhancedBookmarksBridge_addToBookmarkIdList( env, j_result_obj, node->id(), node->type()); } } ScopedJavaLocalRef<jobjectArray> EnhancedBookmarksBridge::GetFilters( JNIEnv* env, jobject obj) { DCHECK(enhanced_bookmark_model_->loaded()); const std::vector<std::string> filters = cluster_service_->GetClusters(); return base::android::ToJavaArrayOfStrings(env, filters); } ScopedJavaLocalRef<jobject> EnhancedBookmarksBridge::AddFolder(JNIEnv* env, jobject obj, jobject j_parent_id_obj, jint index, jstring j_title) { DCHECK(enhanced_bookmark_model_->loaded()); long bookmark_id = JavaBookmarkIdGetId(env, j_parent_id_obj); const BookmarkNode* parent = bookmarks::GetBookmarkNodeByID( enhanced_bookmark_model_->bookmark_model(), static_cast<int64>(bookmark_id)); const BookmarkNode* new_node = enhanced_bookmark_model_->AddFolder( parent, index, base::android::ConvertJavaStringToUTF16(env, j_title)); if (!new_node) { NOTREACHED(); return ScopedJavaLocalRef<jobject>(); } ScopedJavaLocalRef<jobject> new_java_obj = JavaBookmarkIdCreateBookmarkId(env, new_node->id(), new_node->type()); return new_java_obj; } void EnhancedBookmarksBridge::MoveBookmark(JNIEnv* env, jobject obj, jobject j_bookmark_id_obj, jobject j_parent_id_obj) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(enhanced_bookmark_model_->loaded()); long bookmark_id = JavaBookmarkIdGetId(env, j_bookmark_id_obj); const BookmarkNode* node = bookmarks::GetBookmarkNodeByID( enhanced_bookmark_model_->bookmark_model(), static_cast<int64>(bookmark_id)); if (!IsEditable(node)) { NOTREACHED(); return; } bookmark_id = JavaBookmarkIdGetId(env, j_parent_id_obj); const BookmarkNode* new_parent_node = bookmarks::GetBookmarkNodeByID( enhanced_bookmark_model_->bookmark_model(), static_cast<int64>(bookmark_id)); enhanced_bookmark_model_->Move(node, new_parent_node, new_parent_node->child_count()); } ScopedJavaLocalRef<jobject> EnhancedBookmarksBridge::AddBookmark( JNIEnv* env, jobject obj, jobject j_parent_id_obj, jint index, jstring j_title, jstring j_url) { DCHECK(enhanced_bookmark_model_->loaded()); long bookmark_id = JavaBookmarkIdGetId(env, j_parent_id_obj); const BookmarkNode* parent = bookmarks::GetBookmarkNodeByID( enhanced_bookmark_model_->bookmark_model(), static_cast<int64>(bookmark_id)); const BookmarkNode* new_node = enhanced_bookmark_model_->AddURL( parent, index, base::android::ConvertJavaStringToUTF16(env, j_title), GURL(base::android::ConvertJavaStringToUTF16(env, j_url)), base::Time::Now()); if (!new_node) { NOTREACHED(); return ScopedJavaLocalRef<jobject>(); } ScopedJavaLocalRef<jobject> new_java_obj = JavaBookmarkIdCreateBookmarkId(env, new_node->id(), new_node->type()); return new_java_obj; } void EnhancedBookmarksBridge::SendSearchRequest(JNIEnv* env, jobject obj, jstring j_query) { search_service_->Search(base::android::ConvertJavaStringToUTF8(env, j_query)); } ScopedJavaLocalRef<jobject> EnhancedBookmarksBridge::GetSearchResults( JNIEnv* env, jobject obj, jstring j_query) { DCHECK(enhanced_bookmark_model_->loaded()); ScopedJavaLocalRef<jobject> j_list = Java_EnhancedBookmarksBridge_createBookmarkIdList(env); scoped_ptr<std::vector<const BookmarkNode*>> results = search_service_->ResultForQuery( base::android::ConvertJavaStringToUTF8(env, j_query)); // If result is null, return a null java reference. if (!results.get()) return ScopedJavaLocalRef<jobject>(); for (const BookmarkNode* node : *results) { Java_EnhancedBookmarksBridge_addToBookmarkIdList(env, j_list.obj(), node->id(), node->type()); } return j_list; } void EnhancedBookmarksBridge::OnChange(BookmarkServerService* service) { DCHECK(enhanced_bookmark_model_->loaded()); JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> obj = weak_java_ref_.get(env); if (obj.is_null()) return; if (service == cluster_service_) { Java_EnhancedBookmarksBridge_onFiltersChanged(env, obj.obj()); } else if (service == search_service_.get()) { Java_EnhancedBookmarksBridge_onSearchResultReturned(env, obj.obj()); } } bool EnhancedBookmarksBridge::IsEditable(const BookmarkNode* node) const { if (!node || (node->type() != BookmarkNode::FOLDER && node->type() != BookmarkNode::URL)) { return false; } return profile_->GetPrefs()->GetBoolean( bookmarks::prefs::kEditBookmarksEnabled); } static jlong Init(JNIEnv* env, jobject obj, jobject j_profile) { return reinterpret_cast<jlong>(new EnhancedBookmarksBridge( env, obj, ProfileAndroid::FromProfileAndroid(j_profile))); } bool RegisterEnhancedBookmarksBridge(JNIEnv* env) { return RegisterNativesImpl(env); } } // namespace android } // namespace enhanced_bookmarks <commit_msg>Fix bug that AddBookmarks returns partner bookmark node<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 "chrome/browser/enhanced_bookmarks/android/enhanced_bookmarks_bridge.h" #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/prefs/pref_service.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" #include "chrome/browser/enhanced_bookmarks/android/bookmark_image_service_android.h" #include "chrome/browser/enhanced_bookmarks/android/bookmark_image_service_factory.h" #include "chrome/browser/enhanced_bookmarks/chrome_bookmark_server_cluster_service.h" #include "chrome/browser/enhanced_bookmarks/chrome_bookmark_server_cluster_service_factory.h" #include "chrome/browser/enhanced_bookmarks/enhanced_bookmark_model_factory.h" #include "chrome/browser/profiles/profile_android.h" #include "chrome/browser/signin/profile_oauth2_token_service_factory.h" #include "chrome/browser/signin/signin_manager_factory.h" #include "chrome/common/chrome_version_info.h" #include "chrome/common/pref_names.h" #include "components/bookmarks/browser/bookmark_model.h" #include "components/bookmarks/browser/bookmark_utils.h" #include "components/bookmarks/common/android/bookmark_id.h" #include "components/bookmarks/common/android/bookmark_type.h" #include "components/enhanced_bookmarks/enhanced_bookmark_model.h" #include "components/enhanced_bookmarks/image_record.h" #include "components/signin/core/browser/signin_manager.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/web_contents.h" #include "jni/EnhancedBookmarksBridge_jni.h" #include "ui/gfx/android/java_bitmap.h" #include "ui/gfx/image/image.h" using base::android::AttachCurrentThread; using base::android::ScopedJavaGlobalRef; using bookmarks::android::JavaBookmarkIdCreateBookmarkId; using bookmarks::android::JavaBookmarkIdGetId; using bookmarks::android::JavaBookmarkIdGetType; using bookmarks::BookmarkNode; using bookmarks::BookmarkType; using content::WebContents; using content::BrowserThread; using enhanced_bookmarks::ImageRecord; namespace { void Callback(ScopedJavaGlobalRef<jobject>* j_callback, const ImageRecord& image_record) { JNIEnv* env = base::android::AttachCurrentThread(); scoped_ptr<ScopedJavaGlobalRef<jobject> > j_callback_ptr(j_callback); ScopedJavaLocalRef<jstring> j_url = base::android::ConvertUTF8ToJavaString(env, image_record.url.spec()); SkBitmap bitmap = image_record.image.AsBitmap(); ScopedJavaLocalRef<jobject> j_bitmap; if (!bitmap.isNull()) { j_bitmap = gfx::ConvertToJavaBitmap(&bitmap); } enhanced_bookmarks::android::Java_SalientImageCallback_onSalientImageReady( env, j_callback_ptr->obj(), j_bitmap.Release(), j_url.Release()); } } // namespace namespace enhanced_bookmarks { namespace android { EnhancedBookmarksBridge::EnhancedBookmarksBridge(JNIEnv* env, jobject obj, Profile* profile) : weak_java_ref_(env, obj) { profile_ = profile; enhanced_bookmark_model_ = EnhancedBookmarkModelFactory::GetForBrowserContext(profile_); enhanced_bookmark_model_->SetVersionSuffix(chrome::VersionInfo().OSType()); cluster_service_ = ChromeBookmarkServerClusterServiceFactory::GetForBrowserContext(profile_); cluster_service_->AddObserver(this); bookmark_image_service_ = static_cast<BookmarkImageServiceAndroid*>( BookmarkImageServiceFactory::GetForBrowserContext(profile_)); search_service_.reset(new BookmarkServerSearchService( profile_->GetRequestContext(), ProfileOAuth2TokenServiceFactory::GetForProfile(profile_), SigninManagerFactory::GetForProfile(profile_), EnhancedBookmarkModelFactory::GetForBrowserContext(profile_))); search_service_->AddObserver(this); } EnhancedBookmarksBridge::~EnhancedBookmarksBridge() { cluster_service_->RemoveObserver(this); search_service_->RemoveObserver(this); } void EnhancedBookmarksBridge::Destroy(JNIEnv*, jobject) { delete this; } void EnhancedBookmarksBridge::SalientImageForUrl(JNIEnv* env, jobject obj, jstring j_url, jobject j_callback) { DCHECK(j_callback); GURL url(base::android::ConvertJavaStringToUTF16(env, j_url)); scoped_ptr<ScopedJavaGlobalRef<jobject>> j_callback_ptr( new ScopedJavaGlobalRef<jobject>()); j_callback_ptr->Reset(env, j_callback); bookmark_image_service_->SalientImageForUrl( url, base::Bind(&Callback, j_callback_ptr.release())); } void EnhancedBookmarksBridge::FetchImageForTab(JNIEnv* env, jobject obj, jobject j_web_contents) { WebContents* web_contents = WebContents::FromJavaWebContents(j_web_contents); bookmark_image_service_->RetrieveSalientImageFromContext( web_contents->GetMainFrame(), web_contents->GetURL(), true); } ScopedJavaLocalRef<jstring> EnhancedBookmarksBridge::GetBookmarkDescription( JNIEnv* env, jobject obj, jlong id, jint type) { DCHECK(enhanced_bookmark_model_->loaded()); if (type != BookmarkType::BOOKMARK_TYPE_NORMAL) { return base::android::ConvertUTF8ToJavaString(env, std::string()); } const BookmarkNode* node = bookmarks::GetBookmarkNodeByID( enhanced_bookmark_model_->bookmark_model(), static_cast<int64>(id)); return node ? base::android::ConvertUTF8ToJavaString( env, enhanced_bookmark_model_->GetDescription(node)) : ScopedJavaLocalRef<jstring>(); } void EnhancedBookmarksBridge::SetBookmarkDescription(JNIEnv* env, jobject obj, jlong id, jint type, jstring description) { DCHECK(enhanced_bookmark_model_->loaded()); DCHECK_EQ(type, BookmarkType::BOOKMARK_TYPE_NORMAL); const BookmarkNode* node = bookmarks::GetBookmarkNodeByID( enhanced_bookmark_model_->bookmark_model(), static_cast<int64>(id)); enhanced_bookmark_model_->SetDescription( node, base::android::ConvertJavaStringToUTF8(env, description)); } ScopedJavaLocalRef<jobjectArray> EnhancedBookmarksBridge::GetFiltersForBookmark( JNIEnv* env, jobject obj, jlong id, jint type) { DCHECK(enhanced_bookmark_model_->loaded()); if (type != BookmarkType::BOOKMARK_TYPE_NORMAL) { return base::android::ToJavaArrayOfStrings(env, std::vector<std::string>()); } const BookmarkNode* node = bookmarks::GetBookmarkNodeByID( enhanced_bookmark_model_->bookmark_model(), static_cast<int64>(id)); std::vector<std::string> filters = cluster_service_->ClustersForBookmark(node); return base::android::ToJavaArrayOfStrings(env, filters); } void EnhancedBookmarksBridge::GetBookmarksForFilter(JNIEnv* env, jobject obj, jstring j_filter, jobject j_result_obj) { DCHECK(enhanced_bookmark_model_->loaded()); const std::string title = base::android::ConvertJavaStringToUTF8(env, j_filter); const std::vector<const BookmarkNode*> bookmarks = cluster_service_->BookmarksForClusterNamed(title); for (const BookmarkNode* node : bookmarks) { Java_EnhancedBookmarksBridge_addToBookmarkIdList( env, j_result_obj, node->id(), node->type()); } } ScopedJavaLocalRef<jobjectArray> EnhancedBookmarksBridge::GetFilters( JNIEnv* env, jobject obj) { DCHECK(enhanced_bookmark_model_->loaded()); const std::vector<std::string> filters = cluster_service_->GetClusters(); return base::android::ToJavaArrayOfStrings(env, filters); } ScopedJavaLocalRef<jobject> EnhancedBookmarksBridge::AddFolder(JNIEnv* env, jobject obj, jobject j_parent_id_obj, jint index, jstring j_title) { DCHECK(enhanced_bookmark_model_->loaded()); long bookmark_id = JavaBookmarkIdGetId(env, j_parent_id_obj); const BookmarkNode* parent = bookmarks::GetBookmarkNodeByID( enhanced_bookmark_model_->bookmark_model(), static_cast<int64>(bookmark_id)); const BookmarkNode* new_node = enhanced_bookmark_model_->AddFolder( parent, index, base::android::ConvertJavaStringToUTF16(env, j_title)); if (!new_node) { NOTREACHED(); return ScopedJavaLocalRef<jobject>(); } ScopedJavaLocalRef<jobject> new_java_obj = JavaBookmarkIdCreateBookmarkId( env, new_node->id(), BookmarkType::BOOKMARK_TYPE_NORMAL); return new_java_obj; } void EnhancedBookmarksBridge::MoveBookmark(JNIEnv* env, jobject obj, jobject j_bookmark_id_obj, jobject j_parent_id_obj) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); DCHECK(enhanced_bookmark_model_->loaded()); long bookmark_id = JavaBookmarkIdGetId(env, j_bookmark_id_obj); const BookmarkNode* node = bookmarks::GetBookmarkNodeByID( enhanced_bookmark_model_->bookmark_model(), static_cast<int64>(bookmark_id)); if (!IsEditable(node)) { NOTREACHED(); return; } bookmark_id = JavaBookmarkIdGetId(env, j_parent_id_obj); const BookmarkNode* new_parent_node = bookmarks::GetBookmarkNodeByID( enhanced_bookmark_model_->bookmark_model(), static_cast<int64>(bookmark_id)); enhanced_bookmark_model_->Move(node, new_parent_node, new_parent_node->child_count()); } ScopedJavaLocalRef<jobject> EnhancedBookmarksBridge::AddBookmark( JNIEnv* env, jobject obj, jobject j_parent_id_obj, jint index, jstring j_title, jstring j_url) { DCHECK(enhanced_bookmark_model_->loaded()); long bookmark_id = JavaBookmarkIdGetId(env, j_parent_id_obj); const BookmarkNode* parent = bookmarks::GetBookmarkNodeByID( enhanced_bookmark_model_->bookmark_model(), static_cast<int64>(bookmark_id)); const BookmarkNode* new_node = enhanced_bookmark_model_->AddURL( parent, index, base::android::ConvertJavaStringToUTF16(env, j_title), GURL(base::android::ConvertJavaStringToUTF16(env, j_url)), base::Time::Now()); if (!new_node) { NOTREACHED(); return ScopedJavaLocalRef<jobject>(); } ScopedJavaLocalRef<jobject> new_java_obj = JavaBookmarkIdCreateBookmarkId( env, new_node->id(), BookmarkType::BOOKMARK_TYPE_NORMAL); return new_java_obj; } void EnhancedBookmarksBridge::SendSearchRequest(JNIEnv* env, jobject obj, jstring j_query) { search_service_->Search(base::android::ConvertJavaStringToUTF8(env, j_query)); } ScopedJavaLocalRef<jobject> EnhancedBookmarksBridge::GetSearchResults( JNIEnv* env, jobject obj, jstring j_query) { DCHECK(enhanced_bookmark_model_->loaded()); ScopedJavaLocalRef<jobject> j_list = Java_EnhancedBookmarksBridge_createBookmarkIdList(env); scoped_ptr<std::vector<const BookmarkNode*>> results = search_service_->ResultForQuery( base::android::ConvertJavaStringToUTF8(env, j_query)); // If result is null, return a null java reference. if (!results.get()) return ScopedJavaLocalRef<jobject>(); for (const BookmarkNode* node : *results) { Java_EnhancedBookmarksBridge_addToBookmarkIdList(env, j_list.obj(), node->id(), node->type()); } return j_list; } void EnhancedBookmarksBridge::OnChange(BookmarkServerService* service) { DCHECK(enhanced_bookmark_model_->loaded()); JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jobject> obj = weak_java_ref_.get(env); if (obj.is_null()) return; if (service == cluster_service_) { Java_EnhancedBookmarksBridge_onFiltersChanged(env, obj.obj()); } else if (service == search_service_.get()) { Java_EnhancedBookmarksBridge_onSearchResultReturned(env, obj.obj()); } } bool EnhancedBookmarksBridge::IsEditable(const BookmarkNode* node) const { if (!node || (node->type() != BookmarkNode::FOLDER && node->type() != BookmarkNode::URL)) { return false; } return profile_->GetPrefs()->GetBoolean( bookmarks::prefs::kEditBookmarksEnabled); } static jlong Init(JNIEnv* env, jobject obj, jobject j_profile) { return reinterpret_cast<jlong>(new EnhancedBookmarksBridge( env, obj, ProfileAndroid::FromProfileAndroid(j_profile))); } bool RegisterEnhancedBookmarksBridge(JNIEnv* env) { return RegisterNativesImpl(env); } } // namespace android } // namespace enhanced_bookmarks <|endoftext|>
<commit_before>#include "optionsdialog.h" #include "optionsmodel.h" #include "bitcoinamountfield.h" #include "monitoreddatamapper.h" #include "guiutil.h" #include "bitcoinunits.h" #include "qvaluecombobox.h" #include <QHBoxLayout> #include <QVBoxLayout> #include <QPushButton> #include <QListWidget> #include <QStackedWidget> #include <QCheckBox> #include <QLabel> #include <QLineEdit> #include <QIntValidator> #include <QDoubleValidator> #include <QRegExpValidator> #include <QDialogButtonBox> /* First page of options */ class MainOptionsPage : public QWidget { Q_OBJECT public: explicit MainOptionsPage(QWidget *parent=0); void setMapper(MonitoredDataMapper *mapper); private: QCheckBox *bitcoin_at_startup; #ifndef Q_WS_MAC QCheckBox *minimize_to_tray; #endif QCheckBox *map_port_upnp; #ifndef Q_WS_MAC QCheckBox *minimize_on_close; #endif QCheckBox *connect_socks4; QLineEdit *proxy_ip; QLineEdit *proxy_port; BitcoinAmountField *fee_edit; signals: public slots: }; class DisplayOptionsPage : public QWidget { Q_OBJECT public: explicit DisplayOptionsPage(QWidget *parent=0); void setMapper(MonitoredDataMapper *mapper); private: QValueComboBox *unit; QCheckBox *display_addresses; signals: public slots: }; #include "optionsdialog.moc" OptionsDialog::OptionsDialog(QWidget *parent): QDialog(parent), contents_widget(0), pages_widget(0), model(0), main_page(0), display_page(0) { contents_widget = new QListWidget(); contents_widget->setMaximumWidth(128); pages_widget = new QStackedWidget(); pages_widget->setMinimumWidth(300); QListWidgetItem *item_main = new QListWidgetItem(tr("Main")); contents_widget->addItem(item_main); main_page = new MainOptionsPage(this); pages_widget->addWidget(main_page); QListWidgetItem *item_display = new QListWidgetItem(tr("Display")); contents_widget->addItem(item_display); display_page = new DisplayOptionsPage(this); pages_widget->addWidget(display_page); contents_widget->setCurrentRow(0); QHBoxLayout *main_layout = new QHBoxLayout(); main_layout->addWidget(contents_widget); main_layout->addWidget(pages_widget, 1); QVBoxLayout *layout = new QVBoxLayout(); layout->addLayout(main_layout); QDialogButtonBox *buttonbox = new QDialogButtonBox(); buttonbox->setStandardButtons(QDialogButtonBox::Apply|QDialogButtonBox::Ok|QDialogButtonBox::Cancel); apply_button = buttonbox->button(QDialogButtonBox::Apply); layout->addWidget(buttonbox); setLayout(layout); setWindowTitle(tr("Options")); /* Widget-to-option mapper */ mapper = new MonitoredDataMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setOrientation(Qt::Vertical); /* enable apply button when data modified */ connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApply())); /* disable apply button when new data loaded */ connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApply())); /* Event bindings */ connect(contents_widget, SIGNAL(currentRowChanged(int)), this, SLOT(changePage(int))); connect(buttonbox->button(QDialogButtonBox::Ok), SIGNAL(clicked()), this, SLOT(okClicked())); connect(buttonbox->button(QDialogButtonBox::Cancel), SIGNAL(clicked()), this, SLOT(cancelClicked())); connect(buttonbox->button(QDialogButtonBox::Apply), SIGNAL(clicked()), this, SLOT(applyClicked())); } void OptionsDialog::setModel(OptionsModel *model) { this->model = model; mapper->setModel(model); main_page->setMapper(mapper); display_page->setMapper(mapper); mapper->toFirst(); } void OptionsDialog::changePage(int index) { pages_widget->setCurrentIndex(index); } void OptionsDialog::okClicked() { mapper->submit(); accept(); } void OptionsDialog::cancelClicked() { reject(); } void OptionsDialog::applyClicked() { mapper->submit(); apply_button->setEnabled(false); } void OptionsDialog::enableApply() { apply_button->setEnabled(true); } void OptionsDialog::disableApply() { apply_button->setEnabled(false); } MainOptionsPage::MainOptionsPage(QWidget *parent): QWidget(parent) { QVBoxLayout *layout = new QVBoxLayout(); bitcoin_at_startup = new QCheckBox(tr("&Start Bitcoin on window system startup")); bitcoin_at_startup->setToolTip(tr("Automatically start Bitcoin after the computer is turned on")); layout->addWidget(bitcoin_at_startup); #ifndef Q_WS_MAC minimize_to_tray = new QCheckBox(tr("&Minimize to the tray instead of the taskbar")); minimize_to_tray->setToolTip(tr("Show only a tray icon after minimizing the window")); layout->addWidget(minimize_to_tray); #endif map_port_upnp = new QCheckBox(tr("Map port using &UPnP")); map_port_upnp->setToolTip(tr("Automatically open the Bitcoin client port on the router. This only works when your router supports UPnP and it is enabled.")); layout->addWidget(map_port_upnp); #ifndef Q_WS_MAC minimize_on_close = new QCheckBox(tr("M&inimize on close")); minimize_on_close->setToolTip(tr("Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.")); layout->addWidget(minimize_on_close); #endif connect_socks4 = new QCheckBox(tr("&Connect through SOCKS4 proxy:")); connect_socks4->setToolTip(tr("Connect to the Bitcon network through a SOCKS4 proxy (e.g. when connecting through Tor)")); layout->addWidget(connect_socks4); QHBoxLayout *proxy_hbox = new QHBoxLayout(); proxy_hbox->addSpacing(18); QLabel *proxy_ip_label = new QLabel(tr("Proxy &IP: ")); proxy_hbox->addWidget(proxy_ip_label); proxy_ip = new QLineEdit(); proxy_ip->setMaximumWidth(140); proxy_ip->setEnabled(false); proxy_ip->setValidator(new QRegExpValidator(QRegExp("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"), this)); proxy_ip->setToolTip(tr("IP address of the proxy (e.g. 127.0.0.1)")); proxy_ip_label->setBuddy(proxy_ip); proxy_hbox->addWidget(proxy_ip); QLabel *proxy_port_label = new QLabel(tr("&Port: ")); proxy_hbox->addWidget(proxy_port_label); proxy_port = new QLineEdit(); proxy_port->setMaximumWidth(55); proxy_port->setValidator(new QIntValidator(0, 65535, this)); proxy_port->setEnabled(false); proxy_port->setToolTip(tr("Port of the proxy (e.g. 1234)")); proxy_port_label->setBuddy(proxy_port); proxy_hbox->addWidget(proxy_port); proxy_hbox->addStretch(1); layout->addLayout(proxy_hbox); QLabel *fee_help = new QLabel(tr("Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.")); fee_help->setWordWrap(true); layout->addWidget(fee_help); QHBoxLayout *fee_hbox = new QHBoxLayout(); fee_hbox->addSpacing(18); QLabel *fee_label = new QLabel(tr("Pay transaction &fee")); fee_hbox->addWidget(fee_label); fee_edit = new BitcoinAmountField(); fee_edit->setToolTip(tr("Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.")); fee_label->setBuddy(fee_edit); fee_hbox->addWidget(fee_edit); fee_hbox->addStretch(1); layout->addLayout(fee_hbox); layout->addStretch(1); // Extra space at bottom setLayout(layout); connect(connect_socks4, SIGNAL(toggled(bool)), proxy_ip, SLOT(setEnabled(bool))); connect(connect_socks4, SIGNAL(toggled(bool)), proxy_port, SLOT(setEnabled(bool))); #ifndef USE_UPNP map_port_upnp->setDisabled(true); #endif } void MainOptionsPage::setMapper(MonitoredDataMapper *mapper) { // Map model to widgets mapper->addMapping(bitcoin_at_startup, OptionsModel::StartAtStartup); #ifndef Q_WS_MAC mapper->addMapping(minimize_to_tray, OptionsModel::MinimizeToTray); #endif mapper->addMapping(map_port_upnp, OptionsModel::MapPortUPnP); #ifndef Q_WS_MAC mapper->addMapping(minimize_on_close, OptionsModel::MinimizeOnClose); #endif mapper->addMapping(connect_socks4, OptionsModel::ConnectSOCKS4); mapper->addMapping(proxy_ip, OptionsModel::ProxyIP); mapper->addMapping(proxy_port, OptionsModel::ProxyPort); mapper->addMapping(fee_edit, OptionsModel::Fee); } DisplayOptionsPage::DisplayOptionsPage(QWidget *parent): QWidget(parent) { QVBoxLayout *layout = new QVBoxLayout(); QHBoxLayout *unit_hbox = new QHBoxLayout(); unit_hbox->addSpacing(18); QLabel *unit_label = new QLabel(tr("&Unit to show amounts in: ")); unit_hbox->addWidget(unit_label); unit = new QValueComboBox(this); unit->setModel(new BitcoinUnits(this)); unit->setToolTip(tr("Choose the default subdivision unit to show in the interface, and when sending coins")); unit_label->setBuddy(unit); unit_hbox->addWidget(unit); layout->addLayout(unit_hbox); display_addresses = new QCheckBox(tr("Display addresses in transaction list"), this); layout->addWidget(display_addresses); layout->addStretch(); setLayout(layout); } void DisplayOptionsPage::setMapper(MonitoredDataMapper *mapper) { mapper->addMapping(unit, OptionsModel::DisplayUnit); mapper->addMapping(display_addresses, OptionsModel::DisplayAddresses); } <commit_msg>Bitcoin-Qt: Remove redundant tooltip on optional transaction fee. Fixes #1218<commit_after>#include "optionsdialog.h" #include "optionsmodel.h" #include "bitcoinamountfield.h" #include "monitoreddatamapper.h" #include "guiutil.h" #include "bitcoinunits.h" #include "qvaluecombobox.h" #include <QHBoxLayout> #include <QVBoxLayout> #include <QPushButton> #include <QListWidget> #include <QStackedWidget> #include <QCheckBox> #include <QLabel> #include <QLineEdit> #include <QIntValidator> #include <QDoubleValidator> #include <QRegExpValidator> #include <QDialogButtonBox> /* First page of options */ class MainOptionsPage : public QWidget { Q_OBJECT public: explicit MainOptionsPage(QWidget *parent=0); void setMapper(MonitoredDataMapper *mapper); private: QCheckBox *bitcoin_at_startup; #ifndef Q_WS_MAC QCheckBox *minimize_to_tray; #endif QCheckBox *map_port_upnp; #ifndef Q_WS_MAC QCheckBox *minimize_on_close; #endif QCheckBox *connect_socks4; QLineEdit *proxy_ip; QLineEdit *proxy_port; BitcoinAmountField *fee_edit; signals: public slots: }; class DisplayOptionsPage : public QWidget { Q_OBJECT public: explicit DisplayOptionsPage(QWidget *parent=0); void setMapper(MonitoredDataMapper *mapper); private: QValueComboBox *unit; QCheckBox *display_addresses; signals: public slots: }; #include "optionsdialog.moc" OptionsDialog::OptionsDialog(QWidget *parent): QDialog(parent), contents_widget(0), pages_widget(0), model(0), main_page(0), display_page(0) { contents_widget = new QListWidget(); contents_widget->setMaximumWidth(128); pages_widget = new QStackedWidget(); pages_widget->setMinimumWidth(300); QListWidgetItem *item_main = new QListWidgetItem(tr("Main")); contents_widget->addItem(item_main); main_page = new MainOptionsPage(this); pages_widget->addWidget(main_page); QListWidgetItem *item_display = new QListWidgetItem(tr("Display")); contents_widget->addItem(item_display); display_page = new DisplayOptionsPage(this); pages_widget->addWidget(display_page); contents_widget->setCurrentRow(0); QHBoxLayout *main_layout = new QHBoxLayout(); main_layout->addWidget(contents_widget); main_layout->addWidget(pages_widget, 1); QVBoxLayout *layout = new QVBoxLayout(); layout->addLayout(main_layout); QDialogButtonBox *buttonbox = new QDialogButtonBox(); buttonbox->setStandardButtons(QDialogButtonBox::Apply|QDialogButtonBox::Ok|QDialogButtonBox::Cancel); apply_button = buttonbox->button(QDialogButtonBox::Apply); layout->addWidget(buttonbox); setLayout(layout); setWindowTitle(tr("Options")); /* Widget-to-option mapper */ mapper = new MonitoredDataMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setOrientation(Qt::Vertical); /* enable apply button when data modified */ connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApply())); /* disable apply button when new data loaded */ connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApply())); /* Event bindings */ connect(contents_widget, SIGNAL(currentRowChanged(int)), this, SLOT(changePage(int))); connect(buttonbox->button(QDialogButtonBox::Ok), SIGNAL(clicked()), this, SLOT(okClicked())); connect(buttonbox->button(QDialogButtonBox::Cancel), SIGNAL(clicked()), this, SLOT(cancelClicked())); connect(buttonbox->button(QDialogButtonBox::Apply), SIGNAL(clicked()), this, SLOT(applyClicked())); } void OptionsDialog::setModel(OptionsModel *model) { this->model = model; mapper->setModel(model); main_page->setMapper(mapper); display_page->setMapper(mapper); mapper->toFirst(); } void OptionsDialog::changePage(int index) { pages_widget->setCurrentIndex(index); } void OptionsDialog::okClicked() { mapper->submit(); accept(); } void OptionsDialog::cancelClicked() { reject(); } void OptionsDialog::applyClicked() { mapper->submit(); apply_button->setEnabled(false); } void OptionsDialog::enableApply() { apply_button->setEnabled(true); } void OptionsDialog::disableApply() { apply_button->setEnabled(false); } MainOptionsPage::MainOptionsPage(QWidget *parent): QWidget(parent) { QVBoxLayout *layout = new QVBoxLayout(); bitcoin_at_startup = new QCheckBox(tr("&Start Bitcoin on window system startup")); bitcoin_at_startup->setToolTip(tr("Automatically start Bitcoin after the computer is turned on")); layout->addWidget(bitcoin_at_startup); #ifndef Q_WS_MAC minimize_to_tray = new QCheckBox(tr("&Minimize to the tray instead of the taskbar")); minimize_to_tray->setToolTip(tr("Show only a tray icon after minimizing the window")); layout->addWidget(minimize_to_tray); #endif map_port_upnp = new QCheckBox(tr("Map port using &UPnP")); map_port_upnp->setToolTip(tr("Automatically open the Bitcoin client port on the router. This only works when your router supports UPnP and it is enabled.")); layout->addWidget(map_port_upnp); #ifndef Q_WS_MAC minimize_on_close = new QCheckBox(tr("M&inimize on close")); minimize_on_close->setToolTip(tr("Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.")); layout->addWidget(minimize_on_close); #endif connect_socks4 = new QCheckBox(tr("&Connect through SOCKS4 proxy:")); connect_socks4->setToolTip(tr("Connect to the Bitcon network through a SOCKS4 proxy (e.g. when connecting through Tor)")); layout->addWidget(connect_socks4); QHBoxLayout *proxy_hbox = new QHBoxLayout(); proxy_hbox->addSpacing(18); QLabel *proxy_ip_label = new QLabel(tr("Proxy &IP: ")); proxy_hbox->addWidget(proxy_ip_label); proxy_ip = new QLineEdit(); proxy_ip->setMaximumWidth(140); proxy_ip->setEnabled(false); proxy_ip->setValidator(new QRegExpValidator(QRegExp("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"), this)); proxy_ip->setToolTip(tr("IP address of the proxy (e.g. 127.0.0.1)")); proxy_ip_label->setBuddy(proxy_ip); proxy_hbox->addWidget(proxy_ip); QLabel *proxy_port_label = new QLabel(tr("&Port: ")); proxy_hbox->addWidget(proxy_port_label); proxy_port = new QLineEdit(); proxy_port->setMaximumWidth(55); proxy_port->setValidator(new QIntValidator(0, 65535, this)); proxy_port->setEnabled(false); proxy_port->setToolTip(tr("Port of the proxy (e.g. 1234)")); proxy_port_label->setBuddy(proxy_port); proxy_hbox->addWidget(proxy_port); proxy_hbox->addStretch(1); layout->addLayout(proxy_hbox); QLabel *fee_help = new QLabel(tr("Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.")); fee_help->setWordWrap(true); layout->addWidget(fee_help); QHBoxLayout *fee_hbox = new QHBoxLayout(); fee_hbox->addSpacing(18); QLabel *fee_label = new QLabel(tr("Pay transaction &fee")); fee_hbox->addWidget(fee_label); fee_edit = new BitcoinAmountField(); fee_label->setBuddy(fee_edit); fee_hbox->addWidget(fee_edit); fee_hbox->addStretch(1); layout->addLayout(fee_hbox); layout->addStretch(1); // Extra space at bottom setLayout(layout); connect(connect_socks4, SIGNAL(toggled(bool)), proxy_ip, SLOT(setEnabled(bool))); connect(connect_socks4, SIGNAL(toggled(bool)), proxy_port, SLOT(setEnabled(bool))); #ifndef USE_UPNP map_port_upnp->setDisabled(true); #endif } void MainOptionsPage::setMapper(MonitoredDataMapper *mapper) { // Map model to widgets mapper->addMapping(bitcoin_at_startup, OptionsModel::StartAtStartup); #ifndef Q_WS_MAC mapper->addMapping(minimize_to_tray, OptionsModel::MinimizeToTray); #endif mapper->addMapping(map_port_upnp, OptionsModel::MapPortUPnP); #ifndef Q_WS_MAC mapper->addMapping(minimize_on_close, OptionsModel::MinimizeOnClose); #endif mapper->addMapping(connect_socks4, OptionsModel::ConnectSOCKS4); mapper->addMapping(proxy_ip, OptionsModel::ProxyIP); mapper->addMapping(proxy_port, OptionsModel::ProxyPort); mapper->addMapping(fee_edit, OptionsModel::Fee); } DisplayOptionsPage::DisplayOptionsPage(QWidget *parent): QWidget(parent) { QVBoxLayout *layout = new QVBoxLayout(); QHBoxLayout *unit_hbox = new QHBoxLayout(); unit_hbox->addSpacing(18); QLabel *unit_label = new QLabel(tr("&Unit to show amounts in: ")); unit_hbox->addWidget(unit_label); unit = new QValueComboBox(this); unit->setModel(new BitcoinUnits(this)); unit->setToolTip(tr("Choose the default subdivision unit to show in the interface, and when sending coins")); unit_label->setBuddy(unit); unit_hbox->addWidget(unit); layout->addLayout(unit_hbox); display_addresses = new QCheckBox(tr("Display addresses in transaction list"), this); layout->addWidget(display_addresses); layout->addStretch(); setLayout(layout); } void DisplayOptionsPage::setMapper(MonitoredDataMapper *mapper) { mapper->addMapping(unit, OptionsModel::DisplayUnit); mapper->addMapping(display_addresses, OptionsModel::DisplayAddresses); } <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH * * * * 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. * ******************************************************************************* * SOFA :: Applications * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include <plugins/SofaTest/Sofa_test.h> #include <sofa/simulation/graph/DAGSimulation.h> #include <plugins/SceneCreator/SceneCreator.h> namespace sofa { using namespace modeling; /** Test the Simulation class */ struct Simulation_test: public Sofa_test<double> { // root simulation::Node::SPtr root; /// Test Simulation::computeBBox void computeBBox() { // Init Sofa simulation::Simulation* simulation; sofa::simulation::setSimulation(simulation = new sofa::simulation::graph::DAGSimulation()); root = simulation::getSimulation()->createNewGraph("root"); // create DOFs and its expected bounding box MechanicalObject3::SPtr DOF = core::objectmodel::New<MechanicalObject3>(); root->addObject(DOF); DOF->resize(4); MechanicalObject3::WriteVecCoord x = DOF->writePositions(); x[0] = defaulttype::Vector3(0,0,0); x[1] = defaulttype::Vector3(1,0,0); x[2] = defaulttype::Vector3(0,1,0); x[3] = defaulttype::Vector3(0,0,1); defaulttype::Vector3 expectedMin(0,0,0), expectedMax(1,1,1); DOF->showObject.setValue(true); // bbox is updated only for drawn MO // end create scene //********* initScene(); //********* defaulttype::Vector3 sceneMinBBox, sceneMaxBBox; simulation->computeBBox(root.get(), sceneMinBBox.ptr(), sceneMaxBBox.ptr()); if( vectorMaxDiff(sceneMinBBox,expectedMin)>this->epsilon() || vectorMaxDiff(sceneMaxBBox,expectedMax)>this->epsilon() ) { ADD_FAILURE() << "Wrong bounding box, expected (" << expectedMin <<", "<<expectedMax<<") , got ("<< sceneMinBBox <<", "<<sceneMaxBBox << ")" << endl; } } }; TEST_F( Simulation_test,SimulationTest) { this->computeBBox(); } }// namespace sofa <commit_msg>Add: object suppression unit test<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 * * (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH * * * * 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. * ******************************************************************************* * SOFA :: Applications * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include <plugins/SofaTest/Sofa_test.h> #include <sofa/simulation/graph/DAGSimulation.h> #include <plugins/SceneCreator/SceneCreator.h> #include <SofaBaseMechanics/UniformMass.h> namespace sofa { using namespace modeling; static int objectCounter = 0; template <class DataType> class InstrumentedObject : public DataType { public: InstrumentedObject() { objectCounter++; } ~InstrumentedObject() { objectCounter--; } }; /** Test the Simulation class */ struct Simulation_test: public Sofa_test<double> { // root simulation::Node::SPtr root; typedef component::mass::UniformMass<defaulttype::Vec3Types, SReal> UniformMass3; /// Test Simulation::computeBBox void computeBBox() { // Init Sofa simulation::Simulation* simulation; sofa::simulation::setSimulation(simulation = new sofa::simulation::graph::DAGSimulation()); root = simulation::getSimulation()->createNewGraph("root"); // create DOFs and its expected bounding box MechanicalObject3::SPtr DOF = core::objectmodel::New<MechanicalObject3>(); root->addObject(DOF); DOF->resize(4); MechanicalObject3::WriteVecCoord x = DOF->writePositions(); x[0] = defaulttype::Vector3(0,0,0); x[1] = defaulttype::Vector3(1,0,0); x[2] = defaulttype::Vector3(0,1,0); x[3] = defaulttype::Vector3(0,0,1); defaulttype::Vector3 expectedMin(0,0,0), expectedMax(1,1,1); DOF->showObject.setValue(true); // bbox is updated only for drawn MO // end create scene //********* initScene(); //********* defaulttype::Vector3 sceneMinBBox, sceneMaxBBox; simulation->computeBBox(root.get(), sceneMinBBox.ptr(), sceneMaxBBox.ptr()); if( vectorMaxDiff(sceneMinBBox,expectedMin)>this->epsilon() || vectorMaxDiff(sceneMaxBBox,expectedMax)>this->epsilon() ) { ADD_FAILURE() << "Wrong bounding box, expected (" << expectedMin <<", "<<expectedMax<<") , got ("<< sceneMinBBox <<", "<<sceneMaxBBox << ")" << endl; } } void objectSuppression() { // Init Sofa simulation::Simulation* simulation; sofa::simulation::setSimulation(simulation = new sofa::simulation::graph::DAGSimulation()); root = simulation::getSimulation()->createNewGraph("root"); root->addObject(core::objectmodel::New<InstrumentedObject<MechanicalObject3>>()); root->addObject(core::objectmodel::New<InstrumentedObject<UniformMass3>>()); simulation::Node::SPtr child = simulation::getSimulation()->createNewNode("child"); root->addChild(child); child->addObject(core::objectmodel::New<InstrumentedObject<MechanicalObject3>>()); child->addObject(core::objectmodel::New<InstrumentedObject<UniformMass3>>()); // root = simulation::getSimulation()->createNewGraph("root2"); } }; TEST_F( Simulation_test,SimulationTest) { this->computeBBox(); } TEST_F( Simulation_test,objectSuppression) { this->objectSuppression(); if(objectCounter>0) ADD_FAILURE() << "missing delete: "<<objectCounter<<endl; } }// namespace sofa <|endoftext|>
<commit_before>#include <osg/Camera> #include <osg/Texture2D> #include <osgDB/ReadFile> #include <osgGA/TrackballManipulator> #include <osgViewer/Viewer> class FindTextureVisitor : public osg::NodeVisitor { public: FindTextureVisitor(osg::Texture* tex) : texture_(tex) { setTraversalMode(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN); } virtual void apply(osg::Node& node) { replaceTexure(node.getStateSet()); traverse(node); } virtual void apply(osg::Geode& geode) { replaceTexure(geode.getStateSet()); for (unsigned int i = 0; i < geode.getNumDrawables(); ++i) { replaceTexure(geode.getDrawable(i)->getStateSet()); } traverse(geode); } void replaceTexure(osg::StateSet* ss) { if (ss) { osg::Texture* oldTexture = dynamic_cast<osg::Texture*>( ss->getTextureAttribute(0, osg::StateAttribute::TEXTURE)); if (oldTexture) { ss->setTextureAttribute(0, texture_.get()); } } } protected: osg::ref_ptr<osg::Texture> texture_; }; int main( int /*argc*/, char** /*argv*/) { osg::ref_ptr<osg::Node> model = osgDB::readNodeFile("lz.osg"); osg::ref_ptr<osg::Node> sub_model = osgDB::readNodeFile("glider.osg"); int tex_width = 1024; int tex_height = 1024; osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D; texture->setTextureSize(tex_width, tex_height); texture->setInternalFormat(GL_RGBA); texture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR); texture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR); FindTextureVisitor ftv(texture.get()); if (model.valid()) { model->accept(ftv); } osg::ref_ptr<osg::Camera> camera = new osg::Camera; camera->setViewport(0, 0, tex_width, tex_height); camera->setClearColor(osg::Vec4(1.0f, 1.0f, 1.0f, 1.0f)); camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); camera->setRenderOrder(osg::Camera::PRE_RENDER); camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT); camera->attach(osg::Camera::COLOR_BUFFER, texture.get()); camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF); camera->addChild(sub_model); osg::ref_ptr<osg::Group> root = new osg::Group; root->addChild(camera.get()); root->addChild(model.get()); osgViewer::Viewer viewer; viewer.setSceneData(root.get()); viewer.setCameraManipulator(new osgGA::TrackballManipulator); float range = 0.25f; float speed = range / 50; float delta = speed; float bias = 0.0f; osg::Vec3 eye(0.0f, -5.0f, 5.0f); while (!viewer.done()) { if (bias < -range) { delta = speed; } else if (bias > range) { delta = -speed; } bias += delta; camera->setViewMatrixAsLookAt( eye, osg::Vec3(), osg::Vec3(bias, 1.0f, 1.0f)); viewer.frame(); } return 0; } <commit_msg>Finish chapter 7<commit_after>#include <osg/Camera> #include <osg/Texture2D> #include <osgDB/ReadFile> #include <osgGA/TrackballManipulator> #include <osgViewer/Viewer> class FindTextureVisitor : public osg::NodeVisitor { public: FindTextureVisitor(osg::Texture* tex) : texture_(tex) { setTraversalMode(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN); } virtual void apply(osg::Node& node) { replaceTexure(node.getStateSet()); traverse(node); } virtual void apply(osg::Geode& geode) { replaceTexure(geode.getStateSet()); for (unsigned int i = 0; i < geode.getNumDrawables(); ++i) { replaceTexure(geode.getDrawable(i)->getStateSet()); } traverse(geode); } void replaceTexure(osg::StateSet* ss) { if (ss) { osg::Texture* oldTexture = dynamic_cast<osg::Texture*>( ss->getTextureAttribute(0, osg::StateAttribute::TEXTURE)); if (oldTexture) { ss->setTextureAttribute(0, texture_.get()); } } } protected: osg::ref_ptr<osg::Texture> texture_; }; int main( int /*argc*/, char** /*argv*/) { osg::ref_ptr<osg::Node> model = osgDB::readNodeFile("lz.osg"); osg::ref_ptr<osg::Node> sub_model = osgDB::readNodeFile("glider.osg"); int tex_width = 1024; int tex_height = 1024; osg::ref_ptr<osg::Texture2D> texture = new osg::Texture2D; texture->setTextureSize(tex_width, tex_height); texture->setInternalFormat(GL_RGBA); texture->setFilter(osg::Texture::MIN_FILTER, osg::Texture::LINEAR); texture->setFilter(osg::Texture::MAG_FILTER, osg::Texture::LINEAR); FindTextureVisitor ftv(texture.get()); if (model.valid()) { model->accept(ftv); } osg::ref_ptr<osg::Camera> camera = new osg::Camera; camera->setViewport(0, 0, tex_width, tex_height); camera->setClearColor(osg::Vec4(1.0f, 1.0f, 1.0f, 0.0f)); camera->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); camera->setRenderOrder(osg::Camera::PRE_RENDER); camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT); camera->attach(osg::Camera::COLOR_BUFFER, texture.get()); camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF); camera->addChild(sub_model); osg::ref_ptr<osg::Group> root = new osg::Group; root->addChild(camera.get()); root->addChild(model.get()); osgViewer::Viewer viewer; viewer.setSceneData(root.get()); viewer.setCameraManipulator(new osgGA::TrackballManipulator); float range = 0.25f; float speed = range / 50; float delta = speed; float bias = 0.0f; osg::Vec3 eye(0.0f, -5.0f, 5.0f); while (!viewer.done()) { if (bias < -range) { delta = speed; } else if (bias > range) { delta = -speed; } bias += delta; camera->setViewMatrixAsLookAt( eye, osg::Vec3(), osg::Vec3(bias, 1.0f, 1.0f)); viewer.frame(); } return 0; } <|endoftext|>
<commit_before>#include <ctrcommon/input.hpp> #include <ctrcommon/platform.hpp> #include <ctrcommon/ui.hpp> #include <stdio.h> #include <sstream> #include <iomanip> #include <sys/dirent.h> #include <3ds.h> #include <ctrcommon/app.hpp> typedef enum { INSTALL_CIA, DELETE_CIA, DELETE_TITLE, LAUNCH_TITLE } Mode; int main(int argc, char **argv) { if(!platformInit()) { return 0; } bool ninjhax = platformIsNinjhax(); std::vector<std::string> extensions; extensions.push_back("cia"); MediaType destination = SD; Mode mode = INSTALL_CIA; bool exit = false; bool netInstall = false; u64 freeSpace = fsGetFreeSpace(destination); auto onLoop = [&]() { if(ninjhax && inputIsPressed(BUTTON_START)) { exit = true; return true; } bool breakLoop = false; if(inputIsPressed(BUTTON_L)) { if(destination == SD) { destination = NAND; } else { destination = SD; } freeSpace = fsGetFreeSpace(destination); if(mode == DELETE_TITLE) { breakLoop = true; } } if(inputIsPressed(BUTTON_R)) { if(mode == INSTALL_CIA) { mode = DELETE_CIA; } else if(mode == DELETE_CIA) { mode = DELETE_TITLE; breakLoop = true; } else if(mode == DELETE_TITLE) { mode = LAUNCH_TITLE; } else if(mode == LAUNCH_TITLE) { mode = INSTALL_CIA; breakLoop = true; } } if(inputIsPressed(BUTTON_Y)) { netInstall = true; breakLoop = true; } std::stringstream stream; stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n"; stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n"; stream << "L - Switch Destination, R - Switch Mode" << "\n"; if(mode == INSTALL_CIA) { stream << "X - Install all CIAs in the current directory" << "\n"; } else if(mode == DELETE_CIA) { stream << "X - Delete all CIAs in the current directory" << "\n"; } stream << "Y - Receive an app over the network" << "\n"; if(ninjhax) { stream << "START - Exit to launcher" << "\n"; } std::string str = stream.str(); screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255); return breakLoop; }; auto onProgress = [&](u64 pos, u64 totalSize) { std::stringstream details; details << "(" << std::fixed << std::setprecision(2) << ((double) pos / 1024.0 / 1024.0) << "MB / " << std::fixed << std::setprecision(2) << ((double) totalSize / 1024.0 / 1024.0) << "MB)" << "\n"; details << "Press B to cancel."; u32 progress = (u32) (((double) pos / (double) totalSize) * 100); uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress); inputPoll(); return !inputIsPressed(BUTTON_B); }; while(platformIsRunning()) { std::string fileTarget; App appTarget; if(mode == INSTALL_CIA || mode == DELETE_CIA) { uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) { if(inputIsPressed(BUTTON_X)) { std::stringstream confirmMsg; if(mode == INSTALL_CIA) { confirmMsg << "Install "; } else { confirmMsg << "Delete "; } confirmMsg << "all CIAs in the current directory?"; if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) { bool failed = false; std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory); for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) { std::string path = (*it).path; std::string fileName = (*it).name; if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) { if(mode == INSTALL_CIA) { AppResult ret = appInstallFile(destination, path, onProgress); if(ret != APP_SUCCESS) { std::stringstream resultMsg; resultMsg << "Install failed!" << "\n"; resultMsg << fileName << "\n"; resultMsg << appGetResultString(ret) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); failed = true; break; } } else { if(!fsDelete(path)) { std::stringstream resultMsg; resultMsg << "Delete failed!" << "\n"; resultMsg << fileName << "\n"; resultMsg << platformGetErrorString(platformGetError()) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); failed = true; break; } else { updateList = true; } } } } if(!failed) { uiPrompt(TOP_SCREEN, "Install succeeded!\n", false); } freeSpace = fsGetFreeSpace(destination); } } return onLoop(); }, [&](const std::string path, bool &updateList) { std::stringstream confirmMsg; if(mode == INSTALL_CIA) { confirmMsg << "Install "; } else { confirmMsg << "Delete "; } confirmMsg << "the selected CIA?"; if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) { std::stringstream resultMsg; if(mode == INSTALL_CIA) { resultMsg << "Install "; } else { resultMsg << "Delete "; } if(mode == INSTALL_CIA) { AppResult ret = appInstallFile(destination, path, onProgress); if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } } else { if(fsDelete(path)) { updateList = true; resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << platformGetErrorString(platformGetError()) << "\n"; } } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } return false; }); } else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) { uiSelectApp(&appTarget, destination, [&](bool &updateList) { return onLoop(); }, [&](App app, bool &updateList) { if(mode == DELETE_TITLE) { if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true)) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Deleting title..."); AppResult ret = appDelete(app); std::stringstream resultMsg; resultMsg << "Delete "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } } else if(mode == LAUNCH_TITLE) { if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Launching title..."); AppResult ret = appLaunch(app); if(ret != APP_SUCCESS) { std::stringstream resultMsg; resultMsg << "Launch failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); } else { while(true) { } } } } return false; }); } if(netInstall && !exit) { netInstall = false; screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0); RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN); if(file.fd == NULL) { continue; } std::stringstream confirmStream; confirmStream << "Install the received application?" << "\n"; confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n"; if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) { AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress); std::stringstream resultMsg; resultMsg << "Install "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); } fclose(file.fd); continue; } if(exit) { break; } } platformCleanup(); return 0; } <commit_msg>Only show network install option when in installation mode.<commit_after>#include <ctrcommon/input.hpp> #include <ctrcommon/platform.hpp> #include <ctrcommon/ui.hpp> #include <stdio.h> #include <sstream> #include <iomanip> #include <sys/dirent.h> #include <3ds.h> #include <ctrcommon/app.hpp> typedef enum { INSTALL_CIA, DELETE_CIA, DELETE_TITLE, LAUNCH_TITLE } Mode; int main(int argc, char **argv) { if(!platformInit()) { return 0; } bool ninjhax = platformIsNinjhax(); std::vector<std::string> extensions; extensions.push_back("cia"); MediaType destination = SD; Mode mode = INSTALL_CIA; bool exit = false; bool netInstall = false; u64 freeSpace = fsGetFreeSpace(destination); auto onLoop = [&]() { if(ninjhax && inputIsPressed(BUTTON_START)) { exit = true; return true; } bool breakLoop = false; if(inputIsPressed(BUTTON_L)) { if(destination == SD) { destination = NAND; } else { destination = SD; } freeSpace = fsGetFreeSpace(destination); if(mode == DELETE_TITLE) { breakLoop = true; } } if(inputIsPressed(BUTTON_R)) { if(mode == INSTALL_CIA) { mode = DELETE_CIA; } else if(mode == DELETE_CIA) { mode = DELETE_TITLE; breakLoop = true; } else if(mode == DELETE_TITLE) { mode = LAUNCH_TITLE; } else if(mode == LAUNCH_TITLE) { mode = INSTALL_CIA; breakLoop = true; } } if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) { netInstall = true; breakLoop = true; } std::stringstream stream; stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n"; stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n"; stream << "L - Switch Destination, R - Switch Mode" << "\n"; if(mode == INSTALL_CIA) { stream << "X - Install all CIAs in the current directory" << "\n"; stream << "Y - Receive an app over the network" << "\n"; } else if(mode == DELETE_CIA) { stream << "X - Delete all CIAs in the current directory" << "\n"; } if(ninjhax) { stream << "START - Exit to launcher" << "\n"; } std::string str = stream.str(); screenDrawString(str, (screenGetWidth() - screenGetStrWidth(str)) / 2, screenGetHeight() - 4 - screenGetStrHeight(str), 255, 255, 255); return breakLoop; }; auto onProgress = [&](u64 pos, u64 totalSize) { std::stringstream details; details << "(" << std::fixed << std::setprecision(2) << ((double) pos / 1024.0 / 1024.0) << "MB / " << std::fixed << std::setprecision(2) << ((double) totalSize / 1024.0 / 1024.0) << "MB)" << "\n"; details << "Press B to cancel."; u32 progress = (u32) (((double) pos / (double) totalSize) * 100); uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress); inputPoll(); return !inputIsPressed(BUTTON_B); }; while(platformIsRunning()) { std::string fileTarget; App appTarget; if(mode == INSTALL_CIA || mode == DELETE_CIA) { uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) { if(inputIsPressed(BUTTON_X)) { std::stringstream confirmMsg; if(mode == INSTALL_CIA) { confirmMsg << "Install "; } else { confirmMsg << "Delete "; } confirmMsg << "all CIAs in the current directory?"; if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) { bool failed = false; std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory); for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) { std::string path = (*it).path; std::string fileName = (*it).name; if(!fsIsDirectory(path) && fsHasExtensions(path, extensions)) { if(mode == INSTALL_CIA) { AppResult ret = appInstallFile(destination, path, onProgress); if(ret != APP_SUCCESS) { std::stringstream resultMsg; resultMsg << "Install failed!" << "\n"; resultMsg << fileName << "\n"; resultMsg << appGetResultString(ret) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); failed = true; break; } } else { if(!fsDelete(path)) { std::stringstream resultMsg; resultMsg << "Delete failed!" << "\n"; resultMsg << fileName << "\n"; resultMsg << platformGetErrorString(platformGetError()) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); failed = true; break; } else { updateList = true; } } } } if(!failed) { uiPrompt(TOP_SCREEN, "Install succeeded!\n", false); } freeSpace = fsGetFreeSpace(destination); } } return onLoop(); }, [&](const std::string path, bool &updateList) { std::stringstream confirmMsg; if(mode == INSTALL_CIA) { confirmMsg << "Install "; } else { confirmMsg << "Delete "; } confirmMsg << "the selected CIA?"; if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) { std::stringstream resultMsg; if(mode == INSTALL_CIA) { resultMsg << "Install "; } else { resultMsg << "Delete "; } if(mode == INSTALL_CIA) { AppResult ret = appInstallFile(destination, path, onProgress); if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } } else { if(fsDelete(path)) { updateList = true; resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << platformGetErrorString(platformGetError()) << "\n"; } } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } return false; }); } else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) { uiSelectApp(&appTarget, destination, [&](bool &updateList) { return onLoop(); }, [&](App app, bool &updateList) { if(mode == DELETE_TITLE) { if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true)) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Deleting title..."); AppResult ret = appDelete(app); std::stringstream resultMsg; resultMsg << "Delete "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); freeSpace = fsGetFreeSpace(destination); } } else if(mode == LAUNCH_TITLE) { if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) { updateList = true; uiDisplayMessage(TOP_SCREEN, "Launching title..."); AppResult ret = appLaunch(app); if(ret != APP_SUCCESS) { std::stringstream resultMsg; resultMsg << "Launch failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; uiPrompt(TOP_SCREEN, resultMsg.str(), false); } else { while(true) { } } } } return false; }); } if(netInstall && !exit) { netInstall = false; screenClearBuffers(BOTTOM_SCREEN, 0, 0, 0); RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN); if(file.fd == NULL) { continue; } std::stringstream confirmStream; confirmStream << "Install the received application?" << "\n"; confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)" << "\n"; if(uiPrompt(TOP_SCREEN, confirmStream.str(), true)) { AppResult ret = appInstall(destination, file.fd, file.fileSize, onProgress); std::stringstream resultMsg; resultMsg << "Install "; if(ret == APP_SUCCESS) { resultMsg << "succeeded!"; } else { resultMsg << "failed!" << "\n"; resultMsg << appGetResultString(ret) << "\n"; } uiPrompt(TOP_SCREEN, resultMsg.str(), false); } fclose(file.fd); continue; } if(exit) { break; } } platformCleanup(); return 0; } <|endoftext|>
<commit_before>// Copyright 2011 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 "webkit/renderer/compositor_bindings/web_external_texture_layer_impl.h" #include "cc/layers/texture_layer.h" #include "cc/resources/resource_update_queue.h" #include "cc/resources/single_release_callback.h" #include "cc/resources/texture_mailbox.h" #include "third_party/WebKit/public/platform/WebExternalTextureLayerClient.h" #include "third_party/WebKit/public/platform/WebExternalTextureMailbox.h" #include "third_party/WebKit/public/platform/WebFloatRect.h" #include "third_party/WebKit/public/platform/WebGraphicsContext3D.h" #include "third_party/WebKit/public/platform/WebSize.h" #include "third_party/khronos/GLES2/gl2.h" #include "webkit/renderer/compositor_bindings/web_external_bitmap_impl.h" #include "webkit/renderer/compositor_bindings/web_layer_impl.h" using cc::TextureLayer; using cc::ResourceUpdateQueue; namespace webkit { WebExternalTextureLayerImpl::WebExternalTextureLayerImpl( blink::WebExternalTextureLayerClient* client) : client_(client) { cc::TextureLayerClient* cc_client = client_ ? this : NULL; scoped_refptr<TextureLayer> layer = TextureLayer::CreateForMailbox(cc_client); layer->SetIsDrawable(true); layer_.reset(new WebLayerImpl(layer)); } WebExternalTextureLayerImpl::~WebExternalTextureLayerImpl() { static_cast<TextureLayer*>(layer_->layer())->ClearClient(); } blink::WebLayer* WebExternalTextureLayerImpl::layer() { return layer_.get(); } void WebExternalTextureLayerImpl::clearTexture() { TextureLayer *layer = static_cast<TextureLayer*>(layer_->layer()); layer->ClearTexture(); } void WebExternalTextureLayerImpl::setOpaque(bool opaque) { static_cast<TextureLayer*>(layer_->layer())->SetContentsOpaque(opaque); } void WebExternalTextureLayerImpl::setPremultipliedAlpha( bool premultiplied_alpha) { static_cast<TextureLayer*>(layer_->layer())->SetPremultipliedAlpha( premultiplied_alpha); } void WebExternalTextureLayerImpl::setBlendBackgroundColor(bool blend) { static_cast<TextureLayer*>(layer_->layer())->SetBlendBackgroundColor(blend); } void WebExternalTextureLayerImpl::setRateLimitContext(bool rate_limit) { static_cast<TextureLayer*>(layer_->layer())->SetRateLimitContext(rate_limit); } bool WebExternalTextureLayerImpl::PrepareTextureMailbox( cc::TextureMailbox* mailbox, scoped_ptr<cc::SingleReleaseCallback>* release_callback, bool use_shared_memory) { blink::WebExternalTextureMailbox client_mailbox; WebExternalBitmapImpl* bitmap = NULL; if (use_shared_memory) bitmap = AllocateBitmap(); if (!client_->prepareMailbox(&client_mailbox, bitmap)) { if (bitmap) free_bitmaps_.push_back(bitmap); return false; } gpu::Mailbox name; name.SetName(client_mailbox.name); if (bitmap) { *mailbox = cc::TextureMailbox(bitmap->shared_memory(), bitmap->size()); } else { *mailbox = cc::TextureMailbox(name, GL_TEXTURE_2D, client_mailbox.syncPoint); } if (mailbox->IsValid()) { *release_callback = cc::SingleReleaseCallback::Create(base::Bind( &WebExternalTextureLayerImpl::DidReleaseMailbox, this->AsWeakPtr(), client_mailbox, bitmap)); } return true; } WebExternalBitmapImpl* WebExternalTextureLayerImpl::AllocateBitmap() { if (!free_bitmaps_.empty()) { WebExternalBitmapImpl* result = free_bitmaps_.back(); free_bitmaps_.weak_erase(free_bitmaps_.end() - 1); return result; } return new WebExternalBitmapImpl; } // static void WebExternalTextureLayerImpl::DidReleaseMailbox( base::WeakPtr<WebExternalTextureLayerImpl> layer, const blink::WebExternalTextureMailbox& mailbox, WebExternalBitmapImpl* bitmap, unsigned sync_point, bool lost_resource) { if (lost_resource || !layer) { delete bitmap; return; } blink::WebExternalTextureMailbox available_mailbox; memcpy(available_mailbox.name, mailbox.name, sizeof(available_mailbox.name)); available_mailbox.syncPoint = sync_point; if (bitmap) layer->free_bitmaps_.push_back(bitmap); layer->client_->mailboxReleased(available_mailbox); } } // namespace webkit <commit_msg>Pass information about overlay support in a mailbox from blink to CC.<commit_after>// Copyright 2011 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 "webkit/renderer/compositor_bindings/web_external_texture_layer_impl.h" #include "cc/layers/texture_layer.h" #include "cc/resources/resource_update_queue.h" #include "cc/resources/single_release_callback.h" #include "cc/resources/texture_mailbox.h" #include "third_party/WebKit/public/platform/WebExternalTextureLayerClient.h" #include "third_party/WebKit/public/platform/WebExternalTextureMailbox.h" #include "third_party/WebKit/public/platform/WebFloatRect.h" #include "third_party/WebKit/public/platform/WebGraphicsContext3D.h" #include "third_party/WebKit/public/platform/WebSize.h" #include "third_party/khronos/GLES2/gl2.h" #include "webkit/renderer/compositor_bindings/web_external_bitmap_impl.h" #include "webkit/renderer/compositor_bindings/web_layer_impl.h" using cc::TextureLayer; using cc::ResourceUpdateQueue; namespace webkit { WebExternalTextureLayerImpl::WebExternalTextureLayerImpl( blink::WebExternalTextureLayerClient* client) : client_(client) { cc::TextureLayerClient* cc_client = client_ ? this : NULL; scoped_refptr<TextureLayer> layer = TextureLayer::CreateForMailbox(cc_client); layer->SetIsDrawable(true); layer_.reset(new WebLayerImpl(layer)); } WebExternalTextureLayerImpl::~WebExternalTextureLayerImpl() { static_cast<TextureLayer*>(layer_->layer())->ClearClient(); } blink::WebLayer* WebExternalTextureLayerImpl::layer() { return layer_.get(); } void WebExternalTextureLayerImpl::clearTexture() { TextureLayer *layer = static_cast<TextureLayer*>(layer_->layer()); layer->ClearTexture(); } void WebExternalTextureLayerImpl::setOpaque(bool opaque) { static_cast<TextureLayer*>(layer_->layer())->SetContentsOpaque(opaque); } void WebExternalTextureLayerImpl::setPremultipliedAlpha( bool premultiplied_alpha) { static_cast<TextureLayer*>(layer_->layer())->SetPremultipliedAlpha( premultiplied_alpha); } void WebExternalTextureLayerImpl::setBlendBackgroundColor(bool blend) { static_cast<TextureLayer*>(layer_->layer())->SetBlendBackgroundColor(blend); } void WebExternalTextureLayerImpl::setRateLimitContext(bool rate_limit) { static_cast<TextureLayer*>(layer_->layer())->SetRateLimitContext(rate_limit); } bool WebExternalTextureLayerImpl::PrepareTextureMailbox( cc::TextureMailbox* mailbox, scoped_ptr<cc::SingleReleaseCallback>* release_callback, bool use_shared_memory) { blink::WebExternalTextureMailbox client_mailbox; WebExternalBitmapImpl* bitmap = NULL; if (use_shared_memory) bitmap = AllocateBitmap(); if (!client_->prepareMailbox(&client_mailbox, bitmap)) { if (bitmap) free_bitmaps_.push_back(bitmap); return false; } gpu::Mailbox name; name.SetName(client_mailbox.name); if (bitmap) { *mailbox = cc::TextureMailbox(bitmap->shared_memory(), bitmap->size()); } else { *mailbox = cc::TextureMailbox(name, GL_TEXTURE_2D, client_mailbox.syncPoint); } mailbox->set_allow_overlay(client_mailbox.allowOverlay); if (mailbox->IsValid()) { *release_callback = cc::SingleReleaseCallback::Create(base::Bind( &WebExternalTextureLayerImpl::DidReleaseMailbox, this->AsWeakPtr(), client_mailbox, bitmap)); } return true; } WebExternalBitmapImpl* WebExternalTextureLayerImpl::AllocateBitmap() { if (!free_bitmaps_.empty()) { WebExternalBitmapImpl* result = free_bitmaps_.back(); free_bitmaps_.weak_erase(free_bitmaps_.end() - 1); return result; } return new WebExternalBitmapImpl; } // static void WebExternalTextureLayerImpl::DidReleaseMailbox( base::WeakPtr<WebExternalTextureLayerImpl> layer, const blink::WebExternalTextureMailbox& mailbox, WebExternalBitmapImpl* bitmap, unsigned sync_point, bool lost_resource) { if (lost_resource || !layer) { delete bitmap; return; } blink::WebExternalTextureMailbox available_mailbox; memcpy(available_mailbox.name, mailbox.name, sizeof(available_mailbox.name)); available_mailbox.syncPoint = sync_point; if (bitmap) layer->free_bitmaps_.push_back(bitmap); layer->client_->mailboxReleased(available_mailbox); } } // namespace webkit <|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // Copyright (c) 2015, Jeff Hutchinson // 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 D3D11Test nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- // Require MSVC compiler for this application #ifndef _MSC_VER #error "You must use MSVC to compile this application." #endif // _MSC_VER #include <stdlib.h> #include <SDL.h> #include <SDL_syswm.h> // Windows specific header + D3D11 SDK header #include <Windows.h> #include <d3d11.h> // link with D3D11.lib #pragma comment(lib, "D3D11.lib") // SDL2 hack. #ifdef main #undef main #endif // main // used to signify that the variable is being outputted #define OUT HWND getWindowHandle(SDL_Window *window); bool createD3D11DeviceAndSwapChain(HWND window, OUT ID3D11Device *&device, OUT IDXGISwapChain *&swapChain, OUT ID3D11DeviceContext *&context); void render(ID3D11Device *device, ID3D11DeviceContext *context); int main(int argc, const char **argv) { SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS); // create window SDL_Window *window = SDL_CreateWindow("D3D11 Test Application", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1366, 768, SDL_WINDOW_SHOWN); if (window == nullptr) { SDL_Quit(); return 1; } // get window handle from the window HWND windowHandle = getWindowHandle(window); if (windowHandle == nullptr) { SDL_DestroyWindow(window); SDL_Quit(); return 2; } ID3D11Device *device = nullptr; IDXGISwapChain *swapChain = nullptr; ID3D11DeviceContext *context = nullptr; bool r = createD3D11DeviceAndSwapChain(windowHandle, device, swapChain, context); if (r == false) { SDL_DestroyWindow(window); SDL_Quit(); return 3; } // render target view ID3D11RenderTargetView *rtv = nullptr; { ID3D11Texture2D *backBuffer = nullptr; if (swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBuffer) != S_OK) { SDL_DestroyWindow(window); SDL_Quit(); return 4; } HRESULT check = device->CreateRenderTargetView(backBuffer, NULL, &rtv); // release back buffer texture as it already has been set. backBuffer->Release(); if (check != S_OK) { SDL_DestroyWindow(window); SDL_Quit(); return 5; } context->OMSetRenderTargets(1, &rtv, NULL); } // set viewport D3D11_VIEWPORT vp; vp.Width = (FLOAT)1366; vp.Height = (FLOAT)768; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0; vp.TopLeftY = 0; context->RSSetViewports(1, &vp); SDL_Event event; bool running = true; while (running) { // Run event loop. while (SDL_PollEvent(&event)) { // check to see if we fired a quit event. If we did, we're done // running the program. if (event.type == SDL_QUIT) { running = false; break; } } // clear color static float clearColor[4] = { 1.0f, 0.0f, 0.0f, 1.0f }; context->ClearRenderTargetView(rtv, clearColor); render(device, context); // swap buffer swapChain->Present(0, 0); } // cleanup SDL_DestroyWindow(window); SDL_Quit(); return 0; } HWND getWindowHandle(SDL_Window *window) { SDL_SysWMinfo info; SDL_VERSION(&info.version); if (!SDL_GetWindowWMInfo(window, &info)) return nullptr; return info.info.win.window; } bool createD3D11DeviceAndSwapChain(HWND window, OUT ID3D11Device *&device, OUT IDXGISwapChain *&swapChain, OUT ID3D11DeviceContext *&context) { // create swap chain description DXGI_SWAP_CHAIN_DESC swapDesc; ZeroMemory(&swapDesc, sizeof(DXGI_SWAP_CHAIN_DESC)); swapDesc.BufferCount = 1; // how many back buffers swapDesc.BufferDesc.Width = 1366; // window width swapDesc.BufferDesc.Height = 768; // window height swapDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // standard backbuffer format swapDesc.BufferDesc.RefreshRate.Numerator = 60; // vsync swapDesc.BufferDesc.RefreshRate.Denominator = 1; // vsync swapDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // yes we are rendering to a window swapDesc.OutputWindow = window; // the window we are outputting to swapDesc.SampleDesc.Count = 1; swapDesc.SampleDesc.Quality = 0; // Antialiasing swapDesc.Windowed = true; // we are not in fullscreen // request feature level 11_0 D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0; UINT featureLevelCount = 1; D3D_FEATURE_LEVEL featureLevelSupported; HRESULT r = D3D11CreateDeviceAndSwapChain( NULL, // adapter D3D_DRIVER_TYPE_HARDWARE, // device type NULL, // do we want software emulation for features not supported? 0, // device flags &featureLevel, // feature level(s) requested featureLevelCount, // amount of feature level(s) requested D3D11_SDK_VERSION, // version of the DX11 SDK &swapDesc, // swap chain description &swapChain, // OUT the swap chain pointer &device, // OUT the d3d11 device &featureLevelSupported, // OUT the d3d11 feature level that is supported on this computer. &context // OUT the d3d11 context ); if (r == S_OK) return true; return false; } void render(ID3D11Device *device, ID3D11DeviceContext *context) { }<commit_msg>cleanup<commit_after>//----------------------------------------------------------------------------- // Copyright (c) 2015, Jeff Hutchinson // 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 D3D11Test nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- // Require MSVC compiler for this application #ifndef _MSC_VER #error "You must use MSVC to compile this application." #endif // _MSC_VER #include <stdlib.h> #include <SDL.h> #include <SDL_syswm.h> // Windows specific header + D3D11 SDK header #include <Windows.h> #include <d3d11.h> // link with D3D11.lib #pragma comment(lib, "D3D11.lib") // SDL2 hack. #ifdef main #undef main #endif // main // used to signify that the variable is being outputted #define OUT HWND getWindowHandle(SDL_Window *window); bool createD3D11DeviceAndSwapChain(HWND window, OUT ID3D11Device *&device, OUT IDXGISwapChain *&swapChain, OUT ID3D11DeviceContext *&context); void render(ID3D11Device *device, ID3D11DeviceContext *context); int main(int argc, const char **argv) { SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS); // create window SDL_Window *window = SDL_CreateWindow("D3D11 Test Application", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 1366, 768, SDL_WINDOW_SHOWN); if (window == nullptr) { SDL_Quit(); return 1; } // get window handle from the window HWND windowHandle = getWindowHandle(window); if (windowHandle == nullptr) { SDL_DestroyWindow(window); SDL_Quit(); return 2; } ID3D11Device *device = nullptr; IDXGISwapChain *swapChain = nullptr; ID3D11DeviceContext *context = nullptr; bool r = createD3D11DeviceAndSwapChain(windowHandle, device, swapChain, context); if (r == false) { SDL_DestroyWindow(window); SDL_Quit(); return 3; } // render target view ID3D11RenderTargetView *rtv = nullptr; { ID3D11Texture2D *backBuffer = nullptr; if (swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<LPVOID*>(&backBuffer)) != S_OK) { SDL_DestroyWindow(window); SDL_Quit(); return 4; } HRESULT check = device->CreateRenderTargetView(backBuffer, NULL, &rtv); // release back buffer texture as it already has been set. backBuffer->Release(); if (check != S_OK) { SDL_DestroyWindow(window); SDL_Quit(); return 5; } context->OMSetRenderTargets(1, &rtv, NULL); } // set viewport D3D11_VIEWPORT vp; vp.Width = 1366.0f; vp.Height = 768.0f; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0; vp.TopLeftY = 0; context->RSSetViewports(1, &vp); // clear color static float clearColor[4] = { 1.0f, 0.0f, 0.0f, 1.0f }; SDL_Event event; bool running = true; while (running) { // Run event loop. while (SDL_PollEvent(&event)) { // check to see if we fired a quit event. If we did, we're done // running the program. if (event.type == SDL_QUIT) { running = false; break; } } // set canvas clear color context->ClearRenderTargetView(rtv, clearColor); // perform any additional render logic render(device, context); // swap buffer swapChain->Present(0, 0); } // cleanup SDL_DestroyWindow(window); SDL_Quit(); return 0; } HWND getWindowHandle(SDL_Window *window) { SDL_SysWMinfo info; SDL_VERSION(&info.version); if (!SDL_GetWindowWMInfo(window, &info)) return nullptr; return info.info.win.window; } bool createD3D11DeviceAndSwapChain(HWND window, OUT ID3D11Device *&device, OUT IDXGISwapChain *&swapChain, OUT ID3D11DeviceContext *&context) { // create swap chain description DXGI_SWAP_CHAIN_DESC swapDesc; ZeroMemory(&swapDesc, sizeof(DXGI_SWAP_CHAIN_DESC)); swapDesc.BufferCount = 1; // how many back buffers swapDesc.BufferDesc.Width = 1366; // window width swapDesc.BufferDesc.Height = 768; // window height swapDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // standard backbuffer format swapDesc.BufferDesc.RefreshRate.Numerator = 60; // vsync swapDesc.BufferDesc.RefreshRate.Denominator = 1; // vsync swapDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // yes we are rendering to a window swapDesc.OutputWindow = window; // the window we are outputting to swapDesc.SampleDesc.Count = 1; swapDesc.SampleDesc.Quality = 0; // Antialiasing swapDesc.Windowed = true; // we are not in fullscreen // request feature level 11_0 D3D_FEATURE_LEVEL featureLevel = D3D_FEATURE_LEVEL_11_0; UINT featureLevelCount = 1; D3D_FEATURE_LEVEL featureLevelSupported; HRESULT r = D3D11CreateDeviceAndSwapChain( NULL, // adapter D3D_DRIVER_TYPE_HARDWARE, // device type NULL, // do we want software emulation for features not supported? 0, // device flags &featureLevel, // feature level(s) requested featureLevelCount, // amount of feature level(s) requested D3D11_SDK_VERSION, // version of the DX11 SDK &swapDesc, // swap chain description &swapChain, // OUT the swap chain pointer &device, // OUT the d3d11 device &featureLevelSupported, // OUT the d3d11 feature level that is supported on this computer. &context // OUT the d3d11 context ); if (r == S_OK) return true; return false; } void render(ID3D11Device *device, ID3D11DeviceContext *context) { }<|endoftext|>
<commit_before><commit_msg>include config.h first otherwise bad things happen<commit_after><|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 "webkit/glue/webcursor.h" #include <gdk/gdk.h> #include <gtk/gtk.h> #include "base/logging.h" #include "third_party/WebKit/WebKit/chromium/public/WebCursorInfo.h" using WebKit::WebCursorInfo; namespace { // webcursor_gtk_data.h is taken directly from WebKit's CursorGtk.h. #include "webkit/glue/webcursor_gtk_data.h" // This helper function is taken directly from WebKit's CursorGtk.cpp. // It attempts to create a custom cursor from the data inlined in // webcursor_gtk_data.h. GdkCursor* GetInlineCustomCursor(CustomCursorType type) { const CustomCursor& custom = CustomCursors[type]; GdkCursor* cursor = gdk_cursor_new_from_name(gdk_display_get_default(), custom.name); if (!cursor) { const GdkColor fg = { 0, 0, 0, 0 }; const GdkColor bg = { 65535, 65535, 65535, 65535 }; GdkPixmap* source = gdk_bitmap_create_from_data(NULL, custom.bits, 32, 32); GdkPixmap* mask = gdk_bitmap_create_from_data(NULL, custom.mask_bits, 32, 32); cursor = gdk_cursor_new_from_pixmap(source, mask, &fg, &bg, custom.hot_x, custom.hot_y); g_object_unref(source); g_object_unref(mask); } return cursor; } // For GTK 2.16 and beyond, GDK_BLANK_CURSOR is available. Before, we have to // use a custom cursor. #if !GTK_CHECK_VERSION(2, 16, 0) // Get/create a custom cursor which is invisible. GdkCursor* GetInvisibleCustomCursor() { const char bits[] = { 0 }; const GdkColor color = { 0, 0, 0, 0 }; GdkPixmap* bitmap = gdk_bitmap_create_from_data(NULL, bits, 1, 1); GdkCursor* cursor = gdk_cursor_new_from_pixmap(bitmap, bitmap, &color, &color, 0, 0); g_object_unref(bitmap); return cursor; } #endif } // end anonymous namespace int WebCursor::GetCursorType() const { // http://library.gnome.org/devel/gdk/2.12/gdk-Cursors.html has images // of the default X theme, but beware that the user's cursor theme can // change everything. switch (type_) { case WebCursorInfo::TypePointer: return GDK_LAST_CURSOR; case WebCursorInfo::TypeCross: return GDK_CROSS; case WebCursorInfo::TypeHand: return GDK_HAND2; case WebCursorInfo::TypeIBeam: return GDK_XTERM; case WebCursorInfo::TypeWait: return GDK_WATCH; case WebCursorInfo::TypeHelp: return GDK_QUESTION_ARROW; case WebCursorInfo::TypeEastResize: return GDK_RIGHT_SIDE; case WebCursorInfo::TypeNorthResize: return GDK_TOP_SIDE; case WebCursorInfo::TypeNorthEastResize: return GDK_TOP_RIGHT_CORNER; case WebCursorInfo::TypeNorthWestResize: return GDK_TOP_LEFT_CORNER; case WebCursorInfo::TypeSouthResize: return GDK_BOTTOM_SIDE; case WebCursorInfo::TypeSouthEastResize: return GDK_BOTTOM_RIGHT_CORNER; case WebCursorInfo::TypeSouthWestResize: return GDK_BOTTOM_LEFT_CORNER; case WebCursorInfo::TypeWestResize: return GDK_LEFT_SIDE; case WebCursorInfo::TypeNorthSouthResize: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeEastWestResize: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeNorthEastSouthWestResize: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeNorthWestSouthEastResize: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeColumnResize: return GDK_SB_H_DOUBLE_ARROW; // TODO(evanm): is this correct? case WebCursorInfo::TypeRowResize: return GDK_SB_V_DOUBLE_ARROW; // TODO(evanm): is this correct? case WebCursorInfo::TypeMiddlePanning: return GDK_FLEUR; case WebCursorInfo::TypeEastPanning: return GDK_SB_RIGHT_ARROW; case WebCursorInfo::TypeNorthPanning: return GDK_SB_UP_ARROW; case WebCursorInfo::TypeNorthEastPanning: return GDK_TOP_RIGHT_CORNER; case WebCursorInfo::TypeNorthWestPanning: return GDK_TOP_LEFT_CORNER; case WebCursorInfo::TypeSouthPanning: return GDK_SB_DOWN_ARROW; case WebCursorInfo::TypeSouthEastPanning: return GDK_BOTTOM_RIGHT_CORNER; case WebCursorInfo::TypeSouthWestPanning: return GDK_BOTTOM_LEFT_CORNER; case WebCursorInfo::TypeWestPanning: return GDK_SB_LEFT_ARROW; case WebCursorInfo::TypeMove: return GDK_FLEUR; case WebCursorInfo::TypeVerticalText: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeCell: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeContextMenu: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeAlias: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeProgress: return GDK_WATCH; case WebCursorInfo::TypeNoDrop: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeCopy: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeNone: // See comment above |GetInvisibleCustomCursor()|. #if !GTK_CHECK_VERSION(2, 16, 0) return GDK_CURSOR_IS_PIXMAP; #else return GDK_BLANK_CURSOR; #endif case WebCursorInfo::TypeNotAllowed: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeZoomIn: case WebCursorInfo::TypeZoomOut: case WebCursorInfo::TypeCustom: return GDK_CURSOR_IS_PIXMAP; } NOTREACHED(); return GDK_LAST_CURSOR; } GdkCursor* WebCursor::GetCustomCursor() const { switch (type_) { // See comment above |GetInvisibleCustomCursor()|. #if !GTK_CHECK_VERSION(2, 16, 0) case WebCursorInfo::TypeNone: return GetInvisibleCustomCursor(); #endif case WebCursorInfo::TypeZoomIn: return GetInlineCustomCursor(CustomCursorZoomIn); case WebCursorInfo::TypeZoomOut: return GetInlineCustomCursor(CustomCursorZoomOut); } if (type_ != WebCursorInfo::TypeCustom) { NOTREACHED(); return NULL; } const guchar* data = reinterpret_cast<const guchar*>(&custom_data_[0]); GdkPixbuf* pixbuf = gdk_pixbuf_new_from_data(data, GDK_COLORSPACE_RGB, TRUE, // has_alpha 8, // bits_per_sample custom_size_.width(), // width custom_size_.height(), // height custom_size_.width() * 4, // row stride NULL, // data destroy function NULL); // data destroy function extra data GdkCursor* cursor = gdk_cursor_new_from_pixbuf(gdk_display_get_default(), pixbuf, hotspot_.x(), hotspot_.y()); gdk_pixbuf_unref(pixbuf); return cursor; } void WebCursor::InitPlatformData() { return; } bool WebCursor::SerializePlatformData(Pickle* pickle) const { return true; } bool WebCursor::DeserializePlatformData(const Pickle* pickle, void** iter) { return true; } bool WebCursor::IsPlatformDataEqual(const WebCursor& other) const { return true; } void WebCursor::CleanupPlatformData() { return; } void WebCursor::CopyPlatformData(const WebCursor& other) { return; } <commit_msg>GTK: fix decoding of custom cursor bytes.<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 "webkit/glue/webcursor.h" #include <gdk/gdk.h> #include <gtk/gtk.h> #include "base/logging.h" #include "gfx/gtk_util.h" #include "third_party/WebKit/WebKit/chromium/public/WebCursorInfo.h" using WebKit::WebCursorInfo; namespace { // webcursor_gtk_data.h is taken directly from WebKit's CursorGtk.h. #include "webkit/glue/webcursor_gtk_data.h" // This helper function is taken directly from WebKit's CursorGtk.cpp. // It attempts to create a custom cursor from the data inlined in // webcursor_gtk_data.h. GdkCursor* GetInlineCustomCursor(CustomCursorType type) { const CustomCursor& custom = CustomCursors[type]; GdkCursor* cursor = gdk_cursor_new_from_name(gdk_display_get_default(), custom.name); if (!cursor) { const GdkColor fg = { 0, 0, 0, 0 }; const GdkColor bg = { 65535, 65535, 65535, 65535 }; GdkPixmap* source = gdk_bitmap_create_from_data(NULL, custom.bits, 32, 32); GdkPixmap* mask = gdk_bitmap_create_from_data(NULL, custom.mask_bits, 32, 32); cursor = gdk_cursor_new_from_pixmap(source, mask, &fg, &bg, custom.hot_x, custom.hot_y); g_object_unref(source); g_object_unref(mask); } return cursor; } // For GTK 2.16 and beyond, GDK_BLANK_CURSOR is available. Before, we have to // use a custom cursor. #if !GTK_CHECK_VERSION(2, 16, 0) // Get/create a custom cursor which is invisible. GdkCursor* GetInvisibleCustomCursor() { const char bits[] = { 0 }; const GdkColor color = { 0, 0, 0, 0 }; GdkPixmap* bitmap = gdk_bitmap_create_from_data(NULL, bits, 1, 1); GdkCursor* cursor = gdk_cursor_new_from_pixmap(bitmap, bitmap, &color, &color, 0, 0); g_object_unref(bitmap); return cursor; } #endif } // end anonymous namespace int WebCursor::GetCursorType() const { // http://library.gnome.org/devel/gdk/2.12/gdk-Cursors.html has images // of the default X theme, but beware that the user's cursor theme can // change everything. switch (type_) { case WebCursorInfo::TypePointer: return GDK_LAST_CURSOR; case WebCursorInfo::TypeCross: return GDK_CROSS; case WebCursorInfo::TypeHand: return GDK_HAND2; case WebCursorInfo::TypeIBeam: return GDK_XTERM; case WebCursorInfo::TypeWait: return GDK_WATCH; case WebCursorInfo::TypeHelp: return GDK_QUESTION_ARROW; case WebCursorInfo::TypeEastResize: return GDK_RIGHT_SIDE; case WebCursorInfo::TypeNorthResize: return GDK_TOP_SIDE; case WebCursorInfo::TypeNorthEastResize: return GDK_TOP_RIGHT_CORNER; case WebCursorInfo::TypeNorthWestResize: return GDK_TOP_LEFT_CORNER; case WebCursorInfo::TypeSouthResize: return GDK_BOTTOM_SIDE; case WebCursorInfo::TypeSouthEastResize: return GDK_BOTTOM_RIGHT_CORNER; case WebCursorInfo::TypeSouthWestResize: return GDK_BOTTOM_LEFT_CORNER; case WebCursorInfo::TypeWestResize: return GDK_LEFT_SIDE; case WebCursorInfo::TypeNorthSouthResize: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeEastWestResize: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeNorthEastSouthWestResize: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeNorthWestSouthEastResize: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeColumnResize: return GDK_SB_H_DOUBLE_ARROW; // TODO(evanm): is this correct? case WebCursorInfo::TypeRowResize: return GDK_SB_V_DOUBLE_ARROW; // TODO(evanm): is this correct? case WebCursorInfo::TypeMiddlePanning: return GDK_FLEUR; case WebCursorInfo::TypeEastPanning: return GDK_SB_RIGHT_ARROW; case WebCursorInfo::TypeNorthPanning: return GDK_SB_UP_ARROW; case WebCursorInfo::TypeNorthEastPanning: return GDK_TOP_RIGHT_CORNER; case WebCursorInfo::TypeNorthWestPanning: return GDK_TOP_LEFT_CORNER; case WebCursorInfo::TypeSouthPanning: return GDK_SB_DOWN_ARROW; case WebCursorInfo::TypeSouthEastPanning: return GDK_BOTTOM_RIGHT_CORNER; case WebCursorInfo::TypeSouthWestPanning: return GDK_BOTTOM_LEFT_CORNER; case WebCursorInfo::TypeWestPanning: return GDK_SB_LEFT_ARROW; case WebCursorInfo::TypeMove: return GDK_FLEUR; case WebCursorInfo::TypeVerticalText: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeCell: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeContextMenu: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeAlias: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeProgress: return GDK_WATCH; case WebCursorInfo::TypeNoDrop: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeCopy: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeNone: // See comment above |GetInvisibleCustomCursor()|. #if !GTK_CHECK_VERSION(2, 16, 0) return GDK_CURSOR_IS_PIXMAP; #else return GDK_BLANK_CURSOR; #endif case WebCursorInfo::TypeNotAllowed: NOTIMPLEMENTED(); return GDK_LAST_CURSOR; case WebCursorInfo::TypeZoomIn: case WebCursorInfo::TypeZoomOut: case WebCursorInfo::TypeCustom: return GDK_CURSOR_IS_PIXMAP; } NOTREACHED(); return GDK_LAST_CURSOR; } GdkCursor* WebCursor::GetCustomCursor() const { switch (type_) { // See comment above |GetInvisibleCustomCursor()|. #if !GTK_CHECK_VERSION(2, 16, 0) case WebCursorInfo::TypeNone: return GetInvisibleCustomCursor(); #endif case WebCursorInfo::TypeZoomIn: return GetInlineCustomCursor(CustomCursorZoomIn); case WebCursorInfo::TypeZoomOut: return GetInlineCustomCursor(CustomCursorZoomOut); } if (type_ != WebCursorInfo::TypeCustom) { NOTREACHED(); return NULL; } SkBitmap bitmap; bitmap.setConfig(SkBitmap::kARGB_8888_Config, custom_size_.width(), custom_size_.height()); bitmap.allocPixels(); memcpy(bitmap.getAddr32(0, 0), custom_data_.data(), custom_data_.size()); GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&bitmap); GdkCursor* cursor = gdk_cursor_new_from_pixbuf(gdk_display_get_default(), pixbuf, hotspot_.x(), hotspot_.y()); gdk_pixbuf_unref(pixbuf); return cursor; } void WebCursor::InitPlatformData() { return; } bool WebCursor::SerializePlatformData(Pickle* pickle) const { return true; } bool WebCursor::DeserializePlatformData(const Pickle* pickle, void** iter) { return true; } bool WebCursor::IsPlatformDataEqual(const WebCursor& other) const { return true; } void WebCursor::CleanupPlatformData() { return; } void WebCursor::CopyPlatformData(const WebCursor& other) { return; } <|endoftext|>
<commit_before>// Copyright (c) 2016, Joseph Mirabel // Authors: Joseph Mirabel ([email protected]) // // This file is part of hpp-core. // hpp-core is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // hpp-core 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core. If not, see <http://www.gnu.org/licenses/>. #include <hpp/core/relative-motion.hh> #include <hpp/model/device.hh> #include <hpp/model/joint.hh> #include <hpp/constraints/relative-transformation.hh> #include <hpp/core/constraint-set.hh> #include <hpp/core/config-projector.hh> #include <hpp/core/locked-joint.hh> namespace hpp { namespace core { namespace { inline void symSet (RelativeMotion::matrix_type& m, size_type i0, size_type i1, RelativeMotion::RelativeMotionType t) { m(i0,i1) = m(i1,i0) = t; } inline JointPtr_t getNonAnchorParent (const JointPtr_t j) { JointPtr_t parent = j; // Find the closest non-fixed parent in the kinematic chain while ( ((parent = parent->parentJoint()) != NULL) && parent->numberDof() == 0) {} return parent; } inline size_type index (const JointPtr_t j, const size_type& idIfNull) { if (j == NULL) return idIfNull; else return j->rankInVelocity(); } } RelativeMotion::matrix_type RelativeMotion::matrix (const DevicePtr_t& dev) { assert (dev); const size_type N = dev->numberDof () + 1; matrix_type matrix (N, N); matrix.setConstant (Unconstrained); matrix.diagonal().setConstant(Constrained); return matrix; } void RelativeMotion::fromConstraint (matrix_type& matrix, const DevicePtr_t& robot, const ConstraintSetPtr_t& c) { using constraints::RelativeTransformation; using constraints::RelativeTransformationPtr_t; assert (robot); assert (c); const size_type N = robot->numberDof () + 1; if (matrix.rows() != N || matrix.cols() != N) throw std::invalid_argument ("Wrong RelativeMotion::matrix_type size"); ConfigProjectorPtr_t proj = c->configProjector(); if (!proj) return; // Loop over the LockedJoint const LockedJoints_t& lj = proj->lockedJoints (); for (LockedJoints_t::const_iterator it = lj.begin (); it != lj.end (); ++it) { JointPtr_t j; try { // Extra dofs and partial locked joints have a name that won't be // recognized by Device::getJointByName. So they can be filtered // this way. j = robot->getJointByName ((*it)->jointName()); } catch (const std::runtime_error& e) { hppDout (info, "Joint not found:" << e.what ()); continue; } bool cstRHS = (*it)->comparisonType()->constantRightHandSide(); const size_type i1 = index(j, N-1), i2 = index(getNonAnchorParent(j),N-1); recurseSetRelMotion (matrix, i1, i2, (cstRHS ? Constrained : Parameterized)); } // Loop over the DifferentiableFunction const NumericalConstraints_t& ncs = proj->numericalConstraints (); for (NumericalConstraints_t::const_iterator _ncs = ncs.begin(); _ncs != ncs.end(); ++_ncs) { const NumericalConstraint& nc = **_ncs; if (nc.comparisonType()->constantRightHandSide()) { RelativeTransformationPtr_t rt = HPP_DYNAMIC_PTR_CAST(RelativeTransformation, nc.functionPtr()); if (!rt && rt->outputSize() != 6) continue; const size_type i1 = index(rt->joint1(), N-1), i2 = index(rt->joint2(), N-1); bool cstRHS = nc.comparisonType()->constantRightHandSide(); recurseSetRelMotion (matrix, i1, i2, (cstRHS ? Constrained : Parameterized)); } } } void RelativeMotion::recurseSetRelMotion(matrix_type& matrix, const size_type& i1, const size_type& i2, const RelativeMotion::RelativeMotionType& type) { bool param = (type == Parameterized); RelativeMotionType t = Unconstrained; if (type == Unconstrained) return; symSet(matrix, i1, i2, type); // i1 to i3 for (size_type i3 = 0; i3 < matrix.rows(); ++i3) { if (i3 == i1) continue; if (i3 == i2) continue; if (matrix(i2,i3) != Unconstrained) { t = (!param && matrix(i2,i3) == Constrained) ? Constrained : Parameterized; symSet(matrix, i1, i3, t); } } for (size_type i0 = 0; i0 < matrix.rows(); ++i0) { if (i0 == i2) continue; if (i0 == i1) continue; // i0 to i2 if (matrix(i0,i1) != Unconstrained) { t = (!param && matrix(i0,i1) == Constrained) ? Constrained : Parameterized; symSet (matrix, i0, i2 ,t); } // from i0 to i3 if (matrix(i0,i1) == Unconstrained) continue; for (size_type i3 = 0; i3 < matrix.rows(); ++i3) { if (i3 == i2) continue; if (i3 == i1) continue; if (i3 == i0) continue; if (matrix(i2,i3) == Unconstrained) continue; t = (!param && matrix(i0,i1) == Constrained && matrix(i2,i3) == Constrained) ? Constrained : Parameterized; symSet (matrix, i0, i3, t); } } } } // namespace core } // namespace hpp <commit_msg>Fix bug in RelativeMotion matrix computation<commit_after>// Copyright (c) 2016, Joseph Mirabel // Authors: Joseph Mirabel ([email protected]) // // This file is part of hpp-core. // hpp-core is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // hpp-core 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-core. If not, see <http://www.gnu.org/licenses/>. #include <hpp/core/relative-motion.hh> #include <hpp/model/device.hh> #include <hpp/model/joint.hh> #include <hpp/constraints/relative-transformation.hh> #include <hpp/core/constraint-set.hh> #include <hpp/core/config-projector.hh> #include <hpp/core/locked-joint.hh> namespace hpp { namespace core { namespace { inline void symSet (RelativeMotion::matrix_type& m, size_type i0, size_type i1, RelativeMotion::RelativeMotionType t) { m(i0,i1) = m(i1,i0) = t; } inline JointPtr_t getNonAnchorParent (const JointPtr_t j) { JointPtr_t parent = j; // Find the closest non-fixed parent in the kinematic chain while ( ((parent = parent->parentJoint()) != NULL) && parent->numberDof() == 0) {} return parent; } inline size_type index (const JointPtr_t j, const size_type& idIfNull) { if (j == NULL) return idIfNull; else return j->rankInVelocity(); } } RelativeMotion::matrix_type RelativeMotion::matrix (const DevicePtr_t& dev) { assert (dev); const size_type N = dev->numberDof () + 1; matrix_type matrix (N, N); matrix.setConstant (Unconstrained); matrix.diagonal().setConstant(Constrained); return matrix; } void RelativeMotion::fromConstraint (matrix_type& matrix, const DevicePtr_t& robot, const ConstraintSetPtr_t& c) { using constraints::RelativeTransformation; using constraints::RelativeTransformationPtr_t; assert (robot); assert (c); const size_type N = robot->numberDof () + 1; if (matrix.rows() != N || matrix.cols() != N) throw std::invalid_argument ("Wrong RelativeMotion::matrix_type size"); ConfigProjectorPtr_t proj = c->configProjector(); if (!proj) return; // Loop over the LockedJoint const LockedJoints_t& lj = proj->lockedJoints (); for (LockedJoints_t::const_iterator it = lj.begin (); it != lj.end (); ++it) { JointPtr_t j; try { // Extra dofs and partial locked joints have a name that won't be // recognized by Device::getJointByName. So they can be filtered // this way. j = robot->getJointByName ((*it)->jointName()); } catch (const std::runtime_error& e) { hppDout (info, "Joint not found:" << e.what ()); continue; } bool cstRHS = (*it)->comparisonType()->constantRightHandSide(); const size_type i1 = index(j, N-1), i2 = index(getNonAnchorParent(j),N-1); recurseSetRelMotion (matrix, i1, i2, (cstRHS ? Constrained : Parameterized)); } // Loop over the DifferentiableFunction const NumericalConstraints_t& ncs = proj->numericalConstraints (); for (NumericalConstraints_t::const_iterator _ncs = ncs.begin(); _ncs != ncs.end(); ++_ncs) { const NumericalConstraint& nc = **_ncs; if (nc.comparisonType()->constantRightHandSide()) { RelativeTransformationPtr_t rt = HPP_DYNAMIC_PTR_CAST(RelativeTransformation, nc.functionPtr()); if (!rt || rt->outputSize() != 6) continue; const size_type i1 = index(rt->joint1(), N-1), i2 = index(rt->joint2(), N-1); bool cstRHS = nc.comparisonType()->constantRightHandSide(); recurseSetRelMotion (matrix, i1, i2, (cstRHS ? Constrained : Parameterized)); } } } void RelativeMotion::recurseSetRelMotion(matrix_type& matrix, const size_type& i1, const size_type& i2, const RelativeMotion::RelativeMotionType& type) { bool param = (type == Parameterized); RelativeMotionType t = Unconstrained; if (type == Unconstrained) return; symSet(matrix, i1, i2, type); // i1 to i3 for (size_type i3 = 0; i3 < matrix.rows(); ++i3) { if (i3 == i1) continue; if (i3 == i2) continue; if (matrix(i2,i3) != Unconstrained) { t = (!param && matrix(i2,i3) == Constrained) ? Constrained : Parameterized; symSet(matrix, i1, i3, t); } } for (size_type i0 = 0; i0 < matrix.rows(); ++i0) { if (i0 == i2) continue; if (i0 == i1) continue; // i0 to i2 if (matrix(i0,i1) != Unconstrained) { t = (!param && matrix(i0,i1) == Constrained) ? Constrained : Parameterized; symSet (matrix, i0, i2 ,t); } // from i0 to i3 if (matrix(i0,i1) == Unconstrained) continue; for (size_type i3 = 0; i3 < matrix.rows(); ++i3) { if (i3 == i2) continue; if (i3 == i1) continue; if (i3 == i0) continue; if (matrix(i2,i3) == Unconstrained) continue; t = (!param && matrix(i0,i1) == Constrained && matrix(i2,i3) == Constrained) ? Constrained : Parameterized; symSet (matrix, i0, i3, t); } } } } // namespace core } // namespace hpp <|endoftext|>
<commit_before>/* * This file is part of the IAN project - https://github.com/Meoo/IAN * * 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/. */ // Generated file #pragma once #include <functional> #include <map> #include <mutex> #include <type_traits> namespace @RPC_NAMESPACE@ { namespace impl { // http://en.cppreference.com/w/cpp/types/disjunction // Remove when C++17 template<class...> struct Disjunction : std::false_type {}; template<class B1> struct Disjunction<B1> : B1 {}; template<class B1, class... Bn> struct Disjunction<B1, Bn...> : std::conditional_t<bool(B1::value), B1, Disjunction<Bn...>> {}; template<class If, class... Interfaces> using ContainsIf = impl::Disjunction<std::is_same<If, Interfaces>...>; } // Return callback template<class Base, class R, typename T> class RpcReturn { public: explicit inline RpcReturn(Base * ptr) : ptr_(ptr) {} inline RpcReturn(RpcReturn && other) : ptr_(other.ptr_), rpc_id_(other.rpc_id_) { other.ptr_ = nullptr; } RpcReturn(const RpcReturn &) = delete; RpcReturn & operator=(const RpcReturn &) = delete; inline ~RpcReturn() { if (ptr_) error(0, "RpcReturn object dropped"); } inline void operator()(flatbuffers::FlatBufferBuilder & builder, flatbuffers::Offset<T> data) { if (!ptr_) return; auto rpc_rep = CreateRpcReply(builder, rpc_id_, RpcReplyUTraits<T>::enum_value, data.Union()); static_cast<R *>(ptr_)->emit_rpc_reply(builder, rpc_rep); ptr_ = nullptr; } inline void error(std::uint32_t error_code, const char * error_str) { if (!ptr_) return; flatbuffers::FlatBufferBuilder builder; auto err = CreateRpcErrorDirect(builder, error_code, error_str); auto rpc_rep = CreateRpcReply(builder, rpc_id_, RpcReplyU::RpcReplyU_RpcError, err.Union()); static_cast<R *>(ptr_)->emit_rpc_reply(builder, rpc_rep); ptr_ = nullptr; } private: Base * ptr_; uint32_t rpc_id_ = 0; }; // Result invoker class RpcResultInvoker { public: RpcResultInvoker() : expected_reply_(RpcReplyU::RpcReplyU_NONE) {} RpcResultInvoker(RpcResultInvoker && other) : expected_reply_(other.expected_reply_), callback_(other.callback_) { other.expected_reply_ = RpcReplyU::RpcReplyU_NONE; } RpcResultInvoker(const RpcResultInvoker &) = delete; RpcResultInvoker & operator=(const RpcResultInvoker &) = delete; template<typename F> RpcResultInvoker(RpcReplyU expected_reply, F && callback) : expected_reply_(expected_reply), callback_(std::forward<F>(callback)) { } void invoke(const RpcReply & reply) { if (reply.data_type() == RpcReplyU::RpcReplyU_RpcError) { callback_(nullptr, reply.data_as_RpcError()); return; } if (reply.data_type() != expected_reply_) { // Should never happen flatbuffers::FlatBufferBuilder builder; auto rep = CreateRpcErrorDirect(builder, 0, "Received invalid result"); auto err = flatbuffers::GetRoot<RpcError>(builder.GetBufferPointer()); callback_(nullptr, err); return; } callback_(reply.data(), nullptr); } private: RpcReplyU expected_reply_; std::function<void(const void *, const RpcError *)> callback_; }; // { Interfaces @RPC_HPP_INTERFACES@// } Interfaces // Receiver template<class Base, template<class, bool> class... Interfaces> class RpcReceiver : public Interfaces<Base, true>... { protected: inline bool dispatch_rpc_request(const RpcRequest & request) { switch (request.data_type()) { @RPC_HPP_REQUEST_SWITCH@ default: return false; } } private: @RPC_HPP_REQUEST_DISPATCHERS@ }; // Sender template<class Base, template<class, bool> class... Interfaces> class RpcSender : public Interfaces<Base, false>... { protected: std::uint32_t register_rpc_return_callback(RpcResultInvoker callback) final { std::unique_lock<std::mutex> lock(mutex_); std::uint32_t id = next_id_++; result_callbacks_.emplace(std::make_pair(id, std::move(callback))); return id; } inline bool dispatch_rpc_reply(const RpcReply & reply) { RpcResultInvoker cb; { std::unique_lock<std::mutex> lock(mutex_); auto it = result_callbacks_.find(reply.id()); if (it == result_callbacks_.end()) return false; cb = std::move(it->second); result_callbacks_.erase(it); } cb.invoke(reply); } private: std::mutex mutex_; std::uint32_t next_id_ = 1; std::map<std::uint32_t, RpcResultInvoker> result_callbacks_; }; } // namespace @RPC_NAMESPACE@ <commit_msg>Rpc: add move assignment to RpcReturn & RpcResultInvoker<commit_after>/* * This file is part of the IAN project - https://github.com/Meoo/IAN * * 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/. */ // Generated file #pragma once #include <functional> #include <map> #include <mutex> #include <type_traits> namespace @RPC_NAMESPACE@ { namespace impl { // http://en.cppreference.com/w/cpp/types/disjunction // Remove when C++17 template<class...> struct Disjunction : std::false_type {}; template<class B1> struct Disjunction<B1> : B1 {}; template<class B1, class... Bn> struct Disjunction<B1, Bn...> : std::conditional_t<bool(B1::value), B1, Disjunction<Bn...>> {}; template<class If, class... Interfaces> using ContainsIf = impl::Disjunction<std::is_same<If, Interfaces>...>; } // Return callback template<class Base, class R, typename T> class RpcReturn { public: explicit inline RpcReturn(Base * ptr) : ptr_(ptr) {} inline RpcReturn(RpcReturn && other) : ptr_(other.ptr_), rpc_id_(other.rpc_id_) { other.ptr_ = nullptr; } RpcReturn(const RpcReturn &) = delete; RpcReturn & operator=(const RpcReturn &) = delete; RpcReturn & operator=(RpcReturn && other) { ptr_ = other.ptr_; rpc_id_ = other.rpc_id_; other.ptr_ = nullptr; return *this; } inline ~RpcReturn() { if (ptr_) error(0, "RpcReturn object dropped"); } inline void operator()(flatbuffers::FlatBufferBuilder & builder, flatbuffers::Offset<T> data) { if (!ptr_) return; auto rpc_rep = CreateRpcReply(builder, rpc_id_, RpcReplyUTraits<T>::enum_value, data.Union()); static_cast<R *>(ptr_)->emit_rpc_reply(builder, rpc_rep); ptr_ = nullptr; } inline void error(std::uint32_t error_code, const char * error_str) { if (!ptr_) return; flatbuffers::FlatBufferBuilder builder; auto err = CreateRpcErrorDirect(builder, error_code, error_str); auto rpc_rep = CreateRpcReply(builder, rpc_id_, RpcReplyU::RpcReplyU_RpcError, err.Union()); static_cast<R *>(ptr_)->emit_rpc_reply(builder, rpc_rep); ptr_ = nullptr; } private: Base * ptr_; uint32_t rpc_id_ = 0; }; // Result invoker class RpcResultInvoker { public: RpcResultInvoker() : expected_reply_(RpcReplyU::RpcReplyU_NONE) {} RpcResultInvoker(RpcResultInvoker && other) : expected_reply_(other.expected_reply_), callback_(other.callback_) { other.expected_reply_ = RpcReplyU::RpcReplyU_NONE; } RpcResultInvoker(const RpcResultInvoker &) = delete; RpcResultInvoker & operator=(const RpcResultInvoker &) = delete; RpcResultInvoker & operator=(RpcResultInvoker && other) { expected_reply_ = other.expected_reply_; callback_ = other.callback_; other.expected_reply_ = RpcReplyU::RpcReplyU_NONE; return *this; } template<typename F> RpcResultInvoker(RpcReplyU expected_reply, F && callback) : expected_reply_(expected_reply), callback_(std::forward<F>(callback)) { } void invoke(const RpcReply & reply) { if (reply.data_type() == RpcReplyU::RpcReplyU_RpcError) { callback_(nullptr, reply.data_as_RpcError()); return; } if (reply.data_type() != expected_reply_) { // Should never happen flatbuffers::FlatBufferBuilder builder; auto rep = CreateRpcErrorDirect(builder, 0, "Received invalid result"); auto err = flatbuffers::GetRoot<RpcError>(builder.GetBufferPointer()); callback_(nullptr, err); return; } callback_(reply.data(), nullptr); } private: RpcReplyU expected_reply_; std::function<void(const void *, const RpcError *)> callback_; }; // { Interfaces @RPC_HPP_INTERFACES@// } Interfaces // Receiver template<class Base, template<class, bool> class... Interfaces> class RpcReceiver : public Interfaces<Base, true>... { protected: inline bool dispatch_rpc_request(const RpcRequest & request) { switch (request.data_type()) { @RPC_HPP_REQUEST_SWITCH@ default: return false; } } private: @RPC_HPP_REQUEST_DISPATCHERS@ }; // Sender template<class Base, template<class, bool> class... Interfaces> class RpcSender : public Interfaces<Base, false>... { protected: std::uint32_t register_rpc_return_callback(RpcResultInvoker callback) final { std::unique_lock<std::mutex> lock(mutex_); std::uint32_t id = next_id_++; result_callbacks_.emplace(std::make_pair(id, std::move(callback))); return id; } inline bool dispatch_rpc_reply(const RpcReply & reply) { RpcResultInvoker cb; { std::unique_lock<std::mutex> lock(mutex_); auto it = result_callbacks_.find(reply.id()); if (it == result_callbacks_.end()) return false; cb = std::move(it->second); result_callbacks_.erase(it); } cb.invoke(reply); } private: std::mutex mutex_; std::uint32_t next_id_ = 1; std::map<std::uint32_t, RpcResultInvoker> result_callbacks_; }; } // namespace @RPC_NAMESPACE@ <|endoftext|>
<commit_before>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "proto_rpc_adapter.h" #include "searchapi.h" #include "docsumapi.h" #include "monitorapi.h" #include <vespa/fnet/frt/rpcrequest.h> #include <vespa/fnet/frt/supervisor.h> #include <vespa/vespalib/util/compressor.h> #include <vespa/searchlib/util/slime_output_raw_buf_adapter.h> #include <vespa/vespalib/data/databuffer.h> #include <vespa/searchlib/common/packets.h> #include <vespa/log/log.h> LOG_SETUP(".engine.proto_rpc_adapter"); namespace search::engine { using vespalib::DataBuffer; using vespalib::ConstBufferRef; using vespalib::compression::CompressionConfig; using ProtoSearchRequest = ProtoConverter::ProtoSearchRequest; using ProtoSearchReply = ProtoConverter::ProtoSearchReply; using ProtoDocsumRequest = ProtoConverter::ProtoDocsumRequest; using ProtoDocsumReply = ProtoConverter::ProtoDocsumReply; using ProtoMonitorRequest = ProtoConverter::ProtoMonitorRequest; using ProtoMonitorReply = ProtoConverter::ProtoMonitorReply; using QueryStats = SearchProtocolMetrics::QueryStats; using DocsumStats = SearchProtocolMetrics::DocsumStats; namespace { CompressionConfig get_compression_config() { using search::fs4transport::FS4PersistentPacketStreamer; const FS4PersistentPacketStreamer & streamer = FS4PersistentPacketStreamer::Instance; return CompressionConfig(streamer.getCompressionType(), streamer.getCompressionLevel(), 80, streamer.getCompressionLimit()); } template <typename MSG> void encode_message(const MSG &src, FRT_Values &dst) { using vespalib::compression::compress; auto output = src.SerializeAsString(); ConstBufferRef buf(output.data(), output.size()); DataBuffer compressed(output.data(), output.size()); CompressionConfig::Type type = compress(get_compression_config(), buf, compressed, true); dst.AddInt8(type); dst.AddInt32(buf.size()); dst.AddData(compressed.getData(), compressed.getDataLen()); } void encode_search_reply(const ProtoSearchReply &src, FRT_Values &dst) { using vespalib::compression::compress; auto output = src.SerializeAsString(); if (src.grouping_blob().empty()) { dst.AddInt8(CompressionConfig::Type::NONE); dst.AddInt32(output.size()); dst.AddData(output.data(), output.size()); } else { ConstBufferRef buf(output.data(), output.size()); DataBuffer compressed(output.data(), output.size()); CompressionConfig::Type type = compress(get_compression_config(), buf, compressed, true); dst.AddInt8(type); dst.AddInt32(buf.size()); dst.AddData(compressed.getData(), compressed.getDataLen()); } } template <typename MSG> bool decode_message(const FRT_Values &src, MSG &dst) { using vespalib::compression::decompress; uint8_t encoding = src[0]._intval8; uint32_t uncompressed_size = src[1]._intval32; DataBuffer uncompressed(src[2]._data._buf, src[2]._data._len); ConstBufferRef blob(src[2]._data._buf, src[2]._data._len); decompress(CompressionConfig::toType(encoding), uncompressed_size, blob, uncompressed, true); assert(uncompressed_size == uncompressed.getDataLen()); return dst.ParseFromArray(uncompressed.getData(), uncompressed.getDataLen()); } //----------------------------------------------------------------------------- struct SearchRequestDecoder : SearchRequest::Source::Decoder { FRT_RPCRequest &rpc; // valid until Return is called QueryStats &stats; RelativeTime relative_time; SearchRequestDecoder(FRT_RPCRequest &rpc_in, QueryStats &stats_in) : rpc(rpc_in), stats(stats_in), relative_time(std::make_unique<SteadyClock>()) {} std::unique_ptr<SearchRequest> decode() override { ProtoSearchRequest msg; stats.request_size = (*rpc.GetParams())[2]._data._len; if (!decode_message(*rpc.GetParams(), msg)) { LOG(warning, "got bad protobuf search request over rpc (unable to decode)"); return std::unique_ptr<SearchRequest>(nullptr); } auto req = std::make_unique<SearchRequest>(std::move(relative_time)); ProtoConverter::search_request_from_proto(msg, *req); return req; } }; std::unique_ptr<SearchRequest::Source::Decoder> search_request_decoder(FRT_RPCRequest &rpc, QueryStats &stats) { return std::make_unique<SearchRequestDecoder>(rpc, stats); } // allocated in the stash of the request it is completing; no self-delete needed struct SearchCompletionHandler : SearchClient { FRT_RPCRequest &req; SearchProtocolMetrics &metrics; QueryStats stats; SearchCompletionHandler(FRT_RPCRequest &req_in, SearchProtocolMetrics &metrics_in) : req(req_in), metrics(metrics_in), stats() {} void searchDone(SearchReply::UP reply) override { ProtoSearchReply msg; ProtoConverter::search_reply_to_proto(*reply, msg); encode_search_reply(msg, *req.GetReturn()); stats.reply_size = (*req.GetReturn())[2]._data._len; if (reply->request) { stats.latency = vespalib::to_s(reply->request->getTimeUsed()); metrics.update_query_metrics(stats); } req.Return(); } }; //----------------------------------------------------------------------------- struct DocsumRequestDecoder : DocsumRequest::Source::Decoder { FRT_RPCRequest &rpc; // valid until Return is called DocsumStats &stats; RelativeTime relative_time; DocsumRequestDecoder(FRT_RPCRequest &rpc_in, DocsumStats &stats_in) : rpc(rpc_in), stats(stats_in), relative_time(std::make_unique<SteadyClock>()) {} std::unique_ptr<DocsumRequest> decode() override { ProtoDocsumRequest msg; stats.request_size = (*rpc.GetParams())[2]._data._len; if (!decode_message(*rpc.GetParams(), msg)) { LOG(warning, "got bad protobuf docsum request over rpc (unable to decode)"); return std::unique_ptr<DocsumRequest>(nullptr); } stats.requested_documents = msg.global_ids_size(); auto req = std::make_unique<DocsumRequest>(std::move(relative_time)); ProtoConverter::docsum_request_from_proto(msg, *req); return req; } }; std::unique_ptr<DocsumRequest::Source::Decoder> docsum_request_decoder(FRT_RPCRequest &rpc, DocsumStats &stats) { return std::make_unique<DocsumRequestDecoder>(rpc, stats); } // allocated in the stash of the request it is completing; no self-delete needed struct GetDocsumsCompletionHandler : DocsumClient { FRT_RPCRequest &req; SearchProtocolMetrics &metrics; DocsumStats stats; GetDocsumsCompletionHandler(FRT_RPCRequest &req_in, SearchProtocolMetrics &metrics_in) : req(req_in), metrics(metrics_in), stats() {} void getDocsumsDone(DocsumReply::UP reply) override { ProtoDocsumReply msg; ProtoConverter::docsum_reply_to_proto(*reply, msg); encode_message(msg, *req.GetReturn()); stats.reply_size = (*req.GetReturn())[2]._data._len; if (reply->hasRequest()) { stats.latency = vespalib::to_s(reply->request().getTimeUsed()); metrics.update_docsum_metrics(stats); } req.Return(); } }; //----------------------------------------------------------------------------- // allocated in the stash of the request it is completing; no self-delete needed struct PingCompletionHandler : MonitorClient { FRT_RPCRequest &req; PingCompletionHandler(FRT_RPCRequest &req_in) : req(req_in) {} void pingDone(std::unique_ptr<MonitorReply> reply) override { ProtoMonitorReply msg; ProtoConverter::monitor_reply_to_proto(*reply, msg); encode_message(msg, *req.GetReturn()); req.Return(); } }; //----------------------------------------------------------------------------- void describe_bix_param_return(FRT_ReflectionBuilder &rb) { rb.ParamDesc("encoding", "0=raw, 6=lz4, 7=zstd"); rb.ParamDesc("uncompressed_size", "uncompressed size of serialized request"); rb.ParamDesc("request", "possibly compressed serialized request"); rb.ReturnDesc("encoding", "0=raw, 6=lz4, 7=zstd"); rb.ReturnDesc("uncompressed_size", "uncompressed size of serialized reply"); rb.ReturnDesc("reply", "possibly compressed serialized reply"); } } ProtoRpcAdapter::ProtoRpcAdapter(SearchServer &search_server, DocsumServer &docsum_server, MonitorServer &monitor_server, FRT_Supervisor &orb) : _search_server(search_server), _docsum_server(docsum_server), _monitor_server(monitor_server), _online(false), _metrics() { FRT_ReflectionBuilder rb(&orb); //------------------------------------------------------------------------- rb.DefineMethod("vespa.searchprotocol.search", "bix", "bix", FRT_METHOD(ProtoRpcAdapter::rpc_search), this); rb.MethodDesc("perform a search against this back-end"); describe_bix_param_return(rb); //------------------------------------------------------------------------- rb.DefineMethod("vespa.searchprotocol.getDocsums", "bix", "bix", FRT_METHOD(ProtoRpcAdapter::rpc_getDocsums), this); rb.MethodDesc("fetch document summaries from this back-end"); describe_bix_param_return(rb); //------------------------------------------------------------------------- rb.DefineMethod("vespa.searchprotocol.ping", "bix", "bix", FRT_METHOD(ProtoRpcAdapter::rpc_ping), this); rb.MethodDesc("ping this back-end"); describe_bix_param_return(rb); //------------------------------------------------------------------------- } void ProtoRpcAdapter::rpc_search(FRT_RPCRequest *req) { if (!is_online()) { return req->SetError(FRTE_RPC_METHOD_FAILED, "Server not online"); } req->Detach(); auto &client = req->getStash().create<SearchCompletionHandler>(*req, _metrics); auto reply = _search_server.search(search_request_decoder(*req, client.stats), client); if (reply) { client.searchDone(std::move(reply)); } } void ProtoRpcAdapter::rpc_getDocsums(FRT_RPCRequest *req) { if (!is_online()) { return req->SetError(FRTE_RPC_METHOD_FAILED, "Server not online"); } req->Detach(); auto &client = req->getStash().create<GetDocsumsCompletionHandler>(*req, _metrics); auto reply = _docsum_server.getDocsums(docsum_request_decoder(*req, client.stats), client); if (reply) { client.getDocsumsDone(std::move(reply)); } } void ProtoRpcAdapter::rpc_ping(FRT_RPCRequest *rpc) { if (!is_online()) { return rpc->SetError(FRTE_RPC_METHOD_FAILED, "Server not online"); } rpc->Detach(); ProtoMonitorRequest msg; if (decode_message(*rpc->GetParams(), msg)) { auto req = std::make_unique<MonitorRequest>(); ProtoConverter::monitor_request_from_proto(msg, *req); auto &client = rpc->getStash().create<PingCompletionHandler>(*rpc); auto reply = _monitor_server.ping(std::move(req), client); if (reply) { client.pingDone(std::move(reply)); } } else { LOG(warning, "got bad protobuf monitor request over rpc (unable to decode)"); rpc->SetError(FRTE_RPC_METHOD_FAILED, "malformed monitor request"); rpc->Return(); } } //----------------------------------------------------------------------------- void ProtoRpcAdapter::encode_search_request(const ProtoSearchRequest &src, FRT_RPCRequest &dst) { dst.SetMethodName("vespa.searchprotocol.search"); encode_message(src, *dst.GetParams()); } bool ProtoRpcAdapter::decode_search_reply(FRT_RPCRequest &src, ProtoSearchReply &dst) { return (src.CheckReturnTypes("bix") && decode_message(*src.GetReturn(), dst)); } void ProtoRpcAdapter::encode_docsum_request(const ProtoDocsumRequest &src, FRT_RPCRequest &dst) { dst.SetMethodName("vespa.searchprotocol.getDocsums"); encode_message(src, *dst.GetParams()); } bool ProtoRpcAdapter::decode_docsum_reply(FRT_RPCRequest &src, ProtoDocsumReply &dst) { return (src.CheckReturnTypes("bix") && decode_message(*src.GetReturn(), dst)); } void ProtoRpcAdapter::encode_monitor_request(const ProtoMonitorRequest &src, FRT_RPCRequest &dst) { dst.SetMethodName("vespa.searchprotocol.ping"); encode_message(src, *dst.GetParams()); } bool ProtoRpcAdapter::decode_monitor_reply(FRT_RPCRequest &src, ProtoMonitorReply &dst) { return (src.CheckReturnTypes("bix") && decode_message(*src.GetReturn(), dst)); } } <commit_msg>Add request capability filters to search API functions<commit_after>// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "proto_rpc_adapter.h" #include "searchapi.h" #include "docsumapi.h" #include "monitorapi.h" #include <vespa/fnet/frt/require_capabilities.h> #include <vespa/fnet/frt/rpcrequest.h> #include <vespa/fnet/frt/supervisor.h> #include <vespa/vespalib/util/compressor.h> #include <vespa/searchlib/util/slime_output_raw_buf_adapter.h> #include <vespa/vespalib/data/databuffer.h> #include <vespa/searchlib/common/packets.h> #include <vespa/log/log.h> LOG_SETUP(".engine.proto_rpc_adapter"); namespace search::engine { using vespalib::DataBuffer; using vespalib::ConstBufferRef; using vespalib::compression::CompressionConfig; using ProtoSearchRequest = ProtoConverter::ProtoSearchRequest; using ProtoSearchReply = ProtoConverter::ProtoSearchReply; using ProtoDocsumRequest = ProtoConverter::ProtoDocsumRequest; using ProtoDocsumReply = ProtoConverter::ProtoDocsumReply; using ProtoMonitorRequest = ProtoConverter::ProtoMonitorRequest; using ProtoMonitorReply = ProtoConverter::ProtoMonitorReply; using QueryStats = SearchProtocolMetrics::QueryStats; using DocsumStats = SearchProtocolMetrics::DocsumStats; namespace { CompressionConfig get_compression_config() { using search::fs4transport::FS4PersistentPacketStreamer; const FS4PersistentPacketStreamer & streamer = FS4PersistentPacketStreamer::Instance; return CompressionConfig(streamer.getCompressionType(), streamer.getCompressionLevel(), 80, streamer.getCompressionLimit()); } template <typename MSG> void encode_message(const MSG &src, FRT_Values &dst) { using vespalib::compression::compress; auto output = src.SerializeAsString(); ConstBufferRef buf(output.data(), output.size()); DataBuffer compressed(output.data(), output.size()); CompressionConfig::Type type = compress(get_compression_config(), buf, compressed, true); dst.AddInt8(type); dst.AddInt32(buf.size()); dst.AddData(compressed.getData(), compressed.getDataLen()); } void encode_search_reply(const ProtoSearchReply &src, FRT_Values &dst) { using vespalib::compression::compress; auto output = src.SerializeAsString(); if (src.grouping_blob().empty()) { dst.AddInt8(CompressionConfig::Type::NONE); dst.AddInt32(output.size()); dst.AddData(output.data(), output.size()); } else { ConstBufferRef buf(output.data(), output.size()); DataBuffer compressed(output.data(), output.size()); CompressionConfig::Type type = compress(get_compression_config(), buf, compressed, true); dst.AddInt8(type); dst.AddInt32(buf.size()); dst.AddData(compressed.getData(), compressed.getDataLen()); } } template <typename MSG> bool decode_message(const FRT_Values &src, MSG &dst) { using vespalib::compression::decompress; uint8_t encoding = src[0]._intval8; uint32_t uncompressed_size = src[1]._intval32; DataBuffer uncompressed(src[2]._data._buf, src[2]._data._len); ConstBufferRef blob(src[2]._data._buf, src[2]._data._len); decompress(CompressionConfig::toType(encoding), uncompressed_size, blob, uncompressed, true); assert(uncompressed_size == uncompressed.getDataLen()); return dst.ParseFromArray(uncompressed.getData(), uncompressed.getDataLen()); } //----------------------------------------------------------------------------- struct SearchRequestDecoder : SearchRequest::Source::Decoder { FRT_RPCRequest &rpc; // valid until Return is called QueryStats &stats; RelativeTime relative_time; SearchRequestDecoder(FRT_RPCRequest &rpc_in, QueryStats &stats_in) : rpc(rpc_in), stats(stats_in), relative_time(std::make_unique<SteadyClock>()) {} std::unique_ptr<SearchRequest> decode() override { ProtoSearchRequest msg; stats.request_size = (*rpc.GetParams())[2]._data._len; if (!decode_message(*rpc.GetParams(), msg)) { LOG(warning, "got bad protobuf search request over rpc (unable to decode)"); return std::unique_ptr<SearchRequest>(nullptr); } auto req = std::make_unique<SearchRequest>(std::move(relative_time)); ProtoConverter::search_request_from_proto(msg, *req); return req; } }; std::unique_ptr<SearchRequest::Source::Decoder> search_request_decoder(FRT_RPCRequest &rpc, QueryStats &stats) { return std::make_unique<SearchRequestDecoder>(rpc, stats); } // allocated in the stash of the request it is completing; no self-delete needed struct SearchCompletionHandler : SearchClient { FRT_RPCRequest &req; SearchProtocolMetrics &metrics; QueryStats stats; SearchCompletionHandler(FRT_RPCRequest &req_in, SearchProtocolMetrics &metrics_in) : req(req_in), metrics(metrics_in), stats() {} void searchDone(SearchReply::UP reply) override { ProtoSearchReply msg; ProtoConverter::search_reply_to_proto(*reply, msg); encode_search_reply(msg, *req.GetReturn()); stats.reply_size = (*req.GetReturn())[2]._data._len; if (reply->request) { stats.latency = vespalib::to_s(reply->request->getTimeUsed()); metrics.update_query_metrics(stats); } req.Return(); } }; //----------------------------------------------------------------------------- struct DocsumRequestDecoder : DocsumRequest::Source::Decoder { FRT_RPCRequest &rpc; // valid until Return is called DocsumStats &stats; RelativeTime relative_time; DocsumRequestDecoder(FRT_RPCRequest &rpc_in, DocsumStats &stats_in) : rpc(rpc_in), stats(stats_in), relative_time(std::make_unique<SteadyClock>()) {} std::unique_ptr<DocsumRequest> decode() override { ProtoDocsumRequest msg; stats.request_size = (*rpc.GetParams())[2]._data._len; if (!decode_message(*rpc.GetParams(), msg)) { LOG(warning, "got bad protobuf docsum request over rpc (unable to decode)"); return std::unique_ptr<DocsumRequest>(nullptr); } stats.requested_documents = msg.global_ids_size(); auto req = std::make_unique<DocsumRequest>(std::move(relative_time)); ProtoConverter::docsum_request_from_proto(msg, *req); return req; } }; std::unique_ptr<DocsumRequest::Source::Decoder> docsum_request_decoder(FRT_RPCRequest &rpc, DocsumStats &stats) { return std::make_unique<DocsumRequestDecoder>(rpc, stats); } // allocated in the stash of the request it is completing; no self-delete needed struct GetDocsumsCompletionHandler : DocsumClient { FRT_RPCRequest &req; SearchProtocolMetrics &metrics; DocsumStats stats; GetDocsumsCompletionHandler(FRT_RPCRequest &req_in, SearchProtocolMetrics &metrics_in) : req(req_in), metrics(metrics_in), stats() {} void getDocsumsDone(DocsumReply::UP reply) override { ProtoDocsumReply msg; ProtoConverter::docsum_reply_to_proto(*reply, msg); encode_message(msg, *req.GetReturn()); stats.reply_size = (*req.GetReturn())[2]._data._len; if (reply->hasRequest()) { stats.latency = vespalib::to_s(reply->request().getTimeUsed()); metrics.update_docsum_metrics(stats); } req.Return(); } }; //----------------------------------------------------------------------------- // allocated in the stash of the request it is completing; no self-delete needed struct PingCompletionHandler : MonitorClient { FRT_RPCRequest &req; PingCompletionHandler(FRT_RPCRequest &req_in) : req(req_in) {} void pingDone(std::unique_ptr<MonitorReply> reply) override { ProtoMonitorReply msg; ProtoConverter::monitor_reply_to_proto(*reply, msg); encode_message(msg, *req.GetReturn()); req.Return(); } }; //----------------------------------------------------------------------------- void describe_bix_param_return(FRT_ReflectionBuilder &rb) { rb.ParamDesc("encoding", "0=raw, 6=lz4, 7=zstd"); rb.ParamDesc("uncompressed_size", "uncompressed size of serialized request"); rb.ParamDesc("request", "possibly compressed serialized request"); rb.ReturnDesc("encoding", "0=raw, 6=lz4, 7=zstd"); rb.ReturnDesc("uncompressed_size", "uncompressed size of serialized reply"); rb.ReturnDesc("reply", "possibly compressed serialized reply"); } std::unique_ptr<FRT_RequireCapabilities> make_search_api_capability_filter() { return FRT_RequireCapabilities::of(vespalib::net::tls::Capability::content_search_api()); } } ProtoRpcAdapter::ProtoRpcAdapter(SearchServer &search_server, DocsumServer &docsum_server, MonitorServer &monitor_server, FRT_Supervisor &orb) : _search_server(search_server), _docsum_server(docsum_server), _monitor_server(monitor_server), _online(false), _metrics() { FRT_ReflectionBuilder rb(&orb); //------------------------------------------------------------------------- rb.DefineMethod("vespa.searchprotocol.search", "bix", "bix", FRT_METHOD(ProtoRpcAdapter::rpc_search), this); rb.MethodDesc("perform a search against this back-end"); rb.RequestAccessFilter(make_search_api_capability_filter()); describe_bix_param_return(rb); //------------------------------------------------------------------------- rb.DefineMethod("vespa.searchprotocol.getDocsums", "bix", "bix", FRT_METHOD(ProtoRpcAdapter::rpc_getDocsums), this); rb.MethodDesc("fetch document summaries from this back-end"); rb.RequestAccessFilter(make_search_api_capability_filter()); describe_bix_param_return(rb); //------------------------------------------------------------------------- rb.DefineMethod("vespa.searchprotocol.ping", "bix", "bix", FRT_METHOD(ProtoRpcAdapter::rpc_ping), this); rb.MethodDesc("ping this back-end"); rb.RequestAccessFilter(make_search_api_capability_filter()); describe_bix_param_return(rb); //------------------------------------------------------------------------- } void ProtoRpcAdapter::rpc_search(FRT_RPCRequest *req) { if (!is_online()) { return req->SetError(FRTE_RPC_METHOD_FAILED, "Server not online"); } req->Detach(); auto &client = req->getStash().create<SearchCompletionHandler>(*req, _metrics); auto reply = _search_server.search(search_request_decoder(*req, client.stats), client); if (reply) { client.searchDone(std::move(reply)); } } void ProtoRpcAdapter::rpc_getDocsums(FRT_RPCRequest *req) { if (!is_online()) { return req->SetError(FRTE_RPC_METHOD_FAILED, "Server not online"); } req->Detach(); auto &client = req->getStash().create<GetDocsumsCompletionHandler>(*req, _metrics); auto reply = _docsum_server.getDocsums(docsum_request_decoder(*req, client.stats), client); if (reply) { client.getDocsumsDone(std::move(reply)); } } void ProtoRpcAdapter::rpc_ping(FRT_RPCRequest *rpc) { if (!is_online()) { return rpc->SetError(FRTE_RPC_METHOD_FAILED, "Server not online"); } rpc->Detach(); ProtoMonitorRequest msg; if (decode_message(*rpc->GetParams(), msg)) { auto req = std::make_unique<MonitorRequest>(); ProtoConverter::monitor_request_from_proto(msg, *req); auto &client = rpc->getStash().create<PingCompletionHandler>(*rpc); auto reply = _monitor_server.ping(std::move(req), client); if (reply) { client.pingDone(std::move(reply)); } } else { LOG(warning, "got bad protobuf monitor request over rpc (unable to decode)"); rpc->SetError(FRTE_RPC_METHOD_FAILED, "malformed monitor request"); rpc->Return(); } } //----------------------------------------------------------------------------- void ProtoRpcAdapter::encode_search_request(const ProtoSearchRequest &src, FRT_RPCRequest &dst) { dst.SetMethodName("vespa.searchprotocol.search"); encode_message(src, *dst.GetParams()); } bool ProtoRpcAdapter::decode_search_reply(FRT_RPCRequest &src, ProtoSearchReply &dst) { return (src.CheckReturnTypes("bix") && decode_message(*src.GetReturn(), dst)); } void ProtoRpcAdapter::encode_docsum_request(const ProtoDocsumRequest &src, FRT_RPCRequest &dst) { dst.SetMethodName("vespa.searchprotocol.getDocsums"); encode_message(src, *dst.GetParams()); } bool ProtoRpcAdapter::decode_docsum_reply(FRT_RPCRequest &src, ProtoDocsumReply &dst) { return (src.CheckReturnTypes("bix") && decode_message(*src.GetReturn(), dst)); } void ProtoRpcAdapter::encode_monitor_request(const ProtoMonitorRequest &src, FRT_RPCRequest &dst) { dst.SetMethodName("vespa.searchprotocol.ping"); encode_message(src, *dst.GetParams()); } bool ProtoRpcAdapter::decode_monitor_reply(FRT_RPCRequest &src, ProtoMonitorReply &dst) { return (src.CheckReturnTypes("bix") && decode_message(*src.GetReturn(), dst)); } } <|endoftext|>
<commit_before>#include <algorithm> #include <iostream> #include <stdexcept> #include <chrono> #include "config.hpp" #include "requestHandler.hpp" #include "response.hpp" #include "torrent.hpp" #include "utility.hpp" #include "mysql.hpp" TorrentMap RequestHandler::torMap; UserMap RequestHandler::usrMap; Database* RequestHandler::db; std::string RequestHandler::handle(std::string str, std::string ip) { std::pair<Request, std::forward_list<std::string>> infos = Parser::parse(str); // parse the request Request* req = &infos.first; std::forward_list<std::string>* infoHashes = &infos.second; bool gzip = false; try { // check if the client accepts gzip if (req->at("accept-encoding").find("gzip") != std::string::npos) gzip = true; } catch (const std::exception& e) {} std::string check = Parser::check(*req); // check if we have all we need to process (saves time if not the case if (infoHashes->begin() == infoHashes->end()) return error("missing info_hash", gzip); if (check != "success") // missing params return error(check, gzip); if (Config::get("type") == "private" && getUser(req->at("passkey")) == nullptr) return error("passkey not found", gzip); try { req->at("ip") = Utility::ip_hex_encode(req->at("ip")) + Utility::port_hex_encode(req->at("port")); } catch (const std::exception& e) { req->emplace("ip", ip + Utility::port_hex_encode(req->at("port"))); } if (req->at("action") == "announce") { req->emplace("event", "updating"); return announce(req, infoHashes->front(), gzip); } else if (req->at("action") == "scrape") return scrape(infoHashes, gzip); return error("invalid action", gzip); // not possible, since the request is checked, but, well, who knows :3 } std::string RequestHandler::announce(const Request* req, const std::string& infoHash, const bool& gzip) { auto duration = std::chrono::system_clock::now().time_since_epoch(); long long now = std::chrono::duration_cast<std::chrono::seconds>(duration).count(); if (Config::get("type") != "private") torMap.emplace(infoHash, Torrent(0)); Torrent *tor = nullptr; try { tor = &torMap.at(infoHash); } catch (const std::exception& e) { return error("unregistered torrent", gzip); } Peers *peers = nullptr; Peer *peer = nullptr; if (req->at("left") != "0") { peer = tor->getLeechers()->getPeer(req->at("peer_id"), now); if (req->at("event") == "stopped") { if (peer != nullptr) { db->record(peer->record(std::stoul(req->at("left")), req->at("peer_id"))); db->record(Peer::remove(req->at("peer_id"), tor->getID())); tor->getLeechers()->removePeer(*req); } } else if (req->at("event") == "started") { if (peer == nullptr) tor->getLeechers()->addPeer(*req, tor->getID(), now); } else if (peer != nullptr) { peer->updateStats(std::stoul(req->at("downloaded"))/(1-(tor->getFree()/100)), now); } peers = tor->getSeeders(); } else { peer = tor->getSeeders()->getPeer(req->at("peer_id"), now); if (req->at("event") == "stopped" || req->at("event") == "completed") { if (peer != nullptr) { if (req->at("event") == "completed") { tor->downloadedpp(); tor->getSeeders()->addPeer(*req, tor->getID(), now); tor->getLeechers()->removePeer(*req); } else { db->record(peer->record(std::stoul(req->at("left")), req->at("peer_id"))); db->record(Peer::remove(req->at("peer_id"), tor->getID())); } } } else if (req->at("event") == "started") { if (peer == nullptr) tor->getSeeders()->addPeer(*req, tor->getID(), now); } else if (peer != nullptr) { tor->getLeechers()->getPeer(req->at("peer_id"), now)->updateStats(std::stoul(req->at("downloaded"))/(1-(tor->getFree()/100)), now); } peers = tor->getLeechers(); } std::string peerlist; unsigned long i = 0; if (req->at("event") != "stopped") { i = 10; try { i = std::stoi(req->at("numwant")); } catch (const std::exception& e) {} i = std::min(i, peers->size()); } while (i-- > 0) { Peer* p = peers->nextPeer(now); if (p != nullptr) peerlist.append(*p->getHexIP()); } return response( ("d8:completei" + std::to_string(tor->getSeeders()->size()) + "e10:incompletei" + std::to_string(tor->getLeechers()->size()) + "e10:downloadedi" + std::to_string(tor->getDownloaded()) + "e8:intervali" + std::to_string(900) + "e12:min intervali" + std::to_string(300) + "e5:peers" + std::to_string(peerlist.length()) + ":" + peerlist + "e"), gzip ); // doesn't look as bad as it is stated on ocelot, needs stresstesting to check } std::string RequestHandler::scrape(const std::forward_list<std::string>* infoHashes, const bool& gzip) { std::string resp("d5:filesd"); for (const auto& infoHash : *infoHashes) { const TorrentMap::iterator it = torMap.find(infoHash); if (it != torMap.end()) { resp += std::to_string(infoHash.length()) + ":" + infoHash + "d8:completei" + std::to_string(it->second.getSeeders()->size()) + "e10:incompletei" + std::to_string(it->second.getLeechers()->size()) + "e10:downloadedi" + std::to_string(it->second.getDownloaded()) + "ee"; } } resp += "ee"; return response(resp, gzip); } std::string RequestHandler::update(const Request* req) { std::string resp; const std::string& type = req->at("type"); if (type == "change_passkey") resp = changePasskey(req); else if (type == "add_torrent") resp = addTorrent(req); else if (type == "delete_torrent") resp = deleteTorrent(req); else if (type == "update_torrent") resp = updateTorrent(req); else if (type == "add_user") resp = addUser(req); else if (type == "remove_user") resp = removeUser(req); return resp; } std::string RequestHandler::changePasskey(const Request* req) { try { const std::string& old = req->at("oldpasskey"); User* user = usrMap.at(old); usrMap.erase(old); usrMap.emplace(req->at("newpasskey"), user); return "success"; } catch (const std::exception& e) { return "failure"; } } std::string RequestHandler::addTorrent(const Request* req) { try { auto t = torMap.emplace(req->at("info_hash"), Torrent(std::stoul(req->at("id")))); if (!t.second) return "failure"; try { if (req->at("freetorrent") == "1") t.first->second.setFree(1); else t.first->second.setFree(0); } catch (const std::exception& e) {} return "success"; } catch (const std::exception& e) { return "failure"; } } std::string RequestHandler::deleteTorrent(const Request* req) { const auto it = torMap.find(req->at("info_hash")); if (it != torMap.end()) torMap.erase(it); return "success"; } std::string RequestHandler::updateTorrent(const Request* req) { auto it = torMap.find(req->at("info_hash")); if (it != torMap.end()) { if (req->at("freetorrent") == "1") it->second.setFree(1); else it->second.setFree(0); return "success"; } return "failure"; } std::string RequestHandler::addUser(const Request* req) { try { return (usrMap.emplace(req->at("passkey"), new User(std::stoul(req->at("id")))).second) ? "success" : "failure"; } catch (const std::exception& e) { return "failure"; } } std::string RequestHandler::removeUser(const Request* req) { return (usrMap.erase(req->at("passkey")) == 1) ? "success" : "failure"; } User* RequestHandler::getUser(const std::string& passkey) { try { return usrMap.at(passkey); } catch (const std::exception& e) { return nullptr; } } void RequestHandler::init() { db = new MySQL(); db->connect(); db->loadUsers(usrMap); db->loadTorrents(torMap); } void RequestHandler::stop() { // TODO record every changes before flushing db->flush(); db->disconnect(); } void RequestHandler::clearTorrentPeers(ev::timer& timer, int revents) { auto duration = std::chrono::system_clock::now().time_since_epoch(); long long now = std::chrono::duration_cast<std::chrono::seconds>(duration).count(); for (auto& t : torMap) { t.second.getSeeders()->timedOut(now); t.second.getLeechers()->timedOut(now); } } <commit_msg>was getting a leecher instead of a seeder<commit_after>#include <algorithm> #include <iostream> #include <stdexcept> #include <chrono> #include "config.hpp" #include "requestHandler.hpp" #include "response.hpp" #include "torrent.hpp" #include "utility.hpp" #include "mysql.hpp" TorrentMap RequestHandler::torMap; UserMap RequestHandler::usrMap; Database* RequestHandler::db; std::string RequestHandler::handle(std::string str, std::string ip) { std::pair<Request, std::forward_list<std::string>> infos = Parser::parse(str); // parse the request Request* req = &infos.first; std::forward_list<std::string>* infoHashes = &infos.second; bool gzip = false; try { // check if the client accepts gzip if (req->at("accept-encoding").find("gzip") != std::string::npos) gzip = true; } catch (const std::exception& e) {} std::string check = Parser::check(*req); // check if we have all we need to process (saves time if not the case if (infoHashes->begin() == infoHashes->end()) return error("missing info_hash", gzip); if (check != "success") // missing params return error(check, gzip); if (Config::get("type") == "private" && getUser(req->at("passkey")) == nullptr) return error("passkey not found", gzip); try { req->at("ip") = Utility::ip_hex_encode(req->at("ip")) + Utility::port_hex_encode(req->at("port")); } catch (const std::exception& e) { req->emplace("ip", ip + Utility::port_hex_encode(req->at("port"))); } if (req->at("action") == "announce") { req->emplace("event", "updating"); return announce(req, infoHashes->front(), gzip); } else if (req->at("action") == "scrape") return scrape(infoHashes, gzip); return error("invalid action", gzip); // not possible, since the request is checked, but, well, who knows :3 } std::string RequestHandler::announce(const Request* req, const std::string& infoHash, const bool& gzip) { auto duration = std::chrono::system_clock::now().time_since_epoch(); long long now = std::chrono::duration_cast<std::chrono::seconds>(duration).count(); if (Config::get("type") != "private") torMap.emplace(infoHash, Torrent(0)); Torrent *tor = nullptr; try { tor = &torMap.at(infoHash); } catch (const std::exception& e) { return error("unregistered torrent", gzip); } Peers *peers = nullptr; Peer *peer = nullptr; if (req->at("left") != "0") { peer = tor->getLeechers()->getPeer(req->at("peer_id"), now); if (req->at("event") == "stopped") { if (peer != nullptr) { db->record(peer->record(std::stoul(req->at("left")), req->at("peer_id"))); db->record(Peer::remove(req->at("peer_id"), tor->getID())); tor->getLeechers()->removePeer(*req); } } else if (req->at("event") == "started") { if (peer == nullptr) tor->getLeechers()->addPeer(*req, tor->getID(), now); } else { peer->updateStats(std::stoul(req->at("downloaded"))/(1-(tor->getFree()/100)), now); } peers = tor->getSeeders(); } else { peer = tor->getSeeders()->getPeer(req->at("peer_id"), now); if (req->at("event") == "stopped" || req->at("event") == "completed") { if (peer != nullptr) { if (req->at("event") == "completed") { tor->downloadedpp(); tor->getSeeders()->addPeer(*req, tor->getID(), now); tor->getLeechers()->removePeer(*req); } else { db->record(peer->record(std::stoul(req->at("left")), req->at("peer_id"))); db->record(Peer::remove(req->at("peer_id"), tor->getID())); } } } else if (req->at("event") == "started") { if (peer == nullptr) tor->getSeeders()->addPeer(*req, tor->getID(), now); } else { tor->getSeeders()->getPeer(req->at("peer_id"), now)->updateStats(std::stoul(req->at("downloaded"))/(1-(tor->getFree()/100)), now); } peers = tor->getLeechers(); } std::string peerlist; unsigned long i = 0; if (req->at("event") != "stopped") { i = 10; try { i = std::stoi(req->at("numwant")); } catch (const std::exception& e) {} i = std::min(i, peers->size()); } while (i-- > 0) { Peer* p = peers->nextPeer(now); if (p != nullptr) peerlist.append(*p->getHexIP()); } return response( ("d8:completei" + std::to_string(tor->getSeeders()->size()) + "e10:incompletei" + std::to_string(tor->getLeechers()->size()) + "e10:downloadedi" + std::to_string(tor->getDownloaded()) + "e8:intervali" + std::to_string(900) + "e12:min intervali" + std::to_string(300) + "e5:peers" + std::to_string(peerlist.length()) + ":" + peerlist + "e"), gzip ); // doesn't look as bad as it is stated on ocelot, needs stresstesting to check } std::string RequestHandler::scrape(const std::forward_list<std::string>* infoHashes, const bool& gzip) { std::string resp("d5:filesd"); for (const auto& infoHash : *infoHashes) { const TorrentMap::iterator it = torMap.find(infoHash); if (it != torMap.end()) { resp += std::to_string(infoHash.length()) + ":" + infoHash + "d8:completei" + std::to_string(it->second.getSeeders()->size()) + "e10:incompletei" + std::to_string(it->second.getLeechers()->size()) + "e10:downloadedi" + std::to_string(it->second.getDownloaded()) + "ee"; } } resp += "ee"; return response(resp, gzip); } std::string RequestHandler::update(const Request* req) { std::string resp; const std::string& type = req->at("type"); if (type == "change_passkey") resp = changePasskey(req); else if (type == "add_torrent") resp = addTorrent(req); else if (type == "delete_torrent") resp = deleteTorrent(req); else if (type == "update_torrent") resp = updateTorrent(req); else if (type == "add_user") resp = addUser(req); else if (type == "remove_user") resp = removeUser(req); return resp; } std::string RequestHandler::changePasskey(const Request* req) { try { const std::string& old = req->at("oldpasskey"); User* user = usrMap.at(old); usrMap.erase(old); usrMap.emplace(req->at("newpasskey"), user); return "success"; } catch (const std::exception& e) { return "failure"; } } std::string RequestHandler::addTorrent(const Request* req) { try { auto t = torMap.emplace(req->at("info_hash"), Torrent(std::stoul(req->at("id")))); if (!t.second) return "failure"; try { if (req->at("freetorrent") == "1") t.first->second.setFree(1); else t.first->second.setFree(0); } catch (const std::exception& e) {} return "success"; } catch (const std::exception& e) { return "failure"; } } std::string RequestHandler::deleteTorrent(const Request* req) { const auto it = torMap.find(req->at("info_hash")); if (it != torMap.end()) torMap.erase(it); return "success"; } std::string RequestHandler::updateTorrent(const Request* req) { auto it = torMap.find(req->at("info_hash")); if (it != torMap.end()) { if (req->at("freetorrent") == "1") it->second.setFree(1); else it->second.setFree(0); return "success"; } return "failure"; } std::string RequestHandler::addUser(const Request* req) { try { return (usrMap.emplace(req->at("passkey"), new User(std::stoul(req->at("id")))).second) ? "success" : "failure"; } catch (const std::exception& e) { return "failure"; } } std::string RequestHandler::removeUser(const Request* req) { return (usrMap.erase(req->at("passkey")) == 1) ? "success" : "failure"; } User* RequestHandler::getUser(const std::string& passkey) { try { return usrMap.at(passkey); } catch (const std::exception& e) { return nullptr; } } void RequestHandler::init() { db = new MySQL(); db->connect(); db->loadUsers(usrMap); db->loadTorrents(torMap); } void RequestHandler::stop() { // TODO record every changes before flushing db->flush(); db->disconnect(); } void RequestHandler::clearTorrentPeers(ev::timer& timer, int revents) { auto duration = std::chrono::system_clock::now().time_since_epoch(); long long now = std::chrono::duration_cast<std::chrono::seconds>(duration).count(); for (auto& t : torMap) { t.second.getSeeders()->timedOut(now); t.second.getLeechers()->timedOut(now); } } <|endoftext|>
<commit_before>// Copyright 2020 Google LLC // // 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. // Perform decompression from *.jp2 to *.pnm format #include <libgen.h> #include <syscall.h> #include <cstdlib> #include <iostream> #include <vector> #include <iterator> #include "absl/algorithm/container.h" #include "convert_helper.h" #include "openjp2_sapi.sapi.h" class Openjp2SapiSandbox : public Openjp2Sandbox { public: Openjp2SapiSandbox(const std::string in_file) : in_file_(std::move(in_file)) {} std::unique_ptr<sandbox2::Policy> ModifyPolicy( sandbox2::PolicyBuilder*) override { return sandbox2::PolicyBuilder() .AllowStaticStartup() .AllowOpen() .AllowRead() .AllowWrite() .AllowStat() .AllowSystemMalloc() .AllowExit() .AllowSyscalls({ __NR_futex, __NR_close, __NR_lseek, }) .AddFile(in_file_) .BuildOrDie(); } private: std::string in_file_; }; int main(int argc, char* argv[]) { gflags::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); if (argc != 3) { std::cerr << "usage: " << basename(argv[0]) << " absolute/path/to/INPUT.jp2" << " absolute/path/to/OUTPUT.pnm\n"; return EXIT_FAILURE; } std::string in_file(argv[1]); // initialize sandbox Openjp2SapiSandbox sandbox(in_file); absl::Status status = sandbox.Init(); if (!status.ok()) { LOG(FATAL) << "sandbox initialization status: " << status; return EXIT_FAILURE; } Openjp2Api api(&sandbox); sapi::v::ConstCStr in_file_v(in_file.c_str()); // initialize library's main data-holders sapi::StatusOr<opj_stream_t*> stream = api.opj_stream_create_default_file_stream(in_file_v.PtrBefore(), 1); if (!stream.ok()) { LOG(FATAL) << "opj_stream initialization failed: " << stream.status(); return EXIT_FAILURE; } sapi::v::RemotePtr stream_pointer(stream.value()); sapi::StatusOr<opj_codec_t*> codec = api.opj_create_decompress(OPJ_CODEC_JP2); if (!codec.ok()) { LOG(FATAL) << "opj_codec initialization failed: " << codec.status(); return EXIT_FAILURE; } sapi::v::RemotePtr codec_pointer(codec.value()); sapi::v::Struct<opj_dparameters_t> parameters; status = api.opj_set_default_decoder_parameters(parameters.PtrBoth()); if (!status.ok()) { LOG(FATAL) << "parameters initialization failed: " << status; return EXIT_FAILURE; } sapi::StatusOr<OPJ_BOOL> bool_status = api.opj_setup_decoder(&codec_pointer, parameters.PtrBefore()); if (!bool_status.ok() || !bool_status.value()) { LOG(FATAL) << "decoder setup failed"; return EXIT_FAILURE; } // start reading image from the input file sapi::v::GenericPtr image_pointer; bool_status = api.opj_read_header(&stream_pointer, &codec_pointer, image_pointer.PtrAfter()); if (!bool_status.ok() || !bool_status.value()) { LOG(FATAL) << "reading image header failed"; return EXIT_FAILURE; } sapi::v::Struct<opj_image_t> image; image.SetRemote((void*)image_pointer.GetValue()); if (!sandbox.TransferFromSandboxee(&image).ok()) { LOG(FATAL) << "transfer from sandboxee failed"; return EXIT_FAILURE; } sapi::v::RemotePtr image_remote_pointer(image.GetRemote()); bool_status = api.opj_decode(&codec_pointer, &stream_pointer, &image_remote_pointer); if (!bool_status.ok() || !bool_status.value()) { LOG(FATAL) << "decoding failed"; return EXIT_FAILURE; } bool_status = api.opj_end_decompress(&codec_pointer, &stream_pointer); if (!bool_status.ok() || !bool_status.value()) { LOG(FATAL) << "ending decompress failed"; return EXIT_FAILURE; } int components = image.data().numcomps; // transfer the read data to the main process sapi::v::Array<opj_image_comp_t> image_components(components); image_components.SetRemote(image.data().comps); if (!sandbox.TransferFromSandboxee(&image_components).ok()) { LOG(FATAL) << "transfer from sandboxee failed"; return EXIT_FAILURE; } image.mutable_data()->comps = (opj_image_comp_t*)image_components.GetLocal(); int width = (int)image.data().comps[0].w; int height = (int)image.data().comps[0].h; OPJ_INT32 data[components][width * height]; sapi::v::Array<OPJ_INT32> image_components_data(width * height); for (int i = 0; i < components; ++i) { image_components_data.SetRemote(image.data().comps[i].data); if (!sandbox.TransferFromSandboxee(&image_components_data).ok()) { LOG(FATAL) << "transfer from sandboxee failed"; return EXIT_FAILURE; } for (int j = 0; j < width * height; ++j) { data[i][j] = image_components_data[j]; } image_components[i].data = data[i]; } // convert the image to the desired format and save it to the file int error = imagetopnm((opj_image_t*)image.GetLocal(), argv[2], 0); if (error) LOG(FATAL) << "image convert failed"; // cleanup status = api.opj_image_destroy(image.PtrNone()); if (!status.ok()) LOG(FATAL) << "image destroy failed: " << status; status = api.opj_stream_destroy(&stream_pointer); if (!status.ok()) LOG(FATAL) << "stream destroy failed: " << status; status = api.opj_destroy_codec(&codec_pointer); if (!status.ok()) LOG(FATAL) << "codec destroy failed: " << status; return EXIT_SUCCESS; } <commit_msg>changed VLA to vectors<commit_after>// Copyright 2020 Google LLC // // 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. // Perform decompression from *.jp2 to *.pnm format #include <libgen.h> #include <syscall.h> #include <cstdlib> #include <iostream> #include <vector> #include "absl/algorithm/container.h" #include "convert_helper.h" #include "openjp2_sapi.sapi.h" class Openjp2SapiSandbox : public Openjp2Sandbox { public: Openjp2SapiSandbox(const std::string in_file) : in_file_(std::move(in_file)) {} std::unique_ptr<sandbox2::Policy> ModifyPolicy( sandbox2::PolicyBuilder*) override { return sandbox2::PolicyBuilder() .AllowStaticStartup() .AllowOpen() .AllowRead() .AllowWrite() .AllowStat() .AllowSystemMalloc() .AllowExit() .AllowSyscalls({ __NR_futex, __NR_close, __NR_lseek, }) .AddFile(in_file_) .BuildOrDie(); } private: std::string in_file_; }; int main(int argc, char* argv[]) { gflags::ParseCommandLineFlags(&argc, &argv, true); google::InitGoogleLogging(argv[0]); if (argc != 3) { std::cerr << "usage: " << basename(argv[0]) << " absolute/path/to/INPUT.jp2" << " absolute/path/to/OUTPUT.pnm\n"; return EXIT_FAILURE; } std::string in_file(argv[1]); // initialize sandbox Openjp2SapiSandbox sandbox(in_file); absl::Status status = sandbox.Init(); if (!status.ok()) { LOG(FATAL) << "sandbox initialization status: " << status; return EXIT_FAILURE; } Openjp2Api api(&sandbox); sapi::v::ConstCStr in_file_v(in_file.c_str()); // initialize library's main data-holders sapi::StatusOr<opj_stream_t*> stream = api.opj_stream_create_default_file_stream(in_file_v.PtrBefore(), 1); if (!stream.ok()) { LOG(FATAL) << "opj_stream initialization failed: " << stream.status(); return EXIT_FAILURE; } sapi::v::RemotePtr stream_pointer(stream.value()); sapi::StatusOr<opj_codec_t*> codec = api.opj_create_decompress(OPJ_CODEC_JP2); if (!codec.ok()) { LOG(FATAL) << "opj_codec initialization failed: " << codec.status(); return EXIT_FAILURE; } sapi::v::RemotePtr codec_pointer(codec.value()); sapi::v::Struct<opj_dparameters_t> parameters; status = api.opj_set_default_decoder_parameters(parameters.PtrBoth()); if (!status.ok()) { LOG(FATAL) << "parameters initialization failed: " << status; return EXIT_FAILURE; } sapi::StatusOr<OPJ_BOOL> bool_status = api.opj_setup_decoder(&codec_pointer, parameters.PtrBefore()); if (!bool_status.ok() || !bool_status.value()) { LOG(FATAL) << "decoder setup failed"; return EXIT_FAILURE; } // start reading image from the input file sapi::v::GenericPtr image_pointer; bool_status = api.opj_read_header(&stream_pointer, &codec_pointer, image_pointer.PtrAfter()); if (!bool_status.ok() || !bool_status.value()) { LOG(FATAL) << "reading image header failed"; return EXIT_FAILURE; } sapi::v::Struct<opj_image_t> image; image.SetRemote((void*)image_pointer.GetValue()); if (!sandbox.TransferFromSandboxee(&image).ok()) { LOG(FATAL) << "transfer from sandboxee failed"; return EXIT_FAILURE; } sapi::v::RemotePtr image_remote_pointer(image.GetRemote()); bool_status = api.opj_decode(&codec_pointer, &stream_pointer, &image_remote_pointer); if (!bool_status.ok() || !bool_status.value()) { LOG(FATAL) << "decoding failed"; return EXIT_FAILURE; } bool_status = api.opj_end_decompress(&codec_pointer, &stream_pointer); if (!bool_status.ok() || !bool_status.value()) { LOG(FATAL) << "ending decompress failed"; return EXIT_FAILURE; } int components = image.data().numcomps; // transfer the read data to the main process sapi::v::Array<opj_image_comp_t> image_components(components); image_components.SetRemote(image.data().comps); if (!sandbox.TransferFromSandboxee(&image_components).ok()) { LOG(FATAL) << "transfer from sandboxee failed"; return EXIT_FAILURE; } image.mutable_data()->comps = (opj_image_comp_t*)image_components.GetLocal(); int width = (int)image.data().comps[0].w; int height = (int)image.data().comps[0].h; std::vector<std::vector<OPJ_INT32>> data; sapi::v::Array<OPJ_INT32> image_components_data(width * height); for (int i = 0; i < components; ++i) { image_components_data.SetRemote(image.data().comps[i].data); if (!sandbox.TransferFromSandboxee(&image_components_data).ok()) { LOG(FATAL) << "transfer from sandboxee failed"; return EXIT_FAILURE; } std::vector<OPJ_INT32> component_data( image_components_data.GetData(), image_components_data.GetData() + (width * height)); data.push_back(component_data); } for (int i = 0; i < components; ++i) { image_components[i].data = &data[i][0]; } // convert the image to the desired format and save it to the file int error = imagetopnm((opj_image_t*)image.GetLocal(), argv[2], 0); if (error) LOG(FATAL) << "image convert failed"; // cleanup status = api.opj_image_destroy(image.PtrNone()); if (!status.ok()) LOG(FATAL) << "image destroy failed: " << status; status = api.opj_stream_destroy(&stream_pointer); if (!status.ok()) LOG(FATAL) << "stream destroy failed: " << status; status = api.opj_destroy_codec(&codec_pointer); if (!status.ok()) LOG(FATAL) << "codec destroy failed: " << status; return EXIT_SUCCESS; } <|endoftext|>
<commit_before><commit_msg>`Species::render`: render only if `this->should_be_rendered`.<commit_after><|endoftext|>
<commit_before>#include <iostream> #include "Block.hpp" #include "Matrix4x4.hpp" #include "Matrix3x3.hpp" #include "vec.hpp" #include "PhongMaterial.hpp" using namespace rffalcon; // _element_indices are in the order of 3 sides: xmin, ymin, ymax GLuint Block::_element_indices[12] = { 1, 0, 7, 6, 0, 2, 6, 4, 1, 7, 3, 5 }; Block::Block(float x, float y, float z, float lengthX, float lengthY, float lengthZ) { _xmin = x; _xmax = x + lengthX; _ymin = y; _ymax = y + lengthY; _zmin = z; _zmax = z + lengthZ; _phongMaterial = std::make_shared<PhongMaterial>(PhongMaterial::PolishedCopper); } Block::~Block() { glDeleteBuffers(2, _vbo); glDeleteVertexArrays(1, _vao); } void Block::getMCBoundingBox(double* xyzBounds) const { double buffer = 0.25; xyzBounds[0] = _xmin - buffer; xyzBounds[1] = _xmax + buffer; xyzBounds[2] = _ymin - buffer; xyzBounds[3] = _ymax + buffer; xyzBounds[4] = _zmin - buffer; xyzBounds[5] = _zmax + buffer; } void Block::render() { if (!_initialized) { _initBlock(); _initialized = true; } glBindVertexArray(_vao[0]); GLint programId; glGetIntegerv(GL_CURRENT_PROGRAM, &programId); GLint pvaLoc_mcNormal = glGetAttribLocation(programId, "mcNormal"); if (pvaLoc_mcNormal < 0) { std::cerr << "Unable to find per-vertex attribute: 'mcNormal'" << std::endl; } else { glVertexAttrib3f(pvaLoc_mcNormal, 0.0, 0.0, 1.0); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); //float color2[] = { 0.8f, 0.8f, 0.0f }; //glUniform3fv(_ppuLoc_kd, 1, color2); glVertexAttrib3f(pvaLoc_mcNormal, 1.0, 0.0, 0.0); glDrawArrays(GL_TRIANGLE_STRIP, 2, 4); //float color3[] = { 0.0f, 0.8f, 0.0f }; //glUniform3fv(_ppuLoc_kd, 1, color3); glVertexAttrib3f(pvaLoc_mcNormal, 0.0, 0.0, -1.0); glDrawArrays(GL_TRIANGLE_STRIP, 4, 4); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _vbo[1]); //float color4[] = { 0.8f, 0.0f, 0.0f }; //glUniform3fv(_ppuLoc_kd, 1, color4); glVertexAttrib3f(pvaLoc_mcNormal, -1.0, 0.0, 0.0); glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_INT, (void*)0); //float color5[] = { 0.8f, 0.0f, 0.8f }; //glUniform3fv(_ppuLoc_kd, 1, color5); glVertexAttrib3f(pvaLoc_mcNormal, 0.0, -1.0, 0.0); glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_INT, (void*)(4 * sizeof(int))); //float color6[] = { 0.0f, 0.8f, 0.8f }; //glUniform3fv(_ppuLoc_kd, 1, color6); glVertexAttrib3f(pvaLoc_mcNormal, 0.0, 1.0, 0.0); glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_INT, (void*)(8 * sizeof(int))); } } void Block::_initBlock() { vec3 vertices[] = { { _xmin, _ymin, _zmax }, { _xmin, _ymax, _zmax }, { _xmax, _ymin, _zmax }, { _xmax, _ymax, _zmax }, { _xmax, _ymin, _zmin }, { _xmax, _ymax, _zmin }, { _xmin, _ymin, _zmin }, { _xmin, _ymax, _zmin } }; glGenVertexArrays(1, _vao); glBindVertexArray(_vao[0]); glGenBuffers(2, _vbo); glBindBuffer(GL_ARRAY_BUFFER, _vbo[0]); glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(vec3), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _vbo[1]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, 12 * sizeof(int), _element_indices, GL_STATIC_DRAW); GLint programId; glGetIntegerv(GL_CURRENT_PROGRAM, &programId); GLint pvaLoc_mcNormal = glGetAttribLocation(programId, "mcNormal"); GLint pvaLoc_mcPosition = glGetAttribLocation(programId, "mcPosition"); if (pvaLoc_mcPosition < 0) { std::cerr << "Unable to find per-vertex attribute: 'mcPosition'" << std::endl; } else { glVertexAttribPointer(pvaLoc_mcPosition, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(pvaLoc_mcPosition); } if (pvaLoc_mcNormal < 0) { std::cerr << "Unable to find per-vertex attribute: 'mcNormal'" << std::endl; } else { glDisableVertexAttribArray(pvaLoc_mcNormal); } } <commit_msg>Removing unnecessary include<commit_after>#include <iostream> #include "Block.hpp" #include "Matrix3x3.hpp" #include "vec.hpp" #include "PhongMaterial.hpp" using namespace rffalcon; // _element_indices are in the order of 3 sides: xmin, ymin, ymax GLuint Block::_element_indices[12] = { 1, 0, 7, 6, 0, 2, 6, 4, 1, 7, 3, 5 }; Block::Block(float x, float y, float z, float lengthX, float lengthY, float lengthZ) { _xmin = x; _xmax = x + lengthX; _ymin = y; _ymax = y + lengthY; _zmin = z; _zmax = z + lengthZ; _phongMaterial = std::make_shared<PhongMaterial>(PhongMaterial::PolishedCopper); } Block::~Block() { glDeleteBuffers(2, _vbo); glDeleteVertexArrays(1, _vao); } void Block::getMCBoundingBox(double* xyzBounds) const { double buffer = 0.25; xyzBounds[0] = _xmin - buffer; xyzBounds[1] = _xmax + buffer; xyzBounds[2] = _ymin - buffer; xyzBounds[3] = _ymax + buffer; xyzBounds[4] = _zmin - buffer; xyzBounds[5] = _zmax + buffer; } void Block::render() { if (!_initialized) { _initBlock(); _initialized = true; } glBindVertexArray(_vao[0]); GLint programId; glGetIntegerv(GL_CURRENT_PROGRAM, &programId); GLint pvaLoc_mcNormal = glGetAttribLocation(programId, "mcNormal"); if (pvaLoc_mcNormal < 0) { std::cerr << "Unable to find per-vertex attribute: 'mcNormal'" << std::endl; } else { glVertexAttrib3f(pvaLoc_mcNormal, 0.0, 0.0, 1.0); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); //float color2[] = { 0.8f, 0.8f, 0.0f }; //glUniform3fv(_ppuLoc_kd, 1, color2); glVertexAttrib3f(pvaLoc_mcNormal, 1.0, 0.0, 0.0); glDrawArrays(GL_TRIANGLE_STRIP, 2, 4); //float color3[] = { 0.0f, 0.8f, 0.0f }; //glUniform3fv(_ppuLoc_kd, 1, color3); glVertexAttrib3f(pvaLoc_mcNormal, 0.0, 0.0, -1.0); glDrawArrays(GL_TRIANGLE_STRIP, 4, 4); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _vbo[1]); //float color4[] = { 0.8f, 0.0f, 0.0f }; //glUniform3fv(_ppuLoc_kd, 1, color4); glVertexAttrib3f(pvaLoc_mcNormal, -1.0, 0.0, 0.0); glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_INT, (void*)0); //float color5[] = { 0.8f, 0.0f, 0.8f }; //glUniform3fv(_ppuLoc_kd, 1, color5); glVertexAttrib3f(pvaLoc_mcNormal, 0.0, -1.0, 0.0); glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_INT, (void*)(4 * sizeof(int))); //float color6[] = { 0.0f, 0.8f, 0.8f }; //glUniform3fv(_ppuLoc_kd, 1, color6); glVertexAttrib3f(pvaLoc_mcNormal, 0.0, 1.0, 0.0); glDrawElements(GL_TRIANGLE_STRIP, 4, GL_UNSIGNED_INT, (void*)(8 * sizeof(int))); } } void Block::_initBlock() { vec3 vertices[] = { { _xmin, _ymin, _zmax }, { _xmin, _ymax, _zmax }, { _xmax, _ymin, _zmax }, { _xmax, _ymax, _zmax }, { _xmax, _ymin, _zmin }, { _xmax, _ymax, _zmin }, { _xmin, _ymin, _zmin }, { _xmin, _ymax, _zmin } }; glGenVertexArrays(1, _vao); glBindVertexArray(_vao[0]); glGenBuffers(2, _vbo); glBindBuffer(GL_ARRAY_BUFFER, _vbo[0]); glBufferData(GL_ARRAY_BUFFER, 8 * sizeof(vec3), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _vbo[1]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, 12 * sizeof(int), _element_indices, GL_STATIC_DRAW); GLint programId; glGetIntegerv(GL_CURRENT_PROGRAM, &programId); GLint pvaLoc_mcNormal = glGetAttribLocation(programId, "mcNormal"); GLint pvaLoc_mcPosition = glGetAttribLocation(programId, "mcPosition"); if (pvaLoc_mcPosition < 0) { std::cerr << "Unable to find per-vertex attribute: 'mcPosition'" << std::endl; } else { glVertexAttribPointer(pvaLoc_mcPosition, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(pvaLoc_mcPosition); } if (pvaLoc_mcNormal < 0) { std::cerr << "Unable to find per-vertex attribute: 'mcNormal'" << std::endl; } else { glDisableVertexAttribArray(pvaLoc_mcNormal); } } <|endoftext|>
<commit_before>/* * This file is part of the statismo library. * * Author: Marcel Luethi ([email protected]) * * Copyright (c) 2011 University of Basel * 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 project's author nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef __PCAModelBuilder_TXX #define __PCAModelBuilder_TXX #include "PCAModelBuilder.h" #include <iostream> #include <Eigen/SVD> #include <Eigen/Eigenvalues> #include "CommonTypes.h" #include "Exceptions.h" namespace statismo { template <typename T> PCAModelBuilder<T>::PCAModelBuilder() : Superclass() { } template <typename T> typename PCAModelBuilder<T>::StatisticalModelType* PCAModelBuilder<T>::BuildNewModel(const DataItemListType& sampleDataList, double noiseVariance, bool computeScores, EigenValueMethod method) const { unsigned n = sampleDataList.size(); if (n <= 0) { throw StatisticalModelException("Provided empty sample set. Cannot build the sample matrix"); } unsigned p = sampleDataList.front()->GetSampleVector().rows(); const Representer<T>* representer = sampleDataList.front()->GetRepresenter(); // Compute the mean vector mu VectorType mu = VectorType::Zero(p); for (typename DataItemListType::const_iterator it = sampleDataList.begin(); it != sampleDataList.end(); ++it) { assert((*it)->GetSampleVector().rows() == p); // all samples must have same number of rows assert((*it)->GetRepresenter() == representer); // all samples have the same representer mu += (*it)->GetSampleVector(); } // Build the mean free sample matrix X0 MatrixType X0(n, p); unsigned i = 0; for (typename DataItemListType::const_iterator it = sampleDataList.begin(); it != sampleDataList.end(); ++it) { X0.row(i++) = (*it)->GetSampleVector() - mu; } // build the model StatisticalModelType* model = BuildNewModelInternal(representer, X0, mu, noiseVariance, method); // compute the scores if requested MatrixType scores; if (computeScores) { scores = this->ComputeScores(sampleDataList, model); } typename BuilderInfo::ParameterInfoList bi; bi.push_back(BuilderInfo::KeyValuePair("NoiseVariance ", Utils::toString(noiseVariance))); typename BuilderInfo::DataInfoList dataInfo; i = 0; for (typename DataItemListType::const_iterator it = sampleDataList.begin(); it != sampleDataList.end(); ++it, i++) { std::ostringstream os; os << "URI_" << i; dataInfo.push_back(BuilderInfo::KeyValuePair(os.str().c_str(),(*it)->GetDatasetURI())); } // finally add meta data to the model info BuilderInfo builderInfo("PCAModelBuilder", dataInfo, bi); ModelInfo::BuilderInfoList biList; biList.push_back(builderInfo); ModelInfo info(scores, biList); model->SetModelInfo(info); return model; } template <typename T> typename PCAModelBuilder<T>::StatisticalModelType* PCAModelBuilder<T>::BuildNewModelInternal(const Representer<T>* representer, const MatrixType& X0, const VectorType& mu, double noiseVariance, EigenValueMethod method) const { unsigned n = X0.rows(); unsigned p = X0.cols(); switch(method) { case JacobiSVD: typedef Eigen::JacobiSVD<MatrixType> SVDType; typedef Eigen::JacobiSVD<MatrixTypeDoublePrecision> SVDDoublePrecisionType; // We destinguish the case where we have more variables than samples and // the case where we have more samples than variable. // In the first case we compute the (smaller) inner product matrix instead of the full covariance matrix. // It is known that this has the same non-zero singular values as the covariance matrix. // Furthermore, it is possible to compute the corresponding eigenvectors of the covariance matrix from the // decomposition. if (n < p) { // we compute the eigenvectors of the covariance matrix by computing an SVD of the // n x n inner product matrix 1/(n-1) X0X0^T MatrixType Cov = X0 * X0.transpose() * 1.0/(n-1); SVDDoublePrecisionType SVD(Cov.cast<double>(), Eigen::ComputeThinV); VectorType singularValues = SVD.singularValues().cast<ScalarType>(); MatrixType V = SVD.matrixV().cast<ScalarType>(); unsigned numComponentsAboveTolerance = ((singularValues.array() - noiseVariance - Superclass::TOLERANCE) > 0).count(); // there can be at most n-1 nonzero singular values in this case. Everything else must be due to numerical inaccuracies unsigned numComponentsToKeep = std::min(numComponentsAboveTolerance, n - 1); // compute the pseudo inverse of the square root of the singular values // which is then needed to recompute the PCA basis VectorType singSqrt = singularValues.array().sqrt(); VectorType singSqrtInv = VectorType::Zero(singSqrt.rows()); for (unsigned i = 0; i < numComponentsToKeep; i++) { assert(singSqrt(i) > Superclass::TOLERANCE); singSqrtInv(i) = 1.0 / singSqrt(i); } if (numComponentsToKeep == 0) { throw StatisticalModelException("All the eigenvalues are below the given tolerance. Model cannot be built."); } // we recover the eigenvectors U of the full covariance matrix from the eigenvectors V of the inner product matrix. // We use the fact that if we decompose X as X=UDV^T, then we get X^TX = UD^2U^T and XX^T = VD^2V^T (exploiting the orthogonormality // of the matrix U and V from the SVD). The additional factor sqrt(n-1) is to compensate for the 1/sqrt(n-1) in the formula // for the covariance matrix. MatrixType pcaBasis = X0.transpose() * V * singSqrtInv.asDiagonal(); pcaBasis /= sqrt(n - 1.0); pcaBasis.conservativeResize(Eigen::NoChange, numComponentsToKeep); VectorType sampleVarianceVector = singularValues.topRows(numComponentsToKeep); VectorType pcaVariance = (sampleVarianceVector - VectorType::Ones(numComponentsToKeep) * noiseVariance); StatisticalModelType* model = StatisticalModelType::Create(representer, mu, pcaBasis, pcaVariance, noiseVariance); return model; } else { // we compute an SVD of the full p x p covariance matrix 1/(n-1) X0^TX0 directly SVDType SVD(X0.transpose() * X0, Eigen::ComputeThinU); VectorType singularValues = SVD.singularValues(); unsigned numComponentsToKeep = ((singularValues.array() - noiseVariance - Superclass::TOLERANCE) > 0).count(); MatrixType pcaBasis = SVD.matrixU(); pcaBasis /= sqrt(n - 1.0); pcaBasis.conservativeResize(Eigen::NoChange, numComponentsToKeep); if (numComponentsToKeep == 0) { throw StatisticalModelException("All the eigenvalues are below the given tolerance. Model cannot be built."); } VectorType sampleVarianceVector = singularValues.topRows(numComponentsToKeep); VectorType pcaVariance = (sampleVarianceVector - VectorType::Ones(numComponentsToKeep) * noiseVariance); StatisticalModelType* model = StatisticalModelType::Create(representer, mu, pcaBasis, pcaVariance, noiseVariance); return model; } break; case SelfAdjointEigenSolver: { // we compute the eigenvalues/eigenvectors of the full p x p covariance matrix 1/(n-1) X0^TX0 directly typedef Eigen::SelfAdjointEigenSolver<MatrixType> SelfAdjointEigenSolver; SelfAdjointEigenSolver es; es.compute(X0.transpose() * X0); VectorType eigenValues = es.eigenvalues().reverse(); // SelfAdjointEigenSolver orders the eigenvalues in increasing order unsigned numComponentsToKeep = ((eigenValues.array() - noiseVariance - Superclass::TOLERANCE) > 0).count(); MatrixType pcaBasis = es.eigenvectors().rowwise().reverse(); pcaBasis /= sqrt(n - 1.0); pcaBasis.conservativeResize(Eigen::NoChange, numComponentsToKeep); if (numComponentsToKeep == 0) { throw StatisticalModelException("All the eigenvalues are below the given tolerance. Model cannot be built."); } VectorType sampleVarianceVector = eigenValues.topRows(numComponentsToKeep); VectorType pcaVariance = (sampleVarianceVector - VectorType::Ones(numComponentsToKeep) * noiseVariance); StatisticalModelType* model = StatisticalModelType::Create(representer, mu, pcaBasis, pcaVariance, noiseVariance); return model; } break; default: throw StatisticalModelException("Unrecognized decomposition/eigenvalue solver method."); return 0; break; } } } // namespace statismo #endif <commit_msg>fixed bug in mean computation<commit_after>/* * This file is part of the statismo library. * * Author: Marcel Luethi ([email protected]) * * Copyright (c) 2011 University of Basel * 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 project's author nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef __PCAModelBuilder_TXX #define __PCAModelBuilder_TXX #include "PCAModelBuilder.h" #include <iostream> #include <Eigen/SVD> #include <Eigen/Eigenvalues> #include "CommonTypes.h" #include "Exceptions.h" namespace statismo { template <typename T> PCAModelBuilder<T>::PCAModelBuilder() : Superclass() { } template <typename T> typename PCAModelBuilder<T>::StatisticalModelType* PCAModelBuilder<T>::BuildNewModel(const DataItemListType& sampleDataList, double noiseVariance, bool computeScores, EigenValueMethod method) const { unsigned n = sampleDataList.size(); if (n <= 0) { throw StatisticalModelException("Provided empty sample set. Cannot build the sample matrix"); } unsigned p = sampleDataList.front()->GetSampleVector().rows(); const Representer<T>* representer = sampleDataList.front()->GetRepresenter(); // Compute the mean vector mu VectorType mu = VectorType::Zero(p); for (typename DataItemListType::const_iterator it = sampleDataList.begin(); it != sampleDataList.end(); ++it) { assert((*it)->GetSampleVector().rows() == p); // all samples must have same number of rows assert((*it)->GetRepresenter() == representer); // all samples have the same representer mu += (*it)->GetSampleVector(); } mu /= n; // Build the mean free sample matrix X0 MatrixType X0(n, p); unsigned i = 0; for (typename DataItemListType::const_iterator it = sampleDataList.begin(); it != sampleDataList.end(); ++it) { X0.row(i++) = (*it)->GetSampleVector() - mu; } // build the model StatisticalModelType* model = BuildNewModelInternal(representer, X0, mu, noiseVariance, method); // compute the scores if requested MatrixType scores; computeScores = false; if (computeScores) { scores = this->ComputeScores(sampleDataList, model); } typename BuilderInfo::ParameterInfoList bi; bi.push_back(BuilderInfo::KeyValuePair("NoiseVariance ", Utils::toString(noiseVariance))); typename BuilderInfo::DataInfoList dataInfo; i = 0; for (typename DataItemListType::const_iterator it = sampleDataList.begin(); it != sampleDataList.end(); ++it, i++) { std::ostringstream os; os << "URI_" << i; dataInfo.push_back(BuilderInfo::KeyValuePair(os.str().c_str(),(*it)->GetDatasetURI())); } // finally add meta data to the model info BuilderInfo builderInfo("PCAModelBuilder", dataInfo, bi); ModelInfo::BuilderInfoList biList; biList.push_back(builderInfo); ModelInfo info(scores, biList); model->SetModelInfo(info); return model; } template <typename T> typename PCAModelBuilder<T>::StatisticalModelType* PCAModelBuilder<T>::BuildNewModelInternal(const Representer<T>* representer, const MatrixType& X0, const VectorType& mu, double noiseVariance, EigenValueMethod method) const { unsigned n = X0.rows(); unsigned p = X0.cols(); switch(method) { case JacobiSVD: typedef Eigen::JacobiSVD<MatrixType> SVDType; typedef Eigen::JacobiSVD<MatrixTypeDoublePrecision> SVDDoublePrecisionType; // We destinguish the case where we have more variables than samples and // the case where we have more samples than variable. // In the first case we compute the (smaller) inner product matrix instead of the full covariance matrix. // It is known that this has the same non-zero singular values as the covariance matrix. // Furthermore, it is possible to compute the corresponding eigenvectors of the covariance matrix from the // decomposition. if (n < p) { // we compute the eigenvectors of the covariance matrix by computing an SVD of the // n x n inner product matrix 1/(n-1) X0X0^T MatrixType Cov = X0 * X0.transpose() * 1.0/(n-1); SVDDoublePrecisionType SVD(Cov.cast<double>(), Eigen::ComputeThinV); VectorType singularValues = SVD.singularValues().cast<ScalarType>(); MatrixType V = SVD.matrixV().cast<ScalarType>(); unsigned numComponentsAboveTolerance = ((singularValues.array() - noiseVariance - Superclass::TOLERANCE) > 0).count(); // there can be at most n-1 nonzero singular values in this case. Everything else must be due to numerical inaccuracies unsigned numComponentsToKeep = std::min(numComponentsAboveTolerance, n - 1); // compute the pseudo inverse of the square root of the singular values // which is then needed to recompute the PCA basis VectorType singSqrt = singularValues.array().sqrt(); VectorType singSqrtInv = VectorType::Zero(singSqrt.rows()); for (unsigned i = 0; i < numComponentsToKeep; i++) { assert(singSqrt(i) > Superclass::TOLERANCE); singSqrtInv(i) = 1.0 / singSqrt(i); } if (numComponentsToKeep == 0) { throw StatisticalModelException("All the eigenvalues are below the given tolerance. Model cannot be built."); } // we recover the eigenvectors U of the full covariance matrix from the eigenvectors V of the inner product matrix. // We use the fact that if we decompose X as X=UDV^T, then we get X^TX = UD^2U^T and XX^T = VD^2V^T (exploiting the orthogonormality // of the matrix U and V from the SVD). The additional factor sqrt(n-1) is to compensate for the 1/sqrt(n-1) in the formula // for the covariance matrix. MatrixType pcaBasis = X0.transpose() * V * singSqrtInv.asDiagonal(); pcaBasis /= sqrt(n - 1.0); pcaBasis.conservativeResize(Eigen::NoChange, numComponentsToKeep); VectorType sampleVarianceVector = singularValues.topRows(numComponentsToKeep); VectorType pcaVariance = (sampleVarianceVector - VectorType::Ones(numComponentsToKeep) * noiseVariance); StatisticalModelType* model = StatisticalModelType::Create(representer, mu, pcaBasis, pcaVariance, noiseVariance); return model; } else { // we compute an SVD of the full p x p covariance matrix 1/(n-1) X0^TX0 directly SVDType SVD(X0.transpose() * X0, Eigen::ComputeThinU); VectorType singularValues = SVD.singularValues(); unsigned numComponentsToKeep = ((singularValues.array() - noiseVariance - Superclass::TOLERANCE) > 0).count(); MatrixType pcaBasis = SVD.matrixU(); pcaBasis /= sqrt(n - 1.0); pcaBasis.conservativeResize(Eigen::NoChange, numComponentsToKeep); if (numComponentsToKeep == 0) { throw StatisticalModelException("All the eigenvalues are below the given tolerance. Model cannot be built."); } VectorType sampleVarianceVector = singularValues.topRows(numComponentsToKeep); VectorType pcaVariance = (sampleVarianceVector - VectorType::Ones(numComponentsToKeep) * noiseVariance); StatisticalModelType* model = StatisticalModelType::Create(representer, mu, pcaBasis, pcaVariance, noiseVariance); return model; } break; case SelfAdjointEigenSolver: { // we compute the eigenvalues/eigenvectors of the full p x p covariance matrix 1/(n-1) X0^TX0 directly typedef Eigen::SelfAdjointEigenSolver<MatrixType> SelfAdjointEigenSolver; SelfAdjointEigenSolver es; es.compute(X0.transpose() * X0); VectorType eigenValues = es.eigenvalues().reverse(); // SelfAdjointEigenSolver orders the eigenvalues in increasing order unsigned numComponentsToKeep = ((eigenValues.array() - noiseVariance - Superclass::TOLERANCE) > 0).count(); MatrixType pcaBasis = es.eigenvectors().rowwise().reverse(); pcaBasis /= sqrt(n - 1.0); pcaBasis.conservativeResize(Eigen::NoChange, numComponentsToKeep); if (numComponentsToKeep == 0) { throw StatisticalModelException("All the eigenvalues are below the given tolerance. Model cannot be built."); } VectorType sampleVarianceVector = eigenValues.topRows(numComponentsToKeep); VectorType pcaVariance = (sampleVarianceVector - VectorType::Ones(numComponentsToKeep) * noiseVariance); StatisticalModelType* model = StatisticalModelType::Create(representer, mu, pcaBasis, pcaVariance, noiseVariance); return model; } break; default: throw StatisticalModelException("Unrecognized decomposition/eigenvalue solver method."); return 0; break; } } } // namespace statismo #endif <|endoftext|>
<commit_before>#include <limits> #include <stdexcept> //test #include <iostream> using namespace std; #include <fstream> #include <stdlib.h> #include "visual.h" #include "bvh_node.h" BVHNode::BVHNode() { this->left = NULL; this->right = NULL; } BVHNode::~BVHNode() { // TODO } void BVHNode::insert(Mesh const& mesh, std::vector<unsigned int>* faceIDs) { this->triangles.push_back(Triangle(&mesh, 0)); Vec3f min = this->triangles.back().getAABBMin(); Vec3f max = this->triangles.back().getAABBMax(); for (unsigned int var = 1; var < faceIDs->size(); ++var) { this->triangles.push_back(Triangle(&mesh, var)); for (int i = 0; i < 3; i++) { if (min[i] > this->triangles.back().getAABBMin()[i]) min[i] = this->triangles.back().getAABBMin()[i]; if (max[i] < this->triangles.back().getAABBMax()[i]) max[i] = this->triangles.back().getAABBMax()[i]; } } std::vector<Triangle> left; std::vector<Triangle> right; Vec3f middle = max; int axis = aabb.getLongestAxis(); middle[axis] = (min[axis] + max[axis]) / 2; AABB half = AABB(min, middle); while (this->triangles.size() > 0) { if (half.inside(this->triangles.back().getCentroid())) left.push_back(this->triangles.back()); else right.push_back(this->triangles.back()); this->triangles.pop_back(); } this->aabb = AABB(min, max); if (left.size() > MAX_LEAF_TRIANGLES) { this->left = new BVHNode(); this->left->insert(&left); } if (right.size() > MAX_LEAF_TRIANGLES) { this->right = new BVHNode(); this->right->insert(&right); } } void BVHNode::insert(std::vector<Triangle>* triangles) { if (triangles->size() == 0) return; this->triangles.push_back(triangles->back()); Vec3f min = this->triangles.back().getAABBMin(); Vec3f max = this->triangles.back().getAABBMax(); triangles->pop_back(); while(triangles->size() > 0) { this->triangles.push_back(triangles->back()); triangles->pop_back(); for (int i = 0; i < 3; i++) { if (min[i] > this->triangles.back().getAABBMin()[i]) min[i] = this->triangles.back().getAABBMin()[i]; if (max[i] < this->triangles.back().getAABBMax()[i]) max[i] = this->triangles.back().getAABBMax()[i]; } } this->aabb = AABB(min, max); if (this->triangles.size() <= MAX_LEAF_TRIANGLES) return; std::vector<Triangle> left; std::vector<Triangle> right; Vec3f middle = max; int axis = aabb.getLongestAxis(); middle[axis] = (min[axis] + max[axis]) / 2; AABB half = AABB(min, middle); while (this->triangles.size() > 0) { if (half.inside(this->triangles.back().getCentroid())) left.push_back(this->triangles.back()); else right.push_back(this->triangles.back()); this->triangles.pop_back(); } if (left.size() == 0) { left.push_back(right.back()); right.pop_back(); } if (right.size() == 0) { right.push_back(left.back()); left.pop_back(); } this->left = new BVHNode(); this->left->insert(&left); this->right = new BVHNode(); this->right->insert(&right); } bool BVHNode::intersect(Ray const& ray, Intersection* intersection) const { bool hitl = false; bool hitr = false; if (this->aabb.intersect(ray)) { if (left == NULL && right == NULL) { for (unsigned int var = 0; var < triangles.size(); ++var) { if (triangles.at(var).intersect(ray, intersection)) return true; } } else { hitl=left->intersect(ray, intersection); hitr=right->intersect(ray, intersection); if (hitl) return true; if (hitr) return true; } } return false; } <commit_msg>refactored intersect<commit_after>#include <limits> #include <stdexcept> #include <iostream> #include <fstream> #include <stdlib.h> #include "visual.h" #include "bvh_node.h" using namespace std; BVHNode::BVHNode() { this->left = NULL; this->right = NULL; } BVHNode::~BVHNode() { // TODO } void BVHNode::insert(Mesh const& mesh, std::vector<unsigned int>* faceIDs) { this->triangles.push_back(Triangle(&mesh, 0)); Vec3f min = this->triangles.back().getAABBMin(); Vec3f max = this->triangles.back().getAABBMax(); for (unsigned int var = 1; var < faceIDs->size(); ++var) { this->triangles.push_back(Triangle(&mesh, var)); for (int i = 0; i < 3; i++) { if (min[i] > this->triangles.back().getAABBMin()[i]) min[i] = this->triangles.back().getAABBMin()[i]; if (max[i] < this->triangles.back().getAABBMax()[i]) max[i] = this->triangles.back().getAABBMax()[i]; } } std::vector<Triangle> left; std::vector<Triangle> right; Vec3f middle = max; int axis = aabb.getLongestAxis(); middle[axis] = (min[axis] + max[axis]) / 2; AABB half = AABB(min, middle); while (this->triangles.size() > 0) { if (half.inside(this->triangles.back().getCentroid())) left.push_back(this->triangles.back()); else right.push_back(this->triangles.back()); this->triangles.pop_back(); } this->aabb = AABB(min, max); if (left.size() > MAX_LEAF_TRIANGLES) { this->left = new BVHNode(); this->left->insert(&left); } if (right.size() > MAX_LEAF_TRIANGLES) { this->right = new BVHNode(); this->right->insert(&right); } } void BVHNode::insert(std::vector<Triangle>* triangles) { this->triangles.push_back(triangles->back()); Vec3f min = this->triangles.back().getAABBMin(); Vec3f max = this->triangles.back().getAABBMax(); triangles->pop_back(); while(triangles->size() > 0) { this->triangles.push_back(triangles->back()); triangles->pop_back(); for (int i = 0; i < 3; i++) { if (min[i] > this->triangles.back().getAABBMin()[i]) min[i] = this->triangles.back().getAABBMin()[i]; if (max[i] < this->triangles.back().getAABBMax()[i]) max[i] = this->triangles.back().getAABBMax()[i]; } } this->aabb = AABB(min, max); if (this->triangles.size() <= MAX_LEAF_TRIANGLES) return; std::vector<Triangle> left; std::vector<Triangle> right; Vec3f middle = max; int axis = aabb.getLongestAxis(); middle[axis] = (min[axis] + max[axis]) / 2; AABB half = AABB(min, middle); while (this->triangles.size() > 0) { if (half.inside(this->triangles.back().getCentroid())) left.push_back(this->triangles.back()); else right.push_back(this->triangles.back()); this->triangles.pop_back(); } if (left.size() == 0) { left.push_back(right.back()); right.pop_back(); } if (right.size() == 0) { right.push_back(left.back()); left.pop_back(); } this->left = new BVHNode(); this->left->insert(&left); this->right = new BVHNode(); this->right->insert(&right); } bool BVHNode::intersect(Ray const& ray, Intersection* intersection) const { bool hitl = false; bool hitr = false; if (this->aabb.intersect(ray)) { if (left == NULL && right == NULL) { for (unsigned int var = 0; var < triangles.size(); ++var) if (triangles.at(var).intersect(ray, intersection)) return true; } else { hitl = left->intersect(ray, intersection); hitr = right->intersect(ray, intersection); return hitl || hitr; } } return false; } <|endoftext|>
<commit_before>#include <limits> #include <stdexcept> #include <iostream> #include <fstream> #include <stdlib.h> #include "visual.h" #include "bvh_node.h" using namespace std; BVHNode::BVHNode() { this->left = NULL; this->right = NULL; } BVHNode::~BVHNode() { // TODO } void BVHNode::insert(Mesh const& mesh, std::vector<unsigned int>* faceIDs) { this->triangles.push_back(Triangle(&mesh, 0)); Vec3f min = this->triangles.back().getAABBMin(); Vec3f max = this->triangles.back().getAABBMax(); for (unsigned int var = 1; var < faceIDs->size(); ++var) { this->triangles.push_back(Triangle(&mesh, var)); for (int i = 0; i < 3; i++) { if (min[i] > this->triangles.back().getAABBMin()[i]) min[i] = this->triangles.back().getAABBMin()[i]; if (max[i] < this->triangles.back().getAABBMax()[i]) max[i] = this->triangles.back().getAABBMax()[i]; } } std::vector<Triangle> left; std::vector<Triangle> right; Vec3f middle = max; int axis = aabb.getLongestAxis(); middle[axis] = (min[axis] + max[axis]) / 2; AABB half = AABB(min, middle); while (this->triangles.size() > 0) { if (half.inside(this->triangles.back().getCentroid())) left.push_back(this->triangles.back()); else right.push_back(this->triangles.back()); this->triangles.pop_back(); } this->aabb = AABB(min, max); if (left.size() > MAX_LEAF_TRIANGLES) { this->left = new BVHNode(); this->left->insert(&left); } if (right.size() > MAX_LEAF_TRIANGLES) { this->right = new BVHNode(); this->right->insert(&right); } } void BVHNode::insert(std::vector<Triangle>* triangles) { this->triangles.push_back(triangles->back()); Vec3f min = this->triangles.back().getAABBMin(); Vec3f max = this->triangles.back().getAABBMax(); triangles->pop_back(); while(triangles->size() > 0) { this->triangles.push_back(triangles->back()); triangles->pop_back(); for (int i = 0; i < 3; i++) { if (min[i] > this->triangles.back().getAABBMin()[i]) min[i] = this->triangles.back().getAABBMin()[i]; if (max[i] < this->triangles.back().getAABBMax()[i]) max[i] = this->triangles.back().getAABBMax()[i]; } } this->aabb = AABB(min, max); if (this->triangles.size() <= MAX_LEAF_TRIANGLES) return; std::vector<Triangle> left; std::vector<Triangle> right; Vec3f middle = max; int axis = aabb.getLongestAxis(); middle[axis] = (min[axis] + max[axis]) / 2; AABB half = AABB(min, middle); while (this->triangles.size() > 0) { if (half.inside(this->triangles.back().getCentroid())) left.push_back(this->triangles.back()); else right.push_back(this->triangles.back()); this->triangles.pop_back(); } if (left.size() == 0) { left.push_back(right.back()); right.pop_back(); } if (right.size() == 0) { right.push_back(left.back()); left.pop_back(); } this->left = new BVHNode(); this->left->insert(&left); this->right = new BVHNode(); this->right->insert(&right); } bool BVHNode::intersect(Ray const& ray, Intersection* intersection) const { bool hitl = false; bool hitr = false; if (this->aabb.intersect(ray)) { if (left == NULL && right == NULL) { for (unsigned int var = 0; var < triangles.size(); ++var) if (triangles.at(var).intersect(ray, intersection)) return true; } else { hitl = left->intersect(ray, intersection); hitr = right->intersect(ray, intersection); return hitl || hitr; } } return false; } <commit_msg>comments added<commit_after>#include <limits> #include <stdexcept> #include <iostream> #include <fstream> #include <stdlib.h> #include "visual.h" #include "bvh_node.h" using namespace std; BVHNode::BVHNode() { this->left = NULL; this->right = NULL; } BVHNode::~BVHNode() { // TODO } void BVHNode::insert(Mesh const& mesh, std::vector<unsigned int>* faceIDs) { std::vector<Triangle> left; std::vector<Triangle> right; Vec3f min; Vec3f max; Vec3f middle; int axis; AABB half; //erstelle erste Dreieck und setzte Baseline für min/max des AABB this->triangles.push_back(Triangle(&mesh, 0)); min = this->triangles.back().getAABBMin(); max = this->triangles.back().getAABBMax(); //füge alle Dreiecke ein und prüfe ob neues min/max gefunden wurde for (unsigned int var = 1; var < faceIDs->size(); ++var) { this->triangles.push_back(Triangle(&mesh, var)); for (int i = 0; i < 3; i++) { if (min[i] > this->triangles.back().getAABBMin()[i]) min[i] = this->triangles.back().getAABBMin()[i]; if (max[i] < this->triangles.back().getAABBMax()[i]) max[i] = this->triangles.back().getAABBMax()[i]; } } this->aabb = AABB(min, max); //prüfe welche Achse die längste ist und teile AABB in der Mitte an dieser middle = max; axis = aabb.getLongestAxis(); middle[axis] = (min[axis] + max[axis]) / 2; half = AABB(min, middle); //teile Dreiecke in Dreiecke die im neuen AABB sind und Dreicke die im anderen AABB sind while (this->triangles.size() > 0) { if (half.inside(this->triangles.back().getCentroid())) left.push_back(this->triangles.back()); else right.push_back(this->triangles.back()); this->triangles.pop_back(); } //erstelle Kinder if (left.size() > MAX_LEAF_TRIANGLES) { this->left = new BVHNode(); this->left->insert(&left);} if (right.size() > MAX_LEAF_TRIANGLES) { this->right = new BVHNode(); this->right->insert(&right);} } void BVHNode::insert(std::vector<Triangle>* triangles) { std::vector<Triangle> left,right; Vec3f min,max,middle; AABB half; int axis; //prüfe Triangle größe if (triangles->size() == 0) return; //erstelle erste Dreieck und setzte Baseline für min/max des AABB this->triangles.push_back(triangles->back()); min = this->triangles.back().getAABBMin(); max = this->triangles.back().getAABBMax(); triangles->pop_back(); //füge alle übergebenen Dreiecke ein und prüfe ob neues min/max gefunden wurde while(triangles->size() > 0) { this->triangles.push_back(triangles->back()); triangles->pop_back(); for (int i = 0; i < 3; i++) { if (min[i] > this->triangles.back().getAABBMin()[i]) min[i] = this->triangles.back().getAABBMin()[i]; if (max[i] < this->triangles.back().getAABBMax()[i]) max[i] = this->triangles.back().getAABBMax()[i]; } } //erstelle AAB und prüfe ob der aktuelle Knoten this->aabb = AABB(min, max); if (this->triangles.size() <= MAX_LEAF_TRIANGLES) return; //prüfe welche Achse die längste ist und teile AABB in der Mitte an dieser middle = max; axis = aabb.getLongestAxis(); middle[axis] = (min[axis] + max[axis]) / 2; half = AABB(min, middle); //teile Dreiecke in Dreiecke die im neuen AABB sind und Dreicke die im anderen AABB sind while (this->triangles.size() > 0) { if (half.inside(this->triangles.back().getCentroid())) left.push_back(this->triangles.back()); else right.push_back(this->triangles.back()); this->triangles.pop_back(); } //prüfe ob trotz des Versuchs aufteilen kein Dreieck in if (left.size() == 0) { left.push_back(right.back()); right.pop_back();} if (right.size() == 0) { right.push_back(left.back()); left.pop_back();} //erstelle Kinder this->left = new BVHNode(); this->left->insert(&left); this->right = new BVHNode(); this->right->insert(&right); } bool BVHNode::intersect(Ray const& ray, Intersection* intersection) const { bool hitl = false; bool hitr = false; //prüft ob der Strahl den aktuellen Knoten/dessen Kinder trifft if (this->aabb.intersect(ray)) { //Blatt, prüfe für jedes Dreieck ob der Strahl es trifft if (left == NULL && right == NULL) { for (unsigned int var = 0; var < triangles.size(); ++var) if (triangles.at(var).intersect(ray, intersection)) return true; } //kein Blatt, rek. Aufruf else { hitl = left->intersect(ray, intersection); hitr = right->intersect(ray, intersection); return hitl || hitr; } } return false; } <|endoftext|>
<commit_before>/************************************************************************ Module: otherArrays.cxx Language: C++ Date: $Date$ Version: $Revision$ ************************************************************************/ // All tests need: // the following include // a Selector proc // a Comparator proc // a Test proc // and a main #include "rtOtherTestBase.h" void SelectorCommand(ostream& strm) { strm << "grep -v 0x | grep -v Modified "; } void ComparatorCommand(ostream& strm) { strm << "diff -b"; } #include "vtkCharArray.h" #include "vtkUnsignedCharArray.h" #include "vtkIntArray.h" #include "vtkUnsignedIntArray.h" #include "vtkLongArray.h" #include "vtkUnsignedLongArray.h" #include "vtkShortArray.h" #include "vtkUnsignedShortArray.h" #include "vtkFloatArray.h" #include "vtkDoubleArray.h" #define SIZE 1000 template <class T, class A> static int doArrayTest (ostream& strm, T *ptr, A *array, int size) { T *ptr2; float tuple1[SIZE/100]; double tuple3[SIZE/100]; float *tuple2; int i; strm << "\tSetArray..."; ptr->SetArray(array, size, 1); strm << "OK" << endl; strm << "\tSetNumberOfTuples..."; ptr->SetNumberOfTuples (100); if (ptr->GetNumberOfTuples() == 100) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tSetNumberOfComponents..."; ptr->SetNumberOfComponents (10); if (ptr->GetNumberOfComponents() == 10) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tMakeObject..."; if (ptr2 = ptr->SafeDownCast(ptr->MakeObject())) { if (ptr2->GetNumberOfComponents() == 10) strm << "OK" << endl; else strm << "FAILED" << endl; } else { strm << "FAILED" << endl; } strm << "\tGetTuple(i)..."; tuple2 = ptr->GetTuple (2); int passed = 1; for (i = 0; i < 10; i++) { strm << *(tuple2 + i) << " "; if (*(tuple2 + i) != (20 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tGetTuple(i, float *tuple)..."; ptr->GetTuple (3, tuple1); passed = 1; for (i = 0; i < 10; i++) { strm << tuple1[i] << " "; if (tuple1[i] != (30 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tGetTuple(i, double *tuple)..."; ptr->GetTuple (4, tuple3); passed = 1; for (i = 0; i < 10; i++) { strm << tuple3[i] << " "; if (tuple3[i] != (40 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tvtkDataArray::GetTuple(i, double *tuple)..."; ptr->vtkDataArray::GetTuple (4, tuple3); passed = 1; for (i = 0; i < 10; i++) { strm << tuple3[i] << " "; if (tuple3[i] != (40 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tSetTuple(i, float *tuple)..."; ptr->SetTuple (99, tuple1); for (i=0; i < 10; i++) tuple1[i] = 0; ptr->GetTuple (99, tuple1); passed = 1; for (i = 0; i < 10; i++) { strm << tuple1[i] << " "; if (tuple1[i] != (30 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tSetTuple(i, double *tuple)..."; ptr->SetTuple (99, tuple3); for (i=0; i < 10; i++) tuple3[i] = 0; ptr->GetTuple (99, tuple3); passed = 1; for (i = 0; i < 10; i++) { strm << tuple3[i] << " "; if (tuple3[i] != (40 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tvtkDataArray::SetTuple(i, double *tuple)..."; ptr->vtkDataArray::SetTuple (99, tuple3); for (i=0; i < 10; i++) tuple3[i] = 0; ptr->GetTuple (99, tuple3); passed = 1; for (i = 0; i < 10; i++) { strm << tuple3[i] << " "; if (tuple3[i] != (40 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tInsertTuple(i, float *tuple)..."; ptr->InsertTuple (100, tuple1); for (i=0; i < 10; i++) tuple1[i] = 0; ptr->GetTuple (100, tuple1); passed = 1; for (i = 0; i < 10; i++) { strm << tuple1[i] << " "; if (tuple1[i] != (30 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tInsertTuple(i, double *tuple)..."; ptr->InsertTuple (100, tuple3); for (i=0; i < 10; i++) tuple3[i] = 0; ptr->GetTuple (100, tuple3); passed = 1; for (i = 0; i < 10; i++) { strm << tuple3[i] << " "; if (tuple3[i] != (40 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tvtkDataArray::InsertTuple(i, double *tuple)..."; ptr->vtkDataArray::InsertTuple (100, tuple3); for (i=0; i < 10; i++) tuple3[i] = 0; ptr->GetTuple (100, tuple3); passed = 1; for (i = 0; i < 10; i++) { strm << tuple3[i] << " "; if (tuple3[i] != (40 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tInsertNextTuple(float *tuple)..."; ptr->InsertNextTuple (tuple1); for (i=0; i < 10; i++) tuple1[i] = 0; ptr->GetTuple (101, tuple1); passed = 1; for (i = 0; i < 10; i++) { strm << tuple1[i] << " "; if (tuple1[i] != (30 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tInsertNextTuple(double *tuple)..."; ptr->InsertNextTuple (tuple3); for (i=0; i < 10; i++) tuple3[i] = 0; ptr->GetTuple (102, tuple3); passed = 1; for (i = 0; i < 10; i++) { strm << tuple3[i] << " "; if (tuple3[i] != (40 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tvtkDataArray::InsertNextTuple(double *tuple)..."; ptr->vtkDataArray::InsertNextTuple (tuple3); for (i=0; i < 10; i++) tuple3[i] = 0; ptr->GetTuple (102, tuple3); passed = 1; for (i = 0; i < 10; i++) { strm << tuple3[i] << " "; if (tuple3[i] != (40 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tvtkDataArray::GetData..."; vtkFloatArray *farray = vtkFloatArray::New(); farray->SetNumberOfComponents(1); ptr->vtkDataArray::GetData (0, 59, 1, 1, *farray); passed = 1; for (i = 0; i < 10; i++) { strm << farray->GetTuple(i)[0] << " "; if (farray->GetTuple(i)[0] != (1 + i*10)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; farray->Delete(); strm << "PrintSelf..." << endl; strm << *ptr; return 0; } void Test(ostream& strm) { { strm << "Test CharArray" << endl; vtkCharArray *ptr = vtkCharArray::New(); char *array = new char[SIZE]; for (int i = 0; i < SIZE; i++) *(array + i ) = i; doArrayTest (strm, ptr, array, SIZE); ptr->Delete(); delete []array; } { strm << "Test UnsignedCharArray" << endl; vtkUnsignedCharArray *ptr = vtkUnsignedCharArray::New(); unsigned char *array = new unsigned char[SIZE]; for (int i = 0; i < SIZE; i++) *(array + i ) = i; doArrayTest (strm, ptr, array, SIZE); ptr->Delete(); delete []array; } { strm << "Test IntArray" << endl; vtkIntArray *ptr = vtkIntArray::New(); int *array = new int[SIZE]; for (int i = 0; i < SIZE; i++) *(array + i ) = i; doArrayTest (strm, ptr, array, SIZE); ptr->Delete(); delete []array; } { strm << "Test UnsignedIntArray" << endl; vtkUnsignedIntArray *ptr = vtkUnsignedIntArray::New(); unsigned int *array = new unsigned int[SIZE]; for (int i = 0; i < SIZE; i++) *(array + i ) = i; doArrayTest (strm, ptr, array, SIZE); ptr->Delete(); delete []array; } { strm << "Test LongArray" << endl; vtkLongArray *ptr = vtkLongArray::New(); long *array = new long[SIZE]; for (int i = 0; i < SIZE; i++) *(array + i ) = i; doArrayTest (strm, ptr, array, SIZE); ptr->Delete(); delete []array; } { strm << "Test UnsignedLongArray" << endl; vtkUnsignedLongArray *ptr = vtkUnsignedLongArray::New(); unsigned long *array = new unsigned long[SIZE]; for (int i = 0; i < SIZE; i++) *(array + i ) = i; doArrayTest (strm, ptr, array, SIZE); ptr->Delete(); delete []array; } { strm << "Test ShortArray" << endl; vtkShortArray *ptr = vtkShortArray::New(); short *array = new short[SIZE]; for (int i = 0; i < SIZE; i++) *(array + i ) = i; doArrayTest (strm, ptr, array, SIZE); ptr->Delete(); delete []array; } { strm << "Test UnsignedShortArray" << endl; vtkUnsignedShortArray *ptr = vtkUnsignedShortArray::New(); unsigned short *array = new unsigned short[SIZE]; for (int i = 0; i < SIZE; i++) *(array + i ) = i; doArrayTest (strm, ptr, array, SIZE); ptr->Delete(); delete []array; } { strm << "Test FloatArray" << endl; vtkFloatArray *ptr = vtkFloatArray::New(); float *array = new float[SIZE]; for (int i = 0; i < SIZE; i++) *(array + i ) = i; doArrayTest (strm, ptr, array, SIZE); ptr->Delete(); delete []array; } { strm << "Test DoubleArray" << endl; vtkDoubleArray *ptr = vtkDoubleArray::New(); double *array = new double[SIZE]; for (int i = 0; i < SIZE; i++) *(array + i ) = i; doArrayTest (strm, ptr, array, SIZE); ptr->Delete(); delete []array; } } int main(int argc, char* argv[]) { rtOtherTestBase::RunTest(argc, argv, SelectorCommand, ComparatorCommand, Test); return 0; } <commit_msg>It was using deprecated version of GetData<commit_after>/************************************************************************ Module: otherArrays.cxx Language: C++ Date: $Date$ Version: $Revision$ ************************************************************************/ // All tests need: // the following include // a Selector proc // a Comparator proc // a Test proc // and a main #include "rtOtherTestBase.h" void SelectorCommand(ostream& strm) { strm << "grep -v 0x | grep -v Modified "; } void ComparatorCommand(ostream& strm) { strm << "diff -b"; } #include "vtkCharArray.h" #include "vtkUnsignedCharArray.h" #include "vtkIntArray.h" #include "vtkUnsignedIntArray.h" #include "vtkLongArray.h" #include "vtkUnsignedLongArray.h" #include "vtkShortArray.h" #include "vtkUnsignedShortArray.h" #include "vtkFloatArray.h" #include "vtkDoubleArray.h" #define SIZE 1000 template <class T, class A> static int doArrayTest (ostream& strm, T *ptr, A *array, int size) { T *ptr2; float tuple1[SIZE/100]; double tuple3[SIZE/100]; float *tuple2; int i; strm << "\tSetArray..."; ptr->SetArray(array, size, 1); strm << "OK" << endl; strm << "\tSetNumberOfTuples..."; ptr->SetNumberOfTuples (100); if (ptr->GetNumberOfTuples() == 100) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tSetNumberOfComponents..."; ptr->SetNumberOfComponents (10); if (ptr->GetNumberOfComponents() == 10) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tMakeObject..."; if (ptr2 = ptr->SafeDownCast(ptr->MakeObject())) { if (ptr2->GetNumberOfComponents() == 10) strm << "OK" << endl; else strm << "FAILED" << endl; } else { strm << "FAILED" << endl; } strm << "\tGetTuple(i)..."; tuple2 = ptr->GetTuple (2); int passed = 1; for (i = 0; i < 10; i++) { strm << *(tuple2 + i) << " "; if (*(tuple2 + i) != (20 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tGetTuple(i, float *tuple)..."; ptr->GetTuple (3, tuple1); passed = 1; for (i = 0; i < 10; i++) { strm << tuple1[i] << " "; if (tuple1[i] != (30 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tGetTuple(i, double *tuple)..."; ptr->GetTuple (4, tuple3); passed = 1; for (i = 0; i < 10; i++) { strm << tuple3[i] << " "; if (tuple3[i] != (40 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tvtkDataArray::GetTuple(i, double *tuple)..."; ptr->vtkDataArray::GetTuple (4, tuple3); passed = 1; for (i = 0; i < 10; i++) { strm << tuple3[i] << " "; if (tuple3[i] != (40 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tSetTuple(i, float *tuple)..."; ptr->SetTuple (99, tuple1); for (i=0; i < 10; i++) tuple1[i] = 0; ptr->GetTuple (99, tuple1); passed = 1; for (i = 0; i < 10; i++) { strm << tuple1[i] << " "; if (tuple1[i] != (30 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tSetTuple(i, double *tuple)..."; ptr->SetTuple (99, tuple3); for (i=0; i < 10; i++) tuple3[i] = 0; ptr->GetTuple (99, tuple3); passed = 1; for (i = 0; i < 10; i++) { strm << tuple3[i] << " "; if (tuple3[i] != (40 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tvtkDataArray::SetTuple(i, double *tuple)..."; ptr->vtkDataArray::SetTuple (99, tuple3); for (i=0; i < 10; i++) tuple3[i] = 0; ptr->GetTuple (99, tuple3); passed = 1; for (i = 0; i < 10; i++) { strm << tuple3[i] << " "; if (tuple3[i] != (40 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tInsertTuple(i, float *tuple)..."; ptr->InsertTuple (100, tuple1); for (i=0; i < 10; i++) tuple1[i] = 0; ptr->GetTuple (100, tuple1); passed = 1; for (i = 0; i < 10; i++) { strm << tuple1[i] << " "; if (tuple1[i] != (30 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tInsertTuple(i, double *tuple)..."; ptr->InsertTuple (100, tuple3); for (i=0; i < 10; i++) tuple3[i] = 0; ptr->GetTuple (100, tuple3); passed = 1; for (i = 0; i < 10; i++) { strm << tuple3[i] << " "; if (tuple3[i] != (40 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tvtkDataArray::InsertTuple(i, double *tuple)..."; ptr->vtkDataArray::InsertTuple (100, tuple3); for (i=0; i < 10; i++) tuple3[i] = 0; ptr->GetTuple (100, tuple3); passed = 1; for (i = 0; i < 10; i++) { strm << tuple3[i] << " "; if (tuple3[i] != (40 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tInsertNextTuple(float *tuple)..."; ptr->InsertNextTuple (tuple1); for (i=0; i < 10; i++) tuple1[i] = 0; ptr->GetTuple (101, tuple1); passed = 1; for (i = 0; i < 10; i++) { strm << tuple1[i] << " "; if (tuple1[i] != (30 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tInsertNextTuple(double *tuple)..."; ptr->InsertNextTuple (tuple3); for (i=0; i < 10; i++) tuple3[i] = 0; ptr->GetTuple (102, tuple3); passed = 1; for (i = 0; i < 10; i++) { strm << tuple3[i] << " "; if (tuple3[i] != (40 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tvtkDataArray::InsertNextTuple(double *tuple)..."; ptr->vtkDataArray::InsertNextTuple (tuple3); for (i=0; i < 10; i++) tuple3[i] = 0; ptr->GetTuple (102, tuple3); passed = 1; for (i = 0; i < 10; i++) { strm << tuple3[i] << " "; if (tuple3[i] != (40 + i)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; strm << "\tvtkDataArray::GetData..."; vtkFloatArray *farray = vtkFloatArray::New(); farray->SetNumberOfComponents(1); ptr->vtkDataArray::GetData (0, 59, 1, 1, farray); passed = 1; for (i = 0; i < 10; i++) { strm << farray->GetTuple(i)[0] << " "; if (farray->GetTuple(i)[0] != (1 + i*10)) { passed = 0; break; } } if (passed) strm << "OK" << endl; else strm << "FAILED" << endl; farray->Delete(); strm << "PrintSelf..." << endl; strm << *ptr; return 0; } void Test(ostream& strm) { { strm << "Test CharArray" << endl; vtkCharArray *ptr = vtkCharArray::New(); char *array = new char[SIZE]; for (int i = 0; i < SIZE; i++) *(array + i ) = i; doArrayTest (strm, ptr, array, SIZE); ptr->Delete(); delete []array; } { strm << "Test UnsignedCharArray" << endl; vtkUnsignedCharArray *ptr = vtkUnsignedCharArray::New(); unsigned char *array = new unsigned char[SIZE]; for (int i = 0; i < SIZE; i++) *(array + i ) = i; doArrayTest (strm, ptr, array, SIZE); ptr->Delete(); delete []array; } { strm << "Test IntArray" << endl; vtkIntArray *ptr = vtkIntArray::New(); int *array = new int[SIZE]; for (int i = 0; i < SIZE; i++) *(array + i ) = i; doArrayTest (strm, ptr, array, SIZE); ptr->Delete(); delete []array; } { strm << "Test UnsignedIntArray" << endl; vtkUnsignedIntArray *ptr = vtkUnsignedIntArray::New(); unsigned int *array = new unsigned int[SIZE]; for (int i = 0; i < SIZE; i++) *(array + i ) = i; doArrayTest (strm, ptr, array, SIZE); ptr->Delete(); delete []array; } { strm << "Test LongArray" << endl; vtkLongArray *ptr = vtkLongArray::New(); long *array = new long[SIZE]; for (int i = 0; i < SIZE; i++) *(array + i ) = i; doArrayTest (strm, ptr, array, SIZE); ptr->Delete(); delete []array; } { strm << "Test UnsignedLongArray" << endl; vtkUnsignedLongArray *ptr = vtkUnsignedLongArray::New(); unsigned long *array = new unsigned long[SIZE]; for (int i = 0; i < SIZE; i++) *(array + i ) = i; doArrayTest (strm, ptr, array, SIZE); ptr->Delete(); delete []array; } { strm << "Test ShortArray" << endl; vtkShortArray *ptr = vtkShortArray::New(); short *array = new short[SIZE]; for (int i = 0; i < SIZE; i++) *(array + i ) = i; doArrayTest (strm, ptr, array, SIZE); ptr->Delete(); delete []array; } { strm << "Test UnsignedShortArray" << endl; vtkUnsignedShortArray *ptr = vtkUnsignedShortArray::New(); unsigned short *array = new unsigned short[SIZE]; for (int i = 0; i < SIZE; i++) *(array + i ) = i; doArrayTest (strm, ptr, array, SIZE); ptr->Delete(); delete []array; } { strm << "Test FloatArray" << endl; vtkFloatArray *ptr = vtkFloatArray::New(); float *array = new float[SIZE]; for (int i = 0; i < SIZE; i++) *(array + i ) = i; doArrayTest (strm, ptr, array, SIZE); ptr->Delete(); delete []array; } { strm << "Test DoubleArray" << endl; vtkDoubleArray *ptr = vtkDoubleArray::New(); double *array = new double[SIZE]; for (int i = 0; i < SIZE; i++) *(array + i ) = i; doArrayTest (strm, ptr, array, SIZE); ptr->Delete(); delete []array; } } int main(int argc, char* argv[]) { rtOtherTestBase::RunTest(argc, argv, SelectorCommand, ComparatorCommand, Test); return 0; } <|endoftext|>
<commit_before>/// \file stream.cpp /// Utilities for handling streams. #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include "json.h" #include "stream.h" #include "procs.h" #include "config.h" #include "socket.h" #include "defines.h" std::string Util::getTmpFolder(){ std::string dir; char * tmp_char = 0; if ( !tmp_char){ tmp_char = getenv("TMP"); } if ( !tmp_char){ tmp_char = getenv("TEMP"); } if ( !tmp_char){ tmp_char = getenv("TMPDIR"); } if (tmp_char){ dir = tmp_char; dir += "/mist"; }else{ #if defined(_WIN32) || defined(_CYGWIN_) dir = "C:/tmp/mist"; #else dir = "/tmp/mist"; #endif } if (access(dir.c_str(), 0) != 0){ mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IRWXO); //attempt to create mist folder - ignore failures } return dir + "/"; } /// Filters the streamname, removing invalid characters and converting all /// letters to lowercase. If a '?' character is found, everything following /// that character is deleted. The original string is modified. void Util::Stream::sanitizeName(std::string & streamname){ //strip anything that isn't numbers, digits or underscores for (std::string::iterator i = streamname.end() - 1; i >= streamname.begin(); --i){ if ( *i == '?'){ streamname.erase(i, streamname.end()); break; } if ( !isalpha( *i) && !isdigit( *i) && *i != '_'){ streamname.erase(i); }else{ *i = tolower( *i); } } } Socket::Connection Util::Stream::getLive(std::string streamname){ return Socket::Connection(getTmpFolder() + "stream_" + streamname); } /// Starts a process for a VoD stream. Socket::Connection Util::Stream::getVod(std::string filename, std::string streamname){ std::string name = "MistPlayer " + filename; std::string player_bin = Util::getMyPath() + "MistPlayer"; char* const argv[] = {(char*)player_bin.c_str(), (char*)filename.c_str(), (char*)"-s", (char*)streamname.c_str(), (char*)0}; int fdin = -1, fdout = -1, fderr = fileno(stderr); Util::Procs::StartPiped(name, argv, &fdin, &fdout, &fderr); // if StartPiped fails then fdin and fdout will be unmodified (-1) return Socket::Connection(fdin, fdout); } /// Probe for available streams. Currently first VoD, then Live. Socket::Connection Util::Stream::getStream(std::string streamname){ sanitizeName(streamname); JSON::Value ServConf = JSON::fromFile(getTmpFolder() + "streamlist"); if (ServConf["streams"].isMember(streamname)){ if (ServConf["streams"][streamname]["source"].asString()[0] == '/'){ return getVod(ServConf["streams"][streamname]["source"].asString(), streamname); }else{ return Socket::Connection(getTmpFolder() + "stream_" + streamname); } } DEBUG_MSG(DLVL_ERROR, "Stream not found: %s", streamname.c_str()); return Socket::Connection(); } /// Create a stream on the system. /// Filters the streamname, removing invalid characters and /// converting all letters to lowercase. /// If a '?' character is found, everything following that character is deleted. Socket::Server Util::Stream::makeLive(std::string streamname){ sanitizeName(streamname); std::string loc = getTmpFolder() + "stream_" + streamname; //create and return the Socket::Server return Socket::Server(loc); } <commit_msg>Fixed threaded use of MistPlayer.<commit_after>/// \file stream.cpp /// Utilities for handling streams. #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <stdlib.h> #include "json.h" #include "stream.h" #include "procs.h" #include "config.h" #include "socket.h" #include "defines.h" std::string Util::getTmpFolder(){ std::string dir; char * tmp_char = 0; if ( !tmp_char){ tmp_char = getenv("TMP"); } if ( !tmp_char){ tmp_char = getenv("TEMP"); } if ( !tmp_char){ tmp_char = getenv("TMPDIR"); } if (tmp_char){ dir = tmp_char; dir += "/mist"; }else{ #if defined(_WIN32) || defined(_CYGWIN_) dir = "C:/tmp/mist"; #else dir = "/tmp/mist"; #endif } if (access(dir.c_str(), 0) != 0){ mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IRWXO); //attempt to create mist folder - ignore failures } return dir + "/"; } /// Filters the streamname, removing invalid characters and converting all /// letters to lowercase. If a '?' character is found, everything following /// that character is deleted. The original string is modified. void Util::Stream::sanitizeName(std::string & streamname){ //strip anything that isn't numbers, digits or underscores for (std::string::iterator i = streamname.end() - 1; i >= streamname.begin(); --i){ if ( *i == '?'){ streamname.erase(i, streamname.end()); break; } if ( !isalpha( *i) && !isdigit( *i) && *i != '_'){ streamname.erase(i); }else{ *i = tolower( *i); } } } Socket::Connection Util::Stream::getLive(std::string streamname){ return Socket::Connection(getTmpFolder() + "stream_" + streamname); } /// Starts a process for a VoD stream. Socket::Connection Util::Stream::getVod(std::string filename, std::string streamname){ static unsigned long long counter = 0; std::stringstream name; name << "MistPlayer " << (counter++); std::string player_bin = Util::getMyPath() + "MistPlayer"; char* const argv[] = {(char*)player_bin.c_str(), (char*)filename.c_str(), (char*)"-s", (char*)streamname.c_str(), (char*)0}; int fdin = -1, fdout = -1, fderr = fileno(stderr); Util::Procs::StartPiped(name.str(), argv, &fdin, &fdout, &fderr); // if StartPiped fails then fdin and fdout will be unmodified (-1) return Socket::Connection(fdin, fdout); } /// Probe for available streams. Currently first VoD, then Live. Socket::Connection Util::Stream::getStream(std::string streamname){ sanitizeName(streamname); JSON::Value ServConf = JSON::fromFile(getTmpFolder() + "streamlist"); if (ServConf["streams"].isMember(streamname)){ if (ServConf["streams"][streamname]["source"].asString()[0] == '/'){ return getVod(ServConf["streams"][streamname]["source"].asString(), streamname); }else{ return Socket::Connection(getTmpFolder() + "stream_" + streamname); } } DEBUG_MSG(DLVL_ERROR, "Stream not found: %s", streamname.c_str()); return Socket::Connection(); } /// Create a stream on the system. /// Filters the streamname, removing invalid characters and /// converting all letters to lowercase. /// If a '?' character is found, everything following that character is deleted. Socket::Server Util::Stream::makeLive(std::string streamname){ sanitizeName(streamname); std::string loc = getTmpFolder() + "stream_" + streamname; //create and return the Socket::Server return Socket::Server(loc); } <|endoftext|>
<commit_before>/***************************************************************************** * cmd_quit.cpp ***************************************************************************** * Copyright (C) 2003 the VideoLAN team * $Id$ * * Authors: Cyril Deguet <[email protected]> * Olivier Teulière <[email protected]> * * 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. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vlc_osd.h> #include <vlc_playlist.h> #include "cmd_quit.hpp" #include "../src/os_factory.hpp" #include "../src/os_loop.hpp" void CmdQuit::execute() { // Stop the playlist vout_OSDMessage( getIntf(), DEFAULT_CHAN, _( "Quit" ) ); playlist_Stop( getIntf()->p_sys->p_playlist ); // Get the instance of OSFactory OSFactory *pOsFactory = OSFactory::instance( getIntf() ); // Exit the main OS loop pOsFactory->getOSLoop()->exit(); // Kill libvlc vlc_object_kill( getIntf()->p_libvlc ); } <commit_msg>Fix quit sequence in skins2.<commit_after>/***************************************************************************** * cmd_quit.cpp ***************************************************************************** * Copyright (C) 2003 the VideoLAN team * $Id$ * * Authors: Cyril Deguet <[email protected]> * Olivier Teulière <[email protected]> * * 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. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vlc_osd.h> #include <vlc_playlist.h> #include "cmd_quit.hpp" #include "../src/os_factory.hpp" #include "../src/os_loop.hpp" void CmdQuit::execute() { // Stop the playlist vout_OSDMessage( getIntf(), DEFAULT_CHAN, _( "Quit" ) ); // Get the instance of OSFactory OSFactory *pOsFactory = OSFactory::instance( getIntf() ); // Exit the main OS loop pOsFactory->getOSLoop()->exit(); // Kill libvlc vlc_object_kill( getIntf()->p_libvlc ); } <|endoftext|>
<commit_before>/******************************************************************************\ * ___ __ * * /\_ \ __/\ \ * * \//\ \ /\_\ \ \____ ___ _____ _____ __ * * \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ * * \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ * * /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ * * \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ * * \ \_\ \ \_\ * * \/_/ \/_/ * * * * Copyright (C) 2011-2013 * * Dominik Charousset <[email protected]> * * Raphael Hiesgen <[email protected]> * * * * This file is part of libcppa. * * libcppa is free software: you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License as published by the * * Free Software Foundation, either version 3 of the License * * or (at your option) any later version. * * * * libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. * \******************************************************************************/ #ifndef CPPA_OPENCL_ACTOR_FACADE_HPP #define CPPA_OPENCL_ACTOR_FACADE_HPP #include <ostream> #include <stdexcept> #include "cppa/cppa.hpp" #include "cppa/channel.hpp" #include "cppa/to_string.hpp" #include "cppa/tuple_cast.hpp" #include "cppa/intrusive_ptr.hpp" #include "cppa/util/int_list.hpp" #include "cppa/util/type_list.hpp" #include "cppa/util/scope_guard.hpp" #include "cppa/opencl/global.hpp" #include "cppa/opencl/command.hpp" #include "cppa/opencl/program.hpp" #include "cppa/opencl/smart_ptr.hpp" #include "cppa/detail/scheduled_actor_dummy.hpp" namespace cppa { namespace opencl { class command_dispatcher; void enqueue_to_dispatcher(command_dispatcher*, command_ptr); template<typename Signature> class actor_facade; template<typename Ret, typename... Args> class actor_facade<Ret(Args...)> : public actor { public: /* actor_facade(command_dispatcher* dispatcher, const program& prog, const char* kernel_name) : m_program(prog.m_program) , m_context(prog.m_context) , m_dispatcher(dispatcher) { CPPA_LOG_TRACE("new actor facde with ID " << this->id()); init_kernel(m_program.get(), kernel_name); } actor_facade(command_dispatcher* dispatcher, const program& prog, const char* kernel_name, std::vector<size_t>& global_dimensions, std::vector<size_t>& local_dimensions) : m_program(prog.m_program) , m_context(prog.m_context) , m_dispatcher(dispatcher) , m_global_dimensions(global_dimensions) , m_local_dimensions(local_dimensions) { CPPA_LOG_TRACE("new actor facde with ID " << this->id()); if(m_local_dimensions .size() > 3 || m_global_dimensions.size() > 3) { std::ostringstream oss; oss << "Creating actor facade: a maximum of 3 dimensions allowed."; CPPA_LOG_ERROR(oss.str()); throw std::runtime_error(oss.str()); } init_kernel(m_program.get(), kernel_name); } */ actor_facade(command_dispatcher* dispatcher, const program& prog, const char* kernel_name, std::vector<size_t> global_dimensions, std::vector<size_t> local_dimensions, std::function<option<cow_tuple<typename util::rm_ref<Args>::type...>>(any_tuple)> map_args, std::function<any_tuple(Ret&)> map_result) //std::function<option<cow_tuple<Args...>>(any_tuple)> map_args, //std::function<any_tuple(Ret& result)> map_result) : m_program(prog.m_program) , m_context(prog.m_context) , m_dispatcher(dispatcher) , m_global_dimensions(std::move(global_dimensions)) , m_local_dimensions(std::move(local_dimensions)) , m_map_args(std::move(map_args)) , m_map_result(std::move(map_result)) { CPPA_LOG_TRACE("new actor facde with ID " << this->id()); if(m_local_dimensions .size() > 3 || m_global_dimensions.size() > 3) { std::ostringstream oss; oss << "Creating actor facade: a maximum of 3 dimensions allowed."; CPPA_LOG_ERROR(oss.str()); throw std::runtime_error(oss.str()); } init_kernel(m_program.get(), kernel_name); } void sync_enqueue(const actor_ptr& sender, message_id id, any_tuple msg) { CPPA_LOG_TRACE("actor_facade::sync_enqueue()"); typename util::il_indices<util::type_list<Args...>>::type indices; enqueue_impl(sender, msg, id, indices); } void enqueue(const actor_ptr& sender, any_tuple msg) { CPPA_LOG_TRACE("actor_facade::enqueue()"); typename util::il_indices<util::type_list<Args...>>::type indices; enqueue_impl(sender, msg, message_id{}, indices); } private: void init_kernel(cl_program program, const char* kernel_name) { cl_int err{0}; m_kernel.adopt(clCreateKernel(program, kernel_name, &err)); if (err != CL_SUCCESS) { std::ostringstream oss; oss << "clCreateKernel: '" << get_opencl_error(err) << "'."; CPPA_LOG_ERROR(oss.str()); throw std::runtime_error(oss.str()); } } template<long... Is> void enqueue_impl(const actor_ptr& sender, any_tuple msg, message_id id, util::int_list<Is...>) { //auto opt = tuple_cast<Args...>(msg); auto opt = m_map_args(msg); if (opt) { response_handle handle{this, sender, id}; size_t number_of_values = 1; if (!m_global_dimensions.empty()) { for (auto s : m_global_dimensions) { number_of_values *= s; } } else { number_of_values = get<0>(*opt).size(); m_global_dimensions.push_back(number_of_values); m_global_dimensions.push_back(1); m_global_dimensions.push_back(1); } if (m_global_dimensions.empty() || number_of_values <= 0) { std::ostringstream oss; oss << "actor_facade::enqueue() can't handle dimension sizes!"; CPPA_LOG_ERROR(oss.str()); throw std::runtime_error(oss.str()); } Ret result_buf(number_of_values); std::vector<mem_ptr> arguments; add_arguments_to_kernel(arguments, m_context.get(), m_kernel.get(), result_buf, get_ref<Is>(*opt)...); CPPA_LOG_TRACE("enqueue to dispatcher"); enqueue_to_dispatcher(m_dispatcher, make_counted<command_impl<Ret>>(handle, m_kernel, arguments, m_global_dimensions, m_local_dimensions, m_map_result)); } else { CPPA_LOG_ERROR("actor_facade::enqueue() tuple_cast failed."); } } typedef std::vector<mem_ptr> args_vec; program_ptr m_program; kernel_ptr m_kernel; context_ptr m_context; command_dispatcher* m_dispatcher; std::vector<size_t> m_global_dimensions; std::vector<size_t> m_local_dimensions; std::function<option<cow_tuple<Args...>>(any_tuple)> m_map_args; std::function<any_tuple(Ret& result)> m_map_result; void add_arguments_to_kernel_rec(args_vec& arguments, cl_context, cl_kernel kernel) { cl_int err{0}; for(unsigned long i{1}; i < arguments.size(); ++i) { err = clSetKernelArg(kernel, (i-1), sizeof(cl_mem), static_cast<void*>(&arguments[i])); if (err != CL_SUCCESS) { std::ostringstream oss; oss << "clSetKernelArg: '" << get_opencl_error(err) << "'."; CPPA_LOG_ERROR(oss.str()); throw std::runtime_error(oss.str()); } } err = clSetKernelArg(kernel, arguments.size()-1, sizeof(cl_mem), static_cast<void*>(&arguments[0])); if (err != CL_SUCCESS) { std::ostringstream oss; oss << "clSetKernelArg: '" << get_opencl_error(err) << "'."; CPPA_LOG_ERROR(oss.str()); throw std::runtime_error(oss.str()); } } template<typename T0, typename... Ts> void add_arguments_to_kernel_rec(args_vec& arguments, cl_context context, cl_kernel kernel, T0& arg0, Ts&... args) { cl_int err{0}; auto buf = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(typename T0::value_type)*arg0.size(), arg0.data(), &err); if (err != CL_SUCCESS) { std::ostringstream oss; oss << "clCreateBuffer: '" << get_opencl_error(err) << "'."; CPPA_LOG_ERROR(oss.str()); throw std::runtime_error(oss.str()); } else { mem_ptr tmp; tmp.adopt(std::move(buf)); arguments.push_back(tmp); return add_arguments_to_kernel_rec(arguments, context, kernel, args...); } } template<typename R, typename... Ts> void add_arguments_to_kernel(args_vec& arguments, cl_context context, cl_kernel kernel, R& ret, Ts&&... args) { arguments.clear(); cl_int err{0}; auto buf = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(typename R::value_type)*ret.size(), nullptr, &err); if (err != CL_SUCCESS) { std::ostringstream oss; oss << "clCreateBuffer: '" << get_opencl_error(err) << "'."; CPPA_LOG_ERROR(oss.str()); throw std::runtime_error(oss.str()); } else { mem_ptr tmp; tmp.adopt(std::move(buf)); arguments.push_back(tmp); return add_arguments_to_kernel_rec(arguments, context, kernel, std::forward<Ts>(args)...); } } }; } } // namespace cppa::opencl #endif // CPPA_OPENCL_ACTOR_FACADE_HPP <commit_msg>fixed type of mapping functor<commit_after>/******************************************************************************\ * ___ __ * * /\_ \ __/\ \ * * \//\ \ /\_\ \ \____ ___ _____ _____ __ * * \ \ \ \/\ \ \ '__`\ /'___\/\ '__`\/\ '__`\ /'__`\ * * \_\ \_\ \ \ \ \L\ \/\ \__/\ \ \L\ \ \ \L\ \/\ \L\.\_ * * /\____\\ \_\ \_,__/\ \____\\ \ ,__/\ \ ,__/\ \__/.\_\ * * \/____/ \/_/\/___/ \/____/ \ \ \/ \ \ \/ \/__/\/_/ * * \ \_\ \ \_\ * * \/_/ \/_/ * * * * Copyright (C) 2011-2013 * * Dominik Charousset <[email protected]> * * Raphael Hiesgen <[email protected]> * * * * This file is part of libcppa. * * libcppa is free software: you can redistribute it and/or modify it under * * the terms of the GNU Lesser General Public License as published by the * * Free Software Foundation, either version 3 of the License * * or (at your option) any later version. * * * * libcppa 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 libcppa. If not, see <http://www.gnu.org/licenses/>. * \******************************************************************************/ #ifndef CPPA_OPENCL_ACTOR_FACADE_HPP #define CPPA_OPENCL_ACTOR_FACADE_HPP #include <ostream> #include <stdexcept> #include "cppa/cppa.hpp" #include "cppa/channel.hpp" #include "cppa/to_string.hpp" #include "cppa/tuple_cast.hpp" #include "cppa/intrusive_ptr.hpp" #include "cppa/util/int_list.hpp" #include "cppa/util/type_list.hpp" #include "cppa/util/scope_guard.hpp" #include "cppa/opencl/global.hpp" #include "cppa/opencl/command.hpp" #include "cppa/opencl/program.hpp" #include "cppa/opencl/smart_ptr.hpp" #include "cppa/detail/scheduled_actor_dummy.hpp" namespace cppa { namespace opencl { class command_dispatcher; void enqueue_to_dispatcher(command_dispatcher*, command_ptr); template<typename Signature> class actor_facade; template<typename Ret, typename... Args> class actor_facade<Ret(Args...)> : public actor { public: typedef cow_tuple<typename util::rm_ref<Args>::type...> args_tuple; typedef std::function<option<args_tuple>(any_tuple)> arg_mapping; typedef std::function<any_tuple(Ret&)> result_mapping; actor_facade(command_dispatcher* dispatcher, const program& prog, const char* kernel_name, std::vector<size_t> global_dimensions, std::vector<size_t> local_dimensions, arg_mapping map_args, result_mapping map_result) : m_program(prog.m_program) , m_context(prog.m_context) , m_dispatcher(dispatcher) , m_global_dimensions(std::move(global_dimensions)) , m_local_dimensions(std::move(local_dimensions)) , m_map_args(std::move(map_args)) , m_map_result(std::move(map_result)) { CPPA_LOG_TRACE("new actor facde with ID " << this->id()); if(m_local_dimensions .size() > 3 || m_global_dimensions.size() > 3) { std::ostringstream oss; oss << "Creating actor facade: a maximum of 3 dimensions allowed."; CPPA_LOG_ERROR(oss.str()); throw std::runtime_error(oss.str()); } init_kernel(m_program.get(), kernel_name); } void sync_enqueue(const actor_ptr& sender, message_id id, any_tuple msg) { CPPA_LOG_TRACE("actor_facade::sync_enqueue()"); typename util::il_indices<util::type_list<Args...>>::type indices; enqueue_impl(sender, msg, id, indices); } void enqueue(const actor_ptr& sender, any_tuple msg) { CPPA_LOG_TRACE("actor_facade::enqueue()"); typename util::il_indices<util::type_list<Args...>>::type indices; enqueue_impl(sender, msg, message_id{}, indices); } private: void init_kernel(cl_program program, const char* kernel_name) { cl_int err{0}; m_kernel.adopt(clCreateKernel(program, kernel_name, &err)); if (err != CL_SUCCESS) { std::ostringstream oss; oss << "clCreateKernel: '" << get_opencl_error(err) << "'."; CPPA_LOG_ERROR(oss.str()); throw std::runtime_error(oss.str()); } } template<long... Is> void enqueue_impl(const actor_ptr& sender, any_tuple msg, message_id id, util::int_list<Is...>) { //auto opt = tuple_cast<Args...>(msg); auto opt = m_map_args(msg); if (opt) { response_handle handle{this, sender, id}; size_t number_of_values = 1; if (!m_global_dimensions.empty()) { for (auto s : m_global_dimensions) { number_of_values *= s; } } else { number_of_values = get<0>(*opt).size(); m_global_dimensions.push_back(number_of_values); m_global_dimensions.push_back(1); m_global_dimensions.push_back(1); } if (m_global_dimensions.empty() || number_of_values <= 0) { std::ostringstream oss; oss << "actor_facade::enqueue() can't handle dimension sizes!"; CPPA_LOG_ERROR(oss.str()); throw std::runtime_error(oss.str()); } Ret result_buf(number_of_values); std::vector<mem_ptr> arguments; add_arguments_to_kernel(arguments, m_context.get(), m_kernel.get(), result_buf, get_ref<Is>(*opt)...); CPPA_LOG_TRACE("enqueue to dispatcher"); enqueue_to_dispatcher(m_dispatcher, make_counted<command_impl<Ret>>(handle, m_kernel, arguments, m_global_dimensions, m_local_dimensions, m_map_result)); } else { CPPA_LOG_ERROR("actor_facade::enqueue() tuple_cast failed."); } } typedef std::vector<mem_ptr> args_vec; program_ptr m_program; kernel_ptr m_kernel; context_ptr m_context; command_dispatcher* m_dispatcher; std::vector<size_t> m_global_dimensions; std::vector<size_t> m_local_dimensions; arg_mapping m_map_args; result_mapping m_map_result; void add_arguments_to_kernel_rec(args_vec& arguments, cl_context, cl_kernel kernel) { cl_int err{0}; for(unsigned long i{1}; i < arguments.size(); ++i) { err = clSetKernelArg(kernel, (i-1), sizeof(cl_mem), static_cast<void*>(&arguments[i])); if (err != CL_SUCCESS) { std::ostringstream oss; oss << "clSetKernelArg: '" << get_opencl_error(err) << "'."; CPPA_LOG_ERROR(oss.str()); throw std::runtime_error(oss.str()); } } err = clSetKernelArg(kernel, arguments.size()-1, sizeof(cl_mem), static_cast<void*>(&arguments[0])); if (err != CL_SUCCESS) { std::ostringstream oss; oss << "clSetKernelArg: '" << get_opencl_error(err) << "'."; CPPA_LOG_ERROR(oss.str()); throw std::runtime_error(oss.str()); } } template<typename T0, typename... Ts> void add_arguments_to_kernel_rec(args_vec& arguments, cl_context context, cl_kernel kernel, T0& arg0, Ts&... args) { cl_int err{0}; auto buf = clCreateBuffer(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(typename T0::value_type)*arg0.size(), arg0.data(), &err); if (err != CL_SUCCESS) { std::ostringstream oss; oss << "clCreateBuffer: '" << get_opencl_error(err) << "'."; CPPA_LOG_ERROR(oss.str()); throw std::runtime_error(oss.str()); } else { mem_ptr tmp; tmp.adopt(std::move(buf)); arguments.push_back(tmp); return add_arguments_to_kernel_rec(arguments, context, kernel, args...); } } template<typename R, typename... Ts> void add_arguments_to_kernel(args_vec& arguments, cl_context context, cl_kernel kernel, R& ret, Ts&&... args) { arguments.clear(); cl_int err{0}; auto buf = clCreateBuffer(context, CL_MEM_WRITE_ONLY, sizeof(typename R::value_type)*ret.size(), nullptr, &err); if (err != CL_SUCCESS) { std::ostringstream oss; oss << "clCreateBuffer: '" << get_opencl_error(err) << "'."; CPPA_LOG_ERROR(oss.str()); throw std::runtime_error(oss.str()); } else { mem_ptr tmp; tmp.adopt(std::move(buf)); arguments.push_back(tmp); return add_arguments_to_kernel_rec(arguments, context, kernel, std::forward<Ts>(args)...); } } }; } } // namespace cppa::opencl #endif // CPPA_OPENCL_ACTOR_FACADE_HPP <|endoftext|>
<commit_before>/* RTcmix - Copyright (C) 2000 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ /* Originally by Brad Garton, Doug Scott, and Dave Topper. Reworked for v2.3 by John Gibson. */ #include <globals.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <sndlibsupport.h> #include <rtdefs.h> #ifdef LINUX #include <fcntl.h> #endif /* LINUX */ #ifdef SGI #include <dmedia/audio.h> #endif /* SGI */ /* code that lets user specify buses for input sources */ //#define INPUT_BUS_SUPPORT typedef enum { MIC, LINE, DIGITAL } AudioPortType; #ifdef LINUX #define open_audio_input open_linux_audio_input #endif #ifdef SGI #define open_audio_input open_sgi_audio_input #endif static last_input_index = -1; /* ------------------------------------------------- get_last_inpud_index --- */ /* Called by rtsetinput to find out which file to set for the inst. */ int get_last_input_index() { return last_input_index; } #ifdef LINUX /* ----------------------------------------------- open_linux_audio_input --- */ /* The device has already been opened in rtsetparams. */ static int open_linux_audio_input() { if (in_port) return in_port; /* global set in rtsetparams */ else return -1; } #endif /* LINUX */ #ifdef SGI /* ------------------------------------------------- open_sgi_audio_input --- */ /* <port_type> is one of AL_INPUT_MIC, AL_INPUT_LINE, or AL_INPUT_DIGITAL. */ static int open_sgi_audio_input(AudioPortType port_type, int nchans) { int port; long pvbuf[4]; long buflen; ALconfig in_port_config; /* configure and open input audio port */ in_port_config = ALnewconfig(); ALsetwidth(in_port_config, AL_SAMPLE_16); if (nchans == 1) ALsetchannels(in_port_config, AL_MONO); else (nchans == 2) ALsetchannels(in_port_config, AL_STEREO); if (ALsetqueuesize(in_port_config, RTBUFSAMPS * 4) == -1) { fprintf(stderr, "Could not configure the input audio port queue size to %d.\n", RTBUFSAMPS * 4); return -1; } switch (port_type) { case LINE: port = AL_INPUT_LINE; break; case DIGITAL: port = AL_INPUT_DIGITAL; break; default: port = AL_INPUT_MIC; break; } pvbuf[0] = AL_INPUT_RATE; pvbuf[1] = (long) SR; pvbuf[2] = AL_INPUT_SOURCE; pvbuf[3] = port; buflen = 4; ALsetparams(AL_DEFAULT_DEVICE, pvbuf, buflen); /* open up thet thar audio port! */ in_port = ALopenport("rtcmixin", "r", in_port_config); ALfreeconfig(in_port_config); if (!in_port) { fprintf(stderr, "Could not open input audio port.\n"); return -1; } return AUDIO_DEVICE_ID; /* our fake fd for SGI audio devices */ } #endif /* SGI */ /* ------------------------------------------------------ open_sound_file --- */ static int open_sound_file( char *sfname, int *header_type, int *data_format, int *data_location, double *srate, int *nchans, long *nsamps) { int fd; struct stat sfst; /* See if file exists and is a regular file or link. */ if (stat(sfname, &sfst) == -1) { fprintf(stderr, "%s: %s\n", sfname, strerror(errno)); return -1; } if (!S_ISREG(sfst.st_mode) && !S_ISLNK(sfst.st_mode)) { fprintf(stderr, "%s is not a regular file or a link.\n", sfname); return -1; } /* Open the file and read its header. */ fd = sndlib_open_read(sfname); if (fd == -1) { fprintf(stderr, "Can't read header of \"%s\" (%s)\n", sfname, strerror(errno)); return -1; } /* Now info is available from sndlib query functions. */ *header_type = c_snd_header_type(); if (NOT_A_SOUND_FILE(*header_type)) { fprintf(stderr, "\"%s\" is probably not a sound file\n", sfname); sndlib_close(fd, 0, 0, 0, 0); return -1; } *data_format = c_snd_header_format(); if (INVALID_DATA_FORMAT(*data_format)) { fprintf(stderr, "\"%s\" has invalid sound data format\n", sfname); sndlib_close(fd, 0, 0, 0, 0); return -1; } #ifdef NOMORE // float input should work now -JG if (IS_FLOAT_FORMAT(*data_format)) { fprintf(stderr, "\"%s\": can't handle float input files yet.\n", sfname); sndlib_close(fd, 0, 0, 0, 0); return -1; } #endif *data_location = c_snd_header_data_location(); *srate = (double) c_snd_header_srate(); *nchans = c_snd_header_chans(); *nsamps = c_snd_header_data_size(); return fd; } /* -------------------------------------------------------------- rtinput --- */ /* This function is used in the score to open a file or an audio device for subsequent reads by RT Instruments. "rtsetinput" is used in the init member functions of the Instruments to access the file. p[0] is either a sound file name or "AUDIO" (for an audio device). If it's "AUDIO", then p[1] (optional) can be "MIC", "LINE" or "DIGITAL". (This option not available yet under Linux.) This sets up the input device to do real-time reading of sound. FIXME: this stuff not implemented yet -JGG pfields after these are bus specification strings in the format accepted by the bus_config Minc function. They *must* be "in" buses, not "auxin". The bus spec. is optional - if absent, the default is "in0-X", where `X' is the number of channels in the sound file; "AUDIO" input defaults to stereo ("in0-1"). Note that the only reason to bother with the bus specification is to make it possible to have more than one input source for an instrument. */ double rtinput(float p[], int n_args, double pp[]) { int i, j, anint, audio_in, p1_is_audioport, start_pfield, fd; int is_open, header_type, data_format, data_location, nchans; #ifdef INPUT_BUS_SUPPORT int startchan, endchan; short busindex, buslist[MAXBUS]; BusType type; #endif /* INPUT_BUS_SUPPORT */ long nsamps; double srate, dur; char *sfname, *str; AudioPortType port_type = MIC; header_type = unsupported_sound_file; data_format = snd_unsupported; data_location = 0; dur = 0.0; audio_in = 0; p1_is_audioport = 0; is_open = 0; /* Cast Minc double to int, then to a string ptr. */ anint = (int) pp[0]; sfname = (char *) anint; if (strcmp(sfname, "AUDIO") == 0) { audio_in = 1; if (pp[1] != 0.0) { p1_is_audioport = 1; anint = (int) pp[1]; str = (char *) anint; if (strcmp(str, "MIC") == 0) port_type = MIC; else if (strcmp(str, "LINE") == 0) port_type = LINE; else if (strcmp(str, "DIGITAL") == 0) port_type = DIGITAL; else p1_is_audioport = 0; /* p[1] might be a bus spec. */ } /* This signals inTraverse() to grab buffers from the audio device. */ audio_on = 1; } #ifdef INPUT_BUS_SUPPORT /* Parse bus specification. */ busindex = 0; for (i = 0; i < MAXBUS; i++) buslist[i] = -1; type = BUS_IN; startchan = endchan = -1; start_pfield = p1_is_audioport ? 2 : 1; for (i = start_pfield; i < n_args; i++) { ErrCode err; anint = (int) pp[i]; str = (char *) anint; err = parse_bus_name(str, &type, &startchan, &endchan); if (err) { fprintf(stderr, "rtinput: invalid bus name specification.\n"); exit(1); /* syntax error */ } if (type != BUS_IN) { fprintf(stderr, "You have to use an \"in\" bus with rtinput.\n"); exit(1); /* syntax error */ } for (j = startchan; j <= endchan; j++) buslist[busindex++] = j; } if (startchan == -1) { /* no bus specified */ } #endif /* INPUT_BUS_SUPPORT */ /* See if this audio device or file has already been opened. */ for (i = 0; i < MAX_INPUT_FDS; i++) { if (inputFileTable[i].fd != NO_FD) { if (strcmp(sfname, inputFileTable[i].filename) == 0) { last_input_index = i; is_open = 1; break; } } } if (!is_open) { /* then open audio device or file. */ if (audio_in) { fd = open_audio_input(port_type, nchans); if (fd == -1) return -1.0; #ifdef INPUT_BUS_SUPPORT #endif /* INPUT_BUS_SUPPORT */ } else { fd = open_sound_file(sfname, &header_type, &data_format, &data_location, &srate, &nchans, &nsamps); if (fd == -1) return -1.0; #ifdef INPUT_BUS_SUPPORT if (startchan == -1) { /* no bus specified above */ startchan = 0; endchan = nchans - 1; } else { if (endchan - startchan >= nchans) { fprintf(stderr, "WARNING: You specifed more input buses than " "input file '%s' has channels.\n", sfname); fprintf(stderr, "Using in buses %d \n", foo); endchan = (startchan + nchans) - 1; } } #endif /* INPUT_BUS_SUPPORT */ dur = (double) (nsamps / nchans) / srate; if (print_is_on) { printf("Input file set for reading:\n"); printf(" name: %s\n", sfname); printf(" type: %s\n", sound_type_name(header_type)); printf(" format: %s\n", sound_format_name(data_format)); printf(" srate: %g\n", srate); printf(" chans: %d\n", nchans); printf(" duration: %g\n\n", dur); #ifdef INPUT_BUS_SUPPORT #endif /* INPUT_BUS_SUPPORT */ } if (srate != SR) { fprintf(stderr, "WARNING: The input file sampling rate is %g, but " "the output rate is currently %g.\n", srate, SR); } } /* Put new file descriptor into the first available slot in the inputFileTable. Also copy the filename for later checking, and fill in the other fields in the InputDesc struct (see rtdefs.h). last_input_index is the value that will be used by any instrument created after this call to rtinput(). */ for (i = 0; i < MAX_INPUT_FDS; i++) { if (inputFileTable[i].fd == NO_FD) { inputFileTable[i].filename = strdup(sfname); inputFileTable[i].fd = fd; inputFileTable[i].refcount = 0; inputFileTable[i].is_audio_dev = audio_in; inputFileTable[i].header_type = header_type; inputFileTable[i].data_format = data_format; inputFileTable[i].data_location = data_location; inputFileTable[i].srate = (float) srate; inputFileTable[i].chans = nchans; inputFileTable[i].dur = dur; last_input_index = i; break; } } /* If this is true, we've used up all input descriptors in our array. */ if (i == MAX_INPUT_FDS) { fprintf(stderr, "You have exceeded the maximum number of input " "files (%d)!\n", MAX_INPUT_FDS); return -1.0; } } /* Return this to Minc, so user can pass it to functions. */ return (double) last_input_index; } <commit_msg>Handle new in_port array. Set audioNCHANS.<commit_after>/* RTcmix - Copyright (C) 2000 The RTcmix Development Team See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for the license to this software and for a DISCLAIMER OF ALL WARRANTIES. */ /* Originally by Brad Garton, Doug Scott, and Dave Topper. Reworked for v2.3 by John Gibson. */ #include <globals.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <errno.h> #include <sndlibsupport.h> #include <rtdefs.h> #ifdef LINUX #include <fcntl.h> #endif /* LINUX */ #ifdef SGI #include <dmedia/audio.h> #endif /* SGI */ /* code that lets user specify buses for input sources */ //#define INPUT_BUS_SUPPORT typedef enum { MIC, LINE, DIGITAL } AudioPortType; #ifdef LINUX #define open_audio_input open_linux_audio_input #endif #ifdef SGI #define open_audio_input open_sgi_audio_input #endif static last_input_index = -1; /* ------------------------------------------------- get_last_input_index --- */ /* Called by rtsetinput to find out which file to set for the inst. */ int get_last_input_index() { return last_input_index; } #ifdef LINUX /* ----------------------------------------------- open_linux_audio_input --- */ /* The device has already been opened in rtsetparams. */ static int open_linux_audio_input() { #ifdef MONO_DEVICES // FIXME: what do we return? #else /* !MONO_DEVICES */ if (in_port[0]) return in_port[0]; /* global set in rtsetparams */ else return -1; #endif /* !MONO_DEVICES */ } #endif /* LINUX */ #ifdef SGI /* ------------------------------------------------- open_sgi_audio_input --- */ /* <port_type> is one of AL_INPUT_MIC, AL_INPUT_LINE, or AL_INPUT_DIGITAL. */ static int open_sgi_audio_input(AudioPortType port_type, int nchans) { int port; long pvbuf[4]; long buflen; ALconfig in_port_config; /* configure and open input audio port */ in_port_config = ALnewconfig(); ALsetwidth(in_port_config, AL_SAMPLE_16); if (nchans == 1) ALsetchannels(in_port_config, AL_MONO); else (nchans == 2) ALsetchannels(in_port_config, AL_STEREO); if (ALsetqueuesize(in_port_config, RTBUFSAMPS * 4) == -1) { fprintf(stderr, "Could not configure the input audio port queue size to %d.\n", RTBUFSAMPS * 4); return -1; } switch (port_type) { case LINE: port = AL_INPUT_LINE; break; case DIGITAL: port = AL_INPUT_DIGITAL; break; default: port = AL_INPUT_MIC; break; } pvbuf[0] = AL_INPUT_RATE; pvbuf[1] = (long) SR; pvbuf[2] = AL_INPUT_SOURCE; pvbuf[3] = port; buflen = 4; ALsetparams(AL_DEFAULT_DEVICE, pvbuf, buflen); /* open up thet thar audio port! */ in_port = ALopenport("rtcmixin", "r", in_port_config); ALfreeconfig(in_port_config); if (!in_port) { fprintf(stderr, "Could not open input audio port.\n"); return -1; } return AUDIO_DEVICE_ID; /* our fake fd for SGI audio devices */ } #endif /* SGI */ /* ------------------------------------------------------ open_sound_file --- */ static int open_sound_file( char *sfname, int *header_type, int *data_format, int *data_location, double *srate, int *nchans, long *nsamps) { int fd; struct stat sfst; /* See if file exists and is a regular file or link. */ if (stat(sfname, &sfst) == -1) { fprintf(stderr, "%s: %s\n", sfname, strerror(errno)); return -1; } if (!S_ISREG(sfst.st_mode) && !S_ISLNK(sfst.st_mode)) { fprintf(stderr, "%s is not a regular file or a link.\n", sfname); return -1; } /* Open the file and read its header. */ fd = sndlib_open_read(sfname); if (fd == -1) { fprintf(stderr, "Can't read header of \"%s\" (%s)\n", sfname, strerror(errno)); return -1; } /* Now info is available from sndlib query functions. */ *header_type = c_snd_header_type(); if (NOT_A_SOUND_FILE(*header_type)) { fprintf(stderr, "\"%s\" is probably not a sound file\n", sfname); sndlib_close(fd, 0, 0, 0, 0); return -1; } *data_format = c_snd_header_format(); if (INVALID_DATA_FORMAT(*data_format)) { fprintf(stderr, "\"%s\" has invalid sound data format\n", sfname); sndlib_close(fd, 0, 0, 0, 0); return -1; } #ifdef NOMORE // float input should work now -JG if (IS_FLOAT_FORMAT(*data_format)) { fprintf(stderr, "\"%s\": can't handle float input files yet.\n", sfname); sndlib_close(fd, 0, 0, 0, 0); return -1; } #endif *data_location = c_snd_header_data_location(); *srate = (double) c_snd_header_srate(); *nchans = c_snd_header_chans(); *nsamps = c_snd_header_data_size(); return fd; } /* -------------------------------------------------------------- rtinput --- */ /* This function is used in the score to open a file or an audio device for subsequent reads by RT Instruments. "rtsetinput" is used in the init member functions of the Instruments to access the file. p[0] is either a sound file name or "AUDIO" (for an audio device). If it's "AUDIO", then p[1] (optional) can be "MIC", "LINE" or "DIGITAL". (This option not available yet under Linux.) This sets up the input device to do real-time reading of sound. FIXME: this stuff not implemented yet -JGG pfields after these are bus specification strings in the format accepted by the bus_config Minc function. They *must* be "in" buses, not "auxin". The bus spec. is optional - if absent, the default is "in0-X", where `X' is the number of channels in the sound file; "AUDIO" input defaults to stereo ("in0-1"). Note that the only reason to bother with the bus specification is to make it possible to have more than one input source for an instrument. */ double rtinput(float p[], int n_args, double pp[]) { int i, j, anint, audio_in, p1_is_audioport, start_pfield, fd; int is_open, header_type, data_format, data_location, nchans; #ifdef INPUT_BUS_SUPPORT int startchan, endchan; short busindex, buslist[MAXBUS]; BusType type; #endif /* INPUT_BUS_SUPPORT */ long nsamps; double srate, dur; char *sfname, *str; AudioPortType port_type = MIC; header_type = unsupported_sound_file; data_format = snd_unsupported; data_location = 0; dur = 0.0; audio_in = 0; p1_is_audioport = 0; is_open = 0; /* Cast Minc double to int, then to a string ptr. */ anint = (int) pp[0]; sfname = (char *) anint; if (strcmp(sfname, "AUDIO") == 0) { audio_in = 1; if (pp[1] != 0.0) { p1_is_audioport = 1; anint = (int) pp[1]; str = (char *) anint; if (strcmp(str, "MIC") == 0) port_type = MIC; else if (strcmp(str, "LINE") == 0) port_type = LINE; else if (strcmp(str, "DIGITAL") == 0) port_type = DIGITAL; else p1_is_audioport = 0; /* p[1] might be a bus spec. */ } /* This signals inTraverse() to grab buffers from the audio device. */ audio_on = 1; // FIXME: need to replace this with the bus spec scheme below... -JGG audioNCHANS = (n_args > 2) ? (int) p[2] : NCHANS; } #ifdef INPUT_BUS_SUPPORT /* Parse bus specification. */ busindex = 0; for (i = 0; i < MAXBUS; i++) buslist[i] = -1; type = BUS_IN; startchan = endchan = -1; start_pfield = p1_is_audioport ? 2 : 1; for (i = start_pfield; i < n_args; i++) { ErrCode err; anint = (int) pp[i]; str = (char *) anint; err = parse_bus_name(str, &type, &startchan, &endchan); if (err) { fprintf(stderr, "rtinput: invalid bus name specification.\n"); exit(1); /* syntax error */ } if (type != BUS_IN) { fprintf(stderr, "You have to use an \"in\" bus with rtinput.\n"); exit(1); /* syntax error */ } for (j = startchan; j <= endchan; j++) buslist[busindex++] = j; } if (startchan == -1) { /* no bus specified */ } #endif /* INPUT_BUS_SUPPORT */ /* See if this audio device or file has already been opened. */ for (i = 0; i < MAX_INPUT_FDS; i++) { if (inputFileTable[i].fd != NO_FD) { if (strcmp(sfname, inputFileTable[i].filename) == 0) { last_input_index = i; is_open = 1; break; } } } if (!is_open) { /* then open audio device or file. */ if (audio_in) { fd = open_audio_input(port_type, nchans); if (fd == -1) return -1.0; #ifdef INPUT_BUS_SUPPORT #endif /* INPUT_BUS_SUPPORT */ } else { fd = open_sound_file(sfname, &header_type, &data_format, &data_location, &srate, &nchans, &nsamps); if (fd == -1) return -1.0; #ifdef INPUT_BUS_SUPPORT if (startchan == -1) { /* no bus specified above */ startchan = 0; endchan = nchans - 1; } else { if (endchan - startchan >= nchans) { fprintf(stderr, "WARNING: You specifed more input buses than " "input file '%s' has channels.\n", sfname); fprintf(stderr, "Using in buses %d \n", foo); endchan = (startchan + nchans) - 1; } } #endif /* INPUT_BUS_SUPPORT */ dur = (double) (nsamps / nchans) / srate; if (print_is_on) { printf("Input file set for reading:\n"); printf(" name: %s\n", sfname); printf(" type: %s\n", sound_type_name(header_type)); printf(" format: %s\n", sound_format_name(data_format)); printf(" srate: %g\n", srate); printf(" chans: %d\n", nchans); printf(" duration: %g\n\n", dur); #ifdef INPUT_BUS_SUPPORT #endif /* INPUT_BUS_SUPPORT */ } if (srate != SR) { fprintf(stderr, "WARNING: The input file sampling rate is %g, but " "the output rate is currently %g.\n", srate, SR); } } /* Put new file descriptor into the first available slot in the inputFileTable. Also copy the filename for later checking, and fill in the other fields in the InputDesc struct (see rtdefs.h). last_input_index is the value that will be used by any instrument created after this call to rtinput(). */ for (i = 0; i < MAX_INPUT_FDS; i++) { if (inputFileTable[i].fd == NO_FD) { inputFileTable[i].filename = strdup(sfname); inputFileTable[i].fd = fd; inputFileTable[i].refcount = 0; inputFileTable[i].is_audio_dev = audio_in; inputFileTable[i].header_type = header_type; inputFileTable[i].data_format = data_format; inputFileTable[i].data_location = data_location; inputFileTable[i].srate = (float) srate; inputFileTable[i].chans = nchans; inputFileTable[i].dur = dur; last_input_index = i; break; } } /* If this is true, we've used up all input descriptors in our array. */ if (i == MAX_INPUT_FDS) { fprintf(stderr, "You have exceeded the maximum number of input " "files (%d)!\n", MAX_INPUT_FDS); return -1.0; } } /* Return this to Minc, so user can pass it to functions. */ return (double) last_input_index; } <|endoftext|>
<commit_before>/** * Copyright 2016 Pivotal Software, 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. **/ #ifndef QUICKSTEP_EXPRESSIONS_TABLE_GENERATOR_GENERATE_SERIES_HANDLE_HPP_ #define QUICKSTEP_EXPRESSIONS_TABLE_GENERATOR_GENERATE_SERIES_HANDLE_HPP_ #include <string> #include <vector> #include "expressions/table_generator/GeneratorFunctionHandle.hpp" #include "types/Type.hpp" #include "types/TypeFactory.hpp" #include "types/TypedValue.hpp" #include "types/containers/ColumnVectorsValueAccessor.hpp" #include "utility/Macros.hpp" #include "glog/logging.h" namespace quickstep { class ColumnVector; /** \addtogroup Expressions * @{ */ /** * @brief Handle for the instantiated GenerateSeries function. */ class GenerateSeriesHandle : public GeneratorFunctionHandle { public: /** * @brief Constructor * * @param func_name The registered name of the GenerateSeries function. * @param orig_args The original constant arguments to this function * @param type The unified type for the arguments. * @param start The start value. Its type should equal unified_type. * @param end The end value. Its type should equal unified_type. * @param step The step size. Its type should equal unified_type. */ GenerateSeriesHandle(const std::string &func_name, const std::vector<TypedValue> &orig_args, const Type &unified_type, const TypedValue &start, const TypedValue &end, const TypedValue &step) : GeneratorFunctionHandle(func_name, orig_args), type_(unified_type), start_(start), end_(end), step_(step) { } int getNumberOfOutputColumns() const override { return 1; } std::string getOutputColumnName(int index) const override { if (index > 0) { LOG(FATAL) << "generate_series function has only 1 output column"; } // Use the function name as the column name. return getName(); } const Type &getOutputColumnType(int index) const override { if (index > 0) { LOG(FATAL) << "generate_series function has only 1 output column"; } return type_; } void populateColumns(ColumnVectorsValueAccessor *results) const override { DCHECK(results != nullptr); // Populate the output column. ColumnVector *result_vec; switch (type_.getTypeID()) { case TypeID::kInt: { result_vec = generateColumn<int>(); break; } case TypeID::kLong: { result_vec = generateColumn<std::int64_t>(); break; } case TypeID::kFloat: { result_vec = generateColumn<float>(); break; } case TypeID::kDouble: { result_vec = generateColumn<double>(); break; } default: LOG(FATAL) << "GenerateSeries cannot handle arguments with type " << type_.getName(); } results->addColumn(result_vec); } private: template <typename T> ColumnVector *generateColumn() const { T start = start_.getLiteral<T>(); T end = end_.getLiteral<T>(); T step = step_.getLiteral<T>(); DCHECK_NE(step, 0); std::size_t length = static_cast<std::size_t>((end - start) / step) + 1; DCHECK_GE(length, 0); NativeColumnVector *result_vec = new NativeColumnVector(type_, length); T value = start; for (std::size_t i = 0; i < length; i++) { result_vec->appendUntypedValue(&value); value += step; } return result_vec; } const Type &type_; const TypedValue start_; const TypedValue end_; const TypedValue step_; DISALLOW_COPY_AND_ASSIGN(GenerateSeriesHandle); }; /** @} */ } // namespace quickstep #endif /* QUICKSTEP_EXPRESSIONS_TABLE_GENERATOR_GENERATE_SERIES_HANDLE_HPP_ */ <commit_msg>fix_DCHECK_GE_type<commit_after>/** * Copyright 2016 Pivotal Software, 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. **/ #ifndef QUICKSTEP_EXPRESSIONS_TABLE_GENERATOR_GENERATE_SERIES_HANDLE_HPP_ #define QUICKSTEP_EXPRESSIONS_TABLE_GENERATOR_GENERATE_SERIES_HANDLE_HPP_ #include <string> #include <vector> #include "expressions/table_generator/GeneratorFunctionHandle.hpp" #include "types/Type.hpp" #include "types/TypeFactory.hpp" #include "types/TypedValue.hpp" #include "types/containers/ColumnVectorsValueAccessor.hpp" #include "utility/Macros.hpp" #include "glog/logging.h" namespace quickstep { class ColumnVector; /** \addtogroup Expressions * @{ */ /** * @brief Handle for the instantiated GenerateSeries function. */ class GenerateSeriesHandle : public GeneratorFunctionHandle { public: /** * @brief Constructor * * @param func_name The registered name of the GenerateSeries function. * @param orig_args The original constant arguments to this function * @param type The unified type for the arguments. * @param start The start value. Its type should equal unified_type. * @param end The end value. Its type should equal unified_type. * @param step The step size. Its type should equal unified_type. */ GenerateSeriesHandle(const std::string &func_name, const std::vector<TypedValue> &orig_args, const Type &unified_type, const TypedValue &start, const TypedValue &end, const TypedValue &step) : GeneratorFunctionHandle(func_name, orig_args), type_(unified_type), start_(start), end_(end), step_(step) { } int getNumberOfOutputColumns() const override { return 1; } std::string getOutputColumnName(int index) const override { if (index > 0) { LOG(FATAL) << "generate_series function has only 1 output column"; } // Use the function name as the column name. return getName(); } const Type &getOutputColumnType(int index) const override { if (index > 0) { LOG(FATAL) << "generate_series function has only 1 output column"; } return type_; } void populateColumns(ColumnVectorsValueAccessor *results) const override { DCHECK(results != nullptr); // Populate the output column. ColumnVector *result_vec; switch (type_.getTypeID()) { case TypeID::kInt: { result_vec = generateColumn<int>(); break; } case TypeID::kLong: { result_vec = generateColumn<std::int64_t>(); break; } case TypeID::kFloat: { result_vec = generateColumn<float>(); break; } case TypeID::kDouble: { result_vec = generateColumn<double>(); break; } default: LOG(FATAL) << "GenerateSeries cannot handle arguments with type " << type_.getName(); } results->addColumn(result_vec); } private: template <typename T> ColumnVector *generateColumn() const { T start = start_.getLiteral<T>(); T end = end_.getLiteral<T>(); T step = step_.getLiteral<T>(); DCHECK_NE(step, static_cast<T>(0)); std::size_t length = static_cast<std::size_t>((end - start) / step) + 1; DCHECK_GE(length, static_cast<std::size_t>(0)); NativeColumnVector *result_vec = new NativeColumnVector(type_, length); T value = start; for (std::size_t i = 0; i < length; i++) { result_vec->appendUntypedValue(&value); value += step; } return result_vec; } const Type &type_; const TypedValue start_; const TypedValue end_; const TypedValue step_; DISALLOW_COPY_AND_ASSIGN(GenerateSeriesHandle); }; /** @} */ } // namespace quickstep #endif /* QUICKSTEP_EXPRESSIONS_TABLE_GENERATOR_GENERATE_SERIES_HANDLE_HPP_ */ <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. 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. *****************************************************************************/ /** * @file **/ #include "modules/planning/lattice/trajectory1d/piecewise_trajectory1d.h" #include <cmath> #include "modules/common/log.h" #include "glog/logging.h" namespace apollo { namespace planning { double PiecewiseTrajectory1d::Evaluate(const std::uint32_t order, const double param) const { auto it_lower = std::lower_bound(accumulated_param_lengths_.begin(), accumulated_param_lengths_.end(), param); CHECK(it_lower != accumulated_param_lengths_.end()); std::size_t index = (std::size_t)(it_lower - accumulated_param_lengths_.begin()); double param_overhead = 0.0; if (index != 0) { param_overhead = accumulated_param_lengths_[index - 1]; } return trajectory_segments_[index]->Evaluate(order, param - param_overhead); } double PiecewiseTrajectory1d::ParamLength() const { if (accumulated_param_lengths_.empty()) { return 0.0; } return accumulated_param_lengths_.back(); } std::string PiecewiseTrajectory1d::ToString() const { return ""; } void PiecewiseTrajectory1d::AppendSegment( const std::shared_ptr<Curve1d> trajectory) { if (trajectory_segments_.size() > 0) { trajectory_segments_.push_back(trajectory); } else { double s1 = trajectory->Evaluate(0, 0.0); double v1 = trajectory->Evaluate(1, 0.0); double a1 = trajectory->Evaluate(2, 0.0); double j1 = trajectory->Evaluate(3, 0.0); auto last_trajectory = trajectory_segments_.back(); double last_param_length = last_trajectory->ParamLength(); double s0 = last_trajectory->Evaluate(0, last_param_length); double v0 = last_trajectory->Evaluate(1, last_param_length); double a0 = last_trajectory->Evaluate(2, last_param_length); double j0 = last_trajectory->Evaluate(3, last_param_length); if (std::fabs(s0 - s1) > 1.0e-4) { AWARN << "The appended segment is not smooth in order 0"; } if (std::fabs(v0 - v1) > 1.0e-4) { AWARN << "The appended segment is not smooth in order 1"; } if (std::fabs(a0 - a1) > 1.0e-4) { AWARN << "The appended segment is not smooth in order 2"; } if (std::fabs(j0 - j1) > 1.0e-4) { AWARN << "The appended segment is not smooth in order 3"; } trajectory_segments_.push_back(trajectory); } double accumulated_param_length = trajectory->ParamLength(); if (accumulated_param_lengths_.size() > 0) { accumulated_param_length += accumulated_param_lengths_.back(); } accumulated_param_lengths_.push_back(accumulated_param_length); } void PiecewiseTrajectory1d::PopSegment() { if (trajectory_segments_.empty()) { return; } trajectory_segments_.pop_back(); accumulated_param_lengths_.pop_back(); } std::size_t PiecewiseTrajectory1d::NumOfSegments() const { return trajectory_segments_.size(); } } // namespace planning } // namespace apollo <commit_msg>planning: bug fix in piecewise_trajectory1d<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. 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. *****************************************************************************/ /** * @file **/ #include "modules/planning/lattice/trajectory1d/piecewise_trajectory1d.h" #include <cmath> #include "modules/common/log.h" #include "glog/logging.h" namespace apollo { namespace planning { double PiecewiseTrajectory1d::Evaluate(const std::uint32_t order, const double param) const { auto it_lower = std::lower_bound(accumulated_param_lengths_.begin(), accumulated_param_lengths_.end(), param); CHECK(it_lower != accumulated_param_lengths_.end()); std::size_t index = (std::size_t)(it_lower - accumulated_param_lengths_.begin()); double param_overhead = 0.0; if (index != 0) { param_overhead = accumulated_param_lengths_[index - 1]; } return trajectory_segments_[index]->Evaluate(order, param - param_overhead); } double PiecewiseTrajectory1d::ParamLength() const { if (accumulated_param_lengths_.empty()) { return 0.0; } return accumulated_param_lengths_.back(); } std::string PiecewiseTrajectory1d::ToString() const { return ""; } void PiecewiseTrajectory1d::AppendSegment( const std::shared_ptr<Curve1d> trajectory) { if (trajectory_segments_.size() == 0) { trajectory_segments_.push_back(trajectory); } else { double s1 = trajectory->Evaluate(0, 0.0); double v1 = trajectory->Evaluate(1, 0.0); double a1 = trajectory->Evaluate(2, 0.0); double j1 = trajectory->Evaluate(3, 0.0); auto last_trajectory = trajectory_segments_.back(); double last_param_length = last_trajectory->ParamLength(); double s0 = last_trajectory->Evaluate(0, last_param_length); double v0 = last_trajectory->Evaluate(1, last_param_length); double a0 = last_trajectory->Evaluate(2, last_param_length); double j0 = last_trajectory->Evaluate(3, last_param_length); if (std::fabs(s0 - s1) > 1.0e-4) { AWARN << "The appended segment is not smooth in order 0"; } if (std::fabs(v0 - v1) > 1.0e-4) { AWARN << "The appended segment is not smooth in order 1"; } if (std::fabs(a0 - a1) > 1.0e-4) { AWARN << "The appended segment is not smooth in order 2"; } if (std::fabs(j0 - j1) > 1.0e-4) { AWARN << "The appended segment is not smooth in order 3"; } trajectory_segments_.push_back(trajectory); } double accumulated_param_length = trajectory->ParamLength(); if (accumulated_param_lengths_.size() > 0) { accumulated_param_length += accumulated_param_lengths_.back(); } accumulated_param_lengths_.push_back(accumulated_param_length); } void PiecewiseTrajectory1d::PopSegment() { if (trajectory_segments_.empty()) { return; } trajectory_segments_.pop_back(); accumulated_param_lengths_.pop_back(); } std::size_t PiecewiseTrajectory1d::NumOfSegments() const { return trajectory_segments_.size(); } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved */ #include "../../../StroikaPreComp.h" #include "../../../Characters/FloatConversion.h" #include "../../../Characters/Format.h" #include "../../../Characters/String2Int.h" #include "../../../Characters/StringBuilder.h" #include "../../../Characters/String_Constant.h" #include "../../../Streams/TextReader.h" #include "../../BadFormatException.h" #include "Reader.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::DataExchange; using Characters::Character; using Characters::StringBuilder; using Memory::Byte; using Memory::Optional; using Characters::String_Constant; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 namespace { /* * Parse strategy: * o Pre-pass to map all input to UNICODE - and then just handle a sequence of unicode strings * o Classic resursive decent parser. * o Inline lexical analysis (cuz very simple) */ enum ReadState_ { eNeutral_, eInObject_, eInArray_, eInNumber_, eInString_, }; /* * Utilities to treat string iterator/end ptr as a 'stream pointer' - and get next char */ inline wchar_t NextChar_ (const Streams::InputStream<Character>& in) { Require (not in.IsAtEOF ()); return in.Read ()->As<wchar_t> (); } VariantValue Reader_value_ (const Streams::InputStream<Character>& in); // throw if bad hex digit unsigned int HexChar2Num_ (char c) { if ('0' <= c and c <= '9') { return c - '0'; } if ('A' <= c and c <= 'F') { return (c - 'A') + 10; } if ('a' <= c and c <= 'f') { return (c - 'a') + 10; } Execution::Throw (BadFormatException (String_Constant{L"JSON: bad hex digit after \\u"})); } // 'in' is positioned to the start of string, and we read, leaving in possitioned just after end of string VariantValue Reader_String_ (const Streams::InputStream<Character>& in) { Require (in != nullptr); Require (not in.IsAtEOF ()); wchar_t c = NextChar_ (in); if (c != '\"') { Execution::Throw (BadFormatException (String_Constant{L"JSON: Expected quoted string"})); } // accumulate chars, and check for close-quote StringBuilder result; while (true) { if (in.IsAtEOF ()) { Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected EOF reading string (looking for close quote)"})); } c = NextChar_ (in); if (c == '\"') { return VariantValue (result.str ()); } else if (c == '\\') { // quoted character read... if (in.IsAtEOF ()) { Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected EOF reading string (looking for close quote)"})); } c = NextChar_ (in); switch (c) { case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'u': { // Not sure this is right -- But I hope so ... -- LGP 2012-11-29 wchar_t newC = '\0'; for (int n = 0; n < 4; ++n) { if (in.IsAtEOF ()) { Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected EOF reading string (looking for close quote)"})); } newC += HexChar2Num_ (static_cast<char> (NextChar_ (in))); if (n != 3) { newC <<= 4; } } c = newC; } break; default: { // if we have \N for any unrecognized N, just treat it as N } } } result += c; // must handle other character quoting (besides \u which was preflighted) } } // 'in' is positioned to the second character of number (first passed as arg), and we read, leaving in positioned just after end of number static constexpr Character kDash_{'-'}; VariantValue Reader_Number_ (wchar_t initialChar, const Streams::InputStream<Character>& in) { Require (in != nullptr); Require (initialChar == '-' or iswdigit (initialChar)); bool containsDot = false; // ACCUMULATE STRING, and then call builtin number parsing functions... // This accumulation is NOT as restrictive as it could be - but should accept all valid numbers StringBuilder tmp; for (wchar_t c = initialChar; c != '\0'; c = in.Read ().Value ('\0').As<wchar_t> ()) { if (iswdigit (c) or c == '.' or c == 'e' or c == 'E' or c == '+' or c == '-') { tmp += c; if (c == '.') { containsDot = true; } } else { // any other character signals end of number (not a syntax error) // but backup - don't consume next character - not part of number Assert (not!tmp.empty ()); // at least consumed 'initialChar' in.Seek (Streams::Whence::eFromCurrent, -1); break; } } if (containsDot) { return VariantValue (Characters::String2Float<long double> (tmp.str ())); } else { // if no - use unsigned since has wider range (if no -) String t = tmp.str (); return t.LTrim ().StartsWith (kDash_) ? VariantValue (Characters::String2Int<long long int> (t)) : VariantValue (Characters::String2Int<unsigned long long int> (t)); } } // NOTE: THIS STARTS SEEKED JUST PAST OPENING '{' VariantValue Reader_Object_ (const Streams::InputStream<Character>& in) { Require (in != nullptr); Require (not in.IsAtEOF ()); Mapping<String, VariantValue> result; // accumulate elements, and check for close-array enum LookingFor { eName, eValue, eColon, eComma }; LookingFor lf = eName; Optional<String> curName; while (true) { Optional<Character> oNextChar = in.Read (); if (oNextChar.IsMissing ()) { in.Seek (Streams::Whence::eFromCurrent, -1); Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected EOF reading string (looking for '}')"})); } wchar_t nextChar = oNextChar->As<wchar_t> (); if (nextChar == '}') { if (lf == eName or lf == eComma) { // skip char return VariantValue (result); } else { in.Seek (Streams::Whence::eFromCurrent, -1); Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected '}' reading object"})); } } else if (iswspace (nextChar)) { // skip char } else if (nextChar == ',') { if (lf == eComma) { // skip char lf = eName; // next elt } else { in.Seek (Streams::Whence::eFromCurrent, -1); Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected ',' reading object"})); } } else if (nextChar == ':') { if (lf == eColon) { // skip char lf = eValue; // next elt } else { in.Seek (Streams::Whence::eFromCurrent, -1); Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected ':' reading object"})); } } else { in.Seek (Streams::Whence::eFromCurrent, -1); if (lf == eName) { curName = Reader_String_ (in).As<wstring> (); lf = eColon; } else if (lf == eValue) { Assert (curName.IsPresent ()); result.Add (*curName, Reader_value_ (in)); curName.clear (); lf = eComma; } else { Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected character looking for colon or comma reading object"})); } } } } // NOTE - called with OPENING '[' already read VariantValue Reader_Array_ (const Streams::InputStream<Characters::Character>& in) { Require (in != nullptr); Require (not in.IsAtEOF ()); vector<VariantValue> result; // accumulate elements, and check for close-array bool lookingForElt = true; while (true) { if (in.IsAtEOF ()) { Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected EOF reading string (looking for ']')"})); } if (in.Peek () == ']') { if (lookingForElt) { // allow ending ',' - harmless - could be more aggressive - but if so - careful of zero-sized array special case } NextChar_ (in); // skip char return VariantValue (result); } else if (in.Peek () == ',') { if (lookingForElt) { Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected second ',' in reading array"})); } else { lookingForElt = true; } NextChar_ (in); // skip char } else if (iswspace (in.Peek ()->As<wchar_t> ())) { NextChar_ (in); // skip char } else { // not looking at whitespace, in midst of array, and array not terminated, so better be looking at a value if (lookingForElt) { Containers::ReserveSpeedTweekAdd1 (result); result.push_back (Reader_value_ (in)); lookingForElt = false; } else { Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected character (missing ',' ?) in reading array"})); } } } } VariantValue Reader_SpecialToken_ (wchar_t initialChar, const Streams::InputStream<Characters::Character>& in) { Require (in != nullptr); Streams::SeekOffsetType savedPos = in.GetOffset (); switch (initialChar) { case 'f': { Character buf[4]; if (in.ReadAll (begin (buf), end (buf)) == 4 and buf[0] == 'a' and buf[1] == 'l' and buf[2] == 's' and buf[3] == 'e') { return VariantValue{false}; } } break; case 't': { Character buf[3]; if (in.ReadAll (begin (buf), end (buf)) == 3 and buf[0] == 'r' and buf[1] == 'u' and buf[2] == 'e') { return VariantValue{true}; } } break; case 'n': { Character buf[3]; if (in.ReadAll (begin (buf), end (buf)) == 3 and buf[0] == 'u' and buf[1] == 'l' and buf[2] == 'l') { return VariantValue{}; } } break; } in.Seek (savedPos - 1); // because handed initial char, and seeked past it Execution::Throw (BadFormatException (String_Constant{L"JSON: Unrecognized token"})); } VariantValue Reader_value_ (const Streams::InputStream<Characters::Character>& in) { // Skip initial whitespace, and look for any value: // string // number // object // array // true // false // null for (Optional<Character> oc = in.Read (); oc; oc = in.Read ()) { switch (oc->As<wchar_t> ()) { case '\"': in.Seek (Streams::Whence::eFromCurrent, -1); return Reader_String_ (in); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return Reader_Number_ (oc->As<wchar_t> (), in); case '{': return Reader_Object_ (in); case '[': return Reader_Array_ (in); case 't': case 'f': case 'n': return Reader_SpecialToken_ (oc->As<wchar_t> (), in); default: { if (iswspace (oc->As<wchar_t> ())) { // ignore } else { Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected character looking for start of value"})); } } } } // if we get here - nothing found Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected EOF looking for value"})); } } /* ******************************************************************************** ************************* Variant::JSON::Reader ******************************** ******************************************************************************** */ class Variant::JSON::Reader::Rep_ : public Variant::Reader::_IRep { public: virtual _SharedPtrIRep Clone () const override { return make_shared<Rep_> (); // no instance data } virtual String GetDefaultFileSuffix () const override { return String_Constant{L".json"}; } virtual VariantValue Read (const Streams::InputStream<Byte>& in) override { constexpr bool kSeekable_{true}; return Read (Streams::TextReader (in, kSeekable_)); } virtual VariantValue Read (const Streams::InputStream<Characters::Character>& in) override { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx ("DataExchange::JSON::Reader::Rep_::Read"); #endif Require (in.IsSeekable ()); return Reader_value_ (in); } }; Variant::JSON::Reader::Reader () : inherited (make_shared<Rep_> ()) { } <commit_msg>fixed a couple small assertion/regressions in JSON/Reader for recent changes<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2017. All rights reserved */ #include "../../../StroikaPreComp.h" #include "../../../Characters/FloatConversion.h" #include "../../../Characters/Format.h" #include "../../../Characters/String2Int.h" #include "../../../Characters/StringBuilder.h" #include "../../../Characters/String_Constant.h" #include "../../../Streams/TextReader.h" #include "../../BadFormatException.h" #include "Reader.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::DataExchange; using Characters::Character; using Characters::StringBuilder; using Memory::Byte; using Memory::Optional; using Characters::String_Constant; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 namespace { /* * Parse strategy: * o Pre-pass to map all input to UNICODE - and then just handle a sequence of unicode strings * o Classic resursive decent parser. * o Inline lexical analysis (cuz very simple) */ enum ReadState_ { eNeutral_, eInObject_, eInArray_, eInNumber_, eInString_, }; /* * Utilities to treat string iterator/end ptr as a 'stream pointer' - and get next char */ inline wchar_t NextChar_ (const Streams::InputStream<Character>& in) { Require (not in.IsAtEOF ()); return in.Read ()->As<wchar_t> (); } VariantValue Reader_value_ (const Streams::InputStream<Character>& in); // throw if bad hex digit unsigned int HexChar2Num_ (char c) { if ('0' <= c and c <= '9') { return c - '0'; } if ('A' <= c and c <= 'F') { return (c - 'A') + 10; } if ('a' <= c and c <= 'f') { return (c - 'a') + 10; } Execution::Throw (BadFormatException (String_Constant{L"JSON: bad hex digit after \\u"})); } // 'in' is positioned to the start of string, and we read, leaving in possitioned just after end of string VariantValue Reader_String_ (const Streams::InputStream<Character>& in) { Require (in != nullptr); Require (not in.IsAtEOF ()); wchar_t c = NextChar_ (in); if (c != '\"') { Execution::Throw (BadFormatException (String_Constant{L"JSON: Expected quoted string"})); } // accumulate chars, and check for close-quote StringBuilder result; while (true) { if (in.IsAtEOF ()) { Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected EOF reading string (looking for close quote)"})); } c = NextChar_ (in); if (c == '\"') { return VariantValue (result.str ()); } else if (c == '\\') { // quoted character read... if (in.IsAtEOF ()) { Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected EOF reading string (looking for close quote)"})); } c = NextChar_ (in); switch (c) { case 'b': c = '\b'; break; case 'f': c = '\f'; break; case 'n': c = '\n'; break; case 'r': c = '\r'; break; case 't': c = '\t'; break; case 'u': { // Not sure this is right -- But I hope so ... -- LGP 2012-11-29 wchar_t newC = '\0'; for (int n = 0; n < 4; ++n) { if (in.IsAtEOF ()) { Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected EOF reading string (looking for close quote)"})); } newC += HexChar2Num_ (static_cast<char> (NextChar_ (in))); if (n != 3) { newC <<= 4; } } c = newC; } break; default: { // if we have \N for any unrecognized N, just treat it as N } } } result += c; // must handle other character quoting (besides \u which was preflighted) } } // 'in' is positioned to the second character of number (first passed as arg), and we read, leaving in positioned just after end of number static constexpr Character kDash_{'-'}; VariantValue Reader_Number_ (wchar_t initialChar, const Streams::InputStream<Character>& in) { Require (in != nullptr); Require (initialChar == '-' or iswdigit (initialChar)); bool containsDot = false; // ACCUMULATE STRING, and then call builtin number parsing functions... // This accumulation is NOT as restrictive as it could be - but should accept all valid numbers StringBuilder tmp; for (wchar_t c = initialChar; c != '\0'; c = in.Read ().Value ('\0').As<wchar_t> ()) { if (iswdigit (c) or c == '.' or c == 'e' or c == 'E' or c == '+' or c == '-') { tmp += c; if (c == '.') { containsDot = true; } } else { // any other character signals end of number (not a syntax error) // but backup - don't consume next character - not part of number Assert (not tmp.empty ()); // at least consumed 'initialChar' in.Seek (Streams::Whence::eFromCurrent, -1); break; } } if (containsDot) { return VariantValue (Characters::String2Float<long double> (tmp.str ())); } else { // if no - use unsigned since has wider range (if no -) String t = tmp.str (); return t.LTrim ().StartsWith (kDash_) ? VariantValue (Characters::String2Int<long long int> (t)) : VariantValue (Characters::String2Int<unsigned long long int> (t)); } } // NOTE: THIS STARTS SEEKED JUST PAST OPENING '{' VariantValue Reader_Object_ (const Streams::InputStream<Character>& in) { Require (in != nullptr); Mapping<String, VariantValue> result; // accumulate elements, and check for close-array enum LookingFor { eName, eValue, eColon, eComma }; LookingFor lf = eName; Optional<String> curName; while (true) { Optional<Character> oNextChar = in.Read (); if (oNextChar.IsMissing ()) { in.Seek (Streams::Whence::eFromCurrent, -1); Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected EOF reading string (looking for '}')"})); } wchar_t nextChar = oNextChar->As<wchar_t> (); if (nextChar == '}') { if (lf == eName or lf == eComma) { // skip char return VariantValue (result); } else { in.Seek (Streams::Whence::eFromCurrent, -1); Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected '}' reading object"})); } } else if (iswspace (nextChar)) { // skip char } else if (nextChar == ',') { if (lf == eComma) { // skip char lf = eName; // next elt } else { in.Seek (Streams::Whence::eFromCurrent, -1); Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected ',' reading object"})); } } else if (nextChar == ':') { if (lf == eColon) { // skip char lf = eValue; // next elt } else { in.Seek (Streams::Whence::eFromCurrent, -1); Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected ':' reading object"})); } } else { in.Seek (Streams::Whence::eFromCurrent, -1); if (lf == eName) { curName = Reader_String_ (in).As<wstring> (); lf = eColon; } else if (lf == eValue) { Assert (curName.IsPresent ()); result.Add (*curName, Reader_value_ (in)); curName.clear (); lf = eComma; } else { Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected character looking for colon or comma reading object"})); } } } } // NOTE - called with OPENING '[' already read VariantValue Reader_Array_ (const Streams::InputStream<Characters::Character>& in) { Require (in != nullptr); vector<VariantValue> result; // accumulate elements, and check for close-array bool lookingForElt = true; while (true) { if (in.IsAtEOF ()) { Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected EOF reading string (looking for ']')"})); } if (in.Peek () == ']') { if (lookingForElt) { // allow ending ',' - harmless - could be more aggressive - but if so - careful of zero-sized array special case } NextChar_ (in); // skip char return VariantValue (result); } else if (in.Peek () == ',') { if (lookingForElt) { Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected second ',' in reading array"})); } else { lookingForElt = true; } NextChar_ (in); // skip char } else if (iswspace (in.Peek ()->As<wchar_t> ())) { NextChar_ (in); // skip char } else { // not looking at whitespace, in midst of array, and array not terminated, so better be looking at a value if (lookingForElt) { Containers::ReserveSpeedTweekAdd1 (result); result.push_back (Reader_value_ (in)); lookingForElt = false; } else { Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected character (missing ',' ?) in reading array"})); } } } } VariantValue Reader_SpecialToken_ (wchar_t initialChar, const Streams::InputStream<Characters::Character>& in) { Require (in != nullptr); Streams::SeekOffsetType savedPos = in.GetOffset (); switch (initialChar) { case 'f': { Character buf[4]; if (in.ReadAll (begin (buf), end (buf)) == 4 and buf[0] == 'a' and buf[1] == 'l' and buf[2] == 's' and buf[3] == 'e') { return VariantValue{false}; } } break; case 't': { Character buf[3]; if (in.ReadAll (begin (buf), end (buf)) == 3 and buf[0] == 'r' and buf[1] == 'u' and buf[2] == 'e') { return VariantValue{true}; } } break; case 'n': { Character buf[3]; if (in.ReadAll (begin (buf), end (buf)) == 3 and buf[0] == 'u' and buf[1] == 'l' and buf[2] == 'l') { return VariantValue{}; } } break; } in.Seek (savedPos - 1); // because handed initial char, and seeked past it Execution::Throw (BadFormatException (String_Constant{L"JSON: Unrecognized token"})); } VariantValue Reader_value_ (const Streams::InputStream<Characters::Character>& in) { // Skip initial whitespace, and look for any value: // string // number // object // array // true // false // null for (Optional<Character> oc = in.Read (); oc; oc = in.Read ()) { switch (oc->As<wchar_t> ()) { case '\"': in.Seek (Streams::Whence::eFromCurrent, -1); return Reader_String_ (in); case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return Reader_Number_ (oc->As<wchar_t> (), in); case '{': return Reader_Object_ (in); case '[': return Reader_Array_ (in); case 't': case 'f': case 'n': return Reader_SpecialToken_ (oc->As<wchar_t> (), in); default: { if (iswspace (oc->As<wchar_t> ())) { // ignore } else { Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected character looking for start of value"})); } } } } // if we get here - nothing found Execution::Throw (BadFormatException (String_Constant{L"JSON: Unexpected EOF looking for value"})); } } /* ******************************************************************************** ************************* Variant::JSON::Reader ******************************** ******************************************************************************** */ class Variant::JSON::Reader::Rep_ : public Variant::Reader::_IRep { public: virtual _SharedPtrIRep Clone () const override { return make_shared<Rep_> (); // no instance data } virtual String GetDefaultFileSuffix () const override { return String_Constant{L".json"}; } virtual VariantValue Read (const Streams::InputStream<Byte>& in) override { constexpr bool kSeekable_{true}; return Read (Streams::TextReader (in, kSeekable_)); } virtual VariantValue Read (const Streams::InputStream<Characters::Character>& in) override { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx ("DataExchange::JSON::Reader::Rep_::Read"); #endif Require (in.IsSeekable ()); return Reader_value_ (in); } }; Variant::JSON::Reader::Reader () : inherited (make_shared<Rep_> ()) { } <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <otbMachineLearningModel.h> typedef otb::MachineLearningModel<float,short> MachineLearningModelType1; typedef MachineLearningModelType1::InputValueType InputValueType1; typedef MachineLearningModelType1::InputSampleType InputSampleType1; typedef MachineLearningModelType1::InputListSampleType InputListSampleType1; typedef MachineLearningModelType1::TargetValueType TargetValueType1; typedef MachineLearningModelType1::TargetSampleType TargetSampleType1; typedef MachineLearningModelType1::TargetListSampleType TargetListSampleType1; typedef otb::MachineLearningModel<float,itk::VariableLengthVector<double>> MachineLearningModelType2; typedef MachineLearningModelType2::InputValueType InputValueType2; typedef MachineLearningModelType2::InputSampleType InputSampleType2; typedef MachineLearningModelType2::InputListSampleType InputListSampleType2; typedef MachineLearningModelType2::TargetValueType TargetValueType2; typedef MachineLearningModelType2::TargetSampleType TargetSampleType2; typedef MachineLearningModelType2::TargetListSampleType TargetListSampleType2; <commit_msg>BUG: avoid >> at the end of nested templates<commit_after>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <otbMachineLearningModel.h> typedef otb::MachineLearningModel<float,short> MachineLearningModelType1; typedef MachineLearningModelType1::InputValueType InputValueType1; typedef MachineLearningModelType1::InputSampleType InputSampleType1; typedef MachineLearningModelType1::InputListSampleType InputListSampleType1; typedef MachineLearningModelType1::TargetValueType TargetValueType1; typedef MachineLearningModelType1::TargetSampleType TargetSampleType1; typedef MachineLearningModelType1::TargetListSampleType TargetListSampleType1; typedef otb::MachineLearningModel<float,itk::VariableLengthVector<double> > MachineLearningModelType2; typedef MachineLearningModelType2::InputValueType InputValueType2; typedef MachineLearningModelType2::InputSampleType InputSampleType2; typedef MachineLearningModelType2::InputListSampleType InputListSampleType2; typedef MachineLearningModelType2::TargetValueType TargetValueType2; typedef MachineLearningModelType2::TargetSampleType TargetSampleType2; typedef MachineLearningModelType2::TargetListSampleType TargetListSampleType2; <|endoftext|>
<commit_before>#include <node.h> #include <node_object_wrap.h> extern "C" { #include <unicode/usprep.h> #include <string.h> } #include <exception> using namespace v8; using namespace node; /*** Utility ***/ static Handle<Value> throwTypeError(const char *msg) { return ThrowException(Exception::TypeError(String::New(msg))); } /* supports return of just enum */ class UnknownProfileException : public std::exception { }; class StringPrep : public ObjectWrap { public: static void Initialize(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "prepare", Prepare); target->Set(String::NewSymbol("StringPrep"), t->GetFunction()); } bool good() const { // warnings are negative, errors positive return error <= 0; } const char *errorName() const { return u_errorName(error); } Handle<Value> makeException() const { return ThrowException(Exception::Error(String::New(errorName()))); } protected: /*** Constructor ***/ static Handle<Value> New(const Arguments& args) { HandleScope scope; if (args.Length() == 1 && args[0]->IsString()) { String::Utf8Value arg0(args[0]->ToString()); UStringPrepProfileType profileType = parseProfileType(arg0); if (profileType < 0) return throwTypeError("Unknown StringPrep profile"); else { StringPrep *self = new StringPrep(profileType); if (self->good()) { self->Wrap(args.This()); return args.This(); } else { Handle<Value> exception = self->makeException(); delete self; return ThrowException(exception); } } } else return throwTypeError("Bad argument."); } StringPrep(const UStringPrepProfileType profileType) { profile = usprep_openByType(profileType, &error); } /*** Destructor ***/ ~StringPrep() { if (profile) usprep_close(profile); } /*** Prepare ***/ static Handle<Value> Prepare(const Arguments& args) { HandleScope scope; if (args.Length() == 1 && args[0]->IsString()) { StringPrep *self = ObjectWrap::Unwrap<StringPrep>(args.This()); String::Utf8Value arg0(args[0]->ToString()); return scope.Close(self->prepare(arg0)); } else return throwTypeError("Bad argument."); } Handle<Value> prepare(String::Utf8Value &str) { size_t destLen = str.length(); char *dest = NULL; while(!dest) { dest = new char[destLen]; size_t w = usprep_prepare(profile, reinterpret_cast<UChar *>(*str), str.length(), reinterpret_cast<UChar *>(dest), destLen, USPREP_DEFAULT, NULL, &error); if (error == U_BUFFER_OVERFLOW_ERROR) { // retry with a dest buffer twice as large destLen *= 2; delete[] dest; dest = NULL; } else if (!good()) { // other error, just bail out delete[] dest; return ThrowException(makeException()); } } Local<String> result = String::New(dest, destLen); delete[] dest; return result; } private: UStringPrepProfile *profile; UErrorCode error; static enum UStringPrepProfileType parseProfileType(String::Utf8Value &profile) //throw(UnknownProfileException) { if (strcasecmp(*profile, "nameprep") == 0) return USPREP_RFC3491_NAMEPREP; if (strcasecmp(*profile, "nfs4_cs_prep") == 0) return USPREP_RFC3530_NFS4_CS_PREP; if (strcasecmp(*profile, "nfs4_cs_prep") == 0) return USPREP_RFC3530_NFS4_CS_PREP_CI; if (strcasecmp(*profile, "nfs4_cis_prep") == 0) return USPREP_RFC3530_NFS4_CIS_PREP; if (strcasecmp(*profile, "nfs4_mixed_prep prefix") == 0) return USPREP_RFC3530_NFS4_MIXED_PREP_PREFIX; if (strcasecmp(*profile, "nfs4_mixed_prep suffix") == 0) return USPREP_RFC3530_NFS4_MIXED_PREP_SUFFIX; if (strcasecmp(*profile, "iscsi") == 0) return USPREP_RFC3722_ISCSI; if (strcasecmp(*profile, "nodeprep") == 0) return USPREP_RFC3920_NODEPREP; if (strcasecmp(*profile, "resourceprep") == 0) return USPREP_RFC3920_RESOURCEPREP; if (strcasecmp(*profile, "mib") == 0) return USPREP_RFC4011_MIB; if (strcasecmp(*profile, "saslprep") == 0) return USPREP_RFC4013_SASLPREP; if (strcasecmp(*profile, "trace") == 0) return USPREP_RFC4505_TRACE; if (strcasecmp(*profile, "ldap") == 0) return USPREP_RFC4518_LDAP; if (strcasecmp(*profile, "ldapci") == 0) return USPREP_RFC4518_LDAP_CI; throw UnknownProfileException(); } }; /*** Initialization ***/ extern "C" void init(Handle<Object> target) { HandleScope scope; StringPrep::Initialize(target); } <commit_msg>node-stringprep: fix error handling<commit_after>#include <node.h> #include <node_object_wrap.h> extern "C" { #include <unicode/usprep.h> #include <string.h> } #include <exception> using namespace v8; using namespace node; /*** Utility ***/ static Handle<Value> throwTypeError(const char *msg) { return ThrowException(Exception::TypeError(String::New(msg))); } /* supports return of just enum */ class UnknownProfileException : public std::exception { }; class StringPrep : public ObjectWrap { public: static void Initialize(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); t->InstanceTemplate()->SetInternalFieldCount(1); NODE_SET_PROTOTYPE_METHOD(t, "prepare", Prepare); target->Set(String::NewSymbol("StringPrep"), t->GetFunction()); } bool good() const { // warnings are negative, errors positive return error <= 0; } const char *errorName() const { return u_errorName(error); } Handle<Value> makeException() const { return Exception::Error(String::New(errorName())); } protected: /*** Constructor ***/ static Handle<Value> New(const Arguments& args) { HandleScope scope; if (args.Length() == 1 && args[0]->IsString()) { String::Utf8Value arg0(args[0]->ToString()); UStringPrepProfileType profileType; try { profileType = parseProfileType(arg0); } catch (UnknownProfileException &) { return throwTypeError("Unknown StringPrep profile"); } StringPrep *self = new StringPrep(profileType); if (self->good()) { self->Wrap(args.This()); return args.This(); } else { Handle<Value> exception = self->makeException(); delete self; return ThrowException(exception); } } else return throwTypeError("Bad argument."); } StringPrep(const UStringPrepProfileType profileType) : error(U_ZERO_ERROR) { profile = usprep_openByType(profileType, &error); } /*** Destructor ***/ ~StringPrep() { if (profile) usprep_close(profile); } /*** Prepare ***/ static Handle<Value> Prepare(const Arguments& args) { HandleScope scope; if (args.Length() == 1 && args[0]->IsString()) { StringPrep *self = ObjectWrap::Unwrap<StringPrep>(args.This()); String::Utf8Value arg0(args[0]->ToString()); return scope.Close(self->prepare(arg0)); } else return throwTypeError("Bad argument."); } Handle<Value> prepare(String::Utf8Value &str) { size_t destLen = str.length(); char *dest = NULL; while(!dest) { dest = new char[destLen]; size_t w = usprep_prepare(profile, reinterpret_cast<UChar *>(*str), str.length(), reinterpret_cast<UChar *>(dest), destLen, USPREP_DEFAULT, NULL, &error); if (error == U_BUFFER_OVERFLOW_ERROR) { // retry with a dest buffer twice as large destLen *= 2; delete[] dest; dest = NULL; } else if (!good()) { // other error, just bail out delete[] dest; return ThrowException(makeException()); } } Local<String> result = String::New(dest, destLen); delete[] dest; return result; } private: UStringPrepProfile *profile; UErrorCode error; static enum UStringPrepProfileType parseProfileType(String::Utf8Value &profile) throw(UnknownProfileException) { if (strcasecmp(*profile, "nameprep") == 0) return USPREP_RFC3491_NAMEPREP; if (strcasecmp(*profile, "nfs4_cs_prep") == 0) return USPREP_RFC3530_NFS4_CS_PREP; if (strcasecmp(*profile, "nfs4_cs_prep") == 0) return USPREP_RFC3530_NFS4_CS_PREP_CI; if (strcasecmp(*profile, "nfs4_cis_prep") == 0) return USPREP_RFC3530_NFS4_CIS_PREP; if (strcasecmp(*profile, "nfs4_mixed_prep prefix") == 0) return USPREP_RFC3530_NFS4_MIXED_PREP_PREFIX; if (strcasecmp(*profile, "nfs4_mixed_prep suffix") == 0) return USPREP_RFC3530_NFS4_MIXED_PREP_SUFFIX; if (strcasecmp(*profile, "iscsi") == 0) return USPREP_RFC3722_ISCSI; if (strcasecmp(*profile, "nodeprep") == 0) return USPREP_RFC3920_NODEPREP; if (strcasecmp(*profile, "resourceprep") == 0) return USPREP_RFC3920_RESOURCEPREP; if (strcasecmp(*profile, "mib") == 0) return USPREP_RFC4011_MIB; if (strcasecmp(*profile, "saslprep") == 0) return USPREP_RFC4013_SASLPREP; if (strcasecmp(*profile, "trace") == 0) return USPREP_RFC4505_TRACE; if (strcasecmp(*profile, "ldap") == 0) return USPREP_RFC4518_LDAP; if (strcasecmp(*profile, "ldapci") == 0) return USPREP_RFC4518_LDAP_CI; throw UnknownProfileException(); } }; /*** Initialization ***/ extern "C" void init(Handle<Object> target) { HandleScope scope; StringPrep::Initialize(target); } <|endoftext|>
<commit_before>// Scintilla source code edit control /** @file CallTip.cxx ** Code for displaying call tips. **/ // Copyright 1998-2001 by Neil Hodgson <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include "Platform.h" #include "Scintilla.h" #include "CallTip.h" #include <stdio.h> #ifdef SCI_NAMESPACE using namespace Scintilla; #endif static const int insetX = 5; // text inset in x from calltip border static const int widthArrow = 14; CallTip::CallTip() { wCallTip = 0; inCallTipMode = false; posStartCallTip = 0; val = 0; rectUp = PRectangle(0,0,0,0); rectDown = PRectangle(0,0,0,0); lineHeight = 1; startHighlight = 0; endHighlight = 0; tabSize = 0; useStyleCallTip = false; // for backwards compatibility #ifdef __APPLE__ // proper apple colours for the default colourBG.desired = ColourDesired(0xff, 0xff, 0xc6); colourUnSel.desired = ColourDesired(0, 0, 0); #else colourBG.desired = ColourDesired(0xff, 0xff, 0xff); colourUnSel.desired = ColourDesired(0x80, 0x80, 0x80); #endif colourSel.desired = ColourDesired(0, 0, 0x80); colourShade.desired = ColourDesired(0, 0, 0); colourLight.desired = ColourDesired(0xc0, 0xc0, 0xc0); } CallTip::~CallTip() { font.Release(); wCallTip.Destroy(); delete []val; val = 0; } void CallTip::RefreshColourPalette(Palette &pal, bool want) { pal.WantFind(colourBG, want); pal.WantFind(colourUnSel, want); pal.WantFind(colourSel, want); pal.WantFind(colourShade, want); pal.WantFind(colourLight, want); } // Although this test includes 0, we should never see a \0 character. static bool IsArrowCharacter(char ch) { return (ch == 0) || (ch == '\001') || (ch == '\002'); } // We ignore tabs unless a tab width has been set. bool CallTip::IsTabCharacter(char ch) { return (tabSize > 0) && (ch == '\t'); } int CallTip::NextTabPos(int x) { if (tabSize > 0) { // paranoia... not called unless this is true x -= insetX; // position relative to text x = (x + tabSize) / tabSize; // tab "number" return tabSize*x + insetX; // position of next tab } else { return x + 1; // arbitrary } } // Draw a section of the call tip that does not include \n in one colour. // The text may include up to numEnds tabs or arrow characters. void CallTip::DrawChunk(Surface *surface, int &x, const char *s, int posStart, int posEnd, int ytext, PRectangle rcClient, bool highlight, bool draw) { s += posStart; int len = posEnd - posStart; // Divide the text into sections that are all text, or that are // single arrows or single tab characters (if tabSize > 0). int maxEnd = 0; const int numEnds = 10; int ends[numEnds + 2]; for (int i=0;i<len;i++) { if ((maxEnd < numEnds) && (IsArrowCharacter(s[i]) || IsTabCharacter(s[i])) ) { if (i > 0) ends[maxEnd++] = i; ends[maxEnd++] = i+1; } } ends[maxEnd++] = len; int startSeg = 0; int xEnd; for (int seg = 0; seg<maxEnd; seg++) { int endSeg = ends[seg]; if (endSeg > startSeg) { if (IsArrowCharacter(s[startSeg])) { bool upArrow = s[startSeg] == '\001'; rcClient.left = x; rcClient.right = rcClient.left + widthArrow; if (draw) { const int halfWidth = widthArrow / 2 - 3; const int centreX = rcClient.left + widthArrow / 2 - 1; const int centreY = (rcClient.top + rcClient.bottom) / 2; surface->FillRectangle(rcClient, colourBG.allocated); PRectangle rcClientInner(rcClient.left + 1, rcClient.top + 1, rcClient.right - 2, rcClient.bottom - 1); surface->FillRectangle(rcClientInner, colourUnSel.allocated); if (upArrow) { // Up arrow Point pts[] = { Point(centreX - halfWidth, centreY + halfWidth / 2), Point(centreX + halfWidth, centreY + halfWidth / 2), Point(centreX, centreY - halfWidth + halfWidth / 2), }; surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]), colourBG.allocated, colourBG.allocated); } else { // Down arrow Point pts[] = { Point(centreX - halfWidth, centreY - halfWidth / 2), Point(centreX + halfWidth, centreY - halfWidth / 2), Point(centreX, centreY + halfWidth - halfWidth / 2), }; surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]), colourBG.allocated, colourBG.allocated); } } xEnd = rcClient.right; offsetMain = xEnd; if (upArrow) { rectUp = rcClient; } else { rectDown = rcClient; } } else if (IsTabCharacter(s[startSeg])) { xEnd = NextTabPos(x); } else { xEnd = x + surface->WidthText(font, s + startSeg, endSeg - startSeg); if (draw) { rcClient.left = x; rcClient.right = xEnd; surface->DrawTextTransparent(rcClient, font, ytext, s+startSeg, endSeg - startSeg, highlight ? colourSel.allocated : colourUnSel.allocated); } } x = xEnd; startSeg = endSeg; } } } int CallTip::PaintContents(Surface *surfaceWindow, bool draw) { PRectangle rcClientPos = wCallTip.GetClientPosition(); PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left, rcClientPos.bottom - rcClientPos.top); PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1); // To make a nice small call tip window, it is only sized to fit most normal characters without accents int ascent = surfaceWindow->Ascent(font) - surfaceWindow->InternalLeading(font); // For each line... // Draw the definition in three parts: before highlight, highlighted, after highlight int ytext = rcClient.top + ascent + 1; rcClient.bottom = ytext + surfaceWindow->Descent(font) + 1; char *chunkVal = val; bool moreChunks = true; int maxWidth = 0; while (moreChunks) { char *chunkEnd = strchr(chunkVal, '\n'); if (chunkEnd == NULL) { chunkEnd = chunkVal + strlen(chunkVal); moreChunks = false; } int chunkOffset = chunkVal - val; int chunkLength = chunkEnd - chunkVal; int chunkEndOffset = chunkOffset + chunkLength; int thisStartHighlight = Platform::Maximum(startHighlight, chunkOffset); thisStartHighlight = Platform::Minimum(thisStartHighlight, chunkEndOffset); thisStartHighlight -= chunkOffset; int thisEndHighlight = Platform::Maximum(endHighlight, chunkOffset); thisEndHighlight = Platform::Minimum(thisEndHighlight, chunkEndOffset); thisEndHighlight -= chunkOffset; rcClient.top = ytext - ascent - 1; int x = insetX; // start each line at this inset DrawChunk(surfaceWindow, x, chunkVal, 0, thisStartHighlight, ytext, rcClient, false, draw); DrawChunk(surfaceWindow, x, chunkVal, thisStartHighlight, thisEndHighlight, ytext, rcClient, true, draw); DrawChunk(surfaceWindow, x, chunkVal, thisEndHighlight, chunkLength, ytext, rcClient, false, draw); chunkVal = chunkEnd + 1; ytext += lineHeight; rcClient.bottom += lineHeight; maxWidth = Platform::Maximum(maxWidth, x); } return maxWidth; } void CallTip::PaintCT(Surface *surfaceWindow) { if (!val) return; PRectangle rcClientPos = wCallTip.GetClientPosition(); PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left, rcClientPos.bottom - rcClientPos.top); PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1); surfaceWindow->FillRectangle(rcClient, colourBG.allocated); offsetMain = insetX; // initial alignment assuming no arrows PaintContents(surfaceWindow, true); #ifndef __APPLE__ // OSX doesn't put borders on "help tags" // Draw a raised border around the edges of the window surfaceWindow->MoveTo(0, rcClientSize.bottom - 1); surfaceWindow->PenColour(colourShade.allocated); surfaceWindow->LineTo(rcClientSize.right - 1, rcClientSize.bottom - 1); surfaceWindow->LineTo(rcClientSize.right - 1, 0); surfaceWindow->PenColour(colourLight.allocated); surfaceWindow->LineTo(0, 0); surfaceWindow->LineTo(0, rcClientSize.bottom - 1); #endif } void CallTip::MouseClick(Point pt) { clickPlace = 0; if (rectUp.Contains(pt)) clickPlace = 1; if (rectDown.Contains(pt)) clickPlace = 2; } PRectangle CallTip::CallTipStart(int pos, Point pt, const char *defn, const char *faceName, int size, int codePage_, int characterSet, Window &wParent) { clickPlace = 0; if (val) delete []val; val = 0; val = new char[strlen(defn) + 1]; strcpy(val, defn); codePage = codePage_; Surface *surfaceMeasure = Surface::Allocate(); if (!surfaceMeasure) return PRectangle(); surfaceMeasure->Init(wParent.GetID()); surfaceMeasure->SetUnicodeMode(SC_CP_UTF8 == codePage); surfaceMeasure->SetDBCSMode(codePage); startHighlight = 0; endHighlight = 0; inCallTipMode = true; posStartCallTip = pos; int deviceHeight = surfaceMeasure->DeviceHeightFont(size); font.Create(faceName, characterSet, deviceHeight, false, false); // Look for multiple lines in the text // Only support \n here - simply means container must avoid \r! int numLines = 1; const char *newline; const char *look = val; rectUp = PRectangle(0,0,0,0); rectDown = PRectangle(0,0,0,0); offsetMain = insetX; // changed to right edge of any arrows int width = PaintContents(surfaceMeasure, false) + insetX; while ((newline = strchr(look, '\n')) != NULL) { look = newline + 1; numLines++; } lineHeight = surfaceMeasure->Height(font); // Extra line for border and an empty line at top and bottom. The returned // rectangle is aligned to the right edge of the last arrow encountered in // the tip text, else to the tip text left edge. int height = lineHeight * numLines - surfaceMeasure->InternalLeading(font) + 2 + 2; delete surfaceMeasure; return PRectangle(pt.x - offsetMain, pt.y + 1, pt.x + width - offsetMain, pt.y + 1 + height); } void CallTip::CallTipCancel() { inCallTipMode = false; if (wCallTip.Created()) { wCallTip.Destroy(); } } void CallTip::SetHighlight(int start, int end) { // Avoid flashing by checking something has really changed if ((start != startHighlight) || (end != endHighlight)) { startHighlight = start; endHighlight = end; if (wCallTip.Created()) { wCallTip.InvalidateAll(); } } } // Set the tab size (sizes > 0 enable the use of tabs). This also enables the // use of the STYLE_CALLTIP. void CallTip::SetTabSize(int tabSz) { tabSize = tabSz; useStyleCallTip = true; } // It might be better to have two access functions for this and to use // them for all settings of colours. void CallTip::SetForeBack(const ColourPair &fore, const ColourPair &back) { colourBG = back; colourUnSel = fore; } <commit_msg>Removed unnecessary check for NULL.<commit_after>// Scintilla source code edit control /** @file CallTip.cxx ** Code for displaying call tips. **/ // Copyright 1998-2001 by Neil Hodgson <[email protected]> // The License.txt file describes the conditions under which this software may be distributed. #include <stdlib.h> #include <string.h> #include "Platform.h" #include "Scintilla.h" #include "CallTip.h" #include <stdio.h> #ifdef SCI_NAMESPACE using namespace Scintilla; #endif static const int insetX = 5; // text inset in x from calltip border static const int widthArrow = 14; CallTip::CallTip() { wCallTip = 0; inCallTipMode = false; posStartCallTip = 0; val = 0; rectUp = PRectangle(0,0,0,0); rectDown = PRectangle(0,0,0,0); lineHeight = 1; startHighlight = 0; endHighlight = 0; tabSize = 0; useStyleCallTip = false; // for backwards compatibility #ifdef __APPLE__ // proper apple colours for the default colourBG.desired = ColourDesired(0xff, 0xff, 0xc6); colourUnSel.desired = ColourDesired(0, 0, 0); #else colourBG.desired = ColourDesired(0xff, 0xff, 0xff); colourUnSel.desired = ColourDesired(0x80, 0x80, 0x80); #endif colourSel.desired = ColourDesired(0, 0, 0x80); colourShade.desired = ColourDesired(0, 0, 0); colourLight.desired = ColourDesired(0xc0, 0xc0, 0xc0); } CallTip::~CallTip() { font.Release(); wCallTip.Destroy(); delete []val; val = 0; } void CallTip::RefreshColourPalette(Palette &pal, bool want) { pal.WantFind(colourBG, want); pal.WantFind(colourUnSel, want); pal.WantFind(colourSel, want); pal.WantFind(colourShade, want); pal.WantFind(colourLight, want); } // Although this test includes 0, we should never see a \0 character. static bool IsArrowCharacter(char ch) { return (ch == 0) || (ch == '\001') || (ch == '\002'); } // We ignore tabs unless a tab width has been set. bool CallTip::IsTabCharacter(char ch) { return (tabSize > 0) && (ch == '\t'); } int CallTip::NextTabPos(int x) { if (tabSize > 0) { // paranoia... not called unless this is true x -= insetX; // position relative to text x = (x + tabSize) / tabSize; // tab "number" return tabSize*x + insetX; // position of next tab } else { return x + 1; // arbitrary } } // Draw a section of the call tip that does not include \n in one colour. // The text may include up to numEnds tabs or arrow characters. void CallTip::DrawChunk(Surface *surface, int &x, const char *s, int posStart, int posEnd, int ytext, PRectangle rcClient, bool highlight, bool draw) { s += posStart; int len = posEnd - posStart; // Divide the text into sections that are all text, or that are // single arrows or single tab characters (if tabSize > 0). int maxEnd = 0; const int numEnds = 10; int ends[numEnds + 2]; for (int i=0;i<len;i++) { if ((maxEnd < numEnds) && (IsArrowCharacter(s[i]) || IsTabCharacter(s[i])) ) { if (i > 0) ends[maxEnd++] = i; ends[maxEnd++] = i+1; } } ends[maxEnd++] = len; int startSeg = 0; int xEnd; for (int seg = 0; seg<maxEnd; seg++) { int endSeg = ends[seg]; if (endSeg > startSeg) { if (IsArrowCharacter(s[startSeg])) { bool upArrow = s[startSeg] == '\001'; rcClient.left = x; rcClient.right = rcClient.left + widthArrow; if (draw) { const int halfWidth = widthArrow / 2 - 3; const int centreX = rcClient.left + widthArrow / 2 - 1; const int centreY = (rcClient.top + rcClient.bottom) / 2; surface->FillRectangle(rcClient, colourBG.allocated); PRectangle rcClientInner(rcClient.left + 1, rcClient.top + 1, rcClient.right - 2, rcClient.bottom - 1); surface->FillRectangle(rcClientInner, colourUnSel.allocated); if (upArrow) { // Up arrow Point pts[] = { Point(centreX - halfWidth, centreY + halfWidth / 2), Point(centreX + halfWidth, centreY + halfWidth / 2), Point(centreX, centreY - halfWidth + halfWidth / 2), }; surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]), colourBG.allocated, colourBG.allocated); } else { // Down arrow Point pts[] = { Point(centreX - halfWidth, centreY - halfWidth / 2), Point(centreX + halfWidth, centreY - halfWidth / 2), Point(centreX, centreY + halfWidth - halfWidth / 2), }; surface->Polygon(pts, sizeof(pts) / sizeof(pts[0]), colourBG.allocated, colourBG.allocated); } } xEnd = rcClient.right; offsetMain = xEnd; if (upArrow) { rectUp = rcClient; } else { rectDown = rcClient; } } else if (IsTabCharacter(s[startSeg])) { xEnd = NextTabPos(x); } else { xEnd = x + surface->WidthText(font, s + startSeg, endSeg - startSeg); if (draw) { rcClient.left = x; rcClient.right = xEnd; surface->DrawTextTransparent(rcClient, font, ytext, s+startSeg, endSeg - startSeg, highlight ? colourSel.allocated : colourUnSel.allocated); } } x = xEnd; startSeg = endSeg; } } } int CallTip::PaintContents(Surface *surfaceWindow, bool draw) { PRectangle rcClientPos = wCallTip.GetClientPosition(); PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left, rcClientPos.bottom - rcClientPos.top); PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1); // To make a nice small call tip window, it is only sized to fit most normal characters without accents int ascent = surfaceWindow->Ascent(font) - surfaceWindow->InternalLeading(font); // For each line... // Draw the definition in three parts: before highlight, highlighted, after highlight int ytext = rcClient.top + ascent + 1; rcClient.bottom = ytext + surfaceWindow->Descent(font) + 1; char *chunkVal = val; bool moreChunks = true; int maxWidth = 0; while (moreChunks) { char *chunkEnd = strchr(chunkVal, '\n'); if (chunkEnd == NULL) { chunkEnd = chunkVal + strlen(chunkVal); moreChunks = false; } int chunkOffset = chunkVal - val; int chunkLength = chunkEnd - chunkVal; int chunkEndOffset = chunkOffset + chunkLength; int thisStartHighlight = Platform::Maximum(startHighlight, chunkOffset); thisStartHighlight = Platform::Minimum(thisStartHighlight, chunkEndOffset); thisStartHighlight -= chunkOffset; int thisEndHighlight = Platform::Maximum(endHighlight, chunkOffset); thisEndHighlight = Platform::Minimum(thisEndHighlight, chunkEndOffset); thisEndHighlight -= chunkOffset; rcClient.top = ytext - ascent - 1; int x = insetX; // start each line at this inset DrawChunk(surfaceWindow, x, chunkVal, 0, thisStartHighlight, ytext, rcClient, false, draw); DrawChunk(surfaceWindow, x, chunkVal, thisStartHighlight, thisEndHighlight, ytext, rcClient, true, draw); DrawChunk(surfaceWindow, x, chunkVal, thisEndHighlight, chunkLength, ytext, rcClient, false, draw); chunkVal = chunkEnd + 1; ytext += lineHeight; rcClient.bottom += lineHeight; maxWidth = Platform::Maximum(maxWidth, x); } return maxWidth; } void CallTip::PaintCT(Surface *surfaceWindow) { if (!val) return; PRectangle rcClientPos = wCallTip.GetClientPosition(); PRectangle rcClientSize(0, 0, rcClientPos.right - rcClientPos.left, rcClientPos.bottom - rcClientPos.top); PRectangle rcClient(1, 1, rcClientSize.right - 1, rcClientSize.bottom - 1); surfaceWindow->FillRectangle(rcClient, colourBG.allocated); offsetMain = insetX; // initial alignment assuming no arrows PaintContents(surfaceWindow, true); #ifndef __APPLE__ // OSX doesn't put borders on "help tags" // Draw a raised border around the edges of the window surfaceWindow->MoveTo(0, rcClientSize.bottom - 1); surfaceWindow->PenColour(colourShade.allocated); surfaceWindow->LineTo(rcClientSize.right - 1, rcClientSize.bottom - 1); surfaceWindow->LineTo(rcClientSize.right - 1, 0); surfaceWindow->PenColour(colourLight.allocated); surfaceWindow->LineTo(0, 0); surfaceWindow->LineTo(0, rcClientSize.bottom - 1); #endif } void CallTip::MouseClick(Point pt) { clickPlace = 0; if (rectUp.Contains(pt)) clickPlace = 1; if (rectDown.Contains(pt)) clickPlace = 2; } PRectangle CallTip::CallTipStart(int pos, Point pt, const char *defn, const char *faceName, int size, int codePage_, int characterSet, Window &wParent) { clickPlace = 0; delete []val; val = 0; val = new char[strlen(defn) + 1]; strcpy(val, defn); codePage = codePage_; Surface *surfaceMeasure = Surface::Allocate(); if (!surfaceMeasure) return PRectangle(); surfaceMeasure->Init(wParent.GetID()); surfaceMeasure->SetUnicodeMode(SC_CP_UTF8 == codePage); surfaceMeasure->SetDBCSMode(codePage); startHighlight = 0; endHighlight = 0; inCallTipMode = true; posStartCallTip = pos; int deviceHeight = surfaceMeasure->DeviceHeightFont(size); font.Create(faceName, characterSet, deviceHeight, false, false); // Look for multiple lines in the text // Only support \n here - simply means container must avoid \r! int numLines = 1; const char *newline; const char *look = val; rectUp = PRectangle(0,0,0,0); rectDown = PRectangle(0,0,0,0); offsetMain = insetX; // changed to right edge of any arrows int width = PaintContents(surfaceMeasure, false) + insetX; while ((newline = strchr(look, '\n')) != NULL) { look = newline + 1; numLines++; } lineHeight = surfaceMeasure->Height(font); // Extra line for border and an empty line at top and bottom. The returned // rectangle is aligned to the right edge of the last arrow encountered in // the tip text, else to the tip text left edge. int height = lineHeight * numLines - surfaceMeasure->InternalLeading(font) + 2 + 2; delete surfaceMeasure; return PRectangle(pt.x - offsetMain, pt.y + 1, pt.x + width - offsetMain, pt.y + 1 + height); } void CallTip::CallTipCancel() { inCallTipMode = false; if (wCallTip.Created()) { wCallTip.Destroy(); } } void CallTip::SetHighlight(int start, int end) { // Avoid flashing by checking something has really changed if ((start != startHighlight) || (end != endHighlight)) { startHighlight = start; endHighlight = end; if (wCallTip.Created()) { wCallTip.InvalidateAll(); } } } // Set the tab size (sizes > 0 enable the use of tabs). This also enables the // use of the STYLE_CALLTIP. void CallTip::SetTabSize(int tabSz) { tabSize = tabSz; useStyleCallTip = true; } // It might be better to have two access functions for this and to use // them for all settings of colours. void CallTip::SetForeBack(const ColourPair &fore, const ColourPair &back) { colourBG = back; colourUnSel = fore; } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "Interval.h" #include "WTF/CurrentTime.h" namespace WebCore { const char* kIntervalExtensionName = "v8/Interval"; class IntervalExtensionWrapper : public v8::Extension { public: IntervalExtensionWrapper() : v8::Extension(kIntervalExtensionName, "native function HiResTime();" "function Interval() {" " var start_ = 0;" " var stop_ = 0;" " this.start = function() {" " start_ = HiResTime();" " };" " this.stop = function() {" " stop_ = HiResTime();" " if (start_ == 0)" " stop_ = 0;" " };" " this.microseconds = function() {" " if (stop_ == 0)" " stop();" " return Math.ceil((stop_ - start_) * 1000000);" " };" "}") {}; virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction(v8::Handle<v8::String> name) { if (name->Equals(v8::String::New("HiResTime"))) return v8::FunctionTemplate::New(HiResTime); return v8::Handle<v8::FunctionTemplate>(); } static v8::Handle<v8::Value> HiResTime(const v8::Arguments& args) { return v8::Number::New(WTF::currentTime()); } }; v8::Extension* IntervalExtension::Get() { return new IntervalExtensionWrapper(); } } <commit_msg>Case sensitive directory names on linux<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "Interval.h" #include "wtf/CurrentTime.h" namespace WebCore { const char* kIntervalExtensionName = "v8/Interval"; class IntervalExtensionWrapper : public v8::Extension { public: IntervalExtensionWrapper() : v8::Extension(kIntervalExtensionName, "native function HiResTime();" "function Interval() {" " var start_ = 0;" " var stop_ = 0;" " this.start = function() {" " start_ = HiResTime();" " };" " this.stop = function() {" " stop_ = HiResTime();" " if (start_ == 0)" " stop_ = 0;" " };" " this.microseconds = function() {" " if (stop_ == 0)" " stop();" " return Math.ceil((stop_ - start_) * 1000000);" " };" "}") {}; virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction(v8::Handle<v8::String> name) { if (name->Equals(v8::String::New("HiResTime"))) return v8::FunctionTemplate::New(HiResTime); return v8::Handle<v8::FunctionTemplate>(); } static v8::Handle<v8::Value> HiResTime(const v8::Arguments& args) { return v8::Number::New(WTF::currentTime()); } }; v8::Extension* IntervalExtension::Get() { return new IntervalExtensionWrapper(); } } <|endoftext|>
<commit_before>#include <b9.hpp> #include <b9/loader.hpp> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> /// B9run's usage string. Printed when run with -help. static const char* usage = "Usage: b9run [<option>...] [--] <module> [<main>]\n" " Or: b9run -help\n" "Options:\n" " -callstyle <style>: Set the calling style. One of:\n" " interpreter: Calls are made through the interpreter\n" " direct: Calls are made directly, but parameters are on the " "operand stack\n" " passparameter: Direct calls, with parameters passed in CPU " "registers\n" " operandstack: Like passparam, but will keep the VM operand stack " "updated\n" " -loop <n>: Run the program <n> times\n" " -inline <n>: Enable inlining\n" " -debug: Enable debug code\n" " -verbose: Run with verbose printing\n" " -help: Print this help message"; /// The b9run program's global configuration. struct RunConfig { b9::VirtualMachineConfig vm; const char* moduleName = ""; const char* mainFunction = "b9main"; std::size_t loopCount = 1; bool verbose = false; }; /// Print the configuration summary. std::ostream& operator<<(std::ostream& out, const RunConfig& cfg) { return out << "Loading: " << cfg.moduleName << std::endl << "Executing: " << cfg.mainFunction << std::endl << "Call Style: " << cfg.vm.jitConfig.callStyle << std::endl << "Looping: " << cfg.loopCount << " times" << std::endl << "Inline depth: " << cfg.vm.jitConfig.maxInlineDepth; } /// Parse CLI arguments and set up the config. static bool parseArguments(RunConfig& cfg, const int argc, char* argv[]) { std::size_t i = 1; for (; i < argc; i++) { const char* arg = argv[i]; if (strcmp(arg, "-help") == 0) { std::cout << usage << std::endl; exit(EXIT_SUCCESS); } else if (strcmp(arg, "-loop") == 0) { cfg.loopCount = atoi(argv[++i]); } else if (strcmp(arg, "-inline") == 0) { cfg.vm.jitConfig.maxInlineDepth = atoi(argv[++i]); } else if (strcmp(arg, "-verbose") == 0) { cfg.verbose = true; cfg.vm.verbose = true; cfg.vm.jitConfig.verbose = true; } else if (strcmp(arg, "-debug") == 0) { cfg.vm.debug = true; cfg.vm.jitConfig.debug = true; } else if (strcmp(arg, "-callstyle") == 0) { i += 1; auto callStyle = argv[i]; if (strcmp("interpreter", callStyle) == 0) { cfg.vm.jitConfig.callStyle = b9::CallStyle::interpreter; } else if (strcmp("direct", callStyle) == 0) { cfg.vm.jitConfig.callStyle = b9::CallStyle::direct; } else if (strcmp("passparameter", callStyle) == 0) { cfg.vm.jitConfig.callStyle = b9::CallStyle::passParameter; } else if (strcmp("operandstack", callStyle) == 0) { cfg.vm.jitConfig.callStyle = b9::CallStyle::operandStack; } } else if (strcmp(arg, "--") == 0) { i++; break; } else if (strcmp(arg, "-") == 0) { std::cerr << "Unrecognized option: " << arg << std::endl; return false; } else { break; } } // positional if (i < argc) { cfg.moduleName = argv[i++]; } else { std::cerr << "No module name given to b9run" << std::endl; return false; } return true; } static void run(const RunConfig& cfg) { b9::VirtualMachine vm{cfg.vm}; vm.initialize(); b9::DlLoader loader{true}; auto module = loader.loadModule(cfg.moduleName); if (module->functions.size() == 0) { throw b9::DlException{"Empty module"}; } vm.load(module); size_t functionIndex = module->findFunction(cfg.mainFunction); if (cfg.loopCount == 1) { b9::StackElement returnVal = vm.run(functionIndex); std::cout << cfg.mainFunction << " returned: " << returnVal << std::endl; } else { b9::StackElement returnVal; std::cout << "Running " << cfg.mainFunction << " " << cfg.loopCount << " times:" << std::endl; for (std::size_t i = 1; i <= cfg.loopCount; i++) { returnVal = vm.run(functionIndex); std::cout << "Return value of iteration " << i << ": " << returnVal << std::endl; } } } int main(int argc, char* argv[]) { RunConfig cfg; if (!parseArguments(cfg, argc, argv)) { std::cerr << usage << std::endl; exit(EXIT_FAILURE); } try { run(cfg); } catch (const b9::DlException& e) { std::cerr << "Failed to load module: " << e.what() << std::endl; exit(EXIT_FAILURE); } catch (const b9::FunctionNotFoundException& e) { std::cerr << "Failed to find function: " << e.what() << std::endl; exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); } <commit_msg>Add -function option / parse user specified arguments<commit_after>#include <b9.hpp> #include <b9/loader.hpp> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> /// B9run's usage string. Printed when run with -help. static const char* usage = "Usage: b9run [<option>...] [--] <module> [<main>]\n" " Or: b9run -help\n" "Options:\n" " -callstyle <style>: Set the calling style. One of:\n" " interpreter: Calls are made through the interpreter\n" " direct: Calls are made directly, but parameters are on the " "operand stack\n" " passparameter: Direct calls, with parameters passed in CPU " "registers\n" " operandstack: Like passparam, but will keep the VM operand stack " "updated\n" " -loop <n>: Run the program <n> times\n" " -inline <n>: Enable inlining\n" " -debug: Enable debug code\n" " -verbose: Run with verbose printing\n" " -help: Print this help message"; /// The b9run program's global configuration. struct RunConfig { b9::VirtualMachineConfig vm; const char* moduleName = ""; const char* mainFunction = "b9main"; std::size_t loopCount = 1; bool verbose = false; std::vector<int> usrArgs; }; /// Print the configuration summary. std::ostream& operator<<(std::ostream& out, const RunConfig& cfg) { return out << "Loading: " << cfg.moduleName << std::endl << "Executing: " << cfg.mainFunction << std::endl << "Call Style: " << cfg.vm.jitConfig.callStyle << std::endl << "Looping: " << cfg.loopCount << " times" << std::endl << "Inline depth: " << cfg.vm.jitConfig.maxInlineDepth; } /// Parse CLI arguments and set up the config. static bool parseArguments(RunConfig& cfg, const int argc, char* argv[]) { std::size_t i = 1; for (; i < argc; i++) { const char* arg = argv[i]; if (strcmp(arg, "-help") == 0) { std::cout << usage << std::endl; exit(EXIT_SUCCESS); } else if (strcmp(arg, "-loop") == 0) { cfg.loopCount = atoi(argv[++i]); } else if (strcmp(arg, "-inline") == 0) { cfg.vm.jitConfig.maxInlineDepth = atoi(argv[++i]); } else if (strcmp(arg, "-verbose") == 0) { cfg.verbose = true; cfg.vm.verbose = true; cfg.vm.jitConfig.verbose = true; } else if (strcmp(arg, "-debug") == 0) { cfg.vm.debug = true; cfg.vm.jitConfig.debug = true; } else if (strcmp(arg, "-callstyle") == 0) { i += 1; auto callStyle = argv[i]; if (strcmp("interpreter", callStyle) == 0) { cfg.vm.jitConfig.callStyle = b9::CallStyle::interpreter; } else if (strcmp("direct", callStyle) == 0) { cfg.vm.jitConfig.callStyle = b9::CallStyle::direct; } else if (strcmp("passparameter", callStyle) == 0) { cfg.vm.jitConfig.callStyle = b9::CallStyle::passParameter; } else if (strcmp("operandstack", callStyle) == 0) { cfg.vm.jitConfig.callStyle = b9::CallStyle::operandStack; } } else if (strcmp(arg, "-function") == 0) { cfg.mainFunction=argv[++i]; } else if (strcmp(arg, "--") == 0) { i++; break; } else if (strcmp(arg, "-") == 0) { std::cerr << "Unrecognized option: " << arg << std::endl; return false; } else { break; } } // check for user defined module if (i < argc) { cfg.moduleName = argv[i++]; } else { std::cerr << "No module name given to b9run" << std::endl; return false; } // check for user defined arguments for (; i < argc; i++) { cfg.usrArgs.push_back(std::atoi(argv[i])); } return true; } static void run(const RunConfig& cfg) { b9::VirtualMachine vm{cfg.vm}; vm.initialize(); b9::DlLoader loader{true}; auto module = loader.loadModule(cfg.moduleName); if (module->functions.size() == 0) { throw b9::DlException{"Empty module"}; } vm.load(module); size_t functionIndex = module->findFunction(cfg.mainFunction); if (cfg.loopCount == 1) { b9::StackElement returnVal = vm.run(functionIndex); std::cout << cfg.mainFunction << " returned: " << returnVal << std::endl; } else { b9::StackElement returnVal; std::cout << "Running " << cfg.mainFunction << " " << cfg.loopCount << " times:" << std::endl; for (std::size_t i = 1; i <= cfg.loopCount; i++) { returnVal = vm.run(functionIndex); std::cout << "Return value of iteration " << i << ": " << returnVal << std::endl; } } } int main(int argc, char* argv[]) { RunConfig cfg; if (!parseArguments(cfg, argc, argv)) { std::cerr << usage << std::endl; exit(EXIT_FAILURE); } try { run(cfg); } catch (const b9::DlException& e) { std::cerr << "Failed to load module: " << e.what() << std::endl; exit(EXIT_FAILURE); } catch (const b9::FunctionNotFoundException& e) { std::cerr << "Failed to find function: " << e.what() << std::endl; exit(EXIT_FAILURE); } exit(EXIT_SUCCESS); } <|endoftext|>
<commit_before>// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __STOUT_FLAGS_PARSE_HPP__ #define __STOUT_FLAGS_PARSE_HPP__ #include <sstream> // For istringstream. #include <string> #include <stout/bytes.hpp> #include <stout/duration.hpp> #include <stout/error.hpp> #include <stout/json.hpp> #include <stout/strings.hpp> #include <stout/try.hpp> #include <stout/os/read.hpp> namespace flags { template <typename T> Try<T> parse(const std::string& value) { T t; std::istringstream in(value); in >> t; if (!in.good() && !in.eof()) { return Error("Failed to convert into required type"); } return t; } template <> inline Try<std::string> parse(const std::string& value) { return value; } template <> inline Try<bool> parse(const std::string& value) { if (value == "true" || value == "1") { return true; } else if (value == "false" || value == "0") { return false; } return Error("Expecting a boolean (e.g., true or false)"); } template <> inline Try<Duration> parse(const std::string& value) { return Duration::parse(value); } template <> inline Try<Bytes> parse(const std::string& value) { return Bytes::parse(value); } template <> inline Try<JSON::Object> parse(const std::string& value) { // A value that already starts with 'file://' will properly be // loaded from the file and put into 'value' but if it starts with // '/' we need to explicitly handle it for backwards compatibility // reasons (because we used to handle it before we introduced the // 'fetch' mechanism for flags that first fetches the data from URIs // such as 'file://'). if (strings::startsWith(value, "/")) { LOG(WARNING) << "Specifying an absolute filename to read a command line " "option out of without using 'file:// is deprecated and " "will be removed in a future release. Simply adding " "'file://' to the beginning of the path should eliminate " "this warning."; Try<std::string> read = os::read(value); if (read.isError()) { return Error("Error reading file '" + value + "': " + read.error()); } return JSON::parse<JSON::Object>(read.get()); } return JSON::parse<JSON::Object>(value); } template <> inline Try<Path> parse(const std::string& value) { return Path(value); } } // namespace flags { #endif // __STOUT_FLAGS_PARSE_HPP__ <commit_msg>Added a missing include to a stout header.<commit_after>// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __STOUT_FLAGS_PARSE_HPP__ #define __STOUT_FLAGS_PARSE_HPP__ #include <sstream> // For istringstream. #include <string> #include <stout/bytes.hpp> #include <stout/duration.hpp> #include <stout/error.hpp> #include <stout/json.hpp> #include <stout/path.hpp> #include <stout/strings.hpp> #include <stout/try.hpp> #include <stout/os/read.hpp> namespace flags { template <typename T> Try<T> parse(const std::string& value) { T t; std::istringstream in(value); in >> t; if (!in.good() && !in.eof()) { return Error("Failed to convert into required type"); } return t; } template <> inline Try<std::string> parse(const std::string& value) { return value; } template <> inline Try<bool> parse(const std::string& value) { if (value == "true" || value == "1") { return true; } else if (value == "false" || value == "0") { return false; } return Error("Expecting a boolean (e.g., true or false)"); } template <> inline Try<Duration> parse(const std::string& value) { return Duration::parse(value); } template <> inline Try<Bytes> parse(const std::string& value) { return Bytes::parse(value); } template <> inline Try<JSON::Object> parse(const std::string& value) { // A value that already starts with 'file://' will properly be // loaded from the file and put into 'value' but if it starts with // '/' we need to explicitly handle it for backwards compatibility // reasons (because we used to handle it before we introduced the // 'fetch' mechanism for flags that first fetches the data from URIs // such as 'file://'). if (strings::startsWith(value, "/")) { LOG(WARNING) << "Specifying an absolute filename to read a command line " "option out of without using 'file:// is deprecated and " "will be removed in a future release. Simply adding " "'file://' to the beginning of the path should eliminate " "this warning."; Try<std::string> read = os::read(value); if (read.isError()) { return Error("Error reading file '" + value + "': " + read.error()); } return JSON::parse<JSON::Object>(read.get()); } return JSON::parse<JSON::Object>(value); } template <> inline Try<Path> parse(const std::string& value) { return Path(value); } } // namespace flags { #endif // __STOUT_FLAGS_PARSE_HPP__ <|endoftext|>
<commit_before>#include "astutil.h" #include "expr.h" #include "passes.h" #include "stmt.h" #include "symbol.h" #include "type.h" #include "symscope.h" #include "stringutil.h" static void check_redefinition(Symbol* sym) { if (sym->isCompilerTemp) return; if (sym->parentScope == rootScope) return; if (sym->overloadNext) { int count = 0; for (Symbol* tmp = sym; tmp; tmp = tmp->overloadNext) { if (!tmp->getFnSymbol()) { count++; } } if (count >= 2) { char* redefinitionLocations = ""; for (Symbol* tmp = sym->overloadNext; tmp; tmp = tmp->overloadNext) { if (!tmp->getFnSymbol()) { redefinitionLocations = stringcat(redefinitionLocations, "\n ", tmp->stringLoc()); } } USR_FATAL(sym, "'%s' has multiple definitions, redefined at:%s", sym->name, redefinitionLocations); } } } static void check_functions(FnSymbol* fn) { Vec<BaseAST*> asts; Vec<CallExpr*> rets; collect_asts(&asts, fn); forv_Vec(BaseAST, ast, asts) { if (CallExpr* ret = dynamic_cast<CallExpr*>(ast)) if (ret->isPrimitive(PRIMITIVE_RETURN) && ret->parentSymbol == fn) rets.add(ret); } if (rets.n == 0) return; bool returns_void = false; forv_Vec(CallExpr, ret, rets) { if (SymExpr* sym = dynamic_cast<SymExpr*>(ret->get(1))) if (sym->var == gVoid) returns_void = true; } forv_Vec(CallExpr, ret, rets) { if (returns_void && ret->typeInfo() != dtVoid) if (fn->getModule()->initFn == fn) USR_FATAL(ret, "return statement is not in a function"); else USR_FATAL(fn, "Not all function returns return a value"); } } static void check_parsed_vars(VarSymbol* var) { if (var->isParam() && !var->immediate) if (!var->defPoint->init && (dynamic_cast<FnSymbol*>(var->defPoint->parentSymbol) || dynamic_cast<ModuleSymbol*>(var->defPoint->parentSymbol)) && !dynamic_cast<FnSymbol*>(var->defPoint->parentScope->astParent)) USR_FATAL(var, "Top-level params must be initialized."); if (var->varClass == VAR_CONFIG && var->defPoint->parentSymbol != var->getModule()->initFn) { char *varType = NULL; switch (var->consClass) { case VAR_VAR: varType = "variables"; break; case VAR_CONST: varType = "constants"; break; case VAR_PARAM: varType = "parameters"; break; default: INT_FATAL("Illegal constant class."); } USR_FATAL_CONT(var->defPoint, "Configuration %s only allowed at module scope.", varType); } } static void check_named_arguments(CallExpr* call) { Vec<char*> names; for_actuals(expr, call) { if (NamedExpr* named = dynamic_cast<NamedExpr*>(expr)) { forv_Vec(char, name, names) { if (!strcmp(name, named->name)) USR_FATAL(named, "The named argument '%s' is used more " "than once in the same function call.", name); } names.add(named->name); } } } void checkParsed(void) { Vec<BaseAST*> asts; collect_asts(&asts); forv_Vec(BaseAST, ast, asts) { if (CallExpr* call = dynamic_cast<CallExpr*>(ast)) check_named_arguments(call); if (DefExpr* def = dynamic_cast<DefExpr*>(ast)) { if (!strcmp(def->sym->name, "_")) { USR_FATAL("Symbol cannot be named \"_\""); } else if (dynamic_cast<VarSymbol*>(def->sym)) { if (def->sym->hasPragma("internal var")) def->sym->isCompilerTemp = true; if (!def->init && !def->exprType && !def->sym->isCompilerTemp) if (dynamic_cast<BlockStmt*>(def->parentExpr)) USR_FATAL_CONT(def->sym, "Variable '%s' is not initialized or has no type", def->sym->name); } } if (Symbol* sym = dynamic_cast<Symbol*>(ast)) check_redefinition(sym); if (VarSymbol* a = dynamic_cast<VarSymbol*>(ast)) check_parsed_vars(a); else if (FnSymbol* fn = dynamic_cast<FnSymbol*>(ast)) check_functions(fn); } } void checkNormalized(void) { forv_Vec(FnSymbol, fn, gFns) { if (fn->fnClass == FN_ITERATOR) { for_formals(formal, fn) { if (formal->intent == INTENT_IN || formal->intent == INTENT_INOUT || formal->intent == INTENT_OUT || formal->intent == INTENT_REF) { USR_FATAL(formal, "formal argument of iterator cannot have intent"); } } } // do not check body of nested function (would be again) if (fn->defPoint->parentSymbol->astType == SYMBOL_FN) continue; ModuleSymbol* mod = fn->getModule(); Vec<char*> reported; Vec<BaseAST*> asts; Vec<Symbol*> defined; collect_asts_postorder(&asts, fn); forv_Vec(BaseAST, ast, asts) { if (CallExpr* call = dynamic_cast<CallExpr*>(ast)) { if (SymExpr* base = dynamic_cast<SymExpr*>(call->baseExpr)) if (dynamic_cast<ModuleSymbol*>(base->var)) USR_FATAL_CONT(call, "illegal use of module '%s'", base->var->name); if (call->isPrimitive(PRIMITIVE_MOVE)) defined.set_add(dynamic_cast<SymExpr*>(call->get(1))->var); } else if (SymExpr* sym = dynamic_cast<SymExpr*>(ast)) { if (CallExpr* call = dynamic_cast<CallExpr*>(sym->parentExpr)) if (call->isPrimitive(PRIMITIVE_MOVE) && call->get(1) == sym) continue; if (dynamic_cast<VarSymbol*>(sym->var)) if (sym->var->defPoint && (sym->var->defPoint->parentSymbol == fn || (sym->var->defPoint->parentSymbol == mod && mod->initFn == fn))) if (!defined.set_in(sym->var)) if (sym->var != fn->_this) USR_FATAL(sym, "'%s' used before defined", sym->var->name); CallExpr* parent = dynamic_cast<CallExpr*>(sym->parentExpr); if (!(parent && parent->baseExpr == sym)) if (dynamic_cast<UnresolvedSymbol*>(sym->var)) { if (!reported.set_in(sym->var->name)) { USR_FATAL_CONT(sym, "'%s' undeclared (first use this function)", sym->var->name); reported.set_add(sym->var->name); } } } } } } static void check_resolved_syms(Symbol* var) { if (!var->isConst() && !var->isParam()) return; if (VarSymbol* vs = dynamic_cast<VarSymbol*>(var)) if (vs->immediate) return; if (var->defs.n > 1) USR_FATAL_CONT(var->defs.v[var->defs.n-1], "Assigning to a constant expression"); // need something like below to check constant assignment via refs forv_Vec(SymExpr, use, var->uses) { if (CallExpr* call = dynamic_cast<CallExpr*>(use->parentExpr)) if (call->isPrimitive(PRIMITIVE_SET_REF)) if (CallExpr* move = dynamic_cast<CallExpr*>(call->parentExpr)) if (move->isPrimitive(PRIMITIVE_MOVE)) if (SymExpr* lhs = dynamic_cast<SymExpr*>(move->get(1))) if (lhs->var->defs.n > 1) USR_FATAL_CONT(lhs->var->defs.v[lhs->var->defs.n-1], "Assigning to a constant expression"); } } void checkResolved(void) { compute_sym_uses(); Vec<BaseAST*> asts; collect_asts(&asts); forv_Vec(BaseAST, ast, asts) { if (dynamic_cast<VarSymbol*>(ast) || dynamic_cast<ArgSymbol*>(ast)) check_resolved_syms(dynamic_cast<Symbol*>(ast)); } forv_Vec(TypeSymbol, type, gTypes) { if (EnumType* et = dynamic_cast<EnumType*>(type->type)) { for_alist(DefExpr, def, et->constants) { if (def->init) { SymExpr* sym = dynamic_cast<SymExpr*>(def->init); if (!sym || (dynamic_cast<VarSymbol*>(sym->var)->consClass != VAR_PARAM && !dynamic_cast<VarSymbol*>(sym->var)->immediate)) USR_FATAL(def, "enumerator '%s' is not an int parameter", def->sym->name); } } } } } <commit_msg>Fixed braces around USR_FATAL in conditional.<commit_after>#include "astutil.h" #include "expr.h" #include "passes.h" #include "stmt.h" #include "symbol.h" #include "type.h" #include "symscope.h" #include "stringutil.h" static void check_redefinition(Symbol* sym) { if (sym->isCompilerTemp) return; if (sym->parentScope == rootScope) return; if (sym->overloadNext) { int count = 0; for (Symbol* tmp = sym; tmp; tmp = tmp->overloadNext) { if (!tmp->getFnSymbol()) { count++; } } if (count >= 2) { char* redefinitionLocations = ""; for (Symbol* tmp = sym->overloadNext; tmp; tmp = tmp->overloadNext) { if (!tmp->getFnSymbol()) { redefinitionLocations = stringcat(redefinitionLocations, "\n ", tmp->stringLoc()); } } USR_FATAL(sym, "'%s' has multiple definitions, redefined at:%s", sym->name, redefinitionLocations); } } } static void check_functions(FnSymbol* fn) { Vec<BaseAST*> asts; Vec<CallExpr*> rets; collect_asts(&asts, fn); forv_Vec(BaseAST, ast, asts) { if (CallExpr* ret = dynamic_cast<CallExpr*>(ast)) if (ret->isPrimitive(PRIMITIVE_RETURN) && ret->parentSymbol == fn) rets.add(ret); } if (rets.n == 0) return; bool returns_void = false; forv_Vec(CallExpr, ret, rets) { if (SymExpr* sym = dynamic_cast<SymExpr*>(ret->get(1))) if (sym->var == gVoid) returns_void = true; } forv_Vec(CallExpr, ret, rets) { if (returns_void && ret->typeInfo() != dtVoid) { if (fn->getModule()->initFn == fn) { USR_FATAL(ret, "return statement is not in a function"); } else { USR_FATAL(fn, "Not all function returns return a value"); } } } } static void check_parsed_vars(VarSymbol* var) { if (var->isParam() && !var->immediate) if (!var->defPoint->init && (dynamic_cast<FnSymbol*>(var->defPoint->parentSymbol) || dynamic_cast<ModuleSymbol*>(var->defPoint->parentSymbol)) && !dynamic_cast<FnSymbol*>(var->defPoint->parentScope->astParent)) USR_FATAL(var, "Top-level params must be initialized."); if (var->varClass == VAR_CONFIG && var->defPoint->parentSymbol != var->getModule()->initFn) { char *varType = NULL; switch (var->consClass) { case VAR_VAR: varType = "variables"; break; case VAR_CONST: varType = "constants"; break; case VAR_PARAM: varType = "parameters"; break; default: INT_FATAL("Illegal constant class."); } USR_FATAL_CONT(var->defPoint, "Configuration %s only allowed at module scope.", varType); } } static void check_named_arguments(CallExpr* call) { Vec<char*> names; for_actuals(expr, call) { if (NamedExpr* named = dynamic_cast<NamedExpr*>(expr)) { forv_Vec(char, name, names) { if (!strcmp(name, named->name)) USR_FATAL(named, "The named argument '%s' is used more " "than once in the same function call.", name); } names.add(named->name); } } } void checkParsed(void) { Vec<BaseAST*> asts; collect_asts(&asts); forv_Vec(BaseAST, ast, asts) { if (CallExpr* call = dynamic_cast<CallExpr*>(ast)) check_named_arguments(call); if (DefExpr* def = dynamic_cast<DefExpr*>(ast)) { if (!strcmp(def->sym->name, "_")) { USR_FATAL("Symbol cannot be named \"_\""); } else if (dynamic_cast<VarSymbol*>(def->sym)) { if (def->sym->hasPragma("internal var")) def->sym->isCompilerTemp = true; if (!def->init && !def->exprType && !def->sym->isCompilerTemp) if (dynamic_cast<BlockStmt*>(def->parentExpr)) USR_FATAL_CONT(def->sym, "Variable '%s' is not initialized or has no type", def->sym->name); } } if (Symbol* sym = dynamic_cast<Symbol*>(ast)) check_redefinition(sym); if (VarSymbol* a = dynamic_cast<VarSymbol*>(ast)) check_parsed_vars(a); else if (FnSymbol* fn = dynamic_cast<FnSymbol*>(ast)) check_functions(fn); } } void checkNormalized(void) { forv_Vec(FnSymbol, fn, gFns) { if (fn->fnClass == FN_ITERATOR) { for_formals(formal, fn) { if (formal->intent == INTENT_IN || formal->intent == INTENT_INOUT || formal->intent == INTENT_OUT || formal->intent == INTENT_REF) { USR_FATAL(formal, "formal argument of iterator cannot have intent"); } } } // do not check body of nested function (would be again) if (fn->defPoint->parentSymbol->astType == SYMBOL_FN) continue; ModuleSymbol* mod = fn->getModule(); Vec<char*> reported; Vec<BaseAST*> asts; Vec<Symbol*> defined; collect_asts_postorder(&asts, fn); forv_Vec(BaseAST, ast, asts) { if (CallExpr* call = dynamic_cast<CallExpr*>(ast)) { if (SymExpr* base = dynamic_cast<SymExpr*>(call->baseExpr)) if (dynamic_cast<ModuleSymbol*>(base->var)) USR_FATAL_CONT(call, "illegal use of module '%s'", base->var->name); if (call->isPrimitive(PRIMITIVE_MOVE)) defined.set_add(dynamic_cast<SymExpr*>(call->get(1))->var); } else if (SymExpr* sym = dynamic_cast<SymExpr*>(ast)) { if (CallExpr* call = dynamic_cast<CallExpr*>(sym->parentExpr)) if (call->isPrimitive(PRIMITIVE_MOVE) && call->get(1) == sym) continue; if (dynamic_cast<VarSymbol*>(sym->var)) if (sym->var->defPoint && (sym->var->defPoint->parentSymbol == fn || (sym->var->defPoint->parentSymbol == mod && mod->initFn == fn))) if (!defined.set_in(sym->var)) if (sym->var != fn->_this) USR_FATAL(sym, "'%s' used before defined", sym->var->name); CallExpr* parent = dynamic_cast<CallExpr*>(sym->parentExpr); if (!(parent && parent->baseExpr == sym)) if (dynamic_cast<UnresolvedSymbol*>(sym->var)) { if (!reported.set_in(sym->var->name)) { USR_FATAL_CONT(sym, "'%s' undeclared (first use this function)", sym->var->name); reported.set_add(sym->var->name); } } } } } } static void check_resolved_syms(Symbol* var) { if (!var->isConst() && !var->isParam()) return; if (VarSymbol* vs = dynamic_cast<VarSymbol*>(var)) if (vs->immediate) return; if (var->defs.n > 1) USR_FATAL_CONT(var->defs.v[var->defs.n-1], "Assigning to a constant expression"); // need something like below to check constant assignment via refs forv_Vec(SymExpr, use, var->uses) { if (CallExpr* call = dynamic_cast<CallExpr*>(use->parentExpr)) if (call->isPrimitive(PRIMITIVE_SET_REF)) if (CallExpr* move = dynamic_cast<CallExpr*>(call->parentExpr)) if (move->isPrimitive(PRIMITIVE_MOVE)) if (SymExpr* lhs = dynamic_cast<SymExpr*>(move->get(1))) if (lhs->var->defs.n > 1) USR_FATAL_CONT(lhs->var->defs.v[lhs->var->defs.n-1], "Assigning to a constant expression"); } } void checkResolved(void) { compute_sym_uses(); Vec<BaseAST*> asts; collect_asts(&asts); forv_Vec(BaseAST, ast, asts) { if (dynamic_cast<VarSymbol*>(ast) || dynamic_cast<ArgSymbol*>(ast)) check_resolved_syms(dynamic_cast<Symbol*>(ast)); } forv_Vec(TypeSymbol, type, gTypes) { if (EnumType* et = dynamic_cast<EnumType*>(type->type)) { for_alist(DefExpr, def, et->constants) { if (def->init) { SymExpr* sym = dynamic_cast<SymExpr*>(def->init); if (!sym || (dynamic_cast<VarSymbol*>(sym->var)->consClass != VAR_PARAM && !dynamic_cast<VarSymbol*>(sym->var)->immediate)) USR_FATAL(def, "enumerator '%s' is not an int parameter", def->sym->name); } } } } } <|endoftext|>
<commit_before>#ifndef AFFINE_INVARIANT_FEATURES_FEATURE_PARAMETERS #define AFFINE_INVARIANT_FEATURES_FEATURE_PARAMETERS #include <string> #include <affine_invariant_features/cv_serializable.hpp> #include <opencv2/core.hpp> #include <opencv2/features2d.hpp> #include <opencv2/xfeatures2d.hpp> namespace affine_invariant_features { // // A base class for parameter sets of feature detectors and descriptor extractors // struct FeatureParameters : public CvSerializable { public: FeatureParameters() {} virtual ~FeatureParameters() {} virtual cv::Ptr< cv::Feature2D > createFeature() const = 0; }; // // SIFT // struct SIFTParameters : public FeatureParameters { public: // opencv does not provide interfaces to access default SIFT parameters. // thus values below are copied from online reference. SIFTParameters() : nfeatures(0), nOctaveLayers(3), contrastThreshold(0.04), edgeThreshold(10.), sigma(1.6) {} virtual ~SIFTParameters() {} virtual cv::Ptr< cv::Feature2D > createFeature() const { return cv::xfeatures2d::SIFT::create(nfeatures, nOctaveLayers, contrastThreshold, edgeThreshold, sigma); } virtual void read(const cv::FileNode &fn) { fn["nfeatures"] >> nfeatures; fn["nOctaveLayers"] >> nOctaveLayers; fn["contrastThreshold"] >> contrastThreshold; fn["edgeThreshold"] >> edgeThreshold; fn["sigma"] >> sigma; } virtual void write(cv::FileStorage &fs) const { fs << "nfeatures" << nfeatures; fs << "nOctaveLayers" << nOctaveLayers; fs << "contrastThreshold" << contrastThreshold; fs << "edgeThreshold" << edgeThreshold; fs << "sigma" << sigma; } virtual std::string getDefaultName() const { return "SIFTParameters"; } public: int nfeatures; int nOctaveLayers; double contrastThreshold; double edgeThreshold; double sigma; }; // // AKAZE // struct AKAZEParameters : public FeatureParameters { public: AKAZEParameters() : descriptorType(defaultAKAZE().getDescriptorType()), descriptorSize(defaultAKAZE().getDescriptorSize()), descriptorChannels(defaultAKAZE().getDescriptorChannels()), threshold(defaultAKAZE().getThreshold()), nOctaves(defaultAKAZE().getNOctaves()), nOctaveLayers(defaultAKAZE().getNOctaveLayers()), diffusivity(defaultAKAZE().getDiffusivity()) {} virtual ~AKAZEParameters() {} virtual cv::Ptr< cv::Feature2D > createFeature() const { return cv::AKAZE::create(descriptorType, descriptorSize, descriptorChannels, threshold, nOctaves, nOctaveLayers, diffusivity); } virtual void read(const cv::FileNode &fn) { fn["descriptorType"] >> descriptorType; fn["descriptorSize"] >> descriptorSize; fn["descriptorChannels"] >> descriptorChannels; fn["threshold"] >> threshold; fn["nOctaves"] >> nOctaves; fn["nOctaveLayers"] >> nOctaveLayers; fn["diffusivity"] >> diffusivity; } virtual void write(cv::FileStorage &fs) const { fs << "descriptorType" << descriptorType; fs << "descriptorSize" << descriptorSize; fs << "descriptorChannels" << descriptorChannels; fs << "threshold" << threshold; fs << "nOctaves" << nOctaves; fs << "nOctaveLayers" << nOctaveLayers; fs << "diffusivity" << diffusivity; } virtual std::string getDefaultName() const { return "AKAZEParameters"; } protected: static const cv::AKAZE &defaultAKAZE() { static cv::Ptr< cv::AKAZE > default_akaze(cv::AKAZE::create()); CV_Assert(default_akaze); return *default_akaze; } public: int descriptorType; int descriptorSize; int descriptorChannels; float threshold; int nOctaves; int nOctaveLayers; int diffusivity; }; // // BRISK // struct BRISKParameters : public FeatureParameters { public: // Note: like SIFT, no interface to access default BRISK parameters BRISKParameters() : threshold(30), nOctaves(3), patternScale(1.0f) {} virtual ~BRISKParameters() {} virtual cv::Ptr< cv::Feature2D > createFeature() const { return cv::BRISK::create(threshold, nOctaves, patternScale); } virtual void read(const cv::FileNode &fn) { fn["threshold"] >> threshold; fn["nOctaves"] >> nOctaves; fn["patternScale"] >> patternScale; } virtual void write(cv::FileStorage &fs) const { fs << "threshold" << threshold; fs << "nOctaves" << nOctaves; fs << "patternScale" << patternScale; } virtual std::string getDefaultName() const { return "BRISKParameters"; } public: int threshold; int nOctaves; float patternScale; }; // // Utility functions to create or read variants of FeatureParameters // #define AIF_RETURN_IF_CREATE(type) \ do { \ const cv::Ptr< type > params(new type()); \ if (type_name == params->getDefaultName()) { \ return params; \ } \ } while (false) static inline cv::Ptr< FeatureParameters > createFeatureParameters(const std::string &type_name) { AIF_RETURN_IF_CREATE(AKAZEParameters); AIF_RETURN_IF_CREATE(BRISKParameters); AIF_RETURN_IF_CREATE(SIFTParameters); return cv::Ptr< FeatureParameters >(); } #define AIF_RETURN_IF_LOAD(type) \ do { \ const cv::Ptr< type > params(load< type >(fn)); \ if (params) { \ return params; \ } \ } while (false) template <> cv::Ptr< FeatureParameters > load< FeatureParameters >(const cv::FileNode &fn) { AIF_RETURN_IF_LOAD(AKAZEParameters); AIF_RETURN_IF_LOAD(BRISKParameters); AIF_RETURN_IF_LOAD(SIFTParameters); return cv::Ptr< FeatureParameters >(); } } #endif<commit_msg>add a meta parameter set AIFParameters<commit_after>#ifndef AFFINE_INVARIANT_FEATURES_FEATURE_PARAMETERS #define AFFINE_INVARIANT_FEATURES_FEATURE_PARAMETERS #include <string> #include <affine_invariant_features/affine_invariant_feature.hpp> #include <affine_invariant_features/cv_serializable.hpp> #include <opencv2/core.hpp> #include <opencv2/features2d.hpp> #include <opencv2/xfeatures2d.hpp> namespace affine_invariant_features { // // A base class for parameter sets of feature detectors and descriptor extractors // struct FeatureParameters : public CvSerializable { public: FeatureParameters() {} virtual ~FeatureParameters() {} virtual cv::Ptr< cv::Feature2D > createFeature() const = 0; }; // // Affine invariant sampled feature // static cv::Ptr< FeatureParameters > createFeatureParameters(const std::string &); struct AIFParameters : public std::vector< cv::Ptr< FeatureParameters > >, public FeatureParameters { public: AIFParameters() {} virtual ~AIFParameters() {} virtual cv::Ptr< cv::Feature2D > createFeature() const { switch (size()) { case 0: return cv::Ptr< cv::Feature2D >(); case 1: return AffineInvariantFeature::create(at(0) ? at(0)->createFeature() : cv::Ptr< cv::Feature2D >()); default: return AffineInvariantFeature::create( at(0) ? at(0)->createFeature() : cv::Ptr< cv::Feature2D >(), at(1) ? at(1)->createFeature() : cv::Ptr< cv::Feature2D >()); } } virtual void read(const cv::FileNode &fn) { clear(); for (cv::FileNodeIterator node = fn.begin(); node != fn.end(); ++node) { if (!(*node).isNamed()) { // operator-> did not work continue; } const cv::Ptr< FeatureParameters > p(createFeatureParameters((*node).name())); if (!p) { continue; } p->read(*node); push_back(p); } } virtual void write(cv::FileStorage &fs) const { for (std::vector< cv::Ptr< FeatureParameters > >::const_iterator p = begin(); p != end(); ++p) { if (!(*p)) { continue; } fs << (*p)->getDefaultName() << "{"; (*p)->write(fs); fs << "}"; } } virtual std::string getDefaultName() const { return "AIFParameters"; } }; // // SIFT // struct SIFTParameters : public FeatureParameters { public: // opencv does not provide interfaces to access default SIFT parameters. // thus values below are copied from online reference. SIFTParameters() : nfeatures(0), nOctaveLayers(3), contrastThreshold(0.04), edgeThreshold(10.), sigma(1.6) {} virtual ~SIFTParameters() {} virtual cv::Ptr< cv::Feature2D > createFeature() const { return cv::xfeatures2d::SIFT::create(nfeatures, nOctaveLayers, contrastThreshold, edgeThreshold, sigma); } virtual void read(const cv::FileNode &fn) { fn["nfeatures"] >> nfeatures; fn["nOctaveLayers"] >> nOctaveLayers; fn["contrastThreshold"] >> contrastThreshold; fn["edgeThreshold"] >> edgeThreshold; fn["sigma"] >> sigma; } virtual void write(cv::FileStorage &fs) const { fs << "nfeatures" << nfeatures; fs << "nOctaveLayers" << nOctaveLayers; fs << "contrastThreshold" << contrastThreshold; fs << "edgeThreshold" << edgeThreshold; fs << "sigma" << sigma; } virtual std::string getDefaultName() const { return "SIFTParameters"; } public: int nfeatures; int nOctaveLayers; double contrastThreshold; double edgeThreshold; double sigma; }; // // AKAZE // struct AKAZEParameters : public FeatureParameters { public: AKAZEParameters() : descriptorType(defaultAKAZE().getDescriptorType()), descriptorSize(defaultAKAZE().getDescriptorSize()), descriptorChannels(defaultAKAZE().getDescriptorChannels()), threshold(defaultAKAZE().getThreshold()), nOctaves(defaultAKAZE().getNOctaves()), nOctaveLayers(defaultAKAZE().getNOctaveLayers()), diffusivity(defaultAKAZE().getDiffusivity()) {} virtual ~AKAZEParameters() {} virtual cv::Ptr< cv::Feature2D > createFeature() const { return cv::AKAZE::create(descriptorType, descriptorSize, descriptorChannels, threshold, nOctaves, nOctaveLayers, diffusivity); } virtual void read(const cv::FileNode &fn) { fn["descriptorType"] >> descriptorType; fn["descriptorSize"] >> descriptorSize; fn["descriptorChannels"] >> descriptorChannels; fn["threshold"] >> threshold; fn["nOctaves"] >> nOctaves; fn["nOctaveLayers"] >> nOctaveLayers; fn["diffusivity"] >> diffusivity; } virtual void write(cv::FileStorage &fs) const { fs << "descriptorType" << descriptorType; fs << "descriptorSize" << descriptorSize; fs << "descriptorChannels" << descriptorChannels; fs << "threshold" << threshold; fs << "nOctaves" << nOctaves; fs << "nOctaveLayers" << nOctaveLayers; fs << "diffusivity" << diffusivity; } virtual std::string getDefaultName() const { return "AKAZEParameters"; } protected: static const cv::AKAZE &defaultAKAZE() { static cv::Ptr< cv::AKAZE > default_akaze(cv::AKAZE::create()); CV_Assert(default_akaze); return *default_akaze; } public: int descriptorType; int descriptorSize; int descriptorChannels; float threshold; int nOctaves; int nOctaveLayers; int diffusivity; }; // // BRISK // struct BRISKParameters : public FeatureParameters { public: // Note: like SIFT, no interface to access default BRISK parameters BRISKParameters() : threshold(30), nOctaves(3), patternScale(1.0f) {} virtual ~BRISKParameters() {} virtual cv::Ptr< cv::Feature2D > createFeature() const { return cv::BRISK::create(threshold, nOctaves, patternScale); } virtual void read(const cv::FileNode &fn) { fn["threshold"] >> threshold; fn["nOctaves"] >> nOctaves; fn["patternScale"] >> patternScale; } virtual void write(cv::FileStorage &fs) const { fs << "threshold" << threshold; fs << "nOctaves" << nOctaves; fs << "patternScale" << patternScale; } virtual std::string getDefaultName() const { return "BRISKParameters"; } public: int threshold; int nOctaves; float patternScale; }; // // Utility functions to create or read variants of FeatureParameters // #define AIF_RETURN_IF_CREATE(type) \ do { \ const cv::Ptr< type > params(new type()); \ if (type_name == params->getDefaultName()) { \ return params; \ } \ } while (false) static inline cv::Ptr< FeatureParameters > createFeatureParameters(const std::string &type_name) { AIF_RETURN_IF_CREATE(AIFParameters); AIF_RETURN_IF_CREATE(AKAZEParameters); AIF_RETURN_IF_CREATE(BRISKParameters); AIF_RETURN_IF_CREATE(SIFTParameters); return cv::Ptr< FeatureParameters >(); } #define AIF_RETURN_IF_LOAD(type) \ do { \ const cv::Ptr< type > params(load< type >(fn)); \ if (params) { \ return params; \ } \ } while (false) template <> cv::Ptr< FeatureParameters > load< FeatureParameters >(const cv::FileNode &fn) { AIF_RETURN_IF_LOAD(AIFParameters); AIF_RETURN_IF_LOAD(AKAZEParameters); AIF_RETURN_IF_LOAD(BRISKParameters); AIF_RETURN_IF_LOAD(SIFTParameters); return cv::Ptr< FeatureParameters >(); } } #endif<|endoftext|>
<commit_before>// Copyright (c) 2016 Pierre Fourgeaud // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "./core/fileaccess.h" #include <logger.h> namespace CodeHero { FileAccess::FileAccess() {} FileAccess::~FileAccess() { Close(); } Error FileAccess::Open(const std::string& iFilename, Flags iFlags) { Close(); std::string modeString; switch (iFlags) { case READ: modeString = "rb"; break; case WRITE: modeString = "wb"; break; case READ_WRITE: modeString = "rb+"; break; default: return ERR_INVALID_PARAMETER; }; LOGD2 << "[FileAccess::Open]: Opening " << iFilename << " with mode " << modeString << std::endl; m_pFile = std::fopen(iFilename.c_str(), modeString.c_str()); m_Name = iFilename; return !IsOpen() ? ERR_FILE_NOT_FOUND : OK; } void FileAccess::Close() { if (!IsOpen()) { return; } LOGD2 << "[FileAccess::Close]: Closing " << m_Name << "." << std::endl; fclose(m_pFile); m_pFile = nullptr; } int FileAccess::Read(uint8_t* oData, int iLength) { if (!IsOpen()) { m_LastError = ERR_NO_FILE_OPENED; return 0; } int res = std::fread(oData, sizeof(uint8_t), iLength, m_pFile); _CheckErrors(); return res; } uint8_t FileAccess::Read8() { uint8_t byte = 0; Read(&byte, 1); return byte; } uint16_t FileAccess::Read16() { uint16_t res = 0; uint8_t a = Read8(); uint8_t b = Read8(); res = b; res <<= 8; res |= a; return res; } uint32_t FileAccess::Read32() { uint32_t res = 0; uint16_t a = Read16(); uint16_t b = Read16(); res = b; res <<= 16; res |= a; return res; } std::string FileAccess::ReadAll() { size_t size = GetSize(); std::string out(size, '\0'); Read((uint8_t*)&out[0], size); return std::move(out); } int32_t FileAccess::GetPos() { if (!IsOpen()) { return ERR_NO_FILE_OPENED; } int32_t pos = std::ftell(m_pFile); return pos; } bool FileAccess::IsEOF() const { return IsOpen() && feof(m_pFile); } Error FileAccess::SeekTop() { if (!IsOpen()) { return ERR_NO_FILE_OPENED; } std::rewind(m_pFile); return OK; } Error FileAccess::Seek(int64_t iPosition) { if (!IsOpen()) { return ERR_NO_FILE_OPENED; } if (std::fseek(m_pFile, iPosition, SEEK_SET) != 0) { return FAILED; } return OK; } Error FileAccess::SeekEnd() { if (!IsOpen()) { return ERR_NO_FILE_OPENED; } if (std::fseek(m_pFile, 0, SEEK_END) != 0) { return FAILED; } return OK; } int32_t FileAccess::GetSize() { if (m_Size < 0) { int32_t pos = std::ftell(m_pFile); SeekEnd(); m_Size = std::ftell(m_pFile); Seek(pos); } return m_Size; } bool FileAccess::IsOpen() const { return m_pFile != nullptr; } bool FileAccess::Exists(const std::string& iFilename) { // TODO use new C++ features FILE* fp; fp = fopen(iFilename.c_str(), "rb"); if (fp == nullptr) { return false; } fclose(fp); return true; } void FileAccess::_CheckErrors() { if (!IsOpen()) { return; } if (feof(m_pFile)) { m_LastError = ERR_FILE_EOF; } } } // namespace CodeHero <commit_msg>Make FileAccess::GetPos return 0 on error instead of '6'<commit_after>// Copyright (c) 2016 Pierre Fourgeaud // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "./core/fileaccess.h" #include <logger.h> namespace CodeHero { FileAccess::FileAccess() {} FileAccess::~FileAccess() { Close(); } Error FileAccess::Open(const std::string& iFilename, Flags iFlags) { Close(); std::string modeString; switch (iFlags) { case READ: modeString = "rb"; break; case WRITE: modeString = "wb"; break; case READ_WRITE: modeString = "rb+"; break; default: return ERR_INVALID_PARAMETER; }; LOGD2 << "[FileAccess::Open]: Opening " << iFilename << " with mode " << modeString << std::endl; m_pFile = std::fopen(iFilename.c_str(), modeString.c_str()); m_Name = iFilename; return !IsOpen() ? ERR_FILE_NOT_FOUND : OK; } void FileAccess::Close() { if (!IsOpen()) { return; } LOGD2 << "[FileAccess::Close]: Closing " << m_Name << "." << std::endl; fclose(m_pFile); m_pFile = nullptr; } int FileAccess::Read(uint8_t* oData, int iLength) { if (!IsOpen()) { m_LastError = ERR_NO_FILE_OPENED; return 0; } int res = std::fread(oData, sizeof(uint8_t), iLength, m_pFile); _CheckErrors(); return res; } uint8_t FileAccess::Read8() { uint8_t byte = 0; Read(&byte, 1); return byte; } uint16_t FileAccess::Read16() { uint16_t res = 0; uint8_t a = Read8(); uint8_t b = Read8(); res = b; res <<= 8; res |= a; return res; } uint32_t FileAccess::Read32() { uint32_t res = 0; uint16_t a = Read16(); uint16_t b = Read16(); res = b; res <<= 16; res |= a; return res; } std::string FileAccess::ReadAll() { size_t size = GetSize(); std::string out(size, '\0'); Read((uint8_t*)&out[0], size); return std::move(out); } int32_t FileAccess::GetPos() { if (!IsOpen()) { return 0; } int32_t pos = std::ftell(m_pFile); return pos; } bool FileAccess::IsEOF() const { return IsOpen() && feof(m_pFile); } Error FileAccess::SeekTop() { if (!IsOpen()) { return ERR_NO_FILE_OPENED; } std::rewind(m_pFile); return OK; } Error FileAccess::Seek(int64_t iPosition) { if (!IsOpen()) { return ERR_NO_FILE_OPENED; } if (std::fseek(m_pFile, iPosition, SEEK_SET) != 0) { return FAILED; } return OK; } Error FileAccess::SeekEnd() { if (!IsOpen()) { return ERR_NO_FILE_OPENED; } if (std::fseek(m_pFile, 0, SEEK_END) != 0) { return FAILED; } return OK; } int32_t FileAccess::GetSize() { if (m_Size < 0) { int32_t pos = std::ftell(m_pFile); SeekEnd(); m_Size = std::ftell(m_pFile); Seek(pos); } return m_Size; } bool FileAccess::IsOpen() const { return m_pFile != nullptr; } bool FileAccess::Exists(const std::string& iFilename) { // TODO use new C++ features FILE* fp; fp = fopen(iFilename.c_str(), "rb"); if (fp == nullptr) { return false; } fclose(fp); return true; } void FileAccess::_CheckErrors() { if (!IsOpen()) { return; } if (feof(m_pFile)) { m_LastError = ERR_FILE_EOF; } } } // namespace CodeHero <|endoftext|>
<commit_before>/************************************************************************** * @licence app begin@ * * SPDX-License-Identifier: MPL-2.0 * * \brief Test program for GNSS+SNS logging * * * \author Helmut Schmidt <https://github.com/huirad> * * \copyright Copyright (C) 2015, Helmut Schmidt * * \license * 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/. * * @licence end@ **************************************************************************/ #define __STDC_FORMAT_MACROS #include <inttypes.h> #include "poslog.h" #include "gnsslog.h" #include "snslog.h" #if (DLT_ENABLED) #include "dlt.h" #endif #include <syslog.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include <pthread.h> #include <signal.h> #include <inttypes.h> #include "gnss-init.h" #include "gnss.h" #include "gnss-status.h" #include "sns-init.h" /** * Double buffer for log strings * Purpose: avoid blocking of callback functions by I/O * Multiple writer threads are allowed but only on reader thread */ class DBuf { #define DBUF_STRING_SIZE 256 #define DBUF_NUM_LINES 512 struct SBuf { public: char strings [DBUF_STRING_SIZE] [DBUF_NUM_LINES]; uint16_t rnext; uint16_t wnext; SBuf(): rnext(0), wnext(0) {}; }; SBuf* wbuf; SBuf* rbuf; pthread_mutex_t wmutex; pthread_mutex_t rmutex; public: DBuf() { pthread_mutex_init(&wmutex, NULL); pthread_mutex_init(&rmutex, NULL); wbuf = new(SBuf); rbuf = new(SBuf); } /** * Add a string to the buffer. * Return true on success, false on failure (e.g. buffer full). */ bool write(const char* s) { bool retval = false; pthread_mutex_lock(&wmutex); if (s && wbuf && (wbuf->wnext < DBUF_NUM_LINES)) { strncpy(wbuf->strings[wbuf->wnext], s, DBUF_STRING_SIZE-1); wbuf->strings[wbuf->wnext][DBUF_STRING_SIZE-1] = 0; wbuf->wnext++; retval = true; } pthread_mutex_unlock(&wmutex); return retval; } /** * Read next string from the buffer * Return NULL, if no more string available */ const char* read() { const char* ret = NULL; pthread_mutex_lock(&rmutex); if (rbuf && (rbuf->rnext < rbuf->wnext) && (rbuf->rnext < DBUF_NUM_LINES) ) { ret = rbuf->strings[rbuf->rnext]; rbuf->rnext++; } pthread_mutex_unlock(&rmutex); return ret; } /** * Swap read and write buffers. * Clears read buffer before to ensure that new write buffer is empty. * Shall only be called by reader thread when read buffer has been * completely processed. */ void swap() { SBuf* tmp; pthread_mutex_lock(&rmutex); rbuf->rnext = 0; rbuf->wnext = 0; pthread_mutex_lock(&wmutex); tmp = wbuf; wbuf = rbuf; rbuf = tmp; pthread_mutex_unlock(&wmutex); pthread_mutex_unlock(&rmutex); } }; #define GNSS_INIT_MAX_RETRIES 30 //global variable to control the main loop - will be set by signal handlers or status callback enum EExitCondition { eExitNone = 0, eExitSigInt, eExitGnssFailure }; static volatile bool g_sigterm = false; static volatile EExitCondition g_exit = eExitNone; static volatile bool g_gnss_failure = false; //global pointer to the double buffer DBuf* g_dbuf = 0; pthread_t g_logthread; uint32_t g_write_failures = 0; FILE* g_logfile = 0; /** * Logger callback to add string to the double buffer. */ void dbufCb(const char* string) { if (g_dbuf) { bool write_success = g_dbuf->write(string); if (!write_success) { g_write_failures++; } //printf("WBUF %s\n", string); } } /** * Background thread to write double buffer to a file. * */ void* loop_log_writer(void*) { bool stop = false; //printf("LOGWRITER\n"); while (g_dbuf && !stop && !g_sigterm) { const char* s = 0; //process read buffer - should always be empty while (s = g_dbuf->read()) { printf("BUF1 %s\n", s); } //swap and process previous write buffer g_dbuf->swap(); while (s = g_dbuf->read()) { fprintf(g_logfile, "%s\n", s); } fflush(g_logfile); //printf("LOGWRITER SLEEP\n"); if (g_exit == eExitNone) { sleep(2); //TODO it seems that only the main thread will be interrupted by the signal??? //TODO CHECK how to force faster reaction } else { stop = true; } //printf("LOGWRITER WAKEUP\n"); } //printf("LOGWRITER END\n"); } static void sigHandler (int sig, siginfo_t *siginfo, void *context) { if (sig == SIGINT) { g_exit = eExitSigInt; if (g_logfile) { //ensure that also the logger thread is interrupted //pthread_kill(g_logthread, sig); //seems not to work somehow } } else if (sig == SIGTERM) { g_sigterm = true; } } static bool registerSigHandlers() { bool is_success = true; struct sigaction action; memset (&action, '\0', sizeof(action)); action.sa_sigaction = &sigHandler; action.sa_flags = SA_SIGINFO; if (sigaction(SIGINT, &action, NULL) < 0) { is_success = false; } if (sigaction(SIGTERM, &action, NULL) < 0) { is_success = false; } return is_success; } static void cbTime(const TGNSSTime time[], uint16_t numElements) { gnssTimeLog(gnsslogGetTimestamp(), time, numElements); } static void cbPosition(const TGNSSPosition position[], uint16_t numElements) { gnssPositionLog(gnsslogGetTimestamp(), position, numElements); } static void cbGNSSStatus(const TGNSSStatus *status) { if (status && (status->validityBits & GNSS_STATUS_STATUS_VALID)) { char status_string[64]; sprintf(status_string, "#GNSS Status: %d", status->status); poslogAddString(status_string); if (status->status == GNSS_STATUS_FAILURE) { g_exit = eExitGnssFailure; } } } static void cbAccel(const TAccelerationData accelerationData[], uint16_t numElements) { accelerationDataLog(snslogGetTimestamp(), accelerationData, numElements); } static void cbGyro(const TGyroscopeData gyroData[], uint16_t numElements) { gyroscopeDataLog(snslogGetTimestamp(), gyroData, numElements); } int main (int argc, char *argv[]) { int major; int minor; int micro; char version_string[64]; bool is_poslog_init_ok = false; bool is_sns_init_ok = false; bool is_sns_gyro_init_ok = false; bool is_sns_accel_init_ok = false; bool is_gnss_init_ok = false; int gnss_init_tries = 0; registerSigHandlers(); #if (DLT_ENABLED) DLT_REGISTER_APP("GLT","GNSS/SNS Logger"); #endif poslogSetFD(STDOUT_FILENO); is_poslog_init_ok = poslogInit(); if (is_poslog_init_ok) { if(argv[1] && (g_logfile = fopen(argv[1], "a"))) { g_dbuf = new(DBuf); poslogSetCB(dbufCb); pthread_create(&g_logthread, NULL, loop_log_writer, NULL); poslogSetActiveSinks(POSLOG_SINK_DLT|POSLOG_SINK_CB); } else { poslogSetActiveSinks(POSLOG_SINK_DLT|POSLOG_SINK_FD|POSLOG_SINK_CB); } gnssGetVersion(&major, &minor, &micro); sprintf(version_string, "0,0$GVGNSVER,%d,%d,%d", major, minor, micro); poslogAddString(version_string); snsGetVersion(&major, &minor, &micro); sprintf(version_string, "0,0$GVSNSVER,%d,%d,%d", major, minor, micro); poslogAddString(version_string); is_sns_init_ok = snsInit(); if (is_sns_init_ok) { is_sns_gyro_init_ok = snsGyroscopeInit(); if(is_sns_gyro_init_ok) { poslogAddString("#INF snsGyroscopeInit() success"); snsGyroscopeRegisterCallback(&cbGyro); } is_sns_accel_init_ok = snsAccelerationInit(); if (is_sns_accel_init_ok) { poslogAddString("#INF snsAccelerationInit() success"); snsAccelerationRegisterCallback(&cbAccel); } if (!is_sns_gyro_init_ok && !is_sns_accel_init_ok) { is_sns_init_ok = false; snsDestroy(); } else { poslogAddString("#INF snsInit() success"); } } //GNSS device may be available a bit late after startup is_gnss_init_ok = gnssInit(); while (!is_gnss_init_ok && (gnss_init_tries < GNSS_INIT_MAX_RETRIES) && (g_exit == eExitNone) && !g_sigterm) { sleep(1); is_gnss_init_ok = gnssInit(); gnss_init_tries += 1; } if (is_gnss_init_ok) { poslogAddString("#INF gnssInit() success"); gnssRegisterTimeCallback(&cbTime); gnssRegisterPositionCallback(&cbPosition); gnssRegisterStatusCallback(&cbGNSSStatus); } if (is_sns_init_ok || is_gnss_init_ok) { while(!g_sigterm && (g_exit == eExitNone)) { sleep(1); } } else { poslogAddString("#ERR snsInit() or gnssInit() failure - terminating"); } //if not interrupted by SIGTERM then we have time to cleanup if (!g_sigterm) { if (g_exit == eExitSigInt) { poslogAddString("#SIGINT"); } if (g_exit == eExitGnssFailure) { poslogAddString("#GNSS_STATUS_FAILURE"); } if (is_sns_init_ok) { if (is_sns_accel_init_ok) { snsAccelerationDeregisterCallback(&cbAccel); snsAccelerationDestroy(); } if (is_sns_gyro_init_ok) { snsGyroscopeRegisterCallback(&cbGyro); snsGyroscopeDestroy(); } snsDestroy(); } if (is_gnss_init_ok) { gnssDeregisterStatusCallback(&cbGNSSStatus); gnssDeregisterPositionCallback(&cbPosition); gnssDeregisterTimeCallback(&cbTime); gnssDestroy(); } } if (g_logfile) { pthread_join(g_logthread, NULL); fclose(g_logfile); printf("#Write Failures: %"PRIu64"\n", g_write_failures); } poslogDestroy(); } #if (DLT_ENABLED) DLT_UNREGISTER_APP(); #endif } <commit_msg>UDP log<commit_after>/************************************************************************** * @licence app begin@ * * SPDX-License-Identifier: MPL-2.0 * * \brief Test program for GNSS+SNS logging * * * \author Helmut Schmidt <https://github.com/huirad> * * \copyright Copyright (C) 2015, Helmut Schmidt * * \license * 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/. * * @licence end@ **************************************************************************/ #define __STDC_FORMAT_MACROS #include <inttypes.h> #include "poslog.h" #include "gnsslog.h" #include "snslog.h" #if (DLT_ENABLED) #include "dlt.h" #endif #include <syslog.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include <pthread.h> #include <signal.h> #include <inttypes.h> #include "gnss-init.h" #include "gnss.h" #include "gnss-status.h" #include "sns-init.h" /** * Double buffer for log strings * Purpose: avoid blocking of callback functions by I/O * Multiple writer threads are allowed but only on reader thread */ class DBuf { #define DBUF_STRING_SIZE 256 #define DBUF_NUM_LINES 512 struct SBuf { public: char strings [DBUF_STRING_SIZE] [DBUF_NUM_LINES]; uint16_t rnext; uint16_t wnext; SBuf(): rnext(0), wnext(0) {}; }; SBuf* wbuf; SBuf* rbuf; pthread_mutex_t wmutex; pthread_mutex_t rmutex; public: DBuf() { pthread_mutex_init(&wmutex, NULL); pthread_mutex_init(&rmutex, NULL); wbuf = new(SBuf); rbuf = new(SBuf); } /** * Add a string to the buffer. * Return true on success, false on failure (e.g. buffer full). */ bool write(const char* s) { bool retval = false; pthread_mutex_lock(&wmutex); if (s && wbuf && (wbuf->wnext < DBUF_NUM_LINES)) { strncpy(wbuf->strings[wbuf->wnext], s, DBUF_STRING_SIZE-1); wbuf->strings[wbuf->wnext][DBUF_STRING_SIZE-1] = 0; wbuf->wnext++; retval = true; } pthread_mutex_unlock(&wmutex); return retval; } /** * Read next string from the buffer * Return NULL, if no more string available */ const char* read() { const char* ret = NULL; pthread_mutex_lock(&rmutex); if (rbuf && (rbuf->rnext < rbuf->wnext) && (rbuf->rnext < DBUF_NUM_LINES) ) { ret = rbuf->strings[rbuf->rnext]; rbuf->rnext++; } pthread_mutex_unlock(&rmutex); return ret; } /** * Swap read and write buffers. * Clears read buffer before to ensure that new write buffer is empty. * Shall only be called by reader thread when read buffer has been * completely processed. */ void swap() { SBuf* tmp; pthread_mutex_lock(&rmutex); rbuf->rnext = 0; rbuf->wnext = 0; pthread_mutex_lock(&wmutex); tmp = wbuf; wbuf = rbuf; rbuf = tmp; pthread_mutex_unlock(&wmutex); pthread_mutex_unlock(&rmutex); } }; #define GNSS_INIT_MAX_RETRIES 30 //global variable to control the main loop - will be set by signal handlers or status callback enum EExitCondition { eExitNone = 0, eExitSigInt, eExitGnssFailure }; static volatile bool g_sigterm = false; static volatile EExitCondition g_exit = eExitNone; static volatile bool g_gnss_failure = false; //global pointer to the double buffer DBuf* g_dbuf = 0; pthread_t g_logthread; uint32_t g_write_failures = 0; FILE* g_logfile = 0; /** * Logger callback to add string to the double buffer. */ void dbufCb(const char* string) { if (g_dbuf) { bool write_success = g_dbuf->write(string); if (!write_success) { g_write_failures++; } //printf("WBUF %s\n", string); } } /** * Background thread to write double buffer to a file. * */ void* loop_log_writer(void*) { bool stop = false; //printf("LOGWRITER\n"); while (g_dbuf && !stop && !g_sigterm) { const char* s = 0; //process read buffer - should always be empty while (s = g_dbuf->read()) { printf("BUF1 %s\n", s); } //swap and process previous write buffer g_dbuf->swap(); while (s = g_dbuf->read()) { fprintf(g_logfile, "%s\n", s); } fflush(g_logfile); //printf("LOGWRITER SLEEP\n"); if (g_exit == eExitNone) { sleep(2); //TODO it seems that only the main thread will be interrupted by the signal??? //TODO CHECK how to force faster reaction } else { stop = true; } //printf("LOGWRITER WAKEUP\n"); } //printf("LOGWRITER END\n"); } static void sigHandler (int sig, siginfo_t *siginfo, void *context) { if (sig == SIGINT) { g_exit = eExitSigInt; if (g_logfile) { //ensure that also the logger thread is interrupted //pthread_kill(g_logthread, sig); //seems not to work somehow } } else if (sig == SIGTERM) { g_sigterm = true; } } static bool registerSigHandlers() { bool is_success = true; struct sigaction action; memset (&action, '\0', sizeof(action)); action.sa_sigaction = &sigHandler; action.sa_flags = SA_SIGINFO; if (sigaction(SIGINT, &action, NULL) < 0) { is_success = false; } if (sigaction(SIGTERM, &action, NULL) < 0) { is_success = false; } return is_success; } static void cbTime(const TGNSSTime time[], uint16_t numElements) { gnssTimeLog(gnsslogGetTimestamp(), time, numElements); } static void cbPosition(const TGNSSPosition position[], uint16_t numElements) { gnssPositionLog(gnsslogGetTimestamp(), position, numElements); } static void cbGNSSStatus(const TGNSSStatus *status) { if (status && (status->validityBits & GNSS_STATUS_STATUS_VALID)) { char status_string[64]; sprintf(status_string, "#GNSS Status: %d", status->status); poslogAddString(status_string); if (status->status == GNSS_STATUS_FAILURE) { g_exit = eExitGnssFailure; } } } static void cbAccel(const TAccelerationData accelerationData[], uint16_t numElements) { accelerationDataLog(snslogGetTimestamp(), accelerationData, numElements); } static void cbGyro(const TGyroscopeData gyroData[], uint16_t numElements) { gyroscopeDataLog(snslogGetTimestamp(), gyroData, numElements); } #define UDP_LOG #ifdef UDP_LOG #include<stdlib.h> //exit(0); #include<arpa/inet.h> #include<sys/socket.h> #define UDP_BUFLEN 128 //Max length of buffer #define UDP_PORT 5701 //The port on which to listen for incoming data #define UDP_LOGLEN 256 pthread_t g_udpthread; void* loop_udp_log(void*) { struct sockaddr_in si_me, si_other; int s; socklen_t slen = sizeof(si_other); ssize_t recv_len; char buf[UDP_BUFLEN]; char log_string[UDP_LOGLEN]; bool ok = true; //create a UDP socket if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { ok = false; } if (ok) { // zero out the structure memset((char *) &si_me, 0, sizeof(si_me)); si_me.sin_family = AF_INET; si_me.sin_port = htons(UDP_PORT); si_me.sin_addr.s_addr = htonl(INADDR_ANY); //bind socket to port if( bind(s , (struct sockaddr*)&si_me, sizeof(si_me) ) == -1) { ok = false; } } //keep listening for data while(ok) { //try to receive some data, this is a blocking call if ((recv_len = recvfrom(s, buf, UDP_BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) == -1) { ok = false; } else { snprintf(log_string, UDP_LOGLEN-1, "%"PRIu64",0,$UDP,%s,%d,%s", snslogGetTimestamp(), inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port), buf ); log_string[UDP_LOGLEN-1] = 0; //ensure that string is null-terminated poslogAddString(log_string); } } close(s); } #endif int main (int argc, char *argv[]) { int major; int minor; int micro; char version_string[64]; bool is_poslog_init_ok = false; bool is_sns_init_ok = false; bool is_sns_gyro_init_ok = false; bool is_sns_accel_init_ok = false; bool is_gnss_init_ok = false; int gnss_init_tries = 0; registerSigHandlers(); #if (DLT_ENABLED) DLT_REGISTER_APP("GLT","GNSS/SNS Logger"); #endif poslogSetFD(STDOUT_FILENO); is_poslog_init_ok = poslogInit(); if (is_poslog_init_ok) { if(argv[1] && (g_logfile = fopen(argv[1], "a"))) { g_dbuf = new(DBuf); poslogSetCB(dbufCb); pthread_create(&g_logthread, NULL, loop_log_writer, NULL); poslogSetActiveSinks(POSLOG_SINK_DLT|POSLOG_SINK_CB); } else { poslogSetActiveSinks(POSLOG_SINK_DLT|POSLOG_SINK_FD|POSLOG_SINK_CB); } gnssGetVersion(&major, &minor, &micro); sprintf(version_string, "0,0$GVGNSVER,%d,%d,%d", major, minor, micro); poslogAddString(version_string); snsGetVersion(&major, &minor, &micro); sprintf(version_string, "0,0$GVSNSVER,%d,%d,%d", major, minor, micro); poslogAddString(version_string); #ifdef UDP_LOG pthread_create(&g_udpthread, NULL, loop_udp_log, NULL); #endif is_sns_init_ok = snsInit(); if (is_sns_init_ok) { is_sns_gyro_init_ok = snsGyroscopeInit(); if(is_sns_gyro_init_ok) { poslogAddString("#INF snsGyroscopeInit() success"); snsGyroscopeRegisterCallback(&cbGyro); } is_sns_accel_init_ok = snsAccelerationInit(); if (is_sns_accel_init_ok) { poslogAddString("#INF snsAccelerationInit() success"); snsAccelerationRegisterCallback(&cbAccel); } if (!is_sns_gyro_init_ok && !is_sns_accel_init_ok) { is_sns_init_ok = false; snsDestroy(); } else { poslogAddString("#INF snsInit() success"); } } //GNSS device may be available a bit late after startup is_gnss_init_ok = gnssInit(); while (!is_gnss_init_ok && (gnss_init_tries < GNSS_INIT_MAX_RETRIES) && (g_exit == eExitNone) && !g_sigterm) { sleep(1); is_gnss_init_ok = gnssInit(); gnss_init_tries += 1; } if (is_gnss_init_ok) { poslogAddString("#INF gnssInit() success"); gnssRegisterTimeCallback(&cbTime); gnssRegisterPositionCallback(&cbPosition); gnssRegisterStatusCallback(&cbGNSSStatus); } if (is_sns_init_ok || is_gnss_init_ok) { while(!g_sigterm && (g_exit == eExitNone)) { sleep(1); } } else { poslogAddString("#ERR snsInit() or gnssInit() failure - terminating"); } //if not interrupted by SIGTERM then we have time to cleanup if (!g_sigterm) { if (g_exit == eExitSigInt) { poslogAddString("#SIGINT"); } if (g_exit == eExitGnssFailure) { poslogAddString("#GNSS_STATUS_FAILURE"); } if (is_sns_init_ok) { if (is_sns_accel_init_ok) { snsAccelerationDeregisterCallback(&cbAccel); snsAccelerationDestroy(); } if (is_sns_gyro_init_ok) { snsGyroscopeRegisterCallback(&cbGyro); snsGyroscopeDestroy(); } snsDestroy(); } if (is_gnss_init_ok) { gnssDeregisterStatusCallback(&cbGNSSStatus); gnssDeregisterPositionCallback(&cbPosition); gnssDeregisterTimeCallback(&cbTime); gnssDestroy(); } } if (g_logfile) { pthread_join(g_logthread, NULL); fclose(g_logfile); printf("#Write Failures: %"PRIu64"\n", g_write_failures); } poslogDestroy(); } #if (DLT_ENABLED) DLT_UNREGISTER_APP(); #endif } <|endoftext|>
<commit_before>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_OUT_VALUE_POLICY_HPP_INCLUDED #define LUABIND_OUT_VALUE_POLICY_HPP_INCLUDED #include <luabind/config.hpp> #include <luabind/detail/policy.hpp> // for find_conversion_policy, etc #include <luabind/detail/decorate_type.hpp> // for decorated_type #include <luabind/detail/primitives.hpp> // for by_pointer, by_reference, etc #include <luabind/detail/typetraits.hpp> // for is_nonconst_pointer, is_nonconst_reference, etc #include <new> // for operator new namespace luabind { namespace detail { template<int N> struct char_array { char storage[N]; }; template<class U> char_array<sizeof(typename identity<U>::type)> indirect_sizeof_test(by_reference<U>); template<class U> char_array<sizeof(typename identity<U>::type)> indirect_sizeof_test(by_const_reference<U>); template<class U> char_array<sizeof(typename identity<U>::type)> indirect_sizeof_test(by_pointer<U>); template<class U> char_array<sizeof(typename identity<U>::type)> indirect_sizeof_test(by_const_pointer<U>); template<class U> char_array<sizeof(typename identity<U>::type)> indirect_sizeof_test(by_value<U>); template<class T> struct indirect_sizeof { static const int value = sizeof(indirect_sizeof_test(decorated_type<T>())); }; namespace out_value_detail { template< int Size > struct temporary_storage_size { template< typename T, typename... Args > void construct(Args&&... args) { new (&m_storage) T(std::forward<Args>(args)...); } template<typename T> T& get() { return *reinterpret_cast<T*>(&m_storage); } template<typename T> const T& get() const { return *reinterpret_cast<T*>(&m_storage); } template<typename T> void destroy() { get<T>().~T(); } typename std::aligned_storage<Size>::type m_storage; }; template< typename T > struct temporary_storage_type { template< typename... Args > void construct(Args&&... args) { new (&m_storage) T(std::forward<Args>(args)...); } T& get() { return *reinterpret_cast<T*>(&m_storage); } const T& get() const { return *reinterpret_cast<T*>(&m_storage); } void destroy() { get().~T(); } typename std::aligned_storage<sizeof(T),alignof(T)>::type m_storage; }; } // See note in out_value_policy about why we're not templating // for the parameter type. template<typename T, class Policies = no_policies> struct out_value_converter { enum { consumed_args = 1 }; T& to_cpp(lua_State* L, by_reference<T>, int index) { //specialized_converter_policy_n<1, Policies, T, lua_to_cpp> converter; storage_.construct(converter_.to_cpp(L, decorated_type<T>(), index)); return storage_.get(); } int match(lua_State* L, by_reference<T>, int index) { return converter_.match(L, decorated_type<T>(), index); } void converter_postcall(lua_State* L, by_reference<T>, int) { //specialized_converter_policy_n<2,Policies,T,cpp_to_lua> converter; converter_.to_lua(L, storage_.get()); storage_.destroy(); } T* to_cpp(lua_State* L, by_pointer<T>, int index) { storage_.construct(converter_.to_cpp(L, decorated_type<T>(), index)); return &storage_.get(); } int match(lua_State* L, by_pointer<T>, int index) { return converter_.match(L, decorated_type<T>(), index); } void converter_postcall(lua_State* L, by_pointer<T>, int) { //specialized_converter_policy_n<2, Policies, T, cpp_to_lua> converter; converter_.to_lua(L, storage_.get()); storage_.destroy(); } private: specialized_converter_policy_n<1, Policies, T, lua_to_cpp > converter_; out_value_detail::temporary_storage_type<T> storage_; }; template<class Policies = no_policies> struct out_value_policy { struct only_accepts_nonconst_references_or_pointers {}; struct can_only_convert_from_lua_to_cpp {}; template<class T, class Direction> struct specialize { static_assert(std::is_same< Direction, lua_to_cpp >::value, "Out value policy can only convert from lua to cpp"); static_assert(meta::or_< is_nonconst_reference<T>, is_nonconst_pointer<T> >::value, "Out value policy only accepts non const references or pointers"); // Note to myself: // Using the size and template members instead of a policy templated for the type seems // to be done to tame template bloat. Need to check if this is worth is. using base_type = typename std::remove_pointer< typename std::remove_reference< T >::type >::type; typedef out_value_converter<base_type, Policies> type; }; }; template<int Size, class Policies = no_policies> struct pure_out_value_converter { enum { consumed_args = 0 }; template<class T> T& to_cpp(lua_State*, by_reference<T>, int) { storage_.construct<T>(); return storage_.get<T>(); } template<class T> static int match(lua_State*, by_reference<T>, int) { return 0; } template<class T> void converter_postcall(lua_State* L, by_reference<T>, int) { specialized_converter_policy_n<1, Policies, T, cpp_to_lua> converter; converter.to_lua(L, storage_.get<T>()); storage_.destroy<T>(); } template<class T> T* to_cpp(lua_State*, by_pointer<T>, int) { storage_.construct<T>(); return &storage_.get<T>(); } template<class T> static int match(lua_State*, by_pointer<T>, int) { return 0; } template<class T> void converter_postcall(lua_State* L, by_pointer<T>, int) { specialized_converter_policy_n<1, Policies, T, cpp_to_lua> converter; converter.to_lua(L, storage_.get<T>()); storage_.destroy<T>(); } private: out_value_detail::temporary_storage_size<Size> storage_; }; template<class Policies = no_policies> struct pure_out_value_policy { struct only_accepts_nonconst_references_or_pointers {}; struct can_only_convert_from_lua_to_cpp {}; template<class T, class Direction> struct specialize { static_assert(std::is_same< Direction, lua_to_cpp >::value, "Pure out value policy can only convert from lua to cpp"); static_assert(meta::or_< is_nonconst_reference<T>, is_nonconst_pointer<T> >::value, "Pure out value policy only accepts non const references or pointers"); typedef pure_out_value_converter<indirect_sizeof<T>::value, Policies> type; }; }; }} namespace luabind { template<unsigned int N, class Policies = no_policies > using out_value = meta::type_list<converter_policy_injector<N,detail::out_value_policy<Policies>>>; template<unsigned int N, class Policies = no_policies > using pure_out_value = meta::type_list<converter_policy_injector<N,detail::pure_out_value_policy<Policies>>>; } #endif // LUABIND_OUT_VALUE_POLICY_HPP_INCLUDED <commit_msg>Added missing 'template' keyword<commit_after>// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef LUABIND_OUT_VALUE_POLICY_HPP_INCLUDED #define LUABIND_OUT_VALUE_POLICY_HPP_INCLUDED #include <luabind/config.hpp> #include <luabind/detail/policy.hpp> // for find_conversion_policy, etc #include <luabind/detail/decorate_type.hpp> // for decorated_type #include <luabind/detail/primitives.hpp> // for by_pointer, by_reference, etc #include <luabind/detail/typetraits.hpp> // for is_nonconst_pointer, is_nonconst_reference, etc #include <new> // for operator new namespace luabind { namespace detail { template<int N> struct char_array { char storage[N]; }; template<class U> char_array<sizeof(typename identity<U>::type)> indirect_sizeof_test(by_reference<U>); template<class U> char_array<sizeof(typename identity<U>::type)> indirect_sizeof_test(by_const_reference<U>); template<class U> char_array<sizeof(typename identity<U>::type)> indirect_sizeof_test(by_pointer<U>); template<class U> char_array<sizeof(typename identity<U>::type)> indirect_sizeof_test(by_const_pointer<U>); template<class U> char_array<sizeof(typename identity<U>::type)> indirect_sizeof_test(by_value<U>); template<class T> struct indirect_sizeof { static const int value = sizeof(indirect_sizeof_test(decorated_type<T>())); }; namespace out_value_detail { template< int Size > struct temporary_storage_size { template< typename T, typename... Args > void construct(Args&&... args) { new (&m_storage) T(std::forward<Args>(args)...); } template<typename T> T& get() { return *reinterpret_cast<T*>(&m_storage); } template<typename T> const T& get() const { return *reinterpret_cast<T*>(&m_storage); } template<typename T> void destroy() { get<T>().~T(); } typename std::aligned_storage<Size>::type m_storage; }; template< typename T > struct temporary_storage_type { template< typename... Args > void construct(Args&&... args) { new (&m_storage) T(std::forward<Args>(args)...); } T& get() { return *reinterpret_cast<T*>(&m_storage); } const T& get() const { return *reinterpret_cast<T*>(&m_storage); } void destroy() { get().~T(); } typename std::aligned_storage<sizeof(T),alignof(T)>::type m_storage; }; } // See note in out_value_policy about why we're not templating // for the parameter type. template<typename T, class Policies = no_policies> struct out_value_converter { enum { consumed_args = 1 }; T& to_cpp(lua_State* L, by_reference<T>, int index) { //specialized_converter_policy_n<1, Policies, T, lua_to_cpp> converter; storage_.construct(converter_.to_cpp(L, decorated_type<T>(), index)); return storage_.get(); } int match(lua_State* L, by_reference<T>, int index) { return converter_.match(L, decorated_type<T>(), index); } void converter_postcall(lua_State* L, by_reference<T>, int) { //specialized_converter_policy_n<2,Policies,T,cpp_to_lua> converter; converter_.to_lua(L, storage_.get()); storage_.destroy(); } T* to_cpp(lua_State* L, by_pointer<T>, int index) { storage_.construct(converter_.to_cpp(L, decorated_type<T>(), index)); return &storage_.get(); } int match(lua_State* L, by_pointer<T>, int index) { return converter_.match(L, decorated_type<T>(), index); } void converter_postcall(lua_State* L, by_pointer<T>, int) { //specialized_converter_policy_n<2, Policies, T, cpp_to_lua> converter; converter_.to_lua(L, storage_.get()); storage_.destroy(); } private: specialized_converter_policy_n<1, Policies, T, lua_to_cpp > converter_; out_value_detail::temporary_storage_type<T> storage_; }; template<class Policies = no_policies> struct out_value_policy { struct only_accepts_nonconst_references_or_pointers {}; struct can_only_convert_from_lua_to_cpp {}; template<class T, class Direction> struct specialize { static_assert(std::is_same< Direction, lua_to_cpp >::value, "Out value policy can only convert from lua to cpp"); static_assert(meta::or_< is_nonconst_reference<T>, is_nonconst_pointer<T> >::value, "Out value policy only accepts non const references or pointers"); // Note to myself: // Using the size and template members instead of a policy templated for the type seems // to be done to tame template bloat. Need to check if this is worth is. using base_type = typename std::remove_pointer< typename std::remove_reference< T >::type >::type; typedef out_value_converter<base_type, Policies> type; }; }; template<int Size, class Policies = no_policies> struct pure_out_value_converter { enum { consumed_args = 0 }; template<class T> T& to_cpp(lua_State*, by_reference<T>, int) { storage_.template construct<T>(); return storage_.template get<T>(); } template<class T> static int match(lua_State*, by_reference<T>, int) { return 0; } template<class T> void converter_postcall(lua_State* L, by_reference<T>, int) { specialized_converter_policy_n<1, Policies, T, cpp_to_lua> converter; converter.to_lua(L, storage_.template get<T>()); storage_.template destroy<T>(); } template<class T> T* to_cpp(lua_State*, by_pointer<T>, int) { storage_.template construct<T>(); return &storage_.template get<T>(); } template<class T> static int match(lua_State*, by_pointer<T>, int) { return 0; } template<class T> void converter_postcall(lua_State* L, by_pointer<T>, int) { specialized_converter_policy_n<1, Policies, T, cpp_to_lua> converter; converter.to_lua(L, storage_.template get<T>()); storage_.template destroy<T>(); } private: out_value_detail::temporary_storage_size<Size> storage_; }; template<class Policies = no_policies> struct pure_out_value_policy { struct only_accepts_nonconst_references_or_pointers {}; struct can_only_convert_from_lua_to_cpp {}; template<class T, class Direction> struct specialize { static_assert(std::is_same< Direction, lua_to_cpp >::value, "Pure out value policy can only convert from lua to cpp"); static_assert(meta::or_< is_nonconst_reference<T>, is_nonconst_pointer<T> >::value, "Pure out value policy only accepts non const references or pointers"); typedef pure_out_value_converter<indirect_sizeof<T>::value, Policies> type; }; }; }} namespace luabind { template<unsigned int N, class Policies = no_policies > using out_value = meta::type_list<converter_policy_injector<N,detail::out_value_policy<Policies>>>; template<unsigned int N, class Policies = no_policies > using pure_out_value = meta::type_list<converter_policy_injector<N,detail::pure_out_value_policy<Policies>>>; } #endif // LUABIND_OUT_VALUE_POLICY_HPP_INCLUDED <|endoftext|>
<commit_before>/* * Copyright (C) 2015 by Glenn Hickey ([email protected]) * * Released under the MIT license, see LICENSE.txt */ #include "sgsql.h" using namespace std; using namespace hal; SGSQL::SGSQL() : _sgBuilder(0), _sg(0) { } SGSQL::~SGSQL() { } void SGSQL::writeDb(const SGBuilder* sgBuilder, const string& sqlInsertPath, const string& fastaPath) { _sgBuilder = sgBuilder; _sg = _sgBuilder->getSideGraph(); assert(_sg != NULL); _outPath = sqlInsertPath; _outStream.open(_outPath.c_str()); assert(_outStream); _faPath = fastaPath; _faStream.open(_faPath.c_str()); assert(_faStream); _checksumMap.clear(); writeFasta(); writeFastaInsert(); writeSequenceInserts(); writeReferenceInserts(); writeJoinInserts(); writePathInserts(); _outStream.close(); _faStream.close(); } void SGSQL::writeFasta() { string dnaBuffer; for (sg_int_t i = 0; i < _sg->getNumSequences(); ++i) { const SGSequence* seq = _sg->getSequence(i); _sgBuilder->getSequenceString(seq, dnaBuffer); assert((sg_int_t)dnaBuffer.length() == seq->getLength()); _faStream << ">" << seq->getName() << "\n"; size_t len; for (size_t pos = 0; pos < dnaBuffer.length(); pos += len) { len = min((size_t)80, dnaBuffer.length() - pos); _faStream << dnaBuffer.substr(pos, len) << "\n"; } string checksum; getChecksum(dnaBuffer, checksum); _checksumMap.insert(pair<sg_seqid_t, string>(seq->getID(), checksum)); } } /* CREATE TABLE FASTA (ID INTEGER PRIMARY KEY, fastaURI TEXT NOT NULL); */ void SGSQL::writeFastaInsert() { _outStream << "INSERT INTO FASTA VALUES (" << 0 << ", " << "file://" << _faPath << ")\n"; _outStream << endl; } /* CREATE TABLE Sequence (ID INTEGER PRIMARY KEY, -- FASTA file URI and record name within it containing sequence fastaID INTEGER, -- If null, query enclosing ReferenceSet's fastaID sequenceRecordName TEXT NOT NULL, md5checksum TEXT NOT NULL, length INTEGER NOT NULL, FOREIGN KEY(fastaID) REFERENCES FASTA(ID)); */ void SGSQL::writeSequenceInserts() { for (sg_int_t i = 0; i < _sg->getNumSequences(); ++i) { const SGSequence* seq = _sg->getSequence(i); map<sg_seqid_t, string>::const_iterator j = _checksumMap.find(seq->getID()); assert(j != _checksumMap.end()); _outStream << "INSERT INTO Sequence VALUES (" << seq->getID() << ", " << 0 << ", " << "\'"<< seq->getName() << "\', " << "\'" << j->second << "\', " << seq->getLength() << ");\n"; } _outStream << endl; } /* -- References CREATE TABLE Reference (ID INTEGER PRIMARY KEY, name TEXT NOT NULL, updateTime DATE NOT NULL, sequenceID INTEGER NOT NULL, start INTEGER NOT NULL, -- default 0. length INTEGER, -- if null, assume sequence.lenght - start md5checksum TEXT, -- if null, assume sequence.md5checksum isDerived BOOLEAN NOT NULL, sourceDivergence REAL, -- may be null if isDerived is FALSE (not sure if it needs to be stored)? ncbiTaxonID INTEGER, -- ID from http://www.ncbi.nlm.nih.gov/taxonomy, may be null isPrimary BOOLEAN NOT NULL, FOREIGN KEY(sequenceID) REFERENCES Sequence(ID)); CREATE TABLE ReferenceAccession (ID INTEGER PRIMARY KEY, referenceID INTEGER NOT NULL, accessionID TEXT NOT NULL, FOREIGN KEY(referenceID) REFERENCES Reference(ID)); -- Reference sets CREATE TABLE ReferenceSet (ID INTEGER PRIMARY KEY, ncbiTaxonID INT, -- may be null, may differ from ncbiTaxonID of contained Reference record description TEXT, -- may be null, but shouldn't be? fastaID INTEGER, -- may be null. TODO: What if both this and a member Reference's Sequence fastaID are null? assemblyID TEXT, -- may be null, but REALLY shouldn't be? isDerived BOOLEAN NOT NULL, FOREIGN KEY(fastaID) REFERENCES FASTA(ID)); CREATE TABLE ReferenceSetAccession (ID INTEGER PRIMARY KEY, referenceSetID INTEGER NOT NULL, accessionID TEXT NOT NULL, FOREIGN KEY(referenceSetID) REFERENCES ReferenceSet(ID)); CREATE TABLE Reference_ReferenceSet_Join (referenceID INTEGER NOT NULL, referenceSetID INTEGER NOT NULL, PRIMARY KEY(referenceID, referenceSetID), FOREIGN KEY(referenceID) REFERENCES Reference(ID), FOREIGN KEY(referenceSetID) REFERENCES ReferenceSet(ID)); */ void SGSQL::writeReferenceInserts() { // make a reference set for each input genome from the HAL map<string, size_t> refMap; refMap.insert(pair<string, size_t>(_sgBuilder->getPrimaryGenomeName(), 0)); _outStream << "INSERT INTO ReferenceSet VALUES " << "(0, NULL, NULL, 0, NULL, \'FALSE\')\n"; for (sg_int_t i = 0; i < _sg->getNumSequences(); ++i) { const SGSequence* seq = _sg->getSequence(i); string halGenomeName = _sgBuilder->getHalGenomeName(seq); if (refMap.find(halGenomeName) == refMap.end()) { sg_int_t id = refMap.size(); refMap.insert(pair<string, size_t>(halGenomeName, id)); // single reference set _outStream << "INSERT INTO ReferenceSet VALUES " << "(" << id << ", NULL, " << "\'HAL Genome " + halGenomeName << "\'" << ", 0, NULL, \'FALSE\')\n"; } } for (sg_int_t i = 0; i < _sg->getNumSequences(); ++i) { const SGSequence* seq = _sg->getSequence(i); string halGenomeName = _sgBuilder->getHalGenomeName(seq); bool primary = halGenomeName == _sgBuilder->getPrimaryGenomeName(); _outStream << "INSERT INTO Reference VALUES (" << seq->getID() << ", " << "\'"<< seq->getName() << "\', " << "date(\'now\')" << ", " << seq->getID() << ", " << refMap.find(halGenomeName)->second << ", " << "NULL " << ", " << "NULL " << ", " << "\'FALSE\'" << ", " << "NULL " << ", " << "NULL " << ", " << (primary ? "\'TRUE\'" : "\'FALSE\'") << ");\n"; } for (sg_int_t i = 0; i < _sg->getNumSequences(); ++i) { const SGSequence* seq = _sg->getSequence(i); _outStream << "INSERT INTO Reference_ReferenceSet_Join VALUES (" << seq->getID() << ", 0);\n"; } _outStream << endl; } /* CREATE TABLE GraphJoin (ID INTEGER PRIMARY KEY, -- startJoin defines parent sequence & position that 5' end attaches to. side1SequenceID INTEGER NOT NULL, side1Position INTEGER NOT NULL, side1StrandIsForward BOOLEAN NOT NULL, -- endJoin defines parent sequence & position that 3' end attaches to. side2SequenceID INTEGER NOT NULL, side2Position INTEGER NOT NULL, side2StrandIsForward BOOLEAN NOT NULL, FOREIGN KEY(side1SequenceID) REFERENCES Sequence(ID), FOREIGN KEY(side2SequenceID) REFERENCES Sequence(ID)); */ void SGSQL::writeJoinInserts() { const SideGraph::JoinSet* joinSet = _sg->getJoinSet(); SideGraph::JoinSet::const_iterator i; size_t count = 0; for (i = joinSet->begin(); i != joinSet->end(); ++i) { const SGJoin* join = *i; const SGSide& side1 = join->getSide1(); const SGSide& side2 = join->getSide2(); _outStream << "INSERT INTO GraphJoin VALUES (" << count++ << ", " << side1.getBase().getSeqID() << ", " << side1.getBase().getPos() << ", " << (side1.getForward() ? "TRUE" : "FALSE") << ", " << side2.getBase().getSeqID() << ", " << side2.getBase().getPos() << ", " << (side2.getForward() ? "TRUE" : "FALSE") << ")\n"; } _outStream << endl; } void SGSQL::writePathInserts() { const vector<const Sequence*>& halSequences = _sgBuilder->getHalSequences(); _outStream << "# Preliminary path data for each INPUT sequence (from " << "HAL file). \n#Still need to write in whatever official" << " path format is. Tuples below are:\n" << "# (INPUT-SEQUENCE-NAME, PATH-STEP-#, SEGMENT) " << "where SEGMENT = (SEQUENCE-ID, POSITION, LENGTH, FORWARD)\n"; for (size_t i = 0; i < halSequences.size(); ++i) { vector<SGSegment> path; _sgBuilder->getHalSequencePath(halSequences[i], path); for (size_t j = 0; j < path.size(); ++j) { _outStream << "INSERT INTO Path VALUES (" << halSequences[i]->getFullName() << ", " << j << ", " << path[j].getSide().getBase().getSeqID() << ", " << path[j].getSide().getBase().getPos() << ", " << path[j].getLength() << ", " << (path[j].getSide().getForward() ? "\'TRUE\'" : "\'FALSE\'") << ")\n"; } } _outStream <<endl; } void SGSQL::getChecksum(const string& inputString, string& outputString) { outputString = "md5"; } <commit_msg>clean path comment a bit<commit_after>/* * Copyright (C) 2015 by Glenn Hickey ([email protected]) * * Released under the MIT license, see LICENSE.txt */ #include "sgsql.h" using namespace std; using namespace hal; SGSQL::SGSQL() : _sgBuilder(0), _sg(0) { } SGSQL::~SGSQL() { } void SGSQL::writeDb(const SGBuilder* sgBuilder, const string& sqlInsertPath, const string& fastaPath) { _sgBuilder = sgBuilder; _sg = _sgBuilder->getSideGraph(); assert(_sg != NULL); _outPath = sqlInsertPath; _outStream.open(_outPath.c_str()); assert(_outStream); _faPath = fastaPath; _faStream.open(_faPath.c_str()); assert(_faStream); _checksumMap.clear(); writeFasta(); writeFastaInsert(); writeSequenceInserts(); writeReferenceInserts(); writeJoinInserts(); writePathInserts(); _outStream.close(); _faStream.close(); } void SGSQL::writeFasta() { string dnaBuffer; for (sg_int_t i = 0; i < _sg->getNumSequences(); ++i) { const SGSequence* seq = _sg->getSequence(i); _sgBuilder->getSequenceString(seq, dnaBuffer); assert((sg_int_t)dnaBuffer.length() == seq->getLength()); _faStream << ">" << seq->getName() << "\n"; size_t len; for (size_t pos = 0; pos < dnaBuffer.length(); pos += len) { len = min((size_t)80, dnaBuffer.length() - pos); _faStream << dnaBuffer.substr(pos, len) << "\n"; } string checksum; getChecksum(dnaBuffer, checksum); _checksumMap.insert(pair<sg_seqid_t, string>(seq->getID(), checksum)); } } /* CREATE TABLE FASTA (ID INTEGER PRIMARY KEY, fastaURI TEXT NOT NULL); */ void SGSQL::writeFastaInsert() { _outStream << "INSERT INTO FASTA VALUES (" << 0 << ", " << "file://" << _faPath << ")\n"; _outStream << endl; } /* CREATE TABLE Sequence (ID INTEGER PRIMARY KEY, -- FASTA file URI and record name within it containing sequence fastaID INTEGER, -- If null, query enclosing ReferenceSet's fastaID sequenceRecordName TEXT NOT NULL, md5checksum TEXT NOT NULL, length INTEGER NOT NULL, FOREIGN KEY(fastaID) REFERENCES FASTA(ID)); */ void SGSQL::writeSequenceInserts() { for (sg_int_t i = 0; i < _sg->getNumSequences(); ++i) { const SGSequence* seq = _sg->getSequence(i); map<sg_seqid_t, string>::const_iterator j = _checksumMap.find(seq->getID()); assert(j != _checksumMap.end()); _outStream << "INSERT INTO Sequence VALUES (" << seq->getID() << ", " << 0 << ", " << "\'"<< seq->getName() << "\', " << "\'" << j->second << "\', " << seq->getLength() << ");\n"; } _outStream << endl; } /* -- References CREATE TABLE Reference (ID INTEGER PRIMARY KEY, name TEXT NOT NULL, updateTime DATE NOT NULL, sequenceID INTEGER NOT NULL, start INTEGER NOT NULL, -- default 0. length INTEGER, -- if null, assume sequence.lenght - start md5checksum TEXT, -- if null, assume sequence.md5checksum isDerived BOOLEAN NOT NULL, sourceDivergence REAL, -- may be null if isDerived is FALSE (not sure if it needs to be stored)? ncbiTaxonID INTEGER, -- ID from http://www.ncbi.nlm.nih.gov/taxonomy, may be null isPrimary BOOLEAN NOT NULL, FOREIGN KEY(sequenceID) REFERENCES Sequence(ID)); CREATE TABLE ReferenceAccession (ID INTEGER PRIMARY KEY, referenceID INTEGER NOT NULL, accessionID TEXT NOT NULL, FOREIGN KEY(referenceID) REFERENCES Reference(ID)); -- Reference sets CREATE TABLE ReferenceSet (ID INTEGER PRIMARY KEY, ncbiTaxonID INT, -- may be null, may differ from ncbiTaxonID of contained Reference record description TEXT, -- may be null, but shouldn't be? fastaID INTEGER, -- may be null. TODO: What if both this and a member Reference's Sequence fastaID are null? assemblyID TEXT, -- may be null, but REALLY shouldn't be? isDerived BOOLEAN NOT NULL, FOREIGN KEY(fastaID) REFERENCES FASTA(ID)); CREATE TABLE ReferenceSetAccession (ID INTEGER PRIMARY KEY, referenceSetID INTEGER NOT NULL, accessionID TEXT NOT NULL, FOREIGN KEY(referenceSetID) REFERENCES ReferenceSet(ID)); CREATE TABLE Reference_ReferenceSet_Join (referenceID INTEGER NOT NULL, referenceSetID INTEGER NOT NULL, PRIMARY KEY(referenceID, referenceSetID), FOREIGN KEY(referenceID) REFERENCES Reference(ID), FOREIGN KEY(referenceSetID) REFERENCES ReferenceSet(ID)); */ void SGSQL::writeReferenceInserts() { // make a reference set for each input genome from the HAL map<string, size_t> refMap; refMap.insert(pair<string, size_t>(_sgBuilder->getPrimaryGenomeName(), 0)); _outStream << "INSERT INTO ReferenceSet VALUES " << "(0, NULL, NULL, 0, NULL, \'FALSE\')\n"; for (sg_int_t i = 0; i < _sg->getNumSequences(); ++i) { const SGSequence* seq = _sg->getSequence(i); string halGenomeName = _sgBuilder->getHalGenomeName(seq); if (refMap.find(halGenomeName) == refMap.end()) { sg_int_t id = refMap.size(); refMap.insert(pair<string, size_t>(halGenomeName, id)); // single reference set _outStream << "INSERT INTO ReferenceSet VALUES " << "(" << id << ", NULL, " << "\'HAL Genome " + halGenomeName << "\'" << ", 0, NULL, \'FALSE\')\n"; } } for (sg_int_t i = 0; i < _sg->getNumSequences(); ++i) { const SGSequence* seq = _sg->getSequence(i); string halGenomeName = _sgBuilder->getHalGenomeName(seq); bool primary = halGenomeName == _sgBuilder->getPrimaryGenomeName(); _outStream << "INSERT INTO Reference VALUES (" << seq->getID() << ", " << "\'"<< seq->getName() << "\', " << "date(\'now\')" << ", " << seq->getID() << ", " << refMap.find(halGenomeName)->second << ", " << "NULL " << ", " << "NULL " << ", " << "\'FALSE\'" << ", " << "NULL " << ", " << "NULL " << ", " << (primary ? "\'TRUE\'" : "\'FALSE\'") << ");\n"; } for (sg_int_t i = 0; i < _sg->getNumSequences(); ++i) { const SGSequence* seq = _sg->getSequence(i); _outStream << "INSERT INTO Reference_ReferenceSet_Join VALUES (" << seq->getID() << ", 0);\n"; } _outStream << endl; } /* CREATE TABLE GraphJoin (ID INTEGER PRIMARY KEY, -- startJoin defines parent sequence & position that 5' end attaches to. side1SequenceID INTEGER NOT NULL, side1Position INTEGER NOT NULL, side1StrandIsForward BOOLEAN NOT NULL, -- endJoin defines parent sequence & position that 3' end attaches to. side2SequenceID INTEGER NOT NULL, side2Position INTEGER NOT NULL, side2StrandIsForward BOOLEAN NOT NULL, FOREIGN KEY(side1SequenceID) REFERENCES Sequence(ID), FOREIGN KEY(side2SequenceID) REFERENCES Sequence(ID)); */ void SGSQL::writeJoinInserts() { const SideGraph::JoinSet* joinSet = _sg->getJoinSet(); SideGraph::JoinSet::const_iterator i; size_t count = 0; for (i = joinSet->begin(); i != joinSet->end(); ++i) { const SGJoin* join = *i; const SGSide& side1 = join->getSide1(); const SGSide& side2 = join->getSide2(); _outStream << "INSERT INTO GraphJoin VALUES (" << count++ << ", " << side1.getBase().getSeqID() << ", " << side1.getBase().getPos() << ", " << (side1.getForward() ? "TRUE" : "FALSE") << ", " << side2.getBase().getSeqID() << ", " << side2.getBase().getPos() << ", " << (side2.getForward() ? "TRUE" : "FALSE") << ")\n"; } _outStream << endl; } void SGSQL::writePathInserts() { const vector<const Sequence*>& halSequences = _sgBuilder->getHalSequences(); _outStream << "-- Preliminary path data for each INPUT sequence (from " << "HAL file). \n-- Still need to write in whatever official" << " path format is. Tuples below are:\n" << "-- (INPUT-SEQUENCE-NAME, PATH-STEP-#, SEGMENT) " << "where SEGMENT = (SEQUENCE-ID, POSITION, LENGTH, FORWARD)\n"; for (size_t i = 0; i < halSequences.size(); ++i) { vector<SGSegment> path; _sgBuilder->getHalSequencePath(halSequences[i], path); for (size_t j = 0; j < path.size(); ++j) { _outStream << "INSERT INTO Path VALUES (" << halSequences[i]->getFullName() << ", " << j << ", " << path[j].getSide().getBase().getSeqID() << ", " << path[j].getSide().getBase().getPos() << ", " << path[j].getLength() << ", " << (path[j].getSide().getForward() ? "\'TRUE\'" : "\'FALSE\'") << ")\n"; } } _outStream <<endl; } void SGSQL::getChecksum(const string& inputString, string& outputString) { outputString = "md5"; } <|endoftext|>
<commit_before>#ifndef MIDDLEWARE_PARSLEY_HPP #define MIDDLEWARE_PARSLEY_HPP #include "json.hpp" #include "middleware.hpp" /** * @brief A vegan way to parse JSON Content in a response * @details TBC.. * */ class Parsley : public server::Middleware { public: virtual void process( server::Request_ptr req, server::Response_ptr, server::Next next ) override { using namespace json; if(!has_json(req)) { printf("<Parsley> No JSON in header field.\n"); (*next)(); return; } printf("<Parsley> Found json header\n"); // Request doesn't have JSON attribute if(!req->has_attribute<JsonDoc>()) { // create attribute auto json = std::make_shared<JsonDoc>(); // access the document and parse the body json->doc().Parse(req->get_body().c_str()); printf("<Parsley> Parsed JSON data.\n"); // add the json to the request req->set_attribute(json); } (*next)(); } private: bool has_json(server::Request_ptr req) const { auto c_type = http::header_fields::Entity::Content_Type; if(!req->has_header(c_type)) return false; return (req->header_value(c_type).find("application/json") != std::string::npos); } }; #endif <commit_msg>Middleware: Silenced some debug output<commit_after>#ifndef MIDDLEWARE_PARSLEY_HPP #define MIDDLEWARE_PARSLEY_HPP #include "json.hpp" #include "middleware.hpp" /** * @brief A vegan way to parse JSON Content in a response * @details TBC.. * */ class Parsley : public server::Middleware { public: virtual void process( server::Request_ptr req, server::Response_ptr, server::Next next ) override { using namespace json; if(!has_json(req)) { //printf("<Parsley> No JSON in header field.\n"); (*next)(); return; } //printf("<Parsley> Found json header\n"); // Request doesn't have JSON attribute if(!req->has_attribute<JsonDoc>()) { // create attribute auto json = std::make_shared<JsonDoc>(); // access the document and parse the body json->doc().Parse(req->get_body().c_str()); printf("<Parsley> Parsed JSON data.\n"); // add the json to the request req->set_attribute(json); } (*next)(); } private: bool has_json(server::Request_ptr req) const { auto c_type = http::header_fields::Entity::Content_Type; if(!req->has_header(c_type)) return false; return (req->header_value(c_type).find("application/json") != std::string::npos); } }; #endif <|endoftext|>
<commit_before>#ifndef BFC_SOURCELOC_HPP #define BFC_SOURCELOC_HPP #include <cstddef> #include <memory> #include <ostream> #include <string> namespace bfc { struct source_pos { off_t off; unsigned long row; unsigned long col; }; static std::ostream & operator<<(std::ostream &out, source_pos pos) { return out << pos.row << ',' << pos.col; } class source_loc { public: source_loc(source_pos begin, source_pos end, std::string name) noexcept : source_loc{begin, end, std::make_shared<std::string>(std::move(name))} {} source_loc(source_pos begin, source_pos end, std::shared_ptr<std::string> name) noexcept : begin_pos{begin}, end_pos{end}, source_name{name} {} source_pos begin(void) const noexcept { return begin_pos; } source_pos end(void) const noexcept { return end_pos; } const std::string &name(void) const noexcept { return *source_name; } source_loc with_pos(source_pos begin, source_pos end) const noexcept { return source_loc{begin, end, source_name}; } void print(std::ostream &out) const { out << *source_name << ':' << begin_pos << '-' << end_pos; } private: std::shared_ptr<std::string> source_name; source_pos begin_pos; source_pos end_pos; }; static std::ostream & operator<<(std::ostream &out, const source_loc &loc) { loc.print(out); return out; } } #endif /* !BFC_SOURCELOC_HPP */ <commit_msg>Remove off_t (since it's POSIX and not part of the C or C++ standards)<commit_after>#ifndef BFC_SOURCELOC_HPP #define BFC_SOURCELOC_HPP #include <cstddef> #include <memory> #include <ostream> #include <string> namespace bfc { struct source_pos { unsigned long off; unsigned long row; unsigned long col; }; static std::ostream & operator<<(std::ostream &out, source_pos pos) { return out << pos.row << ',' << pos.col; } class source_loc { public: source_loc(source_pos begin, source_pos end, std::string name) noexcept : source_loc{begin, end, std::make_shared<std::string>(std::move(name))} {} source_loc(source_pos begin, source_pos end, std::shared_ptr<std::string> name) noexcept : begin_pos{begin}, end_pos{end}, source_name{name} {} source_pos begin(void) const noexcept { return begin_pos; } source_pos end(void) const noexcept { return end_pos; } const std::string &name(void) const noexcept { return *source_name; } source_loc with_pos(source_pos begin, source_pos end) const noexcept { return source_loc{begin, end, source_name}; } void print(std::ostream &out) const { out << *source_name << ':' << begin_pos << '-' << end_pos; } private: std::shared_ptr<std::string> source_name; source_pos begin_pos; source_pos end_pos; }; static std::ostream & operator<<(std::ostream &out, const source_loc &loc) { loc.print(out); return out; } } #endif /* !BFC_SOURCELOC_HPP */ <|endoftext|>
<commit_before>// Copyright 2014 Alessio Sclocco <[email protected]> // // 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 <iostream> #include <fstream> #include <exception> #include <string> #include <utility> #include <map> #include <iomanip> #include <cstring> #include <ArgumentList.hpp> #include <utils.hpp> int main(int argc, char * argv[]) { // DMs unsigned int nrDMs = 0; float firstDM = 0.0f; float stepDM = 0.0f; // Periods unsigned int nrPeriods = 0; unsigned int firstPeriod = 0; unsigned int stepPeriod = 0; // Sampling unsigned int nrSamplesPerSecond = 0; // I/O std::string outFilename; std::ifstream searchFile; std::ofstream outFile; // Data bool exclusive = false; bool * exclusionMapDM = 0; bool * exclusionMapP = 0; float percentile = 0; std::multimap< float, std::pair< unsigned int, unsigned int > > snrList; isa::utils::ArgumentList args(argc, argv); try { exclusive = args.getSwitch("-exclusive"); if ( exclusive ) { nrDMs = args.getSwitchArgument< unsigned int >("-dms"); nrPeriods = args.getSwitchArgument< unsigned int >("-periods"); } outFilename = args.getSwitchArgument< std::string >("-output"); firstDM = args.getSwitchArgument< float >("-dm_first"); stepDM = args.getSwitchArgument< float >("-dm_step"); firstPeriod = args.getSwitchArgument< unsigned int >("-period_first"); stepPeriod = args.getSwitchArgument< unsigned int >("-period_step"); nrSamplesPerSecond = args.getSwitchArgument< unsigned int >("-samples"); percentile = args.getSwitchArgument< float >("-percentile"); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << args.getName() << " [-exclusive] -output ... -dm_first ... -dm_step ... -period_first ... -period_step ... -samples ... -percentile ... input" << std::endl; std::cerr << "\t -exclusive -dms ... -periods ..." << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } // Read the SNR data try { while ( true ) { searchFile.open(args.getFirst< std::string >()); while ( ! searchFile.eof() ) { std::string temp; unsigned int splitPoint = 0; unsigned int DM = 0; unsigned int period = 0; float snr = 0.0f; std::getline(searchFile, temp); if ( ! std::isdigit(temp[0]) ) { continue; } splitPoint = temp.find(" "); period = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); DM = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); snr = isa::utils::castToType< std::string, float >(temp); snrList.insert(std::make_pair(snr, std::make_pair(DM, period))); } searchFile.close(); } } catch ( isa::utils::EmptyCommandLine & err ) { } // Print the percentile unsigned int lowerLimit = static_cast< unsigned int >((percentile * snrList.size()) / 100.0); unsigned int counter = snrList.size() - 1; if ( exclusive ) { exclusionMapDM = new bool [nrDMs]; std::memset(reinterpret_cast< void * >(exclusionMapDM, 0, nrDMs * sizeof(bool))); exclusionMapP = new bool [nrPeriods]; std::memset(reinterpret_cast< void * >(exclusionMapP, 0, nrDMs * sizeof(bool))); } outFile.open(outFilename); outFile << std::fixed; outFile << "# DMIndex DM periodIndex period snr" << std::endl; for ( std::multimap< float, std::pair< unsigned int, unsigned int> >::const_reverse_iterator item = snrList.crend(); counter >= lowerLimit; counter-- ) { ++item; if ( exclusive && (exclusionMapDM[(*item).second.first] || exclusionMapP[(*item).second.second]) ) { continue; } else if ( exclusionMapDM[(*item).second.first] || exclusionMapP[(*item).second.second] ) { exclusionMapDM[(*item).second.first] = true; exclusionMapP[(*item).second.second] = true; } outFile << std::setprecision(2); outFile << (*item).second.first << " " << firstDM + ((*item).second.first * stepDM) << " "; outFile << std::setprecision(6); outFile << (*item).second.second << " " << (firstPeriod + ((*item).second.second * stepPeriod)) / static_cast< float >(nrSamplesPerSecond) << " "; outFile << (*item).first << std::endl; } delete [] exclusionMapDM; delete [] exclusionMapP; outFile.close(); return 0; } <commit_msg>Typo.<commit_after>// Copyright 2014 Alessio Sclocco <[email protected]> // // 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 <iostream> #include <fstream> #include <exception> #include <string> #include <utility> #include <map> #include <iomanip> #include <cstring> #include <ArgumentList.hpp> #include <utils.hpp> int main(int argc, char * argv[]) { // DMs unsigned int nrDMs = 0; float firstDM = 0.0f; float stepDM = 0.0f; // Periods unsigned int nrPeriods = 0; unsigned int firstPeriod = 0; unsigned int stepPeriod = 0; // Sampling unsigned int nrSamplesPerSecond = 0; // I/O std::string outFilename; std::ifstream searchFile; std::ofstream outFile; // Data bool exclusive = false; bool * exclusionMapDM = 0; bool * exclusionMapP = 0; float percentile = 0; std::multimap< float, std::pair< unsigned int, unsigned int > > snrList; isa::utils::ArgumentList args(argc, argv); try { exclusive = args.getSwitch("-exclusive"); if ( exclusive ) { nrDMs = args.getSwitchArgument< unsigned int >("-dms"); nrPeriods = args.getSwitchArgument< unsigned int >("-periods"); } outFilename = args.getSwitchArgument< std::string >("-output"); firstDM = args.getSwitchArgument< float >("-dm_first"); stepDM = args.getSwitchArgument< float >("-dm_step"); firstPeriod = args.getSwitchArgument< unsigned int >("-period_first"); stepPeriod = args.getSwitchArgument< unsigned int >("-period_step"); nrSamplesPerSecond = args.getSwitchArgument< unsigned int >("-samples"); percentile = args.getSwitchArgument< float >("-percentile"); } catch ( isa::utils::EmptyCommandLine & err ) { std::cerr << args.getName() << " [-exclusive] -output ... -dm_first ... -dm_step ... -period_first ... -period_step ... -samples ... -percentile ... input" << std::endl; std::cerr << "\t -exclusive -dms ... -periods ..." << std::endl; return 1; } catch ( std::exception & err ) { std::cerr << err.what() << std::endl; return 1; } // Read the SNR data try { while ( true ) { searchFile.open(args.getFirst< std::string >()); while ( ! searchFile.eof() ) { std::string temp; unsigned int splitPoint = 0; unsigned int DM = 0; unsigned int period = 0; float snr = 0.0f; std::getline(searchFile, temp); if ( ! std::isdigit(temp[0]) ) { continue; } splitPoint = temp.find(" "); period = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); DM = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint)); temp = temp.substr(splitPoint + 1); splitPoint = temp.find(" "); snr = isa::utils::castToType< std::string, float >(temp); snrList.insert(std::make_pair(snr, std::make_pair(DM, period))); } searchFile.close(); } } catch ( isa::utils::EmptyCommandLine & err ) { } // Print the percentile unsigned int lowerLimit = static_cast< unsigned int >((percentile * snrList.size()) / 100.0); unsigned int counter = snrList.size() - 1; if ( exclusive ) { exclusionMapDM = new bool [nrDMs]; std::memset(reinterpret_cast< void * >(exclusionMapDM), 0, nrDMs * sizeof(bool)); exclusionMapP = new bool [nrPeriods]; std::memset(reinterpret_cast< void * >(exclusionMapP), 0, nrDMs * sizeof(bool)); } outFile.open(outFilename); outFile << std::fixed; outFile << "# DMIndex DM periodIndex period snr" << std::endl; for ( std::multimap< float, std::pair< unsigned int, unsigned int> >::const_reverse_iterator item = snrList.crend(); counter >= lowerLimit; counter-- ) { ++item; if ( exclusive && (exclusionMapDM[(*item).second.first] || exclusionMapP[(*item).second.second]) ) { continue; } else if ( exclusionMapDM[(*item).second.first] || exclusionMapP[(*item).second.second] ) { exclusionMapDM[(*item).second.first] = true; exclusionMapP[(*item).second.second] = true; } outFile << std::setprecision(2); outFile << (*item).second.first << " " << firstDM + ((*item).second.first * stepDM) << " "; outFile << std::setprecision(6); outFile << (*item).second.second << " " << (firstPeriod + ((*item).second.second * stepPeriod)) / static_cast< float >(nrSamplesPerSecond) << " "; outFile << (*item).first << std::endl; } delete [] exclusionMapDM; delete [] exclusionMapP; outFile.close(); return 0; } <|endoftext|>
<commit_before>/*********************************************************************** created: Wed May 21 2014 author: Timotei Dolean <[email protected]> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/views/ItemModel.h" namespace CEGUI { //----------------------------------------------------------------------------// const String ItemModel::EventChildrenWillBeAdded("ChildrenWillBeAdded"); const String ItemModel::EventChildrenAdded("ChildrenAdded"); const String ItemModel::EventChildrenWillBeRemoved("ChildrenWillBeRemoved"); const String ItemModel::EventChildrenRemoved("ChildrenRemoved"); const String ItemModel::EventChildrenDataWillChange; const String ItemModel::EventChildrenDataChanged("ChildrenDataChanged"); //----------------------------------------------------------------------------// std::ostream& operator<< (std::ostream& os, const ModelIndex& arg) { return os << "CEGUI::ModelIndex(" << arg.d_modelData << ")"; } //----------------------------------------------------------------------------// ModelEventArgs::ModelEventArgs(ItemModel* item_model, ModelIndex parent_index, size_t start_id, size_t count /*= 1*/) : d_itemModel(item_model), d_parentIndex(parent_index), d_startId(start_id), d_count(count) { } //----------------------------------------------------------------------------// ModelIndex::ModelIndex(void* model_data /*= 0*/) : d_modelData(model_data) { } //----------------------------------------------------------------------------// ItemModel::~ItemModel() { } //----------------------------------------------------------------------------// void ItemModel::notifyChildrenWillBeAdded(ModelIndex parent_index, size_t start_id, size_t count) { ModelEventArgs args(this, parent_index, start_id, count); fireEvent(EventChildrenWillBeAdded, args); } //----------------------------------------------------------------------------// void ItemModel::notifyChildrenAdded(ModelIndex parent_index, size_t start_id, size_t count) { ModelEventArgs args(this, parent_index, start_id, count); fireEvent(EventChildrenAdded, args); } //----------------------------------------------------------------------------// void ItemModel::notifyChildrenWillBeRemoved(ModelIndex parent_index, size_t start_id, size_t count) { ModelEventArgs args(this, parent_index, start_id, count); fireEvent(EventChildrenWillBeRemoved, args); } //----------------------------------------------------------------------------// void ItemModel::notifyChildrenRemoved(ModelIndex parent_index, size_t start_id, size_t count) { ModelEventArgs args(this, parent_index, start_id, count); fireEvent(EventChildrenRemoved, args); } //----------------------------------------------------------------------------// void ItemModel::notifyChildrenDataWillChange(ModelIndex parent_index, size_t start_id, size_t count) { ModelEventArgs args(this, parent_index, start_id, count); fireEvent(EventChildrenDataWillChange, args); } //----------------------------------------------------------------------------// void ItemModel::notifyChildrenDataChanged(ModelIndex parent_index, size_t start_id, size_t count) { ModelEventArgs args(this, parent_index, start_id, count); fireEvent(EventChildrenDataChanged, args); } //----------------------------------------------------------------------------// bool ItemModel::areIndicesEqual(const ModelIndex& index1, const ModelIndex& index2) const { return compareIndices(index1, index2) == 0; } } <commit_msg>Add missing <ostream> include<commit_after>/*********************************************************************** created: Wed May 21 2014 author: Timotei Dolean <[email protected]> *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/views/ItemModel.h" #include <ostream> namespace CEGUI { //----------------------------------------------------------------------------// const String ItemModel::EventChildrenWillBeAdded("ChildrenWillBeAdded"); const String ItemModel::EventChildrenAdded("ChildrenAdded"); const String ItemModel::EventChildrenWillBeRemoved("ChildrenWillBeRemoved"); const String ItemModel::EventChildrenRemoved("ChildrenRemoved"); const String ItemModel::EventChildrenDataWillChange; const String ItemModel::EventChildrenDataChanged("ChildrenDataChanged"); //----------------------------------------------------------------------------// std::ostream& operator<< (std::ostream& os, const ModelIndex& arg) { return os << "CEGUI::ModelIndex(" << arg.d_modelData << ")"; } //----------------------------------------------------------------------------// ModelEventArgs::ModelEventArgs(ItemModel* item_model, ModelIndex parent_index, size_t start_id, size_t count /*= 1*/) : d_itemModel(item_model), d_parentIndex(parent_index), d_startId(start_id), d_count(count) { } //----------------------------------------------------------------------------// ModelIndex::ModelIndex(void* model_data /*= 0*/) : d_modelData(model_data) { } //----------------------------------------------------------------------------// ItemModel::~ItemModel() { } //----------------------------------------------------------------------------// void ItemModel::notifyChildrenWillBeAdded(ModelIndex parent_index, size_t start_id, size_t count) { ModelEventArgs args(this, parent_index, start_id, count); fireEvent(EventChildrenWillBeAdded, args); } //----------------------------------------------------------------------------// void ItemModel::notifyChildrenAdded(ModelIndex parent_index, size_t start_id, size_t count) { ModelEventArgs args(this, parent_index, start_id, count); fireEvent(EventChildrenAdded, args); } //----------------------------------------------------------------------------// void ItemModel::notifyChildrenWillBeRemoved(ModelIndex parent_index, size_t start_id, size_t count) { ModelEventArgs args(this, parent_index, start_id, count); fireEvent(EventChildrenWillBeRemoved, args); } //----------------------------------------------------------------------------// void ItemModel::notifyChildrenRemoved(ModelIndex parent_index, size_t start_id, size_t count) { ModelEventArgs args(this, parent_index, start_id, count); fireEvent(EventChildrenRemoved, args); } //----------------------------------------------------------------------------// void ItemModel::notifyChildrenDataWillChange(ModelIndex parent_index, size_t start_id, size_t count) { ModelEventArgs args(this, parent_index, start_id, count); fireEvent(EventChildrenDataWillChange, args); } //----------------------------------------------------------------------------// void ItemModel::notifyChildrenDataChanged(ModelIndex parent_index, size_t start_id, size_t count) { ModelEventArgs args(this, parent_index, start_id, count); fireEvent(EventChildrenDataChanged, args); } //----------------------------------------------------------------------------// bool ItemModel::areIndicesEqual(const ModelIndex& index1, const ModelIndex& index2) const { return compareIndices(index1, index2) == 0; } } <|endoftext|>
<commit_before>/*********************************************************************** filename: CEGUISpinner.cpp created: 3/2/2005 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/widgets/Spinner.h" #include "CEGUI/widgets/PushButton.h" #include "CEGUI/widgets/Editbox.h" #include "CEGUI/Exceptions.h" #include "CEGUI/WindowManager.h" #include <stdio.h> #include <sstream> #include <iomanip> // Start of CEGUI namespace section namespace CEGUI { const String Spinner::WidgetTypeName("CEGUI/Spinner"); ////////////////////////////////////////////////////////////////////////// // event strings const String Spinner::EventNamespace("Spinner"); const String Spinner::EventValueChanged("ValueChanged"); const String Spinner::EventStepChanged("StepChanged"); const String Spinner::EventMaximumValueChanged("MaximumValueChanged"); const String Spinner::EventMinimumValueChanged("MinimumValueChanged"); const String Spinner::EventTextInputModeChanged("TextInputModeChanged"); // Validator strings const String Spinner::FloatValidator("-?\\d*\\.?\\d*"); const String Spinner::IntegerValidator("-?\\d*"); const String Spinner::HexValidator("[0-9a-fA-F]*"); const String Spinner::OctalValidator("[0-7]*"); // component widget name strings const String Spinner::EditboxName( "__auto_editbox__" ); const String Spinner::IncreaseButtonName( "__auto_incbtn__" ); const String Spinner::DecreaseButtonName( "__auto_decbtn__" ); ////////////////////////////////////////////////////////////////////////// Spinner::Spinner(const String& type, const String& name) : Window(type, name), d_stepSize(1.0f), d_currentValue(1.0f), d_maxValue(32767.0f), d_minValue(-32768.0f), d_inputMode((TextInputMode)-1) { addSpinnerProperties(); } Spinner::~Spinner(void) { // Nothing to do here. } void Spinner::initialiseComponents(void) { // get all the component widgets PushButton* increaseButton = getIncreaseButton(); PushButton* decreaseButton = getDecreaseButton(); Editbox* editbox = getEditbox(); // setup component controls increaseButton->setPointerAutoRepeatEnabled(true); decreaseButton->setPointerAutoRepeatEnabled(true); // perform event subscriptions. increaseButton->subscribeEvent(Window::EventPointerPressHold, Event::Subscriber(&Spinner::handleIncreaseButton, this)); decreaseButton->subscribeEvent(Window::EventPointerPressHold, Event::Subscriber(&Spinner::handleDecreaseButton, this)); editbox->subscribeEvent(Window::EventTextChanged, Event::Subscriber(&Spinner::handleEditTextChange, this)); // final initialisation setTextInputMode(Integer); setCurrentValue(0.0f); performChildWindowLayout(); } double Spinner::getCurrentValue(void) const { return d_currentValue; } double Spinner::getStepSize(void) const { return d_stepSize; } double Spinner::getMaximumValue(void) const { return d_maxValue; } double Spinner::getMinimumValue(void) const { return d_minValue; } Spinner::TextInputMode Spinner::getTextInputMode(void) const { return d_inputMode; } void Spinner::setCurrentValue(double value) { if (value != d_currentValue) { // limit input value to within valid range for spinner value = ceguimax(ceguimin(value, d_maxValue), d_minValue); d_currentValue = value; WindowEventArgs args(this); onValueChanged(args); } } void Spinner::setStepSize(double step) { if (step != d_stepSize) { d_stepSize = step; WindowEventArgs args(this); onStepChanged(args); } } void Spinner::setMaximumValue(double maxValue) { if (maxValue != d_maxValue) { d_maxValue = maxValue; WindowEventArgs args(this); onMaximumValueChanged(args); } } void Spinner::setMinimumValue(double minVaue) { if (minVaue != d_minValue) { d_minValue = minVaue; WindowEventArgs args(this); onMinimumValueChanged(args); } } void Spinner::setTextInputMode(TextInputMode mode) { if (mode != d_inputMode) { switch (mode) { case FloatingPoint: getEditbox()->setValidationString(FloatValidator); break; case Integer: getEditbox()->setValidationString(IntegerValidator); break; case Hexadecimal: getEditbox()->setValidationString(HexValidator); break; case Octal: getEditbox()->setValidationString(OctalValidator); break; default: CEGUI_THROW(InvalidRequestException( "An unknown TextInputMode was specified.")); } d_inputMode = mode; WindowEventArgs args(this); onTextInputModeChanged(args); } } void Spinner::addSpinnerProperties(void) { const String& propertyOrigin = WidgetTypeName; CEGUI_DEFINE_PROPERTY(Spinner, double, "CurrentValue", "Property to get/set the current value of the spinner. Value is a float.", &Spinner::setCurrentValue, &Spinner::getCurrentValue, 0.0f ); CEGUI_DEFINE_PROPERTY(Spinner, double, "StepSize", "Property to get/set the step size of the spinner. Value is a float.", &Spinner::setStepSize, &Spinner::getStepSize, 1.0f ); CEGUI_DEFINE_PROPERTY(Spinner, double, "MinimumValue", "Property to get/set the minimum value setting of the spinner. Value is a float.", &Spinner::setMinimumValue, &Spinner::getMinimumValue, -32768.000000f ); CEGUI_DEFINE_PROPERTY(Spinner, double, "MaximumValue", "Property to get/set the maximum value setting of the spinner. Value is a float.", &Spinner::setMaximumValue, &Spinner::getMaximumValue, 32767.000000f ); CEGUI_DEFINE_PROPERTY(Spinner, Spinner::TextInputMode, "TextInputMode", "Property to get/set the TextInputMode setting for the spinner. Value is \"FloatingPoint\", \"Integer\", \"Hexadecimal\", or \"Octal\".", &Spinner::setTextInputMode, &Spinner::getTextInputMode, Spinner::Integer ); } double Spinner::getValueFromText(void) const { String tmpTxt(getEditbox()->getText()); // handle empty and lone '-' or '.' cases if (tmpTxt.empty() || (tmpTxt == "-") || (tmpTxt == ".")) { return 0.0f; } int res, tmp; uint utmp; double val; switch (d_inputMode) { case FloatingPoint: res = sscanf(tmpTxt.c_str(), "%lf", &val); break; case Integer: res = sscanf(tmpTxt.c_str(), "%d", &tmp); val = static_cast<double>(tmp); break; case Hexadecimal: res = sscanf(tmpTxt.c_str(), "%x", &utmp); val = static_cast<double>(utmp); break; case Octal: res = sscanf(tmpTxt.c_str(), "%o", &utmp); val = static_cast<double>(utmp); break; default: CEGUI_THROW(InvalidRequestException( "An unknown TextInputMode was encountered.")); } if (res) { return val; } CEGUI_THROW(InvalidRequestException( "The string '" + getEditbox()->getText() + "' can not be converted to numerical representation.")); } String Spinner::getTextFromValue(void) const { std::stringstream tmp; switch (d_inputMode) { case FloatingPoint: return CEGUI::PropertyHelper<float>::toString( static_cast<float>(d_currentValue) ); break; case Integer: tmp << static_cast<int>(d_currentValue); break; case Hexadecimal: tmp << std::hex << std::uppercase << static_cast<int>(d_currentValue); break; case Octal: tmp << std::oct << static_cast<int>(d_currentValue); break; default: CEGUI_THROW(InvalidRequestException( "An unknown TextInputMode was encountered.")); } return String(tmp.str().c_str()); } void Spinner::onFontChanged(WindowEventArgs& e) { // Propagate to children getEditbox()->setFont(getFont()); // Call base class handler Window::onFontChanged(e); } void Spinner::onTextChanged(WindowEventArgs& e) { Editbox* editbox = getEditbox(); // update only if needed if (editbox->getText() != getText()) { // done before doing base class processing so event subscribers see // 'updated' version. editbox->setText(getText()); ++e.handled; Window::onTextChanged(e); } } void Spinner::onActivated(ActivationEventArgs& e) { if (!isActive()) { Window::onActivated(e); Editbox* editbox = getEditbox(); if (!editbox->isActive()) { editbox->activate(); } } } void Spinner::onValueChanged(WindowEventArgs& e) { Editbox* editbox = getEditbox(); // mute to save doing unnecessary events work. bool wasMuted = editbox->isMuted(); editbox->setMutedState(true); // Update text with new value. // (allow empty and '-' cases to equal 0 with no text change required) if (!(d_currentValue == 0 && (editbox->getText().empty() || editbox->getText() == "-"))) { editbox->setText(getTextFromValue()); } // restore previous mute state. editbox->setMutedState(wasMuted); fireEvent(EventValueChanged, e, EventNamespace); } void Spinner::onStepChanged(WindowEventArgs& e) { fireEvent(EventStepChanged, e, EventNamespace); } void Spinner::onMaximumValueChanged(WindowEventArgs& e) { fireEvent(EventMaximumValueChanged, e, EventNamespace); if (d_currentValue > d_maxValue) { setCurrentValue(d_maxValue); } } void Spinner::onMinimumValueChanged(WindowEventArgs& e) { fireEvent(EventMinimumValueChanged, e, EventNamespace); if (d_currentValue < d_minValue) { setCurrentValue(d_minValue); } } void Spinner::onTextInputModeChanged(WindowEventArgs& e) { Editbox* editbox = getEditbox(); // update edit box text to reflect new mode. // mute to save doing unnecessary events work. bool wasMuted = editbox->isMuted(); editbox->setMutedState(true); // Update text with new value. editbox->setText(getTextFromValue()); // restore previous mute state. editbox->setMutedState(wasMuted); fireEvent(EventTextInputModeChanged, e, EventNamespace); } bool Spinner::handleIncreaseButton(const EventArgs& e) { if (((const PointerEventArgs&)e).source == PS_Left) { setCurrentValue(d_currentValue + d_stepSize); return true; } return false; } bool Spinner::handleDecreaseButton(const EventArgs& e) { if (((const PointerEventArgs&)e).source == PS_Left) { setCurrentValue(d_currentValue - d_stepSize); return true; } return false; } bool Spinner::handleEditTextChange(const EventArgs&) { // set this windows text to match setText(getEditbox()->getText()); // update value setCurrentValue(getValueFromText()); return true; } PushButton* Spinner::getIncreaseButton() const { return static_cast<PushButton*>(getChild(IncreaseButtonName)); } PushButton* Spinner::getDecreaseButton() const { return static_cast<PushButton*>(getChild(DecreaseButtonName)); } Editbox* Spinner::getEditbox() const { return static_cast<Editbox*>(getChild(EditboxName)); } ////////////////////////////////////////////////////////////////////////// } // End of CEGUI namespace section <commit_msg>MOD: Fixing Spinner window text update on value change<commit_after>/*********************************************************************** filename: CEGUISpinner.cpp created: 3/2/2005 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/widgets/Spinner.h" #include "CEGUI/widgets/PushButton.h" #include "CEGUI/widgets/Editbox.h" #include "CEGUI/Exceptions.h" #include "CEGUI/WindowManager.h" #include <stdio.h> #include <sstream> #include <iomanip> // Start of CEGUI namespace section namespace CEGUI { const String Spinner::WidgetTypeName("CEGUI/Spinner"); ////////////////////////////////////////////////////////////////////////// // event strings const String Spinner::EventNamespace("Spinner"); const String Spinner::EventValueChanged("ValueChanged"); const String Spinner::EventStepChanged("StepChanged"); const String Spinner::EventMaximumValueChanged("MaximumValueChanged"); const String Spinner::EventMinimumValueChanged("MinimumValueChanged"); const String Spinner::EventTextInputModeChanged("TextInputModeChanged"); // Validator strings const String Spinner::FloatValidator("-?\\d*\\.?\\d*"); const String Spinner::IntegerValidator("-?\\d*"); const String Spinner::HexValidator("[0-9a-fA-F]*"); const String Spinner::OctalValidator("[0-7]*"); // component widget name strings const String Spinner::EditboxName( "__auto_editbox__" ); const String Spinner::IncreaseButtonName( "__auto_incbtn__" ); const String Spinner::DecreaseButtonName( "__auto_decbtn__" ); ////////////////////////////////////////////////////////////////////////// Spinner::Spinner(const String& type, const String& name) : Window(type, name), d_stepSize(1.0f), d_currentValue(1.0f), d_maxValue(32767.0f), d_minValue(-32768.0f), d_inputMode((TextInputMode)-1) { addSpinnerProperties(); } Spinner::~Spinner(void) { // Nothing to do here. } void Spinner::initialiseComponents(void) { // get all the component widgets PushButton* increaseButton = getIncreaseButton(); PushButton* decreaseButton = getDecreaseButton(); Editbox* editbox = getEditbox(); // setup component controls increaseButton->setPointerAutoRepeatEnabled(true); decreaseButton->setPointerAutoRepeatEnabled(true); // perform event subscriptions. increaseButton->subscribeEvent(Window::EventPointerPressHold, Event::Subscriber(&Spinner::handleIncreaseButton, this)); decreaseButton->subscribeEvent(Window::EventPointerPressHold, Event::Subscriber(&Spinner::handleDecreaseButton, this)); editbox->subscribeEvent(Window::EventTextChanged, Event::Subscriber(&Spinner::handleEditTextChange, this)); // final initialisation setTextInputMode(Integer); setCurrentValue(0.0f); performChildWindowLayout(); } double Spinner::getCurrentValue(void) const { return d_currentValue; } double Spinner::getStepSize(void) const { return d_stepSize; } double Spinner::getMaximumValue(void) const { return d_maxValue; } double Spinner::getMinimumValue(void) const { return d_minValue; } Spinner::TextInputMode Spinner::getTextInputMode(void) const { return d_inputMode; } void Spinner::setCurrentValue(double value) { if (value != d_currentValue) { // limit input value to within valid range for spinner value = ceguimax(ceguimin(value, d_maxValue), d_minValue); d_currentValue = value; WindowEventArgs args(this); onValueChanged(args); } } void Spinner::setStepSize(double step) { if (step != d_stepSize) { d_stepSize = step; WindowEventArgs args(this); onStepChanged(args); } } void Spinner::setMaximumValue(double maxValue) { if (maxValue != d_maxValue) { d_maxValue = maxValue; WindowEventArgs args(this); onMaximumValueChanged(args); } } void Spinner::setMinimumValue(double minVaue) { if (minVaue != d_minValue) { d_minValue = minVaue; WindowEventArgs args(this); onMinimumValueChanged(args); } } void Spinner::setTextInputMode(TextInputMode mode) { if (mode != d_inputMode) { switch (mode) { case FloatingPoint: getEditbox()->setValidationString(FloatValidator); break; case Integer: getEditbox()->setValidationString(IntegerValidator); break; case Hexadecimal: getEditbox()->setValidationString(HexValidator); break; case Octal: getEditbox()->setValidationString(OctalValidator); break; default: CEGUI_THROW(InvalidRequestException( "An unknown TextInputMode was specified.")); } d_inputMode = mode; WindowEventArgs args(this); onTextInputModeChanged(args); } } void Spinner::addSpinnerProperties(void) { const String& propertyOrigin = WidgetTypeName; CEGUI_DEFINE_PROPERTY(Spinner, double, "CurrentValue", "Property to get/set the current value of the spinner. Value is a float.", &Spinner::setCurrentValue, &Spinner::getCurrentValue, 0.0f ); CEGUI_DEFINE_PROPERTY(Spinner, double, "StepSize", "Property to get/set the step size of the spinner. Value is a float.", &Spinner::setStepSize, &Spinner::getStepSize, 1.0f ); CEGUI_DEFINE_PROPERTY(Spinner, double, "MinimumValue", "Property to get/set the minimum value setting of the spinner. Value is a float.", &Spinner::setMinimumValue, &Spinner::getMinimumValue, -32768.000000f ); CEGUI_DEFINE_PROPERTY(Spinner, double, "MaximumValue", "Property to get/set the maximum value setting of the spinner. Value is a float.", &Spinner::setMaximumValue, &Spinner::getMaximumValue, 32767.000000f ); CEGUI_DEFINE_PROPERTY(Spinner, Spinner::TextInputMode, "TextInputMode", "Property to get/set the TextInputMode setting for the spinner. Value is \"FloatingPoint\", \"Integer\", \"Hexadecimal\", or \"Octal\".", &Spinner::setTextInputMode, &Spinner::getTextInputMode, Spinner::Integer ); } double Spinner::getValueFromText(void) const { String tmpTxt(getEditbox()->getText()); // handle empty and lone '-' or '.' cases if (tmpTxt.empty() || (tmpTxt == "-") || (tmpTxt == ".")) { return 0.0f; } int res, tmp; uint utmp; double val; switch (d_inputMode) { case FloatingPoint: res = sscanf(tmpTxt.c_str(), "%lf", &val); break; case Integer: res = sscanf(tmpTxt.c_str(), "%d", &tmp); val = static_cast<double>(tmp); break; case Hexadecimal: res = sscanf(tmpTxt.c_str(), "%x", &utmp); val = static_cast<double>(utmp); break; case Octal: res = sscanf(tmpTxt.c_str(), "%o", &utmp); val = static_cast<double>(utmp); break; default: CEGUI_THROW(InvalidRequestException( "An unknown TextInputMode was encountered.")); } if (res) { return val; } CEGUI_THROW(InvalidRequestException( "The string '" + getEditbox()->getText() + "' can not be converted to numerical representation.")); } String Spinner::getTextFromValue(void) const { std::stringstream tmp; switch (d_inputMode) { case FloatingPoint: return CEGUI::PropertyHelper<float>::toString( static_cast<float>(d_currentValue) ); break; case Integer: tmp << static_cast<int>(d_currentValue); break; case Hexadecimal: tmp << std::hex << std::uppercase << static_cast<int>(d_currentValue); break; case Octal: tmp << std::oct << static_cast<int>(d_currentValue); break; default: CEGUI_THROW(InvalidRequestException( "An unknown TextInputMode was encountered.")); } return String(tmp.str().c_str()); } void Spinner::onFontChanged(WindowEventArgs& e) { // Propagate to children getEditbox()->setFont(getFont()); // Call base class handler Window::onFontChanged(e); } void Spinner::onTextChanged(WindowEventArgs& e) { Editbox* editbox = getEditbox(); // update only if needed if (editbox->getText() != getText()) { // done before doing base class processing so event subscribers see // 'updated' version. editbox->setText(getText()); ++e.handled; Window::onTextChanged(e); } } void Spinner::onActivated(ActivationEventArgs& e) { if (!isActive()) { Window::onActivated(e); Editbox* editbox = getEditbox(); if (!editbox->isActive()) { editbox->activate(); } } } void Spinner::onValueChanged(WindowEventArgs& e) { Editbox* editbox = getEditbox(); // mute to save doing unnecessary events work. bool wasMuted = editbox->isMuted(); editbox->setMutedState(true); // Update editbox and spinner text with new value. // (allow empty and '-' cases to equal 0 with no text change required) if (!(d_currentValue == 0 && (editbox->getText().empty() || editbox->getText() == "-"))) { const CEGUI::String& valueString = getTextFromValue(); editbox->setText(valueString); setText(valueString); } // restore previous mute state. editbox->setMutedState(wasMuted); fireEvent(EventValueChanged, e, EventNamespace); } void Spinner::onStepChanged(WindowEventArgs& e) { fireEvent(EventStepChanged, e, EventNamespace); } void Spinner::onMaximumValueChanged(WindowEventArgs& e) { fireEvent(EventMaximumValueChanged, e, EventNamespace); if (d_currentValue > d_maxValue) { setCurrentValue(d_maxValue); } } void Spinner::onMinimumValueChanged(WindowEventArgs& e) { fireEvent(EventMinimumValueChanged, e, EventNamespace); if (d_currentValue < d_minValue) { setCurrentValue(d_minValue); } } void Spinner::onTextInputModeChanged(WindowEventArgs& e) { Editbox* editbox = getEditbox(); // update edit box text to reflect new mode. // mute to save doing unnecessary events work. bool wasMuted = editbox->isMuted(); editbox->setMutedState(true); // Update text with new value. editbox->setText(getTextFromValue()); // restore previous mute state. editbox->setMutedState(wasMuted); fireEvent(EventTextInputModeChanged, e, EventNamespace); } bool Spinner::handleIncreaseButton(const EventArgs& e) { if (((const PointerEventArgs&)e).source == PS_Left) { setCurrentValue(d_currentValue + d_stepSize); return true; } return false; } bool Spinner::handleDecreaseButton(const EventArgs& e) { if (((const PointerEventArgs&)e).source == PS_Left) { setCurrentValue(d_currentValue - d_stepSize); return true; } return false; } bool Spinner::handleEditTextChange(const EventArgs&) { // set this windows text to match setText(getEditbox()->getText()); // update value setCurrentValue(getValueFromText()); return true; } PushButton* Spinner::getIncreaseButton() const { return static_cast<PushButton*>(getChild(IncreaseButtonName)); } PushButton* Spinner::getDecreaseButton() const { return static_cast<PushButton*>(getChild(DecreaseButtonName)); } Editbox* Spinner::getEditbox() const { return static_cast<Editbox*>(getChild(EditboxName)); } ////////////////////////////////////////////////////////////////////////// } // End of CEGUI namespace section <|endoftext|>
<commit_before>/** @file openssl_utils.cc - Interaction with openssl constructs @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <cstring> #include <cerrno> #include <cmath> #include <unistd.h> #include <fcntl.h> #include <pthread.h> #include <sys/types.h> #include <sys/stat.h> #include <openssl/rand.h> #include <netinet/in.h> #include <arpa/inet.h> #include <ts/ts.h> #include "ssl_utils.h" #include "Config.h" #include "session_process.h" #include "common.h" static int ssl_new_session(TSSslSessionID &sid) { // Encode ID std::string encoded_id; int ret = encode_id(sid.bytes, sid.len, encoded_id); if (ret < 0) { TSError("Encoded id failed."); return 0; } std::string redis_channel = ssl_param.cluster_name + "." + encoded_id; int session_ret_len = SSL_SESSION_MAX_DER; char session_data[SSL_SESSION_MAX_DER]; const auto buffer_length = TSSslSessionGetBuffer(&sid, session_data, &session_ret_len); if (buffer_length == 0) { TSError("Failed to find a session buffer."); return 0; } else if (buffer_length > session_ret_len) { TSError("Session data is too large. Its size is: %d but our max buffer size is: %d.", buffer_length, SSL_SESSION_MAX_DER); return 0; } std::string encrypted_data; ret = encrypt_session(session_data, session_ret_len, (unsigned char *)get_key_ptr(), get_key_length(), encrypted_data); if (ret < 0) { TSError("Encrypt_session failed."); return 0; } ssl_param.pub->publish(redis_channel, encrypted_data); TSDebug(PLUGIN, "Create new session id: %s encoded: %s channel: %s", encoded_id.c_str(), encrypted_data.c_str(), redis_channel.c_str()); return 0; } static int ssl_access_session(TSSslSessionID &sid) { return 0; } static int ssl_del_session(TSSslSessionID &sid) { std::string encoded_id; int ret = encode_id(sid.bytes, sid.len, encoded_id); if (!ret) { TSDebug(PLUGIN, "Session is deleted. id: %s", encoded_id.c_str()); } return 0; } int SSL_session_callback(TSCont contp, TSEvent event, void *edata) { TSDebug(PLUGIN, "SSL_session_callback event: %d", event); TSSslSessionID *sessionid = reinterpret_cast<TSSslSessionID *>(edata); switch (event) { case TS_EVENT_SSL_SESSION_NEW: ssl_new_session(*sessionid); break; case TS_EVENT_SSL_SESSION_REMOVE: ssl_del_session(*sessionid); break; case TS_EVENT_SSL_SESSION_GET: ssl_access_session(*sessionid); break; default: break; } return 0; } <commit_msg>TLS Session Reuse: Downgrade noisy log to debug (#7344)<commit_after>/** @file openssl_utils.cc - Interaction with openssl constructs @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <cstring> #include <cerrno> #include <cmath> #include <unistd.h> #include <fcntl.h> #include <pthread.h> #include <sys/types.h> #include <sys/stat.h> #include <openssl/rand.h> #include <netinet/in.h> #include <arpa/inet.h> #include <ts/ts.h> #include "ssl_utils.h" #include "Config.h" #include "session_process.h" #include "common.h" static int ssl_new_session(TSSslSessionID &sid) { // Encode ID std::string encoded_id; int ret = encode_id(sid.bytes, sid.len, encoded_id); if (ret < 0) { TSError("Encoded id failed."); return 0; } std::string redis_channel = ssl_param.cluster_name + "." + encoded_id; int session_ret_len = SSL_SESSION_MAX_DER; char session_data[SSL_SESSION_MAX_DER]; const auto buffer_length = TSSslSessionGetBuffer(&sid, session_data, &session_ret_len); if (buffer_length == 0) { TSDebug(PLUGIN, "Failed to find a session buffer."); return 0; } else if (buffer_length > session_ret_len) { TSError("Session data is too large. Its size is: %d but our max buffer size is: %d.", buffer_length, SSL_SESSION_MAX_DER); return 0; } std::string encrypted_data; ret = encrypt_session(session_data, session_ret_len, (unsigned char *)get_key_ptr(), get_key_length(), encrypted_data); if (ret < 0) { TSError("Encrypt_session failed."); return 0; } ssl_param.pub->publish(redis_channel, encrypted_data); TSDebug(PLUGIN, "Create new session id: %s encoded: %s channel: %s", encoded_id.c_str(), encrypted_data.c_str(), redis_channel.c_str()); return 0; } static int ssl_access_session(TSSslSessionID &sid) { return 0; } static int ssl_del_session(TSSslSessionID &sid) { std::string encoded_id; int ret = encode_id(sid.bytes, sid.len, encoded_id); if (!ret) { TSDebug(PLUGIN, "Session is deleted. id: %s", encoded_id.c_str()); } return 0; } int SSL_session_callback(TSCont contp, TSEvent event, void *edata) { TSDebug(PLUGIN, "SSL_session_callback event: %d", event); TSSslSessionID *sessionid = reinterpret_cast<TSSslSessionID *>(edata); switch (event) { case TS_EVENT_SSL_SESSION_NEW: ssl_new_session(*sessionid); break; case TS_EVENT_SSL_SESSION_REMOVE: ssl_del_session(*sessionid); break; case TS_EVENT_SSL_SESSION_GET: ssl_access_session(*sessionid); break; default: break; } return 0; } <|endoftext|>
<commit_before>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2012 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under 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. Author : Moritz Dannhauer Last modification : March 16 2014 ToDo: Padding is always enabled because of exit() in cleaver lib */ ///TODO: fix include path to remove Externals/ part #include <Externals/cleaver/lib/FloatField.h> #include <Externals/cleaver/lib/Cleaver.h> #include <Externals/cleaver/lib/InverseField.h> #include <Externals/cleaver/lib/PaddedVolume.h> #include <Externals/cleaver/lib/Volume.h> #include <Core/Algorithms/Base/AlgorithmPreconditions.h> #include <Core/Algorithms/Field/InterfaceWithCleaverAlgorithm.h> #include <Core/Algorithms/Base/AlgorithmVariableNames.h> #include <Core/GeometryPrimitives/Vector.h> #include <Core/Datatypes/Legacy/Field/Field.h> #include <Core/Datatypes/Legacy/Field/VField.h> #include <Core/Datatypes/Legacy/Field/VMesh.h> #include <Core/Datatypes/Legacy/Field/FieldInformation.h> #include <iostream> #include <Core/GeometryPrimitives/Point.h> #include <Core/Utils/StringUtil.h> #include <boost/scoped_ptr.hpp> #include <Core/Logging/Log.h> using namespace SCIRun::Core::Algorithms; using namespace SCIRun::Core::Algorithms::Fields; using namespace SCIRun::Core::Geometry; using namespace SCIRun; using namespace SCIRun::Core; using namespace SCIRun::Core::Logging; AlgorithmParameterName InterfaceWithCleaverAlgorithm::Verbose("VerboseCheckBox"); AlgorithmParameterName InterfaceWithCleaverAlgorithm::Padding("PaddingCheckBox"); AlgorithmParameterName InterfaceWithCleaverAlgorithm::VolumeScalingOption("VolumeScalingOption"); AlgorithmParameterName InterfaceWithCleaverAlgorithm::VolumeScalingX("VolumeScalingSpinBox_X"); AlgorithmParameterName InterfaceWithCleaverAlgorithm::VolumeScalingY("VolumeScalingSpinBox_Y"); AlgorithmParameterName InterfaceWithCleaverAlgorithm::VolumeScalingZ("VolumeScalingSpinBox_Z"); InterfaceWithCleaverAlgorithm::InterfaceWithCleaverAlgorithm() { addParameter(Verbose,true); addParameter(Padding,true); add_option(VolumeScalingOption, "Relative size", "Absolute size|Relative size|None"); addParameter(VolumeScalingX,1.0); addParameter(VolumeScalingY,1.0); addParameter(VolumeScalingZ,1.0); } boost::shared_ptr<Cleaver::ScalarField> InterfaceWithCleaverAlgorithm::makeCleaverFieldFromLatVol(FieldHandle field) { //TODO: this function assumes input is completely valid, may want to move various checks from run() function here. VMesh* vmesh = field->vmesh(); VField* vfield = field->vfield(); VMesh::dimension_type dims; vmesh->get_dimensions( dims ); float* ptr = static_cast<float*>(vfield->fdata_pointer()); auto cleaverField = boost::make_shared<Cleaver::FloatField>(dims[0], dims[1], dims[2], ptr); //0 = constant, 1 = linear if (0 == vfield->basis_order()) cleaverField->setCenter(Cleaver::FloatField::CellCentered); else if (1 == vfield->basis_order()) cleaverField->setCenter(Cleaver::FloatField::NodeCentered); //else: TODO? handle other bases, probably by throwing exception. //TODO: Cleaver FloatField needs more setup (constructor is not sufficient) // 1. // setBounds(BoundingBox). Convert vmesh->get_bounding_box() to Cleaver BoundingBox. // 2. // setScale(vec3). Need to figure out which vmesh function to call, and convert to Cleaver::vec3. // 3. unit test heavily. return cleaverField; } FieldHandle InterfaceWithCleaverAlgorithm::run(const std::vector<FieldHandle>& input) const { FieldHandle output; std::vector<FieldHandle> inputs; std::copy_if(input.begin(), input.end(), std::back_inserter(inputs), [](FieldHandle f) { return f; }); if (inputs.empty()) { THROW_ALGORITHM_INPUT_ERROR(" No input fields given "); return FieldHandle(); } if (inputs.size()<2) { THROW_ALGORITHM_INPUT_ERROR(" At least 2 indicator functions stored as float values are needed to run cleaver! " ); return FieldHandle(); } std::vector<boost::shared_ptr<Cleaver::ScalarField>> fields; VMesh::dimension_type dims; int x=0,y=0,z=0; for (size_t p=1; p<inputs.size(); p++) { FieldHandle input = inputs[p]; VMesh* imesh1 = input->vmesh(); if( !imesh1->is_structuredmesh() ) { THROW_ALGORITHM_INPUT_ERROR("needs to be structured mesh!"); } else { VField* vfield1 = input->vfield(); if (!vfield1->is_scalar()) { THROW_ALGORITHM_INPUT_ERROR("values at the node needs to be scalar!"); return FieldHandle(); } imesh1->get_dimensions( dims ); if (p==1) { x=dims[0]; y=dims[1]; z=dims[2]; if (x<1 || y<1 || z<1) { THROW_ALGORITHM_INPUT_ERROR(" Size of input fields should be non-zero !"); } } else { if ( dims[0]!=x || dims[1]!=y || dims[2]!=z) { THROW_ALGORITHM_INPUT_ERROR(" Size of input fields is inconsistent !"); } } if (dims.size()!=3) { THROW_ALGORITHM_INPUT_ERROR("need a three dimensional indicator function"); return FieldHandle(); } if (vfield1->is_float()) { float* ptr = static_cast<float*>(vfield1->fdata_pointer()); if (ptr) { fields.push_back(makeCleaverFieldFromLatVol(input)); } else { THROW_ALGORITHM_INPUT_ERROR(" float field is NULL pointer"); return FieldHandle(); } } } } boost::shared_ptr<Cleaver::Volume> volume(new Cleaver::Volume(toVectorOfRawPointers(fields))); const double xScale = get(VolumeScalingX).toDouble(); const double yScale = get(VolumeScalingY).toDouble(); const double zScale = get(VolumeScalingZ).toDouble(); if (xScale > 0 && yScale > 0 && zScale > 0) { const std::string scaling = get_option(VolumeScalingOption); if ("Absolute size" == scaling) { volume->setSize(xScale, yScale,zScale); } else if ("Relative size" == scaling) { double newX = xScale*volume->size().x; double newY = yScale*volume->size().y; double newZ = zScale*volume->size().z; std::cout << "Cleaver setting volume size to " << newX << "," << newY << "," << newZ << std::endl; volume->setSize(newX, newY, newZ); } else // None volume->setSize(dims[0],dims[1],dims[2]); } else { THROW_ALGORITHM_INPUT_ERROR(" Invalid Scaling. Use Input sizes."); } /// Padding is now optional! boost::shared_ptr<Cleaver::AbstractVolume> paddedVolume(volume); const bool verbose = get(Verbose).toBool(); const bool pad = get(Padding).toBool(); if (pad) paddedVolume.reset(new Cleaver::PaddedVolume(volume.get())); boost::scoped_ptr<Cleaver::TetMesh> mesh(Cleaver::createMeshFromVolume(paddedVolume.get(), verbose)); FieldInformation fi("TetVolMesh",0,"double"); ///create output field output = CreateField(fi); auto omesh = output->vmesh(); auto ofield = output->vfield(); auto nr_of_tets = mesh->tets.size(); auto nr_of_verts = mesh->verts.size(); omesh->node_reserve(nr_of_verts); omesh->elem_reserve(nr_of_tets); for (auto i=0; i<nr_of_verts; i++) { omesh->add_point(Point(mesh->verts[i]->pos().x,mesh->verts[i]->pos().y,mesh->verts[i]->pos().z)); } VMesh::Node::array_type vdata; vdata.resize(4); std::vector<double> values(nr_of_tets); for (auto i=0; i<nr_of_tets; i++) { vdata[0]=mesh->tets[i]->verts[0]->tm_v_index; vdata[1]=mesh->tets[i]->verts[1]->tm_v_index; vdata[2]=mesh->tets[i]->verts[2]->tm_v_index; vdata[3]=mesh->tets[i]->verts[3]->tm_v_index; omesh->add_elem(vdata); auto mat_label = mesh->tets[i]->mat_label+1; values[i]=mat_label; } ofield->resize_values(); ofield->set_values(values); mesh->computeAngles(); std::ostringstream ostr1; ostr1 << "Number of tetrahedral elements:" << ofield->vmesh()->num_elems() << std::endl; ostr1 << "Number of tetrahedral nodes:" << ofield->vmesh()->num_nodes() << std::endl; ostr1 << "Number of tetrahedral nodes:" << ofield->vmesh()->num_nodes() << std::endl; ostr1 << "Worst Angle (min):" << mesh->min_angle << std::endl; ostr1 << "Worst Angle (max):" << mesh->max_angle << std::endl; ostr1 << "Volume:" << volume->size().toString() << std::endl; remark(ostr1.str()); return output; } AlgorithmOutput InterfaceWithCleaverAlgorithm::run_generic(const AlgorithmInput& input) const { auto inputfields = input.getList<Field>(Variables::InputFields); FieldHandle output_fld = run(inputfields); if ( !output_fld ) THROW_ALGORITHM_PROCESSING_ERROR("Null returned on legacy run call."); AlgorithmOutput output; output[Variables::OutputField] = output_fld; return output; } <commit_msg>small update<commit_after>/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2012 Scientific Computing and Imaging Institute, University of Utah. License for the specific language governing rights and limitations under 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. Author : Moritz Dannhauer Last modification : March 16 2014 ToDo: Padding is always enabled because of exit() in cleaver lib */ ///TODO: fix include path to remove Externals/ part #include <Externals/cleaver/lib/FloatField.h> #include <Externals/cleaver/lib/vec3.h> #include <Externals/cleaver/lib/BoundingBox.h> #include <Externals/cleaver/lib/Cleaver.h> #include <Externals/cleaver/lib/InverseField.h> #include <Externals/cleaver/lib/PaddedVolume.h> #include <Externals/cleaver/lib/Volume.h> #include <Core/Algorithms/Base/AlgorithmPreconditions.h> #include <Core/Algorithms/Field/InterfaceWithCleaverAlgorithm.h> #include <Core/Algorithms/Base/AlgorithmVariableNames.h> #include <Core/GeometryPrimitives/Vector.h> #include <Core/Datatypes/Legacy/Field/Field.h> #include <Core/Datatypes/Legacy/Field/VField.h> #include <Core/Datatypes/Legacy/Field/VMesh.h> #include <Core/Datatypes/Legacy/Field/FieldInformation.h> #include <iostream> #include <Core/GeometryPrimitives/Point.h> #include <Core/Utils/StringUtil.h> #include <boost/scoped_ptr.hpp> #include <Core/Logging/Log.h> #include <Core/Math/MiscMath.h> using namespace SCIRun::Core::Algorithms; using namespace SCIRun::Core::Algorithms::Fields; using namespace SCIRun::Core::Geometry; using namespace SCIRun; using namespace SCIRun::Core; using namespace SCIRun::Core::Logging; AlgorithmParameterName InterfaceWithCleaverAlgorithm::Verbose("VerboseCheckBox"); AlgorithmParameterName InterfaceWithCleaverAlgorithm::Padding("PaddingCheckBox"); AlgorithmParameterName InterfaceWithCleaverAlgorithm::VolumeScalingOption("VolumeScalingOption"); AlgorithmParameterName InterfaceWithCleaverAlgorithm::VolumeScalingX("VolumeScalingSpinBox_X"); AlgorithmParameterName InterfaceWithCleaverAlgorithm::VolumeScalingY("VolumeScalingSpinBox_Y"); AlgorithmParameterName InterfaceWithCleaverAlgorithm::VolumeScalingZ("VolumeScalingSpinBox_Z"); InterfaceWithCleaverAlgorithm::InterfaceWithCleaverAlgorithm() { addParameter(Verbose,true); addParameter(Padding,true); add_option(VolumeScalingOption, "Relative size", "Absolute size|Relative size|None"); addParameter(VolumeScalingX,1.0); addParameter(VolumeScalingY,1.0); addParameter(VolumeScalingZ,1.0); } boost::shared_ptr<Cleaver::ScalarField> InterfaceWithCleaverAlgorithm::makeCleaverFieldFromLatVol(FieldHandle field ) { //TODO: this function assumes input is completely valid, may want to move various checks from run() function here. VMesh* vmesh = field->vmesh(); VField* vfield = field->vfield(); VMesh::dimension_type dims; vmesh->get_dimensions( dims ); float* ptr = static_cast<float*>(vfield->fdata_pointer()); auto cleaverField = boost::make_shared<Cleaver::FloatField>(dims[0], dims[1], dims[2], ptr); cleaverField->setCenter(Cleaver::FloatField::CellCentered); BBox bbox=vmesh->get_bounding_box(); Point bmin, bmax; if (bbox.valid()) { bmin = bbox.min(); bmax = bbox.max(); } Cleaver::BoundingBox bb = Cleaver::BoundingBox(Cleaver::vec3::zero, Cleaver::vec3(dims[0],dims[1],dims[2])); cleaverField->setBounds(bb); const Transform &transform = vmesh->get_transform(); int x_spacing=fabs(transform.get_mat_val(0,0)), y_spacing=fabs(transform.get_mat_val(1,1)), z_spacing=fabs(transform.get_mat_val(2,2)); if (IsNan(x_spacing)) x_spacing=1; if (IsNan(y_spacing)) y_spacing=1; if (IsNan(z_spacing)) z_spacing=1; cleaverField->setScale(Cleaver::vec3(x_spacing,y_spacing,z_spacing)); //TODO: Cleaver FloatField needs more setup (constructor is not sufficient) // 1. // setBounds(BoundingBox). Convert vmesh->get_bounding_box() to Cleaver BoundingBox. // 2. // setScale(vec3). Need to figure out which vmesh function to call, and convert to Cleaver::vec3. // 3. unit test heavily. return cleaverField; } FieldHandle InterfaceWithCleaverAlgorithm::run(const std::vector<FieldHandle>& input) const { FieldHandle output; std::vector<FieldHandle> inputs; std::copy_if(input.begin(), input.end(), std::back_inserter(inputs), [](FieldHandle f) { return f; }); if (inputs.empty()) { THROW_ALGORITHM_INPUT_ERROR(" No input fields given "); return FieldHandle(); } if (inputs.size()<2) { THROW_ALGORITHM_INPUT_ERROR(" At least 2 indicator functions stored as float values are needed to run cleaver! " ); return FieldHandle(); } std::vector<boost::shared_ptr<Cleaver::ScalarField>> fields; VMesh::dimension_type dims; int x=0,y=0,z=0; for (size_t p=0; p<inputs.size(); p++) { FieldHandle input = inputs[p]; VMesh* imesh1 = input->vmesh(); if( !imesh1->is_structuredmesh() ) { THROW_ALGORITHM_INPUT_ERROR("needs to be structured mesh!"); } else { VField* vfield1 = input->vfield(); if (!vfield1->is_scalar()) { THROW_ALGORITHM_INPUT_ERROR("values at the node needs to be scalar!"); return FieldHandle(); } imesh1->get_dimensions( dims ); if (p==0) { x=dims[0]; y=dims[1]; z=dims[2]; if (x<1 || y<1 || z<1) { THROW_ALGORITHM_INPUT_ERROR(" Size of input fields should be non-zero !"); } } else { if ( dims[0]!=x || dims[1]!=y || dims[2]!=z) { THROW_ALGORITHM_INPUT_ERROR(" Size of input fields is inconsistent !"); } } if (dims.size()!=3) { THROW_ALGORITHM_INPUT_ERROR("need a three dimensional indicator function"); return FieldHandle(); } //0 = constant, 1 = linear if (0 != vfield1->basis_order()) { THROW_ALGORITHM_INPUT_ERROR("Input data need to be defined on elements. You can use the module MapFieldDataFromNodeToElem to do that."); } if (vfield1->is_float()) { float* ptr = static_cast<float*>(vfield1->fdata_pointer()); if (ptr) { fields.push_back(makeCleaverFieldFromLatVol(input)); } else { THROW_ALGORITHM_INPUT_ERROR(" float field is NULL pointer"); return FieldHandle(); } } else { THROW_ALGORITHM_INPUT_ERROR(" Input field needs to be a structured mesh (LatVOL) with float values defnied on the elements. "); } } } boost::shared_ptr<Cleaver::Volume> volume(new Cleaver::Volume(toVectorOfRawPointers(fields))); /* Cleaver::BoundingBox m_bounds=fields[0]->bounds(); std::cout << "bsize: " << m_bounds.size.x << " " << m_bounds.size.y << " " << m_bounds.size.z << std::endl; std::cout << "borin: " << m_bounds.origin.x << " " << m_bounds.origin.y << " " << m_bounds.origin.z << std::endl; */ const double xScale = get(VolumeScalingX).toDouble(); const double yScale = get(VolumeScalingY).toDouble(); const double zScale = get(VolumeScalingZ).toDouble(); if (xScale > 0 && yScale > 0 && zScale > 0) { const std::string scaling = get_option(VolumeScalingOption); if ("Absolute size" == scaling) { volume->setSize(xScale, yScale,zScale); } else if ("Relative size" == scaling) { double newX = xScale*volume->size().x; double newY = yScale*volume->size().y; double newZ = zScale*volume->size().z; volume->setSize(newX, newY, newZ); } else // None { volume->setSize(dims[0],dims[1],dims[2]); } } else { THROW_ALGORITHM_INPUT_ERROR(" Invalid Scaling. Use Input sizes."); } /// Padding is now optional! boost::shared_ptr<Cleaver::AbstractVolume> paddedVolume(volume); const bool verbose = get(Verbose).toBool(); const bool pad = get(Padding).toBool(); if (pad) paddedVolume.reset(new Cleaver::PaddedVolume(volume.get())); std::cout << "Creating Mesh with Volume Size " << paddedVolume->size().toString() << std::endl; boost::scoped_ptr<Cleaver::TetMesh> mesh(Cleaver::createMeshFromVolume(paddedVolume.get(), verbose)); FieldInformation fi("TetVolMesh",0,"double"); ///create output field output = CreateField(fi); auto omesh = output->vmesh(); auto ofield = output->vfield(); auto nr_of_tets = mesh->tets.size(); auto nr_of_verts = mesh->verts.size(); omesh->node_reserve(nr_of_verts); omesh->elem_reserve(nr_of_tets); for (auto i=0; i<nr_of_verts; i++) { omesh->add_point(Point(mesh->verts[i]->pos().x,mesh->verts[i]->pos().y,mesh->verts[i]->pos().z)); } VMesh::Node::array_type vdata; vdata.resize(4); std::vector<double> values(nr_of_tets); for (auto i=0; i<nr_of_tets; i++) { vdata[0]=mesh->tets[i]->verts[0]->tm_v_index; vdata[1]=mesh->tets[i]->verts[1]->tm_v_index; vdata[2]=mesh->tets[i]->verts[2]->tm_v_index; vdata[3]=mesh->tets[i]->verts[3]->tm_v_index; omesh->add_elem(vdata); auto mat_label = mesh->tets[i]->mat_label; values[i]=mat_label; } ofield->resize_values(); ofield->set_values(values); mesh->computeAngles(); std::ostringstream ostr1; ostr1 << "Number of tetrahedral elements:" << nr_of_tets << std::endl; ostr1 << "Number of tetrahedral nodes:" << nr_of_verts << std::endl; ostr1 << "Worst Angle (min):" << mesh->min_angle << std::endl; ostr1 << "Worst Angle (max):" << mesh->max_angle << std::endl; ostr1 << "Volume:" << volume->size().toString() << std::endl; remark(ostr1.str()); return output; } AlgorithmOutput InterfaceWithCleaverAlgorithm::run_generic(const AlgorithmInput& input) const { auto inputfields = input.getList<Field>(Variables::InputFields); FieldHandle output_fld = run(inputfields); if ( !output_fld ) THROW_ALGORITHM_PROCESSING_ERROR("Null returned on legacy run call."); AlgorithmOutput output; output[Variables::OutputField] = output_fld; return output; } <|endoftext|>
<commit_before>/* * Author: Vladimir Ivan * * Copyright (c) 2017, University Of Edinburgh * 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 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 <exotica/TaskSpaceVector.h> namespace exotica { TaskVectorEntry::TaskVectorEntry(int inId_, RotationType type_) : inId(inId_), type(type_) { } TaskVectorEntry::TaskVectorEntry() : inId(0), type(RotationType::RPY) { } TaskSpaceVector::TaskSpaceVector() { } TaskSpaceVector& TaskSpaceVector::operator=(std::initializer_list<double> other) { if(other.size()!=data.rows()) throw_pretty("Wrong initializer size: " << other.size() << " expecting " << data.rows()); int i = 0; for(double val : other) { data(i) = val; i++; } return *this; } void TaskSpaceVector::setZero(int N) { data = Eigen::VectorXd::Zero(N); for(const TaskVectorEntry& id : map) { int len = getRotationTypeLength(id.type); data.segment(id.inId,len) = setRotation(KDL::Rotation(), id.type); } } Eigen::VectorXd TaskSpaceVector::operator-(const TaskSpaceVector& other) { if(data.rows() != other.data.rows()) throw_pretty("Task space vector sizes do not match!"); int entrySize = 0; for(const TaskVectorEntry& id : map) entrySize += getRotationTypeLength(id.type); Eigen::VectorXd ret(data.rows()+map.size()*3-map.size()*entrySize); int iIn=0; int iOut=0; for(const TaskVectorEntry& id : map) { if(iIn<id.inId) ret.segment(iOut, id.inId-iIn) = data.segment(iIn, id.inId-iIn) - other.data.segment(iIn, id.inId-iIn); iOut += id.inId-iIn; iIn += id.inId-iIn; int len = getRotationTypeLength(id.type); KDL::Rotation M1 = getRotation(data.segment(id.inId, len), id.type); KDL::Rotation M2 = getRotation(other.data.segment(id.inId, len), id.type); KDL::Rotation M = M2.Inverse()*M1; KDL::Vector rotvec = M1*(M.GetRot()); ret(iOut) = rotvec[0]; ret(iOut+1) = rotvec[1]; ret(iOut+2) = rotvec[2]; iOut+=3; iIn+=len; } if(iIn<data.rows()) ret.segment(iOut, data.rows()-iIn) = data.segment(iIn, data.rows()-iIn) - other.data.segment(iIn, data.rows()-iIn); return ret; } } <commit_msg>Fixes multiple ratiotion task inside a task map indexing<commit_after>/* * Author: Vladimir Ivan * * Copyright (c) 2017, University Of Edinburgh * 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 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 <exotica/TaskSpaceVector.h> namespace exotica { TaskVectorEntry::TaskVectorEntry(int inId_, RotationType type_) : inId(inId_), type(type_) { } TaskVectorEntry::TaskVectorEntry() : inId(0), type(RotationType::RPY) { } TaskSpaceVector::TaskSpaceVector() { } TaskSpaceVector& TaskSpaceVector::operator=(std::initializer_list<double> other) { if(other.size()!=data.rows()) throw_pretty("Wrong initializer size: " << other.size() << " expecting " << data.rows()); int i = 0; for(double val : other) { data(i) = val; i++; } return *this; } void TaskSpaceVector::setZero(int N) { data = Eigen::VectorXd::Zero(N); for(const TaskVectorEntry& id : map) { int len = getRotationTypeLength(id.type); data.segment(id.inId,len) = setRotation(KDL::Rotation(), id.type); } } Eigen::VectorXd TaskSpaceVector::operator-(const TaskSpaceVector& other) { if(data.rows() != other.data.rows()) throw_pretty("Task space vector sizes do not match!"); int entrySize = 0; for(const TaskVectorEntry& id : map) entrySize += getRotationTypeLength(id.type); Eigen::VectorXd ret(data.rows()+map.size()*3-entrySize); int iIn=0; int iOut=0; for(const TaskVectorEntry& id : map) { if(iIn<id.inId) ret.segment(iOut, id.inId-iIn) = data.segment(iIn, id.inId-iIn) - other.data.segment(iIn, id.inId-iIn); iOut += id.inId-iIn; iIn += id.inId-iIn; int len = getRotationTypeLength(id.type); KDL::Rotation M1 = getRotation(data.segment(id.inId, len), id.type); KDL::Rotation M2 = getRotation(other.data.segment(id.inId, len), id.type); KDL::Rotation M = M2.Inverse()*M1; KDL::Vector rotvec = M1*(M.GetRot()); ret(iOut) = rotvec[0]; ret(iOut+1) = rotvec[1]; ret(iOut+2) = rotvec[2]; iOut+=3; iIn+=len; } if(iIn<data.rows()) ret.segment(iOut, data.rows()-iIn) = data.segment(iIn, data.rows()-iIn) - other.data.segment(iIn, data.rows()-iIn); return ret; } } <|endoftext|>