text
stringlengths 54
60.6k
|
|---|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_pcie_scominit.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 */
//-----------------------------------------------------------------------------------
///
/// @file p9_pcie_scominit.H
/// @brief Perform PCIE Phase1 init sequence (FAPI2)
///
// *HWP HWP Owner: Christina Graves clgraves@us.ibm.com
// *HWP FW Owner: Thi Tran thi@us.ibm.com
// *HWP Team: Nest
// *HWP Level: 1
// *HWP Consumed by: HB
#ifndef _P9_PCIE_SCOMINIT_H_
#define _P9_PCIE_SCOMINIT_H_
//-----------------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------------
#include <fapi2.H>
//-----------------------------------------------------------------------------------
// Helper Macros
//-----------------------------------------------------------------------------------
#define SET_REG_RMW_WITH_SINGLE_ATTR_8(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\
FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_8)); \
FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \
FAPI_TRY(l_buf.insertFromRight(l_attr_8, in_start_bit, in_bit_count)); \
FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \
FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));
#define SET_REG_RMW_WITH_SINGLE_ATTR_16(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\
FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_16)); \
FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \
FAPI_TRY(l_buf.insertFromRight(l_attr_16, in_start_bit, in_bit_count)); \
FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \
FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));
#define SET_REG_WR_WITH_SINGLE_ATTR_16(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\
l_buf = 0; \
FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_16)); \
FAPI_TRY(l_buf.insertFromRight(l_attr_16, in_start_bit, in_bit_count)); \
FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \
FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));
#define SET_REG_RMW(in_value, in_reg_name, in_start_bit, in_bit_count)\
FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \
FAPI_TRY(l_buf.insertFromRight(in_value, in_start_bit, in_bit_count)); \
FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \
FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));
#define SET_REG_WR(in_value, in_reg_name, in_start_bit, in_bit_count)\
FAPI_TRY(l_buf.insertFromRight(in_value, in_start_bit, in_bit_count)); \
FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \
FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));
//-----------------------------------------------------------------------------------
// Structure definitions
//-----------------------------------------------------------------------------------
//function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_pcie_scominit_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);
//-----------------------------------------------------------------------------------
// Constant definitions
//-----------------------------------------------------------------------------------
const uint8_t NUM_PCS_CONFIG = 4;
const uint8_t NUM_PCIE_LANES = 16;
const uint8_t NUM_M_CONFIG = 4;
const uint8_t PEC0_IOP_CONFIG_START_BIT = 13;
const uint8_t PEC1_IOP_CONFIG_START_BIT = 14;
const uint8_t PEC2_IOP_CONFIG_START_BIT = 10;
const uint8_t PEC0_IOP_BIT_COUNT = 1;
const uint8_t PEC1_IOP_BIT_COUNT = 2;
const uint8_t PEC2_IOP_BIT_COUNT = 3;
const uint8_t PEC0_IOP_SWAP_START_BIT = 12;
const uint8_t PEC1_IOP_SWAP_START_BIT = 12;
const uint8_t PEC2_IOP_SWAP_START_BIT = 7;
const uint8_t PEC0_IOP_IOVALID_ENABLE_START_BIT = 4;
const uint8_t PEC1_IOP_IOVALID_ENABLE_START_BIT = 4;
const uint8_t PEC2_IOP_IOVALID_ENABLE_START_BIT = 4;
const uint8_t PEC_IOP_REFCLOCK_ENABLE_START_BIT = 32;
const uint8_t PEC_IOP_PMA_RESET_START_BIT = 29;
const uint8_t PEC_IOP_PIPE_RESET_START_BIT = 28;
const uint8_t PEC_IOP_HSS_PORT_READY_START_BIT = 58;
const uint64_t PEC_IOP_PLLA_VCO_COURSE_CAL_REGISTER1 = 0x800005010D010C3F;
const uint64_t PEC_IOP_PLLB_VCO_COURSE_CAL_REGISTER1 = 0x800005410D010C3F;
const uint64_t PEC_IOP_RX_DFE_FUNC_REGISTER1 = 0x8000049F0D010C3F;
const uint64_t PEC_IOP_RX_DFE_FUNC_REGISTER2 = 0x800004A00D010C3F;
const uint64_t RX_VGA_CTRL3_REGISTER[NUM_PCIE_LANES] =
{
0x8000008D0D010C3F,
0x800000CD0D010C3F,
0x8000018D0D010C3F,
0x800001CD0D010C3F,
0x8000028D0D010C3F,
0x800002CD0D010C3F,
0x8000038D0D010C3F,
0x800003CD0D010C3F,
0x8000088D0D010C3F,
0x800008CD0D010C3F,
0x8000098D0D010C3F,
0x800009CD0D010C3F,
0x80000A8D0D010C3F,
0x80000ACD0D010C3F,
0x80000B8D0D010C3F,
0x80000BCD0D010C3F,
};
const uint64_t RX_LOFF_CNTL_REGISTER[NUM_PCIE_LANES] =
{
0x800000A60D010C3F,
0x800000E60D010C3F,
0x800001A60D010C3F,
0x800001E60D010C3F,
0x800002A60D010C3F,
0x800002E60D010C3F,
0x800003A60D010C3F,
0x800003E60D010C3F,
0x800008A60D010C3F,
0x800008E60D010C3F,
0x800009A60D010C3F,
0x800009E60D010C3F,
0x80000AA60D010C3F,
0x80000AE60D010C3F,
0x80000BA60D010C3F,
0x80000BE60D010C3F,
};
const uint32_t PCS_CONFIG_MODE0 = 0xA006;
const uint32_t PCS_CONFIG_MODE1 = 0xA805;
const uint32_t PCS_CONFIG_MODE2 = 0xB071;
const uint32_t PCS_CONFIG_MODE3 = 0xB870;
const uint32_t MAX_NUM_POLLS = 100; //Maximum number of iterations (So, 400ns * 100 = 40us before timeout)
const uint64_t PMA_RESET_NANO_SEC_DELAY = 400; //400ns to wait for PMA RESET to go through
const uint64_t PMA_RESET_CYC_DELAY = 400; //400ns to wait for PMA RESET to go through
extern "C" {
//-----------------------------------------------------------------------------------
// Function prototype
//-----------------------------------------------------------------------------------
/// @brief Perform PCIE Phase1 init sequence
/// @param[in] i_target => P9 chip target
/// @return FAPI_RC_SUCCESS if the setup completes successfully,
//
fapi2::ReturnCode p9_pcie_scominit(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);
} //extern"C"
#endif //_P9_PCIE_SCOMINIT_H_
<commit_msg>L3 Update - p9_pcie_scominit HWP<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_pcie_scominit.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 */
/// ---------------------------------------------------------------------------
///
/// @file p9_pcie_scominit.H
/// @brief Perform PCIE Phase1 init sequence (FAPI2)
///
/// *HWP HWP Owner: Ricardo Mata Jr. ricmata@us.ibm.com
/// *HWP FW Owner: Thi Tran thi@us.ibm.com
/// *HWP Team: Nest
/// *HWP Level: 3
/// *HWP Consumed by: HB
/// ---------------------------------------------------------------------------
#ifndef _P9_PCIE_SCOMINIT_H_
#define _P9_PCIE_SCOMINIT_H_
//-----------------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------------
#include <fapi2.H>
//-----------------------------------------------------------------------------------
// Helper Macros
//-----------------------------------------------------------------------------------
#define SET_REG_RMW_WITH_SINGLE_ATTR_8(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\
FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_8)); \
FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \
FAPI_TRY(l_buf.insertFromRight(l_attr_8, in_start_bit, in_bit_count)); \
FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \
FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));
#define SET_REG_RMW_WITH_SINGLE_ATTR_16(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\
FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_16)); \
FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \
FAPI_TRY(l_buf.insertFromRight(l_attr_16, in_start_bit, in_bit_count)); \
FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \
FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));
#define SET_REG_WR_WITH_SINGLE_ATTR_16(in_attr_name, in_reg_name, in_start_bit, in_bit_count)\
l_buf = 0; \
FAPI_TRY(FAPI_ATTR_GET(in_attr_name, l_pec_chiplets, l_attr_16)); \
FAPI_TRY(l_buf.insertFromRight(l_attr_16, in_start_bit, in_bit_count)); \
FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \
FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));
#define SET_REG_RMW(in_value, in_reg_name, in_start_bit, in_bit_count)\
FAPI_TRY(fapi2::getScom(l_pec_chiplets, in_reg_name, l_buf)); \
FAPI_TRY(l_buf.insertFromRight(in_value, in_start_bit, in_bit_count)); \
FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \
FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));
#define SET_REG_WR(in_value, in_reg_name, in_start_bit, in_bit_count)\
FAPI_TRY(l_buf.insertFromRight(in_value, in_start_bit, in_bit_count)); \
FAPI_DBG("pec%i: %#lx", l_pec_id, l_buf()); \
FAPI_TRY(fapi2::putScom(l_pec_chiplets, in_reg_name, l_buf));
//-----------------------------------------------------------------------------------
// Structure definitions
//-----------------------------------------------------------------------------------
//function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_pcie_scominit_FP_t) (const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);
extern "C" {
//-----------------------------------------------------------------------------------
// Function prototype
//-----------------------------------------------------------------------------------
/// @brief Perform PCIE Phase1 init sequence
/// @param[in] i_target => P9 chip target
/// @return FAPI_RC_SUCCESS if the setup completes successfully,
//
fapi2::ReturnCode p9_pcie_scominit(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);
} //extern"C"
#endif //_P9_PCIE_SCOMINIT_H_
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_throttle_sync.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_throttle_sync.H
///
/// @brief Perform p9_throttle_sync HWP
///
/// The purpose of this procedure is to triggers sync command from a 'master'
/// MC to other MCs that have attached memory in a processor.
///
/// ----------------------------------------------------------------------------
/// *HWP HWP Owner : Joe McGill <jmcgill@us.ibm.com>
/// *HWP FW Owner : Thi Tran <thi@us.ibm.com>
/// *HWP Team : Nest
/// *HWP Level : 2
/// *HWP Consumed by : HB
/// ----------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_throttle_sync.H>
#include <fapi2.H>
#include <lib/utils/find.H>
///----------------------------------------------------------------------------
/// Constant definitions
///----------------------------------------------------------------------------
const uint8_t SUPER_SYNC_BIT = 14;
///
/// @brief Perform throttle sync on the Memory Controllers
///
/// @tparam T template parameter, passed in targets.
/// @param[in] i_mcTargets Vector of reference of MC targets (MCS or MI)
///
/// @return FAPI2_RC_SUCCESS if success, else error code.
///
template< fapi2::TargetType T>
fapi2::ReturnCode throttleSync(
const std::vector< fapi2::Target<T> >& i_mcTargets);
/// TARGET_TYPE_MCS
template<>
fapi2::ReturnCode throttleSync(
const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MCS> >& i_mcTargets)
{
FAPI_DBG("Entering");
fapi2::ReturnCode l_rc;
fapi2::buffer<uint64_t> l_scomData(0);
fapi2::buffer<uint64_t> l_scomMask(0);
bool l_mcaWithDimm[MAX_MCA_PER_PROC];
fapi2::Target<fapi2::TARGET_TYPE_MCS> l_masterMcs;
fapi2::Target<fapi2::TARGET_TYPE_MCA> l_mca;
uint8_t l_masterMcsPos = 0;
uint8_t l_mcaPos = 0;
// Initialize
memset(l_mcaWithDimm, false, sizeof(l_mcaWithDimm));
// --------------------------------------------------------------
// 1. Determine the 'master' MCS and mark which MCA ports have
// dimms attached
// --------------------------------------------------------------
bool l_masterMcsFound = false;
for (auto l_mcs : i_mcTargets)
{
// Find first MCS that has DIMM attached
std::vector< fapi2::Target<fapi2::TARGET_TYPE_DIMM> > l_dimms =
mss::find_targets<fapi2::TARGET_TYPE_DIMM>(l_mcs);
if (l_dimms.size() > 0)
{
// Set first MCS with DIMM attached to be master
if (l_masterMcsFound == false)
{
l_masterMcs = l_mcs;
l_masterMcsFound = true;
}
// Loop over the DIMM list to mark the MCAs that own them
for (auto l_thisDimm : l_dimms)
{
l_mca = mss::find_target<fapi2::TARGET_TYPE_MCA>(l_thisDimm);
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_mca, l_mcaPos),
"Error getting ATTR_CHIP_UNIT_POS, l_rc 0x%.8X",
(uint64_t)fapi2::current_err);
l_mcaWithDimm[l_mcaPos] = true;
}
}
}
// No master found
if (l_masterMcsFound == false)
{
// Nothing to do with this proc, exit
// Note: This is a common scenario on Cronus platform.
goto fapi_try_exit;
}
// Display MCS/MCA with DIMM attached
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_masterMcs,
l_masterMcsPos),
"Error getting ATTR_CHIP_UNIT_POS, l_rc 0x%.8X",
(uint64_t)fapi2::current_err);
FAPI_INF("Master MCS pos %u", l_masterMcsPos);
FAPI_DBG("MCA with DIMM attached:");
for (uint8_t ii = 0; ii < MAX_MCA_PER_PROC; ii++)
{
FAPI_DBG(" MCA[%u] %u", ii, l_mcaWithDimm[ii]);
}
// -------------------------------------------------------------------
// 2. Reset sync command on both channels to make sure they are clean
// -------------------------------------------------------------------
// Reset the sync command on both channels to make sure they are clean
l_scomMask.flush<0>().setBit<MCS_MCSYNC_SYNC_GO_CH0>();
l_scomData.flush<0>();
FAPI_TRY(fapi2::putScomUnderMask(l_masterMcs, MCS_MCSYNC,
l_scomData, l_scomMask),
"putScomUnderMask() returns an error (Sync reset), Addr 0x%.16llX",
MCS_MCSYNC);
// --------------------------------------------------------------
// 3. Setup MC Sync Command Register data for master MCS
// --------------------------------------------------------------
// Clear buffers
l_scomData.flush<0>();
l_scomMask.flush<0>();
// Setup MCSYNC_CHANNEL_SELECT
// Set ALL channels with or without DIMMs (bits 0:7)
l_scomData.setBit<MCS_MCSYNC_CHANNEL_SELECT,
MCS_MCSYNC_CHANNEL_SELECT_LEN>();
l_scomMask.setBit<MCS_MCSYNC_CHANNEL_SELECT,
MCS_MCSYNC_CHANNEL_SELECT_LEN>();
// Setup MCSYNC_SYNC_TYPE
// Set all sync types except Super Sync
l_scomData.setBit<MCS_MCSYNC_SYNC_TYPE,
MCS_MCSYNC_SYNC_TYPE_LEN>().clearBit(SUPER_SYNC_BIT);
l_scomMask.setBit<MCS_MCSYNC_SYNC_TYPE,
MCS_MCSYNC_SYNC_TYPE_LEN>();
// Setup SYNC_GO, pick either MCA port of the master MCS, but the port
// must have DIMM connected.
l_mcaPos = l_masterMcsPos * 2; // 1st MCS postion of the master MCS
if (l_mcaWithDimm[l_mcaPos] == true)
{
l_scomMask.setBit<MCS_MCSYNC_SYNC_GO_CH0>();
l_scomData.setBit<MCS_MCSYNC_SYNC_GO_CH0>();
}
// --------------------------------------------------------------
// 4. Write to MC Sync Command Register of master MCS
// --------------------------------------------------------------
// Write to MCSYNC reg
FAPI_INF("Writing MCS_MCSYNC reg 0x%.16llX: Mask 0x%.16llX , Data 0x%.16llX",
MCS_MCSYNC, l_scomMask, l_scomData);
FAPI_TRY(fapi2::putScomUnderMask(l_masterMcs, MCS_MCSYNC,
l_scomData, l_scomMask),
"putScomUnderMask() returns an error (Sync), MCS_MCSYNC reg 0x%.16llX",
MCS_MCSYNC);
// Note: No need to read Sync replay count and retry in P9.
fapi_try_exit:
FAPI_DBG("Exiting");
return fapi2::current_err;
}
/// TARGET_TYPE_MI
template<>
fapi2::ReturnCode throttleSync(
const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MI> >& i_mcTargets)
{
FAPI_DBG("Entering");
fapi2::ReturnCode l_rc;
// Note: Add code for Cumulus
FAPI_DBG("Exiting");
return fapi2::current_err;
}
extern "C"
{
///----------------------------------------------------------------------------
/// Function definitions
///----------------------------------------------------------------------------
///
/// @brief p9_throttle_sync procedure entry point
/// See doxygen in p9_throttle_sync.H
///
fapi2::ReturnCode p9_throttle_sync(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
FAPI_DBG("Entering");
fapi2::ReturnCode l_rc;
auto l_mcsChiplets = i_target.getChildren<fapi2::TARGET_TYPE_MCS>();
auto l_miChiplets = i_target.getChildren<fapi2::TARGET_TYPE_MI>();
// Get the functional MCS on this proc
if (l_mcsChiplets.size() > 0)
{
FAPI_TRY(throttleSync(l_mcsChiplets),
"throttleSync() returns error l_rc 0x%.8X",
(uint64_t)fapi2::current_err);
}
// Cumulus
if (l_miChiplets.size() > 0)
{
FAPI_TRY(throttleSync(l_miChiplets),
"throttleSync() returns error l_rc 0x%.8X",
(uint64_t)fapi2::current_err);
}
fapi_try_exit:
FAPI_DBG("Exiting");
return fapi2::current_err;
}
} // extern "C"
<commit_msg>HW397255 Sync Enablement workaround<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/nest/p9_throttle_sync.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_throttle_sync.H
///
/// @brief Perform p9_throttle_sync HWP
///
/// The purpose of this procedure is to triggers sync command from a 'master'
/// MC to other MCs that have attached memory in a processor.
///
/// ----------------------------------------------------------------------------
/// *HWP HWP Owner : Joe McGill <jmcgill@us.ibm.com>
/// *HWP FW Owner : Thi Tran <thi@us.ibm.com>
/// *HWP Team : Nest
/// *HWP Level : 2
/// *HWP Consumed by : HB
/// ----------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_throttle_sync.H>
#include <fapi2.H>
#include <lib/utils/find.H>
///----------------------------------------------------------------------------
/// Constant definitions
///----------------------------------------------------------------------------
const uint8_t SUPER_SYNC_BIT = 14;
const uint8_t MAX_MC_SIDES_PER_PROC = 2; // MC01, MC23
// Structure that holds the potential master MCS for a MC side (MC01/MC23)
struct mcSideInfo_t
{
bool masterMcsFound = false;
// Master MCS for this MC side
fapi2::Target<fapi2::TARGET_TYPE_MCS> masterMcs;
};
///
/// @brief Programming master MCS
/// Writes MCS_MCSYNC reg to set the input MCS as the master.
///
/// @param[in] i_mcsTarget The MCS target to be programmed as master.
///
/// @return FAPI2_RC_SUCCESS if success, else error code.
///
fapi2::ReturnCode progMasterMcs(
const fapi2::Target<fapi2::TARGET_TYPE_MCS>& i_mcsTarget)
{
FAPI_DBG("Entering");
fapi2::ReturnCode l_rc;
fapi2::buffer<uint64_t> l_scomData(0);
fapi2::buffer<uint64_t> l_scomMask(0);
// -------------------------------------------------------------------
// 1. Reset sync command
// -------------------------------------------------------------------
// Note:
// MCS_MCSYNC reg bit 16 is now used to setup SYNC_GO for both channels.
// Bit 17 is now reserved (it was MCS_MCSYNC_SYNC_GO_CH1 before)
// REGISTER MCSYNC(mcsync(0:27), 0x000000000);
// MCSYNC.address(SCOM) += 0x00000015;
// MCSYNC.comment = "MC Sync Command Register (MCSYNC)";
// MCSYNC.attr(part_decl) = "0:7 = MCSYNC_Channel_Select"
// "8:15 = MCSYNC_Sync_Type"
// "16 = MCSYNC_Sync_Go"
// "17:27 = MCSYNC_Reserved";
// MCSYNC.attr(access) = "**::SCOM = RW";
// MCSYNC.attr(parity) = "mcSYNC_pe";
// MCSYNC.attr(wpulse) = "act_sc15";
l_scomMask.flush<0>().setBit<MCS_MCSYNC_SYNC_GO_CH0>();
l_scomData.flush<0>();
FAPI_TRY(fapi2::putScomUnderMask(i_mcsTarget, MCS_MCSYNC,
l_scomData, l_scomMask),
"putScomUnderMask() returns an error (Sync reset), Addr 0x%.16llX",
MCS_MCSYNC);
// --------------------------------------------------------------
// 2. Setup MC Sync Command Register data for master MCS
// --------------------------------------------------------------
// Clear buffers
l_scomData.flush<0>();
l_scomMask.flush<0>();
// Setup MCSYNC_CHANNEL_SELECT
// Set ALL channels with or without DIMMs (bits 0:7)
l_scomData.setBit<MCS_MCSYNC_CHANNEL_SELECT,
MCS_MCSYNC_CHANNEL_SELECT_LEN>();
l_scomMask.setBit<MCS_MCSYNC_CHANNEL_SELECT,
MCS_MCSYNC_CHANNEL_SELECT_LEN>();
// Setup MCSYNC_SYNC_TYPE
// Set all sync types except Super Sync
l_scomData.setBit<MCS_MCSYNC_SYNC_TYPE,
MCS_MCSYNC_SYNC_TYPE_LEN>().clearBit(SUPER_SYNC_BIT);
l_scomMask.setBit<MCS_MCSYNC_SYNC_TYPE,
MCS_MCSYNC_SYNC_TYPE_LEN>();
// Setup SYNC_GO (bit 16 is now used for both channels)
l_scomMask.setBit<MCS_MCSYNC_SYNC_GO_CH0>();
l_scomData.setBit<MCS_MCSYNC_SYNC_GO_CH0>();
// --------------------------------------------------------------
// 3. Write to MC Sync Command Register of master MCS
// --------------------------------------------------------------
// Write to MCSYNC reg
FAPI_INF("Writing MCS_MCSYNC reg 0x%.16llX: Mask 0x%.16llX , Data 0x%.16llX",
MCS_MCSYNC, l_scomMask, l_scomData);
FAPI_TRY(fapi2::putScomUnderMask(i_mcsTarget, MCS_MCSYNC,
l_scomData, l_scomMask),
"putScomUnderMask() returns an error (Sync), MCS_MCSYNC reg 0x%.16llX",
MCS_MCSYNC);
// Note: No need to read Sync replay count and retry in P9.
fapi_try_exit:
FAPI_DBG("Exiting");
return fapi2::current_err;
}
///
/// @brief Perform throttle sync on the Memory Controllers
///
/// @tparam T template parameter, passed in targets.
/// @param[in] i_mcTargets Vector of reference of MC targets (MCS or MI)
///
/// @return FAPI2_RC_SUCCESS if success, else error code.
///
template< fapi2::TargetType T>
fapi2::ReturnCode throttleSync(
const std::vector< fapi2::Target<T> >& i_mcTargets);
/// TARGET_TYPE_MCS
template<>
fapi2::ReturnCode throttleSync(
const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MCS> >& i_mcTargets)
{
FAPI_DBG("Entering");
fapi2::ReturnCode l_rc;
mcSideInfo_t l_mcSide[MAX_MC_SIDES_PER_PROC];
uint8_t l_sideNum = 0;
uint8_t l_pos = 0;
uint8_t l_numMasterProgrammed = 0;
// Initialization
for (l_sideNum = 0; l_sideNum < MAX_MC_SIDES_PER_PROC; l_sideNum++)
{
l_mcSide[l_sideNum].masterMcsFound = false;
}
// ---------------------------------------------------------------------
// 1. Pick the first MCS with DIMMS as potential master
// for both MC sides (MC01/MC23)
// ---------------------------------------------------------------------
for (auto l_mcs : i_mcTargets)
{
std::vector< fapi2::Target<fapi2::TARGET_TYPE_DIMM> > l_dimms =
mss::find_targets<fapi2::TARGET_TYPE_DIMM>(l_mcs);
if (l_dimms.size() > 0)
{
// This MCS has DIMMs attached, find out which MC side it
// belongs to:
// l_sideNum = 0 --> MC01
// 1 --> MC23
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_mcs,
l_pos),
"Error getting ATTR_CHIP_UNIT_POS, l_rc 0x%.8X",
(uint64_t)fapi2::current_err);
l_sideNum = l_pos / MAX_MC_SIDES_PER_PROC;
FAPI_INF("MCS %u has DIMMs", l_pos);
// If there's no master MCS marked for this side yet, mark
// this MCS as master
if (l_mcSide[l_sideNum].masterMcsFound == false)
{
FAPI_INF("Mark MCS %u as master for MC side %",
l_pos, l_sideNum);
l_mcSide[l_sideNum].masterMcsFound = true;
l_mcSide[l_sideNum].masterMcs = l_mcs;
}
}
}
// --------------------------------------------------------------
// 2. Program the master MCS
// --------------------------------------------------------------
for (l_sideNum = 0; l_sideNum < MAX_MC_SIDES_PER_PROC; l_sideNum++)
{
// If there is a potential master MCS found for this side
if (l_mcSide[l_sideNum].masterMcsFound == true)
{
// No master MCS programmed for either side yet,
// go ahead and program this MCS as master.
if (l_numMasterProgrammed == 0)
{
FAPI_TRY(progMasterMcs(l_mcSide[l_sideNum].masterMcs),
"programMasterMcs() returns error"
"NumMasterProgrammed %d, l_rc 0x%.8X",
l_numMasterProgrammed, (uint64_t)fapi2::current_err);
l_numMasterProgrammed++;
}
else
{
// A master MCS is already programmed on MC side 0 (MC01).
// HW397255 requires to also program a master MCS on MC23 if
// it has DIMMs.
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_chip =
l_mcSide[l_sideNum].masterMcs.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();
fapi2::ATTR_CHIP_EC_FEATURE_HW397255_Type l_HW397255_enabled;
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_HW397255,
l_chip, l_HW397255_enabled),
"Error getting the ATTR_CHIP_EC_FEATURE_HW397255");
if (l_HW397255_enabled)
{
FAPI_TRY(progMasterMcs(l_mcSide[l_sideNum].masterMcs),
"programMasterMcs() returns error"
"NumMasterProgrammed %d, l_rc 0x%.8X",
l_numMasterProgrammed, (uint64_t)fapi2::current_err);
}
}
}
}
fapi_try_exit:
FAPI_DBG("Exiting");
return fapi2::current_err;
}
/// TARGET_TYPE_MI
template<>
fapi2::ReturnCode throttleSync(
const std::vector< fapi2::Target<fapi2::TARGET_TYPE_MI> >& i_mcTargets)
{
FAPI_DBG("Entering");
fapi2::ReturnCode l_rc;
// Note: Add code for Cumulus
FAPI_DBG("Exiting");
return fapi2::current_err;
}
extern "C"
{
///----------------------------------------------------------------------------
/// Function definitions
///----------------------------------------------------------------------------
///
/// @brief p9_throttle_sync procedure entry point
/// See doxygen in p9_throttle_sync.H
///
fapi2::ReturnCode p9_throttle_sync(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
FAPI_DBG("Entering");
fapi2::ReturnCode l_rc;
auto l_mcsChiplets = i_target.getChildren<fapi2::TARGET_TYPE_MCS>();
auto l_miChiplets = i_target.getChildren<fapi2::TARGET_TYPE_MI>();
// Get the functional MCS on this proc
if (l_mcsChiplets.size() > 0)
{
FAPI_TRY(throttleSync(l_mcsChiplets),
"throttleSync() returns error l_rc 0x%.8X",
(uint64_t)fapi2::current_err);
}
// Cumulus
if (l_miChiplets.size() > 0)
{
FAPI_TRY(throttleSync(l_miChiplets),
"throttleSync() returns error l_rc 0x%.8X",
(uint64_t)fapi2::current_err);
}
fapi_try_exit:
FAPI_DBG("Exiting");
return fapi2::current_err;
}
} // extern "C"
<|endoftext|>
|
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/utils/imageProcs/p9_infrastruct_help.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,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 _P9_INFRASTRUCT_HELP_H_
#define _P9_INFRASTRUCT_HELP_H_
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h> //memcpy()
#include <errno.h>
//
// Various image/ring buffer sizes. Must be used by all users (VBU, FSP, HB, HBI, Cronus)
//
//@FIXME: CMO: get rid of FIXED_RING_BUF_SIZE when ring_apply no longer uses it.
const uint32_t FIXED_RING_BUF_SIZE = 60000; // Fixed ring buf size for _fixed.
const uint32_t MAX_SEEPROM_IMAGE_SIZE = 4 * 56 * 1024 - 256; // Max Seeprom size, excl ECC bits (4 banks).
const uint32_t MAX_RT_IMAGE_SIZE = 1024 * 1024; // Max Runtime size.
const uint32_t MAX_RING_BUF_SIZE = 60000; // Max ring buffer size.
const uint32_t MAX_OVERRIDES_SIZE = 2 * 1024; // Max overrides section size.
const uint32_t MAX_HBBL_SIZE = 20 * 1024; // Max hbbl section size.
//@FIXME: CMO: Aren't these defined somewhere else?
#define NUM_OF_CORES 24
#define NUM_OF_CMES 12
#define NUM_OF_QUADS 6
#define CORES_PER_QUAD (NUM_OF_CORES/NUM_OF_QUADS)
enum SYSPHASE
{
SYSPHASE_HB_SBE = 0,
SYSPHASE_RT_CME = 1,
SYSPHASE_RT_SGPE = 2,
NOOF_SYSPHASES = 3,
};
enum MODEBUILD
{
MODEBUILD_IPL = 0,
MODEBUILD_REBUILD = 1,
NOOF_MODEBUILDS = 2,
};
#if defined(__FAPI)
#include <fapi2.H>
#define MY_INF(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_)
#define MY_ERR(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_)
#define MY_DBG(_fmt_, _args_...) FAPI_DBG(_fmt_, ##_args_)
#else
#define MY_INF(_fmt_, _args_...) printf(_fmt_, ##_args_)
#define MY_ERR(_fmt_, _args_...) printf(_fmt_, ##_args_)
#define MY_DBG(_fmt_, _args_...) printf(_fmt_, ##_args_)
#endif
// N-byte align an address, offset or size (aos)
inline uint64_t myByteAlign( const uint8_t nBytes, const uint64_t aos)
{
return ((aos + nBytes - 1) / nBytes) * nBytes;
}
#endif //_P9_INFRASTRUCT_HELP_H_
<commit_msg>Cleanup: ring_apply and associated routines<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/utils/imageProcs/p9_infrastruct_help.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,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 _P9_INFRASTRUCT_HELP_H_
#define _P9_INFRASTRUCT_HELP_H_
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h> //memcpy()
#include <errno.h>
//
// Various image/ring buffer sizes. Must be used by all users (VBU, FSP, HB, HBI, Cronus)
//
const uint32_t MAX_SEEPROM_IMAGE_SIZE = 4 * 56 * 1024 - 256; // Max Seeprom size, excl ECC bits (4 banks).
const uint32_t MAX_RT_IMAGE_SIZE = 1024 * 1024; // Max Runtime size.
const uint32_t MAX_RING_BUF_SIZE = 60000; // Max ring buffer size.
const uint32_t FIXED_RING_BUF_SIZE = 60000; //@TODO: RTC156706
const uint32_t MAX_OVERRIDES_SIZE = 2 * 1024; // Max overrides section size.
const uint32_t MAX_HBBL_SIZE = 20 * 1024; // Max hbbl section size.
//@FIXME: CMO: Aren't these defined somewhere else?
#define NUM_OF_CORES 24
#define NUM_OF_CMES 12
#define NUM_OF_QUADS 6
#define CORES_PER_QUAD (NUM_OF_CORES/NUM_OF_QUADS)
enum SYSPHASE
{
SYSPHASE_HB_SBE = 0,
SYSPHASE_RT_CME = 1,
SYSPHASE_RT_SGPE = 2,
NOOF_SYSPHASES = 3,
};
enum MODEBUILD
{
MODEBUILD_IPL = 0,
MODEBUILD_REBUILD = 1,
NOOF_MODEBUILDS = 2,
};
#if defined(__FAPI)
#include <fapi2.H>
#define MY_INF(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_)
#define MY_ERR(_fmt_, _args_...) FAPI_INF(_fmt_, ##_args_)
#define MY_DBG(_fmt_, _args_...) FAPI_DBG(_fmt_, ##_args_)
#else
#define MY_INF(_fmt_, _args_...) printf(_fmt_, ##_args_)
#define MY_ERR(_fmt_, _args_...) printf(_fmt_, ##_args_)
#define MY_DBG(_fmt_, _args_...) printf(_fmt_, ##_args_)
#endif
// N-byte align an address, offset or size (aos)
inline uint64_t myByteAlign( const uint8_t nBytes, const uint64_t aos)
{
return ((aos + nBytes - 1) / nBytes) * nBytes;
}
#endif //_P9_INFRASTRUCT_HELP_H_
<|endoftext|>
|
<commit_before>#include "projet.h"
#include <QtDebug>
#include <QProcess>
#include <QException>
#include <QPainter>
const QSize Projet::sizeOutput = QSize(1002, 561);
Projet::Projet()
{
}
QImage* Projet::getImageVideo(int number)
{
return _imagesVideo.at(number);
}
QImage* Projet::getImageOutput(int number)
{
return _imagesOutput.at(number);
}
int Projet::getNbFrameVideo()
{
return _nbFrameVideo;
}
Projet* Projet::create(QString &name, QDir &workspace, QFile &video, int frequenceVideo)
{
Projet *projet = new Projet();
projet->_frequenceVideo = frequenceVideo;
if(workspace.exists())
{
if(video.exists())
{
if(workspace.mkdir(name))
{
projet->_project = new QDir(workspace.path()+"/"+name);
qDebug() << projet->_project->path();
projet->_project->mkdir("input");
projet->_input = new QDir(projet->_project->path()+"/input");
projet->_project->mkdir("output");
projet->_output = new QDir(projet->_project->path()+"/output");
video.copy(projet->_project->path()+"/input/video");
projet->_video = new QFile(projet->_project->path()+"/input/video");
QProcess process;
process.start("avconv -i " + projet->_project->path() +"/input/video -vsync 1 -s " + QString::number(sizeOutput.width()) + "x" + QString::number(projet->sizeOutput.height()) + " -r " + QString::number(projet->_frequenceVideo) + " -y " + projet->_project->path() + "/input/img%d.bmp");
process.waitForFinished(-1);
QStringList filters;
filters << "img*.bmp";
projet->_nbFrameVideo = projet->_input->entryList(filters).count();
qDebug() << "Nombre de frames : " << projet->_nbFrameVideo;
QFile file(projet->_project->path() + "/info");
file.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream out(&file);
out << QString::number(projet->_frequenceVideo) << "\n" << QString::number(projet->_nbFrameVideo);
file.close();
for(int i = 1; i <= projet->_nbFrameVideo; i++)
{
projet->_imagesVideo.push_back(new QImage(projet->_input->path()+"/img"+QString::number(i)+".bmp"));
QImage *image = new QImage(projet->sizeOutput.width(),projet->sizeOutput.height(),QImage::Format_ARGB32);
image->save(projet->_output->path() + "/img" + QString::number(i) + ".png");
projet->_imagesOutput.push_back(image);
}
}
else
{
throw QString("Ce projet existe déjà");
}
}
else
{
throw QString("La vidéo n'existe pas");
}
}
else
{
throw QString("Le workspace n'existe pas");
}
return projet;
}
Projet* Projet::open(QDir &path)
{
Projet *projet = new Projet();
if(path.exists())
{
projet->_project = new QDir(path.path());
projet->_input = new QDir(path.path() + "/input");
projet->_output = new QDir(path.path() + "/output");
QFile info(projet->_project->path() + "/info");
if(info.exists())
{
info.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream in(&info);
QString string;
in >> string;
projet->_frequenceVideo = string.toInt();
in >> string;
projet->_nbFrameVideo = string.toInt();
qDebug() << "Frequence : " << projet->_frequenceVideo;
qDebug() << "Nombre de frames : " << projet->_nbFrameVideo;
}
else
{
throw QString("Le projet n'est pas complet");
}
if(projet->_input->exists() && projet->_output->exists())
{
projet->_video = new QFile(projet->_input->path() + "/video");
if(!projet->_video->exists())
{
throw QString("Le projet n'est pas complet");
}
for(int i = 1; i <= projet->_nbFrameVideo; i++)
{
try
{
projet->_imagesVideo.push_back(new QImage(projet->_input->path() + "/img" + QString::number(i) + ".bmp"));
projet->_imagesOutput.push_back(new QImage(projet->_output->path() + "/img" + QString::number(i) + ".png"));
}
catch(QException e)
{
throw QString("Le projet n'est pas complet");
}
}
}
else
{
throw QString("Ce projet est mal formé");
}
}
else
{
throw QString("Ce projet n'existe pas");
}
return projet;
}
void Projet::save()
{
for(size_t i = 0; i < _imagesOutput.size(); i++)
{
_imagesOutput.at(i)->save(_output->path()+"/img" + QString::number(i+1) + ".png");
}
}
void Projet::saveAs(QDir &projet)
{
if(projet.exists())
{
if(projet.count() == 0)
{
QProcess process;
process.start("cp -R " + _project->path() + " " + workspace.path() + "/" + name );
process.waitForFinished(-1);
}
else
{
throw QString("Ce dossier n'est pas vide");
}
}
else
{
throw QString("Ce dossier n'existe pas");
}
}
<commit_msg>Correction of saveAs<commit_after>#include "projet.h"
#include <QtDebug>
#include <QProcess>
#include <QException>
#include <QPainter>
const QSize Projet::sizeOutput = QSize(1002, 561);
Projet::Projet()
{
}
QImage* Projet::getImageVideo(int number)
{
return _imagesVideo.at(number);
}
QImage* Projet::getImageOutput(int number)
{
return _imagesOutput.at(number);
}
int Projet::getNbFrameVideo()
{
return _nbFrameVideo;
}
Projet* Projet::create(QString &name, QDir &workspace, QFile &video, int frequenceVideo)
{
Projet *projet = new Projet();
projet->_frequenceVideo = frequenceVideo;
if(workspace.exists())
{
if(video.exists())
{
if(workspace.mkdir(name))
{
projet->_project = new QDir(workspace.path()+"/"+name);
qDebug() << projet->_project->path();
projet->_project->mkdir("input");
projet->_input = new QDir(projet->_project->path()+"/input");
projet->_project->mkdir("output");
projet->_output = new QDir(projet->_project->path()+"/output");
video.copy(projet->_project->path()+"/input/video");
projet->_video = new QFile(projet->_project->path()+"/input/video");
QProcess process;
process.start("avconv -i " + projet->_project->path() +"/input/video -vsync 1 -s " + QString::number(sizeOutput.width()) + "x" + QString::number(projet->sizeOutput.height()) + " -r " + QString::number(projet->_frequenceVideo) + " -y " + projet->_project->path() + "/input/img%d.bmp");
process.waitForFinished(-1);
QStringList filters;
filters << "img*.bmp";
projet->_nbFrameVideo = projet->_input->entryList(filters).count();
qDebug() << "Nombre de frames : " << projet->_nbFrameVideo;
QFile file(projet->_project->path() + "/info");
file.open(QIODevice::WriteOnly | QIODevice::Text);
QTextStream out(&file);
out << QString::number(projet->_frequenceVideo) << "\n" << QString::number(projet->_nbFrameVideo);
file.close();
for(int i = 1; i <= projet->_nbFrameVideo; i++)
{
projet->_imagesVideo.push_back(new QImage(projet->_input->path()+"/img"+QString::number(i)+".bmp"));
QImage *image = new QImage(projet->sizeOutput.width(),projet->sizeOutput.height(),QImage::Format_ARGB32);
image->save(projet->_output->path() + "/img" + QString::number(i) + ".png");
projet->_imagesOutput.push_back(image);
}
}
else
{
throw QString("Ce projet existe déjà");
}
}
else
{
throw QString("La vidéo n'existe pas");
}
}
else
{
throw QString("Le workspace n'existe pas");
}
return projet;
}
Projet* Projet::open(QDir &path)
{
Projet *projet = new Projet();
if(path.exists())
{
projet->_project = new QDir(path.path());
projet->_input = new QDir(path.path() + "/input");
projet->_output = new QDir(path.path() + "/output");
QFile info(projet->_project->path() + "/info");
if(info.exists())
{
info.open(QIODevice::ReadOnly | QIODevice::Text);
QTextStream in(&info);
QString string;
in >> string;
projet->_frequenceVideo = string.toInt();
in >> string;
projet->_nbFrameVideo = string.toInt();
qDebug() << "Frequence : " << projet->_frequenceVideo;
qDebug() << "Nombre de frames : " << projet->_nbFrameVideo;
}
else
{
throw QString("Le projet n'est pas complet");
}
if(projet->_input->exists() && projet->_output->exists())
{
projet->_video = new QFile(projet->_input->path() + "/video");
if(!projet->_video->exists())
{
throw QString("Le projet n'est pas complet");
}
for(int i = 1; i <= projet->_nbFrameVideo; i++)
{
try
{
projet->_imagesVideo.push_back(new QImage(projet->_input->path() + "/img" + QString::number(i) + ".bmp"));
projet->_imagesOutput.push_back(new QImage(projet->_output->path() + "/img" + QString::number(i) + ".png"));
}
catch(QException e)
{
throw QString("Le projet n'est pas complet");
}
}
}
else
{
throw QString("Ce projet est mal formé");
}
}
else
{
throw QString("Ce projet n'existe pas");
}
return projet;
}
void Projet::save()
{
for(size_t i = 0; i < _imagesOutput.size(); i++)
{
_imagesOutput.at(i)->save(_output->path()+"/img" + QString::number(i+1) + ".png");
}
}
void Projet::saveAs(QDir &projet)
{
if(projet.exists())
{
if(projet.count() == 2) //Les 2 correspond à . et ..
{
QProcess::execute("cp -r " + _project->absolutePath() + "/input " + projet.absolutePath() + "/" + name + "/");
QProcess::execute("cp -r " + _project->absolutePath() + "/output " + projet.absolutePath() + "/" + name + "/");
QProcess::execute("cp -r " + _project->absolutePath() + "/info " + projet.absolutePath() + "/" + name + "/");
}
else
{
throw QString("Ce dossier n'est pas vide");
}
}
else
{
QString name(projet.dirName());
if(projet.cdUp() && projet.mkdir(name))
{
QProcess::execute("cp -r " + _project->absolutePath() + "/input " + projet.absolutePath() + "/" + name + "/");
QProcess::execute("cp -r " + _project->absolutePath() + "/output " + projet.absolutePath() + "/" + name + "/");
QProcess::execute("cp -r " + _project->absolutePath() + "/info " + projet.absolutePath() + "/" + name + "/");
}
else
{
throw QString("Ce dossier n'existe pas");
}
}
}
<|endoftext|>
|
<commit_before>#include "Debug.h"
#include "Editor.h"
#include "Renderer.h"
#include "Color.h"
#include <cstdio>
Editor::Editor(EditorState& editorState, bool wantsFocus)
: mEditorState(editorState), mFocus(NULL), mModal(NULL), mIsDirty(true), mRedraw(true), mParent(NULL), mNumChildren(0), mWantsFocus(wantsFocus)
{
mThisArea.x = 0;
mThisArea.y = 0;
}
Editor::~Editor() {}
Editor * Editor::getFocus()
{
if (mParent)
return mParent->getFocus();
return mFocus;
}
void Editor::setFocus(Editor *editor)
{
if (mParent)
mParent->setFocus(editor);
else
{
if (mFocus)
mFocus->setDirty(true);
mFocus = editor;
if (editor)
editor->setDirty(true);
}
}
bool Editor::onEvent(SDL_Event& event)
{
return false;
}
void Editor::setDirty(bool dirty)
{
mIsDirty = dirty;
if (!dirty)
mRedraw = false;
if (dirty && mParent != NULL)
mParent->setDirty(true);
}
bool Editor::shouldRedrawBackground() const
{
return mRedraw;
}
bool Editor::isDirty() const
{
return mIsDirty || hasDirty();
}
void Editor::addChild(Editor *child, int x, int y, int w, int h)
{
child->mParent = this;
SDL_Rect& area = mChildrenArea[mNumChildren];
area.x = x;
area.y = y;
area.w = w;
area.h = h;
mChildren[mNumChildren++] = child;
SDL_Rect absArea = {area.x + mThisArea.x, area.y + mThisArea.y, area.w, area.h};
child->setArea(absArea);
}
void Editor::setArea(const SDL_Rect& area)
{
mThisArea.x = area.x;
mThisArea.y = area.y;
mThisArea.w = area.w;
mThisArea.h = area.h;
if (mParent) mParent->childAreaChanged(this);
onAreaChanged(mThisArea);
}
const SDL_Rect& Editor::getArea() const
{
return mThisArea;
}
void Editor::onAreaChanged(const SDL_Rect& area)
{
}
bool Editor::hasDirty() const
{
for (int i = 0 ; i < mNumChildren ; ++i)
if (mChildren[i]->isDirty())
return true;
return false;
}
bool Editor::hasFocus()
{
return getFocus() == this;
}
bool Editor::isFocusable() const
{
return mWantsFocus;
}
void Editor::onListenableChange(Listenable *listenable)
{
setDirty(true);
}
void Editor::drawCoveredChildren(Renderer& renderer, const SDL_Rect& area, const SDL_Rect& childArea, int maxIndex)
{
renderer.renderBackground(childArea);
for (int index = 0 ; index <= maxIndex && index < mNumChildren ; ++index)
{
SDL_Rect thisChildArea = mChildrenArea[index];
thisChildArea.x += area.x;
thisChildArea.y += area.y;
SDL_Rect intersection;
if (intersectRect(childArea, thisChildArea, intersection))
{
renderer.setClip(intersection);
mChildren[index]->draw(renderer, thisChildArea);
}
}
}
void Editor::drawChildren(Renderer& renderer, const SDL_Rect& area)
{
for (int index = 0 ; index < mNumChildren ; ++index)
{
if (mChildren[index]->isDirty())
{
SDL_Rect childArea = mChildrenArea[index];
childArea.x += area.x;
childArea.y += area.y;
drawCoveredChildren(renderer, area, childArea, index - 1);
renderer.setClip(childArea);
mChildren[index]->draw(renderer, childArea);
}
}
}
void Editor::drawModal(Renderer& renderer)
{
if (mModal != NULL)
{
if (mModal->shouldRedrawBackground())
{
// Draw plain black background with white border
renderer.clearRect(mModal->getArea(), Color(0, 0, 0));
renderer.drawRect(mModal->getArea(), Color(255, 255, 255));
}
SDL_Rect modalContent = mModal->getArea();
modalContent.x += 2;
modalContent.y += 2;
modalContent.w -= 4;
modalContent.h -= 4;
mModal->draw(renderer, modalContent);
}
}
void Editor::setModal(Editor *modal)
{
if (mModal != NULL)
mModal->mParent = NULL;
mModal = modal;
if (mModal != NULL)
{
mModal->mParent = this;
SDL_Rect modalArea = { mThisArea.x + 16, mThisArea.y + 16, mThisArea.w - 32, mThisArea.h - 32 };
mModal->setArea(modalArea);
}
invalidateAll();
}
void Editor::onFileSelectorEvent(const Editor& fileSelector, bool accept)
{
}
void Editor::invalidateAll()
{
setDirty(true);
mRedraw = true;
for (int index = 0 ; index < mNumChildren ; ++index)
{
mChildren[index]->invalidateAll();
}
if (mModal)
mModal->invalidateAll();
}
void Editor::onMessageBoxEvent(const Editor& messageBox, int code)
{
}
void Editor::draw(Renderer& renderer, const SDL_Rect& area)
{
// This should fix problems with modal backgrounds not being updated
// and perhaps also other child Editors.
invalidateAll();
if (mModal == NULL)
{
this->onDraw(renderer, area);
drawChildren(renderer, area);
}
else
{
drawModal(renderer);
}
setDirty(false);
}
void Editor::invalidateParent()
{
if (mParent)
mParent->invalidateAll();
}
bool Editor::pointInRect(const SDL_Point& point, const SDL_Rect& rect)
{
#ifdef SDL_PointInRect
return SDL_PointInRect(&point, &rect);
#else
// In case we are using SDL <2.0.4 (of whatever the version is
// where the rect built-in functions are introduced. E.g. my
// PocketCHIP only goes up to 2.0.2 by default.
return point.x >= rect.x && point.x < rect.x + rect.w &&
point.y >= rect.y && point.y < rect.y + rect.h;
#endif
}
bool Editor::intersectRect(const SDL_Rect& a, const SDL_Rect& b, SDL_Rect& result)
{
#ifdef SDL_IntersectRect
return SDL_IntersectRect(&point, &rect, &result);
#else
// In case we are using SDL <2.0.4 (of whatever the version is
// where the rect built-in functions are introduced. E.g. my
// PocketCHIP only goes up to 2.0.2 by default.
int aRight = a.x + a.w;
int aBottom = a.y + a.h;
int bRight = b.x + b.w;
int bBottom = b.y + b.h;
if (!(a.x < bRight && aRight > b.x && a.y < bBottom && aBottom > b.y))
return false;
result.x = std::max(a.x, b.x);
result.y = std::max(a.y, b.y);
result.w = std::min(aRight, bRight) - result.x;
result.h = std::min(aBottom, bBottom) - result.y;
return true;
#endif
}
void Editor::showTooltipV(const SDL_Rect& area, const char* message, ...)
{
char dest[1024];
va_list argptr;
va_start(argptr, message);
vsnprintf(dest, sizeof(dest), message, argptr);
va_end(argptr);
showTooltip(area, dest);
}
void Editor::showTooltip(const SDL_Rect& area, const char* message)
{
if (mParent != NULL)
mParent->showTooltip(area, message);
}
void Editor::showMessageV(MessageClass messageClass, const char* message, ...)
{
char dest[1024];
va_list argptr;
va_start(argptr, message);
vsnprintf(dest, sizeof(dest), message, argptr);
va_end(argptr);
showMessage(messageClass, dest);
}
void Editor::showMessage(MessageClass messageClass, const char* message)
{
if (mParent != NULL)
mParent->showMessage(messageClass, message);
else
debug("[%s] %s", messageClass == MessageInfo ? "INFO" : "ERROR", message);
}
void Editor::onUpdate(int ms)
{
}
void Editor::update(int ms)
{
onUpdate(ms);
for (int index = 0 ; index < mNumChildren ; ++index)
{
mChildren[index]->update(ms);
}
}
void Editor::onLoaded()
{
for (int index = 0 ; index < mNumChildren ; ++index)
{
mChildren[index]->onLoaded();
}
}
void Editor::childAreaChanged(Editor *child)
{
for (int index = 0 ; index < mNumChildren ; ++index)
{
if (mChildren[index] == child)
mChildrenArea[index] = child->getArea();
}
}
<commit_msg>Render modal border outside window area<commit_after>#include "Debug.h"
#include "Editor.h"
#include "Renderer.h"
#include "Color.h"
#include <cstdio>
#define MODAL_BORDER 2
Editor::Editor(EditorState& editorState, bool wantsFocus)
: mEditorState(editorState), mFocus(NULL), mModal(NULL), mIsDirty(true), mRedraw(true), mParent(NULL), mNumChildren(0), mWantsFocus(wantsFocus)
{
mThisArea.x = 0;
mThisArea.y = 0;
}
Editor::~Editor() {}
Editor * Editor::getFocus()
{
if (mParent)
return mParent->getFocus();
return mFocus;
}
void Editor::setFocus(Editor *editor)
{
if (mParent)
mParent->setFocus(editor);
else
{
if (mFocus)
mFocus->setDirty(true);
mFocus = editor;
if (editor)
editor->setDirty(true);
}
}
bool Editor::onEvent(SDL_Event& event)
{
return false;
}
void Editor::setDirty(bool dirty)
{
mIsDirty = dirty;
if (!dirty)
mRedraw = false;
if (dirty && mParent != NULL)
mParent->setDirty(true);
}
bool Editor::shouldRedrawBackground() const
{
return mRedraw;
}
bool Editor::isDirty() const
{
return mIsDirty || hasDirty();
}
void Editor::addChild(Editor *child, int x, int y, int w, int h)
{
child->mParent = this;
SDL_Rect& area = mChildrenArea[mNumChildren];
area.x = x;
area.y = y;
area.w = w;
area.h = h;
mChildren[mNumChildren++] = child;
SDL_Rect absArea = {area.x + mThisArea.x, area.y + mThisArea.y, area.w, area.h};
child->setArea(absArea);
}
void Editor::setArea(const SDL_Rect& area)
{
mThisArea.x = area.x;
mThisArea.y = area.y;
mThisArea.w = area.w;
mThisArea.h = area.h;
if (mParent) mParent->childAreaChanged(this);
onAreaChanged(mThisArea);
}
const SDL_Rect& Editor::getArea() const
{
return mThisArea;
}
void Editor::onAreaChanged(const SDL_Rect& area)
{
}
bool Editor::hasDirty() const
{
for (int i = 0 ; i < mNumChildren ; ++i)
if (mChildren[i]->isDirty())
return true;
return false;
}
bool Editor::hasFocus()
{
return getFocus() == this;
}
bool Editor::isFocusable() const
{
return mWantsFocus;
}
void Editor::onListenableChange(Listenable *listenable)
{
setDirty(true);
}
void Editor::drawCoveredChildren(Renderer& renderer, const SDL_Rect& area, const SDL_Rect& childArea, int maxIndex)
{
renderer.renderBackground(childArea);
for (int index = 0 ; index <= maxIndex && index < mNumChildren ; ++index)
{
SDL_Rect thisChildArea = mChildrenArea[index];
thisChildArea.x += area.x;
thisChildArea.y += area.y;
SDL_Rect intersection;
if (intersectRect(childArea, thisChildArea, intersection))
{
renderer.setClip(intersection);
mChildren[index]->draw(renderer, thisChildArea);
}
}
}
void Editor::drawChildren(Renderer& renderer, const SDL_Rect& area)
{
for (int index = 0 ; index < mNumChildren ; ++index)
{
if (mChildren[index]->isDirty())
{
SDL_Rect childArea = mChildrenArea[index];
childArea.x += area.x;
childArea.y += area.y;
drawCoveredChildren(renderer, area, childArea, index - 1);
renderer.setClip(childArea);
mChildren[index]->draw(renderer, childArea);
}
}
}
void Editor::drawModal(Renderer& renderer)
{
if (mModal != NULL)
{
if (mModal->shouldRedrawBackground())
{
// Draw plain black background with white border
SDL_Rect modalBorder = mModal->getArea();
modalBorder.x -= MODAL_BORDER;
modalBorder.y -= MODAL_BORDER;
modalBorder.w += MODAL_BORDER * 2;
modalBorder.h += MODAL_BORDER * 2;
renderer.clearRect(modalBorder, Color(0, 0, 0));
renderer.drawRect(modalBorder, Color(255, 255, 255));
}
mModal->draw(renderer, mModal->getArea());
}
}
void Editor::setModal(Editor *modal)
{
if (mModal != NULL)
mModal->mParent = NULL;
mModal = modal;
if (mModal != NULL)
{
mModal->mParent = this;
SDL_Rect modalArea = { mThisArea.x + 16, mThisArea.y + 16,
mThisArea.w - 32, mThisArea.h - 32 };
mModal->setArea(modalArea);
}
invalidateAll();
}
void Editor::onFileSelectorEvent(const Editor& fileSelector, bool accept)
{
}
void Editor::invalidateAll()
{
setDirty(true);
mRedraw = true;
for (int index = 0 ; index < mNumChildren ; ++index)
{
mChildren[index]->invalidateAll();
}
if (mModal)
mModal->invalidateAll();
}
void Editor::onMessageBoxEvent(const Editor& messageBox, int code)
{
}
void Editor::draw(Renderer& renderer, const SDL_Rect& area)
{
// This should fix problems with modal backgrounds not being updated
// and perhaps also other child Editors.
invalidateAll();
if (mModal == NULL)
{
this->onDraw(renderer, area);
drawChildren(renderer, area);
}
else
{
drawModal(renderer);
}
setDirty(false);
}
void Editor::invalidateParent()
{
if (mParent)
mParent->invalidateAll();
}
bool Editor::pointInRect(const SDL_Point& point, const SDL_Rect& rect)
{
#ifdef SDL_PointInRect
return SDL_PointInRect(&point, &rect);
#else
// In case we are using SDL <2.0.4 (of whatever the version is
// where the rect built-in functions are introduced. E.g. my
// PocketCHIP only goes up to 2.0.2 by default.
return point.x >= rect.x && point.x < rect.x + rect.w &&
point.y >= rect.y && point.y < rect.y + rect.h;
#endif
}
bool Editor::intersectRect(const SDL_Rect& a, const SDL_Rect& b, SDL_Rect& result)
{
#ifdef SDL_IntersectRect
return SDL_IntersectRect(&point, &rect, &result);
#else
// In case we are using SDL <2.0.4 (of whatever the version is
// where the rect built-in functions are introduced. E.g. my
// PocketCHIP only goes up to 2.0.2 by default.
int aRight = a.x + a.w;
int aBottom = a.y + a.h;
int bRight = b.x + b.w;
int bBottom = b.y + b.h;
if (!(a.x < bRight && aRight > b.x && a.y < bBottom && aBottom > b.y))
return false;
result.x = std::max(a.x, b.x);
result.y = std::max(a.y, b.y);
result.w = std::min(aRight, bRight) - result.x;
result.h = std::min(aBottom, bBottom) - result.y;
return true;
#endif
}
void Editor::showTooltipV(const SDL_Rect& area, const char* message, ...)
{
char dest[1024];
va_list argptr;
va_start(argptr, message);
vsnprintf(dest, sizeof(dest), message, argptr);
va_end(argptr);
showTooltip(area, dest);
}
void Editor::showTooltip(const SDL_Rect& area, const char* message)
{
if (mParent != NULL)
mParent->showTooltip(area, message);
}
void Editor::showMessageV(MessageClass messageClass, const char* message, ...)
{
char dest[1024];
va_list argptr;
va_start(argptr, message);
vsnprintf(dest, sizeof(dest), message, argptr);
va_end(argptr);
showMessage(messageClass, dest);
}
void Editor::showMessage(MessageClass messageClass, const char* message)
{
if (mParent != NULL)
mParent->showMessage(messageClass, message);
else
debug("[%s] %s", messageClass == MessageInfo ? "INFO" : "ERROR", message);
}
void Editor::onUpdate(int ms)
{
}
void Editor::update(int ms)
{
onUpdate(ms);
for (int index = 0 ; index < mNumChildren ; ++index)
{
mChildren[index]->update(ms);
}
}
void Editor::onLoaded()
{
for (int index = 0 ; index < mNumChildren ; ++index)
{
mChildren[index]->onLoaded();
}
}
void Editor::childAreaChanged(Editor *child)
{
for (int index = 0 ; index < mNumChildren ; ++index)
{
if (mChildren[index] == child)
mChildrenArea[index] = child->getArea();
}
}
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2012 Kolibre
This file is part of kolibre-narrator.
Kolibre-narrator 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.
Kolibre-narrator 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 kolibre-narrator. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Filter.h"
Filter::Filter()
{
setSetting(SETTING_USE_AA_FILTER, true);
setSetting(SETTING_AA_FILTER_LENGTH, 64);
setSetting(SETTING_USE_QUICKSEEK, false);
setSetting(SETTING_SEQUENCE_MS, 41);
setSetting(SETTING_SEEKWINDOW_MS, 28);
setSetting(SETTING_OVERLAP_MS, 8);
mTempo = 1.0;
mPitch = 1.0;
mGain = 1.0;
setTempo(mTempo);
setPitch(mPitch);
// Set sane defaults
open(44100, 2);
}
Filter::~Filter()
{
clear();
}
bool Filter::open(long rate, int channels)
{
if(mRate != rate || mChannels != channels) {
mRate = rate;
setSampleRate(mRate);
mChannels = channels;
setChannels(mChannels);
}
return true;
}
bool Filter::write(float *buffer, unsigned int samples)
{
putSamples(buffer, samples); // One sample contains data from all channels
return true;
}
unsigned int Filter::read(float *buffer, unsigned int bytes)
{
bytes = receiveSamples(buffer, bytes);
applyGain(buffer, bytes);
return bytes;
}
void Filter::applyGain(float *buffer, unsigned int samples)
{
// Change the gain on the buffer
static unsigned int i;
if(mGain == 1.0) return;
for(i = 0; i < samples; i++) {
buffer[i] = buffer[i] * mGain;
}
}
void Filter::fadeout(float *buffer, unsigned int bytes)
{
// Linear fadeout on the samples in the buffer
static unsigned int i;
float val = 1;
for(i = 0; i < bytes; i++) {
val = (bytes - i) / bytes;
buffer[i] = buffer[i] * val;
}
}
<commit_msg>Initialize variables<commit_after>/*
Copyright (C) 2012 Kolibre
This file is part of kolibre-narrator.
Kolibre-narrator 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.
Kolibre-narrator 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 kolibre-narrator. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Filter.h"
Filter::Filter()
{
setSetting(SETTING_USE_AA_FILTER, true);
setSetting(SETTING_AA_FILTER_LENGTH, 64);
setSetting(SETTING_USE_QUICKSEEK, false);
setSetting(SETTING_SEQUENCE_MS, 41);
setSetting(SETTING_SEEKWINDOW_MS, 28);
setSetting(SETTING_OVERLAP_MS, 8);
mTempo = 1.0;
mPitch = 1.0;
mGain = 1.0;
mRate = 0;
mChannels = 0;
setTempo(mTempo);
setPitch(mPitch);
// Set sane defaults
open(44100, 2);
}
Filter::~Filter()
{
clear();
}
bool Filter::open(long rate, int channels)
{
if(mRate != rate || mChannels != channels) {
mRate = rate;
setSampleRate(mRate);
mChannels = channels;
setChannels(mChannels);
}
return true;
}
bool Filter::write(float *buffer, unsigned int samples)
{
putSamples(buffer, samples); // One sample contains data from all channels
return true;
}
unsigned int Filter::read(float *buffer, unsigned int bytes)
{
bytes = receiveSamples(buffer, bytes);
applyGain(buffer, bytes);
return bytes;
}
void Filter::applyGain(float *buffer, unsigned int samples)
{
// Change the gain on the buffer
static unsigned int i;
if(mGain == 1.0) return;
for(i = 0; i < samples; i++) {
buffer[i] = buffer[i] * mGain;
}
}
void Filter::fadeout(float *buffer, unsigned int bytes)
{
// Linear fadeout on the samples in the buffer
static unsigned int i;
float val = 1;
for(i = 0; i < bytes; i++) {
val = (bytes - i) / bytes;
buffer[i] = buffer[i] * val;
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <cstring>
#include <wait.h>
#include <vector>
#include <fcntl.h>
#include <cstdlib>
#include <errno.h>
#include <sys/stat.h>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace boost;
void execfunction(char **argv, string command)
{
int pid = fork();
if(-1 == pid)
{
perror("There was an error with fork(). ");
}
else if(pid == 0)
{
if(-1 == execvp(command.c_str(), argv))
{
perror("There was an error with execvp() ");
exit(1);
}
_exit(0);
}
else
{
int status;
wait(&status);
if(-1 == status)
{
perror("There was an error with wait(). ");
}
}
}
int main()
{
int savestdout;
if(-1 == (savestdout = dup(1)))
{
perror("There was an error with dup(). ");
}
if(-1 == close(1))
{
perror("There was an error with close(). ");
}
vector<string> branches;
//call execvp to run git branch
string file_name = "tempfile";
int write_to;
char **argv = new char*[3];
argv[0] = const_cast<char*>("git");
argv[1] = const_cast<char*>("branch");
argv[2] = 0;
if(-1 == (write_to = open(file_name.c_str() , O_CREAT | O_WRONLY | O_APPEND | O_TRUNC, S_IRUSR | S_IWUSR)))
{
perror("There was an error with open(). ");
exit(1);
}
execfunction(argv, "git");
delete []argv;
if(-1 == close(write_to))
{
perror("There was an error with close(). ");
}
if(-1 == dup2(savestdout, 1))
{
perror("There was an error with dup2(). ");
}
int read_from;
if(-1 == (read_from = open(file_name.c_str(), O_RDONLY)))
{
perror("There was an error with open(). ");
}
int size;
char c[BUFSIZ];
if(-1 == (size = read(read_from, &c, BUFSIZ)))
{
perror("There was an error with read(). ");
}
while(size > 0)
{
branches.push_back(string(c));
if(-1 == (size = read(read_from, &c, BUFSIZ)))
{
perror("There was an error with read(). ");
}
}
if(-1 == close(read_from))
{
perror("There was an error with close(). ");
}
//take all branch names and put into vector
//for each branch name, call execvp git checkout branchname
string currBranch;
for(unsigned int i = 0; i < branches.size(); ++i)
{
if((branches.at(i)).at(0) == '*')
{
currBranch = (branches.at(i)).substr(2, (branches.at(i)).size()-3);
}
branches.at(i) = (branches.at(i)).substr(2, (branches.at(i)).size()-3);
cout << branches.at(i) << endl;
}
argv = new char*[3];
argv[0] = const_cast<char*>("rm");
argv[1] = const_cast<char*>(file_name.c_str());
argv[2] = 0;
execfunction(argv, "rm");
delete []argv;
//then open/create a file called branchname for whatever branch we are on
if(-1 == (savestdout = dup(1)))
{
perror("There was an error with dup(). ");
}
if(-1 == close(1))
{
perror("There was an error with close(). ");
}
int changed = 0;
for(unsigned int i = 0; i < branches.size(); ++i)
{
if(currBranch != branches.at(i))
{
argv = new char*[4];
argv[0] = const_cast<char*>("git");
argv[1] = const_cast<char*>("checkout");
argv[2] = const_cast<char*>((branches.at(i)).c_str());
argv[3] = 0;
execfunction(argv, "git");
delete []argv;
changed++;
}
string name = branches.at(i);
name += "Branch";
if(-1 == (write_to = open(name.c_str() , O_CREAT | O_WRONLY | O_APPEND | O_TRUNC, S_IRUSR | S_IWUSR)))
{
perror("There was an error with open(). ");
exit(1);
}
argv = new char*[3];
argv[0] = const_cast<char*>("git");
argv[1] = const_cast<char*>("log");
argv[2] = 0;
execfunction(argv, "git");
delete []argv;
if(-1 == close(write_to))
{
perror("There was an error with close(). ");
}
}
if(-1 == dup2(savestdout, 1))
{
perror("There was an error with dup2(). ");
}
if(changed > 0)
{
argv = new char*[4];
argv[0] = const_cast<char*>("git");
argv[1] = const_cast<char*>("checkout");
argv[2] = const_cast<char*>(currBranch.c_str());
argv[3] = 0;
execfunction(argv, "git");
delete []argv;
}
//then call execvp git log to have all the output go to file
//close file
return 0;
}
<commit_msg>updated fork<commit_after>#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <cstring>
#include <wait.h>
#include <vector>
#include <fcntl.h>
#include <cstdlib>
#include <errno.h>
#include <fstream>
#include <sys/stat.h>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace boost;
void execfunction(char **argv, string command)
{
int pid = fork();
if(-1 == pid)
{
perror("There was an error with fork(). ");
}
else if(pid == 0)
{
if(-1 == execvp(command.c_str(), argv))
{
perror("There was an error with execvp() ");
exit(1);
}
_exit(0);
}
else
{
int status;
wait(&status);
if(-1 == status)
{
perror("There was an error with wait(). ");
}
}
}
int main()
{
int savestdout;
if(-1 == (savestdout = dup(1)))
{
perror("There was an error with dup(). ");
}
if(-1 == close(1))
{
perror("There was an error with close(). ");
}
vector<string> branches;
//call execvp to run git branch
char file_name[7] = {'X','X','X','X','X','X',0};
int write_to;
char **argv = new char*[3];
argv[0] = const_cast<char*>("git");
argv[1] = const_cast<char*>("branch");
argv[2] = 0;
if(-1 == (write_to = mkstemp(file_name))) {
perror("There was an error with mkstemp(). ");
exit(1);
}
execfunction(argv, "git");
delete []argv;
if(-1 == close(write_to))
{
perror("There was an error with close(). ");
}
if(-1 == dup2(savestdout, 1))
{
perror("There was an error with dup2(). ");
}
string line;
ifstream myfile(file_name);
while(myfile.good())
{
getline(myfile, line);
branches.push_back(line);
}
myfile.close();
argv = new char*[3];
argv[0] = const_cast<char*>("rm");
argv[1] = const_cast<char*>(file_name);
argv[2] = 0;
execfunction(argv, "rm");
delete []argv;
//take all branch names and put into vector
//for each branch name, call execvp git checkout branchname
string currBranch;
string temp;
for(unsigned int i = 0; i < branches.size()-1; ++i)
{
temp = branches.at(i);
if(temp.at(0) == '*')
{
currBranch = (temp).substr(2, temp.size()-2);
branches.at(i) = currBranch;
}
else
{
branches.at(i) = (temp).substr(2, temp.size()-2);
}
cout << branches.at(i) << endl;
}
//then open/create a file called branchname for whatever branch we are on
if(-1 == (savestdout = dup(1)))
{
perror("There was an error with dup(). ");
}
if(-1 == close(1))
{
perror("There was an error with close(). ");
}
int changed = 0;
for(unsigned int i = 0; i < branches.size(); ++i)
{
if(currBranch != branches.at(i))
{
argv = new char*[4];
argv[0] = const_cast<char*>("git");
argv[1] = const_cast<char*>("checkout");
argv[2] = const_cast<char*>((branches.at(i)).c_str());
argv[3] = 0;
execfunction(argv, "git");
delete []argv;
changed++;
}
string name = branches.at(i);
name += "Branch";
if(-1 == (write_to = open(name.c_str() , O_CREAT | O_WRONLY | O_APPEND | O_TRUNC, S_IRUSR | S_IWUSR)))
{
perror("There was an error with open(). ");
exit(1);
}
argv = new char*[3];
argv[0] = const_cast<char*>("git");
argv[1] = const_cast<char*>("log");
argv[2] = 0;
execfunction(argv, "git");
delete []argv;
if(-1 == close(write_to))
{
perror("There was an error with close(). ");
}
}
if(-1 == dup2(savestdout, 1))
{
perror("There was an error with dup2(). ");
}
if(changed > 0)
{
argv = new char*[4];
argv[0] = const_cast<char*>("git");
argv[1] = const_cast<char*>("checkout");
argv[2] = const_cast<char*>(currBranch.c_str());
argv[3] = 0;
execfunction(argv, "git");
delete []argv;
}
//then call execvp git log to have all the output go to file
//close file
return 0;
}
<|endoftext|>
|
<commit_before>/**
* This file is part of Slideshow.
* Copyright (C) 2008 David Sveningsson <ext@sidvind.com>
*
* Slideshow is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Slideshow is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Slideshow. If not, see <http://www.gnu.org/licenses/>.
*/
// Internal
#include "config.h"
#include "argument_parser.h"
#include "module.h"
#include "module_loader.h"
#include "Kernel.h"
#include "Graphics.h"
#include "OS.h"
#include "Log.h"
#include "Exceptions.h"
#include "Transition.h"
// IPC
#include "IPC/dbus.h"
// FSM
#include "state/State.h"
#include "state/InitialState.h"
#include "state/SwitchState.h"
#include "state/TransitionState.h"
#include "state/ViewState.h"
// libportable
#include <portable/Time.h>
#include <portable/Process.h>
#include <portable/string.h>
// libc
#include <cstdlib>
#include <cstdio>
#include <cstring>
// Platform
#include <sys/wait.h>
#include <signal.h>
#include <X11/Xlib.h>
#include <dirent.h>
#include <fnmatch.h>
#ifdef LINUX
//#include <sys/time.h>
#endif
#ifdef WIN32
#include <windows.h>
#endif
bool* daemon_running = NULL;
static const int mode_normal = 0;
static const int mode_list_transitions = 1;
void quit_signal(int){
Log::message(Log::Verbose, "Caught SIGQUIT\n");
signal(SIGQUIT, quit_signal);
*daemon_running = false;
}
Kernel::Kernel(int argc, const char* argv[]):
_width(800),
_height(600),
_frames(0),
_bin_id(1),
_fullscreen(0),
_daemon(0),
_verbose(1),
_stdin(0),
_mode(mode_normal),
_transition_name(NULL),
_transition_time(3.0f),
_switch_time(5.0f),
_graphics(NULL),
_browser(NULL),
_ipc(NULL),
_browser_string(NULL),
_logfile("slideshow.log"){
initTime();
moduleloader_init();
if ( !parse_argv(argc, argv) ){
throw ArgumentException("");
}
switch ( _mode ){
case mode_list_transitions:
print_transitions();
throw ExitException();
}
if ( !daemon() ){
print_licence_statement();
}
Log::initialize(_logfile);
Log::set_level( (Log::Severity)_verbose );
print_cli_arguments(argc, argv);
Log::flush();
///@todo HACK! Attempt to connect to an xserver.
Display* dpy = XOpenDisplay(NULL);
if( !dpy ) {
throw XlibException("Could not connect to an X server\n");
}
XCloseDisplay(dpy);
Log::message(Log::Info, "Kernel: Starting slideshow\n");
if ( daemon() ){
start_daemon();
}
init_graphics();
init_IPC();
init_browser();
init_fsm();
}
Kernel::~Kernel(){
if ( daemon() ){
Portable::daemon_stop(PACKAGE_NAME);
}
delete _browser;
delete _graphics;
delete _ipc;
moduleloader_cleanup();
free( _browser_string );
_browser = NULL;
_graphics = NULL;
_ipc = NULL;
Log::deinitialize();
}
void Kernel::init_graphics(){
_graphics = new Graphics(_width, _height, _fullscreen);
load_transition( _transition_name ? _transition_name : "fade" );
}
void Kernel::init_IPC(){
_ipc = new DBus(this, 50);
}
void Kernel::init_browser(){
char* password = NULL;
if ( _stdin ){
password = (char*)malloc(256);
scanf("%256s", password);
}
_browser = Browser::factory(_browser_string, password);
free(password);
if ( browser() ){
browser()->change_bin(_bin_id);
browser()->reload();
} else {
Log::message(Log::Warning, "No browser selected, you will not see any slides\n");
}
}
void Kernel::init_fsm(){
TransitionState::set_transition_time(_transition_time);
ViewState::set_view_time(_switch_time);
_state = new InitialState(_browser, _graphics, _ipc);
}
void Kernel::load_transition(const char* name){
struct module_context_t* context = module_open(name);
if ( !context ){
printf("Transition plugin not found\n");
return;
}
if ( module_type(context) != TRANSITION_MODULE ){
printf("Plugin is not a transition module not found\n");
return;
}
transition_module_t* m = (transition_module_t*)module_get(context);
_graphics->set_transition(m);
}
void Kernel::start_daemon(){
Portable::daemonize(PACKAGE_NAME);
if ( signal(SIGQUIT, quit_signal) == SIG_ERR ){
Log::message(Log::Fatal, "Kernel: Could not initialize signal handler!\n");
exit(3);
}
///@ hack
daemon_running = &_running;
}
void Kernel::print_licence_statement(){
printf("Slideshow Copyright (C) 2008 David Sveningsson <ext@sidvind.com>\n");
printf("This program comes with ABSOLUTELY NO WARRANTY.\n");
printf("This is free software, and you are welcome to redistribute it\n");
printf("under certain conditions; see COPYING or <http://www.gnu.org/licenses/>\n");
printf("for details.\n");
}
void Kernel::print_cli_arguments(int argc, const char* argv[]){
Log::message_begin(Log::Verbose);
Log::message_ex("Starting with \"");
for ( int i = 1; i < argc; i++ ){
if ( i > 1 ){
Log::message_ex(" ");
}
Log::message_ex_fmt("%s", argv[i]);
}
Log::message_ex("\n");
}
static int filter(const struct dirent* el){
return fnmatch("*.la", el->d_name, 0) == 0;
}
void Kernel::print_transitions(){
struct dirent **namelist;
int n;
n = scandir(pluginpath(), &namelist, filter, alphasort);
if (n < 0){
perror("scandir");
} else {
printf("Available transitions: \n");
for ( int i = 0; i < n; i++ ){
char* path;
asprintf(&path, "%s/%s", pluginpath(), namelist[i]->d_name);
free(namelist[i]);
struct module_context_t* context = module_open(path);
if ( !context ){
continue;
}
if ( module_type(context) != TRANSITION_MODULE ){
continue;
}
printf("%s\n", module_get_name(context));
module_close(context);
}
free(namelist);
}
}
void Kernel::run(){
_running = true;
_last_switch = getTime();
_transition_start = 0.0f;
while ( _running ){
OS::poll_events(_running);
_state = _state->action();
}
}
bool Kernel::parse_argv(int argc, const char* argv[]){
option_set_t options;
option_initialize(&options, argc, argv);
option_set_description(&options, "Slideshow is an application for showing text and images in a loop on monitors and projectors.");
option_add_flag(&options, "verbose", 'v', "Explain what is being done", &_verbose, 0);
option_add_flag(&options, "quiet", 'q', "Explain what is being done", &_verbose, 2);
option_add_flag(&options, "fullscreen", 'f', "Start in fullscreen mode", &_fullscreen, 1);
option_add_flag(&options, "daemon", 'd', "Run in background", &_daemon, 1);
option_add_flag(&options, "list-transitions", 0, "List available transitions", &_mode, mode_list_transitions);
option_add_flag(&options, "stdin-password", 0, "Except the input (e.g database password) to come from stdin", &_stdin, 1);
option_add_string(&options, "browser", 0, "Browser connection string. provider://user[:pass]@host[:port]/name", &_browser_string);
option_add_string(&options, "transition", 't', "Set slide transition plugin [fade]", &_transition_name);
option_add_int(&options, "collection-id", 'c', "ID of the collection to display", &_bin_id);
option_add_format(&options, "resolution", 'r', "Resolution", "WIDTHxHEIGHT", "%dx%d", &_width, &_height);
int n = option_parse(&options);
option_finalize(&options);
if ( n < 0 ){
return false;
}
if ( n != argc ){
printf("%d %d\n", n, argc);
printf("%s: unrecognized option '%s'\n", argv[0], argv[n+1]);
printf("Try `%s --help' for more information.\n", argv[0]);
return false;
}
return true;
}
void Kernel::play_video(const char* fullpath){
Log::message(Log::Info, "Kernel: Playing video \"%s\"\n", fullpath);
int status;
if ( fork() == 0 ){
execlp("mplayer", "", "-fs", "-really-quiet", fullpath, NULL);
exit(0);
}
::wait(&status);
}
void Kernel::quit(){
_running = false;
}
void Kernel::reload_browser(){
_browser->reload();
}
void Kernel::change_bin(unsigned int id){
Log::message(Log::Verbose, "Kernel: Switching to collection %d\n", id);
_browser->change_bin(id);
_browser->reload();
}
void Kernel::ipc_quit(){
delete _ipc;
_ipc = NULL;
}
void Kernel::debug_dumpqueue(){
_browser->dump_queue();
}
char* Kernel::real_path(const char* filename){
char* dst;
if ( filename[0] == '/' ){
dst = (char*)malloc(strlen(filename)+1);
strcpy(dst, filename);
} else {
if ( asprintf(&dst, "%s/%s", datapath(), filename) == -1 ){
Log::message(Log::Fatal, "Memory allocation failed!");
return NULL;
}
}
return dst;
}
const char* Kernel::datapath(){
const char* path = getenv("SLIDESHOW_DATA_DIR");
if ( !path ){
path = DATA_DIR;
}
return path;
}
const char* Kernel::pluginpath(){
const char* path = getenv("SLIDESHOW_PLUGIN_DIR");
if ( !path ){
path = PLUGIN_DIR;
}
return path;
}
<commit_msg>Releasing _browser_string as early as possible<commit_after>/**
* This file is part of Slideshow.
* Copyright (C) 2008 David Sveningsson <ext@sidvind.com>
*
* Slideshow is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Slideshow is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Slideshow. If not, see <http://www.gnu.org/licenses/>.
*/
// Internal
#include "config.h"
#include "argument_parser.h"
#include "module.h"
#include "module_loader.h"
#include "Kernel.h"
#include "Graphics.h"
#include "OS.h"
#include "Log.h"
#include "Exceptions.h"
#include "Transition.h"
// IPC
#include "IPC/dbus.h"
// FSM
#include "state/State.h"
#include "state/InitialState.h"
#include "state/SwitchState.h"
#include "state/TransitionState.h"
#include "state/ViewState.h"
// libportable
#include <portable/Time.h>
#include <portable/Process.h>
#include <portable/string.h>
// libc
#include <cstdlib>
#include <cstdio>
#include <cstring>
// Platform
#include <sys/wait.h>
#include <signal.h>
#include <X11/Xlib.h>
#include <dirent.h>
#include <fnmatch.h>
#ifdef LINUX
//#include <sys/time.h>
#endif
#ifdef WIN32
#include <windows.h>
#endif
bool* daemon_running = NULL;
static const int mode_normal = 0;
static const int mode_list_transitions = 1;
void quit_signal(int){
Log::message(Log::Verbose, "Caught SIGQUIT\n");
signal(SIGQUIT, quit_signal);
*daemon_running = false;
}
Kernel::Kernel(int argc, const char* argv[]):
_width(800),
_height(600),
_frames(0),
_bin_id(1),
_fullscreen(0),
_daemon(0),
_verbose(1),
_stdin(0),
_mode(mode_normal),
_transition_name(NULL),
_transition_time(3.0f),
_switch_time(5.0f),
_graphics(NULL),
_browser(NULL),
_ipc(NULL),
_browser_string(NULL),
_logfile("slideshow.log"){
initTime();
moduleloader_init();
if ( !parse_argv(argc, argv) ){
throw ArgumentException("");
}
switch ( _mode ){
case mode_list_transitions:
print_transitions();
throw ExitException();
}
if ( !daemon() ){
print_licence_statement();
}
Log::initialize(_logfile);
Log::set_level( (Log::Severity)_verbose );
print_cli_arguments(argc, argv);
Log::flush();
///@todo HACK! Attempt to connect to an xserver.
Display* dpy = XOpenDisplay(NULL);
if( !dpy ) {
throw XlibException("Could not connect to an X server\n");
}
XCloseDisplay(dpy);
Log::message(Log::Info, "Kernel: Starting slideshow\n");
if ( daemon() ){
start_daemon();
}
init_graphics();
init_IPC();
init_browser();
init_fsm();
}
Kernel::~Kernel(){
if ( daemon() ){
Portable::daemon_stop(PACKAGE_NAME);
}
delete _browser;
delete _graphics;
delete _ipc;
moduleloader_cleanup();
_browser = NULL;
_graphics = NULL;
_ipc = NULL;
Log::deinitialize();
}
void Kernel::init_graphics(){
_graphics = new Graphics(_width, _height, _fullscreen);
load_transition( _transition_name ? _transition_name : "fade" );
}
void Kernel::init_IPC(){
_ipc = new DBus(this, 50);
}
void Kernel::init_browser(){
char* password = NULL;
if ( _stdin ){
password = (char*)malloc(256);
scanf("%256s", password);
}
_browser = Browser::factory(_browser_string, password);
free(_browser_string);
free(password);
_browser_string = NULL;
if ( browser() ){
browser()->change_bin(_bin_id);
browser()->reload();
} else {
Log::message(Log::Warning, "No browser selected, you will not see any slides\n");
}
}
void Kernel::init_fsm(){
TransitionState::set_transition_time(_transition_time);
ViewState::set_view_time(_switch_time);
_state = new InitialState(_browser, _graphics, _ipc);
}
void Kernel::load_transition(const char* name){
struct module_context_t* context = module_open(name);
if ( !context ){
printf("Transition plugin not found\n");
return;
}
if ( module_type(context) != TRANSITION_MODULE ){
printf("Plugin is not a transition module not found\n");
return;
}
transition_module_t* m = (transition_module_t*)module_get(context);
_graphics->set_transition(m);
}
void Kernel::start_daemon(){
Portable::daemonize(PACKAGE_NAME);
if ( signal(SIGQUIT, quit_signal) == SIG_ERR ){
Log::message(Log::Fatal, "Kernel: Could not initialize signal handler!\n");
exit(3);
}
///@ hack
daemon_running = &_running;
}
void Kernel::print_licence_statement(){
printf("Slideshow Copyright (C) 2008 David Sveningsson <ext@sidvind.com>\n");
printf("This program comes with ABSOLUTELY NO WARRANTY.\n");
printf("This is free software, and you are welcome to redistribute it\n");
printf("under certain conditions; see COPYING or <http://www.gnu.org/licenses/>\n");
printf("for details.\n");
}
void Kernel::print_cli_arguments(int argc, const char* argv[]){
Log::message_begin(Log::Verbose);
Log::message_ex("Starting with \"");
for ( int i = 1; i < argc; i++ ){
if ( i > 1 ){
Log::message_ex(" ");
}
Log::message_ex_fmt("%s", argv[i]);
}
Log::message_ex("\n");
}
static int filter(const struct dirent* el){
return fnmatch("*.la", el->d_name, 0) == 0;
}
void Kernel::print_transitions(){
struct dirent **namelist;
int n;
n = scandir(pluginpath(), &namelist, filter, alphasort);
if (n < 0){
perror("scandir");
} else {
printf("Available transitions: \n");
for ( int i = 0; i < n; i++ ){
char* path;
asprintf(&path, "%s/%s", pluginpath(), namelist[i]->d_name);
free(namelist[i]);
struct module_context_t* context = module_open(path);
if ( !context ){
continue;
}
if ( module_type(context) != TRANSITION_MODULE ){
continue;
}
printf("%s\n", module_get_name(context));
module_close(context);
}
free(namelist);
}
}
void Kernel::run(){
_running = true;
_last_switch = getTime();
_transition_start = 0.0f;
while ( _running ){
OS::poll_events(_running);
_state = _state->action();
}
}
bool Kernel::parse_argv(int argc, const char* argv[]){
option_set_t options;
option_initialize(&options, argc, argv);
option_set_description(&options, "Slideshow is an application for showing text and images in a loop on monitors and projectors.");
option_add_flag(&options, "verbose", 'v', "Explain what is being done", &_verbose, 0);
option_add_flag(&options, "quiet", 'q', "Explain what is being done", &_verbose, 2);
option_add_flag(&options, "fullscreen", 'f', "Start in fullscreen mode", &_fullscreen, 1);
option_add_flag(&options, "daemon", 'd', "Run in background", &_daemon, 1);
option_add_flag(&options, "list-transitions", 0, "List available transitions", &_mode, mode_list_transitions);
option_add_flag(&options, "stdin-password", 0, "Except the input (e.g database password) to come from stdin", &_stdin, 1);
option_add_string(&options, "browser", 0, "Browser connection string. provider://user[:pass]@host[:port]/name", &_browser_string);
option_add_string(&options, "transition", 't', "Set slide transition plugin [fade]", &_transition_name);
option_add_int(&options, "collection-id", 'c', "ID of the collection to display", &_bin_id);
option_add_format(&options, "resolution", 'r', "Resolution", "WIDTHxHEIGHT", "%dx%d", &_width, &_height);
int n = option_parse(&options);
option_finalize(&options);
if ( n < 0 ){
return false;
}
if ( n != argc ){
printf("%d %d\n", n, argc);
printf("%s: unrecognized option '%s'\n", argv[0], argv[n+1]);
printf("Try `%s --help' for more information.\n", argv[0]);
return false;
}
return true;
}
void Kernel::play_video(const char* fullpath){
Log::message(Log::Info, "Kernel: Playing video \"%s\"\n", fullpath);
int status;
if ( fork() == 0 ){
execlp("mplayer", "", "-fs", "-really-quiet", fullpath, NULL);
exit(0);
}
::wait(&status);
}
void Kernel::quit(){
_running = false;
}
void Kernel::reload_browser(){
_browser->reload();
}
void Kernel::change_bin(unsigned int id){
Log::message(Log::Verbose, "Kernel: Switching to collection %d\n", id);
_browser->change_bin(id);
_browser->reload();
}
void Kernel::ipc_quit(){
delete _ipc;
_ipc = NULL;
}
void Kernel::debug_dumpqueue(){
_browser->dump_queue();
}
char* Kernel::real_path(const char* filename){
char* dst;
if ( filename[0] == '/' ){
dst = (char*)malloc(strlen(filename)+1);
strcpy(dst, filename);
} else {
if ( asprintf(&dst, "%s/%s", datapath(), filename) == -1 ){
Log::message(Log::Fatal, "Memory allocation failed!");
return NULL;
}
}
return dst;
}
const char* Kernel::datapath(){
const char* path = getenv("SLIDESHOW_DATA_DIR");
if ( !path ){
path = DATA_DIR;
}
return path;
}
const char* Kernel::pluginpath(){
const char* path = getenv("SLIDESHOW_PLUGIN_DIR");
if ( !path ){
path = PLUGIN_DIR;
}
return path;
}
<|endoftext|>
|
<commit_before>/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2020 David Shah <dave@ds0.me>
*
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "log.h"
#include "nextpnr.h"
#include "util.h"
NEXTPNR_NAMESPACE_BEGIN
namespace {
struct NexusFasmWriter
{
const Context *ctx;
std::ostream &out;
std::vector<std::string> fasm_ctx;
void push(const std::string &x) { fasm_ctx.push_back(x); }
void pop() { fasm_ctx.pop_back(); }
void pop(int N)
{
for (int i = 0; i < N; i++)
fasm_ctx.pop_back();
}
bool last_was_blank = true;
void blank()
{
if (!last_was_blank)
out << std::endl;
last_was_blank = true;
}
void write_prefix()
{
for (auto &x : fasm_ctx)
out << x << ".";
last_was_blank = false;
}
void write_bit(const std::string &name, bool value = true)
{
if (value) {
write_prefix();
out << name << std::endl;
}
}
void write_comment(const std::string &cmt) { out << "# " << cmt << std::endl; }
void write_vector(const std::string &name, const std::vector<bool> &value, bool invert = false)
{
write_prefix();
out << name << " = " << int(value.size()) << "'b";
for (auto bit : boost::adaptors::reverse(value))
out << ((bit ^ invert) ? '1' : '0');
out << std::endl;
}
void write_int_vector(const std::string &name, uint64_t value, int width, bool invert = false)
{
std::vector<bool> bits(width, false);
for (int i = 0; i < width; i++)
bits[i] = (value & (1ULL << i)) != 0;
write_vector(name, bits, invert);
}
void write_enum(const CellInfo *cell, const std::string &name, const std::string &defval = "")
{
auto fnd = cell->params.find(ctx->id(name));
if (fnd == cell->params.end()) {
if (!defval.empty())
write_bit(stringf("%s.%s", name.c_str(), defval.c_str()));
} else {
write_bit(stringf("%s.%s", name.c_str(), fnd->second.c_str()));
}
}
NexusFasmWriter(const Context *ctx, std::ostream &out) : ctx(ctx), out(out) {}
std::string tile_name(int loc, const PhysicalTileInfoPOD &tile)
{
int r = loc / ctx->chip_info->width;
int c = loc % ctx->chip_info->width;
return stringf("%sR%dC%d__%s", ctx->nameOf(tile.prefix), r, c, ctx->nameOf(tile.tiletype));
}
const PhysicalTileInfoPOD &tile_by_type_and_loc(int loc, IdString type)
{
auto &ploc = ctx->chip_info->grid[loc];
for (int i = 0; i < ploc.num_phys_tiles; i++) {
if (ploc.phys_tiles[i].tiletype == type.index)
return ploc.phys_tiles[i];
}
log_error("No tile of type %s found at location R%dC%d", ctx->nameOf(type), loc / ctx->chip_info->width,
loc % ctx->chip_info->width);
}
const PhysicalTileInfoPOD &tile_at_loc(int loc)
{
auto &ploc = ctx->chip_info->grid[loc];
NPNR_ASSERT(ploc.num_phys_tiles == 1);
return ploc.phys_tiles[0];
}
std::string escape_name(const std::string &name)
{
std::string escaped;
for (char c : name) {
if (c == ':')
escaped += "__";
else
escaped += c;
}
return escaped;
}
void push_tile(int loc, IdString tile_type) { push(tile_name(loc, tile_by_type_and_loc(loc, tile_type))); }
void push_tile(int loc) { push(tile_name(loc, tile_at_loc(loc))); }
void push_belname(BelId bel) { push(ctx->nameOf(ctx->bel_data(bel).name)); }
void write_pip(PipId pip)
{
auto &pd = ctx->pip_data(pip);
if (pd.flags & PIP_FIXED_CONN)
return;
std::string tile = tile_name(pip.tile, tile_by_type_and_loc(pip.tile, pd.tile_type));
std::string source_wire = escape_name(ctx->pip_src_wire_name(pip).str(ctx));
std::string dest_wire = escape_name(ctx->pip_dst_wire_name(pip).str(ctx));
write_bit(stringf("%s.PIP.%s.%s", tile.c_str(), dest_wire.c_str(), source_wire.c_str()));
}
void write_net(const NetInfo *net)
{
write_comment(stringf("Net %s", ctx->nameOf(net)));
std::set<PipId> sorted_pips;
for (auto &w : net->wires)
if (w.second.pip != PipId())
sorted_pips.insert(w.second.pip);
for (auto p : sorted_pips)
write_pip(p);
blank();
}
void write_comb(const CellInfo *cell)
{
BelId bel = cell->bel;
int z = ctx->bel_data(bel).z;
int k = z & 0x1;
char slice = 'A' + (z >> 3);
push_tile(bel.tile, id_PLC);
push(stringf("SLICE%c", slice));
if (cell->params.count(id_INIT))
write_int_vector(stringf("K%d.INIT[15:0]", k), int_or_default(cell->params, id_INIT, 0), 16);
#if 0
if (cell->lutInfo.is_carry) {
write_bit("MODE.CCU2");
write_enum(cell, "INJECT", "NO");
}
#endif
pop(2);
}
void write_ff(const CellInfo *cell)
{
BelId bel = cell->bel;
int z = ctx->bel_data(bel).z;
int k = z & 0x1;
char slice = 'A' + (z >> 3);
push_tile(bel.tile, id_PLC);
push(stringf("SLICE%c", slice));
push(stringf("REG%d", k));
write_bit("USED.YES");
write_enum(cell, "REGSET", "RESET");
write_enum(cell, "LSRMODE", "LSR");
write_enum(cell, "SEL", "DF");
pop();
write_enum(cell, "REGDDR");
write_enum(cell, "SRMODE");
write_enum(cell, "CLKMUX");
write_enum(cell, "CEMUX");
write_enum(cell, "LSRMUX");
write_enum(cell, "GSR");
pop(2);
}
void write_io33(const CellInfo *cell)
{
BelId bel = cell->bel;
push_tile(bel.tile);
push_belname(bel);
const NetInfo *t = get_net_or_empty(cell, id_T);
bool is_input = false, is_output = false;
if (t == nullptr || t->name == ctx->id("$PACKER_VCC_NET")) {
is_input = true;
} else if (t->name == ctx->id("$PACKER_GND_NET")) {
is_output = true;
}
const char *iodir = is_input ? "INPUT" : (is_output ? "OUTPUT" : "BIDIR");
write_bit(stringf("BASE_TYPE.%s_%s", iodir, str_or_default(cell->attrs, id_IO_TYPE, "LVCMOS33").c_str()));
pop(2);
}
void operator()()
{
// Write routing
for (auto n : sorted(ctx->nets)) {
write_net(n.second);
}
// Write cell config
for (auto c : sorted(ctx->cells)) {
const CellInfo *ci = c.second;
write_comment(stringf("# Cell %s", ctx->nameOf(ci)));
if (ci->type == id_OXIDE_COMB)
write_comb(ci);
else if (ci->type == id_OXIDE_FF)
write_ff(ci);
else if (ci->type == id_SEIO33_CORE)
write_io33(ci);
blank();
}
}
};
} // namespace
void Arch::write_fasm(std::ostream &out) const { NexusFasmWriter(getCtx(), out)(); }
NEXTPNR_NAMESPACE_END
<commit_msg>nexus: Add SEIO18 support<commit_after>/*
* nextpnr -- Next Generation Place and Route
*
* Copyright (C) 2020 David Shah <dave@ds0.me>
*
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "log.h"
#include "nextpnr.h"
#include "util.h"
NEXTPNR_NAMESPACE_BEGIN
namespace {
struct NexusFasmWriter
{
const Context *ctx;
std::ostream &out;
std::vector<std::string> fasm_ctx;
void push(const std::string &x) { fasm_ctx.push_back(x); }
void pop() { fasm_ctx.pop_back(); }
void pop(int N)
{
for (int i = 0; i < N; i++)
fasm_ctx.pop_back();
}
bool last_was_blank = true;
void blank()
{
if (!last_was_blank)
out << std::endl;
last_was_blank = true;
}
void write_prefix()
{
for (auto &x : fasm_ctx)
out << x << ".";
last_was_blank = false;
}
void write_bit(const std::string &name, bool value = true)
{
if (value) {
write_prefix();
out << name << std::endl;
}
}
void write_comment(const std::string &cmt) { out << "# " << cmt << std::endl; }
void write_vector(const std::string &name, const std::vector<bool> &value, bool invert = false)
{
write_prefix();
out << name << " = " << int(value.size()) << "'b";
for (auto bit : boost::adaptors::reverse(value))
out << ((bit ^ invert) ? '1' : '0');
out << std::endl;
}
void write_int_vector(const std::string &name, uint64_t value, int width, bool invert = false)
{
std::vector<bool> bits(width, false);
for (int i = 0; i < width; i++)
bits[i] = (value & (1ULL << i)) != 0;
write_vector(name, bits, invert);
}
void write_enum(const CellInfo *cell, const std::string &name, const std::string &defval = "")
{
auto fnd = cell->params.find(ctx->id(name));
if (fnd == cell->params.end()) {
if (!defval.empty())
write_bit(stringf("%s.%s", name.c_str(), defval.c_str()));
} else {
write_bit(stringf("%s.%s", name.c_str(), fnd->second.c_str()));
}
}
NexusFasmWriter(const Context *ctx, std::ostream &out) : ctx(ctx), out(out) {}
std::string tile_name(int loc, const PhysicalTileInfoPOD &tile)
{
int r = loc / ctx->chip_info->width;
int c = loc % ctx->chip_info->width;
return stringf("%sR%dC%d__%s", ctx->nameOf(tile.prefix), r, c, ctx->nameOf(tile.tiletype));
}
const PhysicalTileInfoPOD &tile_by_type_and_loc(int loc, IdString type)
{
auto &ploc = ctx->chip_info->grid[loc];
for (int i = 0; i < ploc.num_phys_tiles; i++) {
if (ploc.phys_tiles[i].tiletype == type.index)
return ploc.phys_tiles[i];
}
log_error("No tile of type %s found at location R%dC%d", ctx->nameOf(type), loc / ctx->chip_info->width,
loc % ctx->chip_info->width);
}
const PhysicalTileInfoPOD &tile_at_loc(int loc)
{
auto &ploc = ctx->chip_info->grid[loc];
NPNR_ASSERT(ploc.num_phys_tiles == 1);
return ploc.phys_tiles[0];
}
std::string escape_name(const std::string &name)
{
std::string escaped;
for (char c : name) {
if (c == ':')
escaped += "__";
else
escaped += c;
}
return escaped;
}
void push_tile(int loc, IdString tile_type) { push(tile_name(loc, tile_by_type_and_loc(loc, tile_type))); }
void push_tile(int loc) { push(tile_name(loc, tile_at_loc(loc))); }
void push_belname(BelId bel) { push(ctx->nameOf(ctx->bel_data(bel).name)); }
void write_pip(PipId pip)
{
auto &pd = ctx->pip_data(pip);
if (pd.flags & PIP_FIXED_CONN)
return;
std::string tile = tile_name(pip.tile, tile_by_type_and_loc(pip.tile, pd.tile_type));
std::string source_wire = escape_name(ctx->pip_src_wire_name(pip).str(ctx));
std::string dest_wire = escape_name(ctx->pip_dst_wire_name(pip).str(ctx));
write_bit(stringf("%s.PIP.%s.%s", tile.c_str(), dest_wire.c_str(), source_wire.c_str()));
}
void write_net(const NetInfo *net)
{
write_comment(stringf("Net %s", ctx->nameOf(net)));
std::set<PipId> sorted_pips;
for (auto &w : net->wires)
if (w.second.pip != PipId())
sorted_pips.insert(w.second.pip);
for (auto p : sorted_pips)
write_pip(p);
blank();
}
void write_comb(const CellInfo *cell)
{
BelId bel = cell->bel;
int z = ctx->bel_data(bel).z;
int k = z & 0x1;
char slice = 'A' + (z >> 3);
push_tile(bel.tile, id_PLC);
push(stringf("SLICE%c", slice));
if (cell->params.count(id_INIT))
write_int_vector(stringf("K%d.INIT[15:0]", k), int_or_default(cell->params, id_INIT, 0), 16);
#if 0
if (cell->lutInfo.is_carry) {
write_bit("MODE.CCU2");
write_enum(cell, "INJECT", "NO");
}
#endif
pop(2);
}
void write_ff(const CellInfo *cell)
{
BelId bel = cell->bel;
int z = ctx->bel_data(bel).z;
int k = z & 0x1;
char slice = 'A' + (z >> 3);
push_tile(bel.tile, id_PLC);
push(stringf("SLICE%c", slice));
push(stringf("REG%d", k));
write_bit("USED.YES");
write_enum(cell, "REGSET", "RESET");
write_enum(cell, "LSRMODE", "LSR");
write_enum(cell, "SEL", "DF");
pop();
write_enum(cell, "REGDDR");
write_enum(cell, "SRMODE");
write_enum(cell, "CLKMUX");
write_enum(cell, "CEMUX");
write_enum(cell, "LSRMUX");
write_enum(cell, "GSR");
pop(2);
}
void write_io33(const CellInfo *cell)
{
BelId bel = cell->bel;
push_tile(bel.tile);
push_belname(bel);
const NetInfo *t = get_net_or_empty(cell, id_T);
bool is_input = false, is_output = false;
if (t == nullptr || t->name == ctx->id("$PACKER_VCC_NET")) {
is_input = true;
} else if (t->name == ctx->id("$PACKER_GND_NET")) {
is_output = true;
}
const char *iodir = is_input ? "INPUT" : (is_output ? "OUTPUT" : "BIDIR");
write_bit(stringf("BASE_TYPE.%s_%s", iodir, str_or_default(cell->attrs, id_IO_TYPE, "LVCMOS33").c_str()));
pop(2);
}
void write_io18(const CellInfo *cell)
{
BelId bel = cell->bel;
push_tile(bel.tile);
push_belname(bel);
push("SEIO18");
const NetInfo *t = get_net_or_empty(cell, id_T);
bool is_input = false, is_output = false;
if (t == nullptr || t->name == ctx->id("$PACKER_VCC_NET")) {
is_input = true;
} else if (t->name == ctx->id("$PACKER_GND_NET")) {
is_output = true;
}
const char *iodir = is_input ? "INPUT" : (is_output ? "OUTPUT" : "BIDIR");
write_bit(stringf("BASE_TYPE.%s_%s", iodir, str_or_default(cell->attrs, id_IO_TYPE, "LVCMOS18H").c_str()));
pop(3);
}
void operator()()
{
// Write routing
for (auto n : sorted(ctx->nets)) {
write_net(n.second);
}
// Write cell config
for (auto c : sorted(ctx->cells)) {
const CellInfo *ci = c.second;
write_comment(stringf("# Cell %s", ctx->nameOf(ci)));
if (ci->type == id_OXIDE_COMB)
write_comb(ci);
else if (ci->type == id_OXIDE_FF)
write_ff(ci);
else if (ci->type == id_SEIO33_CORE)
write_io33(ci);
else if (ci->type == id_SEIO18_CORE)
write_io18(ci);
blank();
}
}
};
} // namespace
void Arch::write_fasm(std::ostream &out) const { NexusFasmWriter(getCtx(), out)(); }
NEXTPNR_NAMESPACE_END
<|endoftext|>
|
<commit_before>////////////
//
// File: Parser.cpp
// Module: RSD
// Author: Michael Farnsworth
// Copyright: (C)2012 by Michael Farnsworth, All Rights Reserved
// Content: RenderSpud scene data parser
//
////////////
#include <string>
#include <vector>
#include <Rsd/Parser.h>
#include "Tokenizer.h"
//
// Main grammar interface
//
void ParseFree(void *p, // The parser to be deleted
void (*freeProc)(void*)); // Function used to reclaim memory
void* ParseAlloc(void *(*mallocProc)(size_t));
void ParseTrace(FILE *traceFile, char *zTracePrompt);
void Parse(void *yyp, // The parser
int yymajor, // The major token code number
RenderSpud::Rsd::Parser::Token* yyminor, // The value for the token
RenderSpud::Rsd::Parser::ParserState *pState); // Optional %extra_argument parameter
//
// Reference grammar interface
//
void ReferenceParseFree(void *p, // The parser to be deleted
void (*freeProc)(void*)); // Function used to reclaim memory
void* ReferenceParseAlloc(void *(*mallocProc)(size_t));
void ReferenceParseTrace(FILE *traceFile, char *zTracePrompt);
void ReferenceParse(void *yyp, // The parser
int yymajor, // The major token code number
RenderSpud::Rsd::Parser::Token* yyminor, // The value for the token
RenderSpud::Rsd::Parser::ParserState *pState); // Optional %extra_argument parameter
namespace RenderSpud
{
namespace Rsd
{
namespace Parser
{
enum GrammarVariant
{
kMainGrammar,
kReferenceGrammar
};
int tokenTypeToLemonId(GrammarVariant variant, TokenType type)
{
if (variant == kMainGrammar)
{
// These ones match automatically
return static_cast<int>(type);
}
else if (variant == kReferenceGrammar)
{
switch (type)
{
case kTokenIdentifier:
return kReferenceToken_IDENTIFIER;
case kTokenAssign:
return kReferenceToken_ASSIGN;
case kTokenColon:
return kReferenceToken_COLON;
case kTokenAt:
return kReferenceToken_AT;
case kTokenSemicolon:
return kReferenceToken_SEMICOLON;
case kTokenComma:
return kReferenceToken_COMMA;
case kTokenDot:
return kReferenceToken_DOT;
case kTokenFloat:
return kReferenceToken_FLOAT;
case kTokenInteger:
return kReferenceToken_INTEGER;
case kTokenBoolean:
return kReferenceToken_BOOLEAN;
case kTokenString:
return kReferenceToken_STRING;
case kTokenLeftParen:
return kReferenceToken_LEFTPAREN;
case kTokenRightParen:
return kReferenceToken_RIGHTPAREN;
case kTokenLeftCurlyBracket:
return kReferenceToken_LEFTCURLYBRACKET;
case kTokenRightCurlyBracket:
return kReferenceToken_RIGHTCURLYBRACKET;
case kTokenLeftSquareBracket:
return kReferenceToken_LEFTSQUAREBRACKET;
case kTokenRightSquareBracket:
return kReferenceToken_RIGHTSQUAREBRACKET;
case kTokenInclude:
return kReferenceToken_INCLUDE;
default:
return static_cast<int>(kTokenInvalid);
}
}
return static_cast<int>(kTokenInvalid);
}
void Parser::parse(const std::string& input, Value& root)
{
//
// Tokenize / parse input into AST
//
ParserState state(root);
void *pParser = ParseAlloc(&(::operator new));
size_t index = 0;
std::vector<Token*> tokens;
while (index < input.length())
{
tokens.push_back(new Token());
Token& token = *tokens.back();
try
{
index = Token::parseToken(index,
input,
token,
state.m_currentLine,
state.m_currentPosition);
}
catch (TokenException tokenException)
{
// Rethrow token exceptions as parse errors, with more information
throw ParseException(std::string("Syntax error: invalid token '") +
input[index] + "'",
state.m_currentSource,
state.m_currentLine,
state.m_currentPosition);
}
// Feed tokens to the parser
if (token.type() != kTokenWhitespace)
{
Parse(pParser,
tokenTypeToLemonId(kMainGrammar, token.type()),
&token,
&state);
}
}
// Clean up the parser
Parse(pParser, 0, NULL, &state);
ParseFree(pParser, &(::operator delete));
// Clean up all the tokens we allocated
for (size_t i = 0; i < tokens.size(); ++i)
{
delete tokens[i];
}
}
void Parser::parseReference(const std::string& input, Reference& ref)
{
//
// Tokenize / parse input into AST
//
ParserState state(ref);
void *pParser = ReferenceParseAlloc(&(::operator new));
size_t index = 0;
std::vector<Token*> tokens;
while (index < input.length())
{
tokens.push_back(new Token());
Token& token = *tokens.back();
try
{
index = Token::parseToken(index,
input,
token,
state.m_currentLine,
state.m_currentPosition);
}
catch (TokenException tokenException)
{
// Rethrow token exceptions as parse errors, with more information
throw ParseException(std::string("Syntax error: invalid token '") +
input[index] + "'",
state.m_currentSource,
state.m_currentLine,
state.m_currentPosition);
}
// Feed tokens to the parser
if (token.type() != kTokenWhitespace)
{
ReferenceParse(pParser,
tokenTypeToLemonId(kReferenceGrammar, token.type()),
&token,
&state);
}
}
// Clean up the parser
ReferenceParse(pParser, 0, NULL, &state);
ReferenceParseFree(pParser, &(::operator delete));
// Clean up all the tokens we allocated
for (size_t i = 0; i < tokens.size(); ++i)
{
delete tokens[i];
}
}
} // namespace Parser
} // namespace Rsd
} // namespace RenderSpud
<commit_msg>Improved parser exception messages when they come from the tokenizer.<commit_after>////////////
//
// File: Parser.cpp
// Module: RSD
// Author: Michael Farnsworth
// Copyright: (C)2012 by Michael Farnsworth, All Rights Reserved
// Content: RenderSpud scene data parser
//
////////////
#include <string>
#include <vector>
#include <Rsd/Parser.h>
#include "Tokenizer.h"
//
// Main grammar interface
//
void ParseFree(void *p, // The parser to be deleted
void (*freeProc)(void*)); // Function used to reclaim memory
void* ParseAlloc(void *(*mallocProc)(size_t));
void ParseTrace(FILE *traceFile, char *zTracePrompt);
void Parse(void *yyp, // The parser
int yymajor, // The major token code number
RenderSpud::Rsd::Parser::Token* yyminor, // The value for the token
RenderSpud::Rsd::Parser::ParserState *pState); // Optional %extra_argument parameter
//
// Reference grammar interface
//
void ReferenceParseFree(void *p, // The parser to be deleted
void (*freeProc)(void*)); // Function used to reclaim memory
void* ReferenceParseAlloc(void *(*mallocProc)(size_t));
void ReferenceParseTrace(FILE *traceFile, char *zTracePrompt);
void ReferenceParse(void *yyp, // The parser
int yymajor, // The major token code number
RenderSpud::Rsd::Parser::Token* yyminor, // The value for the token
RenderSpud::Rsd::Parser::ParserState *pState); // Optional %extra_argument parameter
namespace RenderSpud
{
namespace Rsd
{
namespace Parser
{
enum GrammarVariant
{
kMainGrammar,
kReferenceGrammar
};
int tokenTypeToLemonId(GrammarVariant variant, TokenType type)
{
if (variant == kMainGrammar)
{
// These ones match automatically
return static_cast<int>(type);
}
else if (variant == kReferenceGrammar)
{
switch (type)
{
case kTokenIdentifier:
return kReferenceToken_IDENTIFIER;
case kTokenAssign:
return kReferenceToken_ASSIGN;
case kTokenColon:
return kReferenceToken_COLON;
case kTokenAt:
return kReferenceToken_AT;
case kTokenSemicolon:
return kReferenceToken_SEMICOLON;
case kTokenComma:
return kReferenceToken_COMMA;
case kTokenDot:
return kReferenceToken_DOT;
case kTokenFloat:
return kReferenceToken_FLOAT;
case kTokenInteger:
return kReferenceToken_INTEGER;
case kTokenBoolean:
return kReferenceToken_BOOLEAN;
case kTokenString:
return kReferenceToken_STRING;
case kTokenLeftParen:
return kReferenceToken_LEFTPAREN;
case kTokenRightParen:
return kReferenceToken_RIGHTPAREN;
case kTokenLeftCurlyBracket:
return kReferenceToken_LEFTCURLYBRACKET;
case kTokenRightCurlyBracket:
return kReferenceToken_RIGHTCURLYBRACKET;
case kTokenLeftSquareBracket:
return kReferenceToken_LEFTSQUAREBRACKET;
case kTokenRightSquareBracket:
return kReferenceToken_RIGHTSQUAREBRACKET;
case kTokenInclude:
return kReferenceToken_INCLUDE;
default:
return static_cast<int>(kTokenInvalid);
}
}
return static_cast<int>(kTokenInvalid);
}
void Parser::parse(const std::string& input, Value& root)
{
//
// Tokenize / parse input into AST
//
ParserState state(root);
void *pParser = ParseAlloc(&(::operator new));
size_t index = 0;
std::vector<Token*> tokens;
while (index < input.length())
{
tokens.push_back(new Token());
Token& token = *tokens.back();
try
{
index = Token::parseToken(index,
input,
token,
state.m_currentLine,
state.m_currentPosition);
}
catch (TokenException tokenException)
{
// Rethrow token exceptions as parse errors, with more information
throw ParseException(std::string("Syntax error: ") + tokenException.what(),
state.m_currentSource,
tokenException.line(),
tokenException.position());
}
// Feed tokens to the parser
if (token.type() != kTokenWhitespace)
{
Parse(pParser,
tokenTypeToLemonId(kMainGrammar, token.type()),
&token,
&state);
}
}
// Clean up the parser
Parse(pParser, 0, NULL, &state);
ParseFree(pParser, &(::operator delete));
// Clean up all the tokens we allocated
for (size_t i = 0; i < tokens.size(); ++i)
{
delete tokens[i];
}
}
void Parser::parseReference(const std::string& input, Reference& ref)
{
//
// Tokenize / parse input into AST
//
ParserState state(ref);
void *pParser = ReferenceParseAlloc(&(::operator new));
size_t index = 0;
std::vector<Token*> tokens;
while (index < input.length())
{
tokens.push_back(new Token());
Token& token = *tokens.back();
try
{
index = Token::parseToken(index,
input,
token,
state.m_currentLine,
state.m_currentPosition);
}
catch (TokenException tokenException)
{
// Rethrow token exceptions as parse errors, with more information
throw ParseException(std::string("Syntax error: ") + tokenException.what(),
state.m_currentSource,
tokenException.line(),
tokenException.position());
}
// Feed tokens to the parser
if (token.type() != kTokenWhitespace)
{
ReferenceParse(pParser,
tokenTypeToLemonId(kReferenceGrammar, token.type()),
&token,
&state);
}
}
// Clean up the parser
ReferenceParse(pParser, 0, NULL, &state);
ReferenceParseFree(pParser, &(::operator delete));
// Clean up all the tokens we allocated
for (size_t i = 0; i < tokens.size(); ++i)
{
delete tokens[i];
}
}
} // namespace Parser
} // namespace Rsd
} // namespace RenderSpud
<|endoftext|>
|
<commit_before>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009 - 2015 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Implementation of class QGCApplication
*
* @author Lorenz Meier <mavteam@student.ethz.ch>
*
*/
#include <QFile>
#include <QFlags>
#include <QThread>
#include <QSplashScreen>
#include <QPixmap>
#include <QDesktopWidget>
#include <QPainter>
#include <QStyleFactory>
#include <QAction>
#include <QDebug>
#include "configuration.h"
#include "QGC.h"
#include "QGCCore.h"
#include "MainWindow.h"
#include "GAudioOutput.h"
#include "CmdLineOptParser.h"
#ifdef QGC_RTLAB_ENABLED
#include "OpalLink.h"
#endif
#include "UDPLink.h"
#include "MAVLinkSimulationLink.h"
#include "SerialLink.h"
const char* QGCApplication::_deleteAllSettingsKey = "DeleteAllSettingsNextBoot";
const char* QGCApplication::_settingsVersionKey = "SettingsVersion";
const char* QGCApplication::_savedFilesLocationKey = "SavedFilesLocation";
const char* QGCApplication::_promptFlightDataSave = "PromptFLightDataSave";
const char* QGCApplication::_defaultSavedFileDirectoryName = "QGroundControl";
const char* QGCApplication::_savedFileMavlinkLogDirectoryName = "FlightData";
const char* QGCApplication::_savedFileParameterDirectoryName = "SavedParameters";
/**
* @brief Constructor for the main application.
*
* This constructor initializes and starts the whole application. It takes standard
* command-line parameters
*
* @param argc The number of command-line parameters
* @param argv The string array of parameters
**/
QGCApplication::QGCApplication(int &argc, char* argv[]) :
QApplication(argc, argv),
_mainWindow(NULL)
{
// Set application information
this->setApplicationName(QGC_APPLICATION_NAME);
this->setOrganizationName(QGC_ORG_NAME);
this->setOrganizationDomain(QGC_ORG_DOMAIN);
// Version string is build from component parts. Format is:
// vMajor.Minor.BuildNumber BuildType
QString versionString("v%1.%2.%3 %4");
versionString = versionString.arg(QGC_APPLICATION_VERSION_MAJOR).arg(QGC_APPLICATION_VERSION_MINOR).arg(QGC_APPLICATION_VERSION_BUILDNUMBER).arg(QGC_APPLICATION_VERSION_BUILDTYPE);
this->setApplicationVersion(versionString);
// Set settings format
QSettings::setDefaultFormat(QSettings::IniFormat);
// Parse command line options
bool fClearSettingsOptions = false; // Clear stored settings
CmdLineOpt_t rgCmdLineOptions[] = {
{ "--clear-settings", &fClearSettingsOptions },
// Add additional command line option flags here
};
ParseCmdLineOptions(argc, argv, rgCmdLineOptions, sizeof(rgCmdLineOptions)/sizeof(rgCmdLineOptions[0]), false);
QSettings settings;
// The setting will delete all settings on this boot
fClearSettingsOptions |= settings.contains(_deleteAllSettingsKey);
if (fClearSettingsOptions) {
// User requested settings to be cleared on command line
settings.clear();
settings.setValue(_settingsVersionKey, QGC_SETTINGS_VERSION);
settings.sync();
}
}
bool QGCApplication::init(void)
{
QSettings settings;
// Exit main application when last window is closed
connect(this, SIGNAL(lastWindowClosed()), this, SLOT(quit()));
// Show user an upgrade message if the settings version has been bumped up
bool settingsUpgraded = false;
enum MainWindow::CUSTOM_MODE mode = MainWindow::CUSTOM_MODE_PX4;
if (settings.contains(_settingsVersionKey)) {
if (settings.value(_settingsVersionKey).toInt() != QGC_SETTINGS_VERSION) {
settingsUpgraded = true;
}
} else if (settings.allKeys().count()) {
// Settings version key is missing and there are settings. This is an upgrade scenario.
settingsUpgraded = true;
}
if (settingsUpgraded) {
settings.clear();
settings.setValue(_settingsVersionKey, QGC_SETTINGS_VERSION);
}
// Load saved files location and validate
QString savedFilesLocation;
if (settings.contains(_savedFilesLocationKey)) {
savedFilesLocation = settings.value(_savedFilesLocationKey).toString();
} else {
// No location set. Create a default one in Documents standard location.
QString documentsLocation = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
QDir documentsDir(documentsLocation);
Q_ASSERT(documentsDir.exists());
bool pathCreated = documentsDir.mkpath(_defaultSavedFileDirectoryName);
Q_ASSERT(pathCreated);
savedFilesLocation = documentsDir.filePath(_defaultSavedFileDirectoryName);
settings.setValue(_savedFilesLocationKey, savedFilesLocation);
}
if (!savedFilesLocation.isEmpty()) {
if (!validatePossibleSavedFilesLocation(savedFilesLocation)) {
savedFilesLocation.clear();
}
}
// If we made it this far and we still don't have a location. Either the specfied location was invalid
// or we coudn't create a default location. Either way, we need to let the user know and prompt for a new
/// settings.
if (savedFilesLocation.isEmpty()) {
QMessageBox::warning(MainWindow::instance(),
tr("Bad save location"),
tr("The location to save files to is invalid, or cannot be written to. Please provide a new one."));
MainWindow::instance()->showSettings();
}
mode = (enum MainWindow::CUSTOM_MODE) settings.value("QGC_CUSTOM_MODE", (int)MainWindow::CUSTOM_MODE_PX4).toInt();
settings.sync();
// Show splash screen
QPixmap splashImage(":/files/images/splash.png");
QSplashScreen* splashScreen = new QSplashScreen(splashImage);
// Delete splash screen after mainWindow was displayed
splashScreen->setAttribute(Qt::WA_DeleteOnClose);
splashScreen->show();
processEvents();
splashScreen->showMessage(tr("Loading application fonts"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
// Load application font
QFontDatabase fontDatabase = QFontDatabase();
const QString fontFileName = ":/general/vera.ttf"; ///< Font file is part of the QRC file and compiled into the app
//const QString fontFamilyName = "Bitstream Vera Sans";
if(!QFile::exists(fontFileName)) printf("ERROR! font file: %s DOES NOT EXIST!\n", fontFileName.toStdString().c_str());
fontDatabase.addApplicationFont(fontFileName);
// Avoid Using setFont(). In the Qt docu you can read the following:
// "Warning: Do not use this function in conjunction with Qt Style Sheets."
// setFont(fontDatabase.font(fontFamilyName, "Roman", 12));
// Start the comm link manager
splashScreen->showMessage(tr("Starting communication links"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
startLinkManager();
// Start the UAS Manager
splashScreen->showMessage(tr("Starting UAS manager"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
startUASManager();
// Start the user interface
splashScreen->showMessage(tr("Starting user interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
_mainWindow = MainWindow::_create(splashScreen, mode);
UDPLink* udpLink = NULL;
if (_mainWindow->getCustomMode() == MainWindow::CUSTOM_MODE_WIFI)
{
// Connect links
// to make sure that all components are initialized when the
// first messages arrive
udpLink = new UDPLink(QHostAddress::Any, 14550);
LinkManager::instance()->add(udpLink);
} else {
// We want to have a default serial link available for "quick" connecting.
SerialLink *slink = new SerialLink();
LinkManager::instance()->add(slink);
}
#ifdef QGC_RTLAB_ENABLED
// Add OpalRT Link, but do not connect
OpalLink* opalLink = new OpalLink();
MainWindow::instance()->addLink(opalLink);
#endif
// Remove splash screen
splashScreen->finish(_mainWindow);
_mainWindow->splashScreenFinished();
if (settingsUpgraded) {
_mainWindow->showInfoMessage(tr("Settings Cleared"),
tr("The format for QGroundControl saved settings has been modified. "
"Your saved settings have been reset to defaults."));
}
// Check if link could be connected
if (udpLink && !LinkManager::instance()->connectLink(udpLink))
{
QMessageBox msgBox;
msgBox.setIcon(QMessageBox::Critical);
msgBox.setText("Could not connect UDP port. Is an instance of " + qAppName() + "already running?");
msgBox.setInformativeText("It is recommended to close the application and stop all instances. Click Yes to close.");
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::No);
int ret = msgBox.exec();
// Close the message box shortly after the click to prevent accidental clicks
QTimer::singleShot(15000, &msgBox, SLOT(reject()));
// Exit application
if (ret == QMessageBox::Yes)
{
//mainWindow->close();
QTimer::singleShot(200, _mainWindow, SLOT(close()));
}
}
return true;
}
/**
* @brief Destructor for the groundstation. It destroys all loaded instances.
*
**/
QGCApplication::~QGCApplication()
{
delete UASManager::instance();
delete LinkManager::instance();
}
/**
* @brief Start the link managing component.
*
* The link manager keeps track of all communication links and provides the global
* packet queue. It is the main communication hub
**/
void QGCApplication::startLinkManager()
{
LinkManager::instance();
}
/**
* @brief Start the Unmanned Air System Manager
*
**/
void QGCApplication::startUASManager()
{
// Load UAS plugins
QDir pluginsDir = QDir(qApp->applicationDirPath());
#if defined(Q_OS_WIN)
if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
pluginsDir.cdUp();
#elif defined(Q_OS_LINUX)
if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
pluginsDir.cdUp();
#elif defined(Q_OS_MAC)
if (pluginsDir.dirName() == "MacOS") {
pluginsDir.cdUp();
pluginsDir.cdUp();
pluginsDir.cdUp();
}
#endif
pluginsDir.cd("plugins");
UASManager::instance();
// Load plugins
QStringList pluginFileNames;
foreach (QString fileName, pluginsDir.entryList(QDir::Files)) {
QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));
QObject *plugin = loader.instance();
if (plugin) {
//populateMenus(plugin);
pluginFileNames += fileName;
//printf(QString("Loaded plugin from " + fileName + "\n").toStdString().c_str());
}
}
}
void QGCApplication::deleteAllSettingsNextBoot(void)
{
QSettings settings;
settings.setValue(_deleteAllSettingsKey, true);
}
void QGCApplication::clearDeleteAllSettingsNextBoot(void)
{
QSettings settings;
settings.remove(_deleteAllSettingsKey);
}
void QGCApplication::setSavedFilesLocation(QString& location)
{
QSettings settings;
settings.setValue(_savedFilesLocationKey, location);
}
bool QGCApplication::validatePossibleSavedFilesLocation(QString& location)
{
// Make sure we can write to the directory
QString filename = QDir(location).filePath("QGCTempXXXXXXXX.tmp");
QTemporaryFile tempFile(filename);
if (!tempFile.open()) {
return false;
}
return true;
}
QString QGCApplication::savedFilesLocation(void)
{
QSettings settings;
Q_ASSERT(settings.contains(_savedFilesLocationKey));
return settings.value(_savedFilesLocationKey).toString();
}
QString QGCApplication::savedParameterFilesLocation(void)
{
QString location;
QDir parentDir(savedFilesLocation());
location = parentDir.filePath(_savedFileParameterDirectoryName);
if (!QDir(location).exists()) {
// If directory doesn't exist, try to create it
if (!parentDir.mkpath(_savedFileParameterDirectoryName)) {
// Return an error
location.clear();
}
}
return location;
}
QString QGCApplication::mavlinkLogFilesLocation(void)
{
QString location;
QDir parentDir(savedFilesLocation());
location = parentDir.filePath(_savedFileMavlinkLogDirectoryName);
if (!QDir(location).exists()) {
// If directory doesn't exist, try to create it
if (!parentDir.mkpath(_savedFileMavlinkLogDirectoryName)) {
// Return an error
location.clear();
}
}
return location;
}
bool QGCApplication::promptFlightDataSave(void)
{
QSettings settings;
return settings.value(_promptFlightDataSave, true).toBool();
}
void QGCApplication::setPromptFlightDataSave(bool promptForSave)
{
QSettings settings;
settings.setValue(_promptFlightDataSave, promptForSave);
}
/// @brief Returns the QGCApplication object singleton.
QGCApplication* qgcApp(void)
{
QGCApplication* app = dynamic_cast<QGCApplication*>(qApp);
Q_ASSERT(app);
return app;
}
<commit_msg>Add Q_UNUSED to variable only used in Q_ASSERT<commit_after>/*=====================================================================
QGroundControl Open Source Ground Control Station
(c) 2009 - 2015 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
This file is part of the QGROUNDCONTROL project
QGROUNDCONTROL is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QGROUNDCONTROL 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 QGROUNDCONTROL. If not, see <http://www.gnu.org/licenses/>.
======================================================================*/
/**
* @file
* @brief Implementation of class QGCApplication
*
* @author Lorenz Meier <mavteam@student.ethz.ch>
*
*/
#include <QFile>
#include <QFlags>
#include <QThread>
#include <QSplashScreen>
#include <QPixmap>
#include <QDesktopWidget>
#include <QPainter>
#include <QStyleFactory>
#include <QAction>
#include <QDebug>
#include "configuration.h"
#include "QGC.h"
#include "QGCCore.h"
#include "MainWindow.h"
#include "GAudioOutput.h"
#include "CmdLineOptParser.h"
#ifdef QGC_RTLAB_ENABLED
#include "OpalLink.h"
#endif
#include "UDPLink.h"
#include "MAVLinkSimulationLink.h"
#include "SerialLink.h"
const char* QGCApplication::_deleteAllSettingsKey = "DeleteAllSettingsNextBoot";
const char* QGCApplication::_settingsVersionKey = "SettingsVersion";
const char* QGCApplication::_savedFilesLocationKey = "SavedFilesLocation";
const char* QGCApplication::_promptFlightDataSave = "PromptFLightDataSave";
const char* QGCApplication::_defaultSavedFileDirectoryName = "QGroundControl";
const char* QGCApplication::_savedFileMavlinkLogDirectoryName = "FlightData";
const char* QGCApplication::_savedFileParameterDirectoryName = "SavedParameters";
/**
* @brief Constructor for the main application.
*
* This constructor initializes and starts the whole application. It takes standard
* command-line parameters
*
* @param argc The number of command-line parameters
* @param argv The string array of parameters
**/
QGCApplication::QGCApplication(int &argc, char* argv[]) :
QApplication(argc, argv),
_mainWindow(NULL)
{
// Set application information
this->setApplicationName(QGC_APPLICATION_NAME);
this->setOrganizationName(QGC_ORG_NAME);
this->setOrganizationDomain(QGC_ORG_DOMAIN);
// Version string is build from component parts. Format is:
// vMajor.Minor.BuildNumber BuildType
QString versionString("v%1.%2.%3 %4");
versionString = versionString.arg(QGC_APPLICATION_VERSION_MAJOR).arg(QGC_APPLICATION_VERSION_MINOR).arg(QGC_APPLICATION_VERSION_BUILDNUMBER).arg(QGC_APPLICATION_VERSION_BUILDTYPE);
this->setApplicationVersion(versionString);
// Set settings format
QSettings::setDefaultFormat(QSettings::IniFormat);
// Parse command line options
bool fClearSettingsOptions = false; // Clear stored settings
CmdLineOpt_t rgCmdLineOptions[] = {
{ "--clear-settings", &fClearSettingsOptions },
// Add additional command line option flags here
};
ParseCmdLineOptions(argc, argv, rgCmdLineOptions, sizeof(rgCmdLineOptions)/sizeof(rgCmdLineOptions[0]), false);
QSettings settings;
// The setting will delete all settings on this boot
fClearSettingsOptions |= settings.contains(_deleteAllSettingsKey);
if (fClearSettingsOptions) {
// User requested settings to be cleared on command line
settings.clear();
settings.setValue(_settingsVersionKey, QGC_SETTINGS_VERSION);
settings.sync();
}
}
bool QGCApplication::init(void)
{
QSettings settings;
// Exit main application when last window is closed
connect(this, SIGNAL(lastWindowClosed()), this, SLOT(quit()));
// Show user an upgrade message if the settings version has been bumped up
bool settingsUpgraded = false;
enum MainWindow::CUSTOM_MODE mode = MainWindow::CUSTOM_MODE_PX4;
if (settings.contains(_settingsVersionKey)) {
if (settings.value(_settingsVersionKey).toInt() != QGC_SETTINGS_VERSION) {
settingsUpgraded = true;
}
} else if (settings.allKeys().count()) {
// Settings version key is missing and there are settings. This is an upgrade scenario.
settingsUpgraded = true;
}
if (settingsUpgraded) {
settings.clear();
settings.setValue(_settingsVersionKey, QGC_SETTINGS_VERSION);
}
// Load saved files location and validate
QString savedFilesLocation;
if (settings.contains(_savedFilesLocationKey)) {
savedFilesLocation = settings.value(_savedFilesLocationKey).toString();
} else {
// No location set. Create a default one in Documents standard location.
QString documentsLocation = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
QDir documentsDir(documentsLocation);
Q_ASSERT(documentsDir.exists());
bool pathCreated = documentsDir.mkpath(_defaultSavedFileDirectoryName);
Q_UNUSED(pathCreated);
Q_ASSERT(pathCreated);
savedFilesLocation = documentsDir.filePath(_defaultSavedFileDirectoryName);
settings.setValue(_savedFilesLocationKey, savedFilesLocation);
}
if (!savedFilesLocation.isEmpty()) {
if (!validatePossibleSavedFilesLocation(savedFilesLocation)) {
savedFilesLocation.clear();
}
}
// If we made it this far and we still don't have a location. Either the specfied location was invalid
// or we coudn't create a default location. Either way, we need to let the user know and prompt for a new
/// settings.
if (savedFilesLocation.isEmpty()) {
QMessageBox::warning(MainWindow::instance(),
tr("Bad save location"),
tr("The location to save files to is invalid, or cannot be written to. Please provide a new one."));
MainWindow::instance()->showSettings();
}
mode = (enum MainWindow::CUSTOM_MODE) settings.value("QGC_CUSTOM_MODE", (int)MainWindow::CUSTOM_MODE_PX4).toInt();
settings.sync();
// Show splash screen
QPixmap splashImage(":/files/images/splash.png");
QSplashScreen* splashScreen = new QSplashScreen(splashImage);
// Delete splash screen after mainWindow was displayed
splashScreen->setAttribute(Qt::WA_DeleteOnClose);
splashScreen->show();
processEvents();
splashScreen->showMessage(tr("Loading application fonts"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
// Load application font
QFontDatabase fontDatabase = QFontDatabase();
const QString fontFileName = ":/general/vera.ttf"; ///< Font file is part of the QRC file and compiled into the app
//const QString fontFamilyName = "Bitstream Vera Sans";
if(!QFile::exists(fontFileName)) printf("ERROR! font file: %s DOES NOT EXIST!\n", fontFileName.toStdString().c_str());
fontDatabase.addApplicationFont(fontFileName);
// Avoid Using setFont(). In the Qt docu you can read the following:
// "Warning: Do not use this function in conjunction with Qt Style Sheets."
// setFont(fontDatabase.font(fontFamilyName, "Roman", 12));
// Start the comm link manager
splashScreen->showMessage(tr("Starting communication links"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
startLinkManager();
// Start the UAS Manager
splashScreen->showMessage(tr("Starting UAS manager"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
startUASManager();
// Start the user interface
splashScreen->showMessage(tr("Starting user interface"), Qt::AlignLeft | Qt::AlignBottom, QColor(62, 93, 141));
_mainWindow = MainWindow::_create(splashScreen, mode);
UDPLink* udpLink = NULL;
if (_mainWindow->getCustomMode() == MainWindow::CUSTOM_MODE_WIFI)
{
// Connect links
// to make sure that all components are initialized when the
// first messages arrive
udpLink = new UDPLink(QHostAddress::Any, 14550);
LinkManager::instance()->add(udpLink);
} else {
// We want to have a default serial link available for "quick" connecting.
SerialLink *slink = new SerialLink();
LinkManager::instance()->add(slink);
}
#ifdef QGC_RTLAB_ENABLED
// Add OpalRT Link, but do not connect
OpalLink* opalLink = new OpalLink();
MainWindow::instance()->addLink(opalLink);
#endif
// Remove splash screen
splashScreen->finish(_mainWindow);
_mainWindow->splashScreenFinished();
if (settingsUpgraded) {
_mainWindow->showInfoMessage(tr("Settings Cleared"),
tr("The format for QGroundControl saved settings has been modified. "
"Your saved settings have been reset to defaults."));
}
// Check if link could be connected
if (udpLink && !LinkManager::instance()->connectLink(udpLink))
{
QMessageBox msgBox;
msgBox.setIcon(QMessageBox::Critical);
msgBox.setText("Could not connect UDP port. Is an instance of " + qAppName() + "already running?");
msgBox.setInformativeText("It is recommended to close the application and stop all instances. Click Yes to close.");
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::No);
int ret = msgBox.exec();
// Close the message box shortly after the click to prevent accidental clicks
QTimer::singleShot(15000, &msgBox, SLOT(reject()));
// Exit application
if (ret == QMessageBox::Yes)
{
//mainWindow->close();
QTimer::singleShot(200, _mainWindow, SLOT(close()));
}
}
return true;
}
/**
* @brief Destructor for the groundstation. It destroys all loaded instances.
*
**/
QGCApplication::~QGCApplication()
{
delete UASManager::instance();
delete LinkManager::instance();
}
/**
* @brief Start the link managing component.
*
* The link manager keeps track of all communication links and provides the global
* packet queue. It is the main communication hub
**/
void QGCApplication::startLinkManager()
{
LinkManager::instance();
}
/**
* @brief Start the Unmanned Air System Manager
*
**/
void QGCApplication::startUASManager()
{
// Load UAS plugins
QDir pluginsDir = QDir(qApp->applicationDirPath());
#if defined(Q_OS_WIN)
if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
pluginsDir.cdUp();
#elif defined(Q_OS_LINUX)
if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release")
pluginsDir.cdUp();
#elif defined(Q_OS_MAC)
if (pluginsDir.dirName() == "MacOS") {
pluginsDir.cdUp();
pluginsDir.cdUp();
pluginsDir.cdUp();
}
#endif
pluginsDir.cd("plugins");
UASManager::instance();
// Load plugins
QStringList pluginFileNames;
foreach (QString fileName, pluginsDir.entryList(QDir::Files)) {
QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));
QObject *plugin = loader.instance();
if (plugin) {
//populateMenus(plugin);
pluginFileNames += fileName;
//printf(QString("Loaded plugin from " + fileName + "\n").toStdString().c_str());
}
}
}
void QGCApplication::deleteAllSettingsNextBoot(void)
{
QSettings settings;
settings.setValue(_deleteAllSettingsKey, true);
}
void QGCApplication::clearDeleteAllSettingsNextBoot(void)
{
QSettings settings;
settings.remove(_deleteAllSettingsKey);
}
void QGCApplication::setSavedFilesLocation(QString& location)
{
QSettings settings;
settings.setValue(_savedFilesLocationKey, location);
}
bool QGCApplication::validatePossibleSavedFilesLocation(QString& location)
{
// Make sure we can write to the directory
QString filename = QDir(location).filePath("QGCTempXXXXXXXX.tmp");
QTemporaryFile tempFile(filename);
if (!tempFile.open()) {
return false;
}
return true;
}
QString QGCApplication::savedFilesLocation(void)
{
QSettings settings;
Q_ASSERT(settings.contains(_savedFilesLocationKey));
return settings.value(_savedFilesLocationKey).toString();
}
QString QGCApplication::savedParameterFilesLocation(void)
{
QString location;
QDir parentDir(savedFilesLocation());
location = parentDir.filePath(_savedFileParameterDirectoryName);
if (!QDir(location).exists()) {
// If directory doesn't exist, try to create it
if (!parentDir.mkpath(_savedFileParameterDirectoryName)) {
// Return an error
location.clear();
}
}
return location;
}
QString QGCApplication::mavlinkLogFilesLocation(void)
{
QString location;
QDir parentDir(savedFilesLocation());
location = parentDir.filePath(_savedFileMavlinkLogDirectoryName);
if (!QDir(location).exists()) {
// If directory doesn't exist, try to create it
if (!parentDir.mkpath(_savedFileMavlinkLogDirectoryName)) {
// Return an error
location.clear();
}
}
return location;
}
bool QGCApplication::promptFlightDataSave(void)
{
QSettings settings;
return settings.value(_promptFlightDataSave, true).toBool();
}
void QGCApplication::setPromptFlightDataSave(bool promptForSave)
{
QSettings settings;
settings.setValue(_promptFlightDataSave, promptForSave);
}
/// @brief Returns the QGCApplication object singleton.
QGCApplication* qgcApp(void)
{
QGCApplication* app = dynamic_cast<QGCApplication*>(qApp);
Q_ASSERT(app);
return app;
}
<|endoftext|>
|
<commit_before>#include "Screen.h"
#include "EngineClient.h"
#include <imgui.h>
namespace {
//@TODO: make these conditionally const for "shipping" build
static int32_t RampUpDelay = 5;
static int32_t RampDownDelay = 10;
static int32_t VelocityXDelay = 6;
// LineDrawScale is required because introducing ramp and velX delays means we now create lines
// that go outside the 256x256 grid. So we scale down the line drawing values a little to make
// it fit within the grid again.
static float LineDrawScale = 0.9f;
} // namespace
void Screen::Init() {
m_velocityX.CyclesToUpdateValue = VelocityXDelay;
}
void Screen::Update(cycles_t cycles, RenderContext& renderContext) {
m_velocityX.Update(cycles);
m_velocityY.Update(cycles);
// Handle switching to RampUp/RampDown
switch (m_rampPhase) {
case RampPhase::RampOff:
case RampPhase::RampDown:
if (m_integratorsEnabled) {
m_rampPhase = RampPhase::RampUp;
m_rampDelay = RampUpDelay;
}
break;
case RampPhase::RampOn:
case RampPhase::RampUp:
if (!m_integratorsEnabled) {
m_rampPhase = RampPhase::RampDown;
m_rampDelay = RampDownDelay;
}
}
// Handle switching to RampOn/RampOff
switch (m_rampPhase) {
case RampPhase::RampUp:
// Wait some cycles, then go to RampOn
if (--m_rampDelay <= 0) {
m_rampPhase = RampPhase::RampOn;
}
break;
case RampPhase::RampDown:
// Wait some cycles, then go to RampOff
if (--m_rampDelay <= 0) {
m_rampPhase = RampPhase::RampOff;
}
}
const auto lastPos = m_pos;
// Move beam while ramp is on or its way down
switch (m_rampPhase) {
case RampPhase::RampDown:
case RampPhase::RampOn: {
const auto offset = Vector2{m_xyOffset, m_xyOffset};
Vector2 velocity{m_velocityX, m_velocityY};
Vector2 delta = (velocity + offset) / 128.f * static_cast<float>(cycles) * LineDrawScale;
m_pos += delta;
break;
}
}
// We might draw even when integrators are disabled (e.g. drawing dots)
bool drawingEnabled = !m_blank && (m_brightness > 0.f && m_brightness <= 128.f);
if (drawingEnabled) {
renderContext.lines.emplace_back(Line{lastPos, m_pos});
}
}
void Screen::FrameUpdate() {
ImGui::SliderInt("RampUpDelay", &RampUpDelay, 0, 20);
ImGui::SliderInt("RampDownDelay", &RampDownDelay, 0, 20);
ImGui::SliderInt("VelocityXDelay", &VelocityXDelay, 0, 30);
ImGui::SliderFloat("LineDrawScale", &LineDrawScale, 0.1f, 1.f);
m_velocityX.CyclesToUpdateValue = VelocityXDelay;
}
void Screen::ZeroBeam() {
//@TODO: move beam towards 0,0 over time
m_pos = {0.f, 0.f};
}
<commit_msg>Hook up line brightness<commit_after>#include "Screen.h"
#include "EngineClient.h"
#include <imgui.h>
namespace {
//@TODO: make these conditionally const for "shipping" build
static int32_t RampUpDelay = 5;
static int32_t RampDownDelay = 10;
static int32_t VelocityXDelay = 6;
// LineDrawScale is required because introducing ramp and velX delays means we now create lines
// that go outside the 256x256 grid. So we scale down the line drawing values a little to make
// it fit within the grid again.
static float LineDrawScale = 0.9f;
} // namespace
void Screen::Init() {
m_velocityX.CyclesToUpdateValue = VelocityXDelay;
}
void Screen::Update(cycles_t cycles, RenderContext& renderContext) {
m_velocityX.Update(cycles);
m_velocityY.Update(cycles);
// Handle switching to RampUp/RampDown
switch (m_rampPhase) {
case RampPhase::RampOff:
case RampPhase::RampDown:
if (m_integratorsEnabled) {
m_rampPhase = RampPhase::RampUp;
m_rampDelay = RampUpDelay;
}
break;
case RampPhase::RampOn:
case RampPhase::RampUp:
if (!m_integratorsEnabled) {
m_rampPhase = RampPhase::RampDown;
m_rampDelay = RampDownDelay;
}
}
// Handle switching to RampOn/RampOff
switch (m_rampPhase) {
case RampPhase::RampUp:
// Wait some cycles, then go to RampOn
if (--m_rampDelay <= 0) {
m_rampPhase = RampPhase::RampOn;
}
break;
case RampPhase::RampDown:
// Wait some cycles, then go to RampOff
if (--m_rampDelay <= 0) {
m_rampPhase = RampPhase::RampOff;
}
}
const auto lastPos = m_pos;
// Move beam while ramp is on or its way down
switch (m_rampPhase) {
case RampPhase::RampDown:
case RampPhase::RampOn: {
const auto offset = Vector2{m_xyOffset, m_xyOffset};
Vector2 velocity{m_velocityX, m_velocityY};
Vector2 delta = (velocity + offset) / 128.f * static_cast<float>(cycles) * LineDrawScale;
m_pos += delta;
break;
}
}
// We might draw even when integrators are disabled (e.g. drawing dots)
bool drawingEnabled = !m_blank && (m_brightness > 0.f && m_brightness <= 128.f);
if (drawingEnabled) {
renderContext.lines.emplace_back(Line{lastPos, m_pos, m_brightness / 128.f});
}
}
void Screen::FrameUpdate() {
ImGui::SliderInt("RampUpDelay", &RampUpDelay, 0, 20);
ImGui::SliderInt("RampDownDelay", &RampDownDelay, 0, 20);
ImGui::SliderInt("VelocityXDelay", &VelocityXDelay, 0, 30);
ImGui::SliderFloat("LineDrawScale", &LineDrawScale, 0.1f, 1.f);
m_velocityX.CyclesToUpdateValue = VelocityXDelay;
}
void Screen::ZeroBeam() {
//@TODO: move beam towards 0,0 over time
m_pos = {0.f, 0.f};
}
<|endoftext|>
|
<commit_before>#include "Simple.hpp"
#include "ClockWidget.hpp"
rack::Plugin* plugin;
void init(rack::Plugin *p)
{
plugin = p;
plugin->slug = "IO-Simple";
#ifdef VERSION
p->version = TOSTRING(VERSION);
#endif
p->addModel(rack::createModel<ButtonTriggerWidget>("IO-Simple", "Simple", "IO-ButtonTrigger", "Button Trigger"));
p->addModel(rack::createModel<ClockDividerWidget>("IO-Simple", "Simple", "IO-ClockDivider", "Clock Divider"));
p->addModel(rack::createModel<RecorderWidget>("IO-Simple", "Simple", "IO-Recorder", "Recorder"));
p->addModel(rack::createModel<ClockWidget>("IO-Simple", "Simple", "IO-Clock", "Clock"));
}
<commit_msg>[Clock]: removed clock module from available modules.<commit_after>#include "Simple.hpp"
#include "ClockWidget.hpp"
rack::Plugin* plugin;
void init(rack::Plugin *p)
{
plugin = p;
plugin->slug = "IO-Simple";
#ifdef VERSION
p->version = TOSTRING(VERSION);
#endif
p->addModel(rack::createModel<ButtonTriggerWidget>("IO-Simple", "Simple", "IO-ButtonTrigger", "Button Trigger"));
p->addModel(rack::createModel<ClockDividerWidget>("IO-Simple", "Simple", "IO-ClockDivider", "Clock Divider"));
p->addModel(rack::createModel<RecorderWidget>("IO-Simple", "Simple", "IO-Recorder", "Recorder"));
// p->addModel(rack::createModel<ClockWidget>("IO-Simple", "Simple", "IO-Clock", "Clock"));
}
<|endoftext|>
|
<commit_before>#include "Viewer.hpp"
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/freeglut.h>
#include <iostream>
Viewer* Viewer::instance_ = NULL;
Viewer::Viewer(std::string name, int width, int height) : name_(name), width_(width),
height_(height), running_(false), thetaX_(0.0f), thetaY_(0.0f) {
}
Viewer::~Viewer() {
}
void Viewer::initGlut(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH);
glutInitWindowSize(width_, height_);
glutInitWindowPosition((glutGet(GLUT_SCREEN_WIDTH) - width_) / 2, (glutGet(GLUT_SCREEN_HEIGHT) - height_) / 2);
glutCreateWindow(name_.c_str());
}
void Viewer::initGl() {
glEnable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
glClearDepth(1.0f);
glDepthFunc(GL_LEQUAL);
glShadeModel(GL_SMOOTH);
glMatrixMode(GL_PROJECTION);
glLoadIdentity(); // Reset The Projection Matrix
gluPerspective(45.0f, (GLfloat)width_/(GLfloat)height_, 0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL);
}
void Viewer::setModel(const SmartPtr<Model>& model) {
model_ = model;
}
void Viewer::start() {
if (!running_) {
running_ = true;
glutMainLoop();
}
}
void Viewer::stop() {
if (running_)
glutLeaveMainLoop();
}
void Viewer::idle() {
glutPostRedisplay();
}
void Viewer::display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -5.0f);
glRotatef(thetaX_, 1.0f, 0.0f, 0.0f);
glRotatef(thetaY_, 0.0f, 1.0f, 0.0f);
model_->render();
glutSwapBuffers();
}
void Viewer::resize(int width, int height) {
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity(); // Reset The Projection Matrix
gluPerspective(45.0f, (GLfloat)width_/(GLfloat)height_, 0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW);
}
void Viewer::keyDown(unsigned char key, int x, int y) {
if (27 == key) {
stop();
}
}
void Viewer::specialKey(int key, int x, int y) {
switch(key) {
case GLUT_KEY_UP:
thetaX_ += 5.0f;
break;
case GLUT_KEY_DOWN:
thetaX_ -= 5.0f;
break;
case GLUT_KEY_LEFT:
thetaY_ -= 5.0f;
break;
case GLUT_KEY_RIGHT:
thetaY_ += 5.0f;
break;
}
}
/*
* Static callbacks
*/
void Viewer::setInstance(Viewer* instance) {
instance_ = instance;
glutIdleFunc(idleCallback);
glutDisplayFunc(displayCallback);
glutKeyboardFunc(keyDownCallback);
glutSpecialFunc(specialKeyCallback);
}
void Viewer::idleCallback() {
instance_->idle();
}
void Viewer::displayCallback() {
instance_->display();
}
void Viewer::resizeCallback(int width, int height) {
instance_->resize(width, height);
}
void Viewer::keyDownCallback(unsigned char key, int x, int y) {
instance_->keyDown(key, x, y);
}
void Viewer::specialKeyCallback(int key, int x, int y) {
instance_->specialKey(key, x, y);
}
<commit_msg>Formatting changes.<commit_after>#include "Viewer.hpp"
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/freeglut.h>
#include <iostream>
Viewer* Viewer::instance_ = NULL;
Viewer::Viewer(std::string name, int width, int height) : name_(name), width_(width),
height_(height), running_(false), thetaX_(0.0f), thetaY_(0.0f) {
}
Viewer::~Viewer() {
}
void Viewer::initGlut(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH);
glutInitWindowSize(width_, height_);
glutInitWindowPosition((glutGet(GLUT_SCREEN_WIDTH) - width_) / 2, (glutGet(GLUT_SCREEN_HEIGHT) - height_) / 2);
glutCreateWindow(name_.c_str());
}
void Viewer::initGl() {
glEnable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
glClearDepth(1.0f);
glDepthFunc(GL_LEQUAL);
glShadeModel(GL_SMOOTH);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0f, (GLfloat)width_/(GLfloat)height_, 0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL);
}
void Viewer::setModel(const SmartPtr<Model>& model) {
model_ = model;
}
void Viewer::start() {
if (!running_) {
running_ = true;
glutMainLoop();
}
}
void Viewer::stop() {
if (running_)
glutLeaveMainLoop();
}
void Viewer::idle() {
glutPostRedisplay();
}
void Viewer::display() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.0f, 0.0f, -5.0f);
glRotatef(thetaX_, 1.0f, 0.0f, 0.0f);
glRotatef(thetaY_, 0.0f, 1.0f, 0.0f);
model_->render();
glutSwapBuffers();
}
void Viewer::resize(int width, int height) {
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity(); // Reset The Projection Matrix
gluPerspective(45.0f, (GLfloat)width_/(GLfloat)height_, 0.1f, 100.0f);
glMatrixMode(GL_MODELVIEW);
}
void Viewer::keyDown(unsigned char key, int x, int y) {
if (27 == key) {
stop();
}
}
void Viewer::specialKey(int key, int x, int y) {
switch(key) {
case GLUT_KEY_UP:
thetaX_ += 5.0f;
break;
case GLUT_KEY_DOWN:
thetaX_ -= 5.0f;
break;
case GLUT_KEY_LEFT:
thetaY_ -= 5.0f;
break;
case GLUT_KEY_RIGHT:
thetaY_ += 5.0f;
break;
}
}
/*
* Static callbacks
*/
void Viewer::setInstance(Viewer* instance) {
instance_ = instance;
glutIdleFunc(idleCallback);
glutDisplayFunc(displayCallback);
glutKeyboardFunc(keyDownCallback);
glutSpecialFunc(specialKeyCallback);
}
void Viewer::idleCallback() {
instance_->idle();
}
void Viewer::displayCallback() {
instance_->display();
}
void Viewer::resizeCallback(int width, int height) {
instance_->resize(width, height);
}
void Viewer::keyDownCallback(unsigned char key, int x, int y) {
instance_->keyDown(key, x, y);
}
void Viewer::specialKeyCallback(int key, int x, int y) {
instance_->specialKey(key, x, y);
}
<|endoftext|>
|
<commit_before>/* nobleNote, a note taking application
* Copyright (C) 2012 Christian Metscher <hakaishi@web.de>,
Fabian Deuchler <Taiko000@gmail.com>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* nobleNote is licensed under the MIT, see `http://copyfree.org/licenses/mit/license.txt'.
*/
#include "backup.h"
#include "htmlnotereader.h"
#include "abstractnotereader.h"
#include <QDirIterator>
#include <QMessageBox>
#include <QSettings>
#include <QtConcurrentMap>
#include <QAbstractItemModel>
Backup::Backup(QWidget *parent): QDialog(parent){
setupUi(this);
splitter = new QSplitter(groupBox);
gridLayout_2->addWidget(splitter);
treeWidget = new QTreeWidget(splitter);
treeWidget->setAlternatingRowColors(true);
treeWidget->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
treeWidget->setSortingEnabled(true);
frame = new QFrame(splitter);
gridLayout3 = new QGridLayout(frame);
label = new QLabel(frame);
label->setText(tr("Preview of the selected backup"));
gridLayout3->addWidget(label, 0, 0, 1, 1);
textEdit = new QTextEdit(this);
textEdit->setDisabled(frame);
gridLayout3->addWidget(textEdit, 1, 0, 1, 1);
document = new QTextDocument(this);
textEdit->setDocument(document);
QStringList header;
header << tr("Backups") << tr("Titels");
treeWidget->setHeaderLabels(header);
setupTreeData();
deleteOldButton = new QPushButton(tr("&delete all old backups and file entries"),this);
buttonBox->addButton(deleteOldButton ,QDialogButtonBox::ActionRole);
//TODO: should be selectionChanged instead of activated...
connect(treeWidget, SIGNAL(activated(QModelIndex)), this, SLOT(showPreview(QModelIndex)));
connect(this, SIGNAL(handleBackupsSignal()), this, SLOT(handleBackups()));
connect(this, SIGNAL(accepted()), this, SLOT(restoreBackup()));
connect(deleteOldButton, SIGNAL(clicked(bool)), this, SLOT(deleteOldBackupsAndFileEntries()));
}
void Backup::setupTreeData()
{
treeWidget->clear(); //if there already is any data
//Load backup data
QMap<QString,QList<QVariant> > backupMap;
QDir backupDir(QSettings().value("backupDirPath").toString());
QList<QFileInfo> backupList = backupDir.entryInfoList(QDir::Files, QDir::Name);
foreach(QFileInfo backup, backupList)
{
QList<QVariant> data = getFileData(backup.absoluteFilePath());
data.takeFirst();
backupMap.insert(backup.absoluteFilePath(), data);
}
//Load note data
QMap<QString,QList<QVariant> > noteMap;
QDirIterator itFiles(QSettings().value("noteDirPath").toString(),
QDirIterator::Subdirectories);
QStringList noteFiles;
while(itFiles.hasNext()){
QString filePath = itFiles.next();
if(itFiles.fileInfo().isFile())
noteFiles << filePath;
}
QStringList notebookNameList; //Get notebook names
foreach(QString note, noteFiles)
{
QList<QVariant> data = getFileData(note);
QString uuid = data.takeFirst().toString();
QString title = data.takeFirst().toString();
data.clear(); //We don't need more than that
QString notebook = note;
notebook.remove("/" + QFileInfo(note).fileName());
notebook.remove(QSettings().value("noteDirPath").toString() + "/");
notebookNameList << notebook;
QList<QVariant> list;
list << notebook << title;
noteMap.insert(uuid, list);
}
notebookNameList.removeDuplicates();
foreach(QString notebookName, notebookNameList)
{
//Create tree toplevel items for notebooks
QTreeWidgetItem *notebookItem = new QTreeWidgetItem(treeWidget);
notebookItem->setText(0,notebookName);
//Get note titles and create a child for the notebook
foreach(QString noteUuid, noteMap.keys())
{
if(noteMap[noteUuid].first() == notebookName)
{
//Create a child with the note title
noteMap[noteUuid].takeFirst(); //removing notebook name to get the title
QTreeWidgetItem *noteItem = new QTreeWidgetItem(notebookItem);
noteItem->setText(0,noteMap[noteUuid].first().toString());
foreach(QString backupFile, backupMap.keys())
{
QString backupUuid = "{" + backupFile + "}";
backupUuid.remove(QSettings().value("backupDirPath").toString() + "/");
backupUuid.remove(QRegExp("_\\d+\\-\\d+\\-\\d+T\\d+\\-\\d+\\-\\d+"));
//Create for each backup of the note a child with date and title
if(noteUuid == backupUuid)
{
QList<QVariant> list = backupMap[backupFile];
backupMap.remove(backupFile);
QString title = list.takeFirst().toString();
QDateTime date = list.takeFirst().toDateTime();
QStringList content;
content<< backupFile << list.takeFirst().toString();
QTreeWidgetItem *backupItem = new QTreeWidgetItem(noteItem);
backupItem->setText(0, date.toString("yyyy-MM-dd hh-mm-ss"));
backupItem->setData(0,Qt::UserRole,content);
backupItem->setText(1, title);
}
}
}
}
}
//Create toplevel item for backups of deleted notes
QTreeWidgetItem *item = new QTreeWidgetItem(treeWidget);
item->setText(0,tr("Backups of deleted notes"));
//Get remaining backups
QStringList backupFiles = backupMap.keys();
QStringList deletedTitles;
foreach(QString path, backupFiles)
{
QString str = path;
str.remove(QRegExp("_\\d+\\-\\d+\\-\\d+T\\d+\\-\\d+\\-\\d+"));
deletedTitles << str;
}
deletedTitles.removeDuplicates();
foreach(QString backupPath, deletedTitles)
{
QTreeWidgetItem *childItem = new QTreeWidgetItem(item);
childItem->setText(0,backupMap[backupPath].first().toString());
foreach(QString backupFile, backupMap.keys())
{
QList<QVariant> list = backupMap[backupFile];
backupMap.remove(backupFile);
QString title = list.takeFirst().toString();
QDateTime date = list.takeFirst().toDateTime();
QStringList content;
content << backupFile << list.takeFirst().toString();
QTreeWidgetItem *backupItem = new QTreeWidgetItem(childItem);
backupItem->setText(0,date.toString("yyyy-MM-dd hh-mm-ss"));
backupItem->setData(0,Qt::UserRole,content);
backupItem->setText(1,title);
}
}
treeWidget->resizeColumnToContents(0);
}
QList<QVariant> Backup::getFileData(const QString &file)
{
AbstractNoteReader *reader = new HtmlNoteReader(file,document);
QList<QVariant> list;
QString uuid = reader->uuid();
list << uuid << reader->title() << reader->lastChange() << document->toHtml();
return list;
}
void Backup::showPreview(const QModelIndex &idx)
{
QStringList dataList = idx.data(Qt::UserRole).toStringList();
textEdit->setText(dataList.last());
}
void Backup::restoreBackup()
{
QStringList dataList = treeWidget->selectionModel()->currentIndex().data(Qt::UserRole).toStringList();
if(!QFile(dataList.first()).exists())
return;
else
{
qDebug()<<dataList.first();//TODO:Remove or Override Note
}
}
void Backup::handleBackups()
{
//TODO: Create and handle Backups here
}
void Backup::getNoteUuidList(){
QFutureIterator<QUuid> it(future1->future());
while(it.hasNext())
notesUuids << it.next();
}
void Backup::deleteOldBackupsAndFileEntries(){
notesUuids.clear(); //make sure that it's empty
//searching for existing Notes
QDirIterator itFiles(QSettings().value("noteDirPath").toString(),
QDirIterator::Subdirectories);
QStringList noteFiles;
while(itFiles.hasNext()){
QString filePath = itFiles.next();
if(itFiles.fileInfo().isFile())
noteFiles << filePath;
}
future1 = new QFutureWatcher<QUuid>(this);
QUuid (*uuidPtr)(QString) = & HtmlNoteReader::uuid; // function pointer, because uuid method is overloaded
future1->setFuture(QtConcurrent::mapped(noteFiles, uuidPtr));
indexDialog = new QProgressDialog(this);
indexDialog->setLabelText(QString(tr("Indexing notes...")));
QObject::connect(future1, SIGNAL(finished()), this, SLOT(getNoteUuidList()));
QObject::connect(future1, SIGNAL(finished()), this, SLOT(progressChanges()));
QObject::connect(future1, SIGNAL(finished()), indexDialog, SLOT(reset()));
QObject::connect(indexDialog, SIGNAL(canceled()), future1, SLOT(cancel()));
QObject::connect(future1, SIGNAL(progressRangeChanged(int,int)),
indexDialog, SLOT(setRange(int,int)));
QObject::connect(future1, SIGNAL(progressValueChanged(int)), indexDialog,
SLOT(setValue(int)));
indexDialog->exec();
}
void actualRemoval(const QString& backupAndUuid){
if(!backupAndUuid.contains("Notes/"))
QFile::remove(backupAndUuid);
else
QSettings().remove(backupAndUuid);
}
void Backup::progressChanges(){
//get backup files
QStringList backups;
QDir backupDir(QSettings().value("backupDirPath").toString());
QList<QFileInfo> backupList = backupDir.entryInfoList(QDir::Files, QDir::Name);
foreach(QFileInfo backup, backupList)
backups << backup.absoluteFilePath();
//add QSettings Uuids to the backups
QStringList backupsAndUuids = backups + QSettings().allKeys().filter("Notes/");
//We only need the redundant backups and Uuids
foreach(QString str, backupsAndUuids){
if(!str.contains("Notes/") && notesUuids.contains(QFileInfo(str).fileName()))
backupsAndUuids.removeOne(str);
if(str.contains("Notes/")){
QString settings = str;
settings.remove("Notes/");
settings.remove("_size");
settings.remove("_cursor_position");
if(notesUuids.contains(settings))
backupsAndUuids.removeOne(str);
}
}
QString redundantBackupList;
foreach(QString str, backupsAndUuids)
if(!str.contains("Notes/"))
redundantBackupList += (str+"\n");
if(backupsAndUuids.isEmpty()){
QMessageBox::information(this, tr("No redundant data!"), tr("no redundant"
" Everything is clean! No redundant data!"));
return;
}
else{
if(QMessageBox::warning(this,tr("Deleting backups and file entries"),
tr("Do you really want to delete the backups and entries for the "
"following files?\n\n%1\nYou won't be able to restore them!").arg(
redundantBackupList),
QMessageBox::Yes | QMessageBox::Abort) != QMessageBox::Yes)
return;
}
progressDialog = new QProgressDialog(this);
progressDialog->setLabelText(QString(tr("Progressing files...")));
future2 = new QFutureWatcher<void>(this);
future2->setFuture(QtConcurrent::map(backupsAndUuids, actualRemoval));
QObject::connect(future2, SIGNAL(finished()), progressDialog, SLOT(reset()));
QObject::connect(future2, SIGNAL(finished()), this, SLOT(setupTreeData()));
QObject::connect(progressDialog, SIGNAL(canceled()), future2, SLOT(cancel()));
QObject::connect(future2, SIGNAL(progressRangeChanged(int,int)), progressDialog,
SLOT(setRange(int,int)));
QObject::connect(future2, SIGNAL(progressValueChanged(int)), progressDialog,
SLOT(setValue(int)));
progressDialog->exec();
}
<commit_msg>fixed crush after clicked on empty column.<commit_after>/* nobleNote, a note taking application
* Copyright (C) 2012 Christian Metscher <hakaishi@web.de>,
Fabian Deuchler <Taiko000@gmail.com>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* nobleNote is licensed under the MIT, see `http://copyfree.org/licenses/mit/license.txt'.
*/
#include "backup.h"
#include "htmlnotereader.h"
#include "abstractnotereader.h"
#include <QDirIterator>
#include <QMessageBox>
#include <QSettings>
#include <QtConcurrentMap>
#include <QAbstractItemModel>
Backup::Backup(QWidget *parent): QDialog(parent){
setupUi(this);
splitter = new QSplitter(groupBox);
gridLayout_2->addWidget(splitter);
treeWidget = new QTreeWidget(splitter);
treeWidget->setAlternatingRowColors(true);
treeWidget->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel);
treeWidget->setSortingEnabled(true);
frame = new QFrame(splitter);
gridLayout3 = new QGridLayout(frame);
label = new QLabel(frame);
label->setText(tr("Preview of the selected backup"));
gridLayout3->addWidget(label, 0, 0, 1, 1);
textEdit = new QTextEdit(this);
textEdit->setDisabled(frame);
gridLayout3->addWidget(textEdit, 1, 0, 1, 1);
document = new QTextDocument(this);
textEdit->setDocument(document);
QStringList header;
header << tr("Backups") << tr("Titels");
treeWidget->setHeaderLabels(header);
setupTreeData();
deleteOldButton = new QPushButton(tr("&delete all old backups and file entries"),this);
buttonBox->addButton(deleteOldButton ,QDialogButtonBox::ActionRole);
//TODO: should be selectionChanged instead of activated...
connect(treeWidget, SIGNAL(activated(QModelIndex)), this, SLOT(showPreview(QModelIndex)));
connect(this, SIGNAL(handleBackupsSignal()), this, SLOT(handleBackups()));
connect(this, SIGNAL(accepted()), this, SLOT(restoreBackup()));
connect(deleteOldButton, SIGNAL(clicked(bool)), this, SLOT(deleteOldBackupsAndFileEntries()));
}
void Backup::setupTreeData()
{
treeWidget->clear(); //if there already is any data
//Load backup data
QMap<QString,QList<QVariant> > backupMap;
QDir backupDir(QSettings().value("backupDirPath").toString());
QList<QFileInfo> backupList = backupDir.entryInfoList(QDir::Files, QDir::Name);
foreach(QFileInfo backup, backupList)
{
QList<QVariant> data = getFileData(backup.absoluteFilePath());
data.takeFirst();
backupMap.insert(backup.absoluteFilePath(), data);
}
//Load note data
QMap<QString,QList<QVariant> > noteMap;
QDirIterator itFiles(QSettings().value("noteDirPath").toString(),
QDirIterator::Subdirectories);
QStringList noteFiles;
while(itFiles.hasNext()){
QString filePath = itFiles.next();
if(itFiles.fileInfo().isFile())
noteFiles << filePath;
}
QStringList notebookNameList; //Get notebook names
foreach(QString note, noteFiles)
{
QList<QVariant> data = getFileData(note);
QString uuid = data.takeFirst().toString();
QString title = data.takeFirst().toString();
data.clear(); //We don't need more than that
QString notebook = note;
notebook.remove("/" + QFileInfo(note).fileName());
notebook.remove(QSettings().value("noteDirPath").toString() + "/");
notebookNameList << notebook;
QList<QVariant> list;
list << notebook << title;
noteMap.insert(uuid, list);
}
notebookNameList.removeDuplicates();
foreach(QString notebookName, notebookNameList)
{
//Create tree toplevel items for notebooks
QTreeWidgetItem *notebookItem = new QTreeWidgetItem(treeWidget);
notebookItem->setText(0,notebookName);
//Get note titles and create a child for the notebook
foreach(QString noteUuid, noteMap.keys())
{
if(noteMap[noteUuid].first() == notebookName)
{
//Create a child with the note title
noteMap[noteUuid].takeFirst(); //removing notebook name to get the title
QTreeWidgetItem *noteItem = new QTreeWidgetItem(notebookItem);
noteItem->setText(0,noteMap[noteUuid].first().toString());
foreach(QString backupFile, backupMap.keys())
{
QString backupUuid = "{" + backupFile + "}";
backupUuid.remove(QSettings().value("backupDirPath").toString() + "/");
backupUuid.remove(QRegExp("_\\d+\\-\\d+\\-\\d+T\\d+\\-\\d+\\-\\d+"));
//Create for each backup of the note a child with date and title
if(noteUuid == backupUuid)
{
QList<QVariant> list = backupMap[backupFile];
backupMap.remove(backupFile);
QString title = list.takeFirst().toString();
QDateTime date = list.takeFirst().toDateTime();
QStringList content;
content<< backupFile << list.takeFirst().toString();
QTreeWidgetItem *backupItem = new QTreeWidgetItem(noteItem);
backupItem->setText(0, date.toString("yyyy-MM-dd hh-mm-ss"));
backupItem->setData(0,Qt::UserRole,content);
backupItem->setText(1, title);
}
}
}
}
}
//Create toplevel item for backups of deleted notes
QTreeWidgetItem *item = new QTreeWidgetItem(treeWidget);
item->setText(0,tr("Backups of deleted notes"));
//Get remaining backups
QStringList backupFiles = backupMap.keys();
QStringList deletedTitles;
foreach(QString path, backupFiles)
{
QString str = path;
str.remove(QRegExp("_\\d+\\-\\d+\\-\\d+T\\d+\\-\\d+\\-\\d+"));
deletedTitles << str;
}
deletedTitles.removeDuplicates();
foreach(QString backupPath, deletedTitles)
{
QTreeWidgetItem *childItem = new QTreeWidgetItem(item);
childItem->setText(0,backupMap[backupPath].first().toString());
foreach(QString backupFile, backupMap.keys())
{
QList<QVariant> list = backupMap[backupFile];
backupMap.remove(backupFile);
QString title = list.takeFirst().toString();
QDateTime date = list.takeFirst().toDateTime();
QStringList content;
content << backupFile << list.takeFirst().toString();
QTreeWidgetItem *backupItem = new QTreeWidgetItem(childItem);
backupItem->setText(0,date.toString("yyyy-MM-dd hh-mm-ss"));
backupItem->setData(0,Qt::UserRole,content);
backupItem->setText(1,title);
}
}
treeWidget->resizeColumnToContents(0);
}
QList<QVariant> Backup::getFileData(const QString &file)
{
AbstractNoteReader *reader = new HtmlNoteReader(file,document);
QList<QVariant> list;
QString uuid = reader->uuid();
list << uuid << reader->title() << reader->lastChange() << document->toHtml();
return list;
}
void Backup::showPreview(const QModelIndex &idx)
{
QStringList dataList = idx.data(Qt::UserRole).toStringList();
if(dataList.isEmpty())
return;
textEdit->setText(dataList.last());
}
void Backup::restoreBackup()
{
QStringList dataList = treeWidget->selectionModel()->currentIndex().data(Qt::UserRole).toStringList();
if(!QFile(dataList.first()).exists())
return;
else
{
qDebug()<<dataList.first();//TODO:Remove or Override Note
}
}
void Backup::handleBackups()
{
//TODO: Create and handle Backups here
}
void Backup::getNoteUuidList(){
QFutureIterator<QUuid> it(future1->future());
while(it.hasNext())
notesUuids << it.next();
}
void Backup::deleteOldBackupsAndFileEntries(){
notesUuids.clear(); //make sure that it's empty
//searching for existing Notes
QDirIterator itFiles(QSettings().value("noteDirPath").toString(),
QDirIterator::Subdirectories);
QStringList noteFiles;
while(itFiles.hasNext()){
QString filePath = itFiles.next();
if(itFiles.fileInfo().isFile())
noteFiles << filePath;
}
future1 = new QFutureWatcher<QUuid>(this);
QUuid (*uuidPtr)(QString) = & HtmlNoteReader::uuid; // function pointer, because uuid method is overloaded
future1->setFuture(QtConcurrent::mapped(noteFiles, uuidPtr));
indexDialog = new QProgressDialog(this);
indexDialog->setLabelText(QString(tr("Indexing notes...")));
QObject::connect(future1, SIGNAL(finished()), this, SLOT(getNoteUuidList()));
QObject::connect(future1, SIGNAL(finished()), this, SLOT(progressChanges()));
QObject::connect(future1, SIGNAL(finished()), indexDialog, SLOT(reset()));
QObject::connect(indexDialog, SIGNAL(canceled()), future1, SLOT(cancel()));
QObject::connect(future1, SIGNAL(progressRangeChanged(int,int)),
indexDialog, SLOT(setRange(int,int)));
QObject::connect(future1, SIGNAL(progressValueChanged(int)), indexDialog,
SLOT(setValue(int)));
indexDialog->exec();
}
void actualRemoval(const QString& backupAndUuid){
if(!backupAndUuid.contains("Notes/"))
QFile::remove(backupAndUuid);
else
QSettings().remove(backupAndUuid);
}
void Backup::progressChanges(){
//get backup files
QStringList backups;
QDir backupDir(QSettings().value("backupDirPath").toString());
QList<QFileInfo> backupList = backupDir.entryInfoList(QDir::Files, QDir::Name);
foreach(QFileInfo backup, backupList)
backups << backup.absoluteFilePath();
//add QSettings Uuids to the backups
QStringList backupsAndUuids = backups + QSettings().allKeys().filter("Notes/");
//We only need the redundant backups and Uuids
foreach(QString str, backupsAndUuids){
if(!str.contains("Notes/") && notesUuids.contains(QFileInfo(str).fileName()))
backupsAndUuids.removeOne(str);
if(str.contains("Notes/")){
QString settings = str;
settings.remove("Notes/");
settings.remove("_size");
settings.remove("_cursor_position");
if(notesUuids.contains(settings))
backupsAndUuids.removeOne(str);
}
}
QString redundantBackupList;
foreach(QString str, backupsAndUuids)
if(!str.contains("Notes/"))
redundantBackupList += (str+"\n");
if(backupsAndUuids.isEmpty()){
QMessageBox::information(this, tr("No redundant data!"), tr("no redundant"
" Everything is clean! No redundant data!"));
return;
}
else{
if(QMessageBox::warning(this,tr("Deleting backups and file entries"),
tr("Do you really want to delete the backups and entries for the "
"following files?\n\n%1\nYou won't be able to restore them!").arg(
redundantBackupList),
QMessageBox::Yes | QMessageBox::Abort) != QMessageBox::Yes)
return;
}
progressDialog = new QProgressDialog(this);
progressDialog->setLabelText(QString(tr("Progressing files...")));
future2 = new QFutureWatcher<void>(this);
future2->setFuture(QtConcurrent::map(backupsAndUuids, actualRemoval));
QObject::connect(future2, SIGNAL(finished()), progressDialog, SLOT(reset()));
QObject::connect(future2, SIGNAL(finished()), this, SLOT(setupTreeData()));
QObject::connect(progressDialog, SIGNAL(canceled()), future2, SLOT(cancel()));
QObject::connect(future2, SIGNAL(progressRangeChanged(int,int)), progressDialog,
SLOT(setRange(int,int)));
QObject::connect(future2, SIGNAL(progressValueChanged(int)), progressDialog,
SLOT(setValue(int)));
progressDialog->exec();
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2003-2009, John Wiegley. 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 New Artisans LLC 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 <system.hh>
#include "balance.h"
#include "commodity.h"
#include "pool.h"
#include "unistring.h" // for justify()
namespace ledger {
balance_t::balance_t(const double val)
{
TRACE_CTOR(balance_t, "const double");
amounts.insert
(amounts_map::value_type(amount_t::current_pool->null_commodity, val));
}
balance_t::balance_t(const unsigned long val)
{
TRACE_CTOR(balance_t, "const unsigned long");
amounts.insert
(amounts_map::value_type(amount_t::current_pool->null_commodity, val));
}
balance_t::balance_t(const long val)
{
TRACE_CTOR(balance_t, "const long");
amounts.insert
(amounts_map::value_type(amount_t::current_pool->null_commodity, val));
}
balance_t& balance_t::operator+=(const balance_t& bal)
{
foreach (const amounts_map::value_type& pair, bal.amounts)
*this += pair.second;
return *this;
}
balance_t& balance_t::operator+=(const amount_t& amt)
{
if (amt.is_null())
throw_(balance_error,
_("Cannot add an uninitialized amount to a balance"));
if (amt.is_realzero())
return *this;
amounts_map::iterator i = amounts.find(&amt.commodity());
if (i != amounts.end())
i->second += amt;
else
amounts.insert(amounts_map::value_type(&amt.commodity(), amt));
return *this;
}
balance_t& balance_t::operator-=(const balance_t& bal)
{
foreach (const amounts_map::value_type& pair, bal.amounts)
*this -= pair.second;
return *this;
}
balance_t& balance_t::operator-=(const amount_t& amt)
{
if (amt.is_null())
throw_(balance_error,
_("Cannot subtract an uninitialized amount from a balance"));
if (amt.is_realzero())
return *this;
amounts_map::iterator i = amounts.find(&amt.commodity());
if (i != amounts.end()) {
i->second -= amt;
if (i->second.is_realzero())
amounts.erase(i);
} else {
amounts.insert(amounts_map::value_type(&amt.commodity(), amt.negated()));
}
return *this;
}
balance_t& balance_t::operator*=(const amount_t& amt)
{
if (amt.is_null())
throw_(balance_error,
_("Cannot multiply a balance by an uninitialized amount"));
if (is_realzero()) {
;
}
else if (amt.is_realzero()) {
*this = amt;
}
else if (! amt.commodity()) {
// Multiplying by an amount with no commodity causes all the
// component amounts to be increased by the same factor.
foreach (amounts_map::value_type& pair, amounts)
pair.second *= amt;
}
else if (amounts.size() == 1) {
// Multiplying by a commoditized amount is only valid if the sole
// commodity in the balance is of the same kind as the amount's
// commodity.
if (*amounts.begin()->first == amt.commodity())
amounts.begin()->second *= amt;
else
throw_(balance_error,
_("Cannot multiply a balance with annotated commodities by a commoditized amount"));
}
else {
assert(amounts.size() > 1);
throw_(balance_error,
_("Cannot multiply a multi-commodity balance by a commoditized amount"));
}
return *this;
}
balance_t& balance_t::operator/=(const amount_t& amt)
{
if (amt.is_null())
throw_(balance_error,
_("Cannot divide a balance by an uninitialized amount"));
if (is_realzero()) {
;
}
else if (amt.is_realzero()) {
throw_(balance_error, _("Divide by zero"));
}
else if (! amt.commodity()) {
// Dividing by an amount with no commodity causes all the
// component amounts to be divided by the same factor.
foreach (amounts_map::value_type& pair, amounts)
pair.second /= amt;
}
else if (amounts.size() == 1) {
// Dividing by a commoditized amount is only valid if the sole
// commodity in the balance is of the same kind as the amount's
// commodity.
if (*amounts.begin()->first == amt.commodity())
amounts.begin()->second /= amt;
else
throw_(balance_error,
_("Cannot divide a balance with annotated commodities by a commoditized amount"));
}
else {
assert(amounts.size() > 1);
throw_(balance_error,
_("Cannot divide a multi-commodity balance by a commoditized amount"));
}
return *this;
}
optional<balance_t>
balance_t::value(const bool primary_only,
const optional<datetime_t>& moment,
const optional<commodity_t&>& in_terms_of) const
{
balance_t temp;
bool resolved = false;
foreach (const amounts_map::value_type& pair, amounts) {
if (optional<amount_t> val = pair.second.value(primary_only, moment,
in_terms_of)) {
temp += *val;
resolved = true;
} else {
temp += pair.second;
}
}
return resolved ? temp : optional<balance_t>();
}
balance_t balance_t::price() const
{
balance_t temp;
foreach (const amounts_map::value_type& pair, amounts)
temp += pair.second.price();
return temp;
}
optional<amount_t>
balance_t::commodity_amount(const optional<const commodity_t&>& commodity) const
{
if (! commodity) {
if (amounts.size() == 1) {
return amounts.begin()->second;
}
#if 0
else if (amounts.size() > 1) {
// Try stripping annotations before giving an error.
balance_t temp(strip_annotations());
if (temp.amounts.size() == 1)
return temp.commodity_amount(commodity);
throw_(amount_error,
_("Requested amount of a balance with multiple commodities: %1") << temp);
}
#endif
}
else if (amounts.size() > 0) {
amounts_map::const_iterator i = amounts.find(&*commodity);
if (i != amounts.end())
return i->second;
}
return none;
}
balance_t
balance_t::strip_annotations(const keep_details_t& what_to_keep) const
{
balance_t temp;
foreach (const amounts_map::value_type& pair, amounts)
temp += pair.second.strip_annotations(what_to_keep);
return temp;
}
void balance_t::print(std::ostream& out,
const int first_width,
const int latter_width,
const bool right_justify,
const bool colorize) const
{
bool first = true;
int lwidth = latter_width;
if (lwidth == -1)
lwidth = first_width;
typedef std::vector<const amount_t *> amounts_array;
amounts_array sorted;
foreach (const amounts_map::value_type& pair, amounts)
if (pair.second)
sorted.push_back(&pair.second);
std::stable_sort(sorted.begin(), sorted.end(), compare_amount_commodities());
foreach (const amount_t * amount, sorted) {
int width;
if (! first) {
out << std::endl;
width = lwidth;
} else {
first = false;
width = first_width;
}
std::ostringstream buf;
buf << *amount;
justify(out, buf.str(), width, right_justify,
colorize && amount->sign() < 0);
}
if (first) {
out.width(first_width);
if (right_justify)
out << std::right;
else
out << std::left;
out << 0;
}
}
} // namespace ledger
<commit_msg>Whitespace fix<commit_after>/*
* Copyright (c) 2003-2009, John Wiegley. 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 New Artisans LLC 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 <system.hh>
#include "balance.h"
#include "commodity.h"
#include "pool.h"
#include "unistring.h" // for justify()
namespace ledger {
balance_t::balance_t(const double val)
{
TRACE_CTOR(balance_t, "const double");
amounts.insert
(amounts_map::value_type(amount_t::current_pool->null_commodity, val));
}
balance_t::balance_t(const unsigned long val)
{
TRACE_CTOR(balance_t, "const unsigned long");
amounts.insert
(amounts_map::value_type(amount_t::current_pool->null_commodity, val));
}
balance_t::balance_t(const long val)
{
TRACE_CTOR(balance_t, "const long");
amounts.insert
(amounts_map::value_type(amount_t::current_pool->null_commodity, val));
}
balance_t& balance_t::operator+=(const balance_t& bal)
{
foreach (const amounts_map::value_type& pair, bal.amounts)
*this += pair.second;
return *this;
}
balance_t& balance_t::operator+=(const amount_t& amt)
{
if (amt.is_null())
throw_(balance_error,
_("Cannot add an uninitialized amount to a balance"));
if (amt.is_realzero())
return *this;
amounts_map::iterator i = amounts.find(&amt.commodity());
if (i != amounts.end())
i->second += amt;
else
amounts.insert(amounts_map::value_type(&amt.commodity(), amt));
return *this;
}
balance_t& balance_t::operator-=(const balance_t& bal)
{
foreach (const amounts_map::value_type& pair, bal.amounts)
*this -= pair.second;
return *this;
}
balance_t& balance_t::operator-=(const amount_t& amt)
{
if (amt.is_null())
throw_(balance_error,
_("Cannot subtract an uninitialized amount from a balance"));
if (amt.is_realzero())
return *this;
amounts_map::iterator i = amounts.find(&amt.commodity());
if (i != amounts.end()) {
i->second -= amt;
if (i->second.is_realzero())
amounts.erase(i);
} else {
amounts.insert(amounts_map::value_type(&amt.commodity(), amt.negated()));
}
return *this;
}
balance_t& balance_t::operator*=(const amount_t& amt)
{
if (amt.is_null())
throw_(balance_error,
_("Cannot multiply a balance by an uninitialized amount"));
if (is_realzero()) {
;
}
else if (amt.is_realzero()) {
*this = amt;
}
else if (! amt.commodity()) {
// Multiplying by an amount with no commodity causes all the
// component amounts to be increased by the same factor.
foreach (amounts_map::value_type& pair, amounts)
pair.second *= amt;
}
else if (amounts.size() == 1) {
// Multiplying by a commoditized amount is only valid if the sole
// commodity in the balance is of the same kind as the amount's
// commodity.
if (*amounts.begin()->first == amt.commodity())
amounts.begin()->second *= amt;
else
throw_(balance_error,
_("Cannot multiply a balance with annotated commodities by a commoditized amount"));
}
else {
assert(amounts.size() > 1);
throw_(balance_error,
_("Cannot multiply a multi-commodity balance by a commoditized amount"));
}
return *this;
}
balance_t& balance_t::operator/=(const amount_t& amt)
{
if (amt.is_null())
throw_(balance_error,
_("Cannot divide a balance by an uninitialized amount"));
if (is_realzero()) {
;
}
else if (amt.is_realzero()) {
throw_(balance_error, _("Divide by zero"));
}
else if (! amt.commodity()) {
// Dividing by an amount with no commodity causes all the
// component amounts to be divided by the same factor.
foreach (amounts_map::value_type& pair, amounts)
pair.second /= amt;
}
else if (amounts.size() == 1) {
// Dividing by a commoditized amount is only valid if the sole
// commodity in the balance is of the same kind as the amount's
// commodity.
if (*amounts.begin()->first == amt.commodity())
amounts.begin()->second /= amt;
else
throw_(balance_error,
_("Cannot divide a balance with annotated commodities by a commoditized amount"));
}
else {
assert(amounts.size() > 1);
throw_(balance_error,
_("Cannot divide a multi-commodity balance by a commoditized amount"));
}
return *this;
}
optional<balance_t>
balance_t::value(const bool primary_only,
const optional<datetime_t>& moment,
const optional<commodity_t&>& in_terms_of) const
{
balance_t temp;
bool resolved = false;
foreach (const amounts_map::value_type& pair, amounts) {
if (optional<amount_t> val = pair.second.value(primary_only, moment,
in_terms_of)) {
temp += *val;
resolved = true;
} else {
temp += pair.second;
}
}
return resolved ? temp : optional<balance_t>();
}
balance_t balance_t::price() const
{
balance_t temp;
foreach (const amounts_map::value_type& pair, amounts)
temp += pair.second.price();
return temp;
}
optional<amount_t>
balance_t::commodity_amount(const optional<const commodity_t&>& commodity) const
{
if (! commodity) {
if (amounts.size() == 1) {
return amounts.begin()->second;
}
#if 0
else if (amounts.size() > 1) {
// Try stripping annotations before giving an error.
balance_t temp(strip_annotations());
if (temp.amounts.size() == 1)
return temp.commodity_amount(commodity);
throw_(amount_error,
_("Requested amount of a balance with multiple commodities: %1")
<< temp);
}
#endif
}
else if (amounts.size() > 0) {
amounts_map::const_iterator i =
amounts.find(const_cast<commodity_t *>(&*commodity));
if (i != amounts.end())
return i->second;
}
return none;
}
balance_t
balance_t::strip_annotations(const keep_details_t& what_to_keep) const
{
balance_t temp;
foreach (const amounts_map::value_type& pair, amounts)
temp += pair.second.strip_annotations(what_to_keep);
return temp;
}
void balance_t::print(std::ostream& out,
const int first_width,
const int latter_width,
const bool right_justify,
const bool colorize) const
{
bool first = true;
int lwidth = latter_width;
if (lwidth == -1)
lwidth = first_width;
typedef std::vector<const amount_t *> amounts_array;
amounts_array sorted;
foreach (const amounts_map::value_type& pair, amounts)
if (pair.second)
sorted.push_back(&pair.second);
std::stable_sort(sorted.begin(), sorted.end(), compare_amount_commodities());
foreach (const amount_t * amount, sorted) {
int width;
if (! first) {
out << std::endl;
width = lwidth;
} else {
first = false;
width = first_width;
}
std::ostringstream buf;
buf << *amount;
justify(out, buf.str(), width, right_justify,
colorize && amount->sign() < 0);
}
if (first) {
out.width(first_width);
if (right_justify)
out << std::right;
else
out << std::left;
out << 0;
}
}
} // namespace ledger
<|endoftext|>
|
<commit_before>// Copyright (c) 2014 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "hash.h"
#include "uint256.h"
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <vector>
#include <string>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>
// SYSCOIN use aliases as addresses
extern void GetAddressFromAlias(const std::string& strAlias, std::string& strAddress);
extern void GetAliasFromAddress(const std::string& strAddress, std::string& strAlias);
/** All alphanumeric characters except for "0", "I", "O", and "l" */
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
{
// Skip leading spaces.
while (*psz && isspace(*psz))
psz++;
// Skip and count leading '1's.
int zeroes = 0;
while (*psz == '1') {
zeroes++;
psz++;
}
// Allocate enough space in big-endian base256 representation.
std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up.
// Process the characters.
while (*psz && !isspace(*psz)) {
// Decode base58 character
const char* ch = strchr(pszBase58, *psz);
if (ch == NULL)
return false;
// Apply "b256 = b256 * 58 + ch".
int carry = ch - pszBase58;
for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) {
carry += 58 * (*it);
*it = carry % 256;
carry /= 256;
}
assert(carry == 0);
psz++;
}
// Skip trailing spaces.
while (isspace(*psz))
psz++;
if (*psz != 0)
return false;
// Skip leading zeroes in b256.
std::vector<unsigned char>::iterator it = b256.begin();
while (it != b256.end() && *it == 0)
it++;
// Copy result into output vector.
vch.reserve(zeroes + (b256.end() - it));
vch.assign(zeroes, 0x00);
while (it != b256.end())
vch.push_back(*(it++));
return true;
}
std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{
// Skip & count leading zeroes.
int zeroes = 0;
while (pbegin != pend && *pbegin == 0) {
pbegin++;
zeroes++;
}
// Allocate enough space in big-endian base58 representation.
std::vector<unsigned char> b58((pend - pbegin) * 138 / 100 + 1); // log(256) / log(58), rounded up.
// Process the bytes.
while (pbegin != pend) {
int carry = *pbegin;
// Apply "b58 = b58 * 256 + ch".
for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); it != b58.rend(); it++) {
carry += 256 * (*it);
*it = carry % 58;
carry /= 58;
}
assert(carry == 0);
pbegin++;
}
// Skip leading zeroes in base58 result.
std::vector<unsigned char>::iterator it = b58.begin();
while (it != b58.end() && *it == 0)
it++;
// Translate the result into a string.
std::string str;
str.reserve(zeroes + (b58.end() - it));
str.assign(zeroes, '1');
while (it != b58.end())
str += pszBase58[*(it++)];
return str;
}
std::string EncodeBase58(const std::vector<unsigned char>& vch)
{
return EncodeBase58(&vch[0], &vch[0] + vch.size());
}
bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58(str.c_str(), vchRet);
}
std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
{
// add 4-byte hash check to the end
std::vector<unsigned char> vch(vchIn);
uint256 hash = Hash(vch.begin(), vch.end());
vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
return EncodeBase58(vch);
}
bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
{
if (!DecodeBase58(psz, vchRet) ||
(vchRet.size() < 4)) {
vchRet.clear();
return false;
}
// re-calculate the checksum, insure it matches the included 4-byte checksum
uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);
if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {
vchRet.clear();
return false;
}
vchRet.resize(vchRet.size() - 4);
return true;
}
bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58Check(str.c_str(), vchRet);
}
CBase58Data::CBase58Data()
{
vchVersion.clear();
vchData.clear();
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize)
{
vchVersion = vchVersionIn;
vchData.resize(nSize);
if (!vchData.empty())
memcpy(&vchData[0], pdata, nSize);
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend)
{
SetData(vchVersionIn, (void*)pbegin, pend - pbegin);
}
bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes)
{
std::vector<unsigned char> vchTemp;
bool rc58 = DecodeBase58Check(psz, vchTemp);
if ((!rc58) || (vchTemp.size() < nVersionBytes)) {
vchData.clear();
vchVersion.clear();
return false;
}
vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);
vchData.resize(vchTemp.size() - nVersionBytes);
if (!vchData.empty())
memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size());
memory_cleanse(&vchTemp[0], vchData.size());
return true;
}
bool CBase58Data::SetString(const std::string& str)
{
return SetString(str.c_str());
}
std::string CBase58Data::ToString() const
{
std::vector<unsigned char> vch = vchVersion;
vch.insert(vch.end(), vchData.begin(), vchData.end());
return EncodeBase58Check(vch);
}
int CBase58Data::CompareTo(const CBase58Data& b58) const
{
if (vchVersion < b58.vchVersion)
return -1;
if (vchVersion > b58.vchVersion)
return 1;
if (vchData < b58.vchData)
return -1;
if (vchData > b58.vchData)
return 1;
return 0;
}
namespace
{
class CSyscoinAddressVisitor : public boost::static_visitor<bool>
{
private:
CSyscoinAddress* addr;
// SYSCOIN support old sys
bool bOldSys;
public:
CSyscoinAddressVisitor(CSyscoinAddress* addrIn) : addr(addrIn) {}
CSyscoinAddressVisitor(CSyscoinAddress* addrIn, bool oldSys) : bOldSys(oldSys), addr(addrIn) {}
bool operator()(const CKeyID& id) const { return addr->Set(id, bOldSys); }
bool operator()(const CScriptID& id) const { return addr->Set(id); }
bool operator()(const CNoDestination& no) const { return false; }
};
} // anon namespace
// SYSCOIN aliases as addresses
CSyscoinAddress::CSyscoinAddress() {
isAlias = false;
aliasName = "";
}
// SYSCOIN support old sys
CSyscoinAddress::CSyscoinAddress(const CTxDestination &dest, bool oldSys) {
isAlias = false;
aliasName = "";
Set(dest, oldSys);
}
CSyscoinAddress::CSyscoinAddress(const CTxDestination &dest) {
isAlias = false;
aliasName = "";
Set(dest);
}
CSyscoinAddress::CSyscoinAddress(const std::string& strAddress) {
isAlias = false;
aliasName = "";
SetString(strAddress);
// try to resolve alias address from alias name
if (!IsValid())
{
try
{
std::string strAliasAddress;
GetAddressFromAlias(strAddress, strAliasAddress);
SetString(strAliasAddress);
aliasName = strAddress;
isAlias = true;
}
catch(...)
{
}
}
// try to resolve alias name from alias address
else
{
try
{
std::string strAlias;
GetAliasFromAddress(strAddress, strAlias);
aliasName = strAlias;
isAlias = true;
}
catch(...)
{
}
}
}
CSyscoinAddress::CSyscoinAddress(const char* pszAddress) {
isAlias = false;
SetString(pszAddress);
// try to resolve alias address
if (!IsValid())
{
try
{
std::string strAliasAddress;
GetAddressFromAlias(std::string(pszAddress), strAliasAddress);
SetString(strAliasAddress);
aliasName = std::string(pszAddress);
isAlias = true;
}
catch(...)
{
}
}
else
{
try
{
std::string strAlias;
GetAliasFromAddress(std::string(pszAddress), strAlias);
aliasName = strAlias;
isAlias = true;
}
catch(...)
{
}
}
}
// SYSCOIN support old sys
bool CSyscoinAddress::Set(const CKeyID& id, bool oldSys = false)
{
SetData(Params().Base58Prefix(oldSys? CChainParams::PUBKEY_ADDRESS_SYS: CChainParams::PUBKEY_ADDRESS), &id, 20);
return true;
}
bool CSyscoinAddress::Set(const CScriptID& id)
{
SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);
return true;
}
// SYSCOIN support old sys
bool CSyscoinAddress::Set(const CTxDestination& dest, bool oldSys = false)
{
return boost::apply_visitor(CSyscoinAddressVisitor(this, oldSys), dest);
}
bool CSyscoinAddress::IsValid() const
{
return IsValid(Params());
}
bool CSyscoinAddress::IsValid(const CChainParams& params) const
{
bool fCorrectSize = vchData.size() == 20;
// SYSCOIN allow old SYSCOIN address scheme
bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||
vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS_SYS) ||
vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
return fCorrectSize && fKnownVersion;
}
CTxDestination CSyscoinAddress::Get() const
{
if (!IsValid())
return CNoDestination();
uint160 id;
memcpy(&id, &vchData[0], 20);
// SYSCOIN allow old SYSCOIN address scheme
if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||
vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS_SYS))
return CKeyID(id);
else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))
return CScriptID(id);
else
return CNoDestination();
}
bool CSyscoinAddress::GetKeyID(CKeyID& keyID) const
{
// SYSCOIN allow old SYSCOIN address scheme
if (!IsValid() || (vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS) && vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS_SYS)))
return false;
uint160 id;
memcpy(&id, &vchData[0], 20);
keyID = CKeyID(id);
return true;
}
bool CSyscoinAddress::IsScript() const
{
return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);
}
void CSyscoinSecret::SetKey(const CKey& vchSecret)
{
assert(vchSecret.IsValid());
SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());
if (vchSecret.IsCompressed())
vchData.push_back(1);
}
CKey CSyscoinSecret::GetKey()
{
CKey ret;
assert(vchData.size() >= 32);
ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1);
return ret;
}
bool CSyscoinSecret::IsValid() const
{
bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);
// SYSCOIN allow old SYSCOIN address scheme
bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY) ||
vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY_SYS);
return fExpectedFormat && fCorrectVersion;
}
bool CSyscoinSecret::SetString(const char* pszSecret)
{
return CBase58Data::SetString(pszSecret) && IsValid();
}
bool CSyscoinSecret::SetString(const std::string& strSecret)
{
return SetString(strSecret.c_str());
}
<commit_msg>compile<commit_after>// Copyright (c) 2014 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "base58.h"
#include "hash.h"
#include "uint256.h"
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include <vector>
#include <string>
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>
// SYSCOIN use aliases as addresses
extern void GetAddressFromAlias(const std::string& strAlias, std::string& strAddress);
extern void GetAliasFromAddress(const std::string& strAddress, std::string& strAlias);
/** All alphanumeric characters except for "0", "I", "O", and "l" */
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch)
{
// Skip leading spaces.
while (*psz && isspace(*psz))
psz++;
// Skip and count leading '1's.
int zeroes = 0;
while (*psz == '1') {
zeroes++;
psz++;
}
// Allocate enough space in big-endian base256 representation.
std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up.
// Process the characters.
while (*psz && !isspace(*psz)) {
// Decode base58 character
const char* ch = strchr(pszBase58, *psz);
if (ch == NULL)
return false;
// Apply "b256 = b256 * 58 + ch".
int carry = ch - pszBase58;
for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) {
carry += 58 * (*it);
*it = carry % 256;
carry /= 256;
}
assert(carry == 0);
psz++;
}
// Skip trailing spaces.
while (isspace(*psz))
psz++;
if (*psz != 0)
return false;
// Skip leading zeroes in b256.
std::vector<unsigned char>::iterator it = b256.begin();
while (it != b256.end() && *it == 0)
it++;
// Copy result into output vector.
vch.reserve(zeroes + (b256.end() - it));
vch.assign(zeroes, 0x00);
while (it != b256.end())
vch.push_back(*(it++));
return true;
}
std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{
// Skip & count leading zeroes.
int zeroes = 0;
while (pbegin != pend && *pbegin == 0) {
pbegin++;
zeroes++;
}
// Allocate enough space in big-endian base58 representation.
std::vector<unsigned char> b58((pend - pbegin) * 138 / 100 + 1); // log(256) / log(58), rounded up.
// Process the bytes.
while (pbegin != pend) {
int carry = *pbegin;
// Apply "b58 = b58 * 256 + ch".
for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); it != b58.rend(); it++) {
carry += 256 * (*it);
*it = carry % 58;
carry /= 58;
}
assert(carry == 0);
pbegin++;
}
// Skip leading zeroes in base58 result.
std::vector<unsigned char>::iterator it = b58.begin();
while (it != b58.end() && *it == 0)
it++;
// Translate the result into a string.
std::string str;
str.reserve(zeroes + (b58.end() - it));
str.assign(zeroes, '1');
while (it != b58.end())
str += pszBase58[*(it++)];
return str;
}
std::string EncodeBase58(const std::vector<unsigned char>& vch)
{
return EncodeBase58(&vch[0], &vch[0] + vch.size());
}
bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58(str.c_str(), vchRet);
}
std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
{
// add 4-byte hash check to the end
std::vector<unsigned char> vch(vchIn);
uint256 hash = Hash(vch.begin(), vch.end());
vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
return EncodeBase58(vch);
}
bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
{
if (!DecodeBase58(psz, vchRet) ||
(vchRet.size() < 4)) {
vchRet.clear();
return false;
}
// re-calculate the checksum, insure it matches the included 4-byte checksum
uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4);
if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) {
vchRet.clear();
return false;
}
vchRet.resize(vchRet.size() - 4);
return true;
}
bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58Check(str.c_str(), vchRet);
}
CBase58Data::CBase58Data()
{
vchVersion.clear();
vchData.clear();
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize)
{
vchVersion = vchVersionIn;
vchData.resize(nSize);
if (!vchData.empty())
memcpy(&vchData[0], pdata, nSize);
}
void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend)
{
SetData(vchVersionIn, (void*)pbegin, pend - pbegin);
}
bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes)
{
std::vector<unsigned char> vchTemp;
bool rc58 = DecodeBase58Check(psz, vchTemp);
if ((!rc58) || (vchTemp.size() < nVersionBytes)) {
vchData.clear();
vchVersion.clear();
return false;
}
vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);
vchData.resize(vchTemp.size() - nVersionBytes);
if (!vchData.empty())
memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size());
memory_cleanse(&vchTemp[0], vchData.size());
return true;
}
bool CBase58Data::SetString(const std::string& str)
{
return SetString(str.c_str());
}
std::string CBase58Data::ToString() const
{
std::vector<unsigned char> vch = vchVersion;
vch.insert(vch.end(), vchData.begin(), vchData.end());
return EncodeBase58Check(vch);
}
int CBase58Data::CompareTo(const CBase58Data& b58) const
{
if (vchVersion < b58.vchVersion)
return -1;
if (vchVersion > b58.vchVersion)
return 1;
if (vchData < b58.vchData)
return -1;
if (vchData > b58.vchData)
return 1;
return 0;
}
namespace
{
class CSyscoinAddressVisitor : public boost::static_visitor<bool>
{
private:
CSyscoinAddress* addr;
// SYSCOIN support old sys
bool bOldSys;
public:
CSyscoinAddressVisitor(CSyscoinAddress* addrIn) : addr(addrIn) {}
CSyscoinAddressVisitor(CSyscoinAddress* addrIn, bool oldSys) : bOldSys(oldSys), addr(addrIn) {}
bool operator()(const CKeyID& id) const { return addr->Set(id, bOldSys); }
bool operator()(const CScriptID& id) const { return addr->Set(id); }
bool operator()(const CNoDestination& no) const { return false; }
};
} // anon namespace
// SYSCOIN aliases as addresses
CSyscoinAddress::CSyscoinAddress() {
isAlias = false;
aliasName = "";
}
// SYSCOIN support old sys
CSyscoinAddress::CSyscoinAddress(const CTxDestination &dest, bool oldSys) {
isAlias = false;
aliasName = "";
Set(dest, oldSys);
}
CSyscoinAddress::CSyscoinAddress(const CTxDestination &dest) {
isAlias = false;
aliasName = "";
Set(dest, false);
}
CSyscoinAddress::CSyscoinAddress(const std::string& strAddress) {
isAlias = false;
aliasName = "";
SetString(strAddress);
// try to resolve alias address from alias name
if (!IsValid())
{
try
{
std::string strAliasAddress;
GetAddressFromAlias(strAddress, strAliasAddress);
SetString(strAliasAddress);
aliasName = strAddress;
isAlias = true;
}
catch(...)
{
}
}
// try to resolve alias name from alias address
else
{
try
{
std::string strAlias;
GetAliasFromAddress(strAddress, strAlias);
aliasName = strAlias;
isAlias = true;
}
catch(...)
{
}
}
}
CSyscoinAddress::CSyscoinAddress(const char* pszAddress) {
isAlias = false;
SetString(pszAddress);
// try to resolve alias address
if (!IsValid())
{
try
{
std::string strAliasAddress;
GetAddressFromAlias(std::string(pszAddress), strAliasAddress);
SetString(strAliasAddress);
aliasName = std::string(pszAddress);
isAlias = true;
}
catch(...)
{
}
}
else
{
try
{
std::string strAlias;
GetAliasFromAddress(std::string(pszAddress), strAlias);
aliasName = strAlias;
isAlias = true;
}
catch(...)
{
}
}
}
// SYSCOIN support old sys
bool CSyscoinAddress::Set(const CKeyID& id, bool oldSys = false)
{
SetData(Params().Base58Prefix(oldSys? CChainParams::PUBKEY_ADDRESS_SYS: CChainParams::PUBKEY_ADDRESS), &id, 20);
return true;
}
bool CSyscoinAddress::Set(const CScriptID& id)
{
SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);
return true;
}
// SYSCOIN support old sys
bool CSyscoinAddress::Set(const CTxDestination& dest, bool oldSys = false)
{
return boost::apply_visitor(CSyscoinAddressVisitor(this, oldSys), dest);
}
bool CSyscoinAddress::IsValid() const
{
return IsValid(Params());
}
bool CSyscoinAddress::IsValid(const CChainParams& params) const
{
bool fCorrectSize = vchData.size() == 20;
// SYSCOIN allow old SYSCOIN address scheme
bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||
vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS_SYS) ||
vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
return fCorrectSize && fKnownVersion;
}
CTxDestination CSyscoinAddress::Get() const
{
if (!IsValid())
return CNoDestination();
uint160 id;
memcpy(&id, &vchData[0], 20);
// SYSCOIN allow old SYSCOIN address scheme
if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||
vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS_SYS))
return CKeyID(id);
else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))
return CScriptID(id);
else
return CNoDestination();
}
bool CSyscoinAddress::GetKeyID(CKeyID& keyID) const
{
// SYSCOIN allow old SYSCOIN address scheme
if (!IsValid() || (vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS) && vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS_SYS)))
return false;
uint160 id;
memcpy(&id, &vchData[0], 20);
keyID = CKeyID(id);
return true;
}
bool CSyscoinAddress::IsScript() const
{
return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);
}
void CSyscoinSecret::SetKey(const CKey& vchSecret)
{
assert(vchSecret.IsValid());
SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());
if (vchSecret.IsCompressed())
vchData.push_back(1);
}
CKey CSyscoinSecret::GetKey()
{
CKey ret;
assert(vchData.size() >= 32);
ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1);
return ret;
}
bool CSyscoinSecret::IsValid() const
{
bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);
// SYSCOIN allow old SYSCOIN address scheme
bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY) ||
vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY_SYS);
return fExpectedFormat && fCorrectVersion;
}
bool CSyscoinSecret::SetString(const char* pszSecret)
{
return CBase58Data::SetString(pszSecret) && IsValid();
}
bool CSyscoinSecret::SetString(const std::string& strSecret)
{
return SetString(strSecret.c_str());
}
<|endoftext|>
|
<commit_before>//
// ex8_05.cpp
// Exercise 8.5
//
// Created by pezy on 11/9/14.
// Copyright (c) 2014 pezy. All rights reserved.
//
// @Brief Rewrite the previous program to store each word in a separate element
// @See ex8_04.cpp
#include <fstream>
#include <string>
#include <vector>
#include <iostream>
using std::vector;
using std::string;
using std::ifstream;
using std::cout;
using std::endl;
void ReadFileToVec(const string& fileName, vector<string>& vec)
{
ifstream ifs(fileName);
if (ifs) {
string buf;
while (ifs >> buf) vec.push_back(buf);
}
}
int main()
{
vector<string> vec;
ReadFileToVec("../data/book.txt", vec);
for (const auto& str : vec) cout << str << endl;
return 0;
}
<commit_msg>Update ex8_05.cpp<commit_after>//
// ex8_05.cpp
// Exercise 8.5
//
// Created by pezy on 11/9/14.
// Copyright (c) 2014 pezy. All rights reserved.
//
// @Brief Rewrite the previous program to store each word in a separate element.
// @See ex8_04.cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
using std::cout;
using std::endl;
using std::ifstream;
using std::vector;
using std::string;
void ReadFileToVec(const string &fileName, vector<string> &vec)
{
ifstream input(fileName);
if(input)
{
string s;
while(input>>s)
vec.push_back(s);
}
}
int main()
{
vector<string> vec;
ReadFileToVec("E:\\zzz.txt", vec);
for(const auto &str:vec)
cout<<str<<endl;
}
<|endoftext|>
|
<commit_before>/*
* This file is part of the Objavi Renderer.
*
* Copyright (C) 2013 Borko Jandras <borko.jandras@sourcefabric.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "bookjs.hpp"
#include <QDir>
#include <QFile>
#include <QString>
#include <QVariant>
#include <QTextStream>
#include <QDebug>
#include <QWebElement>
#include <QWebFrame>
#include <QWebPage>
#include <stdexcept>
namespace Objavi { namespace BookJS {
PaginationConfig::PaginationConfig()
{}
PaginationConfig::PaginationConfig(QList<QPair<QString,QVariant> > const & items)
{
typedef QPair<QString,QVariant> ItemType;
Q_FOREACH (ItemType const & item, items)
{
m_map[item.first] = item.second;
}
}
PaginationConfig PaginationConfig::parse(QString const & text)
{
typedef QPair<QString,QVariant> ItemType;
QList<ItemType> items;
Q_FOREACH (QString item, text.split(','))
{
QStringList pair = item.split(':');
if (pair.length() < 2) continue;
QString key = pair[0].trimmed();
QString val = pair[1].trimmed();
QVariant value;
if (key == "lengthUnit")
{
if (val == "'em'" || val == "\"em\"" ||
val == "'cm'" || val == "\"cm\"" ||
val == "'mm'" || val == "\"mm\"" ||
val == "'in'" || val == "\"in\"" ||
val == "'pt'" || val == "\"pt\"" ||
val == "'pc'" || val == "\"pc\"" ||
val == "'px'" || val == "\"px\"" ||
val == "'ex'" || val == "\"ex\"" ||
val == "'%'" || val == "\"%\"")
{
value = val;
}
}
else
{
bool ok = false;
double d = val.toDouble(&ok);
if (ok)
{
value = d;
}
}
if (value.isValid())
{
items.append(ItemType(key, value));
}
else
{
QString msg = QString("invalid value for option %1: %2").arg(key).arg(val);
throw std::runtime_error(msg.toLatin1().data());
}
}
return PaginationConfig(items);
}
namespace {
QSizeF makeSize(QString width, QString height)
{
if (width.endsWith("px") && height.endsWith("px"))
{
width = width.left(width.size() - 2);
height = height.left(height.size() - 2);
return QSizeF(width.toFloat(), height.toFloat());
}
else
{
return QSizeF();
}
}
}
QSizeF getPageSize(QWebPage const * page, QString className)
{
QWebElement document = page->mainFrame()->documentElement();
QWebElement element = document.findFirst(QString(".%1").arg(className));
if (! element.isNull())
{
QString width = element.styleProperty("width", QWebElement::ComputedStyle);
QString height = element.styleProperty("height", QWebElement::ComputedStyle);
return makeSize(width, height);
}
QString script_text =
"(function(className) {"
" var style = getComputedStyle(document.getElementsByClassName(className)[0], className);"
" return [style.width, style.height];"
"})('%1');";
script_text = script_text.arg(className);
QVariant result = document.evaluateJavaScript(script_text);
if (result.canConvert(QVariant::StringList))
{
QStringList list = result.toStringList();
return makeSize(list[0], list[1]);
}
return QSizeF();
}
namespace {
QString loadFile(QString path)
{
QFile file(path);
if (! file.open(QFile::ReadOnly))
{
QString message = QString("could not open file %1").arg(path);
throw std::runtime_error(message.toStdString());
}
return QTextStream(&file).readAll();
}
void appendCSS(QString text, QWebElement & element)
{
QString xml = element.toInnerXml();
xml += "<style>";
xml += text;
xml += "</style>";
element.setInnerXml(xml);
}
void appendJavascript(QString text, QWebElement & element)
{
QString xml = element.toInnerXml();
xml += "<script type=\"text/javascript\">";
xml += text;
xml += "</script>";
element.setInnerXml(xml);
}
QString makeFrontMatterContents(QWebElement const & head)
{
QString title;
QString subtitle;
QString editors;
QString license;
QString copyright;
for (QWebElement node = head.firstChild(); !node.isNull(); node = node.nextSibling())
{
QString name = node.localName();
if (name == "title")
{
title = node.toPlainText();
}
else if (name == "meta")
{
QString name = node.attribute("name");
QString value = node.attribute("content");
if (name == "license")
{
license = value;
}
else if (name == "copyright")
{
copyright = value;
}
}
}
return QString(
"<div id=\"booktitle\">%1</div>"
"<div id=\"booksubtitle\">%2</div>"
"<div id=\"bookeditors\">%3</div>"
"<div class=\"pagebreak\"></div>"
"<div id=\"copyrightpage\">Copyright: %4<br>License: %5</div>"
"<div class=\"pagebreak\"></div>")
.arg(title)
.arg(subtitle)
.arg(editors)
.arg(copyright).arg(license);
}
}
void install(QWebPage * page, QString bookjsPath, PaginationConfig const & paginationConfig, QString customCSS)
{
QWebElement document = page->mainFrame()->documentElement();
QWebElement head = document.findFirst("head");
if (head.isNull())
{
throw std::runtime_error("no document head");
}
QDir bookjsDir = QDir::current();
if (! bookjsPath.isEmpty())
{
bookjsDir = QDir(bookjsPath);
}
if (bookjsDir.exists() == false)
{
throw std::runtime_error("invalid BookJS path");
}
if (! customCSS.isEmpty())
{
appendCSS(customCSS, head);
}
QString script;
// preset pagination configuration
script += loadFile(bookjsDir.filePath("book-config.js"));
// user-specified pagination configuration
//
for (PaginationConfig::MapType::ConstIterator it = paginationConfig.items().begin();
it != paginationConfig.items().end(); ++it)
{
QString optionKey = it.key();
QString optionValue = it.value().toString();
script += QString("paginationConfig.%1 = %2;\n").arg(optionKey).arg(optionValue);
}
// front matter configuration
script += QString("paginationConfig.frontmatterContents = '%1';\n").arg(makeFrontMatterContents(head));
// main BookJS script text
script += loadFile(bookjsDir.filePath("book.js"));
// apply
script += "Pagination.applyBookLayout();";
page->mainFrame()->evaluateJavaScript(script);
}
} } // namespace Objavi::BookJS
<commit_msg>Make sure the contents of frontmatterContents is escaped.<commit_after>/*
* This file is part of the Objavi Renderer.
*
* Copyright (C) 2013 Borko Jandras <borko.jandras@sourcefabric.org>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "bookjs.hpp"
#include <QDir>
#include <QFile>
#include <QString>
#include <QVariant>
#include <QTextStream>
#include <QDebug>
#include <QWebElement>
#include <QWebFrame>
#include <QWebPage>
#include <stdexcept>
namespace Objavi { namespace BookJS {
PaginationConfig::PaginationConfig()
{}
PaginationConfig::PaginationConfig(QList<QPair<QString,QVariant> > const & items)
{
typedef QPair<QString,QVariant> ItemType;
Q_FOREACH (ItemType const & item, items)
{
m_map[item.first] = item.second;
}
}
PaginationConfig PaginationConfig::parse(QString const & text)
{
typedef QPair<QString,QVariant> ItemType;
QList<ItemType> items;
Q_FOREACH (QString item, text.split(','))
{
QStringList pair = item.split(':');
if (pair.length() < 2) continue;
QString key = pair[0].trimmed();
QString val = pair[1].trimmed();
QVariant value;
if (key == "lengthUnit")
{
if (val == "'em'" || val == "\"em\"" ||
val == "'cm'" || val == "\"cm\"" ||
val == "'mm'" || val == "\"mm\"" ||
val == "'in'" || val == "\"in\"" ||
val == "'pt'" || val == "\"pt\"" ||
val == "'pc'" || val == "\"pc\"" ||
val == "'px'" || val == "\"px\"" ||
val == "'ex'" || val == "\"ex\"" ||
val == "'%'" || val == "\"%\"")
{
value = val;
}
}
else
{
bool ok = false;
double d = val.toDouble(&ok);
if (ok)
{
value = d;
}
}
if (value.isValid())
{
items.append(ItemType(key, value));
}
else
{
QString msg = QString("invalid value for option %1: %2").arg(key).arg(val);
throw std::runtime_error(msg.toLatin1().data());
}
}
return PaginationConfig(items);
}
namespace {
QSizeF makeSize(QString width, QString height)
{
if (width.endsWith("px") && height.endsWith("px"))
{
width = width.left(width.size() - 2);
height = height.left(height.size() - 2);
return QSizeF(width.toFloat(), height.toFloat());
}
else
{
return QSizeF();
}
}
}
QSizeF getPageSize(QWebPage const * page, QString className)
{
QWebElement document = page->mainFrame()->documentElement();
QWebElement element = document.findFirst(QString(".%1").arg(className));
if (! element.isNull())
{
QString width = element.styleProperty("width", QWebElement::ComputedStyle);
QString height = element.styleProperty("height", QWebElement::ComputedStyle);
return makeSize(width, height);
}
QString script_text =
"(function(className) {"
" var style = getComputedStyle(document.getElementsByClassName(className)[0], className);"
" return [style.width, style.height];"
"})('%1');";
script_text = script_text.arg(className);
QVariant result = document.evaluateJavaScript(script_text);
if (result.canConvert(QVariant::StringList))
{
QStringList list = result.toStringList();
return makeSize(list[0], list[1]);
}
return QSizeF();
}
namespace {
QString loadFile(QString path)
{
QFile file(path);
if (! file.open(QFile::ReadOnly))
{
QString message = QString("could not open file %1").arg(path);
throw std::runtime_error(message.toStdString());
}
return QTextStream(&file).readAll();
}
void appendCSS(QString text, QWebElement & element)
{
QString xml = element.toInnerXml();
xml += "<style>";
xml += text;
xml += "</style>";
element.setInnerXml(xml);
}
void appendJavascript(QString text, QWebElement & element)
{
QString xml = element.toInnerXml();
xml += "<script type=\"text/javascript\">";
xml += text;
xml += "</script>";
element.setInnerXml(xml);
}
QString makeFrontMatterContents(QWebElement const & head)
{
QString title;
QString subtitle;
QString editors;
QString license;
QString copyright;
for (QWebElement node = head.firstChild(); !node.isNull(); node = node.nextSibling())
{
QString name = node.localName();
if (name == "title")
{
title = node.toPlainText();
}
else if (name == "meta")
{
QString name = node.attribute("name");
QString value = node.attribute("content");
if (name == "license")
{
license = value;
}
else if (name == "copyright")
{
copyright = value;
}
}
}
return QString(
"<div id=\"booktitle\">%1</div>"
"<div id=\"booksubtitle\">%2</div>"
"<div id=\"bookeditors\">%3</div>"
"<div class=\"pagebreak\"></div>"
"<div id=\"copyrightpage\">Copyright: %4<br>License: %5</div>"
"<div class=\"pagebreak\"></div>")
.arg(title)
.arg(subtitle)
.arg(editors)
.arg(copyright).arg(license);
}
}
void install(QWebPage * page, QString bookjsPath, PaginationConfig const & paginationConfig, QString customCSS)
{
QWebElement document = page->mainFrame()->documentElement();
QWebElement head = document.findFirst("head");
if (head.isNull())
{
throw std::runtime_error("no document head");
}
QDir bookjsDir = QDir::current();
if (! bookjsPath.isEmpty())
{
bookjsDir = QDir(bookjsPath);
}
if (bookjsDir.exists() == false)
{
throw std::runtime_error("invalid BookJS path");
}
if (! customCSS.isEmpty())
{
appendCSS(customCSS, head);
}
QString script;
// preset pagination configuration
script += loadFile(bookjsDir.filePath("book-config.js"));
// user-specified pagination configuration
//
for (PaginationConfig::MapType::ConstIterator it = paginationConfig.items().begin();
it != paginationConfig.items().end(); ++it)
{
QString optionKey = it.key();
QString optionValue = it.value().toString();
script += QString("\npaginationConfig.%1 = %2;").arg(optionKey).arg(optionValue);
}
// front matter configuration
//
QString frontmatterContents = makeFrontMatterContents(head);
frontmatterContents.replace("'", "\\'");
script += QString("\npaginationConfig.frontmatterContents = '%1';\n").arg(frontmatterContents);
// main BookJS script text
script += loadFile(bookjsDir.filePath("book.js"));
// apply
script += "\nPagination.applyBookLayout();";
page->mainFrame()->evaluateJavaScript(script);
}
} } // namespace Objavi::BookJS
<|endoftext|>
|
<commit_before>#include "bridge.hpp"
#include "util/common.hpp"
#include "dsp/ringbuffer.hpp"
#include <unistd.h>
#if ARCH_WIN
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <fcntl.h>
#endif
#include <thread>
namespace rack {
struct BridgeClientConnection;
static BridgeClientConnection *connections[BRIDGE_NUM_PORTS] = {};
static AudioIO *audioListeners[BRIDGE_NUM_PORTS] = {};
static std::thread serverThread;
static bool serverRunning = false;
static BridgeMidiDriver *driver = NULL;
struct BridgeClientConnection {
int client;
bool ready = false;
int port = -1;
int sampleRate = 0;
~BridgeClientConnection() {
setPort(-1);
}
/** Returns true if successful */
bool send(const void *buffer, int length) {
if (length <= 0)
return false;
#if ARCH_LIN
int flags = MSG_NOSIGNAL;
#else
int flags = 0;
#endif
ssize_t remaining = 0;
while (remaining < length) {
ssize_t actual = ::send(client, (const char*) buffer, length, flags);
if (actual <= 0) {
ready = false;
return false;
}
remaining += actual;
}
return true;
}
template <typename T>
bool send(T x) {
return send(&x, sizeof(x));
}
/** Returns true if successful */
bool recv(void *buffer, int length) {
if (length <= 0)
return false;
#if ARCH_LIN
int flags = MSG_NOSIGNAL;
#else
int flags = 0;
#endif
ssize_t remaining = 0;
while (remaining < length) {
ssize_t actual = ::recv(client, (char*) buffer + remaining, length - remaining, flags);
if (actual <= 0) {
ready = false;
return false;
}
remaining += actual;
}
return true;
}
template <typename T>
bool recv(T *x) {
return recv(x, sizeof(*x));
}
void flush() {
// Turn off Nagle
int flag = 1;
setsockopt(client, IPPROTO_TCP, TCP_NODELAY, (char*) &flag, sizeof(int));
// Turn on Nagle
flag = 0;
setsockopt(client, IPPROTO_TCP, TCP_NODELAY, (char*) &flag, sizeof(int));
}
void run() {
info("Bridge client connected");
// Check hello key
uint32_t hello = -1;
recv<uint32_t>(&hello);
if (hello != BRIDGE_HELLO) {
info("Bridge client protocol mismatch %x %x", hello, BRIDGE_HELLO);
return;
}
// Process commands until no longer ready
ready = true;
while (ready) {
step();
}
info("Bridge client closed");
}
/** Accepts a command from the client */
void step() {
uint8_t command;
if (!recv<uint8_t>(&command)) {
return;
}
switch (command) {
default:
case NO_COMMAND: {
warn("Bridge client: bad command %d detected, closing", command);
ready = false;
} break;
case QUIT_COMMAND: {
ready = false;
} break;
case PORT_SET_COMMAND: {
uint8_t port = -1;
recv<uint8_t>(&port);
setPort(port);
} break;
case MIDI_MESSAGE_COMMAND: {
MidiMessage message;
if (!recv(&message, 3)) {
return;
}
processMidi(message);
} break;
case AUDIO_SAMPLE_RATE_SET_COMMAND: {
uint32_t sampleRate = 0;
recv<uint32_t>(&sampleRate);
setSampleRate(sampleRate);
} break;
case AUDIO_PROCESS_COMMAND: {
uint32_t frames = 0;
recv<uint32_t>(&frames);
if (frames == 0 || frames > (1<<16)) {
ready = false;
return;
}
float input[BRIDGE_INPUTS * frames];
if (!recv(&input, BRIDGE_INPUTS * frames * sizeof(float))) {
debug("Failed to receive");
return;
}
float output[BRIDGE_OUTPUTS * frames];
memset(&output, 0, sizeof(output));
processStream(input, output, frames);
if (!send(&output, BRIDGE_OUTPUTS * frames * sizeof(float))) {
debug("Failed to send");
return;
}
// flush();
} break;
}
}
void setPort(int port) {
// Unbind from existing port
if (0 <= this->port && connections[this->port] == this) {
connections[this->port] = NULL;
}
// Bind to new port
if ((0 <= port && port < BRIDGE_NUM_PORTS) && !connections[port]) {
this->port = port;
connections[this->port] = this;
refreshAudio();
}
else {
this->port = -1;
}
}
void processMidi(MidiMessage message) {
if (!(0 <= port && port < BRIDGE_NUM_PORTS))
return;
if (!driver)
return;
driver->devices[port].onMessage(message);
}
void setSampleRate(int sampleRate) {
this->sampleRate = sampleRate;
refreshAudio();
}
void processStream(const float *input, float *output, int frames) {
if (!(0 <= port && port < BRIDGE_NUM_PORTS))
return;
if (!audioListeners[port])
return;
audioListeners[port]->setBlockSize(frames);
audioListeners[port]->processStream(input, output, frames);
}
void refreshAudio() {
if (!(0 <= port && port < BRIDGE_NUM_PORTS))
return;
if (connections[port] != this)
return;
if (!audioListeners[port])
return;
audioListeners[port]->setSampleRate(sampleRate);
}
};
static void clientRun(int client) {
defer({
#if ARCH_WIN
if (shutdown(client, SD_SEND)) {
warn("Bridge client shutdown() failed");
}
if (closesocket(client)) {
warn("Bridge client closesocket() failed");
}
#else
if (close(client)) {
warn("Bridge client close() failed");
}
#endif
});
#if ARCH_MAC
// Avoid SIGPIPE
int flag = 1;
if (setsockopt(client, SOL_SOCKET, SO_NOSIGPIPE, &flag, sizeof(int))) {
warn("Bridge client setsockopt() failed");
return;
}
#endif
// Disable non-blocking
#if ARCH_WIN
unsigned long blockingMode = 0;
if (ioctlsocket(client, FIONBIO, &blockingMode)) {
warn("Bridge client ioctlsocket() failed");
return;
}
#else
if (fcntl(client, F_SETFL, fcntl(client, F_GETFL, 0) & ~O_NONBLOCK)) {
warn("Bridge client fcntl() failed");
return;
}
#endif
BridgeClientConnection connection;
connection.client = client;
connection.run();
}
static void serverConnect() {
// Initialize sockets
#if ARCH_WIN
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData)) {
warn("Bridge server WSAStartup() failed");
return;
}
defer({
WSACleanup();
});
#endif
// Get address
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(BRIDGE_PORT);
#if ARCH_WIN
addr.sin_addr.s_addr = inet_addr(BRIDGE_HOST);
#else
inet_pton(AF_INET, BRIDGE_HOST, &addr.sin_addr);
#endif
// Open socket
int server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (server < 0) {
warn("Bridge server socket() failed");
return;
}
defer({
if (close(server)) {
warn("Bridge server close() failed");
return;
}
info("Bridge server closed");
});
#if ARCH_MAC || ARCH_LIN
int reuseAddrFlag = 1;
setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &reuseAddrFlag, sizeof(reuseAddrFlag));
#endif
// Bind socket to address
if (bind(server, (struct sockaddr*) &addr, sizeof(addr))) {
warn("Bridge server bind() failed");
return;
}
// Listen for clients
if (listen(server, 20)) {
warn("Bridge server listen() failed");
return;
}
info("Bridge server started");
// Enable non-blocking
#if ARCH_WIN
unsigned long blockingMode = 1;
if (ioctlsocket(server, FIONBIO, &blockingMode)) {
warn("Bridge server ioctlsocket() failed");
return;
}
#else
int flags = fcntl(server, F_GETFL, 0);
fcntl(server, F_SETFL, flags | O_NONBLOCK);
#endif
// Accept clients
while (serverRunning) {
int client = accept(server, NULL, NULL);
if (client < 0) {
// Wait a bit before attempting to accept another client
std::this_thread::sleep_for(std::chrono::duration<double>(0.1));
continue;
}
// Launch client thread
std::thread clientThread(clientRun, client);
clientThread.detach();
}
}
static void serverRun() {
while (serverRunning) {
std::this_thread::sleep_for(std::chrono::duration<double>(0.1));
serverConnect();
}
}
std::vector<int> BridgeMidiDriver::getInputDeviceIds() {
std::vector<int> deviceIds;
for (int i = 0; i < 16; i++) {
deviceIds.push_back(i);
}
return deviceIds;
}
std::string BridgeMidiDriver::getInputDeviceName(int deviceId) {
return stringf("Port %d", deviceId + 1);
}
MidiInputDevice *BridgeMidiDriver::subscribeInputDevice(int deviceId, MidiInput *midiInput) {
if (!(0 <= deviceId && deviceId < 16))
return NULL;
devices[deviceId].subscribe(midiInput);
return &devices[deviceId];
}
void BridgeMidiDriver::unsubscribeInputDevice(int deviceId, MidiInput *midiInput) {
if (!(0 <= deviceId && deviceId < 16))
return;
devices[deviceId].unsubscribe(midiInput);
}
void bridgeInit() {
serverRunning = true;
serverThread = std::thread(serverRun);
driver = new BridgeMidiDriver();
midiDriverAdd(BRIDGE_DRIVER, driver);
}
void bridgeDestroy() {
serverRunning = false;
serverThread.join();
}
void bridgeAudioSubscribe(int port, AudioIO *audio) {
if (!(0 <= port && port < BRIDGE_NUM_PORTS))
return;
// Check if an Audio is already subscribed on the port
if (audioListeners[port])
return;
audioListeners[port] = audio;
if (connections[port])
connections[port]->refreshAudio();
}
void bridgeAudioUnsubscribe(int port, AudioIO *audio) {
if (!(0 <= port && port < BRIDGE_NUM_PORTS))
return;
if (audioListeners[port] != audio)
return;
audioListeners[port] = NULL;
}
} // namespace rack
<commit_msg>Fix Bridge port name for ID=-1<commit_after>#include "bridge.hpp"
#include "util/common.hpp"
#include "dsp/ringbuffer.hpp"
#include <unistd.h>
#if ARCH_WIN
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <fcntl.h>
#endif
#include <thread>
namespace rack {
struct BridgeClientConnection;
static BridgeClientConnection *connections[BRIDGE_NUM_PORTS] = {};
static AudioIO *audioListeners[BRIDGE_NUM_PORTS] = {};
static std::thread serverThread;
static bool serverRunning = false;
static BridgeMidiDriver *driver = NULL;
struct BridgeClientConnection {
int client;
bool ready = false;
int port = -1;
int sampleRate = 0;
~BridgeClientConnection() {
setPort(-1);
}
/** Returns true if successful */
bool send(const void *buffer, int length) {
if (length <= 0)
return false;
#if ARCH_LIN
int flags = MSG_NOSIGNAL;
#else
int flags = 0;
#endif
ssize_t remaining = 0;
while (remaining < length) {
ssize_t actual = ::send(client, (const char*) buffer, length, flags);
if (actual <= 0) {
ready = false;
return false;
}
remaining += actual;
}
return true;
}
template <typename T>
bool send(T x) {
return send(&x, sizeof(x));
}
/** Returns true if successful */
bool recv(void *buffer, int length) {
if (length <= 0)
return false;
#if ARCH_LIN
int flags = MSG_NOSIGNAL;
#else
int flags = 0;
#endif
ssize_t remaining = 0;
while (remaining < length) {
ssize_t actual = ::recv(client, (char*) buffer + remaining, length - remaining, flags);
if (actual <= 0) {
ready = false;
return false;
}
remaining += actual;
}
return true;
}
template <typename T>
bool recv(T *x) {
return recv(x, sizeof(*x));
}
void flush() {
// Turn off Nagle
int flag = 1;
setsockopt(client, IPPROTO_TCP, TCP_NODELAY, (char*) &flag, sizeof(int));
// Turn on Nagle
flag = 0;
setsockopt(client, IPPROTO_TCP, TCP_NODELAY, (char*) &flag, sizeof(int));
}
void run() {
info("Bridge client connected");
// Check hello key
uint32_t hello = -1;
recv<uint32_t>(&hello);
if (hello != BRIDGE_HELLO) {
info("Bridge client protocol mismatch %x %x", hello, BRIDGE_HELLO);
return;
}
// Process commands until no longer ready
ready = true;
while (ready) {
step();
}
info("Bridge client closed");
}
/** Accepts a command from the client */
void step() {
uint8_t command;
if (!recv<uint8_t>(&command)) {
return;
}
switch (command) {
default:
case NO_COMMAND: {
warn("Bridge client: bad command %d detected, closing", command);
ready = false;
} break;
case QUIT_COMMAND: {
ready = false;
} break;
case PORT_SET_COMMAND: {
uint8_t port = -1;
recv<uint8_t>(&port);
setPort(port);
} break;
case MIDI_MESSAGE_COMMAND: {
MidiMessage message;
if (!recv(&message, 3)) {
return;
}
processMidi(message);
} break;
case AUDIO_SAMPLE_RATE_SET_COMMAND: {
uint32_t sampleRate = 0;
recv<uint32_t>(&sampleRate);
setSampleRate(sampleRate);
} break;
case AUDIO_PROCESS_COMMAND: {
uint32_t frames = 0;
recv<uint32_t>(&frames);
if (frames == 0 || frames > (1<<16)) {
ready = false;
return;
}
float input[BRIDGE_INPUTS * frames];
if (!recv(&input, BRIDGE_INPUTS * frames * sizeof(float))) {
debug("Failed to receive");
return;
}
float output[BRIDGE_OUTPUTS * frames];
memset(&output, 0, sizeof(output));
processStream(input, output, frames);
if (!send(&output, BRIDGE_OUTPUTS * frames * sizeof(float))) {
debug("Failed to send");
return;
}
// flush();
} break;
}
}
void setPort(int port) {
// Unbind from existing port
if (0 <= this->port && connections[this->port] == this) {
connections[this->port] = NULL;
}
// Bind to new port
if ((0 <= port && port < BRIDGE_NUM_PORTS) && !connections[port]) {
this->port = port;
connections[this->port] = this;
refreshAudio();
}
else {
this->port = -1;
}
}
void processMidi(MidiMessage message) {
if (!(0 <= port && port < BRIDGE_NUM_PORTS))
return;
if (!driver)
return;
driver->devices[port].onMessage(message);
}
void setSampleRate(int sampleRate) {
this->sampleRate = sampleRate;
refreshAudio();
}
void processStream(const float *input, float *output, int frames) {
if (!(0 <= port && port < BRIDGE_NUM_PORTS))
return;
if (!audioListeners[port])
return;
audioListeners[port]->setBlockSize(frames);
audioListeners[port]->processStream(input, output, frames);
}
void refreshAudio() {
if (!(0 <= port && port < BRIDGE_NUM_PORTS))
return;
if (connections[port] != this)
return;
if (!audioListeners[port])
return;
audioListeners[port]->setSampleRate(sampleRate);
}
};
static void clientRun(int client) {
defer({
#if ARCH_WIN
if (shutdown(client, SD_SEND)) {
warn("Bridge client shutdown() failed");
}
if (closesocket(client)) {
warn("Bridge client closesocket() failed");
}
#else
if (close(client)) {
warn("Bridge client close() failed");
}
#endif
});
#if ARCH_MAC
// Avoid SIGPIPE
int flag = 1;
if (setsockopt(client, SOL_SOCKET, SO_NOSIGPIPE, &flag, sizeof(int))) {
warn("Bridge client setsockopt() failed");
return;
}
#endif
// Disable non-blocking
#if ARCH_WIN
unsigned long blockingMode = 0;
if (ioctlsocket(client, FIONBIO, &blockingMode)) {
warn("Bridge client ioctlsocket() failed");
return;
}
#else
if (fcntl(client, F_SETFL, fcntl(client, F_GETFL, 0) & ~O_NONBLOCK)) {
warn("Bridge client fcntl() failed");
return;
}
#endif
BridgeClientConnection connection;
connection.client = client;
connection.run();
}
static void serverConnect() {
// Initialize sockets
#if ARCH_WIN
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData)) {
warn("Bridge server WSAStartup() failed");
return;
}
defer({
WSACleanup();
});
#endif
// Get address
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(BRIDGE_PORT);
#if ARCH_WIN
addr.sin_addr.s_addr = inet_addr(BRIDGE_HOST);
#else
inet_pton(AF_INET, BRIDGE_HOST, &addr.sin_addr);
#endif
// Open socket
int server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (server < 0) {
warn("Bridge server socket() failed");
return;
}
defer({
if (close(server)) {
warn("Bridge server close() failed");
return;
}
info("Bridge server closed");
});
#if ARCH_MAC || ARCH_LIN
int reuseAddrFlag = 1;
setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &reuseAddrFlag, sizeof(reuseAddrFlag));
#endif
// Bind socket to address
if (bind(server, (struct sockaddr*) &addr, sizeof(addr))) {
warn("Bridge server bind() failed");
return;
}
// Listen for clients
if (listen(server, 20)) {
warn("Bridge server listen() failed");
return;
}
info("Bridge server started");
// Enable non-blocking
#if ARCH_WIN
unsigned long blockingMode = 1;
if (ioctlsocket(server, FIONBIO, &blockingMode)) {
warn("Bridge server ioctlsocket() failed");
return;
}
#else
int flags = fcntl(server, F_GETFL, 0);
fcntl(server, F_SETFL, flags | O_NONBLOCK);
#endif
// Accept clients
while (serverRunning) {
int client = accept(server, NULL, NULL);
if (client < 0) {
// Wait a bit before attempting to accept another client
std::this_thread::sleep_for(std::chrono::duration<double>(0.1));
continue;
}
// Launch client thread
std::thread clientThread(clientRun, client);
clientThread.detach();
}
}
static void serverRun() {
while (serverRunning) {
std::this_thread::sleep_for(std::chrono::duration<double>(0.1));
serverConnect();
}
}
std::vector<int> BridgeMidiDriver::getInputDeviceIds() {
std::vector<int> deviceIds;
for (int i = 0; i < 16; i++) {
deviceIds.push_back(i);
}
return deviceIds;
}
std::string BridgeMidiDriver::getInputDeviceName(int deviceId) {
if (deviceId < 0)
return "";
return stringf("Port %d", deviceId + 1);
}
MidiInputDevice *BridgeMidiDriver::subscribeInputDevice(int deviceId, MidiInput *midiInput) {
if (!(0 <= deviceId && deviceId < 16))
return NULL;
devices[deviceId].subscribe(midiInput);
return &devices[deviceId];
}
void BridgeMidiDriver::unsubscribeInputDevice(int deviceId, MidiInput *midiInput) {
if (!(0 <= deviceId && deviceId < 16))
return;
devices[deviceId].unsubscribe(midiInput);
}
void bridgeInit() {
serverRunning = true;
serverThread = std::thread(serverRun);
driver = new BridgeMidiDriver();
midiDriverAdd(BRIDGE_DRIVER, driver);
}
void bridgeDestroy() {
serverRunning = false;
serverThread.join();
}
void bridgeAudioSubscribe(int port, AudioIO *audio) {
if (!(0 <= port && port < BRIDGE_NUM_PORTS))
return;
// Check if an Audio is already subscribed on the port
if (audioListeners[port])
return;
audioListeners[port] = audio;
if (connections[port])
connections[port]->refreshAudio();
}
void bridgeAudioUnsubscribe(int port, AudioIO *audio) {
if (!(0 <= port && port < BRIDGE_NUM_PORTS))
return;
if (audioListeners[port] != audio)
return;
audioListeners[port] = NULL;
}
} // namespace rack
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2005-2019 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.
*/
#ifndef otbTrainDecisionTree_hxx
#define otbTrainDecisionTree_hxx
#include "otbLearningApplicationBase.h"
#include "otbDecisionTreeMachineLearningModel.h"
namespace otb
{
namespace Wrapper
{
template <class TInputValue, class TOutputValue>
void
LearningApplicationBase<TInputValue,TOutputValue>
::InitDecisionTreeParams()
{
AddChoice("classifier.dt", "Decision Tree classifier");
SetParameterDescription("classifier.dt",
"http://docs.opencv.org/modules/ml/doc/decision_trees.html");
//MaxDepth
AddParameter(ParameterType_Int, "classifier.dt.max", "Maximum depth of the tree");
#ifdef OTB_OPENCV_3
SetParameterInt("classifier.dt.max",10);
#else
SetParameterInt("classifier.dt.max",65535);
#endif
SetParameterDescription("classifier.dt.max",
"The training algorithm attempts to split each node while its depth is smaller "
"than the maximum possible depth of the tree. The actual depth may be smaller "
"if the other termination criteria are met, and/or if the tree is pruned.");
//MinSampleCount
AddParameter(ParameterType_Int, "classifier.dt.min", "Minimum number of samples in each node");
SetParameterInt("classifier.dt.min",10);
SetParameterDescription("classifier.dt.min",
"If the number of samples in a node is smaller "
"than this parameter, then this node will not be split.");
//RegressionAccuracy
AddParameter(ParameterType_Float, "classifier.dt.ra", "Termination criteria for regression tree");
SetParameterFloat("classifier.dt.ra",0.01);
SetParameterDescription("classifier.dt.ra",
"If all absolute differences between an estimated value in a node "
"and the values of the train samples in this node are smaller than this "
"regression accuracy parameter, then the node will not be split further.");
//UseSurrogates : don't need to be exposed !
//SetParameterDescription("classifier.dt.sur","These splits allow working with missing data and compute variable importance correctly.");
//MaxCategories
AddParameter(ParameterType_Int, "classifier.dt.cat",
"Cluster possible values of a categorical variable into K <= cat clusters to find a "
"suboptimal split");
SetParameterInt("classifier.dt.cat",10);
SetParameterDescription("classifier.dt.cat",
"Cluster possible values of a categorical variable into K <= cat clusters to find a "
"suboptimal split.");
//CVFolds
AddParameter(ParameterType_Int, "classifier.dt.f", "K-fold cross-validations");
#ifdef OTB_OPENCV_3
// disable cross validation by default (crash in opencv 3.2)
SetParameterInt("classifier.dt.f",0);
#else
SetParameterInt("classifier.dt.f",10);
#endif
SetParameterDescription("classifier.dt.f",
"If cv_folds > 1, then it prunes a tree with K-fold cross-validation where K "
"is equal to cv_folds.");
//Use1seRule
AddParameter(ParameterType_Bool, "classifier.dt.r", "Set Use1seRule flag to false");
SetParameterDescription("classifier.dt.r",
"If true, then a pruning will be harsher. This will make a tree more compact and more "
"resistant to the training data noise but a bit less accurate.");
//TruncatePrunedTree
AddParameter(ParameterType_Bool, "classifier.dt.t", "Set TruncatePrunedTree flag to false");
SetParameterDescription("classifier.dt.t",
"If true, then pruned branches are physically removed from the tree.");
//Priors are not exposed.
}
template <class TInputValue, class TOutputValue>
void
LearningApplicationBase<TInputValue,TOutputValue>
::TrainDecisionTree(typename ListSampleType::Pointer trainingListSample,
typename TargetListSampleType::Pointer trainingLabeledListSample,
std::string modelPath)
{
typedef otb::DecisionTreeMachineLearningModel<InputValueType, OutputValueType> DecisionTreeType;
typename DecisionTreeType::Pointer classifier = DecisionTreeType::New();
classifier->SetRegressionMode(this->m_RegressionFlag);
classifier->SetInputListSample(trainingListSample);
classifier->SetTargetListSample(trainingLabeledListSample);
classifier->SetMaxDepth(GetParameterInt("classifier.dt.max"));
classifier->SetMinSampleCount(GetParameterInt("classifier.dt.min"));
classifier->SetRegressionAccuracy(GetParameterFloat("classifier.dt.ra"));
classifier->SetMaxCategories(GetParameterInt("classifier.dt.cat"));
classifier->SetCVFolds(GetParameterInt("classifier.dt.f"));
if (GetParameterInt("classifier.dt.r"))
{
classifier->SetUse1seRule(false);
}
if (GetParameterInt("classifier.dt.t"))
{
classifier->SetTruncatePrunedTree(false);
}
classifier->Train();
classifier->Save(modelPath);
}
} //end namespace wrapper
} //end namespace otb
#endif
<commit_msg>BUG: don't expose dt CVFold parameter for openCV 3<commit_after>/*
* Copyright (C) 2005-2019 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.
*/
#ifndef otbTrainDecisionTree_hxx
#define otbTrainDecisionTree_hxx
#include "otbLearningApplicationBase.h"
#include "otbDecisionTreeMachineLearningModel.h"
namespace otb
{
namespace Wrapper
{
template <class TInputValue, class TOutputValue>
void
LearningApplicationBase<TInputValue,TOutputValue>
::InitDecisionTreeParams()
{
AddChoice("classifier.dt", "Decision Tree classifier");
SetParameterDescription("classifier.dt",
"http://docs.opencv.org/modules/ml/doc/decision_trees.html");
//MaxDepth
AddParameter(ParameterType_Int, "classifier.dt.max", "Maximum depth of the tree");
#ifdef OTB_OPENCV_3
SetParameterInt("classifier.dt.max",10);
#else
SetParameterInt("classifier.dt.max",65535);
#endif
SetParameterDescription("classifier.dt.max",
"The training algorithm attempts to split each node while its depth is smaller "
"than the maximum possible depth of the tree. The actual depth may be smaller "
"if the other termination criteria are met, and/or if the tree is pruned.");
//MinSampleCount
AddParameter(ParameterType_Int, "classifier.dt.min", "Minimum number of samples in each node");
SetParameterInt("classifier.dt.min",10);
SetParameterDescription("classifier.dt.min",
"If the number of samples in a node is smaller "
"than this parameter, then this node will not be split.");
//RegressionAccuracy
AddParameter(ParameterType_Float, "classifier.dt.ra", "Termination criteria for regression tree");
SetParameterFloat("classifier.dt.ra",0.01);
SetParameterDescription("classifier.dt.ra",
"If all absolute differences between an estimated value in a node "
"and the values of the train samples in this node are smaller than this "
"regression accuracy parameter, then the node will not be split further.");
//UseSurrogates : don't need to be exposed !
//SetParameterDescription("classifier.dt.sur","These splits allow working with missing data and compute variable importance correctly.");
//MaxCategories
AddParameter(ParameterType_Int, "classifier.dt.cat",
"Cluster possible values of a categorical variable into K <= cat clusters to find a "
"suboptimal split");
SetParameterInt("classifier.dt.cat",10);
SetParameterDescription("classifier.dt.cat",
"Cluster possible values of a categorical variable into K <= cat clusters to find a "
"suboptimal split.");
//CVFolds: only exposed for OPENCV 2 because it crashes in OpenCV 3
#ifndef OTB_OPENCV_3
AddParameter(ParameterType_Int, "classifier.dt.f", "K-fold cross-validations");
SetParameterInt("classifier.dt.f",10);
SetParameterDescription("classifier.dt.f",
"If cv_folds > 1, then it prunes a tree with K-fold cross-validation where K "
"is equal to cv_folds.");
#endif
//Use1seRule
AddParameter(ParameterType_Bool, "classifier.dt.r", "Set Use1seRule flag to false");
SetParameterDescription("classifier.dt.r",
"If true, then a pruning will be harsher. This will make a tree more compact and more "
"resistant to the training data noise but a bit less accurate.");
//TruncatePrunedTree
AddParameter(ParameterType_Bool, "classifier.dt.t", "Set TruncatePrunedTree flag to false");
SetParameterDescription("classifier.dt.t",
"If true, then pruned branches are physically removed from the tree.");
//Priors are not exposed.
}
template <class TInputValue, class TOutputValue>
void
LearningApplicationBase<TInputValue,TOutputValue>
::TrainDecisionTree(typename ListSampleType::Pointer trainingListSample,
typename TargetListSampleType::Pointer trainingLabeledListSample,
std::string modelPath)
{
typedef otb::DecisionTreeMachineLearningModel<InputValueType, OutputValueType> DecisionTreeType;
typename DecisionTreeType::Pointer classifier = DecisionTreeType::New();
classifier->SetRegressionMode(this->m_RegressionFlag);
classifier->SetInputListSample(trainingListSample);
classifier->SetTargetListSample(trainingLabeledListSample);
classifier->SetMaxDepth(GetParameterInt("classifier.dt.max"));
classifier->SetMinSampleCount(GetParameterInt("classifier.dt.min"));
classifier->SetRegressionAccuracy(GetParameterFloat("classifier.dt.ra"));
classifier->SetMaxCategories(GetParameterInt("classifier.dt.cat"));
//CVFolds is only exposed for OPENCV 2 because it crashes in OpenCV 3
#ifndef OTB_OPENCV_3
classifier->SetCVFolds(GetParameterInt("classifier.dt.f"));
#endif
if (GetParameterInt("classifier.dt.r"))
{
classifier->SetUse1seRule(false);
}
if (GetParameterInt("classifier.dt.t"))
{
classifier->SetTruncatePrunedTree(false);
}
classifier->Train();
classifier->Save(modelPath);
}
} //end namespace wrapper
} //end namespace otb
#endif
<|endoftext|>
|
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkLevelSetDenseImageBase.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkLevelSetTestFunction.h"
/**
* \class ToleranceChecker
* \brief Compare values to see if they are within tolerance.
*/
template< typename RealType >
class ToleranceChecker
{
public:
ToleranceChecker(): m_Tolerance( 1e-8 )
{}
bool IsOutsideTolerance( const RealType & value, const RealType & theoreticalValue ) const
{
if( this->GetFractionalError( value, theoreticalValue ) > m_Tolerance )
{
return true;
}
return false;
}
RealType GetFractionalError( const RealType & value, const RealType & theoreticalValue ) const
{
RealType fractionalError = vnl_math_abs( theoreticalValue - value ) /
( vnl_math_abs( theoreticalValue ) + 20* vnl_math::eps );
return fractionalError;
}
/** Set fractional tolerance. */
void SetTolerance( const RealType & tolerance )
{
m_Tolerance = tolerance;
}
private:
RealType m_Tolerance;
};
int itkLevelSetDenseImageBaseTest( int , char* [] )
{
const unsigned int Dimension = 2;
typedef float PixelType;
typedef itk::Image< PixelType, Dimension > ImageType;
typedef itk::LevelSetDenseImageBase< ImageType > LevelSetType;
ImageType::IndexType index;
index[0] = 0;
index[1] = 0;
ImageType::SizeType size;
size[0] = 10;
size[1] = 20;
ImageType::RegionType region;
region.SetIndex( index );
region.SetSize( size );
PixelType zeroValue = 0.;
ImageType::SpacingType spacing;
spacing[0] = 0.02 / size[0];
spacing[1] = 0.02 / size[1];
ImageType::PointType origin;
origin[0] = 3.99;
origin[1] = 3.99;
ImageType::Pointer input = ImageType::New();
input->SetRegions( region );
input->SetSpacing( spacing );
input->SetOrigin( origin );
input->Allocate();
input->FillBuffer( zeroValue );
itk::ImageRegionIteratorWithIndex< ImageType > it( input,
input->GetLargestPossibleRegion() );
it.GoToBegin();
ImageType::IndexType idx;
ImageType::PointType pt;
typedef itk::LevelSetTestFunction< PixelType > TestFunctionType;
TestFunctionType::Pointer testFunction = TestFunctionType::New();
while( !it.IsAtEnd() )
{
idx = it.GetIndex();
input->TransformIndexToPhysicalPoint( idx, pt );
it.Set( testFunction->Evaluate( pt ) );
++it;
}
LevelSetType::Pointer level_set = LevelSetType::New();
level_set->SetImage( input );
idx[0] = 9;
idx[1] = 18;
input->TransformIndexToPhysicalPoint( idx, pt );
LevelSetType::OutputType theoreticalValue = testFunction->Evaluate( pt );
LevelSetType::OutputType value = level_set->Evaluate( idx );
ToleranceChecker< double > toleranceChecker;
toleranceChecker.SetTolerance( 1e-8 );
it.GoToBegin();
while( !it.IsAtEnd() )
{
idx = it.GetIndex();
input->TransformIndexToPhysicalPoint( idx, pt );
theoreticalValue = testFunction->Evaluate( pt );
value = level_set->Evaluate( idx );
if( toleranceChecker.IsOutsideTolerance( value, theoreticalValue ) )
{
std::cout << "Index:" << idx << " *EvaluateTestFail* " << value << " != "
<< theoreticalValue << std::endl;
return EXIT_FAILURE;
}
++it;
}
LevelSetType::GradientType gradient;
LevelSetType::GradientType theoreticalGradient;
toleranceChecker.SetTolerance( 0.1 );
it.GoToBegin();
while( !it.IsAtEnd() )
{
idx = it.GetIndex();
input->TransformIndexToPhysicalPoint( idx, pt );
theoreticalGradient = testFunction->EvaluateGradient( pt );
gradient = level_set->EvaluateGradient( idx );
if( toleranceChecker.IsOutsideTolerance( gradient[0], theoreticalGradient[0] ) ||
toleranceChecker.IsOutsideTolerance( gradient[1], theoreticalGradient[1] ) )
{
std::cout << "Index:" << idx << " Point: " << pt
<< " Error: [" << toleranceChecker.GetFractionalError( gradient[0], theoreticalGradient[0] )
<< ',' << toleranceChecker.GetFractionalError( gradient[1], theoreticalGradient[1] ) << "] "
<<" *EvaluateGradientTestFail* " << gradient << " != " << theoreticalGradient << std::endl;
return EXIT_FAILURE;
}
++it;
}
/** \todo more thorough testing as with the gradient above for hessian,
* laplacian, gradient norm. */
idx[0] = 9;
idx[1] = 18;
input->TransformIndexToPhysicalPoint( idx, pt );
LevelSetType::HessianType hessian = level_set->EvaluateHessian( idx );
std::cout << "hessian = " << std::endl << hessian << std::endl;
if ( vnl_math_abs( vnl_math_abs( hessian[0][0] ) - 499.998 ) / 499.998 > 5e-2 )
{
std::cout << idx << " *HessianTestFail* " << vnl_math_abs( hessian[0][0] ) << " != "
<< vnl_math_abs( hessian[1][1] ) << std::endl;
return EXIT_FAILURE;
}
LevelSetType::OutputRealType laplacian = level_set->EvaluateLaplacian( idx );
std::cout << "laplacian = " << laplacian << std::endl;
LevelSetType::OutputRealType gradientnorm = level_set->EvaluateGradientNorm( idx );
std::cout <<"gradient norm = " << gradientnorm << std::endl;
if( vnl_math_abs( 1 - gradientnorm ) > 5e-2 )
{
std::cout << idx << " *GradientNormFail* " << gradientnorm << " != "
<< 1 << std::endl;
return EXIT_FAILURE;
}
LevelSetType::OutputRealType meancurvature = level_set->EvaluateMeanCurvature( idx );
std::cout <<"mean curvature = " << meancurvature << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>BUG: LevelSetDenseImage test recognize zero values.<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkLevelSetDenseImageBase.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkLevelSetTestFunction.h"
/**
* \class ToleranceChecker
* \brief Compare values to see if they are within tolerance.
*/
template< typename RealType >
class ToleranceChecker
{
public:
ToleranceChecker(): m_Tolerance( 1e-8 )
{}
bool IsOutsideTolerance( const RealType & value, const RealType & theoreticalValue ) const
{
// ignore if they are both effectively zero
if( vnl_math_max( vnl_math_abs( value ), vnl_math_abs( theoreticalValue ) ) < 50 * vnl_math::eps )
{
return false;
}
if( this->GetFractionalError( value, theoreticalValue ) > m_Tolerance )
{
return true;
}
return false;
}
RealType GetFractionalError( const RealType & value, const RealType & theoreticalValue ) const
{
RealType fractionalError = vnl_math_abs( theoreticalValue - value ) /
( vnl_math_abs( theoreticalValue ) + 20* vnl_math::eps );
return fractionalError;
}
/** Set fractional tolerance. */
void SetTolerance( const RealType & tolerance )
{
m_Tolerance = tolerance;
}
private:
RealType m_Tolerance;
};
int itkLevelSetDenseImageBaseTest( int , char* [] )
{
const unsigned int Dimension = 2;
typedef float PixelType;
typedef itk::Image< PixelType, Dimension > ImageType;
typedef itk::LevelSetDenseImageBase< ImageType > LevelSetType;
ImageType::IndexType index;
index[0] = 0;
index[1] = 0;
ImageType::SizeType size;
size[0] = 10;
size[1] = 20;
ImageType::RegionType region;
region.SetIndex( index );
region.SetSize( size );
PixelType zeroValue = 0.;
ImageType::SpacingType spacing;
spacing[0] = 0.02 / size[0];
spacing[1] = 0.02 / size[1];
ImageType::PointType origin;
origin[0] = 3.99;
origin[1] = 3.99;
ImageType::Pointer input = ImageType::New();
input->SetRegions( region );
input->SetSpacing( spacing );
input->SetOrigin( origin );
input->Allocate();
input->FillBuffer( zeroValue );
itk::ImageRegionIteratorWithIndex< ImageType > it( input,
input->GetLargestPossibleRegion() );
it.GoToBegin();
ImageType::IndexType idx;
ImageType::PointType pt;
typedef itk::LevelSetTestFunction< PixelType > TestFunctionType;
TestFunctionType::Pointer testFunction = TestFunctionType::New();
while( !it.IsAtEnd() )
{
idx = it.GetIndex();
input->TransformIndexToPhysicalPoint( idx, pt );
it.Set( testFunction->Evaluate( pt ) );
++it;
}
LevelSetType::Pointer level_set = LevelSetType::New();
level_set->SetImage( input );
idx[0] = 9;
idx[1] = 18;
input->TransformIndexToPhysicalPoint( idx, pt );
LevelSetType::OutputType theoreticalValue = testFunction->Evaluate( pt );
LevelSetType::OutputType value = level_set->Evaluate( idx );
ToleranceChecker< double > toleranceChecker;
toleranceChecker.SetTolerance( 1e-8 );
it.GoToBegin();
while( !it.IsAtEnd() )
{
idx = it.GetIndex();
input->TransformIndexToPhysicalPoint( idx, pt );
theoreticalValue = testFunction->Evaluate( pt );
value = level_set->Evaluate( idx );
if( toleranceChecker.IsOutsideTolerance( value, theoreticalValue ) )
{
std::cout << "Index:" << idx << " *EvaluateTestFail* " << value << " != "
<< theoreticalValue << std::endl;
return EXIT_FAILURE;
}
++it;
}
LevelSetType::GradientType gradient;
LevelSetType::GradientType theoreticalGradient;
toleranceChecker.SetTolerance( 0.1 );
it.GoToBegin();
while( !it.IsAtEnd() )
{
idx = it.GetIndex();
input->TransformIndexToPhysicalPoint( idx, pt );
theoreticalGradient = testFunction->EvaluateGradient( pt );
gradient = level_set->EvaluateGradient( idx );
if( toleranceChecker.IsOutsideTolerance( gradient[0], theoreticalGradient[0] ) ||
toleranceChecker.IsOutsideTolerance( gradient[1], theoreticalGradient[1] ) )
{
std::cout << "Index:" << idx << " Point: " << pt
<< " Error: [" << toleranceChecker.GetFractionalError( gradient[0], theoreticalGradient[0] )
<< ',' << toleranceChecker.GetFractionalError( gradient[1], theoreticalGradient[1] ) << "] "
<<" *EvaluateGradientTestFail* " << gradient << " != " << theoreticalGradient << std::endl;
return EXIT_FAILURE;
}
++it;
}
/** \todo more thorough testing as with the gradient above for hessian,
* laplacian, gradient norm. */
idx[0] = 9;
idx[1] = 18;
input->TransformIndexToPhysicalPoint( idx, pt );
LevelSetType::HessianType hessian = level_set->EvaluateHessian( idx );
std::cout << "hessian = " << std::endl << hessian << std::endl;
if ( vnl_math_abs( vnl_math_abs( hessian[0][0] ) - 499.998 ) / 499.998 > 5e-2 )
{
std::cout << idx << " *HessianTestFail* " << vnl_math_abs( hessian[0][0] ) << " != "
<< vnl_math_abs( hessian[1][1] ) << std::endl;
return EXIT_FAILURE;
}
LevelSetType::OutputRealType laplacian = level_set->EvaluateLaplacian( idx );
std::cout << "laplacian = " << laplacian << std::endl;
LevelSetType::OutputRealType gradientnorm = level_set->EvaluateGradientNorm( idx );
std::cout <<"gradient norm = " << gradientnorm << std::endl;
if( vnl_math_abs( 1 - gradientnorm ) > 5e-2 )
{
std::cout << idx << " *GradientNormFail* " << gradientnorm << " != "
<< 1 << std::endl;
return EXIT_FAILURE;
}
LevelSetType::OutputRealType meancurvature = level_set->EvaluateMeanCurvature( idx );
std::cout <<"mean curvature = " << meancurvature << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include <array>
#include "builtin.hh"
#include "number.hh"
#include "procedure.hh"
#include "lisp_ptr.hh"
#include "eval.hh"
#include "builtin_util.hh"
#include "printer.hh"
using namespace std;
using namespace Procedure;
namespace {
void plus_2(){
auto args = pick_args<2>();
VM.return_value = {};
Number* n1 = args[0].get<Number*>();
if(!n1){
fprintf(stderr, "native func '+': first arg is not number! %s\n",
stringify(args[0].tag()));
return;
}
Number* n2 = args[1].get<Number*>();
if(!n2){
fprintf(stderr, "native func '+': second arg is not number! %s\n",
stringify(args[1].tag()));
return;
}
Number* newn = new Number(n1->get<long>() + n2->get<long>());
VM.return_value = Lisp_ptr(newn);
}
template <Ptr_tag p>
void type_check_pred(){
auto arg = pick_args_1();
VM.return_value = Lisp_ptr{arg.tag() == p};
}
void type_check_pair(){
auto arg = pick_args_1();
VM.return_value = Lisp_ptr{(arg.tag() == Ptr_tag::cons) && !nullp(arg)};
}
void type_check_procedure(){
auto arg = pick_args_1();
VM.return_value = Lisp_ptr{(arg.tag() == Ptr_tag::i_procedure)
|| (arg.tag() == Ptr_tag::n_procedure)};
}
Lisp_ptr whole_macro_or_expand(Cons* c){
if(!c->cdr() || nullp(c->cdr())){
return c->car();
}
const auto if_sym = intern(VM.symtable, "if");
auto else_clause = whole_macro_or_expand(c->cdr().get<Cons*>());
return Lisp_ptr(new Cons(Lisp_ptr(if_sym),
Lisp_ptr(new Cons(c->car(),
Lisp_ptr(new Cons(Lisp_ptr(vm_op_nop),
Lisp_ptr(new Cons(else_clause, Cons::NIL))))))));
}
Lisp_ptr whole_macro_and_expand(Cons* c){
if(!c->cdr() || nullp(c->cdr())){
return c->car();
}
const auto if_sym = intern(VM.symtable, "if");
auto then_clause = whole_macro_and_expand(c->cdr().get<Cons*>());
return Lisp_ptr(new Cons(Lisp_ptr(if_sym),
Lisp_ptr(new Cons(c->car(),
Lisp_ptr(new Cons(then_clause,
Lisp_ptr(new Cons(Lisp_ptr(vm_op_nop), Cons::NIL))))))));
}
Lisp_ptr whole_macro_cond_expand(Cons* head){
if(!head) return {}; // unspecified in R5RS.
auto clause = head->car();
if(!clause.get<Cons*>()){
fprintf(stderr, "macro cond: informal clause syntax! '");
print(stderr, head->car());
fprintf(stderr, "'\n");
return {};
}
Lisp_ptr test_form;
Lisp_ptr then_form;
int ret = bind_cons_list(clause,
[&](Cons* c){
test_form = c->car();
if(nullp(c->cdr())){
then_form = Lisp_ptr(vm_op_nop);
}
},
[&](Cons* c){
if(auto sym = c->car().get<Symbol*>()){
if(sym->name() == "=>"){
fprintf(stderr, "macto cond: sorry, cond's => syntax is not implemented..\n");
then_form = {};
return;
}
}
then_form = Lisp_ptr(new Cons(Lisp_ptr(intern(VM.symtable, "begin")), Lisp_ptr(c)));
});
assert(ret >= 1); // should be handled by previous tests.
(void)ret;
if(auto sym = test_form.get<Symbol*>()){
if(sym->name() == "else"){
return then_form;
}
}
const auto if_sym = intern(VM.symtable, "if");
auto else_form = whole_macro_cond_expand(head->cdr().get<Cons*>());
return Lisp_ptr(new Cons(Lisp_ptr(if_sym),
Lisp_ptr(new Cons(test_form,
Lisp_ptr(new Cons(then_form,
Lisp_ptr(new Cons(else_form, Cons::NIL))))))));
}
template<typename T, typename Expander>
inline
void whole_macro_conditional(T default_value, Expander e){
auto arg = pick_args_1();
if(!arg) return;
Cons* head;
int len = bind_cons_list(arg,
[](Cons*){},
[&](Cons* c){
head = c;
});
if(len < 2){
VM.return_value = Lisp_ptr(default_value);
return;
}
VM.return_value = e(head);
}
void whole_macro_and(){
whole_macro_conditional(true, whole_macro_and_expand);
}
void whole_macro_or(){
whole_macro_conditional(false, whole_macro_or_expand);
}
void whole_macro_cond(){
whole_macro_conditional(Lisp_ptr{}, whole_macro_cond_expand);
}
bool eq_internal(Lisp_ptr a, Lisp_ptr b){
if(a.tag() != b.tag()) return false;
if(a.tag() == Ptr_tag::boolean){
return a.get<bool>() == b.get<bool>();
}else if(a.tag() == Ptr_tag::character){
// this can be moved into eqv? in R5RS, but char is contained in Lisp_ptr.
return a.get<char>() == b.get<char>();
}else{
return a.get<void*>() == b.get<void*>();
}
}
void eq(){
auto args = pick_args<2>();
VM.return_value = Lisp_ptr{eq_internal(args[0], args[1])};
}
void eqv(){
auto args = pick_args<2>();
if(args[0].tag() == Ptr_tag::number && args[1].tag() == Ptr_tag::number){
VM.return_value = Lisp_ptr{eqv(*args[0].get<Number*>(), *args[1].get<Number*>())};
}else{
VM.return_value = Lisp_ptr{eq_internal(args[0], args[1])};
}
}
constexpr struct Entry {
const char* name;
const NProcedure func;
constexpr Entry(const char* n, const NProcedure& f)
: name(n), func(f){}
} builtin_func[] = {
// syntaxes
{"quote", {
whole_function_quote,
Calling::whole_function, {1, false}}},
{"lambda", {
whole_function_lambda,
Calling::whole_function, {1, true}}},
{"if", {
whole_function_if,
Calling::whole_function, {3, false}}},
{"set!", {
whole_function_set,
Calling::whole_function, {2, false}}},
{"define", {
whole_function_define,
Calling::whole_function, {2, true}}},
{"quasiquote", {
whole_function_quasiquote,
Calling::whole_function, {1, false}}},
{"begin", {
whole_function_begin,
Calling::whole_function, {1, true}}},
{"cond", {
whole_macro_cond,
Calling::whole_macro, {1, true}}},
{"case", {
whole_function_unimplemented,
Calling::whole_function, {0, true}}},
{"and", {
whole_macro_and,
Calling::whole_macro, {0, true}}},
{"or", {
whole_macro_or,
Calling::whole_macro, {0, true}}},
{"let", {
whole_function_let,
Calling::whole_function, {1, true}}},
{"let*", {
whole_function_let_star,
Calling::whole_function, {1, true}}},
{"letrec", {
whole_function_letrec,
Calling::whole_function, {1, true}}},
{"do", {
whole_function_unimplemented,
Calling::whole_function, {0, true}}},
{"delay", {
whole_function_unimplemented,
Calling::whole_function, {0, true}}},
{"unquote", {
whole_function_pass_through,
Calling::whole_function, {0, true}}},
{"unquote-splicing", {
whole_function_pass_through,
Calling::whole_function, {0, true}}},
{"else", {
whole_function_error,
Calling::whole_function, {0, false}}},
{"=>", {
whole_function_error,
Calling::whole_function, {0, false}}},
// functions
{"+", {
plus_2,
Calling::function, {2, true}}},
{"list", {
procedure_list,
Calling::function, {1, true}}},
{"list*", {
procedure_list_star,
Calling::function, {1, true}}},
{"vector", {
procedure_vector,
Calling::function, {1, true}}},
{"boolean?", {
type_check_pred<Ptr_tag::boolean>,
Calling::function, {1, false}}},
{"symbol?", {
type_check_pred<Ptr_tag::symbol>,
Calling::function, {1, false}}},
{"char?", {
type_check_pred<Ptr_tag::character>,
Calling::function, {1, false}}},
{"vector?", {
type_check_pred<Ptr_tag::vector>,
Calling::function, {1, false}}},
{"procedure?", {
type_check_procedure,
Calling::function, {1, false}}},
{"pair?", {
type_check_pair,
Calling::function, {1, false}}},
{"number?", {
type_check_pred<Ptr_tag::number>,
Calling::function, {1, false}}},
{"string?", {
type_check_pred<Ptr_tag::string>,
Calling::function, {1, false}}},
{"port?", {
type_check_pred<Ptr_tag::port>,
Calling::function, {1, false}}},
{"eqv?", {
eqv,
Calling::function, {2, false}}},
{"eq?", {
eq,
Calling::function, {2, false}}}
};
} //namespace
void install_builtin(){
for(auto& e : builtin_func){
VM.set(intern(VM.symtable, e.name), Lisp_ptr{&e.func});
}
}
<commit_msg>bitly change in eql<commit_after>#include <array>
#include "builtin.hh"
#include "number.hh"
#include "procedure.hh"
#include "lisp_ptr.hh"
#include "eval.hh"
#include "builtin_util.hh"
#include "printer.hh"
using namespace std;
using namespace Procedure;
namespace {
void plus_2(){
auto args = pick_args<2>();
VM.return_value = {};
Number* n1 = args[0].get<Number*>();
if(!n1){
fprintf(stderr, "native func '+': first arg is not number! %s\n",
stringify(args[0].tag()));
return;
}
Number* n2 = args[1].get<Number*>();
if(!n2){
fprintf(stderr, "native func '+': second arg is not number! %s\n",
stringify(args[1].tag()));
return;
}
Number* newn = new Number(n1->get<long>() + n2->get<long>());
VM.return_value = Lisp_ptr(newn);
}
template <Ptr_tag p>
void type_check_pred(){
auto arg = pick_args_1();
VM.return_value = Lisp_ptr{arg.tag() == p};
}
void type_check_pair(){
auto arg = pick_args_1();
VM.return_value = Lisp_ptr{(arg.tag() == Ptr_tag::cons) && !nullp(arg)};
}
void type_check_procedure(){
auto arg = pick_args_1();
VM.return_value = Lisp_ptr{(arg.tag() == Ptr_tag::i_procedure)
|| (arg.tag() == Ptr_tag::n_procedure)};
}
Lisp_ptr whole_macro_or_expand(Cons* c){
if(!c->cdr() || nullp(c->cdr())){
return c->car();
}
const auto if_sym = intern(VM.symtable, "if");
auto else_clause = whole_macro_or_expand(c->cdr().get<Cons*>());
return Lisp_ptr(new Cons(Lisp_ptr(if_sym),
Lisp_ptr(new Cons(c->car(),
Lisp_ptr(new Cons(Lisp_ptr(vm_op_nop),
Lisp_ptr(new Cons(else_clause, Cons::NIL))))))));
}
Lisp_ptr whole_macro_and_expand(Cons* c){
if(!c->cdr() || nullp(c->cdr())){
return c->car();
}
const auto if_sym = intern(VM.symtable, "if");
auto then_clause = whole_macro_and_expand(c->cdr().get<Cons*>());
return Lisp_ptr(new Cons(Lisp_ptr(if_sym),
Lisp_ptr(new Cons(c->car(),
Lisp_ptr(new Cons(then_clause,
Lisp_ptr(new Cons(Lisp_ptr(vm_op_nop), Cons::NIL))))))));
}
Lisp_ptr whole_macro_cond_expand(Cons* head){
if(!head) return {}; // unspecified in R5RS.
auto clause = head->car();
if(!clause.get<Cons*>()){
fprintf(stderr, "macro cond: informal clause syntax! '");
print(stderr, head->car());
fprintf(stderr, "'\n");
return {};
}
Lisp_ptr test_form;
Lisp_ptr then_form;
int ret = bind_cons_list(clause,
[&](Cons* c){
test_form = c->car();
if(nullp(c->cdr())){
then_form = Lisp_ptr(vm_op_nop);
}
},
[&](Cons* c){
if(auto sym = c->car().get<Symbol*>()){
if(sym->name() == "=>"){
fprintf(stderr, "macto cond: sorry, cond's => syntax is not implemented..\n");
then_form = {};
return;
}
}
then_form = Lisp_ptr(new Cons(Lisp_ptr(intern(VM.symtable, "begin")), Lisp_ptr(c)));
});
assert(ret >= 1); // should be handled by previous tests.
(void)ret;
if(auto sym = test_form.get<Symbol*>()){
if(sym->name() == "else"){
return then_form;
}
}
const auto if_sym = intern(VM.symtable, "if");
auto else_form = whole_macro_cond_expand(head->cdr().get<Cons*>());
return Lisp_ptr(new Cons(Lisp_ptr(if_sym),
Lisp_ptr(new Cons(test_form,
Lisp_ptr(new Cons(then_form,
Lisp_ptr(new Cons(else_form, Cons::NIL))))))));
}
template<typename T, typename Expander>
inline
void whole_macro_conditional(T default_value, Expander e){
auto arg = pick_args_1();
if(!arg) return;
Cons* head;
int len = bind_cons_list(arg,
[](Cons*){},
[&](Cons* c){
head = c;
});
if(len < 2){
VM.return_value = Lisp_ptr(default_value);
return;
}
VM.return_value = e(head);
}
void whole_macro_and(){
whole_macro_conditional(true, whole_macro_and_expand);
}
void whole_macro_or(){
whole_macro_conditional(false, whole_macro_or_expand);
}
void whole_macro_cond(){
whole_macro_conditional(Lisp_ptr{}, whole_macro_cond_expand);
}
bool eq_internal(Lisp_ptr a, Lisp_ptr b){
if(a.tag() != b.tag()) return false;
if(a.tag() == Ptr_tag::boolean){
return a.get<bool>() == b.get<bool>();
}else if(a.tag() == Ptr_tag::character){
// this can be moved into eqv? in R5RS, but char is contained in Lisp_ptr.
return a.get<char>() == b.get<char>();
}else{
return a.get<void*>() == b.get<void*>();
}
}
bool eqv_internal(Lisp_ptr a, Lisp_ptr b){
if(a.tag() == Ptr_tag::number && b.tag() == Ptr_tag::number){
return eqv(*a.get<Number*>(), *b.get<Number*>());
}else{
return eq_internal(a, b);
}
}
void eq(){
auto args = pick_args<2>();
VM.return_value = Lisp_ptr{eq_internal(args[0], args[1])};
}
void eqv(){
auto args = pick_args<2>();
VM.return_value = Lisp_ptr{eqv_internal(args[0], args[1])};
}
constexpr struct Entry {
const char* name;
const NProcedure func;
constexpr Entry(const char* n, const NProcedure& f)
: name(n), func(f){}
} builtin_func[] = {
// syntaxes
{"quote", {
whole_function_quote,
Calling::whole_function, {1, false}}},
{"lambda", {
whole_function_lambda,
Calling::whole_function, {1, true}}},
{"if", {
whole_function_if,
Calling::whole_function, {3, false}}},
{"set!", {
whole_function_set,
Calling::whole_function, {2, false}}},
{"define", {
whole_function_define,
Calling::whole_function, {2, true}}},
{"quasiquote", {
whole_function_quasiquote,
Calling::whole_function, {1, false}}},
{"begin", {
whole_function_begin,
Calling::whole_function, {1, true}}},
{"cond", {
whole_macro_cond,
Calling::whole_macro, {1, true}}},
{"case", {
whole_function_unimplemented,
Calling::whole_function, {0, true}}},
{"and", {
whole_macro_and,
Calling::whole_macro, {0, true}}},
{"or", {
whole_macro_or,
Calling::whole_macro, {0, true}}},
{"let", {
whole_function_let,
Calling::whole_function, {1, true}}},
{"let*", {
whole_function_let_star,
Calling::whole_function, {1, true}}},
{"letrec", {
whole_function_letrec,
Calling::whole_function, {1, true}}},
{"do", {
whole_function_unimplemented,
Calling::whole_function, {0, true}}},
{"delay", {
whole_function_unimplemented,
Calling::whole_function, {0, true}}},
{"unquote", {
whole_function_pass_through,
Calling::whole_function, {0, true}}},
{"unquote-splicing", {
whole_function_pass_through,
Calling::whole_function, {0, true}}},
{"else", {
whole_function_error,
Calling::whole_function, {0, false}}},
{"=>", {
whole_function_error,
Calling::whole_function, {0, false}}},
// functions
{"+", {
plus_2,
Calling::function, {2, true}}},
{"list", {
procedure_list,
Calling::function, {1, true}}},
{"list*", {
procedure_list_star,
Calling::function, {1, true}}},
{"vector", {
procedure_vector,
Calling::function, {1, true}}},
{"boolean?", {
type_check_pred<Ptr_tag::boolean>,
Calling::function, {1, false}}},
{"symbol?", {
type_check_pred<Ptr_tag::symbol>,
Calling::function, {1, false}}},
{"char?", {
type_check_pred<Ptr_tag::character>,
Calling::function, {1, false}}},
{"vector?", {
type_check_pred<Ptr_tag::vector>,
Calling::function, {1, false}}},
{"procedure?", {
type_check_procedure,
Calling::function, {1, false}}},
{"pair?", {
type_check_pair,
Calling::function, {1, false}}},
{"number?", {
type_check_pred<Ptr_tag::number>,
Calling::function, {1, false}}},
{"string?", {
type_check_pred<Ptr_tag::string>,
Calling::function, {1, false}}},
{"port?", {
type_check_pred<Ptr_tag::port>,
Calling::function, {1, false}}},
{"eqv?", {
eqv,
Calling::function, {2, false}}},
{"eq?", {
eq,
Calling::function, {2, false}}}
};
} //namespace
void install_builtin(){
for(auto& e : builtin_func){
VM.set(intern(VM.symtable, e.name), Lisp_ptr{&e.func});
}
}
<|endoftext|>
|
<commit_before>#include <algorithm>
#include <cmath>
#include <vector>
#include <QFile>
#include <QRegularExpression>
#include "ToolBase.h"
#include "Exceptions.h"
#include "Helper.h"
#include "VcfFile.h"
#include "NeedlemanWunsch.hpp"
using namespace std;
class ConcreteTool: public ToolBase
{
Q_OBJECT
public:
ConcreteTool(int& argc, char *argv[])
: ToolBase(argc, argv)
{
}
virtual void setup()
{
setDescription("Breaks complex variants into primitives preserving INFO/SAMPLE fields.");
setExtendedDescription(QStringList() << "Multi-allelic variants are ignored, since we assume they have already been split, e.g. with VcfBreakMulti."
<< "Complex variants that are decomposed, are flagged with a BBC (before break-complex) info entry.");
addInfile("in", "Input VCF file. If unset, reads from STDIN.", true, true);
addOutfile("out", "Output VCF list. If unset, writes to STDOUT.", true, true);
addOutfile("stats", "Ouptuts statistics. If unset, writes to STDERR.", true, true);
addFlag("keep_mnps", "Write out MNPs unchanged.");
addFlag("no_tag", "Skip annotation of decomposed variants with BBC in INFO field.");
changeLog(2018, 11, 30, "Initial implementation.");
}
/**
* @brief main
* This program breaks complex variants into several lines. It is inspired by vt's decompose_suballelic and vcflib's vcfallelicprimitives.
* However this program will only deal with complex variants. It will not consinder multi-allelic variants.
* We use the classification procedure as described in the VT wiki here https://genome.sph.umich.edu/wiki/Variant_classification
* Local aligment of variants is done using Needleman-Wunsch as implemented in edlib. See https://doi.org/10.1093/bioinformatics/btw753
*/
virtual void main()
{
QString in = getInfile("in");
QString out = getOutfile("out");
QString stats = getOutfile("stats");
bool keep_mnps = getFlag("keep_mnps");
bool no_tag = getFlag("no_tag");
if(in!="" && in==out)
{
THROW(ArgumentException, "Input and output files must be different when streaming!");
}
if(stats!="" && stats==out)
{
THROW(ArgumentException, "Error and output files must be different when streaming!");
}
QSharedPointer<QFile> in_p = Helper::openFileForReading(in, true);
QSharedPointer<QFile> out_p = Helper::openFileForWriting(out, true);
// Statistics
bool inserted_info = false;
unsigned int number_of_additional_snps = 0;
unsigned int number_of_biallelic_block_substitutions = 0;
unsigned int number_of_new_variants = 0;
unsigned int number_of_variants = 0;
using Aligment = tuple<QByteArray, QByteArray, int>; // Describes an aligment of REF, ALT, OFFSET
while(!in_p->atEnd())
{
QByteArray line = in_p->readLine();
// Skip empty lines and headers
if (line.trimmed().isEmpty() || line.startsWith("#"))
{
out_p->write(line);
if (!inserted_info) // Insert right after version line
{
if (!no_tag) out_p->write("##INFO=<ID=BBC,Number=1,Type=String,Description=\"Original chr:pos:ref|alt encoding\">\n");
inserted_info = true;
}
continue;
}
// Not a header line so increment the variant
++number_of_variants;
QByteArray ref = VcfFile::getPartByColumn(line, VcfFile::REF).trimmed();
QByteArray alt = VcfFile::getPartByColumn(line, VcfFile::ALT).trimmed();
int pos = VcfFile::getPartByColumn(line, VcfFile::POS).trimmed().toInt();
// Skip alternating allele pairs
if (alt.contains(","))
{
out_p->write(line);
continue;
}
VariantType variant_type = VcfFile::classifyVariant(ref, alt);
if (variant_type != SNP) // Align with Needleman-Wunsch
{
auto nw = NeedlemanWunsch<QByteArray>(ref, alt);
nw.compute_matrix();
nw.trace_back();
auto aligment = nw.get_aligments();
auto reference = get<ALIGMENT_REFERENCE>(aligment), query = get<ALIGMENT_QUERY>(aligment);
// Iterate through the reference and compare it with the query
using AligmentPair = pair<QByteArray, QByteArray>;
vector<Aligment> aligments;
if (ref.length() == 1 || alt.length() == 1) // SNP
{
aligments.push_back(Aligment(query.replace("-", ""), reference.replace("-", ""), 0));
++number_of_additional_snps;
}
else // MNP or CLUMPED
{
if (keep_mnps) // Keep more complex variants
{
out_p->write(line);
}
else // Break up clumped variants
{
while (query.startsWith("-")) // Kill leading gaps
{
query = query.remove(0, 1);
}
for (auto i = 0; i < query.size(); ++i)
{
if (i + 1 < query.size() && query.at(i + 1) == '-') // transition from REF,- to ALT
{
int gap_start = static_cast<int> (i + 1);
int gap_end = gap_start;
while ((i + 1) < query.size() && query.at(i + 1) == '-')
{
++i;
gap_end++;
}
aligments.push_back(Aligment(query.mid(gap_start - 1, 1), reference.mid(gap_start - 1, gap_end).replace("-", ""), gap_start));
++number_of_biallelic_block_substitutions; // new biallelic block substitutios
}
else if (i + 1 < reference.size() && reference.at(i + 1) == '-') // do the same for the reference
{
int gap_start = static_cast<int> (i +1);
int gap_end = gap_start;
while ((i + 1) < reference.size() && reference.at(i + 1) == '-')
{
++i;
++gap_end;
}
aligments.push_back(Aligment(query.mid(gap_start - 1, 2), reference.mid(gap_start - 1, gap_end).replace("-", ""), gap_start));
++number_of_biallelic_block_substitutions; // new biallelic block substitutios
}
else if (reference.at(i) == '-') {
int gap_start = static_cast<int> (i);
int gap_end = gap_start;
while ((i + 1) < reference.size() && reference.at(i) == '-')
{
++i;
++gap_end;
}
aligments.push_back(Aligment(query.mid(gap_start, gap_end - gap_start), reference.mid(gap_end, 1), gap_start));
++number_of_biallelic_block_substitutions;
}
else if (query.at(i) != reference.at(i)) // transition from REF -> ALT
{
aligments.push_back(Aligment(query.mid(i, 1), reference.mid(i, 1), i));
++i;
++number_of_additional_snps;
}
}
}
}
for (size_t i = 0; i < aligments.size(); ++i) // write out the new sequences
{
if (i > 0) ++number_of_new_variants;
auto parts = line.split('\t');
// Append INFO entry in format BBC=chr:pos:ref:alt
if (!no_tag) parts[VcfFile::INFO] = parts[VcfFile::INFO].trimmed() + ";BBC=" + parts[VcfFile::CHROM] + ":" + parts[VcfFile::POS] + ":" + parts[VcfFile::REF] + "|" + parts[VcfFile::ALT];
// Modify alt and ref with new aligments
parts[VcfFile::REF] = get<0>(aligments[i]);
parts[VcfFile::ALT] = get<1>(aligments[i]);
parts[VcfFile::POS] = QByteArray::number(pos + get<2>(aligments[i]));
// Write to output
out_p->write(parts.join("\t"));
}
}
else // We don't look at SNP's
{
out_p->write(line);
}
}
// After processing print statistics to error stream
QSharedPointer<QFile> stats_p = QSharedPointer<QFile>(new QFile(stats));
stats_p->open(stderr, QFile::WriteOnly | QIODevice::Text);
double new_variants_in_percent = (number_of_variants>0) ? 100.0 * number_of_new_variants / number_of_variants : 0.0;
stats_p->write(QByteArray("Processed ") + QByteArray::number(number_of_variants) + " variant(s) of which " + QByteArray::number(number_of_new_variants) + " (" + QByteArray::number(new_variants_in_percent, 'f', 2) + "%) were decomposed.\n");
stats_p->write(QByteArray::number(number_of_additional_snps - number_of_new_variants) + " of these are additional SNPs and " + QByteArray::number(number_of_biallelic_block_substitutions - number_of_variants) + " of these are biallelic substitutions.\n");
}
};
#include "main.moc"
int main(int argc, char *argv[])
{
ConcreteTool tool(argc, argv);
return tool.execute();
}
<commit_msg>[vcfbreakcomplex] Remove unneeded declaration<commit_after>#include <algorithm>
#include <cmath>
#include <vector>
#include <QFile>
#include <QRegularExpression>
#include "ToolBase.h"
#include "Exceptions.h"
#include "Helper.h"
#include "VcfFile.h"
#include "NeedlemanWunsch.hpp"
using namespace std;
class ConcreteTool: public ToolBase
{
Q_OBJECT
public:
ConcreteTool(int& argc, char *argv[])
: ToolBase(argc, argv)
{
}
virtual void setup()
{
setDescription("Breaks complex variants into primitives preserving INFO/SAMPLE fields.");
setExtendedDescription(QStringList() << "Multi-allelic variants are ignored, since we assume they have already been split, e.g. with VcfBreakMulti."
<< "Complex variants that are decomposed, are flagged with a BBC (before break-complex) info entry.");
addInfile("in", "Input VCF file. If unset, reads from STDIN.", true, true);
addOutfile("out", "Output VCF list. If unset, writes to STDOUT.", true, true);
addOutfile("stats", "Ouptuts statistics. If unset, writes to STDERR.", true, true);
addFlag("keep_mnps", "Write out MNPs unchanged.");
addFlag("no_tag", "Skip annotation of decomposed variants with BBC in INFO field.");
changeLog(2018, 11, 30, "Initial implementation.");
}
/**
* @brief main
* This program breaks complex variants into several lines. It is inspired by vt's decompose_suballelic and vcflib's vcfallelicprimitives.
* However this program will only deal with complex variants. It will not consinder multi-allelic variants.
* We use the classification procedure as described in the VT wiki here https://genome.sph.umich.edu/wiki/Variant_classification
* Local aligment of variants is done using Needleman-Wunsch as implemented in edlib. See https://doi.org/10.1093/bioinformatics/btw753
*/
virtual void main()
{
QString in = getInfile("in");
QString out = getOutfile("out");
QString stats = getOutfile("stats");
bool keep_mnps = getFlag("keep_mnps");
bool no_tag = getFlag("no_tag");
if(in!="" && in==out)
{
THROW(ArgumentException, "Input and output files must be different when streaming!");
}
if(stats!="" && stats==out)
{
THROW(ArgumentException, "Error and output files must be different when streaming!");
}
QSharedPointer<QFile> in_p = Helper::openFileForReading(in, true);
QSharedPointer<QFile> out_p = Helper::openFileForWriting(out, true);
// Statistics
bool inserted_info = false;
unsigned int number_of_additional_snps = 0;
unsigned int number_of_biallelic_block_substitutions = 0;
unsigned int number_of_new_variants = 0;
unsigned int number_of_variants = 0;
using Aligment = tuple<QByteArray, QByteArray, int>; // Describes an aligment of REF, ALT, OFFSET
while(!in_p->atEnd())
{
QByteArray line = in_p->readLine();
// Skip empty lines and headers
if (line.trimmed().isEmpty() || line.startsWith("#"))
{
out_p->write(line);
if (!inserted_info) // Insert right after version line
{
if (!no_tag) out_p->write("##INFO=<ID=BBC,Number=1,Type=String,Description=\"Original chr:pos:ref|alt encoding\">\n");
inserted_info = true;
}
continue;
}
// Not a header line so increment the variant
++number_of_variants;
QByteArray ref = VcfFile::getPartByColumn(line, VcfFile::REF).trimmed();
QByteArray alt = VcfFile::getPartByColumn(line, VcfFile::ALT).trimmed();
int pos = VcfFile::getPartByColumn(line, VcfFile::POS).trimmed().toInt();
// Skip alternating allele pairs
if (alt.contains(","))
{
out_p->write(line);
continue;
}
VariantType variant_type = VcfFile::classifyVariant(ref, alt);
if (variant_type != SNP) // Align with Needleman-Wunsch
{
auto nw = NeedlemanWunsch<QByteArray>(ref, alt);
nw.compute_matrix();
nw.trace_back();
auto aligment = nw.get_aligments();
auto reference = get<ALIGMENT_REFERENCE>(aligment), query = get<ALIGMENT_QUERY>(aligment);
// Iterate through the reference and compare it with the query
vector<Aligment> aligments;
if (ref.length() == 1 || alt.length() == 1) // SNP
{
aligments.push_back(Aligment(query.replace("-", ""), reference.replace("-", ""), 0));
++number_of_additional_snps;
}
else // MNP or CLUMPED
{
if (keep_mnps) // Keep more complex variants
{
out_p->write(line);
}
else // Break up clumped variants
{
while (query.startsWith("-")) // Kill leading gaps
{
query = query.remove(0, 1);
}
for (auto i = 0; i < query.size(); ++i)
{
if (i + 1 < query.size() && query.at(i + 1) == '-') // transition from REF,- to ALT
{
int gap_start = static_cast<int> (i + 1);
int gap_end = gap_start;
while ((i + 1) < query.size() && query.at(i + 1) == '-')
{
++i;
gap_end++;
}
aligments.push_back(Aligment(query.mid(gap_start - 1, 1), reference.mid(gap_start - 1, gap_end).replace("-", ""), gap_start));
++number_of_biallelic_block_substitutions; // new biallelic block substitutios
}
else if (i + 1 < reference.size() && reference.at(i + 1) == '-') // do the same for the reference
{
int gap_start = static_cast<int> (i +1);
int gap_end = gap_start;
while ((i + 1) < reference.size() && reference.at(i + 1) == '-')
{
++i;
++gap_end;
}
aligments.push_back(Aligment(query.mid(gap_start - 1, 2), reference.mid(gap_start - 1, gap_end).replace("-", ""), gap_start));
++number_of_biallelic_block_substitutions; // new biallelic block substitutios
}
else if (reference.at(i) == '-') {
int gap_start = static_cast<int> (i);
int gap_end = gap_start;
while ((i + 1) < reference.size() && reference.at(i) == '-')
{
++i;
++gap_end;
}
aligments.push_back(Aligment(query.mid(gap_start, gap_end - gap_start), reference.mid(gap_end, 1), gap_start));
++number_of_biallelic_block_substitutions;
}
else if (query.at(i) != reference.at(i)) // transition from REF -> ALT
{
aligments.push_back(Aligment(query.mid(i, 1), reference.mid(i, 1), i));
++i;
++number_of_additional_snps;
}
}
}
}
for (size_t i = 0; i < aligments.size(); ++i) // write out the new sequences
{
if (i > 0) ++number_of_new_variants;
auto parts = line.split('\t');
// Append INFO entry in format BBC=chr:pos:ref:alt
if (!no_tag) parts[VcfFile::INFO] = parts[VcfFile::INFO].trimmed() + ";BBC=" + parts[VcfFile::CHROM] + ":" + parts[VcfFile::POS] + ":" + parts[VcfFile::REF] + "|" + parts[VcfFile::ALT];
// Modify alt and ref with new aligments
parts[VcfFile::REF] = get<0>(aligments[i]);
parts[VcfFile::ALT] = get<1>(aligments[i]);
parts[VcfFile::POS] = QByteArray::number(pos + get<2>(aligments[i]));
// Write to output
out_p->write(parts.join("\t"));
}
}
else // We don't look at SNP's
{
out_p->write(line);
}
}
// After processing print statistics to error stream
QSharedPointer<QFile> stats_p = QSharedPointer<QFile>(new QFile(stats));
stats_p->open(stderr, QFile::WriteOnly | QIODevice::Text);
double new_variants_in_percent = (number_of_variants>0) ? 100.0 * number_of_new_variants / number_of_variants : 0.0;
stats_p->write(QByteArray("Processed ") + QByteArray::number(number_of_variants) + " variant(s) of which " + QByteArray::number(number_of_new_variants) + " (" + QByteArray::number(new_variants_in_percent, 'f', 2) + "%) were decomposed.\n");
stats_p->write(QByteArray::number(number_of_additional_snps - number_of_new_variants) + " of these are additional SNPs and " + QByteArray::number(number_of_biallelic_block_substitutions - number_of_variants) + " of these are biallelic substitutions.\n");
}
};
#include "main.moc"
int main(int argc, char *argv[])
{
ConcreteTool tool(argc, argv);
return tool.execute();
}
<|endoftext|>
|
<commit_before>#include "musiclrccontainerforinline.h"
#include "musiclrcmanagerforinline.h"
#include "musiclrcartphotoupload.h"
#include "musiclrcfloatwidget.h"
#include <QVBoxLayout>
#include <QSettings>
#include <QPainter>
#include <QDesktopServices>
#include <QClipboard>
#include <QApplication>
MusicLrcContainerForInline::MusicLrcContainerForInline(QWidget *parent) :
MusicLrcContainer(parent)
{
m_vBoxLayout = new QVBoxLayout(this);
m_vBoxLayout->setMargin(0);
setLayout(m_vBoxLayout);
m_containerType = "INLINE";
for(int i=0; i<MIN_LRCCONTAIN_COUNT; ++i)
{
MusicLRCManager *w = new MusicLRCManagerForInline(this);
m_vBoxLayout->addWidget(w);
m_musicLrcContainer.append(w);
}
changeCurrentLrcColorOrigin();
m_currentLrcIndex = 0;
m_mouseMovedAt = QPoint(-1,-1);
m_mousePressedAt = QPoint(-1,-1);
m_mouseLeftPressed = false;
m_showArtBackground = true;
m_showInlineLrc = true;
for(int i=0; i<MIN_LRCCONTAIN_COUNT; ++i)
m_musicLrcContainer[i]->setText(".........");
m_musicLrcContainer[CURRENT_LRC_PAINT]->setText(tr("noCurrentSongPlay"));
m_lrcFloatWidget = new MusicLrcFloatWidget(this);
}
MusicLrcContainerForInline::~MusicLrcContainerForInline()
{
clearAllMusicLRCManager();
delete m_vBoxLayout;
delete m_lrcFloatWidget;
}
bool MusicLrcContainerForInline::transLrcFileToTime(const QString& lrcFileName)
{
static_cast<MusicLRCManagerForInline*>(m_musicLrcContainer[CURRENT_LRC_PAINT])->setUpdateLrc(false);
m_lrcContainer.clear();///Clear the original map
m_currentShowLrcContainer.clear();///Clear the original lrc
QFile file(m_currentLrcFileName = lrcFileName); ///Open the lyrics file
for(int i=0; i<MIN_LRCCONTAIN_COUNT; ++i)
m_musicLrcContainer[i]->setText(".........");
if(!file.open(QIODevice::ReadOnly))
{
m_musicLrcContainer[CURRENT_LRC_PAINT]->setText(tr("unFoundLrc"));
return false;
}
else
m_musicLrcContainer[CURRENT_LRC_PAINT]->setText(tr("noCurrentSongPlay"));
QString getAllText = QString(file.readAll());
file.close();
//The lyrics by line into the lyrics list
QStringList lines = getAllText.split("\n");
//This is the time the label format[00:05.54]
//Regular expressionsd {2} Said matching 2 numbers
QRegExp reg("\\[\\d{2}:\\d{2}\\.\\d{2}\\]");
foreach(QString oneLine, lines)
{
QString temp = oneLine;
temp.replace(reg,"");
/*Replace the regular expression matching in place with the empty
string, then we get the lyrics text,And then get all the time the
label in the current row, and separately with lyrics text into QMap
IndexIn () to return to the first matching position, if the return
is -1, said no match,Under normal circumstances, POS should be
followed is corresponding to the lyrics file
*/
int pos = reg.indexIn(oneLine, 0);
while(pos != -1)
{ //That match
QString cap = reg.cap(0);
//Return zeroth expression matching the content
//The time tag into the time value, in milliseconds
QRegExp regexp;
regexp.setPattern("\\d{2}(?=:)");
regexp.indexIn(cap);
int minute = regexp.cap(0).toInt();
regexp.setPattern("\\d{2}(?=\\.)");
regexp.indexIn(cap);
int second = regexp.cap(0).toInt();
regexp.setPattern("\\d{2}(?=\\])");
regexp.indexIn(cap);
int millisecond = regexp.cap(0).toInt();
qint64 totalTime = minute * 60000 + second * 1000 + millisecond * 10;
//Insert into lrcContainer
m_lrcContainer.insert(totalTime, temp);
pos += reg.matchedLength();
pos = reg.indexIn(oneLine, pos);//Matching all
}
}
//If the lrcContainer is empty
if (m_lrcContainer.isEmpty())
{
m_musicLrcContainer[CURRENT_LRC_PAINT]->setText(tr("lrcFileError"));
return false;
}
m_currentShowLrcContainer.clear();
m_currentLrcIndex = 0;
for(int i=0; i<MIN_LRCCONTAIN_COUNT/2; ++i)
m_currentShowLrcContainer<<".........";
if(m_lrcContainer.find(0) == m_lrcContainer.end())
m_lrcContainer.insert(0,".........");
MIntStringMapIt it(m_lrcContainer);
while(it.hasNext())
{
it.next();
m_currentShowLrcContainer.append(it.value());
}
for(int i=0; i<MIN_LRCCONTAIN_COUNT/2; ++i)
m_currentShowLrcContainer<<" ";
return true;
}
QString MusicLrcContainerForInline::text() const
{
return m_musicLrcContainer[CURRENT_LRC_PAINT]->text();
}
void MusicLrcContainerForInline::setMaskLinearGradientColor(QColor color)
{
m_musicLrcContainer[CURRENT_LRC_PAINT]->setMaskLinearGradientColor(color);
}
void MusicLrcContainerForInline::startTimerClock()
{
m_musicLrcContainer[CURRENT_LRC_PAINT]->startTimerClock();
}
void MusicLrcContainerForInline::stopLrcMask()
{
m_musicLrcContainer[CURRENT_LRC_PAINT]->stopLrcMask();
}
void MusicLrcContainerForInline::setSongSpeedAndSlow(qint64 time)
{
foreach(qint64 value, m_lrcContainer.keys())
{
if(time < value)
{
time = value;
break;
}
}
for(int i=0; i<m_currentShowLrcContainer.count(); ++i)
{
if(m_currentShowLrcContainer[i] == m_lrcContainer.value(time))
{
m_currentLrcIndex = i - 3;
break;
}
}
}
void MusicLrcContainerForInline::updateCurrentLrc(qint64 time)
{
if(!m_lrcContainer.isEmpty() &&
m_currentLrcIndex + MIN_LRCCONTAIN_COUNT <= m_currentShowLrcContainer.count())
{
for(int i=0; i<MIN_LRCCONTAIN_COUNT; ++i)
{
m_musicLrcContainer[i]->setText(m_currentShowLrcContainer[m_currentLrcIndex + i]);
}
++m_currentLrcIndex;
static_cast<MusicLRCManagerForInline*>(m_musicLrcContainer[CURRENT_LRC_PAINT])->setUpdateLrc(true);
m_musicLrcContainer[CURRENT_LRC_PAINT]->startLrcMask(time);
for(int i=1; i<= MIN_LRCCONTAIN_COUNT; ++i)
{
MusicLRCManagerForInline *w = static_cast<MusicLRCManagerForInline*>(m_musicLrcContainer[i-1]);
if(i == 1 || i == 9)
{
w->setFontSize(3);
w->setTransparent(220);
}
if(i == 2 || i == 8)
{
w->setFontSize(2);
w->setTransparent(105);
}
if(i == 3 || i == 4 || i == 6 || i == 7)
{
w->setFontSize(1);
w->setTransparent(45);
}
}
}
}
void MusicLrcContainerForInline::setLrcSize(LrcSizeTable size)
{
if(size < 13 || size > 17)
{
qDebug()<<"set lrc size error!";
return;
}
for(int i=0; i<MIN_LRCCONTAIN_COUNT; ++i)
{
m_musicLrcContainer[i]->setLrcFontSize(size);
}
QSettings().setValue("LRCSIZECHOICED",size);
}
int MusicLrcContainerForInline::getLrcSize()
{
return QSettings().value("LRCSIZECHOICED").toInt();
}
void MusicLrcContainerForInline::paintEvent(QPaintEvent *)
{
QPainter painter(this);
QFont font;
painter.setFont(font);
painter.setPen(QColor(Qt::white));
painter.drawLine(0, m_mouseMovedAt.y(), width(), m_mouseMovedAt.y());
painter.end();
}
void MusicLrcContainerForInline::mouseMoveEvent(QMouseEvent *event)
{
if(m_mouseLeftPressed)
{
m_mouseMovedAt = event->pos();
update();
}
}
void MusicLrcContainerForInline::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
m_mouseLeftPressed = true;
setCursor(Qt::CrossCursor);
m_mouseMovedAt = m_mousePressedAt = event->pos();
update();
}
}
void MusicLrcContainerForInline::mouseReleaseEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
setCursor(Qt::ArrowCursor);
m_mouseLeftPressed = false;
changeLrcPostion("mouse");
m_mouseMovedAt = m_mousePressedAt = QPoint(-1,-1);
update();
}
}
void MusicLrcContainerForInline::wheelEvent(QWheelEvent *event)
{
MusicLrcContainer::wheelEvent(event);
changeLrcPostion(QString::number(event->delta()));
}
void MusicLrcContainerForInline::changeLrcPostion(const QString &type)
{
int level = m_currentLrcIndex;
if(type == "mouse")
m_currentLrcIndex += (m_mousePressedAt.y() - m_mouseMovedAt.y()) / 35;
else
type.toInt() < 0 ? --m_currentLrcIndex : ++m_currentLrcIndex;
if(m_currentLrcIndex < 0) m_currentLrcIndex = 0;
if(m_currentLrcIndex + MIN_LRCCONTAIN_COUNT < m_currentShowLrcContainer.count())
{
MIntStringMapIt it(m_lrcContainer);
for(int i=0; i<m_currentLrcIndex + 1; ++i)
if(it.hasNext()) it.next();
emit updateCurrentTime(it.key());
}
else
m_currentLrcIndex = level;
}
void MusicLrcContainerForInline::contextMenuEvent(QContextMenuEvent *)
{
QMenu menu(this);
QMenu changColorMenu(tr("changColorMenu"),this);
QMenu changeLrcSize(tr("changeLrcSize"),this);
changColorMenu.setStyleSheet(MusicObject::MusicSystemTrayMenu);
changeLrcSize.setStyleSheet(MusicObject::MusicSystemTrayMenu);
menu.setStyleSheet(MusicObject::MusicSystemTrayMenu);
menu.addAction(tr("searchLrcs"), this, SLOT(searchMusicLrcs()));
menu.addAction(tr("updateLrc"), this, SIGNAL(theCurrentLrcUpdated()));
menu.addSeparator();
menu.addMenu(&changColorMenu);
menu.addMenu(&changeLrcSize);
menu.addSeparator();
changeLrcSize.addAction(tr("smaller"),this,SLOT(changeLrcSizeSmaller()));
changeLrcSize.addAction(tr("small"),this,SLOT(changeLrcSizeSmall()));
changeLrcSize.addAction(tr("middle"),this,SLOT(changeLrcSizeMiddle()));
changeLrcSize.addAction(tr("big"),this,SLOT(changeLrcSizeBig()));
changeLrcSize.addAction(tr("bigger"),this,SLOT(changeLrcSizeBigger()));
changeLrcSize.addSeparator();
changeLrcSize.addAction(tr("custom"),this,SLOT(currentLrcCustom()));
createColorMenu(changColorMenu);
QAction *artBgAc = menu.addAction(tr("artbgoff"), this, SLOT(theArtBgChanged()));
m_showArtBackground ? artBgAc->setText(tr("artbgoff")) : artBgAc->setText(tr("artbgon")) ;
QAction *showLrc = menu.addAction(tr("lrcoff"), this, SLOT(theShowLrcChanged()));
m_showInlineLrc ? showLrc->setText(tr("lrcoff")) : showLrc->setText(tr("lrcon"));
menu.addAction(tr("artbgupload"), this, SLOT(theArtBgUploaded()));
menu.addSeparator();
bool fileCheck = !m_currentLrcFileName.isEmpty() && QFile::exists(m_currentLrcFileName);
QAction *copyToClipAc = menu.addAction(tr("copyToClip"),this,SLOT(lrcCopyClipboard()));
copyToClipAc->setEnabled( fileCheck );
QAction *showLrcFileAc = menu.addAction(tr("showLrcFile"),this,SLOT(lrcOpenFileDir()));
showLrcFileAc->setEnabled( fileCheck );
menu.addSeparator();
menu.addAction(tr("customSetting"),this,SLOT(currentLrcCustom()));
menu.exec(QCursor::pos());
}
void MusicLrcContainerForInline::theArtBgChanged()
{
m_showArtBackground = !m_showArtBackground;
emit theArtBgHasChanged();
}
void MusicLrcContainerForInline::theArtBgUploaded()
{
MusicLrcArtPhotoUpload artDialog(this);
artDialog.exec();
m_showArtBackground = true;
emit theArtBgHasChanged();
}
void MusicLrcContainerForInline::theShowLrcChanged()
{
m_showInlineLrc = !m_showInlineLrc;
foreach(MusicLRCManager *w, m_musicLrcContainer)
{
w->setVisible( m_showInlineLrc );
}
}
void MusicLrcContainerForInline::lrcOpenFileDir()
{
QDesktopServices::openUrl(QUrl(QFileInfo(m_currentLrcFileName).absolutePath(), QUrl::TolerantMode));
}
void MusicLrcContainerForInline::lrcCopyClipboard()
{
QClipboard *clipBoard = QApplication::clipboard();
QString clipString;
foreach(QString s, m_lrcContainer.values())
{
clipString.append(s);
}
clipBoard->setText(clipString);
}
<commit_msg>fix drag timer slider bar error[323212]<commit_after>#include "musiclrccontainerforinline.h"
#include "musiclrcmanagerforinline.h"
#include "musiclrcartphotoupload.h"
#include "musiclrcfloatwidget.h"
#include <QVBoxLayout>
#include <QSettings>
#include <QPainter>
#include <QDesktopServices>
#include <QClipboard>
#include <QApplication>
MusicLrcContainerForInline::MusicLrcContainerForInline(QWidget *parent) :
MusicLrcContainer(parent)
{
m_vBoxLayout = new QVBoxLayout(this);
m_vBoxLayout->setMargin(0);
setLayout(m_vBoxLayout);
m_containerType = "INLINE";
for(int i=0; i<MIN_LRCCONTAIN_COUNT; ++i)
{
MusicLRCManager *w = new MusicLRCManagerForInline(this);
m_vBoxLayout->addWidget(w);
m_musicLrcContainer.append(w);
}
changeCurrentLrcColorOrigin();
m_currentLrcIndex = 0;
m_mouseMovedAt = QPoint(-1,-1);
m_mousePressedAt = QPoint(-1,-1);
m_mouseLeftPressed = false;
m_showArtBackground = true;
m_showInlineLrc = true;
for(int i=0; i<MIN_LRCCONTAIN_COUNT; ++i)
m_musicLrcContainer[i]->setText(".........");
m_musicLrcContainer[CURRENT_LRC_PAINT]->setText(tr("noCurrentSongPlay"));
m_lrcFloatWidget = new MusicLrcFloatWidget(this);
}
MusicLrcContainerForInline::~MusicLrcContainerForInline()
{
clearAllMusicLRCManager();
delete m_vBoxLayout;
delete m_lrcFloatWidget;
}
bool MusicLrcContainerForInline::transLrcFileToTime(const QString& lrcFileName)
{
static_cast<MusicLRCManagerForInline*>(m_musicLrcContainer[CURRENT_LRC_PAINT])->setUpdateLrc(false);
m_lrcContainer.clear();///Clear the original map
m_currentShowLrcContainer.clear();///Clear the original lrc
QFile file(m_currentLrcFileName = lrcFileName); ///Open the lyrics file
for(int i=0; i<MIN_LRCCONTAIN_COUNT; ++i)
m_musicLrcContainer[i]->setText(".........");
if(!file.open(QIODevice::ReadOnly))
{
m_musicLrcContainer[CURRENT_LRC_PAINT]->setText(tr("unFoundLrc"));
return false;
}
else
m_musicLrcContainer[CURRENT_LRC_PAINT]->setText(tr("noCurrentSongPlay"));
QString getAllText = QString(file.readAll());
file.close();
//The lyrics by line into the lyrics list
QStringList lines = getAllText.split("\n");
//This is the time the label format[00:05.54]
//Regular expressionsd {2} Said matching 2 numbers
QRegExp reg("\\[\\d{2}:\\d{2}\\.\\d{2}\\]");
foreach(QString oneLine, lines)
{
QString temp = oneLine;
temp.replace(reg,"");
/*Replace the regular expression matching in place with the empty
string, then we get the lyrics text,And then get all the time the
label in the current row, and separately with lyrics text into QMap
IndexIn () to return to the first matching position, if the return
is -1, said no match,Under normal circumstances, POS should be
followed is corresponding to the lyrics file
*/
int pos = reg.indexIn(oneLine, 0);
while(pos != -1)
{ //That match
QString cap = reg.cap(0);
//Return zeroth expression matching the content
//The time tag into the time value, in milliseconds
QRegExp regexp;
regexp.setPattern("\\d{2}(?=:)");
regexp.indexIn(cap);
int minute = regexp.cap(0).toInt();
regexp.setPattern("\\d{2}(?=\\.)");
regexp.indexIn(cap);
int second = regexp.cap(0).toInt();
regexp.setPattern("\\d{2}(?=\\])");
regexp.indexIn(cap);
int millisecond = regexp.cap(0).toInt();
qint64 totalTime = minute * 60000 + second * 1000 + millisecond * 10;
//Insert into lrcContainer
m_lrcContainer.insert(totalTime, temp);
pos += reg.matchedLength();
pos = reg.indexIn(oneLine, pos);//Matching all
}
}
//If the lrcContainer is empty
if (m_lrcContainer.isEmpty())
{
m_musicLrcContainer[CURRENT_LRC_PAINT]->setText(tr("lrcFileError"));
return false;
}
m_currentShowLrcContainer.clear();
m_currentLrcIndex = 0;
for(int i=0; i<MIN_LRCCONTAIN_COUNT/2; ++i)
m_currentShowLrcContainer<<".........";
if(m_lrcContainer.find(0) == m_lrcContainer.end())
m_lrcContainer.insert(0,".........");
MIntStringMapIt it(m_lrcContainer);
while(it.hasNext())
{
it.next();
m_currentShowLrcContainer.append(it.value());
}
for(int i=0; i<MIN_LRCCONTAIN_COUNT/2; ++i)
m_currentShowLrcContainer<<" ";
return true;
}
QString MusicLrcContainerForInline::text() const
{
return m_musicLrcContainer[CURRENT_LRC_PAINT]->text();
}
void MusicLrcContainerForInline::setMaskLinearGradientColor(QColor color)
{
m_musicLrcContainer[CURRENT_LRC_PAINT]->setMaskLinearGradientColor(color);
}
void MusicLrcContainerForInline::startTimerClock()
{
m_musicLrcContainer[CURRENT_LRC_PAINT]->startTimerClock();
}
void MusicLrcContainerForInline::stopLrcMask()
{
m_musicLrcContainer[CURRENT_LRC_PAINT]->stopLrcMask();
}
void MusicLrcContainerForInline::setSongSpeedAndSlow(qint64 time)
{
foreach(qint64 value, m_lrcContainer.keys())
{
if(time < value)
{
time = value;
break;
}
}
for(int i=0; i<m_currentShowLrcContainer.count(); ++i)
{
if(m_currentShowLrcContainer[i] == m_lrcContainer.value(time))
{
m_currentLrcIndex = i - CURRENT_LRC_PAINT - 1;
break;
}
}
}
void MusicLrcContainerForInline::updateCurrentLrc(qint64 time)
{
if(!m_lrcContainer.isEmpty() &&
m_currentLrcIndex + MIN_LRCCONTAIN_COUNT <= m_currentShowLrcContainer.count())
{
for(int i=0; i<MIN_LRCCONTAIN_COUNT; ++i)
{
m_musicLrcContainer[i]->setText(m_currentShowLrcContainer[m_currentLrcIndex + i]);
}
++m_currentLrcIndex;
static_cast<MusicLRCManagerForInline*>(m_musicLrcContainer[CURRENT_LRC_PAINT])->setUpdateLrc(true);
m_musicLrcContainer[CURRENT_LRC_PAINT]->startLrcMask(time);
for(int i=1; i<= MIN_LRCCONTAIN_COUNT; ++i)
{
MusicLRCManagerForInline *w = static_cast<MusicLRCManagerForInline*>(m_musicLrcContainer[i-1]);
if(i == 1 || i == 9)
{
w->setFontSize(3);
w->setTransparent(220);
}
if(i == 2 || i == 8)
{
w->setFontSize(2);
w->setTransparent(105);
}
if(i == 3 || i == 4 || i == 6 || i == 7)
{
w->setFontSize(1);
w->setTransparent(45);
}
}
}
}
void MusicLrcContainerForInline::setLrcSize(LrcSizeTable size)
{
if(size < 13 || size > 17)
{
qDebug()<<"set lrc size error!";
return;
}
for(int i=0; i<MIN_LRCCONTAIN_COUNT; ++i)
{
m_musicLrcContainer[i]->setLrcFontSize(size);
}
QSettings().setValue("LRCSIZECHOICED",size);
}
int MusicLrcContainerForInline::getLrcSize()
{
return QSettings().value("LRCSIZECHOICED").toInt();
}
void MusicLrcContainerForInline::paintEvent(QPaintEvent *)
{
QPainter painter(this);
QFont font;
painter.setFont(font);
painter.setPen(QColor(Qt::white));
painter.drawLine(0, m_mouseMovedAt.y(), width(), m_mouseMovedAt.y());
painter.end();
}
void MusicLrcContainerForInline::mouseMoveEvent(QMouseEvent *event)
{
if(m_mouseLeftPressed)
{
m_mouseMovedAt = event->pos();
update();
}
}
void MusicLrcContainerForInline::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
m_mouseLeftPressed = true;
setCursor(Qt::CrossCursor);
m_mouseMovedAt = m_mousePressedAt = event->pos();
update();
}
}
void MusicLrcContainerForInline::mouseReleaseEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
setCursor(Qt::ArrowCursor);
m_mouseLeftPressed = false;
changeLrcPostion("mouse");
m_mouseMovedAt = m_mousePressedAt = QPoint(-1,-1);
update();
}
}
void MusicLrcContainerForInline::wheelEvent(QWheelEvent *event)
{
MusicLrcContainer::wheelEvent(event);
changeLrcPostion(QString::number(event->delta()));
}
void MusicLrcContainerForInline::changeLrcPostion(const QString &type)
{
int level = m_currentLrcIndex;
if(type == "mouse")
m_currentLrcIndex += (m_mousePressedAt.y() - m_mouseMovedAt.y()) / 35;
else
type.toInt() < 0 ? --m_currentLrcIndex : ++m_currentLrcIndex;
if(m_currentLrcIndex < 0) m_currentLrcIndex = 0;
if(m_currentLrcIndex + MIN_LRCCONTAIN_COUNT < m_currentShowLrcContainer.count())
{
MIntStringMapIt it(m_lrcContainer);
for(int i=0; i<m_currentLrcIndex + 1; ++i)
if(it.hasNext()) it.next();
emit updateCurrentTime(it.key());
}
else
m_currentLrcIndex = level;
}
void MusicLrcContainerForInline::contextMenuEvent(QContextMenuEvent *)
{
QMenu menu(this);
QMenu changColorMenu(tr("changColorMenu"),this);
QMenu changeLrcSize(tr("changeLrcSize"),this);
changColorMenu.setStyleSheet(MusicObject::MusicSystemTrayMenu);
changeLrcSize.setStyleSheet(MusicObject::MusicSystemTrayMenu);
menu.setStyleSheet(MusicObject::MusicSystemTrayMenu);
menu.addAction(tr("searchLrcs"), this, SLOT(searchMusicLrcs()));
menu.addAction(tr("updateLrc"), this, SIGNAL(theCurrentLrcUpdated()));
menu.addSeparator();
menu.addMenu(&changColorMenu);
menu.addMenu(&changeLrcSize);
menu.addSeparator();
changeLrcSize.addAction(tr("smaller"),this,SLOT(changeLrcSizeSmaller()));
changeLrcSize.addAction(tr("small"),this,SLOT(changeLrcSizeSmall()));
changeLrcSize.addAction(tr("middle"),this,SLOT(changeLrcSizeMiddle()));
changeLrcSize.addAction(tr("big"),this,SLOT(changeLrcSizeBig()));
changeLrcSize.addAction(tr("bigger"),this,SLOT(changeLrcSizeBigger()));
changeLrcSize.addSeparator();
changeLrcSize.addAction(tr("custom"),this,SLOT(currentLrcCustom()));
createColorMenu(changColorMenu);
QAction *artBgAc = menu.addAction(tr("artbgoff"), this, SLOT(theArtBgChanged()));
m_showArtBackground ? artBgAc->setText(tr("artbgoff")) : artBgAc->setText(tr("artbgon")) ;
QAction *showLrc = menu.addAction(tr("lrcoff"), this, SLOT(theShowLrcChanged()));
m_showInlineLrc ? showLrc->setText(tr("lrcoff")) : showLrc->setText(tr("lrcon"));
menu.addAction(tr("artbgupload"), this, SLOT(theArtBgUploaded()));
menu.addSeparator();
bool fileCheck = !m_currentLrcFileName.isEmpty() && QFile::exists(m_currentLrcFileName);
QAction *copyToClipAc = menu.addAction(tr("copyToClip"),this,SLOT(lrcCopyClipboard()));
copyToClipAc->setEnabled( fileCheck );
QAction *showLrcFileAc = menu.addAction(tr("showLrcFile"),this,SLOT(lrcOpenFileDir()));
showLrcFileAc->setEnabled( fileCheck );
menu.addSeparator();
menu.addAction(tr("customSetting"),this,SLOT(currentLrcCustom()));
menu.exec(QCursor::pos());
}
void MusicLrcContainerForInline::theArtBgChanged()
{
m_showArtBackground = !m_showArtBackground;
emit theArtBgHasChanged();
}
void MusicLrcContainerForInline::theArtBgUploaded()
{
MusicLrcArtPhotoUpload artDialog(this);
artDialog.exec();
m_showArtBackground = true;
emit theArtBgHasChanged();
}
void MusicLrcContainerForInline::theShowLrcChanged()
{
m_showInlineLrc = !m_showInlineLrc;
foreach(MusicLRCManager *w, m_musicLrcContainer)
{
w->setVisible( m_showInlineLrc );
}
}
void MusicLrcContainerForInline::lrcOpenFileDir()
{
QDesktopServices::openUrl(QUrl(QFileInfo(m_currentLrcFileName).absolutePath(), QUrl::TolerantMode));
}
void MusicLrcContainerForInline::lrcCopyClipboard()
{
QClipboard *clipBoard = QApplication::clipboard();
QString clipString;
foreach(QString s, m_lrcContainer.values())
{
clipString.append(s);
}
clipBoard->setText(clipString);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 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 "sandbox/win/src/sync_policy_test.h"
#include "base/win/scoped_handle.h"
#include "sandbox/win/src/sandbox.h"
#include "sandbox/win/src/sandbox_policy.h"
#include "sandbox/win/src/sandbox_factory.h"
#include "sandbox/win/src/nt_internals.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace sandbox {
SBOX_TESTS_COMMAND int Event_Open(int argc, wchar_t **argv) {
if (argc != 2)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
DWORD desired_access = SYNCHRONIZE;
if (L'f' == argv[0][0])
desired_access = EVENT_ALL_ACCESS;
base::win::ScopedHandle event_open(::OpenEvent(
desired_access, FALSE, argv[1]));
DWORD error_open = ::GetLastError();
if (event_open.IsValid())
return SBOX_TEST_SUCCEEDED;
if (ERROR_ACCESS_DENIED == error_open ||
ERROR_BAD_PATHNAME == error_open ||
ERROR_FILE_NOT_FOUND == error_open)
return SBOX_TEST_DENIED;
return SBOX_TEST_FAILED;
}
SBOX_TESTS_COMMAND int Event_CreateOpen(int argc, wchar_t **argv) {
if (argc < 2 || argc > 3)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
wchar_t *event_name = NULL;
if (3 == argc)
event_name = argv[2];
BOOL manual_reset = FALSE;
BOOL initial_state = FALSE;
if (L't' == argv[0][0])
manual_reset = TRUE;
if (L't' == argv[1][0])
initial_state = TRUE;
base::win::ScopedHandle event_create(::CreateEvent(
NULL, manual_reset, initial_state, event_name));
DWORD error_create = ::GetLastError();
base::win::ScopedHandle event_open;
if (event_name)
event_open.Set(::OpenEvent(EVENT_ALL_ACCESS, FALSE, event_name));
if (event_create.IsValid()) {
DWORD wait = ::WaitForSingleObject(event_create.Get(), 0);
if (initial_state && WAIT_OBJECT_0 != wait)
return SBOX_TEST_FAILED;
if (!initial_state && WAIT_TIMEOUT != wait)
return SBOX_TEST_FAILED;
}
if (event_name) {
// Both event_open and event_create have to be valid.
if (event_open.IsValid() && event_create.IsValid())
return SBOX_TEST_SUCCEEDED;
if ((event_open.IsValid() && !event_create.IsValid()) ||
(!event_open.IsValid() && event_create.IsValid())) {
return SBOX_TEST_FAILED;
}
} else {
// Only event_create has to be valid.
if (event_create.Get())
return SBOX_TEST_SUCCEEDED;
}
if (ERROR_ACCESS_DENIED == error_create ||
ERROR_BAD_PATHNAME == error_create)
return SBOX_TEST_DENIED;
return SBOX_TEST_FAILED;
}
// Tests the creation of events using all the possible combinations.
TEST(SyncPolicyTest, DISABLED_TestEvent) {
TestRunner runner;
EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,
TargetPolicy::EVENTS_ALLOW_ANY,
L"test1"));
EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,
TargetPolicy::EVENTS_ALLOW_ANY,
L"test2"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen f f"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen t f"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen f t"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen t t"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen f f test1"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen t f test2"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen f t test1"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen t t test2"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen f f test3"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen t f test4"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen f t test3"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen t t test4"));
}
// Tests opening events with read only access.
TEST(SyncPolicyTest, DISABLED_TestEventReadOnly) {
TestRunner runner;
EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,
TargetPolicy::EVENTS_ALLOW_READONLY,
L"test1"));
EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,
TargetPolicy::EVENTS_ALLOW_READONLY,
L"test2"));
EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,
TargetPolicy::EVENTS_ALLOW_READONLY,
L"test5"));
EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,
TargetPolicy::EVENTS_ALLOW_READONLY,
L"test6"));
base::win::ScopedHandle handle1(::CreateEvent(NULL, FALSE, FALSE, L"test1"));
base::win::ScopedHandle handle2(::CreateEvent(NULL, FALSE, FALSE, L"test2"));
base::win::ScopedHandle handle3(::CreateEvent(NULL, FALSE, FALSE, L"test3"));
base::win::ScopedHandle handle4(::CreateEvent(NULL, FALSE, FALSE, L"test4"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen f f"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen t f"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_Open f test1"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_Open s test2"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_Open f test3"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_Open s test4"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen f f test5"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen t f test6"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen f t test5"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen t t test6"));
}
} // namespace sandbox
<commit_msg>Sandbox: Reenable tests that were disabled "temporarily" 2 years ago.<commit_after>// Copyright (c) 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 "sandbox/win/src/sync_policy_test.h"
#include "base/win/scoped_handle.h"
#include "sandbox/win/src/sandbox.h"
#include "sandbox/win/src/sandbox_policy.h"
#include "sandbox/win/src/sandbox_factory.h"
#include "sandbox/win/src/nt_internals.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace sandbox {
SBOX_TESTS_COMMAND int Event_Open(int argc, wchar_t **argv) {
if (argc != 2)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
DWORD desired_access = SYNCHRONIZE;
if (L'f' == argv[0][0])
desired_access = EVENT_ALL_ACCESS;
base::win::ScopedHandle event_open(::OpenEvent(
desired_access, FALSE, argv[1]));
DWORD error_open = ::GetLastError();
if (event_open.IsValid())
return SBOX_TEST_SUCCEEDED;
if (ERROR_ACCESS_DENIED == error_open ||
ERROR_BAD_PATHNAME == error_open ||
ERROR_FILE_NOT_FOUND == error_open)
return SBOX_TEST_DENIED;
return SBOX_TEST_FAILED;
}
SBOX_TESTS_COMMAND int Event_CreateOpen(int argc, wchar_t **argv) {
if (argc < 2 || argc > 3)
return SBOX_TEST_FAILED_TO_EXECUTE_COMMAND;
wchar_t *event_name = NULL;
if (3 == argc)
event_name = argv[2];
BOOL manual_reset = FALSE;
BOOL initial_state = FALSE;
if (L't' == argv[0][0])
manual_reset = TRUE;
if (L't' == argv[1][0])
initial_state = TRUE;
base::win::ScopedHandle event_create(::CreateEvent(
NULL, manual_reset, initial_state, event_name));
DWORD error_create = ::GetLastError();
base::win::ScopedHandle event_open;
if (event_name)
event_open.Set(::OpenEvent(EVENT_ALL_ACCESS, FALSE, event_name));
if (event_create.IsValid()) {
DWORD wait = ::WaitForSingleObject(event_create.Get(), 0);
if (initial_state && WAIT_OBJECT_0 != wait)
return SBOX_TEST_FAILED;
if (!initial_state && WAIT_TIMEOUT != wait)
return SBOX_TEST_FAILED;
}
if (event_name) {
// Both event_open and event_create have to be valid.
if (event_open.IsValid() && event_create.IsValid())
return SBOX_TEST_SUCCEEDED;
if ((event_open.IsValid() && !event_create.IsValid()) ||
(!event_open.IsValid() && event_create.IsValid())) {
return SBOX_TEST_FAILED;
}
} else {
// Only event_create has to be valid.
if (event_create.Get())
return SBOX_TEST_SUCCEEDED;
}
if (ERROR_ACCESS_DENIED == error_create ||
ERROR_BAD_PATHNAME == error_create)
return SBOX_TEST_DENIED;
return SBOX_TEST_FAILED;
}
// Tests the creation of events using all the possible combinations.
TEST(SyncPolicyTest, TestEvent) {
TestRunner runner;
EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,
TargetPolicy::EVENTS_ALLOW_ANY,
L"test1"));
EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,
TargetPolicy::EVENTS_ALLOW_ANY,
L"test2"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen f f"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen t f"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen f t"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen t t"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen f f test1"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen t f test2"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen f t test1"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen t t test2"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen f f test3"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen t f test4"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen f t test3"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen t t test4"));
}
// Tests opening events with read only access.
TEST(SyncPolicyTest, TestEventReadOnly) {
TestRunner runner;
EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,
TargetPolicy::EVENTS_ALLOW_READONLY,
L"test1"));
EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,
TargetPolicy::EVENTS_ALLOW_READONLY,
L"test2"));
EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,
TargetPolicy::EVENTS_ALLOW_READONLY,
L"test5"));
EXPECT_TRUE(runner.AddRule(TargetPolicy::SUBSYS_SYNC,
TargetPolicy::EVENTS_ALLOW_READONLY,
L"test6"));
base::win::ScopedHandle handle1(::CreateEvent(NULL, FALSE, FALSE, L"test1"));
base::win::ScopedHandle handle2(::CreateEvent(NULL, FALSE, FALSE, L"test2"));
base::win::ScopedHandle handle3(::CreateEvent(NULL, FALSE, FALSE, L"test3"));
base::win::ScopedHandle handle4(::CreateEvent(NULL, FALSE, FALSE, L"test4"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen f f"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_CreateOpen t f"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_Open f test1"));
EXPECT_EQ(SBOX_TEST_SUCCEEDED, runner.RunTest(L"Event_Open s test2"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_Open f test3"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_Open s test4"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen f f test5"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen t f test6"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen f t test5"));
EXPECT_EQ(SBOX_TEST_DENIED, runner.RunTest(L"Event_CreateOpen t t test6"));
}
} // namespace sandbox
<|endoftext|>
|
<commit_before>/*
* Copyright 2004 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#if HAVE_OPENSSL_SSL_H
#include "webrtc/base/opensslidentity.h"
// Must be included first before openssl headers.
#include "webrtc/base/win32.h" // NOLINT
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/crypto.h>
#include "webrtc/base/checks.h"
#include "webrtc/base/helpers.h"
#include "webrtc/base/logging.h"
#include "webrtc/base/openssl.h"
#include "webrtc/base/openssldigest.h"
namespace rtc {
// We could have exposed a myriad of parameters for the crypto stuff,
// but keeping it simple seems best.
// Strength of generated keys. Those are RSA.
static const int KEY_LENGTH = 1024;
// Random bits for certificate serial number
static const int SERIAL_RAND_BITS = 64;
// Certificate validity lifetime
static const int CERTIFICATE_LIFETIME = 60*60*24*30; // 30 days, arbitrarily
// Certificate validity window.
// This is to compensate for slightly incorrect system clocks.
static const int CERTIFICATE_WINDOW = -60*60*24;
// Generate a key pair. Caller is responsible for freeing the returned object.
static EVP_PKEY* MakeKey() {
LOG(LS_INFO) << "Making key pair";
EVP_PKEY* pkey = EVP_PKEY_new();
// RSA_generate_key is deprecated. Use _ex version.
BIGNUM* exponent = BN_new();
RSA* rsa = RSA_new();
if (!pkey || !exponent || !rsa ||
!BN_set_word(exponent, 0x10001) || // 65537 RSA exponent
!RSA_generate_key_ex(rsa, KEY_LENGTH, exponent, NULL) ||
!EVP_PKEY_assign_RSA(pkey, rsa)) {
EVP_PKEY_free(pkey);
BN_free(exponent);
RSA_free(rsa);
return NULL;
}
// ownership of rsa struct was assigned, don't free it.
BN_free(exponent);
LOG(LS_INFO) << "Returning key pair";
return pkey;
}
// Generate a self-signed certificate, with the public key from the
// given key pair. Caller is responsible for freeing the returned object.
static X509* MakeCertificate(EVP_PKEY* pkey, const SSLIdentityParams& params) {
LOG(LS_INFO) << "Making certificate for " << params.common_name;
X509* x509 = NULL;
BIGNUM* serial_number = NULL;
X509_NAME* name = NULL;
if ((x509=X509_new()) == NULL)
goto error;
if (!X509_set_pubkey(x509, pkey))
goto error;
// serial number
// temporary reference to serial number inside x509 struct
ASN1_INTEGER* asn1_serial_number;
if ((serial_number = BN_new()) == NULL ||
!BN_pseudo_rand(serial_number, SERIAL_RAND_BITS, 0, 0) ||
(asn1_serial_number = X509_get_serialNumber(x509)) == NULL ||
!BN_to_ASN1_INTEGER(serial_number, asn1_serial_number))
goto error;
if (!X509_set_version(x509, 0L)) // version 1
goto error;
// There are a lot of possible components for the name entries. In
// our P2P SSL mode however, the certificates are pre-exchanged
// (through the secure XMPP channel), and so the certificate
// identification is arbitrary. It can't be empty, so we set some
// arbitrary common_name. Note that this certificate goes out in
// clear during SSL negotiation, so there may be a privacy issue in
// putting anything recognizable here.
if ((name = X509_NAME_new()) == NULL ||
!X509_NAME_add_entry_by_NID(
name, NID_commonName, MBSTRING_UTF8,
(unsigned char*)params.common_name.c_str(), -1, -1, 0) ||
!X509_set_subject_name(x509, name) ||
!X509_set_issuer_name(x509, name))
goto error;
if (!X509_gmtime_adj(X509_get_notBefore(x509), params.not_before) ||
!X509_gmtime_adj(X509_get_notAfter(x509), params.not_after))
goto error;
if (!X509_sign(x509, pkey, EVP_sha1()))
goto error;
BN_free(serial_number);
X509_NAME_free(name);
LOG(LS_INFO) << "Returning certificate";
return x509;
error:
BN_free(serial_number);
X509_NAME_free(name);
X509_free(x509);
return NULL;
}
// This dumps the SSL error stack to the log.
static void LogSSLErrors(const std::string& prefix) {
char error_buf[200];
unsigned long err;
while ((err = ERR_get_error()) != 0) {
ERR_error_string_n(err, error_buf, sizeof(error_buf));
LOG(LS_ERROR) << prefix << ": " << error_buf << "\n";
}
}
OpenSSLKeyPair* OpenSSLKeyPair::Generate() {
EVP_PKEY* pkey = MakeKey();
if (!pkey) {
LogSSLErrors("Generating key pair");
return NULL;
}
return new OpenSSLKeyPair(pkey);
}
OpenSSLKeyPair::~OpenSSLKeyPair() {
EVP_PKEY_free(pkey_);
}
OpenSSLKeyPair* OpenSSLKeyPair::GetReference() {
AddReference();
return new OpenSSLKeyPair(pkey_);
}
void OpenSSLKeyPair::AddReference() {
CRYPTO_add(&pkey_->references, 1, CRYPTO_LOCK_EVP_PKEY);
}
#ifdef _DEBUG
// Print a certificate to the log, for debugging.
static void PrintCert(X509* x509) {
BIO* temp_memory_bio = BIO_new(BIO_s_mem());
if (!temp_memory_bio) {
LOG_F(LS_ERROR) << "Failed to allocate temporary memory bio";
return;
}
X509_print_ex(temp_memory_bio, x509, XN_FLAG_SEP_CPLUS_SPC, 0);
BIO_write(temp_memory_bio, "\0", 1);
char* buffer;
BIO_get_mem_data(temp_memory_bio, &buffer);
LOG(LS_VERBOSE) << buffer;
BIO_free(temp_memory_bio);
}
#endif
OpenSSLCertificate* OpenSSLCertificate::Generate(
OpenSSLKeyPair* key_pair, const SSLIdentityParams& params) {
SSLIdentityParams actual_params(params);
if (actual_params.common_name.empty()) {
// Use a random string, arbitrarily 8chars long.
actual_params.common_name = CreateRandomString(8);
}
X509* x509 = MakeCertificate(key_pair->pkey(), actual_params);
if (!x509) {
LogSSLErrors("Generating certificate");
return NULL;
}
#ifdef _DEBUG
PrintCert(x509);
#endif
OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
X509_free(x509);
return ret;
}
OpenSSLCertificate* OpenSSLCertificate::FromPEMString(
const std::string& pem_string) {
BIO* bio = BIO_new_mem_buf(const_cast<char*>(pem_string.c_str()), -1);
if (!bio)
return NULL;
BIO_set_mem_eof_return(bio, 0);
X509 *x509 = PEM_read_bio_X509(bio, NULL, NULL,
const_cast<char*>("\0"));
BIO_free(bio); // Frees the BIO, but not the pointed-to string.
if (!x509)
return NULL;
OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
X509_free(x509);
return ret;
}
// NOTE: This implementation only functions correctly after InitializeSSL
// and before CleanupSSL.
bool OpenSSLCertificate::GetSignatureDigestAlgorithm(
std::string* algorithm) const {
return OpenSSLDigest::GetDigestName(
EVP_get_digestbyobj(x509_->sig_alg->algorithm), algorithm);
}
bool OpenSSLCertificate::GetChain(SSLCertChain** chain) const {
// Chains are not yet supported when using OpenSSL.
// OpenSSLStreamAdapter::SSLVerifyCallback currently requires the remote
// certificate to be self-signed.
return false;
}
bool OpenSSLCertificate::ComputeDigest(const std::string& algorithm,
unsigned char* digest,
size_t size,
size_t* length) const {
return ComputeDigest(x509_, algorithm, digest, size, length);
}
bool OpenSSLCertificate::ComputeDigest(const X509* x509,
const std::string& algorithm,
unsigned char* digest,
size_t size,
size_t* length) {
const EVP_MD *md;
unsigned int n;
if (!OpenSSLDigest::GetDigestEVP(algorithm, &md))
return false;
if (size < static_cast<size_t>(EVP_MD_size(md)))
return false;
X509_digest(x509, md, digest, &n);
*length = n;
return true;
}
OpenSSLCertificate::~OpenSSLCertificate() {
X509_free(x509_);
}
OpenSSLCertificate* OpenSSLCertificate::GetReference() const {
return new OpenSSLCertificate(x509_);
}
std::string OpenSSLCertificate::ToPEMString() const {
BIO* bio = BIO_new(BIO_s_mem());
if (!bio) {
FATAL() << "unreachable code";
}
if (!PEM_write_bio_X509(bio, x509_)) {
BIO_free(bio);
FATAL() << "unreachable code";
}
BIO_write(bio, "\0", 1);
char* buffer;
BIO_get_mem_data(bio, &buffer);
std::string ret(buffer);
BIO_free(bio);
return ret;
}
void OpenSSLCertificate::ToDER(Buffer* der_buffer) const {
// In case of failure, make sure to leave the buffer empty.
der_buffer->SetSize(0);
// Calculates the DER representation of the certificate, from scratch.
BIO* bio = BIO_new(BIO_s_mem());
if (!bio) {
FATAL() << "unreachable code";
}
if (!i2d_X509_bio(bio, x509_)) {
BIO_free(bio);
FATAL() << "unreachable code";
}
char* data;
size_t length = BIO_get_mem_data(bio, &data);
der_buffer->SetData(data, length);
BIO_free(bio);
}
void OpenSSLCertificate::AddReference() const {
ASSERT(x509_ != NULL);
CRYPTO_add(&x509_->references, 1, CRYPTO_LOCK_X509);
}
OpenSSLIdentity::OpenSSLIdentity(OpenSSLKeyPair* key_pair,
OpenSSLCertificate* certificate)
: key_pair_(key_pair), certificate_(certificate) {
ASSERT(key_pair != NULL);
ASSERT(certificate != NULL);
}
OpenSSLIdentity::~OpenSSLIdentity() = default;
OpenSSLIdentity* OpenSSLIdentity::GenerateInternal(
const SSLIdentityParams& params) {
OpenSSLKeyPair *key_pair = OpenSSLKeyPair::Generate();
if (key_pair) {
OpenSSLCertificate *certificate = OpenSSLCertificate::Generate(
key_pair, params);
if (certificate)
return new OpenSSLIdentity(key_pair, certificate);
delete key_pair;
}
LOG(LS_INFO) << "Identity generation failed";
return NULL;
}
OpenSSLIdentity* OpenSSLIdentity::Generate(const std::string& common_name) {
SSLIdentityParams params;
params.common_name = common_name;
params.not_before = CERTIFICATE_WINDOW;
params.not_after = CERTIFICATE_LIFETIME;
return GenerateInternal(params);
}
OpenSSLIdentity* OpenSSLIdentity::GenerateForTest(
const SSLIdentityParams& params) {
return GenerateInternal(params);
}
SSLIdentity* OpenSSLIdentity::FromPEMStrings(
const std::string& private_key,
const std::string& certificate) {
scoped_ptr<OpenSSLCertificate> cert(
OpenSSLCertificate::FromPEMString(certificate));
if (!cert) {
LOG(LS_ERROR) << "Failed to create OpenSSLCertificate from PEM string.";
return NULL;
}
BIO* bio = BIO_new_mem_buf(const_cast<char*>(private_key.c_str()), -1);
if (!bio) {
LOG(LS_ERROR) << "Failed to create a new BIO buffer.";
return NULL;
}
BIO_set_mem_eof_return(bio, 0);
EVP_PKEY *pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL,
const_cast<char*>("\0"));
BIO_free(bio); // Frees the BIO, but not the pointed-to string.
if (!pkey) {
LOG(LS_ERROR) << "Failed to create the private key from PEM string.";
return NULL;
}
return new OpenSSLIdentity(new OpenSSLKeyPair(pkey),
cert.release());
}
const OpenSSLCertificate& OpenSSLIdentity::certificate() const {
return *certificate_;
}
OpenSSLIdentity* OpenSSLIdentity::GetReference() const {
return new OpenSSLIdentity(key_pair_->GetReference(),
certificate_->GetReference());
}
bool OpenSSLIdentity::ConfigureIdentity(SSL_CTX* ctx) {
// 1 is the documented success return code.
if (SSL_CTX_use_certificate(ctx, certificate_->x509()) != 1 ||
SSL_CTX_use_PrivateKey(ctx, key_pair_->pkey()) != 1) {
LogSSLErrors("Configuring key and certificate");
return false;
}
return true;
}
} // namespace rtc
#endif // HAVE_OPENSSL_SSL_H
<commit_msg>Fix GetSignatureDigestAlgorithm for openssl to prepare for EC key switch.<commit_after>/*
* Copyright 2004 The WebRTC Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#if HAVE_OPENSSL_SSL_H
#include "webrtc/base/opensslidentity.h"
// Must be included first before openssl headers.
#include "webrtc/base/win32.h" // NOLINT
#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/crypto.h>
#include "webrtc/base/checks.h"
#include "webrtc/base/helpers.h"
#include "webrtc/base/logging.h"
#include "webrtc/base/openssl.h"
#include "webrtc/base/openssldigest.h"
namespace rtc {
// We could have exposed a myriad of parameters for the crypto stuff,
// but keeping it simple seems best.
// Strength of generated keys. Those are RSA.
static const int KEY_LENGTH = 1024;
// Random bits for certificate serial number
static const int SERIAL_RAND_BITS = 64;
// Certificate validity lifetime
static const int CERTIFICATE_LIFETIME = 60*60*24*30; // 30 days, arbitrarily
// Certificate validity window.
// This is to compensate for slightly incorrect system clocks.
static const int CERTIFICATE_WINDOW = -60*60*24;
// Generate a key pair. Caller is responsible for freeing the returned object.
static EVP_PKEY* MakeKey() {
LOG(LS_INFO) << "Making key pair";
EVP_PKEY* pkey = EVP_PKEY_new();
// RSA_generate_key is deprecated. Use _ex version.
BIGNUM* exponent = BN_new();
RSA* rsa = RSA_new();
if (!pkey || !exponent || !rsa ||
!BN_set_word(exponent, 0x10001) || // 65537 RSA exponent
!RSA_generate_key_ex(rsa, KEY_LENGTH, exponent, NULL) ||
!EVP_PKEY_assign_RSA(pkey, rsa)) {
EVP_PKEY_free(pkey);
BN_free(exponent);
RSA_free(rsa);
return NULL;
}
// ownership of rsa struct was assigned, don't free it.
BN_free(exponent);
LOG(LS_INFO) << "Returning key pair";
return pkey;
}
// Generate a self-signed certificate, with the public key from the
// given key pair. Caller is responsible for freeing the returned object.
static X509* MakeCertificate(EVP_PKEY* pkey, const SSLIdentityParams& params) {
LOG(LS_INFO) << "Making certificate for " << params.common_name;
X509* x509 = NULL;
BIGNUM* serial_number = NULL;
X509_NAME* name = NULL;
if ((x509=X509_new()) == NULL)
goto error;
if (!X509_set_pubkey(x509, pkey))
goto error;
// serial number
// temporary reference to serial number inside x509 struct
ASN1_INTEGER* asn1_serial_number;
if ((serial_number = BN_new()) == NULL ||
!BN_pseudo_rand(serial_number, SERIAL_RAND_BITS, 0, 0) ||
(asn1_serial_number = X509_get_serialNumber(x509)) == NULL ||
!BN_to_ASN1_INTEGER(serial_number, asn1_serial_number))
goto error;
if (!X509_set_version(x509, 0L)) // version 1
goto error;
// There are a lot of possible components for the name entries. In
// our P2P SSL mode however, the certificates are pre-exchanged
// (through the secure XMPP channel), and so the certificate
// identification is arbitrary. It can't be empty, so we set some
// arbitrary common_name. Note that this certificate goes out in
// clear during SSL negotiation, so there may be a privacy issue in
// putting anything recognizable here.
if ((name = X509_NAME_new()) == NULL ||
!X509_NAME_add_entry_by_NID(
name, NID_commonName, MBSTRING_UTF8,
(unsigned char*)params.common_name.c_str(), -1, -1, 0) ||
!X509_set_subject_name(x509, name) ||
!X509_set_issuer_name(x509, name))
goto error;
if (!X509_gmtime_adj(X509_get_notBefore(x509), params.not_before) ||
!X509_gmtime_adj(X509_get_notAfter(x509), params.not_after))
goto error;
if (!X509_sign(x509, pkey, EVP_sha1()))
goto error;
BN_free(serial_number);
X509_NAME_free(name);
LOG(LS_INFO) << "Returning certificate";
return x509;
error:
BN_free(serial_number);
X509_NAME_free(name);
X509_free(x509);
return NULL;
}
// This dumps the SSL error stack to the log.
static void LogSSLErrors(const std::string& prefix) {
char error_buf[200];
unsigned long err;
while ((err = ERR_get_error()) != 0) {
ERR_error_string_n(err, error_buf, sizeof(error_buf));
LOG(LS_ERROR) << prefix << ": " << error_buf << "\n";
}
}
OpenSSLKeyPair* OpenSSLKeyPair::Generate() {
EVP_PKEY* pkey = MakeKey();
if (!pkey) {
LogSSLErrors("Generating key pair");
return NULL;
}
return new OpenSSLKeyPair(pkey);
}
OpenSSLKeyPair::~OpenSSLKeyPair() {
EVP_PKEY_free(pkey_);
}
OpenSSLKeyPair* OpenSSLKeyPair::GetReference() {
AddReference();
return new OpenSSLKeyPair(pkey_);
}
void OpenSSLKeyPair::AddReference() {
CRYPTO_add(&pkey_->references, 1, CRYPTO_LOCK_EVP_PKEY);
}
#ifdef _DEBUG
// Print a certificate to the log, for debugging.
static void PrintCert(X509* x509) {
BIO* temp_memory_bio = BIO_new(BIO_s_mem());
if (!temp_memory_bio) {
LOG_F(LS_ERROR) << "Failed to allocate temporary memory bio";
return;
}
X509_print_ex(temp_memory_bio, x509, XN_FLAG_SEP_CPLUS_SPC, 0);
BIO_write(temp_memory_bio, "\0", 1);
char* buffer;
BIO_get_mem_data(temp_memory_bio, &buffer);
LOG(LS_VERBOSE) << buffer;
BIO_free(temp_memory_bio);
}
#endif
OpenSSLCertificate* OpenSSLCertificate::Generate(
OpenSSLKeyPair* key_pair, const SSLIdentityParams& params) {
SSLIdentityParams actual_params(params);
if (actual_params.common_name.empty()) {
// Use a random string, arbitrarily 8chars long.
actual_params.common_name = CreateRandomString(8);
}
X509* x509 = MakeCertificate(key_pair->pkey(), actual_params);
if (!x509) {
LogSSLErrors("Generating certificate");
return NULL;
}
#ifdef _DEBUG
PrintCert(x509);
#endif
OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
X509_free(x509);
return ret;
}
OpenSSLCertificate* OpenSSLCertificate::FromPEMString(
const std::string& pem_string) {
BIO* bio = BIO_new_mem_buf(const_cast<char*>(pem_string.c_str()), -1);
if (!bio)
return NULL;
BIO_set_mem_eof_return(bio, 0);
X509 *x509 = PEM_read_bio_X509(bio, NULL, NULL,
const_cast<char*>("\0"));
BIO_free(bio); // Frees the BIO, but not the pointed-to string.
if (!x509)
return NULL;
OpenSSLCertificate* ret = new OpenSSLCertificate(x509);
X509_free(x509);
return ret;
}
// NOTE: This implementation only functions correctly after InitializeSSL
// and before CleanupSSL.
bool OpenSSLCertificate::GetSignatureDigestAlgorithm(
std::string* algorithm) const {
int nid = OBJ_obj2nid(x509_->sig_alg->algorithm);
switch (nid) {
case NID_md5WithRSA:
case NID_md5WithRSAEncryption:
*algorithm = DIGEST_MD5;
break;
case NID_ecdsa_with_SHA1:
case NID_dsaWithSHA1:
case NID_dsaWithSHA1_2:
case NID_sha1WithRSA:
case NID_sha1WithRSAEncryption:
*algorithm = DIGEST_SHA_1;
break;
case NID_ecdsa_with_SHA224:
case NID_sha224WithRSAEncryption:
case NID_dsa_with_SHA224:
*algorithm = DIGEST_SHA_224;
break;
case NID_ecdsa_with_SHA256:
case NID_sha256WithRSAEncryption:
case NID_dsa_with_SHA256:
*algorithm = DIGEST_SHA_256;
break;
case NID_ecdsa_with_SHA384:
case NID_sha384WithRSAEncryption:
*algorithm = DIGEST_SHA_384;
break;
case NID_ecdsa_with_SHA512:
case NID_sha512WithRSAEncryption:
*algorithm = DIGEST_SHA_512;
break;
default:
// Unknown algorithm. There are several unhandled options that are less
// common and more complex.
LOG(LS_ERROR) << "Unknown signature algorithm NID: " << nid;
algorithm->clear();
return false;
}
return true;
}
bool OpenSSLCertificate::GetChain(SSLCertChain** chain) const {
// Chains are not yet supported when using OpenSSL.
// OpenSSLStreamAdapter::SSLVerifyCallback currently requires the remote
// certificate to be self-signed.
return false;
}
bool OpenSSLCertificate::ComputeDigest(const std::string& algorithm,
unsigned char* digest,
size_t size,
size_t* length) const {
return ComputeDigest(x509_, algorithm, digest, size, length);
}
bool OpenSSLCertificate::ComputeDigest(const X509* x509,
const std::string& algorithm,
unsigned char* digest,
size_t size,
size_t* length) {
const EVP_MD *md;
unsigned int n;
if (!OpenSSLDigest::GetDigestEVP(algorithm, &md))
return false;
if (size < static_cast<size_t>(EVP_MD_size(md)))
return false;
X509_digest(x509, md, digest, &n);
*length = n;
return true;
}
OpenSSLCertificate::~OpenSSLCertificate() {
X509_free(x509_);
}
OpenSSLCertificate* OpenSSLCertificate::GetReference() const {
return new OpenSSLCertificate(x509_);
}
std::string OpenSSLCertificate::ToPEMString() const {
BIO* bio = BIO_new(BIO_s_mem());
if (!bio) {
FATAL() << "unreachable code";
}
if (!PEM_write_bio_X509(bio, x509_)) {
BIO_free(bio);
FATAL() << "unreachable code";
}
BIO_write(bio, "\0", 1);
char* buffer;
BIO_get_mem_data(bio, &buffer);
std::string ret(buffer);
BIO_free(bio);
return ret;
}
void OpenSSLCertificate::ToDER(Buffer* der_buffer) const {
// In case of failure, make sure to leave the buffer empty.
der_buffer->SetSize(0);
// Calculates the DER representation of the certificate, from scratch.
BIO* bio = BIO_new(BIO_s_mem());
if (!bio) {
FATAL() << "unreachable code";
}
if (!i2d_X509_bio(bio, x509_)) {
BIO_free(bio);
FATAL() << "unreachable code";
}
char* data;
size_t length = BIO_get_mem_data(bio, &data);
der_buffer->SetData(data, length);
BIO_free(bio);
}
void OpenSSLCertificate::AddReference() const {
ASSERT(x509_ != NULL);
CRYPTO_add(&x509_->references, 1, CRYPTO_LOCK_X509);
}
OpenSSLIdentity::OpenSSLIdentity(OpenSSLKeyPair* key_pair,
OpenSSLCertificate* certificate)
: key_pair_(key_pair), certificate_(certificate) {
ASSERT(key_pair != NULL);
ASSERT(certificate != NULL);
}
OpenSSLIdentity::~OpenSSLIdentity() = default;
OpenSSLIdentity* OpenSSLIdentity::GenerateInternal(
const SSLIdentityParams& params) {
OpenSSLKeyPair *key_pair = OpenSSLKeyPair::Generate();
if (key_pair) {
OpenSSLCertificate *certificate = OpenSSLCertificate::Generate(
key_pair, params);
if (certificate)
return new OpenSSLIdentity(key_pair, certificate);
delete key_pair;
}
LOG(LS_INFO) << "Identity generation failed";
return NULL;
}
OpenSSLIdentity* OpenSSLIdentity::Generate(const std::string& common_name) {
SSLIdentityParams params;
params.common_name = common_name;
params.not_before = CERTIFICATE_WINDOW;
params.not_after = CERTIFICATE_LIFETIME;
return GenerateInternal(params);
}
OpenSSLIdentity* OpenSSLIdentity::GenerateForTest(
const SSLIdentityParams& params) {
return GenerateInternal(params);
}
SSLIdentity* OpenSSLIdentity::FromPEMStrings(
const std::string& private_key,
const std::string& certificate) {
scoped_ptr<OpenSSLCertificate> cert(
OpenSSLCertificate::FromPEMString(certificate));
if (!cert) {
LOG(LS_ERROR) << "Failed to create OpenSSLCertificate from PEM string.";
return NULL;
}
BIO* bio = BIO_new_mem_buf(const_cast<char*>(private_key.c_str()), -1);
if (!bio) {
LOG(LS_ERROR) << "Failed to create a new BIO buffer.";
return NULL;
}
BIO_set_mem_eof_return(bio, 0);
EVP_PKEY *pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL,
const_cast<char*>("\0"));
BIO_free(bio); // Frees the BIO, but not the pointed-to string.
if (!pkey) {
LOG(LS_ERROR) << "Failed to create the private key from PEM string.";
return NULL;
}
return new OpenSSLIdentity(new OpenSSLKeyPair(pkey),
cert.release());
}
const OpenSSLCertificate& OpenSSLIdentity::certificate() const {
return *certificate_;
}
OpenSSLIdentity* OpenSSLIdentity::GetReference() const {
return new OpenSSLIdentity(key_pair_->GetReference(),
certificate_->GetReference());
}
bool OpenSSLIdentity::ConfigureIdentity(SSL_CTX* ctx) {
// 1 is the documented success return code.
if (SSL_CTX_use_certificate(ctx, certificate_->x509()) != 1 ||
SSL_CTX_use_PrivateKey(ctx, key_pair_->pkey()) != 1) {
LogSSLErrors("Configuring key and certificate");
return false;
}
return true;
}
} // namespace rtc
#endif // HAVE_OPENSSL_SSL_H
<|endoftext|>
|
<commit_before>/* Copyright 2016 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.
==============================================================================*/
#include "tensorflow/core/debug/debug_grpc_testlib.h"
#include "tensorflow/core/debug/debug_graph_utils.h"
#include "tensorflow/core/debug/debug_io_utils.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/tracing.h"
namespace tensorflow {
namespace test {
::grpc::Status TestEventListenerImpl::SendEvents(
::grpc::ServerContext* context,
::grpc::ServerReaderWriter< ::tensorflow::EventReply, ::tensorflow::Event>*
stream) {
Event event;
while (stream->Read(&event)) {
const Summary::Value& val = event.summary().value(0);
std::vector<string> name_items =
tensorflow::str_util::Split(val.node_name(), ':');
const string node_name = name_items[0];
int32 output_slot = 0;
tensorflow::strings::safe_strto32(name_items[1], &output_slot);
const string debug_op = name_items[2];
const TensorProto& tensor_proto = val.tensor();
Tensor tensor(tensor_proto.dtype());
if (!tensor.FromProto(tensor_proto)) {
return ::grpc::Status::CANCELLED;
}
string dump_path;
DebugFileIO::DumpTensorToDir(node_name, output_slot, debug_op, tensor,
event.wall_time(), dump_root, &dump_path)
.IgnoreError();
}
return ::grpc::Status::OK;
}
GrpcTestServerClientPair::GrpcTestServerClientPair(const int server_port)
: server_port(server_port) {
const int kTensorSize = 2;
prep_tensor_.reset(
new Tensor(DT_FLOAT, TensorShape({kTensorSize, kTensorSize})));
for (int i = 0; i < kTensorSize * kTensorSize; ++i) {
prep_tensor_->flat<float>()(i) = static_cast<float>(i);
}
// Obtain server's gRPC url.
test_server_url = strings::StrCat("grpc://[::]:", server_port);
// Obtain dump directory for the stream server.
string tmp_dir = port::Tracing::LogDir();
dump_root =
io::JoinPath(tmp_dir, strings::StrCat("tfdbg_dump_port", server_port, "_",
Env::Default()->NowMicros()));
}
bool GrpcTestServerClientPair::PollTillFirstRequestSucceeds() {
const std::vector<string> urls({test_server_url});
int n_attempts = 0;
bool success = false;
// Try a number of times to send the Event proto to the server, as it may
// take the server a few seconds to start up and become responsive.
while (n_attempts++ < kMaxAttempts) {
const uint64 wall_time = Env::Default()->NowMicros();
Status publish_s = DebugIO::PublishDebugTensor(
"prep_node:0", "DebugIdentity", *prep_tensor_, wall_time, urls);
Status close_s = DebugIO::CloseDebugURL(test_server_url);
if (publish_s.ok() && close_s.ok()) {
success = true;
break;
} else {
Env::Default()->SleepForMicroseconds(kSleepDurationMicros);
}
}
return success;
}
} // namespace test
} // namespace tensorflow
<commit_msg>Switch debug_grpc_testlib to bind on localhost<commit_after>/* Copyright 2016 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.
==============================================================================*/
#include "tensorflow/core/debug/debug_grpc_testlib.h"
#include "tensorflow/core/debug/debug_graph_utils.h"
#include "tensorflow/core/debug/debug_io_utils.h"
#include "tensorflow/core/lib/io/path.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/tracing.h"
namespace tensorflow {
namespace test {
::grpc::Status TestEventListenerImpl::SendEvents(
::grpc::ServerContext* context,
::grpc::ServerReaderWriter< ::tensorflow::EventReply, ::tensorflow::Event>*
stream) {
Event event;
while (stream->Read(&event)) {
const Summary::Value& val = event.summary().value(0);
std::vector<string> name_items =
tensorflow::str_util::Split(val.node_name(), ':');
const string node_name = name_items[0];
int32 output_slot = 0;
tensorflow::strings::safe_strto32(name_items[1], &output_slot);
const string debug_op = name_items[2];
const TensorProto& tensor_proto = val.tensor();
Tensor tensor(tensor_proto.dtype());
if (!tensor.FromProto(tensor_proto)) {
return ::grpc::Status::CANCELLED;
}
string dump_path;
DebugFileIO::DumpTensorToDir(node_name, output_slot, debug_op, tensor,
event.wall_time(), dump_root, &dump_path)
.IgnoreError();
}
return ::grpc::Status::OK;
}
GrpcTestServerClientPair::GrpcTestServerClientPair(const int server_port)
: server_port(server_port) {
const int kTensorSize = 2;
prep_tensor_.reset(
new Tensor(DT_FLOAT, TensorShape({kTensorSize, kTensorSize})));
for (int i = 0; i < kTensorSize * kTensorSize; ++i) {
prep_tensor_->flat<float>()(i) = static_cast<float>(i);
}
// Obtain server's gRPC url.
test_server_url = strings::StrCat("grpc://localhost:", server_port);
// Obtain dump directory for the stream server.
string tmp_dir = port::Tracing::LogDir();
dump_root =
io::JoinPath(tmp_dir, strings::StrCat("tfdbg_dump_port", server_port, "_",
Env::Default()->NowMicros()));
}
bool GrpcTestServerClientPair::PollTillFirstRequestSucceeds() {
const std::vector<string> urls({test_server_url});
int n_attempts = 0;
bool success = false;
// Try a number of times to send the Event proto to the server, as it may
// take the server a few seconds to start up and become responsive.
while (n_attempts++ < kMaxAttempts) {
const uint64 wall_time = Env::Default()->NowMicros();
Status publish_s = DebugIO::PublishDebugTensor(
"prep_node:0", "DebugIdentity", *prep_tensor_, wall_time, urls);
Status close_s = DebugIO::CloseDebugURL(test_server_url);
if (publish_s.ok() && close_s.ok()) {
success = true;
break;
} else {
Env::Default()->SleepForMicroseconds(kSleepDurationMicros);
}
}
return success;
}
} // namespace test
} // namespace tensorflow
<|endoftext|>
|
<commit_before>#include "game.h"
#define LOOKAHEAD 4
#define SACRIFICE_OPTIONS 5
#define OPPONENT_MOVES 5
using namespace std;
// globals
int sacrificeCombinations = factorial(SACRIFICE_OPTIONS) / (factorial(SACRIFICE_OPTIONS - 2) * factorial(2));
stringstream token;
char botId, opponentId;
char gameState[16][18];
int roundNum, timebank, myLiveCells, theirLiveCells;
// this just for logging time TODO: remove
auto t = chrono::steady_clock::now();
void game()
{
string line, command;
while (getline(cin, line))
{
token.clear();
token.str(line);
token >> command;
if (command == "action")
processAction();
if (command == "update")
processUpdate();
if (command == "settings")
processSettings();
}
}
void processAction()
{
string type, time;
token >> type;
token >> time;
if (type == "move") {
t = chrono::steady_clock::now(); // TODO: remove
timebank = stoi(time);
makeMove();
chrono::duration<double> diff = chrono::steady_clock::now() - t; // TODO: remove
cerr << diff.count() * 1000 << "ms used\n"; // TODO: remove
} else
cerr << "action type: " << type << " not expected\n";
}
void processUpdate()
{
string target, field, value;
token >> target;
token >> field;
token >> value;
if (target == "game") {
if (field == "round") {
roundNum = stoi(value);
}
if (field == "field") {
parseState(value);
}
} else if (target == "player0" or target == "player1") {
if (field == "living_cells") {
if (target[6] == botId)
myLiveCells = stoi(value);
else
theirLiveCells = stoi(value);
} else if (field != "move")
cerr << "update playerX field: " << field << " not expected\n";
} else
cerr << "update target: " << target << " not expected\n";
}
void processSettings()
{
string field, value;
token >> field;
token >> value;
if (field == "player_names") {
if (value != "player0,player1")
cerr << "settings player_names value: " << value << " not expected\n";
} else if (field == "your_bot") {
if (value != "player0" and value != "player1")
cerr << "settings your_bot value: " << value << " not expected\n";
} else if (field == "timebank") {
if (value == "10000")
timebank = stoi(value);
else
cerr << "settings timebank value: " << value << " not expected\n";
} else if (field == "time_per_move") {
if (value != "100")
cerr << "settings time_per_move value: " << value << " not expected\n";
} else if (field == "field_width") {
if (value != "18")
cerr << "settings field_width value: " << value << " not expected\n";
} else if (field == "field_height") {
if (value != "16")
cerr << "settings field_height value: " << value << " not expected\n";
} else if (field == "max_rounds") {
if (value != "100")
cerr << "settings max_rounds value: " << value << " not expected\n";
} else if (field == "your_botid") {
if (value == "0") {
botId = '0';
opponentId = '1';
} else if (value == "1") {
botId = '1';
opponentId = '0';
}
else
cerr << "settings your_botid value: " << value << " not expected\n";
} else
cerr << "settings field: " << field << " not expected\n";
}
void parseState(const string &value)
{
int row = 0;
int col = 0;
for (const char& c : value) {
if (c != ',') {
gameState[row][col] = c;
if (col == 17) {
col = 0;
row++;
} else {
col++;
}
}
}
}
void makeMove()
{
int numMoves = 1 + (myLiveCells + theirLiveCells) + (sacrificeCombinations * (288 - myLiveCells - theirLiveCells));
// TODO: handle less then n of my cells alive for birthing calcs
node nodes[numMoves];
addKillNodes(nodes);
node bestKillNodes[SACRIFICE_OPTIONS];
findBestKillNodes(nodes, bestKillNodes);
addPassNode(nodes);
addBirthNodes(nodes, bestKillNodes);
// TODO: for the best n nodes, calculate opponent moves and recalculate heuristic, then pick the best of those
// sort then slice, then 2nd round heuristic, then sort then first
sort(nodes, nodes + numMoves, nodeCompare);
// node bestNode = findBestNode(nodes, numMoves);
node bestNode = nodes[0];
sendMove(bestNode);
}
void addKillNodes(node nodes[], const char state[][18])
{
int i = 0;
for (int c = 0; c < 18; c++) {
for (int r = 0; r < 16; r++) {
if (state[r][c] != '.') {
node n;
n.value = state[r][c];
n.type = 'k';
n.target = r * 18 + c;
copyState(n.state);
n.state[r][c] = '.';
calculateNextState(n);
calculateHeuristic(n);
nodes[i++] = n;
}
}
}
}
void findBestKillNodes(node nodes[], node bestKillNodes[])
{
sort(nodes, nodes + myLiveCells + theirLiveCells, nodeCompare);
int killNodeCount = 0;
for (int i = 0; i < myLiveCells + theirLiveCells; i++) {
node n = nodes[i];
if (n.value == botId) {
bestKillNodes[killNodeCount] = n;
killNodeCount++;
if (killNodeCount == SACRIFICE_OPTIONS) {
break;
}
}
}
}
void addPassNode(node nodes[], char state[][18], int idx)
{
node n;
n.type = 'p';
copyState(n.state);
calculateNextState(n);
calculateHeuristic(n);
nodes[idx] = n;
}
void addBirthNodes(node nodes[], char state[][18], const node bestKillNodes[], int idx)
{
for (int x = 0; x < SACRIFICE_OPTIONS - 1; x++) {
for (int y = x + 1; y < SACRIFICE_OPTIONS; y++) {
for (int c = 0; c < 18; c++) {
for (int r = 0; r < 16; r++) {
if (state[r][c] == '.') {
node n;
n.type = 'b';
n.target = r * 18 + c;
n.sacrifice1 = bestKillNodes[x].target;
n.sacrifice2 = bestKillNodes[y].target;
copyState(n.state);
n.state[r][c] = botId;
n.state[n.sacrifice1 / 18][n.sacrifice1 % 18] = '.';
n.state[n.sacrifice2 / 18][n.sacrifice2 % 18] = '.';
calculateNextState(n);
calculateHeuristic(n);
nodes[idx++] = n;
}
}
}
}
}
}
node findBestNode(const node nodes[], int nodeCount)
{
int topHeuristic = -288;
int topHeuristicIdx = 0;
for (int i = 0; i < nodeCount; i++) {
if (nodes[i].heuristicValue > topHeuristic) {
topHeuristic = nodes[topHeuristicIdx].heuristicValue;
topHeuristicIdx = i;
}
}
return nodes[topHeuristicIdx];
}
void sendMove(const node &n)
{
if (n.type == 'p') {
cout << "pass\n";
} else if (n.type == 'k') {
cout << "kill " << coords(n.target) << "\n";
} else if (n.type == 'b') {
cout << "birth " << coords(n.target) << " " << coords(n.sacrifice1) << " " << coords(n.sacrifice2) << "\n";
}
}
void calculateNextState(node &n, int lookahead)
{
for (int l = 0; l < lookahead; l++) {
int neighbours0[16][18];
int neighbours1[16][18];
for (int c = 0; c < 18; c++) {
for (int r = 0; r < 16; r++) {
neighbours0[r][c] = 0;
neighbours1[r][c] = 0;
}
}
for (int c = 0; c < 18; c++) {
for (int r = 0; r < 16; r++) {
if (n.state[r][c] == '0') {
if (c > 0) {
neighbours0[r][c - 1]++;
if (r > 0) neighbours0[r - 1][c - 1]++;
if (r < 15) neighbours0[r + 1][c - 1]++;
}
if (c < 17) {
neighbours0[r][c + 1]++;
if (r > 0) neighbours0[r - 1][c + 1]++;
if (r < 15) neighbours0[r + 1][c + 1]++;
}
if (r > 0) neighbours0[r - 1][c]++;
if (r < 15) neighbours0[r + 1][c]++;
}
if (n.state[r][c] == '1') {
if (c > 0) {
neighbours1[r][c - 1]++;
if (r > 0) neighbours1[r - 1][c - 1]++;
if (r < 15) neighbours1[r + 1][c - 1]++;
}
if (c < 17) {
neighbours1[r][c + 1]++;
if (r > 0) neighbours1[r - 1][c + 1]++;
if (r < 15) neighbours1[r + 1][c + 1]++;
}
if (r > 0) neighbours1[r - 1][c]++;
if (r < 15) neighbours1[r + 1][c]++;
}
}
}
int neighbours;
for (int c = 0; c < 18; c++) {
for (int r = 0; r < 16; r++) {
neighbours = neighbours0[r][c] + neighbours1[r][c];
if (n.state[r][c] == '.' and neighbours == 3) {
n.state[r][c] = (neighbours0[r][c] > neighbours1[r][c]) ? '0' : '1';
} else if (n.state[r][c] != '.' and (neighbours < 2 or neighbours > 3)) {
n.state[r][c] = '.';
}
}
}
}
}
void calculateHeuristic(node &n)
{
int cellCount0 = 0;
int cellCount1 = 0;
// TODO: consider the number of opponent cells alive to increase aggression when they are low
for (int c = 0; c < 18; c++) {
for (int r = 0; r < 16; r++) {
if (n.state[r][c] == '0') {
cellCount0++;
} else if (n.state[r][c] == '1') {
cellCount1++;
}
}
}
if (botId == '0') {
if (cellCount0 == 0) {
n.heuristicValue = -288;
} else if (cellCount1 == 0) {
n.heuristicValue = 288;
} else {
n.heuristicValue = cellCount0 - cellCount1;
}
} else if (botId == '1') {
if (cellCount1 == 0) {
n.heuristicValue = -288;
} else if (cellCount0 == 0) {
n.heuristicValue = 288;
} else {
n.heuristicValue = cellCount1 - cellCount0;
}
}
}
// utility functions
int factorial(int x, int result) {
return (x == 1) ? result : factorial(x - 1, x * result);
}
string coords(int cellIdx)
{
stringstream ss;
ss << (cellIdx % 18) << "," << cellIdx / 18;
return ss.str();
}
void copyState(const char source[][18], char target[][18])
{
for (int r = 0; r < 16; r++) {
for (int c = 0; c < 18; c++) {
target[r][c] = source[r][c];
}
}
}
bool nodeCompare(node lhs, node rhs)
{
// sort descending
return lhs.heuristicValue > rhs.heuristicValue;
}
// debug functions
void setBotId(const char id)
{
botId = id;
}
<commit_msg>findBestKillNodes takes an id<commit_after>#include "game.h"
#define LOOKAHEAD 4
#define SACRIFICE_OPTIONS 5
#define OPPONENT_MOVES 5
using namespace std;
// globals
int sacrificeCombinations = factorial(SACRIFICE_OPTIONS) / (factorial(SACRIFICE_OPTIONS - 2) * factorial(2));
stringstream token;
char botId, opponentId;
char gameState[16][18];
int roundNum, timebank, myLiveCells, theirLiveCells;
// this just for logging time TODO: remove
auto t = chrono::steady_clock::now();
void game()
{
string line, command;
while (getline(cin, line))
{
token.clear();
token.str(line);
token >> command;
if (command == "action")
processAction();
if (command == "update")
processUpdate();
if (command == "settings")
processSettings();
}
}
void processAction()
{
string type, time;
token >> type;
token >> time;
if (type == "move") {
t = chrono::steady_clock::now(); // TODO: remove
timebank = stoi(time);
makeMove();
chrono::duration<double> diff = chrono::steady_clock::now() - t; // TODO: remove
cerr << diff.count() * 1000 << "ms used\n"; // TODO: remove
} else
cerr << "action type: " << type << " not expected\n";
}
void processUpdate()
{
string target, field, value;
token >> target;
token >> field;
token >> value;
if (target == "game") {
if (field == "round") {
roundNum = stoi(value);
}
if (field == "field") {
parseState(value);
}
} else if (target == "player0" or target == "player1") {
if (field == "living_cells") {
if (target[6] == botId)
myLiveCells = stoi(value);
else
theirLiveCells = stoi(value);
} else if (field != "move")
cerr << "update playerX field: " << field << " not expected\n";
} else
cerr << "update target: " << target << " not expected\n";
}
void processSettings()
{
string field, value;
token >> field;
token >> value;
if (field == "player_names") {
if (value != "player0,player1")
cerr << "settings player_names value: " << value << " not expected\n";
} else if (field == "your_bot") {
if (value != "player0" and value != "player1")
cerr << "settings your_bot value: " << value << " not expected\n";
} else if (field == "timebank") {
if (value == "10000")
timebank = stoi(value);
else
cerr << "settings timebank value: " << value << " not expected\n";
} else if (field == "time_per_move") {
if (value != "100")
cerr << "settings time_per_move value: " << value << " not expected\n";
} else if (field == "field_width") {
if (value != "18")
cerr << "settings field_width value: " << value << " not expected\n";
} else if (field == "field_height") {
if (value != "16")
cerr << "settings field_height value: " << value << " not expected\n";
} else if (field == "max_rounds") {
if (value != "100")
cerr << "settings max_rounds value: " << value << " not expected\n";
} else if (field == "your_botid") {
if (value == "0") {
botId = '0';
opponentId = '1';
} else if (value == "1") {
botId = '1';
opponentId = '0';
}
else
cerr << "settings your_botid value: " << value << " not expected\n";
} else
cerr << "settings field: " << field << " not expected\n";
}
void parseState(const string &value)
{
int row = 0;
int col = 0;
for (const char& c : value) {
if (c != ',') {
gameState[row][col] = c;
if (col == 17) {
col = 0;
row++;
} else {
col++;
}
}
}
}
void makeMove()
{
int numMoves = 1 + (myLiveCells + theirLiveCells) + (sacrificeCombinations * (288 - myLiveCells - theirLiveCells));
// TODO: handle less then n of my cells alive for birthing calcs
node nodes[numMoves];
addKillNodes(nodes);
node bestKillNodes[SACRIFICE_OPTIONS];
findBestKillNodes(nodes, bestKillNodes);
addPassNode(nodes);
addBirthNodes(nodes, bestKillNodes);
// TODO: for the best n nodes, calculate opponent moves and recalculate heuristic, then pick the best of those
// sort then slice, then 2nd round heuristic, then sort then first
sort(nodes, nodes + numMoves, nodeCompare);
// node bestNode = findBestNode(nodes, numMoves);
node bestNode = nodes[0];
sendMove(bestNode);
}
void addKillNodes(node nodes[], const char state[][18])
{
int i = 0;
for (int c = 0; c < 18; c++) {
for (int r = 0; r < 16; r++) {
if (state[r][c] != '.') {
node n;
n.value = state[r][c];
n.type = 'k';
n.target = r * 18 + c;
copyState(n.state);
n.state[r][c] = '.';
calculateNextState(n);
calculateHeuristic(n);
nodes[i++] = n;
}
}
}
}
void findBestKillNodes(node nodes[], char id, node bestKillNodes[])
{
int killNodeCount = 0;
for (int i = 0; i < myLiveCells + theirLiveCells; i++) {
node n = nodes[i];
if (n.value == id) {
bestKillNodes[killNodeCount] = n;
killNodeCount++;
if (killNodeCount == SACRIFICE_OPTIONS) {
break;
}
}
}
}
void addPassNode(node nodes[], char state[][18], int idx)
{
node n;
n.type = 'p';
copyState(n.state);
calculateNextState(n);
calculateHeuristic(n);
nodes[idx] = n;
}
void addBirthNodes(node nodes[], char state[][18], const node bestKillNodes[], int idx)
{
for (int x = 0; x < SACRIFICE_OPTIONS - 1; x++) {
for (int y = x + 1; y < SACRIFICE_OPTIONS; y++) {
for (int c = 0; c < 18; c++) {
for (int r = 0; r < 16; r++) {
if (state[r][c] == '.') {
node n;
n.type = 'b';
n.target = r * 18 + c;
n.sacrifice1 = bestKillNodes[x].target;
n.sacrifice2 = bestKillNodes[y].target;
copyState(n.state);
n.state[r][c] = botId;
n.state[n.sacrifice1 / 18][n.sacrifice1 % 18] = '.';
n.state[n.sacrifice2 / 18][n.sacrifice2 % 18] = '.';
calculateNextState(n);
calculateHeuristic(n);
nodes[idx++] = n;
}
}
}
}
}
}
node findBestNode(const node nodes[], int nodeCount)
{
int topHeuristic = -288;
int topHeuristicIdx = 0;
for (int i = 0; i < nodeCount; i++) {
if (nodes[i].heuristicValue > topHeuristic) {
topHeuristic = nodes[topHeuristicIdx].heuristicValue;
topHeuristicIdx = i;
}
}
return nodes[topHeuristicIdx];
}
void sendMove(const node &n)
{
if (n.type == 'p') {
cout << "pass\n";
} else if (n.type == 'k') {
cout << "kill " << coords(n.target) << "\n";
} else if (n.type == 'b') {
cout << "birth " << coords(n.target) << " " << coords(n.sacrifice1) << " " << coords(n.sacrifice2) << "\n";
}
}
void calculateNextState(node &n, int lookahead)
{
for (int l = 0; l < lookahead; l++) {
int neighbours0[16][18];
int neighbours1[16][18];
for (int c = 0; c < 18; c++) {
for (int r = 0; r < 16; r++) {
neighbours0[r][c] = 0;
neighbours1[r][c] = 0;
}
}
for (int c = 0; c < 18; c++) {
for (int r = 0; r < 16; r++) {
if (n.state[r][c] == '0') {
if (c > 0) {
neighbours0[r][c - 1]++;
if (r > 0) neighbours0[r - 1][c - 1]++;
if (r < 15) neighbours0[r + 1][c - 1]++;
}
if (c < 17) {
neighbours0[r][c + 1]++;
if (r > 0) neighbours0[r - 1][c + 1]++;
if (r < 15) neighbours0[r + 1][c + 1]++;
}
if (r > 0) neighbours0[r - 1][c]++;
if (r < 15) neighbours0[r + 1][c]++;
}
if (n.state[r][c] == '1') {
if (c > 0) {
neighbours1[r][c - 1]++;
if (r > 0) neighbours1[r - 1][c - 1]++;
if (r < 15) neighbours1[r + 1][c - 1]++;
}
if (c < 17) {
neighbours1[r][c + 1]++;
if (r > 0) neighbours1[r - 1][c + 1]++;
if (r < 15) neighbours1[r + 1][c + 1]++;
}
if (r > 0) neighbours1[r - 1][c]++;
if (r < 15) neighbours1[r + 1][c]++;
}
}
}
int neighbours;
for (int c = 0; c < 18; c++) {
for (int r = 0; r < 16; r++) {
neighbours = neighbours0[r][c] + neighbours1[r][c];
if (n.state[r][c] == '.' and neighbours == 3) {
n.state[r][c] = (neighbours0[r][c] > neighbours1[r][c]) ? '0' : '1';
} else if (n.state[r][c] != '.' and (neighbours < 2 or neighbours > 3)) {
n.state[r][c] = '.';
}
}
}
}
}
void calculateHeuristic(node &n)
{
int cellCount0 = 0;
int cellCount1 = 0;
// TODO: consider the number of opponent cells alive to increase aggression when they are low
for (int c = 0; c < 18; c++) {
for (int r = 0; r < 16; r++) {
if (n.state[r][c] == '0') {
cellCount0++;
} else if (n.state[r][c] == '1') {
cellCount1++;
}
}
}
if (botId == '0') {
if (cellCount0 == 0) {
n.heuristicValue = -288;
} else if (cellCount1 == 0) {
n.heuristicValue = 288;
} else {
n.heuristicValue = cellCount0 - cellCount1;
}
} else if (botId == '1') {
if (cellCount1 == 0) {
n.heuristicValue = -288;
} else if (cellCount0 == 0) {
n.heuristicValue = 288;
} else {
n.heuristicValue = cellCount1 - cellCount0;
}
}
}
// utility functions
int factorial(int x, int result) {
return (x == 1) ? result : factorial(x - 1, x * result);
}
string coords(int cellIdx)
{
stringstream ss;
ss << (cellIdx % 18) << "," << cellIdx / 18;
return ss.str();
}
void copyState(const char source[][18], char target[][18])
{
for (int r = 0; r < 16; r++) {
for (int c = 0; c < 18; c++) {
target[r][c] = source[r][c];
}
}
}
bool nodeCompare(node lhs, node rhs)
{
// sort descending
return lhs.heuristicValue > rhs.heuristicValue;
}
// debug functions
void setBotId(const char id)
{
botId = id;
}
<|endoftext|>
|
<commit_before>/*
*/
#include "lineFollowing.h"
#include "../control.h"
using namespace std;
using namespace cv;
void detect_lines(Mat &original_frame, double scale_factor);
void compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list);
#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCUnusedGlobalDeclarationInspection"
void line_main() {
// printf("Hello, this is Caleb\n");
// no this is patric
VideoCapture cap("../../tests/videos/top_down_1.m4v");
if (!cap.isOpened()) // check if we succeeded
return;
// Mat edges;
for (; ;) {
Mat frame;
cap >> frame; // get a new frame from camera
detect_lines(frame, .2);
if (waitKey(30) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return;
}
#pragma clang diagnostic pop
void detect_lines(Mat &original_frame, double scale_factor) {
Mat hsv;
Mat mask;
Mat image;
// resize(original_frame, image, Size(), scale_factor, scale_factor); //Potentially scale down the frame
cvtColor(original_frame, hsv, CV_BGR2HSV); // Image is now HSV
double minH = 50;
double minS = 20;
double minV = 150;
double maxH = 125;
double maxS = 100;
double maxV = 255;
Scalar lower(minH, minS, minV);
Scalar upper(maxH, maxS, maxV);
inRange(hsv, lower, upper, mask); // Create a mask of only the desired color
Canny(mask, mask, 50, 200, 3);
vector<Vec2f> lines, condensed, tmp_list;
HoughLines(mask, lines, 1, CV_PI / 180, 100, 0, 0);
// HoughLinesP(mask, lines, 1, CV_PI / 180.0, 10, 50, 10); // Find all lines in the image
printf("Adding in %d lines\n", (int) lines.size());
//Flipping any backwards lines
for (int i = 0; i < lines.size(); i++) {
if (lines[i][1] > CV_PI / 2) {
lines[i][1] -= CV_PI;
lines[i][0] *= -1;
}
else if (lines[i][1] < ((CV_PI / 2) * -1)) {
lines[i][1] += CV_PI;
lines[i][0] *= -1;
}
//put in order of theta, rho
swap(lines[i][0], lines[i][1]);
}
//Order from least to greatest theta
std::sort(lines.begin(), lines.end(),
[](const Vec2f &a, const Vec2f &b) {
return a[0] < b[0];
});
while (!lines.empty()) {
Vec2f to_manipulate = lines.front();
lines.erase(lines.begin());
if (tmp_list.empty()) {
tmp_list.push_back(to_manipulate);
continue;
} else {
if (abs(to_manipulate[0] - tmp_list.front()[0]) < 20 * (CV_PI / 180.0)) {
//The angles are similar
if (abs(to_manipulate[1] - tmp_list.front()[1]) < 50) {
//the distances are similar
tmp_list.push_back(to_manipulate);
continue;
}
} else {
//Need to clear out the tmp_list
compress_lines(condensed, tmp_list);
tmp_list.clear();
tmp_list.push_back(to_manipulate);
}
}
}
if (!tmp_list.empty()) {
compress_lines(condensed, tmp_list);
}
printf("Compressed down to %d lines\n", (int) condensed.size());
// Undoing work:
// condensed = lines;
for (size_t i = 0; i < condensed.size(); i++) {
float theta = condensed[i][0], rho = condensed[i][1];
// float rho = lines[i][0], theta = lines[i][1];
Point pt1, pt2;
double a = cos(theta), b = sin(theta);
double x0 = a * rho, y0 = b * rho;
pt1.x = cvRound(x0 + 1000 * (-b));
pt1.y = cvRound(y0 + 1000 * (a));
pt2.x = cvRound(x0 - 1000 * (-b));
pt2.y = cvRound(y0 - 1000 * (a));
line(original_frame, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);
}
// imshow("line_window", image);
// resize(image, original_frame, Size(), 1 / scale_factor, 1 / scale_factor);
// original_frame = image;
}
void compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list) {
Vec2f new_point;
float angle_sum = 0;
float rho_sum = 0;
for (int j = 0; j < tmp_list.size(); ++j) {
angle_sum += tmp_list[j][0];
rho_sum += tmp_list[j][1];
}
angle_sum /= tmp_list.size();
rho_sum /= tmp_list.size();
new_point[0] = angle_sum;
new_point[1] = rho_sum;
condensed.push_back(new_point);
}
LineFollowing::LineFollowing(Control *control) {
namedWindow("line_window", CV_WINDOW_NORMAL);
control_ptr = control;
return;
}
void LineFollowing::close() {
return;
}
void LineFollowing::fly() {
control_ptr->velocities.vx = 0;
control_ptr->velocities.vy = 0;
control_ptr->velocities.vz = 0;
control_ptr->velocities.vr = 0;
detect_lines(control_ptr->image, 1);
return;
}
<commit_msg>refactoring<commit_after>/*
*/
#include "lineFollowing.h"
#include "../control.h"
using namespace std;
using namespace cv;
void detect_lines(Mat &original_frame, double scale_factor);
void compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list);
void draw_lines(const Mat &image, const vector<Vec2f> &lines);
vector<Vec2f> condense_lines(vector<Vec2f> &lines);
#pragma clang diagnostic push
#pragma ide diagnostic ignored "OCUnusedGlobalDeclarationInspection"
void line_main() {
// printf("Hello, this is Caleb\n");
// no this is patric
VideoCapture cap("../../tests/videos/top_down_1.m4v");
if (!cap.isOpened()) // check if we succeeded
return;
// Mat edges;
for (; ;) {
Mat frame;
cap >> frame; // get a new frame from camera
detect_lines(frame, .2);
if (waitKey(30) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return;
}
#pragma clang diagnostic pop
void detect_lines(Mat &original_frame, double scale_factor) {
Mat hsv;
Mat mask;
Mat image;
// resize(original_frame, image, Size(), scale_factor, scale_factor); //Potentially scale down the frame
cvtColor(original_frame, hsv, CV_BGR2HSV); // Image is now HSV
double minH = 50;
double minS = 20;
double minV = 150;
double maxH = 125;
double maxS = 100;
double maxV = 255;
Scalar lower(minH, minS, minV);
Scalar upper(maxH, maxS, maxV);
inRange(hsv, lower, upper, mask); // Create a mask of only the desired color
Canny(mask, mask, 50, 200, 3);
vector<Vec2f> lines;
HoughLines(mask, lines, 1, CV_PI / 180, 100, 0, 0);
// HoughLinesP(mask, lines, 1, CV_PI / 180.0, 10, 50, 10); // Find all lines in the image
printf("Adding in %d lines\n", (int) lines.size());
//Flipping any backwards lines
vector<Vec2f> condensed = condense_lines(lines);
// printf("Compressed down to %d lines\n", (int) condensed.size());
draw_lines(original_frame, condensed);
}
vector<Vec2f> condense_lines(vector<Vec2f> lines) {
vector<Vec2f> condensed;
vector<Vec2f> tmp_list;
for (int i = 0; i < lines.size(); i++) {
if (lines[i][1] > CV_PI / 2) {
lines[i][1] -= CV_PI;
lines[i][0] *= -1;
}
else if (lines[i][1] < ((CV_PI / 2) * -1)) {
lines[i][1] += CV_PI;
lines[i][0] *= -1;
}
//put in order of theta, rho
swap(lines[i][0], lines[i][1]);
}
//Order from least to greatest theta
sort(lines.begin(), lines.end(),
[](const Vec2f &a, const Vec2f &b) {
return a[0] < b[0];
});
while (!lines.empty()) {
Vec2f to_manipulate = lines.front();
lines.erase(lines.begin());
if (tmp_list.empty()) {
tmp_list.push_back(to_manipulate);
continue;
} else {
if (abs(to_manipulate[0] - tmp_list.front()[0]) < 20 * (CV_PI / 180.0)) {
//The angles are similar
if (abs(to_manipulate[1] - tmp_list.front()[1]) < 50) {
//the distances are similar
tmp_list.push_back(to_manipulate);
continue;
}
} else {
//Need to clear out the tmp_list
compress_lines(condensed, tmp_list);
tmp_list.clear();
tmp_list.push_back(to_manipulate);
}
}
}
if (!tmp_list.empty()) {
compress_lines(condensed, tmp_list);
}
return condensed;
}
void draw_lines(const Mat &image, const vector<Vec2f> &lines) {
for (size_t i = 0; i < lines.size(); i++) {
float theta = lines[i][0], rho = lines[i][1];
// float rho = lines[i][0], theta = lines[i][1];
Point pt1, pt2;
double a = cos(theta), b = sin(theta);
double x0 = a * rho, y0 = b * rho;
pt1.x = cvRound(x0 + 1000 * (-b));
pt1.y = cvRound(y0 + 1000 * (a));
pt2.x = cvRound(x0 - 1000 * (-b));
pt2.y = cvRound(y0 - 1000 * (a));
line(image, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);
}
}
void compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list) {
Vec2f new_point;
float angle_sum = 0;
float rho_sum = 0;
for (int j = 0; j < tmp_list.size(); ++j) {
angle_sum += tmp_list[j][0];
rho_sum += tmp_list[j][1];
}
angle_sum /= tmp_list.size();
rho_sum /= tmp_list.size();
new_point[0] = angle_sum;
new_point[1] = rho_sum;
condensed.push_back(new_point);
}
LineFollowing::LineFollowing(Control *control) {
namedWindow("line_window", CV_WINDOW_NORMAL);
control_ptr = control;
return;
}
void LineFollowing::close() {
return;
}
void LineFollowing::fly() {
control_ptr->velocities.vx = 0;
control_ptr->velocities.vy = 0;
control_ptr->velocities.vz = 0;
control_ptr->velocities.vr = 0;
detect_lines(control_ptr->image, 1);
return;
}
<|endoftext|>
|
<commit_before>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// 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. //
// ======================================================================== //
// ospray
#include "Library.h"
// std
#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#else
# include <dlfcn.h>
#endif
namespace ospray {
std::vector<Library*> loadedLibs;
void loadLibrary(const std::string &_name)
{
#ifdef OSPRAY_TARGET_MIC
std::string name = _name+"_mic";
#else
std::string name = _name;
#endif
for (int i=0;i<loadedLibs.size();i++)
if (loadedLibs[i]->name == name)
// lib already loaded.
return;
Library *lib = new Library;
lib->name = name;
lib->lib = embree::openLibrary(name);
if (lib->lib == NULL)
throw std::runtime_error("could not open module lib "+name);
loadedLibs.push_back(lib);
}
void *getSymbol(const std::string &name)
{
for (int i=0;i<loadedLibs.size();i++) {
void *sym = embree::getSymbol(loadedLibs[i]->lib, name);
if (sym) return sym;
}
// if none found in the loaded libs, try the default lib ...
#ifdef _WIN32
void *sym = GetProcAddress(GetModuleHandle(0), name.c_str());
#else
void *sym = dlsym(RTLD_DEFAULT,name.c_str());
#endif
return sym;
}
} // ::ospray
<commit_msg>Also search in ospray.dll for symbols<commit_after>// ======================================================================== //
// Copyright 2009-2015 Intel Corporation //
// //
// 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. //
// ======================================================================== //
// ospray
#include "Library.h"
// std
#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#else
# include <dlfcn.h>
#endif
namespace ospray {
std::vector<Library*> loadedLibs;
void loadLibrary(const std::string &_name)
{
#ifdef OSPRAY_TARGET_MIC
std::string name = _name+"_mic";
#else
std::string name = _name;
#endif
for (int i=0;i<loadedLibs.size();i++)
if (loadedLibs[i]->name == name)
// lib already loaded.
return;
Library *lib = new Library;
lib->name = name;
lib->lib = embree::openLibrary(name);
if (lib->lib == NULL)
throw std::runtime_error("could not open module lib "+name);
loadedLibs.push_back(lib);
}
void *getSymbol(const std::string &name)
{
for (int i=0;i<loadedLibs.size();i++) {
void *sym = embree::getSymbol(loadedLibs[i]->lib, name);
if (sym) return sym;
}
// if none found in the loaded libs, try the default lib ...
#ifdef _WIN32
void *sym = GetProcAddress(GetModuleHandle(0), name.c_str()); // look in exe (i.e. when linked statically)
if (!sym) {
MEMORY_BASIC_INFORMATION mbi;
VirtualQuery(getSymbol, &mbi, sizeof(mbi)); // get handle to current dll via a known function
sym = GetProcAddress((HINSTANCE)(mbi.AllocationBase), name.c_str()); // look in ospray.dll (i.e. when linked dynamically)
}
#else
void *sym = dlsym(RTLD_DEFAULT,name.c_str());
#endif
return sym;
}
} // ::ospray
<|endoftext|>
|
<commit_before>/*
*/
#include "lineFollowing.h"
using namespace std;
using namespace cv;
ControlMovements lineFollowingControl() {
line_main();
return ControlMovements();
}
void line_main() {
// printf("Hello, this is Caleb\n");
VideoCapture cap("../../tests/videos/top_down_4.m4v");
if (!cap.isOpened()) // check if we succeeded
return;
namedWindow("edges", CV_WINDOW_NORMAL);
Mat edges;
for (; ;) {
Mat frame, mask;
cap >> frame; // get a new frame from camera
cvtColor(frame, edges, CV_BGR2HSV);
Scalar low, high;
low = Scalar(30, 0, 240);
high = Scalar(80, 70, 255);
inRange(frame, low, high, mask);
vector <Vec4i> lines;
HoughLinesP(mask, lines, 1, CV_PI / 180, 100, 100, 10);
for (size_t i = 0; i < lines.size(); i++) {
cout << "adding a line\n";
Vec4i l = lines[i];
line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);
}
imshow("edges", frame);
if (waitKey(30) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return;
}
<commit_msg>first attempt at lines<commit_after>/*
*/
#include "lineFollowing.h"
using namespace std;
using namespace cv;
ControlMovements lineFollowingControl() {
line_main();
return ControlMovements();
}
void line_main() {
// printf("Hello, this is Caleb\n");
VideoCapture cap("../../tests/videos/top_down_4.m4v");
if (!cap.isOpened()) // check if we succeeded
return;
namedWindow("edges", CV_WINDOW_NORMAL);
Mat edges;
for (; ;) {
Mat frame, mask;
cap >> frame; // get a new frame from camera
cvtColor(frame, edges, CV_BGR2HSV);
Scalar low, high;
low = Scalar(30, 0, 240);
high = Scalar(80, 70, 255);
inRange(frame, low, high, mask);
vector <Vec4i> lines;
HoughLinesP(mask, lines, 1, CV_PI / 180, 100, 100, 10);
for (size_t i = 0; i < lines.size(); i++) {
cout << "adding a line\n";
Vec4i l = lines[i];
line(frame, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);
}
imshow("edges", mask);
if (waitKey(30) >= 0) break;
}
// the camera will be deinitialized automatically in VideoCapture destructor
return;
}
<|endoftext|>
|
<commit_before>// $Id$
/*
Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University
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 Stanford University 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.
*/
// ----------------------------------------------------------------------
//
// SeparableAllocator: Separable Allocator
//
// ----------------------------------------------------------------------
#ifndef _SEPARABLE_HPP_
#define _SEPARABLE_HPP_
#include "allocator.hpp"
#include "arbiter.hpp"
#include <cassert>
#include <vector>
class SeparableAllocator : public Allocator {
protected:
vector<int> _matched ;
vector<Arbiter*> _input_arb ;
vector<Arbiter*> _output_arb ;
vector<vector<sRequest> > _requests ;
public:
SeparableAllocator( Module* parent, const string& name, int inputs,
int outputs, const string& arb_type ) ;
virtual ~SeparableAllocator() ;
//
// Allocator Interface
//
virtual void Clear() ;
virtual int ReadRequest( int in, int out ) const ;
virtual bool ReadRequest( sRequest& req, int in, int out ) const ;
virtual void AddRequest( int in, int out, int label = 1,
int in_pri = 0, int out_pri = 0 ) ;
virtual void RemoveRequest( int in, int out, int label = 1 ) ;
virtual void Allocate() = 0 ;
virtual void PrintRequests( ostream * os = NULL ) const ;
} ;
#endif
<commit_msg>remove unused member variable<commit_after>// $Id$
/*
Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University
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 Stanford University 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.
*/
// ----------------------------------------------------------------------
//
// SeparableAllocator: Separable Allocator
//
// ----------------------------------------------------------------------
#ifndef _SEPARABLE_HPP_
#define _SEPARABLE_HPP_
#include "allocator.hpp"
#include "arbiter.hpp"
#include <cassert>
#include <vector>
class SeparableAllocator : public Allocator {
protected:
vector<Arbiter*> _input_arb ;
vector<Arbiter*> _output_arb ;
vector<vector<sRequest> > _requests ;
public:
SeparableAllocator( Module* parent, const string& name, int inputs,
int outputs, const string& arb_type ) ;
virtual ~SeparableAllocator() ;
//
// Allocator Interface
//
virtual void Clear() ;
virtual int ReadRequest( int in, int out ) const ;
virtual bool ReadRequest( sRequest& req, int in, int out ) const ;
virtual void AddRequest( int in, int out, int label = 1,
int in_pri = 0, int out_pri = 0 ) ;
virtual void RemoveRequest( int in, int out, int label = 1 ) ;
virtual void Allocate() = 0 ;
virtual void PrintRequests( ostream * os = NULL ) const ;
} ;
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: colrowst.cxx,v $
*
* $Revision: 1.26 $
*
* last change: $Author: vg $ $Date: 2005-02-21 13:22:30 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "filt_pch.hxx"
#endif
#pragma hdrstop
#include "colrowst.hxx"
#include <string.h>
#include "document.hxx"
#include "root.hxx"
#ifndef SC_FTOOLS_HXX
#include "ftools.hxx"
#endif
#ifndef SC_XLTABLE_HXX
#include "xltable.hxx"
#endif
#ifndef SC_XISTREAM_HXX
#include "xistream.hxx"
#endif
#ifndef SC_XISTYLE_HXX
#include "xistyle.hxx"
#endif
// for filter manager
#include "excimp8.hxx"
ColRowSettings::ColRowSettings( RootData& rRootData ) :
ExcRoot( &rRootData )
{
nDefWidth = nDefHeight = 0;
pWidth = new INT32 [ MAXCOL + 1 ];
pColHidden = new BOOL [ MAXCOL + 1 ];
pHeight = new UINT16 [ MAXROW + 1 ];
pRowFlags = new INT8[ MAXROW + 1 ];
Reset();
}
ColRowSettings::~ColRowSettings()
{
delete[] pRowFlags;
delete[] pHeight;
delete[] pColHidden;
delete[] pWidth;
}
void ColRowSettings::Reset( void )
{
SCCOL nC;
for( nC = 0 ; nC <= MAXCOL ; nC++ )
{
pColHidden[ nC ] = FALSE;
pWidth[ nC ] = -1;
}
memset( pRowFlags, 0x00, sizeof( INT8 ) * ( MAXROW + 1 ) );
bDirty = TRUE;
nMaxRow = -1;
bSetByStandard = FALSE;
}
void ColRowSettings::Apply( SCTAB nScTab )
{
if( !bDirty )
return;
SCCOLROW nC;
SCROW nStart = 0;
UINT16 nWidth;
UINT16 nLastWidth = ( pWidth[ 0 ] >= 0 )? ( UINT16 ) pWidth[ 0 ] : nDefWidth;
ScDocument& rD = pExcRoot->pIR->GetDoc();
rD.IncSizeRecalcLevel( nScTab );
// Column-Bemachung
for( nC = 0 ; nC <= MAXCOL ; nC++ )
{
if( pWidth[ nC ] >= 0 )
// eingestellte Width
nWidth = ( UINT16 ) pWidth[ nC ];
else
// Default-Width
nWidth = nDefWidth;
if( nWidth == 0 )
{
pColHidden[ nC ] = TRUE;
// Column hidden: remember original column width and set width 0.
// Needed for #i11776#, no HIDDEN flags in the document, until
// filters and outlines are inserted.
pWidth[ nC ] = rD.GetColWidth( static_cast<SCCOL>( nC ), nScTab );
}
rD.SetColWidth( static_cast<SCCOL>( nC ), nScTab, nWidth );
}
// Row-Bemachung
INT8 nFlags;
nStart = 0;
UINT16 nHeight;
UINT16 nLastHeight;
nFlags = pRowFlags[ 0 ];
if( nFlags & ROWFLAG_USED )
{
if( nFlags & ROWFLAG_DEFAULT )
nLastHeight = nDefHeight;
else
{
nLastHeight = pHeight[ 0 ];
if( !nLastHeight )
nLastHeight = nDefHeight;
}
}
else
nLastHeight = nDefHeight;
for( nC = 0 ; nC <= nMaxRow ; nC++ )
{
nFlags = pRowFlags[ nC ];
if( nFlags & ROWFLAG_USED )
{
if( nFlags & ROWFLAG_DEFAULT )
nHeight = nDefHeight;
else
{
nHeight = pHeight[ nC ];
if( !nHeight )
nHeight = nDefHeight;
}
if( nFlags & ( ROWFLAG_HIDDEN | ROWFLAG_MAN ) )
{
BYTE nSCFlags = rD.GetRowFlags( nC , nScTab );
if( nFlags & ROWFLAG_MAN )
nSCFlags |= CR_MANUALSIZE;
rD.SetRowFlags( nC, nScTab, nSCFlags );
}
}
else
nHeight = nDefHeight;
if( !nHeight )
{
pRowFlags[ nC ] |= ROWFLAG_HIDDEN;
// Row hidden: remember original row height and set height 0.
// Needed for #i11776#, no HIDDEN flags in the document, until
// filters and outlines are inserted.
pHeight[ nC ] = rD.GetRowHeight( nC, nScTab );
}
if( nLastHeight != nHeight )
{
DBG_ASSERT( nC > 0, "ColRowSettings::Apply(): Algorithmus-Fehler!" );
if( nLastHeight )
rD.SetRowHeightRange( nStart, nC - 1, nScTab, nLastHeight );
nStart = nC;
nLastHeight = nHeight;
}
}
if( nLastHeight && nMaxRow >= 0 )
rD.SetRowHeightRange( nStart, static_cast<SCROW>( nMaxRow ), nScTab, nLastHeight );
bDirty = FALSE; // jetzt stimmt Tabelle im ScDocument
rD.DecSizeRecalcLevel( nScTab );
}
void ColRowSettings::SetHiddenFlags( SCTAB nScTab )
{
ScDocument& rDoc = pExcRoot->pIR->GetDoc();
for( SCCOL nScCol = 0; nScCol <= MAXCOL; ++nScCol )
{
if( pColHidden[ nScCol ] )
{
// set original width, needed to unhide the column
if( pWidth[ nScCol ] > 0 )
rDoc.SetColWidth( nScCol, nScTab, static_cast< sal_uInt16 >( pWidth[ nScCol ] ) );
// really hide the column
rDoc.ShowCol( nScCol, nScTab, FALSE );
}
}
// #i38093# rows hidden by filter need extra flag
SCROW nFirstFilterScRow = SCROW_MAX;
SCROW nLastFilterScRow = SCROW_MAX;
if( pExcRoot->pIR->GetBiff() == EXC_BIFF8 )
{
const XclImpAutoFilterData* pFilter = pExcRoot->pIR->GetFilterManager().GetByTab( nScTab );
if( pFilter && pFilter->IsActive() )
{
nFirstFilterScRow = pFilter->StartRow();
nLastFilterScRow = pFilter->EndRow();
}
}
for( SCROW nScRow = 0; nScRow <= nMaxRow; ++nScRow )
{
if( pRowFlags[ nScRow ] & ROWFLAG_HIDDEN )
{
// set original height, needed to unhide the row
if( pHeight[ nScRow ] > 0 )
rDoc.SetRowHeight( nScRow, nScTab, pHeight[ nScRow ] );
// really hide the row
rDoc.ShowRow( nScRow, nScTab, FALSE );
// #i38093# rows hidden by filter need extra flag
if( (nFirstFilterScRow <= nScRow) && (nScRow <= nLastFilterScRow) )
rDoc.SetRowFlags( nScRow, nScTab, rDoc.GetRowFlags( nScRow, nScTab ) | CR_FILTERED );
}
}
}
void ColRowSettings::HideColRange( SCCOL nColFirst, SCCOL nColLast )
{
DBG_ASSERT( nColFirst <= nColLast, "+ColRowSettings::HideColRange(): First > Last?!" );
DBG_ASSERT( ValidCol(nColLast), "+ColRowSettings::HideColRange(): ungueltige Column" );
if( !ValidCol(nColLast) )
nColLast = MAXCOL;
BOOL* pHidden;
BOOL* pFinish;
pHidden = &pColHidden[ nColFirst ];
pFinish = &pColHidden[ nColLast ];
while( pHidden <= pFinish )
*( pHidden++ ) = TRUE;
}
void ColRowSettings::SetWidthRange( SCCOL nColFirst, SCCOL nColLast, UINT16 nNew )
{
DBG_ASSERT( nColFirst <= nColLast, "+ColRowSettings::SetColWidthRange(): First > Last?!" );
DBG_ASSERT( ValidCol(nColLast), "+ColRowSettings::SetColWidthRange(): ungueltige Column" );
if( !ValidCol(nColLast) )
nColLast = MAXCOL;
INT32* pWidthCount;
INT32* pFinish;
pWidthCount = &pWidth[ nColFirst ];
pFinish = &pWidth[ nColLast ];
while( pWidthCount <= pFinish )
*( pWidthCount++ ) = nNew;
}
void ColRowSettings::SetDefaultXF( SCCOL nColFirst, SCCOL nColLast, UINT16 nXF )
{
DBG_ASSERT( nColFirst <= nColLast, "+ColRowSettings::SetDefaultXF(): First > Last?!" );
DBG_ASSERT( ValidCol(nColLast), "+ColRowSettings::SetDefaultXF(): ungueltige Column" );
if( !ValidCol(nColLast) )
nColLast = MAXCOL;
const XclImpRoot& rRoot = *pExcRoot->pIR;
// #109555# assign the default column formatting here to ensure
// that explicit cell formatting is not overwritten.
for( SCCOL nScCol = nColFirst; nScCol <= nColLast; ++nScCol )
rRoot.GetXFRangeBuffer().SetColumnDefXF( nScCol, nXF );
}
void ColRowSettings::SetDefaults( UINT16 nWidth, UINT16 nHeight )
{
nDefWidth = nWidth;
nDefHeight = nHeight;
}
void ColRowSettings::_SetRowSettings( const SCROW nRow, const UINT16 nExcelHeight, const UINT16 nGrbit )
{
pHeight[ nRow ] = nExcelHeight & 0x7FFF;
INT8 nFlags = ROWFLAG_USED;
if( nExcelHeight & 0x8000 )
nFlags |= ROWFLAG_DEFAULT;
if( nGrbit & EXC_ROW_UNSYNCED )
nFlags |= ROWFLAG_MAN;
if( nGrbit & EXC_ROW_HIDDEN )
nFlags |= ROWFLAG_HIDDEN;
pRowFlags[ nRow ] = nFlags;
if( nRow > nMaxRow )
nMaxRow = nRow;
}
<commit_msg>INTEGRATION: CWS dr34 (1.26.2); FILE MERGED 2005/03/17 16:20:51 dr 1.26.2.1: #i45209# rename classes with name already used somewhere<commit_after>/*************************************************************************
*
* $RCSfile: colrowst.cxx,v $
*
* $Revision: 1.27 $
*
* last change: $Author: rt $ $Date: 2005-03-29 13:36:04 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef PCH
#include "filt_pch.hxx"
#endif
#pragma hdrstop
#include "colrowst.hxx"
#include <string.h>
#include "document.hxx"
#include "root.hxx"
#ifndef SC_FTOOLS_HXX
#include "ftools.hxx"
#endif
#ifndef SC_XLTABLE_HXX
#include "xltable.hxx"
#endif
#ifndef SC_XISTREAM_HXX
#include "xistream.hxx"
#endif
#ifndef SC_XISTYLE_HXX
#include "xistyle.hxx"
#endif
// for filter manager
#include "excimp8.hxx"
XclImpColRowSettings::XclImpColRowSettings( RootData& rRootData ) :
ExcRoot( &rRootData )
{
nDefWidth = nDefHeight = 0;
pWidth = new INT32 [ MAXCOL + 1 ];
pColHidden = new BOOL [ MAXCOL + 1 ];
pHeight = new UINT16 [ MAXROW + 1 ];
pRowFlags = new INT8[ MAXROW + 1 ];
Reset();
}
XclImpColRowSettings::~XclImpColRowSettings()
{
delete[] pRowFlags;
delete[] pHeight;
delete[] pColHidden;
delete[] pWidth;
}
void XclImpColRowSettings::Reset( void )
{
SCCOL nC;
for( nC = 0 ; nC <= MAXCOL ; nC++ )
{
pColHidden[ nC ] = FALSE;
pWidth[ nC ] = -1;
}
memset( pRowFlags, 0x00, sizeof( INT8 ) * ( MAXROW + 1 ) );
bDirty = TRUE;
nMaxRow = -1;
bSetByStandard = FALSE;
}
void XclImpColRowSettings::Apply( SCTAB nScTab )
{
if( !bDirty )
return;
SCCOLROW nC;
SCROW nStart = 0;
UINT16 nWidth;
UINT16 nLastWidth = ( pWidth[ 0 ] >= 0 )? ( UINT16 ) pWidth[ 0 ] : nDefWidth;
ScDocument& rD = pExcRoot->pIR->GetDoc();
rD.IncSizeRecalcLevel( nScTab );
// Column-Bemachung
for( nC = 0 ; nC <= MAXCOL ; nC++ )
{
if( pWidth[ nC ] >= 0 )
// eingestellte Width
nWidth = ( UINT16 ) pWidth[ nC ];
else
// Default-Width
nWidth = nDefWidth;
if( nWidth == 0 )
{
pColHidden[ nC ] = TRUE;
// Column hidden: remember original column width and set width 0.
// Needed for #i11776#, no HIDDEN flags in the document, until
// filters and outlines are inserted.
pWidth[ nC ] = rD.GetColWidth( static_cast<SCCOL>( nC ), nScTab );
}
rD.SetColWidth( static_cast<SCCOL>( nC ), nScTab, nWidth );
}
// Row-Bemachung
INT8 nFlags;
nStart = 0;
UINT16 nHeight;
UINT16 nLastHeight;
nFlags = pRowFlags[ 0 ];
if( nFlags & ROWFLAG_USED )
{
if( nFlags & ROWFLAG_DEFAULT )
nLastHeight = nDefHeight;
else
{
nLastHeight = pHeight[ 0 ];
if( !nLastHeight )
nLastHeight = nDefHeight;
}
}
else
nLastHeight = nDefHeight;
for( nC = 0 ; nC <= nMaxRow ; nC++ )
{
nFlags = pRowFlags[ nC ];
if( nFlags & ROWFLAG_USED )
{
if( nFlags & ROWFLAG_DEFAULT )
nHeight = nDefHeight;
else
{
nHeight = pHeight[ nC ];
if( !nHeight )
nHeight = nDefHeight;
}
if( nFlags & ( ROWFLAG_HIDDEN | ROWFLAG_MAN ) )
{
BYTE nSCFlags = rD.GetRowFlags( nC , nScTab );
if( nFlags & ROWFLAG_MAN )
nSCFlags |= CR_MANUALSIZE;
rD.SetRowFlags( nC, nScTab, nSCFlags );
}
}
else
nHeight = nDefHeight;
if( !nHeight )
{
pRowFlags[ nC ] |= ROWFLAG_HIDDEN;
// Row hidden: remember original row height and set height 0.
// Needed for #i11776#, no HIDDEN flags in the document, until
// filters and outlines are inserted.
pHeight[ nC ] = rD.GetRowHeight( nC, nScTab );
}
if( nLastHeight != nHeight )
{
DBG_ASSERT( nC > 0, "XclImpColRowSettings::Apply(): Algorithmus-Fehler!" );
if( nLastHeight )
rD.SetRowHeightRange( nStart, nC - 1, nScTab, nLastHeight );
nStart = nC;
nLastHeight = nHeight;
}
}
if( nLastHeight && nMaxRow >= 0 )
rD.SetRowHeightRange( nStart, static_cast<SCROW>( nMaxRow ), nScTab, nLastHeight );
bDirty = FALSE; // jetzt stimmt Tabelle im ScDocument
rD.DecSizeRecalcLevel( nScTab );
}
void XclImpColRowSettings::SetHiddenFlags( SCTAB nScTab )
{
ScDocument& rDoc = pExcRoot->pIR->GetDoc();
for( SCCOL nScCol = 0; nScCol <= MAXCOL; ++nScCol )
{
if( pColHidden[ nScCol ] )
{
// set original width, needed to unhide the column
if( pWidth[ nScCol ] > 0 )
rDoc.SetColWidth( nScCol, nScTab, static_cast< sal_uInt16 >( pWidth[ nScCol ] ) );
// really hide the column
rDoc.ShowCol( nScCol, nScTab, FALSE );
}
}
// #i38093# rows hidden by filter need extra flag
SCROW nFirstFilterScRow = SCROW_MAX;
SCROW nLastFilterScRow = SCROW_MAX;
if( pExcRoot->pIR->GetBiff() == EXC_BIFF8 )
{
const XclImpAutoFilterData* pFilter = pExcRoot->pIR->GetFilterManager().GetByTab( nScTab );
if( pFilter && pFilter->IsActive() )
{
nFirstFilterScRow = pFilter->StartRow();
nLastFilterScRow = pFilter->EndRow();
}
}
for( SCROW nScRow = 0; nScRow <= nMaxRow; ++nScRow )
{
if( pRowFlags[ nScRow ] & ROWFLAG_HIDDEN )
{
// set original height, needed to unhide the row
if( pHeight[ nScRow ] > 0 )
rDoc.SetRowHeight( nScRow, nScTab, pHeight[ nScRow ] );
// really hide the row
rDoc.ShowRow( nScRow, nScTab, FALSE );
// #i38093# rows hidden by filter need extra flag
if( (nFirstFilterScRow <= nScRow) && (nScRow <= nLastFilterScRow) )
rDoc.SetRowFlags( nScRow, nScTab, rDoc.GetRowFlags( nScRow, nScTab ) | CR_FILTERED );
}
}
}
void XclImpColRowSettings::HideColRange( SCCOL nColFirst, SCCOL nColLast )
{
DBG_ASSERT( nColFirst <= nColLast, "+XclImpColRowSettings::HideColRange(): First > Last?!" );
DBG_ASSERT( ValidCol(nColLast), "+XclImpColRowSettings::HideColRange(): ungueltige Column" );
if( !ValidCol(nColLast) )
nColLast = MAXCOL;
BOOL* pHidden;
BOOL* pFinish;
pHidden = &pColHidden[ nColFirst ];
pFinish = &pColHidden[ nColLast ];
while( pHidden <= pFinish )
*( pHidden++ ) = TRUE;
}
void XclImpColRowSettings::SetWidthRange( SCCOL nColFirst, SCCOL nColLast, UINT16 nNew )
{
DBG_ASSERT( nColFirst <= nColLast, "+XclImpColRowSettings::SetColWidthRange(): First > Last?!" );
DBG_ASSERT( ValidCol(nColLast), "+XclImpColRowSettings::SetColWidthRange(): ungueltige Column" );
if( !ValidCol(nColLast) )
nColLast = MAXCOL;
INT32* pWidthCount;
INT32* pFinish;
pWidthCount = &pWidth[ nColFirst ];
pFinish = &pWidth[ nColLast ];
while( pWidthCount <= pFinish )
*( pWidthCount++ ) = nNew;
}
void XclImpColRowSettings::SetDefaultXF( SCCOL nColFirst, SCCOL nColLast, UINT16 nXF )
{
DBG_ASSERT( nColFirst <= nColLast, "+XclImpColRowSettings::SetDefaultXF(): First > Last?!" );
DBG_ASSERT( ValidCol(nColLast), "+XclImpColRowSettings::SetDefaultXF(): ungueltige Column" );
if( !ValidCol(nColLast) )
nColLast = MAXCOL;
const XclImpRoot& rRoot = *pExcRoot->pIR;
// #109555# assign the default column formatting here to ensure
// that explicit cell formatting is not overwritten.
for( SCCOL nScCol = nColFirst; nScCol <= nColLast; ++nScCol )
rRoot.GetXFRangeBuffer().SetColumnDefXF( nScCol, nXF );
}
void XclImpColRowSettings::SetDefaults( UINT16 nWidth, UINT16 nHeight )
{
nDefWidth = nWidth;
nDefHeight = nHeight;
}
void XclImpColRowSettings::_SetRowSettings( const SCROW nRow, const UINT16 nExcelHeight, const UINT16 nGrbit )
{
pHeight[ nRow ] = nExcelHeight & 0x7FFF;
INT8 nFlags = ROWFLAG_USED;
if( nExcelHeight & 0x8000 )
nFlags |= ROWFLAG_DEFAULT;
if( nGrbit & EXC_ROW_UNSYNCED )
nFlags |= ROWFLAG_MAN;
if( nGrbit & EXC_ROW_HIDDEN )
nFlags |= ROWFLAG_HIDDEN;
pRowFlags[ nRow ] = nFlags;
if( nRow > nMaxRow )
nMaxRow = nRow;
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <algorithm>
#include <stdio.h>
#include <vector>
#include "NETEQTEST_RTPpacket.h"
/*********************/
/* Misc. definitions */
/*********************/
#define FIRSTLINELEN 40
bool pktCmp (NETEQTEST_RTPpacket *a, NETEQTEST_RTPpacket *b)
{
return (a->time() < b->time());
}
int main(int argc, char* argv[])
{
FILE *inFile=fopen(argv[1],"rb");
if (!inFile)
{
printf("Cannot open input file %s\n", argv[1]);
return(-1);
}
printf("Input RTP file: %s\n",argv[1]);
FILE *statFile=fopen(argv[2],"rt");
if (!statFile)
{
printf("Cannot open timing file %s\n", argv[2]);
return(-1);
}
printf("Timing file: %s\n",argv[2]);
FILE *outFile=fopen(argv[3],"wb");
if (!outFile)
{
printf("Cannot open output file %s\n", argv[3]);
return(-1);
}
printf("Output RTP file: %s\n\n",argv[3]);
// read all statistics and insert into map
// read first line
char tempStr[100];
fgets(tempStr, 100, statFile);
// define map
std::map<std::pair<WebRtc_UWord16, WebRtc_UWord32>, WebRtc_Word32> packetStats;
WebRtc_UWord16 seqNo;
WebRtc_UWord32 ts;
WebRtc_Word32 sendTime;
while(fscanf(statFile, "%hu %lu %ld\n", &seqNo, &ts, &sendTime) == 3)
{
std::pair<WebRtc_UWord16, WebRtc_UWord32> tempPair = std::pair<WebRtc_UWord16, WebRtc_UWord32>(seqNo, ts);
packetStats[tempPair] = sendTime;
}
fclose(statFile);
// read file header and write directly to output file
char firstline[FIRSTLINELEN];
fgets(firstline, FIRSTLINELEN, inFile);
fputs(firstline, outFile);
fread(firstline, 4+4+4+2+2, 1, inFile); // start_sec + start_usec + source + port + padding
fwrite(firstline, 4+4+4+2+2, 1, outFile);
std::vector<NETEQTEST_RTPpacket *> packetVec;
int i = 0;
while (1)
{
// insert in vector
NETEQTEST_RTPpacket *newPacket = new NETEQTEST_RTPpacket();
if (newPacket->readFromFile(inFile) < 0)
{
// end of file
break;
}
// look for new send time in statistics vector
std::pair<WebRtc_UWord16, WebRtc_UWord32> tempPair =
std::pair<WebRtc_UWord16, WebRtc_UWord32>(newPacket->sequenceNumber(), newPacket->timeStamp());
WebRtc_Word32 newSendTime = packetStats[tempPair];
if (newSendTime >= 0)
{
newPacket->setTime(newSendTime); // set new send time
packetVec.push_back(newPacket); // insert in vector
}
else
{
// negative value represents lost packet
// don't insert, but delete packet object
delete newPacket;
}
}
// sort the vector according to send times
std::sort(packetVec.begin(), packetVec.end(), pktCmp);
std::vector<NETEQTEST_RTPpacket *>::iterator it;
for (it = packetVec.begin(); it != packetVec.end(); it++)
{
// write to out file
if ((*it)->writeToFile(outFile) < 0)
{
printf("Error writing to file\n");
return(-1);
}
// delete packet
delete *it;
}
fclose(inFile);
fclose(outFile);
return 0;
}
<commit_msg>Update test tool RTPchange<commit_after>/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <algorithm>
#include <stdio.h>
#include <vector>
#include "NETEQTEST_RTPpacket.h"
/*********************/
/* Misc. definitions */
/*********************/
#define FIRSTLINELEN 40
bool pktCmp (NETEQTEST_RTPpacket *a, NETEQTEST_RTPpacket *b)
{
return (a->time() < b->time());
}
int main(int argc, char* argv[])
{
FILE *inFile=fopen(argv[1],"rb");
if (!inFile)
{
printf("Cannot open input file %s\n", argv[1]);
return(-1);
}
printf("Input RTP file: %s\n",argv[1]);
FILE *statFile=fopen(argv[2],"rt");
if (!statFile)
{
printf("Cannot open timing file %s\n", argv[2]);
return(-1);
}
printf("Timing file: %s\n",argv[2]);
FILE *outFile=fopen(argv[3],"wb");
if (!outFile)
{
printf("Cannot open output file %s\n", argv[3]);
return(-1);
}
printf("Output RTP file: %s\n\n",argv[3]);
// read all statistics and insert into map
// read first line
char tempStr[100];
fgets(tempStr, 100, statFile);
// define map
std::map<std::pair<WebRtc_UWord16, WebRtc_UWord32>, WebRtc_UWord32>
packetStats;
WebRtc_UWord16 seqNo;
WebRtc_UWord32 ts;
WebRtc_UWord32 sendTime;
while(fscanf(statFile, "%u %u %u %*i\n", &seqNo, &ts, &sendTime) == 3)
{
std::pair<WebRtc_UWord16, WebRtc_UWord32> tempPair =
std::pair<WebRtc_UWord16, WebRtc_UWord32>(seqNo, ts);
packetStats[tempPair] = sendTime;
}
fclose(statFile);
// read file header and write directly to output file
char firstline[FIRSTLINELEN];
fgets(firstline, FIRSTLINELEN, inFile);
fputs(firstline, outFile);
fread(firstline, 4+4+4+2+2, 1, inFile); // start_sec + start_usec + source + port + padding
fwrite(firstline, 4+4+4+2+2, 1, outFile);
std::vector<NETEQTEST_RTPpacket *> packetVec;
int i = 0;
while (1)
{
// insert in vector
NETEQTEST_RTPpacket *newPacket = new NETEQTEST_RTPpacket();
if (newPacket->readFromFile(inFile) < 0)
{
// end of file
break;
}
// look for new send time in statistics vector
std::pair<WebRtc_UWord16, WebRtc_UWord32> tempPair =
std::pair<WebRtc_UWord16, WebRtc_UWord32>(newPacket->sequenceNumber(), newPacket->timeStamp());
WebRtc_UWord32 newSendTime = packetStats[tempPair];
if (newSendTime >= 0)
{
newPacket->setTime(newSendTime); // set new send time
packetVec.push_back(newPacket); // insert in vector
}
else
{
// negative value represents lost packet
// don't insert, but delete packet object
delete newPacket;
}
}
// sort the vector according to send times
std::sort(packetVec.begin(), packetVec.end(), pktCmp);
std::vector<NETEQTEST_RTPpacket *>::iterator it;
for (it = packetVec.begin(); it != packetVec.end(); it++)
{
// write to out file
if ((*it)->writeToFile(outFile) < 0)
{
printf("Error writing to file\n");
return(-1);
}
// delete packet
delete *it;
}
fclose(inFile);
fclose(outFile);
return 0;
}
<|endoftext|>
|
<commit_before>/* Copyright 2019 Google LLC. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/experimental/ruy/context.h"
#include "tensorflow/lite/experimental/ruy/check_macros.h"
#include "tensorflow/lite/experimental/ruy/detect_arm.h"
#include "tensorflow/lite/experimental/ruy/detect_x86.h"
#include "tensorflow/lite/experimental/ruy/have_built_path_for.h"
#include "tensorflow/lite/experimental/ruy/platform.h"
namespace ruy {
void Context::SetRuntimeEnabledPaths(Path paths) {
runtime_enabled_paths_ = paths;
}
Path Context::GetRuntimeEnabledPaths() {
// This function should always return the same value on a given machine.
// When runtime_enabled_paths_ has its initial value kNone, it performs
// some platform detection to resolve it to specific Path values.
// Fast path: already resolved.
if (runtime_enabled_paths_ != Path::kNone) {
return runtime_enabled_paths_;
}
// Need to resolve now. Start by considering all paths enabled.
runtime_enabled_paths_ = kAllPaths;
#if RUY_PLATFORM(ARM)
// Now selectively disable paths that aren't supported on this machine.
if ((runtime_enabled_paths_ & Path::kNeonDotprod) != Path::kNone) {
if (!DetectDotprod()) {
runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kNeonDotprod;
// Sanity check.
RUY_DCHECK((runtime_enabled_paths_ & Path::kNeonDotprod) == Path::kNone);
}
}
#endif // RUY_PLATFORM(ARM)
#if RUY_PLATFORM(X86)
if ((runtime_enabled_paths_ & Path::kAvx2) != Path::kNone) {
if (!(HaveBuiltPathForAvx2() && DetectCpuAvx2())) {
runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kAvx2;
// Sanity check.
RUY_DCHECK((runtime_enabled_paths_ & Path::kAvx2) == Path::kNone);
}
}
if ((runtime_enabled_paths_ & Path::kAvx512) != Path::kNone) {
if (!(HaveBuiltPathForAvx512() && DetectCpuAvx512())) {
runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kAvx512;
// Sanity check.
RUY_DCHECK((runtime_enabled_paths_ & Path::kAvx512) == Path::kNone);
}
}
#endif // RUY_PLATFORM(X86)
// Sanity check. We can't possibly have disabled all paths, as some paths
// are universally available (kReference, kStandardCpp).
RUY_DCHECK(runtime_enabled_paths_ != Path::kNone);
return runtime_enabled_paths_;
}
} // namespace ruy
<commit_msg>Ruy: Add mechanism to mask out paths.<commit_after>/* Copyright 2019 Google LLC. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/experimental/ruy/context.h"
#include "tensorflow/lite/experimental/ruy/check_macros.h"
#include "tensorflow/lite/experimental/ruy/detect_arm.h"
#include "tensorflow/lite/experimental/ruy/detect_x86.h"
#include "tensorflow/lite/experimental/ruy/have_built_path_for.h"
#include "tensorflow/lite/experimental/ruy/platform.h"
namespace ruy {
void Context::SetRuntimeEnabledPaths(Path paths) {
runtime_enabled_paths_ = paths;
}
Path Context::GetRuntimeEnabledPaths() {
// This function should always return the same value on a given machine.
// When runtime_enabled_paths_ has its initial value kNone, it performs
// some platform detection to resolve it to specific Path values.
// Fast path: already resolved.
if (runtime_enabled_paths_ != Path::kNone) {
return runtime_enabled_paths_;
}
// Need to resolve now. Start by considering all paths enabled.
runtime_enabled_paths_ = kAllPaths;
// This mechanism is intended to be used for testing and benchmarking. For
// example, one can set RUY_FORCE_DISABLE_PATHS to Path::kAvx512 in order to
// evaluate AVX2 performance on an AVX-512 machine.
#ifdef RUY_FORCE_DISABLE_PATHS
runtime_enabled_paths_ = runtime_enabled_paths_ & ~(RUY_FORCE_DISABLE_PATHS);
#endif
#if RUY_PLATFORM(ARM)
// Now selectively disable paths that aren't supported on this machine.
if ((runtime_enabled_paths_ & Path::kNeonDotprod) != Path::kNone) {
if (!DetectDotprod()) {
runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kNeonDotprod;
// Sanity check.
RUY_DCHECK((runtime_enabled_paths_ & Path::kNeonDotprod) == Path::kNone);
}
}
#endif // RUY_PLATFORM(ARM)
#if RUY_PLATFORM(X86)
if ((runtime_enabled_paths_ & Path::kAvx2) != Path::kNone) {
if (!(HaveBuiltPathForAvx2() && DetectCpuAvx2())) {
runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kAvx2;
// Sanity check.
RUY_DCHECK((runtime_enabled_paths_ & Path::kAvx2) == Path::kNone);
}
}
if ((runtime_enabled_paths_ & Path::kAvx512) != Path::kNone) {
if (!(HaveBuiltPathForAvx512() && DetectCpuAvx512())) {
runtime_enabled_paths_ = runtime_enabled_paths_ & ~Path::kAvx512;
// Sanity check.
RUY_DCHECK((runtime_enabled_paths_ & Path::kAvx512) == Path::kNone);
}
}
#endif // RUY_PLATFORM(X86)
// Sanity check. We can't possibly have disabled all paths, as some paths
// are universally available (kReference, kStandardCpp).
RUY_DCHECK(runtime_enabled_paths_ != Path::kNone);
return runtime_enabled_paths_;
}
} // namespace ruy
<|endoftext|>
|
<commit_before>/*
*/
#include "lineFollowing.h"
#include "../control.h"
using namespace std;
using namespace cv;
void compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list);
void draw_lines(const Mat &image, const vector<Vec2f> &lines);
vector<Vec2f> condense_lines(vector<Vec2f> &lines);
void LineFollowing::detect_lines(Mat &original_frame, double scale_factor) {
Mat hsv;
Mat mask;
Mat image;
cvtColor(original_frame, hsv, CV_BGR2HSV); // Image is now HSV
Scalar lower(minH, minS, minV);
Scalar upper(maxH, maxS, maxV);
inRange(hsv, lower, upper, mask); // Create a mask of only the desired color
Canny(mask, mask, 50, 200, 3);
vector<Vec2f> lines;
HoughLines(mask, lines, 1, CV_PI / 180, 100, 0, 0);
printf("Adding in %d lines\n", (int) lines.size());
vector<Vec2f> condensed = condense_lines(lines);
draw_lines(original_frame, condensed);
}
vector<Vec2f> condense_lines(vector<Vec2f> lines) {
vector<Vec2f> condensed;
vector<Vec2f> tmp_list;
for (int i = 0; i < lines.size(); i++) {
if (lines[i][1] > CV_PI / 2) {
lines[i][1] -= CV_PI;
lines[i][0] *= -1;
}
else if (lines[i][1] < ((CV_PI / 2) * -1)) {
lines[i][1] += CV_PI;
lines[i][0] *= -1;
}
//put in order of theta, rho
swap(lines[i][0], lines[i][1]);
}
//Order from least to greatest theta
sort(lines.begin(), lines.end(),
[](const Vec2f &a, const Vec2f &b) {
return a[0] < b[0];
});
while (!lines.empty()) {
Vec2f to_manipulate = lines.front();
lines.erase(lines.begin());
if (tmp_list.empty()) {
tmp_list.push_back(to_manipulate);
continue;
} else {
if (abs(to_manipulate[0] - tmp_list.front()[0]) < 20 * (CV_PI / 180.0)) {
//The angles are similar
if (abs(to_manipulate[1] - tmp_list.front()[1]) < 50) {
//the distances are similar
tmp_list.push_back(to_manipulate);
continue;
}
} else {
//Need to clear out the tmp_list
compress_lines(condensed, tmp_list);
tmp_list.clear();
tmp_list.push_back(to_manipulate);
}
}
}
if (!tmp_list.empty()) {
compress_lines(condensed, tmp_list);
}
return condensed;
}
void draw_lines(const Mat &image, const vector<Vec2f> &lines) {
for (size_t i = 0; i < lines.size(); i++) {
float theta = lines[i][0], rho = lines[i][1];
// float rho = lines[i][0], theta = lines[i][1];
Point pt1, pt2;
double a = cos(theta), b = sin(theta);
double x0 = a * rho, y0 = b * rho;
pt1.x = cvRound(x0 + 1000 * (-b));
pt1.y = cvRound(y0 + 1000 * (a));
pt2.x = cvRound(x0 - 1000 * (-b));
pt2.y = cvRound(y0 - 1000 * (a));
line(image, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);
}
}
void compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list) {
Vec2f new_point;
float angle_sum = 0;
float rho_sum = 0;
for (int j = 0; j < tmp_list.size(); ++j) {
angle_sum += tmp_list[j][0];
rho_sum += tmp_list[j][1];
}
angle_sum /= tmp_list.size();
rho_sum /= tmp_list.size();
new_point[0] = angle_sum;
new_point[1] = rho_sum;
condensed.push_back(new_point);
}
LineFollowing::LineFollowing(Control *control) {
namedWindow("line_window", CV_WINDOW_NORMAL);
control_ptr = control;
minH = 50;
minS = 20;
minV = 150;
maxH = 125;
maxS = 100;
maxV = 255;
return;
}
void LineFollowing::close() {
return;
}
void LineFollowing::fly() {
control_ptr->velocities.vx = 0;
control_ptr->velocities.vy = 0;
control_ptr->velocities.vz = 0;
control_ptr->velocities.vr = 0;
detect_lines(control_ptr->image, 1);
return;
}
<commit_msg>fixes<commit_after>/*
*/
#include "lineFollowing.h"
#include "../control.h"
using namespace std;
using namespace cv;
void compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list);
void draw_lines(Mat &image, const vector<Vec2f> &lines);
vector<Vec2f> condense_lines(vector<Vec2f> lines);
void LineFollowing::detect_lines(Mat &original_frame, double scale_factor) {
Mat hsv;
Mat mask;
Mat image;
cvtColor(original_frame, hsv, CV_BGR2HSV); // Image is now HSV
Scalar lower(minH, minS, minV);
Scalar upper(maxH, maxS, maxV);
inRange(hsv, lower, upper, mask); // Create a mask of only the desired color
Canny(mask, mask, 50, 200, 3);
vector<Vec2f> lines;
HoughLines(mask, lines, 1, CV_PI / 180, 100, 0, 0);
printf("Adding in %d lines\n", (int) lines.size());
vector<Vec2f> condensed = condense_lines(lines);
draw_lines(original_frame, condensed);
}
vector<Vec2f> condense_lines(vector<Vec2f> lines) {
vector<Vec2f> condensed;
vector<Vec2f> tmp_list;
for (int i = 0; i < lines.size(); i++) {
if (lines[i][1] > CV_PI / 2) {
lines[i][1] -= CV_PI;
lines[i][0] *= -1;
}
else if (lines[i][1] < ((CV_PI / 2) * -1)) {
lines[i][1] += CV_PI;
lines[i][0] *= -1;
}
//put in order of theta, rho
swap(lines[i][0], lines[i][1]);
}
//Order from least to greatest theta
sort(lines.begin(), lines.end(),
[](const Vec2f &a, const Vec2f &b) {
return a[0] < b[0];
});
while (!lines.empty()) {
Vec2f to_manipulate = lines.front();
lines.erase(lines.begin());
if (tmp_list.empty()) {
tmp_list.push_back(to_manipulate);
continue;
} else {
if (abs(to_manipulate[0] - tmp_list.front()[0]) < 20 * (CV_PI / 180.0)) {
//The angles are similar
if (abs(to_manipulate[1] - tmp_list.front()[1]) < 50) {
//the distances are similar
tmp_list.push_back(to_manipulate);
continue;
}
} else {
//Need to clear out the tmp_list
compress_lines(condensed, tmp_list);
tmp_list.clear();
tmp_list.push_back(to_manipulate);
}
}
}
if (!tmp_list.empty()) {
compress_lines(condensed, tmp_list);
}
return condensed;
}
void draw_lines(Mat &image, const vector<Vec2f> &lines) {
for (size_t i = 0; i < lines.size(); i++) {
float theta = lines[i][0], rho = lines[i][1];
// float rho = lines[i][0], theta = lines[i][1];
Point pt1, pt2;
double a = cos(theta), b = sin(theta);
double x0 = a * rho, y0 = b * rho;
pt1.x = cvRound(x0 + 1000 * (-b));
pt1.y = cvRound(y0 + 1000 * (a));
pt2.x = cvRound(x0 - 1000 * (-b));
pt2.y = cvRound(y0 - 1000 * (a));
line(image, pt1, pt2, Scalar(0, 0, 255), 3, CV_AA);
}
}
void compress_lines(vector<Vec2f> &condensed, const vector<Vec2f> &tmp_list) {
Vec2f new_point;
float angle_sum = 0;
float rho_sum = 0;
for (int j = 0; j < tmp_list.size(); ++j) {
angle_sum += tmp_list[j][0];
rho_sum += tmp_list[j][1];
}
angle_sum /= tmp_list.size();
rho_sum /= tmp_list.size();
new_point[0] = angle_sum;
new_point[1] = rho_sum;
condensed.push_back(new_point);
}
LineFollowing::LineFollowing(Control *control) {
namedWindow("line_window", CV_WINDOW_NORMAL);
control_ptr = control;
minH = 50;
minS = 20;
minV = 150;
maxH = 125;
maxS = 100;
maxV = 255;
return;
}
void LineFollowing::close() {
return;
}
void LineFollowing::fly() {
control_ptr->velocities.vx = 0;
control_ptr->velocities.vy = 0;
control_ptr->velocities.vz = 0;
control_ptr->velocities.vr = 0;
detect_lines(control_ptr->image, 1);
return;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: namebuff.cxx,v $
*
* $Revision: 1.23 $
*
* last change: $Author: kz $ $Date: 2006-07-21 11:50:23 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include "namebuff.hxx"
#include <tools/urlobj.hxx>
#include <string.h>
#include "rangenam.hxx"
#include "document.hxx"
#include "compiler.hxx"
#include "scextopt.hxx"
#include "root.hxx"
#include "tokstack.hxx"
#ifndef SC_XLTOOLS_HXX
#include "xltools.hxx"
#endif
#ifndef SC_XIROOT_HXX
#include "xiroot.hxx"
#endif
UINT32 StringHashEntry::MakeHashCode( const String& r )
{
register UINT32 n = 0;
const sal_Unicode* pAkt = r.GetBuffer();
register sal_Unicode cAkt = *pAkt;
while( cAkt )
{
n *= 70;
n += ( UINT32 ) cAkt;
pAkt++;
cAkt = *pAkt;
}
return n;
}
NameBuffer::~NameBuffer()
{
register StringHashEntry* pDel = ( StringHashEntry* ) List::First();
while( pDel )
{
delete pDel;
pDel = ( StringHashEntry* ) List::Next();
}
}
//void NameBuffer::operator <<( const SpString &rNewString )
void NameBuffer::operator <<( const String &rNewString )
{
DBG_ASSERT( Count() + nBase < 0xFFFF,
"*NameBuffer::GetLastIndex(): Ich hab' die Nase voll!" );
List::Insert( new StringHashEntry( rNewString ), LIST_APPEND );
}
void NameBuffer::Reset()
{
register StringHashEntry* pDel = ( StringHashEntry* ) List::First();
while( pDel )
{
delete pDel;
pDel = ( StringHashEntry* ) List::Next();
}
Clear();
}
BOOL NameBuffer::Find( const sal_Char* pRefName, UINT16& rIndex )
{
StringHashEntry aRefEntry( String::CreateFromAscii( pRefName ) );
register StringHashEntry* pFind = ( StringHashEntry* ) List::First();
register UINT16 nCnt = nBase;
while( pFind )
{
if( *pFind == aRefEntry )
{
rIndex = nCnt;
return TRUE;
}
pFind = ( StringHashEntry* ) List::Next();
nCnt++;
}
return FALSE;
}
#ifdef DBG_UTIL
UINT16 nShrCnt;
#endif
size_t
ShrfmlaBuffer::ScAddressHashFunc::operator() (const ScAddress &addr) const
{
// Use something simple, it is just a hash.
return (static_cast <UINT16> (addr.Row()) << 0) |
(static_cast <UINT8> (addr.Col()) << 16) |
(static_cast <UINT8> (addr.Tab()) << 24);
}
static const UINT16 nBase = 16384; // Range~ und Shared~ Dingens mit jeweils der Haelfte Ids
ShrfmlaBuffer::ShrfmlaBuffer( RootData* pRD ) :
ExcRoot( pRD ),
cur_index (nBase)
{
#ifdef DBG_UTIL
nShrCnt = 0;
#endif
}
ShrfmlaBuffer::~ShrfmlaBuffer()
{
}
void ShrfmlaBuffer::Store( const ScRange& rRange, const ScTokenArray& rToken )
{
String aName( CreateName( rRange.aStart ) );
DBG_ASSERT( cur_index <= 0xFFFF, "*ShrfmlaBuffer::Store(): Gleich wird mir schlecht...!" );
ScRangeData* pData = new ScRangeData( pExcRoot->pIR->GetDocPtr(), aName, rToken, rRange.aStart, RT_SHARED );
pData->SetIndex (cur_index);
pExcRoot->pIR->GetNamedRanges().Insert( pData );
index_hash[rRange.aStart] = cur_index;
index_list.push_front (rRange);
cur_index++;
}
UINT16 ShrfmlaBuffer::Find( const ScAddress & aAddr ) const
{
ShrfmlaHash::const_iterator hash = index_hash.find (aAddr);
if (hash != index_hash.end())
return hash->second;
// It was not hashed on the top left corner ? do a brute force search
unsigned int ind = nBase;
for (ShrfmlaList::const_iterator ptr = index_list.end(); ptr != index_list.begin() ; ind++)
if ((--ptr)->In (aAddr))
return ind;
return cur_index;
}
#define SHRFMLA_BASENAME "SHARED_FORMULA_"
String ShrfmlaBuffer::CreateName( const ScRange& r )
{
String aName( RTL_CONSTASCII_USTRINGPARAM( SHRFMLA_BASENAME ) );
aName += String::CreateFromInt32( r.aStart.Col() );
aName.Append( '_' );
aName += String::CreateFromInt32( r.aStart.Row() );
aName.Append( '_' );
aName += String::CreateFromInt32( r.aEnd.Col() );
aName.Append( '_' );
aName += String::CreateFromInt32( r.aEnd.Row() );
aName.Append( '_' );
aName += String::CreateFromInt32( r.aStart.Tab() );
return aName;
}
ExtSheetBuffer::~ExtSheetBuffer()
{
Cont *pAkt = ( Cont * ) List::First();
while( pAkt )
{
delete pAkt;
pAkt = ( Cont * ) List::Next();
}
}
void ExtSheetBuffer::Add( const String& rFPAN, const String& rTN, const BOOL bSWB )
{
List::Insert( new Cont( rFPAN, rTN, bSWB ), LIST_APPEND );
}
BOOL ExtSheetBuffer::GetScTabIndex( UINT16 nExcIndex, UINT16& rScIndex )
{
DBG_ASSERT( nExcIndex,
"*ExtSheetBuffer::GetScTabIndex(): Sheet-Index == 0!" );
nExcIndex--;
Cont* pCur = ( Cont * ) List::GetObject( nExcIndex );
UINT16& rTabNum = pCur->nTabNum;
if( pCur )
{
if( rTabNum < 0xFFFD )
{
rScIndex = rTabNum;
return TRUE;
}
if( rTabNum == 0xFFFF )
{// neue Tabelle erzeugen
SCTAB nNewTabNum;
if( pCur->bSWB )
{// Tabelle ist im selben Workbook!
if( pExcRoot->pIR->GetDoc().GetTable( pCur->aTab, nNewTabNum ) )
{
rScIndex = rTabNum = static_cast<UINT16>(nNewTabNum);
return TRUE;
}
else
rTabNum = 0xFFFD;
}
else if( pExcRoot->pIR->GetDocShell() )
{// Tabelle ist 'echt' extern
if( pExcRoot->pIR->GetExtDocOptions().GetDocSettings().mnLinkCnt == 0 )
{
String aURL( ScGlobal::GetAbsDocName( pCur->aFile,
pExcRoot->pIR->GetDocShell() ) );
String aTabName( ScGlobal::GetDocTabName( aURL, pCur->aTab ) );
if( pExcRoot->pIR->GetDoc().LinkExternalTab( nNewTabNum, aTabName, aURL, pCur->aTab ) )
{
rScIndex = rTabNum = static_cast<UINT16>(nNewTabNum);
return TRUE;
}
else
rTabNum = 0xFFFE; // Tabelle einmal nicht angelegt -> wird
// wohl auch nicht mehr gehen...
}
else
rTabNum = 0xFFFE;
}
}
}
return FALSE;
}
BOOL ExtSheetBuffer::IsLink( const UINT16 nExcIndex ) const
{
DBG_ASSERT( nExcIndex > 0, "*ExtSheetBuffer::IsLink(): Index muss >0 sein!" );
Cont* pRet = ( Cont * ) List::GetObject( nExcIndex - 1 );
if( pRet )
return pRet->bLink;
else
return FALSE;
}
BOOL ExtSheetBuffer::GetLink( const UINT16 nExcIndex, String& rAppl, String& rDoc ) const
{
DBG_ASSERT( nExcIndex > 0, "*ExtSheetBuffer::GetLink(): Index muss >0 sein!" );
Cont* pRet = ( Cont * ) List::GetObject( nExcIndex - 1 );
if( pRet )
{
rAppl = pRet->aFile;
rDoc = pRet->aTab;
return TRUE;
}
else
return FALSE;
}
BOOL ExtSheetBuffer::IsExternal( UINT16 nExcIndex ) const
{
DBG_ASSERT( nExcIndex > 0, "*ExtSheetBuffer::IsExternal(): Index muss >0 sein!" );
Cont* pRet = ( Cont * ) List::GetObject( nExcIndex - 1 );
if( pRet )
return !pRet->bSWB;
else
return FALSE;
}
void ExtSheetBuffer::Reset( void )
{
Cont *pAkt = ( Cont * ) List::First();
while( pAkt )
{
delete pAkt;
pAkt = ( Cont * ) List::Next();
}
List::Clear();
}
BOOL ExtName::IsDDE( void ) const
{
return ( nFlags & 0x0001 ) != 0;
}
BOOL ExtName::IsOLE( void ) const
{
return ( nFlags & 0x0002 ) != 0;
}
BOOL ExtName::IsName( void ) const
{
return ( nFlags & 0x0004 ) != 0;
}
const sal_Char* ExtNameBuff::pJoostTest = "Joost ist immer noch doof!";
ExtNameBuff::~ExtNameBuff()
{
ExtName* pDel = ( ExtName* ) List::First();
while( pDel )
{
delete pDel;
pDel = ( ExtName* ) List::Next();
}
}
void ExtNameBuff::AddDDE( const String& rName )
{
ExtName* pNew = new ExtName( rName );
pNew->nFlags = 0x0001;
List::Insert( pNew, LIST_APPEND );
}
void ExtNameBuff::AddOLE( const String& rName, UINT32 nStorageId )
{
ExtName* pNew = new ExtName( rName );
pNew->nFlags = 0x0002;
pNew->nStorageId = nStorageId;
List::Insert( pNew, LIST_APPEND );
}
void ExtNameBuff::AddName( const String& rName )
{
ExtName* pNew = new ExtName( pExcRoot->pIR->GetScAddInName( rName ) );
pNew->nFlags = 0x0004;
List::Insert( pNew, LIST_APPEND );
}
const ExtName* ExtNameBuff::GetName( const UINT16 nExcelIndex ) const
{
DBG_ASSERT( nExcelIndex > 0, "*ExtNameBuff::GetName(): Index kann nur >0 sein!" );
return ( const ExtName* ) List::GetObject( nExcelIndex - 1 );
}
void ExtNameBuff::Reset( void )
{
ExtName* pDel = ( ExtName* ) List::First();
while( pDel )
{
delete pDel;
pDel = ( ExtName* ) List::Next();
}
sal_Char cTmp = *pJoostTest;
cTmp++;
List::Clear();
}
<commit_msg>INTEGRATION: CWS calcwarnings (1.23.110); FILE MERGED 2006/12/01 14:42:24 dr 1.23.110.1: #i69284# remove compiler warnings for wntmsci10<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: namebuff.cxx,v $
*
* $Revision: 1.24 $
*
* last change: $Author: vg $ $Date: 2007-02-27 12:23:43 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include "namebuff.hxx"
#include <tools/urlobj.hxx>
#include <string.h>
#include "rangenam.hxx"
#include "document.hxx"
#include "compiler.hxx"
#include "scextopt.hxx"
#include "root.hxx"
#include "tokstack.hxx"
#ifndef SC_XLTOOLS_HXX
#include "xltools.hxx"
#endif
#ifndef SC_XIROOT_HXX
#include "xiroot.hxx"
#endif
UINT32 StringHashEntry::MakeHashCode( const String& r )
{
register UINT32 n = 0;
const sal_Unicode* pAkt = r.GetBuffer();
register sal_Unicode cAkt = *pAkt;
while( cAkt )
{
n *= 70;
n += ( UINT32 ) cAkt;
pAkt++;
cAkt = *pAkt;
}
return n;
}
NameBuffer::~NameBuffer()
{
register StringHashEntry* pDel = ( StringHashEntry* ) List::First();
while( pDel )
{
delete pDel;
pDel = ( StringHashEntry* ) List::Next();
}
}
//void NameBuffer::operator <<( const SpString &rNewString )
void NameBuffer::operator <<( const String &rNewString )
{
DBG_ASSERT( Count() + nBase < 0xFFFF,
"*NameBuffer::GetLastIndex(): Ich hab' die Nase voll!" );
List::Insert( new StringHashEntry( rNewString ), LIST_APPEND );
}
void NameBuffer::Reset()
{
register StringHashEntry* pDel = ( StringHashEntry* ) List::First();
while( pDel )
{
delete pDel;
pDel = ( StringHashEntry* ) List::Next();
}
Clear();
}
BOOL NameBuffer::Find( const sal_Char* pRefName, UINT16& rIndex )
{
StringHashEntry aRefEntry( String::CreateFromAscii( pRefName ) );
register StringHashEntry* pFind = ( StringHashEntry* ) List::First();
register UINT16 nCnt = nBase;
while( pFind )
{
if( *pFind == aRefEntry )
{
rIndex = nCnt;
return TRUE;
}
pFind = ( StringHashEntry* ) List::Next();
nCnt++;
}
return FALSE;
}
#ifdef DBG_UTIL
UINT16 nShrCnt;
#endif
size_t ShrfmlaBuffer::ScAddressHashFunc::operator() (const ScAddress &addr) const
{
// Use something simple, it is just a hash.
return (static_cast <UINT16> (addr.Row()) << 0) |
(static_cast <UINT8> (addr.Col()) << 16) |
(static_cast <UINT8> (addr.Tab()) << 24);
}
const size_t nBase = 16384; // Range~ und Shared~ Dingens mit jeweils der Haelfte Ids
ShrfmlaBuffer::ShrfmlaBuffer( RootData* pRD ) :
ExcRoot( pRD ),
mnCurrIdx (nBase)
{
#ifdef DBG_UTIL
nShrCnt = 0;
#endif
}
ShrfmlaBuffer::~ShrfmlaBuffer()
{
}
void ShrfmlaBuffer::Store( const ScRange& rRange, const ScTokenArray& rToken )
{
String aName( CreateName( rRange.aStart ) );
DBG_ASSERT( mnCurrIdx <= 0xFFFF, "*ShrfmlaBuffer::Store(): Gleich wird mir schlecht...!" );
ScRangeData* pData = new ScRangeData( pExcRoot->pIR->GetDocPtr(), aName, rToken, rRange.aStart, RT_SHARED );
pData->SetIndex( static_cast< USHORT >( mnCurrIdx ) );
pExcRoot->pIR->GetNamedRanges().Insert( pData );
index_hash[rRange.aStart] = static_cast< USHORT >( mnCurrIdx );
index_list.push_front (rRange);
++mnCurrIdx;
}
USHORT ShrfmlaBuffer::Find( const ScAddress & aAddr ) const
{
ShrfmlaHash::const_iterator hash = index_hash.find (aAddr);
if (hash != index_hash.end())
return hash->second;
// It was not hashed on the top left corner ? do a brute force search
unsigned int ind = nBase;
for (ShrfmlaList::const_iterator ptr = index_list.end(); ptr != index_list.begin() ; ind++)
if ((--ptr)->In (aAddr))
return static_cast< USHORT >( ind );
return static_cast< USHORT >( mnCurrIdx );
}
#define SHRFMLA_BASENAME "SHARED_FORMULA_"
String ShrfmlaBuffer::CreateName( const ScRange& r )
{
String aName( RTL_CONSTASCII_USTRINGPARAM( SHRFMLA_BASENAME ) );
aName += String::CreateFromInt32( r.aStart.Col() );
aName.Append( '_' );
aName += String::CreateFromInt32( r.aStart.Row() );
aName.Append( '_' );
aName += String::CreateFromInt32( r.aEnd.Col() );
aName.Append( '_' );
aName += String::CreateFromInt32( r.aEnd.Row() );
aName.Append( '_' );
aName += String::CreateFromInt32( r.aStart.Tab() );
return aName;
}
ExtSheetBuffer::~ExtSheetBuffer()
{
Cont *pAkt = ( Cont * ) List::First();
while( pAkt )
{
delete pAkt;
pAkt = ( Cont * ) List::Next();
}
}
void ExtSheetBuffer::Add( const String& rFPAN, const String& rTN, const BOOL bSWB )
{
List::Insert( new Cont( rFPAN, rTN, bSWB ), LIST_APPEND );
}
BOOL ExtSheetBuffer::GetScTabIndex( UINT16 nExcIndex, UINT16& rScIndex )
{
DBG_ASSERT( nExcIndex,
"*ExtSheetBuffer::GetScTabIndex(): Sheet-Index == 0!" );
nExcIndex--;
Cont* pCur = ( Cont * ) List::GetObject( nExcIndex );
UINT16& rTabNum = pCur->nTabNum;
if( pCur )
{
if( rTabNum < 0xFFFD )
{
rScIndex = rTabNum;
return TRUE;
}
if( rTabNum == 0xFFFF )
{// neue Tabelle erzeugen
SCTAB nNewTabNum;
if( pCur->bSWB )
{// Tabelle ist im selben Workbook!
if( pExcRoot->pIR->GetDoc().GetTable( pCur->aTab, nNewTabNum ) )
{
rScIndex = rTabNum = static_cast<UINT16>(nNewTabNum);
return TRUE;
}
else
rTabNum = 0xFFFD;
}
else if( pExcRoot->pIR->GetDocShell() )
{// Tabelle ist 'echt' extern
if( pExcRoot->pIR->GetExtDocOptions().GetDocSettings().mnLinkCnt == 0 )
{
String aURL( ScGlobal::GetAbsDocName( pCur->aFile,
pExcRoot->pIR->GetDocShell() ) );
String aTabName( ScGlobal::GetDocTabName( aURL, pCur->aTab ) );
if( pExcRoot->pIR->GetDoc().LinkExternalTab( nNewTabNum, aTabName, aURL, pCur->aTab ) )
{
rScIndex = rTabNum = static_cast<UINT16>(nNewTabNum);
return TRUE;
}
else
rTabNum = 0xFFFE; // Tabelle einmal nicht angelegt -> wird
// wohl auch nicht mehr gehen...
}
else
rTabNum = 0xFFFE;
}
}
}
return FALSE;
}
BOOL ExtSheetBuffer::IsLink( const UINT16 nExcIndex ) const
{
DBG_ASSERT( nExcIndex > 0, "*ExtSheetBuffer::IsLink(): Index muss >0 sein!" );
Cont* pRet = ( Cont * ) List::GetObject( nExcIndex - 1 );
if( pRet )
return pRet->bLink;
else
return FALSE;
}
BOOL ExtSheetBuffer::GetLink( const UINT16 nExcIndex, String& rAppl, String& rDoc ) const
{
DBG_ASSERT( nExcIndex > 0, "*ExtSheetBuffer::GetLink(): Index muss >0 sein!" );
Cont* pRet = ( Cont * ) List::GetObject( nExcIndex - 1 );
if( pRet )
{
rAppl = pRet->aFile;
rDoc = pRet->aTab;
return TRUE;
}
else
return FALSE;
}
BOOL ExtSheetBuffer::IsExternal( UINT16 nExcIndex ) const
{
DBG_ASSERT( nExcIndex > 0, "*ExtSheetBuffer::IsExternal(): Index muss >0 sein!" );
Cont* pRet = ( Cont * ) List::GetObject( nExcIndex - 1 );
if( pRet )
return !pRet->bSWB;
else
return FALSE;
}
void ExtSheetBuffer::Reset( void )
{
Cont *pAkt = ( Cont * ) List::First();
while( pAkt )
{
delete pAkt;
pAkt = ( Cont * ) List::Next();
}
List::Clear();
}
BOOL ExtName::IsDDE( void ) const
{
return ( nFlags & 0x0001 ) != 0;
}
BOOL ExtName::IsOLE( void ) const
{
return ( nFlags & 0x0002 ) != 0;
}
BOOL ExtName::IsName( void ) const
{
return ( nFlags & 0x0004 ) != 0;
}
const sal_Char* ExtNameBuff::pJoostTest = "Joost ist immer noch doof!";
ExtNameBuff::~ExtNameBuff()
{
ExtName* pDel = ( ExtName* ) List::First();
while( pDel )
{
delete pDel;
pDel = ( ExtName* ) List::Next();
}
}
void ExtNameBuff::AddDDE( const String& rName )
{
ExtName* pNew = new ExtName( rName );
pNew->nFlags = 0x0001;
List::Insert( pNew, LIST_APPEND );
}
void ExtNameBuff::AddOLE( const String& rName, UINT32 nStorageId )
{
ExtName* pNew = new ExtName( rName );
pNew->nFlags = 0x0002;
pNew->nStorageId = nStorageId;
List::Insert( pNew, LIST_APPEND );
}
void ExtNameBuff::AddName( const String& rName )
{
ExtName* pNew = new ExtName( pExcRoot->pIR->GetScAddInName( rName ) );
pNew->nFlags = 0x0004;
List::Insert( pNew, LIST_APPEND );
}
const ExtName* ExtNameBuff::GetName( const UINT16 nExcelIndex ) const
{
DBG_ASSERT( nExcelIndex > 0, "*ExtNameBuff::GetName(): Index kann nur >0 sein!" );
return ( const ExtName* ) List::GetObject( nExcelIndex - 1 );
}
void ExtNameBuff::Reset( void )
{
ExtName* pDel = ( ExtName* ) List::First();
while( pDel )
{
delete pDel;
pDel = ( ExtName* ) List::Next();
}
sal_Char cTmp = *pJoostTest;
cTmp++;
List::Clear();
}
<|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 <sstream>
#include <string>
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/browser/automation/url_request_failed_dns_job.h"
#include "chrome/browser/automation/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request_unittest.h"
namespace {
class ResourceDispatcherTest : public UITest {
public:
void CheckTitleTest(const std::wstring& file,
const std::wstring& expected_title) {
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file));
const int kCheckDelayMs = 100;
int max_wait_time = 5000;
while (max_wait_time > 0) {
max_wait_time -= kCheckDelayMs;
PlatformThread::Sleep(kCheckDelayMs);
if (expected_title == GetActiveTabTitle())
break;
}
EXPECT_EQ(expected_title, GetActiveTabTitle());
}
protected:
ResourceDispatcherTest() : UITest() {
dom_automation_enabled_ = true;
}
};
TEST_F(ResourceDispatcherTest, SniffHTMLWithNoContentType) {
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0");
}
TEST_F(ResourceDispatcherTest, RespectNoSniffDirective) {
CheckTitleTest(L"nosniff-test.html", L"");
}
TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromTextPlain) {
CheckTitleTest(L"content-sniffer-test1.html", L"");
}
TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromImageGIF) {
CheckTitleTest(L"content-sniffer-test2.html", L"");
}
TEST_F(ResourceDispatcherTest, SniffNoContentTypeNoData) {
CheckTitleTest(L"content-sniffer-test3.html",
L"Content Sniffer Test 3");
PlatformThread::Sleep(sleep_timeout_ms() * 2);
EXPECT_EQ(1, GetTabCount());
// Make sure the download shelf is not showing.
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
bool visible = false;
ASSERT_TRUE(browser->IsShelfVisible(&visible));
EXPECT_FALSE(visible);
}
TEST_F(ResourceDispatcherTest, ContentDispositionEmpty) {
CheckTitleTest(L"content-disposition-empty.html", L"success");
}
TEST_F(ResourceDispatcherTest, ContentDispositionInline) {
CheckTitleTest(L"content-disposition-inline.html", L"success");
}
// Test for bug #1091358.
TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest) {
const wchar_t kDocRoot[] = L"chrome/test/data";
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(kDocRoot, NULL);
ASSERT_TRUE(NULL != server.get());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
EXPECT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
tab->NavigateToURL(server->TestServerPageW(
L"files/sync_xmlhttprequest.html"));
// Let's check the XMLHttpRequest ran successfully.
bool success = false;
EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
L"window.domAutomationController.send(DidSyncRequestSucceed());",
&success));
EXPECT_TRUE(success);
}
TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest_Disallowed) {
const wchar_t kDocRoot[] = L"chrome/test/data";
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(kDocRoot, NULL);
ASSERT_TRUE(NULL != server.get());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
EXPECT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
tab->NavigateToURL(server->TestServerPageW(
L"files/sync_xmlhttprequest_disallowed.html"));
// Let's check the XMLHttpRequest ran successfully.
bool success = false;
EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
L"window.domAutomationController.send(DidSucceed());",
&success));
EXPECT_TRUE(success);
}
// Test for bug #1159553 -- A synchronous xhr (whose content-type is
// downloadable) would trigger download and hang the renderer process,
// if executed while navigating to a new page.
TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest_DuringUnload) {
const wchar_t kDocRoot[] = L"chrome/test/data";
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(kDocRoot, NULL);
ASSERT_TRUE(NULL != server.get());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
EXPECT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
tab->NavigateToURL(
server->TestServerPageW(L"files/sync_xmlhttprequest_during_unload.html"));
// Confirm that the page has loaded (since it changes its title during load).
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"sync xhr on unload", tab_title);
// Navigate to a new page, to dispatch unload event and trigger xhr.
// (the bug would make this step hang the renderer).
bool timed_out = false;
tab->NavigateToURLWithTimeout(server->TestServerPageW(L"files/title2.html"),
action_max_timeout_ms(),
&timed_out);
EXPECT_FALSE(timed_out);
// Check that the new page got loaded, and that no download was triggered.
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"Title Of Awesomeness", tab_title);
bool shelf_is_visible = false;
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
EXPECT_TRUE(browser->IsShelfVisible(&shelf_is_visible));
EXPECT_FALSE(shelf_is_visible);
}
// Tests that onunload is run for cross-site requests. (Bug 1114994)
TEST_F(ResourceDispatcherTest, CrossSiteOnunloadCookie) {
const wchar_t kDocRoot[] = L"chrome/test/data";
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(kDocRoot, NULL);
ASSERT_TRUE(NULL != server.get());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
EXPECT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
GURL url(server->TestServerPageW(L"files/onunload_cookie.html"));
tab->NavigateToURL(url);
// Confirm that the page has loaded (since it changes its title during load).
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"set cookie on unload", tab_title);
// Navigate to a new cross-site page, to dispatch unload event and set the
// cookie.
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0");
// Check that the cookie was set.
std::string value_result;
ASSERT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
ASSERT_FALSE(value_result.empty());
ASSERT_STREQ("foo", value_result.c_str());
}
#if !defined(OS_MAC)
// Tests that the onbeforeunload and onunload logic is shortcutted if the old
// renderer is gone. In that case, we don't want to wait for the old renderer
// to run the handlers.
// TODO(pinkerton): We need to disable this because the crash causes
// the OS CrashReporter process to kick in to analyze the poor dead renderer.
// Unfortunately, if the app isn't stripped of debug symbols, this takes about
// five minutes to complete and isn't conducive to quick turnarounds. As we
// don't currently strip the app on the build bots, this is bad times.
TEST_F(ResourceDispatcherTest, CrossSiteAfterCrash) {
// This test only works in multi-process mode
if (in_process_renderer())
return;
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
EXPECT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
// Cause the renderer to crash.
// TODO(albertb): We need to disable this on Linux since
// crash_service.exe hasn't been ported yet.
#if defined(OS_WIN)
expected_crashes_ = 1;
#endif
tab->NavigateToURLAsync(GURL("about:crash"));
// Wait for browser to notice the renderer crash.
PlatformThread::Sleep(sleep_timeout_ms());
// Navigate to a new cross-site page. The browser should not wait around for
// the old renderer's on{before}unload handlers to run.
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0");
}
#endif
// Tests that cross-site navigations work when the new page does not go through
// the BufferedEventHandler (e.g., non-http{s} URLs). (Bug 1225872)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationNonBuffered) {
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
EXPECT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
// Start with an HTTP page.
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0");
// Now load a file:// page, which does not use the BufferedEventHandler.
// Make sure that the page loads and displays a title, and doesn't get stuck.
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("title2.html");
bool timed_out = false;
tab->NavigateToURLWithTimeout(net::FilePathToFileURL(test_file),
action_max_timeout_ms(),
&timed_out);
EXPECT_FALSE(timed_out);
EXPECT_EQ(L"Title Of Awesomeness", GetActiveTabTitle());
}
// Tests that a cross-site navigation to an error page (resulting in the link
// doctor page) still runs the onunload handler and can support navigations
// away from the link doctor page. (Bug 1235537)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationErrorPage) {
const wchar_t kDocRoot[] = L"chrome/test/data";
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(kDocRoot, NULL);
ASSERT_TRUE(NULL != server.get());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
EXPECT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
GURL url(server->TestServerPageW(L"files/onunload_cookie.html"));
tab->NavigateToURL(url);
// Confirm that the page has loaded (since it changes its title during load).
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"set cookie on unload", tab_title);
// Navigate to a new cross-site URL that results in an error page. We must
// wait for the error page to update the title.
// TODO(creis): If this causes crashes or hangs, it might be for the same
// reason as ErrorPageTest::DNSError. See bug 1199491.
tab->NavigateToURL(GURL(URLRequestFailedDnsJob::kTestUrl));
for (int i = 0; i < 10; ++i) {
PlatformThread::Sleep(sleep_timeout_ms());
if (GetActiveTabTitle() != L"set cookie on unload") {
// Success, bail out.
break;
}
}
EXPECT_NE(L"set cookie on unload", GetActiveTabTitle());
// Check that the cookie was set, meaning that the onunload handler ran.
std::string value_result;
EXPECT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
EXPECT_FALSE(value_result.empty());
EXPECT_STREQ("foo", value_result.c_str());
// Check that renderer-initiated navigations still work. In a previous bug,
// the ResourceDispatcherHost would think that such navigations were
// cross-site, because we didn't clean up from the previous request. Since
// TabContents was in the NORMAL state, it would ignore the attempt to run
// the onunload handler, and the navigation would fail.
// (Test by redirecting to javascript:window.location='someURL'.)
GURL test_url(server->TestServerPageW(L"files/title2.html"));
std::string redirect_url = "javascript:window.location='" +
test_url.possibly_invalid_spec() + "'";
tab->NavigateToURLAsync(GURL(redirect_url));
// Wait for JavaScript redirect to happen.
PlatformThread::Sleep(sleep_timeout_ms() * 3);
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"Title Of Awesomeness", tab_title);
}
} // namespace
<commit_msg>s/OS_MAC/OS_MACOSX/<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 <sstream>
#include <string>
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "chrome/browser/automation/url_request_failed_dns_job.h"
#include "chrome/browser/automation/url_request_mock_http_job.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "net/base/net_util.h"
#include "net/url_request/url_request_unittest.h"
namespace {
class ResourceDispatcherTest : public UITest {
public:
void CheckTitleTest(const std::wstring& file,
const std::wstring& expected_title) {
NavigateToURL(URLRequestMockHTTPJob::GetMockUrl(file));
const int kCheckDelayMs = 100;
int max_wait_time = 5000;
while (max_wait_time > 0) {
max_wait_time -= kCheckDelayMs;
PlatformThread::Sleep(kCheckDelayMs);
if (expected_title == GetActiveTabTitle())
break;
}
EXPECT_EQ(expected_title, GetActiveTabTitle());
}
protected:
ResourceDispatcherTest() : UITest() {
dom_automation_enabled_ = true;
}
};
TEST_F(ResourceDispatcherTest, SniffHTMLWithNoContentType) {
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0");
}
TEST_F(ResourceDispatcherTest, RespectNoSniffDirective) {
CheckTitleTest(L"nosniff-test.html", L"");
}
TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromTextPlain) {
CheckTitleTest(L"content-sniffer-test1.html", L"");
}
TEST_F(ResourceDispatcherTest, DoNotSniffHTMLFromImageGIF) {
CheckTitleTest(L"content-sniffer-test2.html", L"");
}
TEST_F(ResourceDispatcherTest, SniffNoContentTypeNoData) {
CheckTitleTest(L"content-sniffer-test3.html",
L"Content Sniffer Test 3");
PlatformThread::Sleep(sleep_timeout_ms() * 2);
EXPECT_EQ(1, GetTabCount());
// Make sure the download shelf is not showing.
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
bool visible = false;
ASSERT_TRUE(browser->IsShelfVisible(&visible));
EXPECT_FALSE(visible);
}
TEST_F(ResourceDispatcherTest, ContentDispositionEmpty) {
CheckTitleTest(L"content-disposition-empty.html", L"success");
}
TEST_F(ResourceDispatcherTest, ContentDispositionInline) {
CheckTitleTest(L"content-disposition-inline.html", L"success");
}
// Test for bug #1091358.
TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest) {
const wchar_t kDocRoot[] = L"chrome/test/data";
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(kDocRoot, NULL);
ASSERT_TRUE(NULL != server.get());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
EXPECT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
tab->NavigateToURL(server->TestServerPageW(
L"files/sync_xmlhttprequest.html"));
// Let's check the XMLHttpRequest ran successfully.
bool success = false;
EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
L"window.domAutomationController.send(DidSyncRequestSucceed());",
&success));
EXPECT_TRUE(success);
}
TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest_Disallowed) {
const wchar_t kDocRoot[] = L"chrome/test/data";
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(kDocRoot, NULL);
ASSERT_TRUE(NULL != server.get());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
EXPECT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
tab->NavigateToURL(server->TestServerPageW(
L"files/sync_xmlhttprequest_disallowed.html"));
// Let's check the XMLHttpRequest ran successfully.
bool success = false;
EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
L"window.domAutomationController.send(DidSucceed());",
&success));
EXPECT_TRUE(success);
}
// Test for bug #1159553 -- A synchronous xhr (whose content-type is
// downloadable) would trigger download and hang the renderer process,
// if executed while navigating to a new page.
TEST_F(ResourceDispatcherTest, SyncXMLHttpRequest_DuringUnload) {
const wchar_t kDocRoot[] = L"chrome/test/data";
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(kDocRoot, NULL);
ASSERT_TRUE(NULL != server.get());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
EXPECT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
tab->NavigateToURL(
server->TestServerPageW(L"files/sync_xmlhttprequest_during_unload.html"));
// Confirm that the page has loaded (since it changes its title during load).
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"sync xhr on unload", tab_title);
// Navigate to a new page, to dispatch unload event and trigger xhr.
// (the bug would make this step hang the renderer).
bool timed_out = false;
tab->NavigateToURLWithTimeout(server->TestServerPageW(L"files/title2.html"),
action_max_timeout_ms(),
&timed_out);
EXPECT_FALSE(timed_out);
// Check that the new page got loaded, and that no download was triggered.
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"Title Of Awesomeness", tab_title);
bool shelf_is_visible = false;
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
EXPECT_TRUE(browser->IsShelfVisible(&shelf_is_visible));
EXPECT_FALSE(shelf_is_visible);
}
// Tests that onunload is run for cross-site requests. (Bug 1114994)
TEST_F(ResourceDispatcherTest, CrossSiteOnunloadCookie) {
const wchar_t kDocRoot[] = L"chrome/test/data";
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(kDocRoot, NULL);
ASSERT_TRUE(NULL != server.get());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
EXPECT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
GURL url(server->TestServerPageW(L"files/onunload_cookie.html"));
tab->NavigateToURL(url);
// Confirm that the page has loaded (since it changes its title during load).
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"set cookie on unload", tab_title);
// Navigate to a new cross-site page, to dispatch unload event and set the
// cookie.
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0");
// Check that the cookie was set.
std::string value_result;
ASSERT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
ASSERT_FALSE(value_result.empty());
ASSERT_STREQ("foo", value_result.c_str());
}
#if !defined(OS_MACOSX)
// Tests that the onbeforeunload and onunload logic is shortcutted if the old
// renderer is gone. In that case, we don't want to wait for the old renderer
// to run the handlers.
// TODO(pinkerton): We need to disable this because the crash causes
// the OS CrashReporter process to kick in to analyze the poor dead renderer.
// Unfortunately, if the app isn't stripped of debug symbols, this takes about
// five minutes to complete and isn't conducive to quick turnarounds. As we
// don't currently strip the app on the build bots, this is bad times.
TEST_F(ResourceDispatcherTest, CrossSiteAfterCrash) {
// This test only works in multi-process mode
if (in_process_renderer())
return;
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
EXPECT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
// Cause the renderer to crash.
// TODO(albertb): We need to disable this on Linux since
// crash_service.exe hasn't been ported yet.
#if defined(OS_WIN)
expected_crashes_ = 1;
#endif
tab->NavigateToURLAsync(GURL("about:crash"));
// Wait for browser to notice the renderer crash.
PlatformThread::Sleep(sleep_timeout_ms());
// Navigate to a new cross-site page. The browser should not wait around for
// the old renderer's on{before}unload handlers to run.
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0");
}
#endif // !defined(OS_MACOSX)
// Tests that cross-site navigations work when the new page does not go through
// the BufferedEventHandler (e.g., non-http{s} URLs). (Bug 1225872)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationNonBuffered) {
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
EXPECT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
// Start with an HTTP page.
CheckTitleTest(L"content-sniffer-test0.html",
L"Content Sniffer Test 0");
// Now load a file:// page, which does not use the BufferedEventHandler.
// Make sure that the page loads and displays a title, and doesn't get stuck.
FilePath test_file(test_data_directory_);
test_file = test_file.AppendASCII("title2.html");
bool timed_out = false;
tab->NavigateToURLWithTimeout(net::FilePathToFileURL(test_file),
action_max_timeout_ms(),
&timed_out);
EXPECT_FALSE(timed_out);
EXPECT_EQ(L"Title Of Awesomeness", GetActiveTabTitle());
}
// Tests that a cross-site navigation to an error page (resulting in the link
// doctor page) still runs the onunload handler and can support navigations
// away from the link doctor page. (Bug 1235537)
TEST_F(ResourceDispatcherTest, CrossSiteNavigationErrorPage) {
const wchar_t kDocRoot[] = L"chrome/test/data";
scoped_refptr<HTTPTestServer> server =
HTTPTestServer::CreateServer(kDocRoot, NULL);
ASSERT_TRUE(NULL != server.get());
scoped_refptr<BrowserProxy> browser_proxy(automation()->GetBrowserWindow(0));
EXPECT_TRUE(browser_proxy.get());
scoped_refptr<TabProxy> tab(browser_proxy->GetActiveTab());
GURL url(server->TestServerPageW(L"files/onunload_cookie.html"));
tab->NavigateToURL(url);
// Confirm that the page has loaded (since it changes its title during load).
std::wstring tab_title;
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"set cookie on unload", tab_title);
// Navigate to a new cross-site URL that results in an error page. We must
// wait for the error page to update the title.
// TODO(creis): If this causes crashes or hangs, it might be for the same
// reason as ErrorPageTest::DNSError. See bug 1199491.
tab->NavigateToURL(GURL(URLRequestFailedDnsJob::kTestUrl));
for (int i = 0; i < 10; ++i) {
PlatformThread::Sleep(sleep_timeout_ms());
if (GetActiveTabTitle() != L"set cookie on unload") {
// Success, bail out.
break;
}
}
EXPECT_NE(L"set cookie on unload", GetActiveTabTitle());
// Check that the cookie was set, meaning that the onunload handler ran.
std::string value_result;
EXPECT_TRUE(tab->GetCookieByName(url, "onunloadCookie", &value_result));
EXPECT_FALSE(value_result.empty());
EXPECT_STREQ("foo", value_result.c_str());
// Check that renderer-initiated navigations still work. In a previous bug,
// the ResourceDispatcherHost would think that such navigations were
// cross-site, because we didn't clean up from the previous request. Since
// TabContents was in the NORMAL state, it would ignore the attempt to run
// the onunload handler, and the navigation would fail.
// (Test by redirecting to javascript:window.location='someURL'.)
GURL test_url(server->TestServerPageW(L"files/title2.html"));
std::string redirect_url = "javascript:window.location='" +
test_url.possibly_invalid_spec() + "'";
tab->NavigateToURLAsync(GURL(redirect_url));
// Wait for JavaScript redirect to happen.
PlatformThread::Sleep(sleep_timeout_ms() * 3);
EXPECT_TRUE(tab->GetTabTitle(&tab_title));
EXPECT_EQ(L"Title Of Awesomeness", tab_title);
}
} // namespace
<|endoftext|>
|
<commit_before>#include <vector>
#include "general.h"
#include "object.h"
#include "expression.h"
#include "../includes/switches.h"
using namespace std;
static vector<string *> string_pool;
Ink_ExpressionList native_exp_list = Ink_ExpressionList();
char *tmp_prog_path = NULL;
string *StrPool_addStr(const char *str)
{
string *tmp;
string_pool.push_back(tmp = new string(str ? str : ""));
return tmp;
}
string *StrPool_addStr(string *str)
{
string_pool.push_back(str);
return str;
}
void StrPool_dispose()
{
unsigned int i;
for (i = 0; i < string_pool.size(); i++) {
delete string_pool[i];
}
string_pool = vector<string *>();
return;
}
void cleanAll()
{
unsigned int i;
const char *tmp;
for (i = 0; i < native_exp_list.size(); i++) {
delete native_exp_list[i];
}
// remove(INK_TMP_PATH);
StrPool_dispose();
if (isDirExist(tmp = string(INK_TMP_PATH).c_str()))
removeDir(tmp);
if (tmp_prog_path)
free(tmp_prog_path);
}
Ink_Argument::~Ink_Argument()
{
if (arg)
delete arg;
if (is_expand)
delete expandee;
}<commit_msg>080116#06: fix a tiny problem in memcpy overlap<commit_after>#include <vector>
#include "general.h"
#include "object.h"
#include "expression.h"
#include "../includes/switches.h"
using namespace std;
static vector<string *> string_pool;
Ink_ExpressionList native_exp_list = Ink_ExpressionList();
char *tmp_prog_path = NULL;
string *StrPool_addStr(const char *str)
{
string *tmp;
string_pool.push_back(tmp = new string(str ? str : ""));
return tmp;
}
string *StrPool_addStr(string *str)
{
string_pool.push_back(str);
return str;
}
void StrPool_dispose()
{
unsigned int i;
for (i = 0; i < string_pool.size(); i++) {
delete string_pool[i];
}
string_pool = vector<string *>();
return;
}
void cleanAll()
{
unsigned int i;
for (i = 0; i < native_exp_list.size(); i++) {
delete native_exp_list[i];
}
// remove(INK_TMP_PATH);
StrPool_dispose();
if (isDirExist(string(INK_TMP_PATH).c_str()))
removeDir(string(INK_TMP_PATH).c_str());
if (tmp_prog_path)
free(tmp_prog_path);
}
Ink_Argument::~Ink_Argument()
{
if (arg)
delete arg;
if (is_expand)
delete expandee;
}<|endoftext|>
|
<commit_before>/*
* Copyright 2008-2013 NVIDIA Corporation
*
* 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 <thrust/detail/config.h>
#include <thrust/merge.h>
#include <thrust/detail/seq.h>
#include <thrust/system/cuda/detail/merge.h>
#include <thrust/system/cuda/detail/bulk.h>
#include <thrust/detail/temporary_array.h>
#include <thrust/tabulate.h>
#include <thrust/iterator/detail/join_iterator.h>
#include <thrust/detail/minmax.h>
#include <thrust/system/cuda/detail/execute_on_stream.h>
namespace thrust
{
namespace system
{
namespace cuda
{
namespace detail
{
namespace merge_detail
{
template<std::size_t groupsize, std::size_t grainsize, typename RandomAccessIterator1, typename Size,typename RandomAccessIterator2, typename RandomAccessIterator3, typename RandomAccessIterator4, typename Compare>
__device__
RandomAccessIterator4
staged_merge(bulk_::concurrent_group<bulk_::agent<grainsize>,groupsize> &exec,
RandomAccessIterator1 first1, Size n1,
RandomAccessIterator2 first2, Size n2,
RandomAccessIterator3 stage,
RandomAccessIterator4 result,
Compare comp)
{
// copy into the stage
bulk_::copy_n(bulk_::bound<groupsize * grainsize>(exec),
thrust::detail::make_join_iterator(first1, n1, first2),
n1 + n2,
stage);
// inplace merge in the stage
bulk_::inplace_merge(bulk_::bound<groupsize * grainsize>(exec),
stage, stage + n1, stage + n1 + n2,
comp);
// copy to the result
// XXX this might be slightly faster with a bounded copy_n
return bulk_::copy_n(exec, stage, n1 + n2, result);
} // end staged_merge()
struct merge_kernel
{
template<std::size_t groupsize, std::size_t grainsize, typename RandomAccessIterator1, typename Size, typename RandomAccessIterator2, typename RandomAccessIterator3, typename RandomAccessIterator4, typename Compare>
__device__
void operator()(bulk_::concurrent_group<bulk_::agent<grainsize>,groupsize> &g,
RandomAccessIterator1 first1, Size n1,
RandomAccessIterator2 first2, Size n2,
RandomAccessIterator3 merge_paths_first,
RandomAccessIterator4 result,
Compare comp)
{
typedef int size_type;
size_type elements_per_group = g.size() * g.this_exec.grainsize();
// determine the ranges to merge
size_type mp0 = merge_paths_first[g.index()];
size_type mp1 = merge_paths_first[g.index()+1];
size_type diag = elements_per_group * g.index();
size_type local_size1 = mp1 - mp0;
size_type local_size2 = thrust::min<size_type>(n1 + n2, diag + elements_per_group) - mp1 - diag + mp0;
first1 += mp0;
first2 += diag - mp0;
result += elements_per_group * g.index();
// XXX this assumes that RandomAccessIterator2's value_type converts to RandomAccessIterator1's value_type
typedef typename thrust::iterator_value<RandomAccessIterator1>::type value_type;
#if __CUDA_ARCH__ >= 200
// merge through a stage
value_type *stage = reinterpret_cast<value_type*>(bulk_::malloc(g, elements_per_group * sizeof(value_type)));
if(bulk_::is_on_chip(stage))
{
staged_merge(g,
first1, local_size1,
first2, local_size2,
bulk_::on_chip_cast(stage),
result,
comp);
} // end if
else
{
staged_merge(g,
first1, local_size1,
first2, local_size2,
stage,
result,
comp);
} // end else
bulk_::free(g, stage);
#else
__shared__ bulk_::uninitialized_array<value_type, groupsize * grainsize> stage;
staged_merge(g, first1, local_size1, first2, local_size2, stage.data(), result, comp);
#endif
} // end operator()
}; // end merge_kernel
template<typename Size, typename RandomAccessIterator1,typename RandomAccessIterator2, typename Compare>
struct locate_merge_path
{
Size partition_size;
RandomAccessIterator1 first1, last1;
RandomAccessIterator2 first2, last2;
Compare comp;
__host__ __device__
locate_merge_path(Size partition_size, RandomAccessIterator1 first1, RandomAccessIterator1 last1, RandomAccessIterator2 first2, RandomAccessIterator2 last2, Compare comp)
: partition_size(partition_size),
first1(first1), last1(last1),
first2(first2), last2(last2),
comp(comp)
{}
template<typename Index>
__device__
Size operator()(Index i)
{
Size n1 = last1 - first1;
Size n2 = last2 - first2;
Size diag = thrust::min<Size>(partition_size * i, n1 + n2);
return bulk_::merge_path(first1, n1, first2, n2, diag, comp);
}
};
template<typename DerivedPolicy,
typename RandomAccessIterator1,
typename RandomAccessIterator2,
typename RandomAccessIterator3,
typename Compare>
__host__ __device__
RandomAccessIterator3 merge(execution_policy<DerivedPolicy> &exec,
RandomAccessIterator1 first1,
RandomAccessIterator1 last1,
RandomAccessIterator2 first2,
RandomAccessIterator2 last2,
RandomAccessIterator3 result,
Compare comp)
{
typedef typename thrust::iterator_value<RandomAccessIterator1>::type value_type;
typedef typename thrust::iterator_difference<RandomAccessIterator1>::type difference_type;
typedef int size_type;
// determined through empirical testing on K20c
const size_type groupsize = (sizeof(value_type) == sizeof(int)) ? 256 : 256 + 32;
const size_type grainsize = (sizeof(value_type) == sizeof(int)) ? 9 : 5;
const size_type tile_size = groupsize * grainsize;
difference_type n = (last1 - first1) + (last2 - first2);
difference_type num_groups = (n + tile_size - 1) / tile_size;
thrust::detail::temporary_array<size_type,DerivedPolicy> merge_paths(exec, num_groups + 1);
thrust::tabulate(exec, merge_paths.begin(), merge_paths.end(), merge_detail::locate_merge_path<size_type,RandomAccessIterator1,RandomAccessIterator2,Compare>(tile_size,first1,last1,first2,last2,comp));
// merge partitions
size_type heap_size = tile_size * sizeof(value_type);
bulk_::concurrent_group<bulk_::agent<grainsize>,groupsize> g(heap_size);
bulk_::async(bulk_::par(stream(thrust::detail::derived_cast(exec)), g, num_groups), merge_detail::merge_kernel(), bulk_::root.this_exec, first1, last1 - first1, first2, last2 - first2, merge_paths.begin(), result, comp);
return result + n;
} // end merge()
} // end merge_detail
template<typename DerivedPolicy,
typename RandomAccessIterator1,
typename RandomAccessIterator2,
typename RandomAccessIterator3,
typename Compare>
__host__ __device__
RandomAccessIterator3 merge(execution_policy<DerivedPolicy> &exec,
RandomAccessIterator1 first1,
RandomAccessIterator1 last1,
RandomAccessIterator2 first2,
RandomAccessIterator2 last2,
RandomAccessIterator3 result,
Compare comp)
{
// we're attempting to launch a kernel, assert we're compiling with nvcc
// ========================================================================
// X Note to the user: If you've found this line due to a compiler error, X
// X you need to compile your code using nvcc, rather than g++ or cl.exe X
// ========================================================================
THRUST_STATIC_ASSERT( (thrust::detail::depend_on_instantiation<RandomAccessIterator1, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) );
struct workaround
{
__host__ __device__
static RandomAccessIterator3 parallel_path(execution_policy<DerivedPolicy> &exec,
RandomAccessIterator1 first1,
RandomAccessIterator1 last1,
RandomAccessIterator2 first2,
RandomAccessIterator2 last2,
RandomAccessIterator3 result,
Compare comp)
{
return thrust::system::cuda::detail::merge_detail::merge(exec, first1, last1, first2, last2, result, comp);
}
__host__ __device__
static RandomAccessIterator3 sequential_path(execution_policy<DerivedPolicy> &,
RandomAccessIterator1 first1,
RandomAccessIterator1 last1,
RandomAccessIterator2 first2,
RandomAccessIterator2 last2,
RandomAccessIterator3 result,
Compare comp)
{
return thrust::merge(thrust::seq, first1, last1, first2, last2, result, comp);
}
};
#if __BULK_HAS_CUDART__
return workaround::parallel_path(exec, first1, last1, first2, last2, result, comp);
#else
return workaround::sequential_path(exec, first1, last1, first2, last2, result, comp);
#endif
} // end merge()
} // end namespace detail
} // end namespace cuda
} // end namespace system
} // end namespace thrust
<commit_msg>Generalized merge_kernel::operator() to use two difference_type size parameters<commit_after>/*
* Copyright 2008-2013 NVIDIA Corporation
*
* 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 <thrust/detail/config.h>
#include <thrust/merge.h>
#include <thrust/detail/seq.h>
#include <thrust/system/cuda/detail/merge.h>
#include <thrust/system/cuda/detail/bulk.h>
#include <thrust/detail/temporary_array.h>
#include <thrust/tabulate.h>
#include <thrust/iterator/detail/join_iterator.h>
#include <thrust/detail/minmax.h>
#include <thrust/system/cuda/detail/execute_on_stream.h>
namespace thrust
{
namespace system
{
namespace cuda
{
namespace detail
{
namespace merge_detail
{
template<std::size_t groupsize, std::size_t grainsize, typename RandomAccessIterator1, typename Size,typename RandomAccessIterator2, typename RandomAccessIterator3, typename RandomAccessIterator4, typename Compare>
__device__
RandomAccessIterator4
staged_merge(bulk_::concurrent_group<bulk_::agent<grainsize>,groupsize> &exec,
RandomAccessIterator1 first1, Size n1,
RandomAccessIterator2 first2, Size n2,
RandomAccessIterator3 stage,
RandomAccessIterator4 result,
Compare comp)
{
// copy into the stage
bulk_::copy_n(bulk_::bound<groupsize * grainsize>(exec),
thrust::detail::make_join_iterator(first1, n1, first2),
n1 + n2,
stage);
// inplace merge in the stage
bulk_::inplace_merge(bulk_::bound<groupsize * grainsize>(exec),
stage, stage + n1, stage + n1 + n2,
comp);
// copy to the result
// XXX this might be slightly faster with a bounded copy_n
return bulk_::copy_n(exec, stage, n1 + n2, result);
} // end staged_merge()
struct merge_kernel
{
template<std::size_t groupsize, std::size_t grainsize, typename RandomAccessIterator1, typename Size1, typename RandomAccessIterator2, typename Size2, typename RandomAccessIterator3, typename RandomAccessIterator4, typename Compare>
__device__
void operator()(bulk_::concurrent_group<bulk_::agent<grainsize>,groupsize> &g,
RandomAccessIterator1 first1, Size1 n1,
RandomAccessIterator2 first2, Size2 n2,
RandomAccessIterator3 merge_paths_first,
RandomAccessIterator4 result,
Compare comp)
{
typedef int size_type;
size_type elements_per_group = g.size() * g.this_exec.grainsize();
// determine the ranges to merge
size_type mp0 = merge_paths_first[g.index()];
size_type mp1 = merge_paths_first[g.index()+1];
size_type diag = elements_per_group * g.index();
size_type local_size1 = mp1 - mp0;
size_type local_size2 = thrust::min<size_type>(n1 + n2, diag + elements_per_group) - mp1 - diag + mp0;
first1 += mp0;
first2 += diag - mp0;
result += elements_per_group * g.index();
// XXX this assumes that RandomAccessIterator2's value_type converts to RandomAccessIterator1's value_type
typedef typename thrust::iterator_value<RandomAccessIterator1>::type value_type;
#if __CUDA_ARCH__ >= 200
// merge through a stage
value_type *stage = reinterpret_cast<value_type*>(bulk_::malloc(g, elements_per_group * sizeof(value_type)));
if(bulk_::is_on_chip(stage))
{
staged_merge(g,
first1, local_size1,
first2, local_size2,
bulk_::on_chip_cast(stage),
result,
comp);
} // end if
else
{
staged_merge(g,
first1, local_size1,
first2, local_size2,
stage,
result,
comp);
} // end else
bulk_::free(g, stage);
#else
__shared__ bulk_::uninitialized_array<value_type, groupsize * grainsize> stage;
staged_merge(g, first1, local_size1, first2, local_size2, stage.data(), result, comp);
#endif
} // end operator()
}; // end merge_kernel
template<typename Size, typename RandomAccessIterator1,typename RandomAccessIterator2, typename Compare>
struct locate_merge_path
{
Size partition_size;
RandomAccessIterator1 first1, last1;
RandomAccessIterator2 first2, last2;
Compare comp;
__host__ __device__
locate_merge_path(Size partition_size, RandomAccessIterator1 first1, RandomAccessIterator1 last1, RandomAccessIterator2 first2, RandomAccessIterator2 last2, Compare comp)
: partition_size(partition_size),
first1(first1), last1(last1),
first2(first2), last2(last2),
comp(comp)
{}
template<typename Index>
__device__
Size operator()(Index i)
{
Size n1 = last1 - first1;
Size n2 = last2 - first2;
Size diag = thrust::min<Size>(partition_size * i, n1 + n2);
return bulk_::merge_path(first1, n1, first2, n2, diag, comp);
}
};
template<typename DerivedPolicy,
typename RandomAccessIterator1,
typename RandomAccessIterator2,
typename RandomAccessIterator3,
typename Compare>
__host__ __device__
RandomAccessIterator3 merge(execution_policy<DerivedPolicy> &exec,
RandomAccessIterator1 first1,
RandomAccessIterator1 last1,
RandomAccessIterator2 first2,
RandomAccessIterator2 last2,
RandomAccessIterator3 result,
Compare comp)
{
typedef typename thrust::iterator_value<RandomAccessIterator1>::type value_type;
typedef typename thrust::iterator_difference<RandomAccessIterator1>::type difference_type;
typedef int size_type;
// determined through empirical testing on K20c
const size_type groupsize = (sizeof(value_type) == sizeof(int)) ? 256 : 256 + 32;
const size_type grainsize = (sizeof(value_type) == sizeof(int)) ? 9 : 5;
const size_type tile_size = groupsize * grainsize;
difference_type n = (last1 - first1) + (last2 - first2);
difference_type num_groups = (n + tile_size - 1) / tile_size;
thrust::detail::temporary_array<size_type,DerivedPolicy> merge_paths(exec, num_groups + 1);
thrust::tabulate(exec, merge_paths.begin(), merge_paths.end(), merge_detail::locate_merge_path<size_type,RandomAccessIterator1,RandomAccessIterator2,Compare>(tile_size,first1,last1,first2,last2,comp));
// merge partitions
size_type heap_size = tile_size * sizeof(value_type);
bulk_::concurrent_group<bulk_::agent<grainsize>,groupsize> g(heap_size);
bulk_::async(bulk_::par(stream(thrust::detail::derived_cast(exec)), g, num_groups), merge_detail::merge_kernel(), bulk_::root.this_exec, first1, last1 - first1, first2, last2 - first2, merge_paths.begin(), result, comp);
return result + n;
} // end merge()
} // end merge_detail
template<typename DerivedPolicy,
typename RandomAccessIterator1,
typename RandomAccessIterator2,
typename RandomAccessIterator3,
typename Compare>
__host__ __device__
RandomAccessIterator3 merge(execution_policy<DerivedPolicy> &exec,
RandomAccessIterator1 first1,
RandomAccessIterator1 last1,
RandomAccessIterator2 first2,
RandomAccessIterator2 last2,
RandomAccessIterator3 result,
Compare comp)
{
// we're attempting to launch a kernel, assert we're compiling with nvcc
// ========================================================================
// X Note to the user: If you've found this line due to a compiler error, X
// X you need to compile your code using nvcc, rather than g++ or cl.exe X
// ========================================================================
THRUST_STATIC_ASSERT( (thrust::detail::depend_on_instantiation<RandomAccessIterator1, THRUST_DEVICE_COMPILER == THRUST_DEVICE_COMPILER_NVCC>::value) );
struct workaround
{
__host__ __device__
static RandomAccessIterator3 parallel_path(execution_policy<DerivedPolicy> &exec,
RandomAccessIterator1 first1,
RandomAccessIterator1 last1,
RandomAccessIterator2 first2,
RandomAccessIterator2 last2,
RandomAccessIterator3 result,
Compare comp)
{
return thrust::system::cuda::detail::merge_detail::merge(exec, first1, last1, first2, last2, result, comp);
}
__host__ __device__
static RandomAccessIterator3 sequential_path(execution_policy<DerivedPolicy> &,
RandomAccessIterator1 first1,
RandomAccessIterator1 last1,
RandomAccessIterator2 first2,
RandomAccessIterator2 last2,
RandomAccessIterator3 result,
Compare comp)
{
return thrust::merge(thrust::seq, first1, last1, first2, last2, result, comp);
}
};
#if __BULK_HAS_CUDART__
return workaround::parallel_path(exec, first1, last1, first2, last2, result, comp);
#else
return workaround::sequential_path(exec, first1, last1, first2, last2, result, comp);
#endif
} // end merge()
} // end namespace detail
} // end namespace cuda
} // end namespace system
} // end namespace thrust
<|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 <set>
#include <vector>
#include "base/command_line.h"
#include "base/ref_counted.h"
#include "base/string16.h"
#include "base/string_util.h"
#include "base/waitable_event.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/webdata/autofill_entry.h"
#include "chrome/browser/webdata/web_database.h"
#include "chrome/browser/webdata/web_data_service.h"
#include "chrome/browser/webdata/web_data_service_test_util.h"
#include "chrome/common/notification_observer_mock.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/live_sync/profile_sync_service_test_harness.h"
#include "chrome/test/live_sync/live_sync_test.h"
#include "chrome/test/thread_observer_helper.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "webkit/glue/form_field.h"
using base::WaitableEvent;
using testing::_;
namespace {
// Define these << operators so we can use EXPECT_EQ with the
// AutofillKeys type.
template<class T1, class T2, class T3>
std::ostream& operator<<(std::ostream& os, const std::set<T1, T2, T3>& seq) {
typedef typename std::set<T1, T2, T3>::const_iterator SetConstIterator;
for (SetConstIterator i = seq.begin(); i != seq.end(); ++i) {
os << *i << ", ";
}
return os;
}
std::ostream& operator<<(std::ostream& os, const AutofillKey& key) {
return os << UTF16ToUTF8(key.name()) << ", " << UTF16ToUTF8(key.value());
}
class GetAllAutofillEntries
: public base::RefCountedThreadSafe<GetAllAutofillEntries> {
public:
explicit GetAllAutofillEntries(WebDataService* web_data_service)
: web_data_service_(web_data_service),
done_event_(false, false) {}
void Init() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
ChromeThread::PostTask(
ChromeThread::DB,
FROM_HERE,
NewRunnableMethod(this, &GetAllAutofillEntries::Run));
done_event_.Wait();
}
const std::vector<AutofillEntry>& entries() const {
return entries_;
}
private:
friend class base::RefCountedThreadSafe<GetAllAutofillEntries>;
void Run() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::DB));
web_data_service_->GetDatabase()->GetAllAutofillEntries(&entries_);
done_event_.Signal();
}
WebDataService* web_data_service_;
base::WaitableEvent done_event_;
std::vector<AutofillEntry> entries_;
};
ACTION_P(SignalEvent, event) {
event->Signal();
}
class AutofillDBThreadObserverHelper : public DBThreadObserverHelper {
protected:
virtual void RegisterObservers() {
registrar_.Add(&observer_,
NotificationType::AUTOFILL_ENTRIES_CHANGED,
NotificationService::AllSources());
registrar_.Add(&observer_,
NotificationType::AUTOFILL_PROFILE_CHANGED,
NotificationService::AllSources());
}
};
} // namespace;
class TwoClientLiveAutofillSyncTest : public LiveSyncTest {
public:
typedef std::set<AutofillKey> AutofillKeys;
TwoClientLiveAutofillSyncTest()
: name1_(ASCIIToUTF16("name1")),
name2_(ASCIIToUTF16("name2")),
value1_(ASCIIToUTF16("value1")),
value2_(ASCIIToUTF16("value2")),
done_event1_(false, false),
done_event2_(false, false) {
// This makes sure browser is visible and active while running test.
InProcessBrowserTest::set_show_window(true);
// Set the initial timeout value to 5 min.
InProcessBrowserTest::SetInitialTimeoutInMS(300000);
}
~TwoClientLiveAutofillSyncTest() {}
protected:
void SetupHarness() {
client1_.reset(new ProfileSyncServiceTestHarness(
browser()->profile(), username_, password_));
profile2_.reset(MakeProfile(FILE_PATH_LITERAL("client2")));
client2_.reset(new ProfileSyncServiceTestHarness(
profile2_.get(), username_, password_));
wds1_ = browser()->profile()->GetWebDataService(Profile::EXPLICIT_ACCESS);
wds2_ = profile2_->GetWebDataService(Profile::EXPLICIT_ACCESS);
}
void SetupSync() {
EXPECT_TRUE(client1_->SetupSync());
EXPECT_TRUE(client1_->AwaitSyncCycleCompletion("Initial setup 1"));
EXPECT_TRUE(client2_->SetupSync());
EXPECT_TRUE(client2_->AwaitSyncCycleCompletion("Initial setup 2"));
}
void Cleanup() {
client2_.reset();
profile2_.reset();
}
void AddToWds(WebDataService* wds, const AutofillKeys& keys) {
std::vector<webkit_glue::FormField> form_fields;
for (AutofillKeys::const_iterator i = keys.begin(); i != keys.end(); ++i) {
form_fields.push_back(
webkit_glue::FormField(string16(),
(*i).name(),
(*i).value(),
string16()));
}
WaitableEvent done_event(false, false);
scoped_refptr<AutofillDBThreadObserverHelper> observer_helper(
new AutofillDBThreadObserverHelper());
observer_helper->Init();
EXPECT_CALL(*observer_helper->observer(), Observe(_, _, _)).
WillOnce(SignalEvent(&done_event));
wds->AddFormFields(form_fields);
done_event.Wait();
}
void GetAllAutofillKeys(WebDataService* wds, AutofillKeys* keys) {
scoped_refptr<GetAllAutofillEntries> get_all_entries =
new GetAllAutofillEntries(wds);
get_all_entries->Init();
const std::vector<AutofillEntry>& entries = get_all_entries->entries();
for (size_t i = 0; i < entries.size(); ++i) {
keys->insert(entries[i].key());
}
}
ProfileSyncServiceTestHarness* client1() { return client1_.get(); }
ProfileSyncServiceTestHarness* client2() { return client2_.get(); }
PrefService* prefs1() { return browser()->profile()->GetPrefs(); }
PrefService* prefs2() { return profile2_->GetPrefs(); }
string16 name1_;
string16 name2_;
string16 value1_;
string16 value2_;
base::WaitableEvent done_event1_;
base::WaitableEvent done_event2_;
scoped_ptr<ProfileSyncServiceTestHarness> client1_;
scoped_ptr<ProfileSyncServiceTestHarness> client2_;
scoped_ptr<Profile> profile2_;
WebDataService* wds1_;
WebDataService* wds2_;
DISALLOW_COPY_AND_ASSIGN(TwoClientLiveAutofillSyncTest);
};
IN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, Client1HasData) {
SetupHarness();
AutofillKeys keys;
keys.insert(AutofillKey("name1", "value1"));
keys.insert(AutofillKey("name1", "value2"));
keys.insert(AutofillKey("name2", "value3"));
keys.insert(AutofillKey("Sigur R\u00F3s", "\u00C1g\u00E6tis byrjun"));
AddToWds(wds1_, keys);
SetupSync();
AutofillKeys wd2_keys;
GetAllAutofillKeys(wds2_, &wd2_keys);
EXPECT_EQ(keys, wd2_keys);
Cleanup();
}
IN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, BothHaveData) {
SetupHarness();
AutofillKeys keys1;
keys1.insert(AutofillKey("name1", "value1"));
keys1.insert(AutofillKey("name1", "value2"));
keys1.insert(AutofillKey("name2", "value3"));
AddToWds(wds1_, keys1);
AutofillKeys keys2;
keys2.insert(AutofillKey("name1", "value2"));
keys2.insert(AutofillKey("name2", "value3"));
keys2.insert(AutofillKey("name3", "value4"));
keys2.insert(AutofillKey("name4", "value4"));
AddToWds(wds2_, keys2);
SetupSync();
// Wait for client1 to get the new keys from client2.
EXPECT_TRUE(client1()->AwaitSyncCycleCompletion("sync cycle"));
AutofillKeys expected_keys;
expected_keys.insert(AutofillKey("name1", "value1"));
expected_keys.insert(AutofillKey("name1", "value2"));
expected_keys.insert(AutofillKey("name2", "value3"));
expected_keys.insert(AutofillKey("name3", "value4"));
expected_keys.insert(AutofillKey("name4", "value4"));
AutofillKeys wd1_keys;
GetAllAutofillKeys(wds1_, &wd1_keys);
EXPECT_EQ(expected_keys, wd1_keys);
AutofillKeys wd2_keys;
GetAllAutofillKeys(wds2_, &wd2_keys);
EXPECT_EQ(expected_keys, wd2_keys);
Cleanup();
}
IN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, Steady) {
SetupHarness();
SetupSync();
AutofillKeys add_one_key;
add_one_key.insert(AutofillKey("name1", "value1"));
AddToWds(wds1_, add_one_key);
AutofillKeys expected_keys;
expected_keys.insert(AutofillKey("name1", "value1"));
EXPECT_TRUE(client1()->AwaitMutualSyncCycleCompletion(client2()));
AutofillKeys keys;
GetAllAutofillKeys(wds1_, &keys);
EXPECT_EQ(expected_keys, keys);
keys.clear();
GetAllAutofillKeys(wds2_, &keys);
EXPECT_EQ(expected_keys, keys);
Cleanup();
}
<commit_msg>Embed unicode literals the correct way<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 <set>
#include <vector>
#include "base/command_line.h"
#include "base/ref_counted.h"
#include "base/string16.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/waitable_event.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/pref_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/webdata/autofill_entry.h"
#include "chrome/browser/webdata/web_database.h"
#include "chrome/browser/webdata/web_data_service.h"
#include "chrome/browser/webdata/web_data_service_test_util.h"
#include "chrome/common/notification_observer_mock.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/notification_type.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/live_sync/profile_sync_service_test_harness.h"
#include "chrome/test/live_sync/live_sync_test.h"
#include "chrome/test/thread_observer_helper.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "webkit/glue/form_field.h"
using base::WaitableEvent;
using testing::_;
namespace {
// Define these << operators so we can use EXPECT_EQ with the
// AutofillKeys type.
template<class T1, class T2, class T3>
std::ostream& operator<<(std::ostream& os, const std::set<T1, T2, T3>& seq) {
typedef typename std::set<T1, T2, T3>::const_iterator SetConstIterator;
for (SetConstIterator i = seq.begin(); i != seq.end(); ++i) {
os << *i << ", ";
}
return os;
}
std::ostream& operator<<(std::ostream& os, const AutofillKey& key) {
return os << UTF16ToUTF8(key.name()) << ", " << UTF16ToUTF8(key.value());
}
class GetAllAutofillEntries
: public base::RefCountedThreadSafe<GetAllAutofillEntries> {
public:
explicit GetAllAutofillEntries(WebDataService* web_data_service)
: web_data_service_(web_data_service),
done_event_(false, false) {}
void Init() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));
ChromeThread::PostTask(
ChromeThread::DB,
FROM_HERE,
NewRunnableMethod(this, &GetAllAutofillEntries::Run));
done_event_.Wait();
}
const std::vector<AutofillEntry>& entries() const {
return entries_;
}
private:
friend class base::RefCountedThreadSafe<GetAllAutofillEntries>;
void Run() {
DCHECK(ChromeThread::CurrentlyOn(ChromeThread::DB));
web_data_service_->GetDatabase()->GetAllAutofillEntries(&entries_);
done_event_.Signal();
}
WebDataService* web_data_service_;
base::WaitableEvent done_event_;
std::vector<AutofillEntry> entries_;
};
ACTION_P(SignalEvent, event) {
event->Signal();
}
class AutofillDBThreadObserverHelper : public DBThreadObserverHelper {
protected:
virtual void RegisterObservers() {
registrar_.Add(&observer_,
NotificationType::AUTOFILL_ENTRIES_CHANGED,
NotificationService::AllSources());
registrar_.Add(&observer_,
NotificationType::AUTOFILL_PROFILE_CHANGED,
NotificationService::AllSources());
}
};
} // namespace;
class TwoClientLiveAutofillSyncTest : public LiveSyncTest {
public:
typedef std::set<AutofillKey> AutofillKeys;
TwoClientLiveAutofillSyncTest()
: name1_(ASCIIToUTF16("name1")),
name2_(ASCIIToUTF16("name2")),
value1_(ASCIIToUTF16("value1")),
value2_(ASCIIToUTF16("value2")),
done_event1_(false, false),
done_event2_(false, false) {
// This makes sure browser is visible and active while running test.
InProcessBrowserTest::set_show_window(true);
// Set the initial timeout value to 5 min.
InProcessBrowserTest::SetInitialTimeoutInMS(300000);
}
~TwoClientLiveAutofillSyncTest() {}
protected:
void SetupHarness() {
client1_.reset(new ProfileSyncServiceTestHarness(
browser()->profile(), username_, password_));
profile2_.reset(MakeProfile(FILE_PATH_LITERAL("client2")));
client2_.reset(new ProfileSyncServiceTestHarness(
profile2_.get(), username_, password_));
wds1_ = browser()->profile()->GetWebDataService(Profile::EXPLICIT_ACCESS);
wds2_ = profile2_->GetWebDataService(Profile::EXPLICIT_ACCESS);
}
void SetupSync() {
EXPECT_TRUE(client1_->SetupSync());
EXPECT_TRUE(client1_->AwaitSyncCycleCompletion("Initial setup 1"));
EXPECT_TRUE(client2_->SetupSync());
EXPECT_TRUE(client2_->AwaitSyncCycleCompletion("Initial setup 2"));
}
void Cleanup() {
client2_.reset();
profile2_.reset();
}
void AddToWds(WebDataService* wds, const AutofillKeys& keys) {
std::vector<webkit_glue::FormField> form_fields;
for (AutofillKeys::const_iterator i = keys.begin(); i != keys.end(); ++i) {
form_fields.push_back(
webkit_glue::FormField(string16(),
(*i).name(),
(*i).value(),
string16()));
}
WaitableEvent done_event(false, false);
scoped_refptr<AutofillDBThreadObserverHelper> observer_helper(
new AutofillDBThreadObserverHelper());
observer_helper->Init();
EXPECT_CALL(*observer_helper->observer(), Observe(_, _, _)).
WillOnce(SignalEvent(&done_event));
wds->AddFormFields(form_fields);
done_event.Wait();
}
void GetAllAutofillKeys(WebDataService* wds, AutofillKeys* keys) {
scoped_refptr<GetAllAutofillEntries> get_all_entries =
new GetAllAutofillEntries(wds);
get_all_entries->Init();
const std::vector<AutofillEntry>& entries = get_all_entries->entries();
for (size_t i = 0; i < entries.size(); ++i) {
keys->insert(entries[i].key());
}
}
ProfileSyncServiceTestHarness* client1() { return client1_.get(); }
ProfileSyncServiceTestHarness* client2() { return client2_.get(); }
PrefService* prefs1() { return browser()->profile()->GetPrefs(); }
PrefService* prefs2() { return profile2_->GetPrefs(); }
string16 name1_;
string16 name2_;
string16 value1_;
string16 value2_;
base::WaitableEvent done_event1_;
base::WaitableEvent done_event2_;
scoped_ptr<ProfileSyncServiceTestHarness> client1_;
scoped_ptr<ProfileSyncServiceTestHarness> client2_;
scoped_ptr<Profile> profile2_;
WebDataService* wds1_;
WebDataService* wds2_;
DISALLOW_COPY_AND_ASSIGN(TwoClientLiveAutofillSyncTest);
};
IN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, Client1HasData) {
SetupHarness();
AutofillKeys keys;
keys.insert(AutofillKey("name1", "value1"));
keys.insert(AutofillKey("name1", "value2"));
keys.insert(AutofillKey("name2", "value3"));
keys.insert(AutofillKey(WideToUTF16(L"Sigur R\u00F3s"),
WideToUTF16(L"\u00C1g\u00E6tis byrjun")));
AddToWds(wds1_, keys);
SetupSync();
AutofillKeys wd2_keys;
GetAllAutofillKeys(wds2_, &wd2_keys);
EXPECT_EQ(keys, wd2_keys);
Cleanup();
}
IN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, BothHaveData) {
SetupHarness();
AutofillKeys keys1;
keys1.insert(AutofillKey("name1", "value1"));
keys1.insert(AutofillKey("name1", "value2"));
keys1.insert(AutofillKey("name2", "value3"));
AddToWds(wds1_, keys1);
AutofillKeys keys2;
keys2.insert(AutofillKey("name1", "value2"));
keys2.insert(AutofillKey("name2", "value3"));
keys2.insert(AutofillKey("name3", "value4"));
keys2.insert(AutofillKey("name4", "value4"));
AddToWds(wds2_, keys2);
SetupSync();
// Wait for client1 to get the new keys from client2.
EXPECT_TRUE(client1()->AwaitSyncCycleCompletion("sync cycle"));
AutofillKeys expected_keys;
expected_keys.insert(AutofillKey("name1", "value1"));
expected_keys.insert(AutofillKey("name1", "value2"));
expected_keys.insert(AutofillKey("name2", "value3"));
expected_keys.insert(AutofillKey("name3", "value4"));
expected_keys.insert(AutofillKey("name4", "value4"));
AutofillKeys wd1_keys;
GetAllAutofillKeys(wds1_, &wd1_keys);
EXPECT_EQ(expected_keys, wd1_keys);
AutofillKeys wd2_keys;
GetAllAutofillKeys(wds2_, &wd2_keys);
EXPECT_EQ(expected_keys, wd2_keys);
Cleanup();
}
IN_PROC_BROWSER_TEST_F(TwoClientLiveAutofillSyncTest, Steady) {
SetupHarness();
SetupSync();
AutofillKeys add_one_key;
add_one_key.insert(AutofillKey("name1", "value1"));
AddToWds(wds1_, add_one_key);
AutofillKeys expected_keys;
expected_keys.insert(AutofillKey("name1", "value1"));
EXPECT_TRUE(client1()->AwaitMutualSyncCycleCompletion(client2()));
AutofillKeys keys;
GetAllAutofillKeys(wds1_, &keys);
EXPECT_EQ(expected_keys, keys);
keys.clear();
GetAllAutofillKeys(wds2_, &keys);
EXPECT_EQ(expected_keys, keys);
Cleanup();
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkRegularStepGradientDescentOptimizerTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <itkRegularStepGradientDescentOptimizer.h>
#include <vnl/vnl_math.h>
/**
* The objectif function is the quadratic form:
*
* 1/2 x^T A x - b^T x
*
* Where A is a matrix and b is a vector
* The system in this example is:
*
* | 3 2 ||x| | 2| |0|
* | 2 6 ||y| + |-8| = |0|
*
*
* the solution is the vector | 2 -2 |
*
*/
class RSGCostFunction : public itk::SingleValuedCostFunction
{
public:
typedef RSGCostFunction Self;
typedef itk::SingleValuedCostFunction Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
itkNewMacro( Self );
enum { SpaceDimension=2 };
typedef Superclass::ParametersType ParametersType;
typedef Superclass::DerivativeType DerivativeType;
typedef Superclass::MeasureType MeasureType ;
RSGCostFunction()
{
}
MeasureType GetValue( const ParametersType & parameters ) const
{
double x = parameters[0];
double y = parameters[1];
std::cout << "GetValue( " ;
std::cout << x << " ";
std::cout << y << ") = ";
MeasureType measure = 0.5*(3*x*x+4*x*y+6*y*y) - 2*x + 8*y;
std::cout << measure << std::endl;
return measure;
}
void GetDerivative( const ParametersType & parameters,
DerivativeType & derivative ) const
{
double x = parameters[0];
double y = parameters[1];
std::cout << "GetDerivative( " ;
std::cout << x << " ";
std::cout << y << ") = ";
derivative = DerivativeType( SpaceDimension );
derivative[0] = 3 * x + 2 * y -2;
derivative[1] = 2 * x + 6 * y +8;
}
unsigned int GetNumberOfParameters(void) const
{
return SpaceDimension;
}
private:
};
int itkRegularStepGradientDescentOptimizerTest(int, char* [] )
{
std::cout << "RegularStepGradientDescentOptimizer Test ";
std::cout << std::endl << std::endl;
typedef itk::RegularStepGradientDescentOptimizer OptimizerType;
typedef OptimizerType::ScalesType ScalesType;
// Declaration of a itkOptimizer
OptimizerType::Pointer itkOptimizer = OptimizerType::New();
// Declaration of the CostFunction
RSGCostFunction::Pointer costFunction = RSGCostFunction::New();
itkOptimizer->SetCostFunction( costFunction.GetPointer() );
typedef RSGCostFunction::ParametersType ParametersType;
const unsigned int spaceDimension =
costFunction->GetNumberOfParameters();
// We start not so far from | 2 -2 |
ParametersType initialPosition( spaceDimension );
initialPosition[0] = 100;
initialPosition[1] = -100;
ScalesType parametersScale( spaceDimension );
parametersScale[0] = 1.0;
parametersScale[1] = 1.0;
itkOptimizer->MinimizeOn();
itkOptimizer->SetScales( parametersScale );
itkOptimizer->SetGradientMagnitudeTolerance( 1e-6 );
itkOptimizer->SetMaximumStepLength( 30.0 );
itkOptimizer->SetMinimumStepLength( 1e-6 );
itkOptimizer->SetNumberOfIterations( 900 );
itkOptimizer->SetInitialPosition( initialPosition );
try
{
itkOptimizer->StartOptimization();
}
catch( itk::ExceptionObject & e )
{
std::cout << "Exception thrown ! " << std::endl;
std::cout << "An error ocurred during Optimization" << std::endl;
std::cout << "Location = " << e.GetLocation() << std::endl;
std::cout << "Description = " << e.GetDescription() << std::endl;
return EXIT_FAILURE;
}
ParametersType finalPosition = itkOptimizer->GetCurrentPosition();
std::cout << "Solution = (";
std::cout << finalPosition[0] << "," ;
std::cout << finalPosition[1] << ")" << std::endl;
//
// check results to see if it is within range
//
bool pass = true;
double trueParameters[2] = { 2, -2 };
for( unsigned int j = 0; j < 2; j++ )
{
if( vnl_math_abs( finalPosition[j] - trueParameters[j] ) > 0.01 )
{
pass = false;
}
}
if( !pass )
{
std::cout << "Test failed." << std::endl;
return EXIT_FAILURE;
}
// Run now with a different relaxation factor
{
itkOptimizer->SetInitialPosition( initialPosition );
itkOptimizer->SetRelaxationFactor( 0.8 );
try
{
itkOptimizer->StartOptimization();
}
catch( itk::ExceptionObject & e )
{
std::cout << "Exception thrown ! " << std::endl;
std::cout << "An error ocurred during Optimization" << std::endl;
std::cout << "Location = " << e.GetLocation() << std::endl;
std::cout << "Description = " << e.GetDescription() << std::endl;
return EXIT_FAILURE;
}
finalPosition = itkOptimizer->GetCurrentPosition();
std::cout << "Solution = (";
std::cout << finalPosition[0] << "," ;
std::cout << finalPosition[1] << ")" << std::endl;
//
// check results to see if it is within range
//
pass = true;
for( unsigned int j = 0; j < 2; j++ )
{
if( vnl_math_abs( finalPosition[j] - trueParameters[j] ) > 0.01 )
{
pass = false;
}
}
if( !pass )
{
std::cout << "Test failed." << std::endl;
return EXIT_FAILURE;
}
}
//
// Verify that the optimizer doesn't run if the
// number of iterations is set to zero.
//
{
itkOptimizer->SetNumberOfIterations( 0 );
itkOptimizer->SetInitialPosition( initialPosition );
try
{
itkOptimizer->StartOptimization();
}
catch( itk::ExceptionObject & excp )
{
std::cout << excp << std::endl;
return EXIT_FAILURE;
}
if( itkOptimizer->GetCurrentIteration() > 0 )
{
std::cerr << "The optimizer is running iterations despite of ";
std::cerr << "having a maximum number of iterations set to zero" << std::endl;
return EXIT_FAILURE;
}
}
std::cout << "Test passed." << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>BUG: 4893. Verifying that an exception is thrown from StartOptimization() when the GradientMagnitudeTolerance value has been set to a negative number.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: itkRegularStepGradientDescentOptimizerTest.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <itkRegularStepGradientDescentOptimizer.h>
#include <vnl/vnl_math.h>
/**
* The objectif function is the quadratic form:
*
* 1/2 x^T A x - b^T x
*
* Where A is a matrix and b is a vector
* The system in this example is:
*
* | 3 2 ||x| | 2| |0|
* | 2 6 ||y| + |-8| = |0|
*
*
* the solution is the vector | 2 -2 |
*
*/
class RSGCostFunction : public itk::SingleValuedCostFunction
{
public:
typedef RSGCostFunction Self;
typedef itk::SingleValuedCostFunction Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
itkNewMacro( Self );
enum { SpaceDimension=2 };
typedef Superclass::ParametersType ParametersType;
typedef Superclass::DerivativeType DerivativeType;
typedef Superclass::MeasureType MeasureType ;
RSGCostFunction()
{
}
MeasureType GetValue( const ParametersType & parameters ) const
{
double x = parameters[0];
double y = parameters[1];
std::cout << "GetValue( " ;
std::cout << x << " ";
std::cout << y << ") = ";
MeasureType measure = 0.5*(3*x*x+4*x*y+6*y*y) - 2*x + 8*y;
std::cout << measure << std::endl;
return measure;
}
void GetDerivative( const ParametersType & parameters,
DerivativeType & derivative ) const
{
double x = parameters[0];
double y = parameters[1];
std::cout << "GetDerivative( " ;
std::cout << x << " ";
std::cout << y << ") = ";
derivative = DerivativeType( SpaceDimension );
derivative[0] = 3 * x + 2 * y -2;
derivative[1] = 2 * x + 6 * y +8;
}
unsigned int GetNumberOfParameters(void) const
{
return SpaceDimension;
}
private:
};
int itkRegularStepGradientDescentOptimizerTest(int, char* [] )
{
std::cout << "RegularStepGradientDescentOptimizer Test ";
std::cout << std::endl << std::endl;
typedef itk::RegularStepGradientDescentOptimizer OptimizerType;
typedef OptimizerType::ScalesType ScalesType;
// Declaration of a itkOptimizer
OptimizerType::Pointer itkOptimizer = OptimizerType::New();
// Declaration of the CostFunction
RSGCostFunction::Pointer costFunction = RSGCostFunction::New();
itkOptimizer->SetCostFunction( costFunction.GetPointer() );
typedef RSGCostFunction::ParametersType ParametersType;
const unsigned int spaceDimension =
costFunction->GetNumberOfParameters();
// We start not so far from | 2 -2 |
ParametersType initialPosition( spaceDimension );
initialPosition[0] = 100;
initialPosition[1] = -100;
ScalesType parametersScale( spaceDimension );
parametersScale[0] = 1.0;
parametersScale[1] = 1.0;
itkOptimizer->MinimizeOn();
itkOptimizer->SetScales( parametersScale );
itkOptimizer->SetGradientMagnitudeTolerance( 1e-6 );
itkOptimizer->SetMaximumStepLength( 30.0 );
itkOptimizer->SetMinimumStepLength( 1e-6 );
itkOptimizer->SetNumberOfIterations( 900 );
itkOptimizer->SetInitialPosition( initialPosition );
try
{
itkOptimizer->StartOptimization();
}
catch( itk::ExceptionObject & e )
{
std::cout << "Exception thrown ! " << std::endl;
std::cout << "An error ocurred during Optimization" << std::endl;
std::cout << "Location = " << e.GetLocation() << std::endl;
std::cout << "Description = " << e.GetDescription() << std::endl;
return EXIT_FAILURE;
}
ParametersType finalPosition = itkOptimizer->GetCurrentPosition();
std::cout << "Solution = (";
std::cout << finalPosition[0] << "," ;
std::cout << finalPosition[1] << ")" << std::endl;
//
// check results to see if it is within range
//
bool pass = true;
double trueParameters[2] = { 2, -2 };
for( unsigned int j = 0; j < 2; j++ )
{
if( vnl_math_abs( finalPosition[j] - trueParameters[j] ) > 0.01 )
{
pass = false;
}
}
if( !pass )
{
std::cout << "Test failed." << std::endl;
return EXIT_FAILURE;
}
// Run now with a different relaxation factor
{
itkOptimizer->SetInitialPosition( initialPosition );
itkOptimizer->SetRelaxationFactor( 0.8 );
try
{
itkOptimizer->StartOptimization();
}
catch( itk::ExceptionObject & e )
{
std::cout << "Exception thrown ! " << std::endl;
std::cout << "An error ocurred during Optimization" << std::endl;
std::cout << "Location = " << e.GetLocation() << std::endl;
std::cout << "Description = " << e.GetDescription() << std::endl;
return EXIT_FAILURE;
}
finalPosition = itkOptimizer->GetCurrentPosition();
std::cout << "Solution = (";
std::cout << finalPosition[0] << "," ;
std::cout << finalPosition[1] << ")" << std::endl;
//
// check results to see if it is within range
//
pass = true;
for( unsigned int j = 0; j < 2; j++ )
{
if( vnl_math_abs( finalPosition[j] - trueParameters[j] ) > 0.01 )
{
pass = false;
}
}
if( !pass )
{
std::cout << "Test failed." << std::endl;
return EXIT_FAILURE;
}
}
//
// Verify that the optimizer doesn't run if the
// number of iterations is set to zero.
//
{
itkOptimizer->SetNumberOfIterations( 0 );
itkOptimizer->SetInitialPosition( initialPosition );
try
{
itkOptimizer->StartOptimization();
}
catch( itk::ExceptionObject & excp )
{
std::cout << excp << std::endl;
return EXIT_FAILURE;
}
if( itkOptimizer->GetCurrentIteration() > 0 )
{
std::cerr << "The optimizer is running iterations despite of ";
std::cerr << "having a maximum number of iterations set to zero" << std::endl;
return EXIT_FAILURE;
}
}
//
// Test the Exception if the GradientMagnitudeTolerance is set to a negative value
//
itkOptimizer->SetGradientMagnitudeTolerance( -1.0 );
bool expectedExceptionReceived = false;
try
{
itkOptimizer->StartOptimization();
}
catch( itk::ExceptionObject & excp )
{
expectedExceptionReceived = true;
std::cout << "Expected Exception " << std::endl;
std::cout << excp << std::endl;
}
if( !expectedExceptionReceived )
{
std::cerr << "Failure to produce an exception when";
std::cerr << "the GradientMagnitudeTolerance is negative " << std::endl;
std::cerr << "TEST FAILED !" << std::endl;
return EXIT_FAILURE;
}
std::cout << "TEST PASSED !" << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2014, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ----------------------------------------------------------------------
*/
/** @file
* Implementation of Connections
*/
#include <iostream>
#include <nta/algorithms/Connections.hpp>
using namespace std;
using namespace nta;
using namespace nta::algorithms::connections;
Connections::Connections(CellIdx numCells) : cells_(numCells)
{
}
Segment Connections::createSegment(const Cell& cell)
{
vector<SegmentData>& segments = cells_[cell.idx].segments;
Segment segment = {segments.size(), cell};
SegmentData segmentData;
segments.push_back(segmentData);
return segment;
}
Synapse Connections::createSynapse(const Segment& segment,
const Cell& presynapticCell,
Permanence permanence)
{
const Cell& cell = segment.cell;
vector<SynapseData>& synapses = cells_[cell.idx].segments[segment.idx].synapses;
Synapse synapse = {synapses.size(), segment};
SynapseData synapseData = {presynapticCell, permanence};
synapses.push_back(synapseData);
return synapse;
}
void Connections::updateSynapsePermanence(const Synapse& synapse,
Permanence permanence)
{
const Segment& segment = synapse.segment;
const Cell& cell = segment.cell;
cells_[cell.idx].segments[segment.idx].synapses[synapse.idx].permanence = permanence;
}
vector<Segment> Connections::getSegmentsForCell(const Cell& cell)
{
vector<Segment> segments;
Segment segment;
for(SegmentIdx i = 0; i < cells_[cell.idx].segments.size(); i++) {
segment.idx = i;
segment.cell = cell;
segments.push_back(segment);
}
return segments;
}
vector<Synapse> Connections::getSynapsesForSegment(const Segment& segment)
{
const Cell& cell = segment.cell;
vector<Synapse> synapses;
Synapse synapse;
for(SynapseIdx i = 0; i < cells_[cell.idx].segments[segment.idx].synapses.size(); i++) {
synapse.idx = i;
synapse.segment = segment;
synapses.push_back(synapse);
}
return synapses;
}
SynapseData Connections::getDataForSynapse(const Synapse& synapse) const
{
const Segment& segment = synapse.segment;
const Cell& cell = segment.cell;
return cells_[cell.idx].segments[segment.idx].synapses[synapse.idx];
}
bool Connections::getMostActiveSegmentForCells(const std::vector<Cell>& cells,
const std::vector<Cell>& input,
UInt synapseThreshold,
Segment& segment) const
{
return false;
}
Activity Connections::computeActivity(const std::vector<Cell>& input,
Permanence permanenceThreshold,
UInt synapseThreshold) const
{
Activity activity;
// vector<Synapse> synapses;
// SynapseData synapseData;
// Synapse synapse;
// for (vector<Cell>::const_iterator c = input.begin(); c != input.end(); c++) {
// synapses = synapsesForPresynapticCell_[*c];
// for (vector<Synapse>::const_iterator s = synapses.begin(); s != synapses.end(); s++) {
// synapseData = getDataForSynapse(*s);
// if (synapseData.permanence >= permanenceThreshold) {
// activity.numActiveSynapsesForSegment[synapse.segment] += 1;
// }
// if (activity.numActiveSynapsesForSegment[synapse.segment]) {
// activity.numActiveSegmentsForCell[*c] += 1;
// }
// }
// }
return activity;
}
<commit_msg>Added sample code for getMostActiveSegmentForCells<commit_after>/* ---------------------------------------------------------------------
* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2014, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ----------------------------------------------------------------------
*/
/** @file
* Implementation of Connections
*/
#include <iostream>
#include <nta/algorithms/Connections.hpp>
using namespace std;
using namespace nta;
using namespace nta::algorithms::connections;
Connections::Connections(CellIdx numCells) : cells_(numCells)
{
}
Segment Connections::createSegment(const Cell& cell)
{
vector<SegmentData>& segments = cells_[cell.idx].segments;
Segment segment = {segments.size(), cell};
SegmentData segmentData;
segments.push_back(segmentData);
return segment;
}
Synapse Connections::createSynapse(const Segment& segment,
const Cell& presynapticCell,
Permanence permanence)
{
const Cell& cell = segment.cell;
vector<SynapseData>& synapses = cells_[cell.idx].segments[segment.idx].synapses;
Synapse synapse = {synapses.size(), segment};
SynapseData synapseData = {presynapticCell, permanence};
synapses.push_back(synapseData);
return synapse;
}
void Connections::updateSynapsePermanence(const Synapse& synapse,
Permanence permanence)
{
const Segment& segment = synapse.segment;
const Cell& cell = segment.cell;
cells_[cell.idx].segments[segment.idx].synapses[synapse.idx].permanence = permanence;
}
vector<Segment> Connections::getSegmentsForCell(const Cell& cell)
{
vector<Segment> segments;
Segment segment;
for(SegmentIdx i = 0; i < cells_[cell.idx].segments.size(); i++) {
segment.idx = i;
segment.cell = cell;
segments.push_back(segment);
}
return segments;
}
vector<Synapse> Connections::getSynapsesForSegment(const Segment& segment)
{
const Cell& cell = segment.cell;
vector<Synapse> synapses;
Synapse synapse;
for(SynapseIdx i = 0; i < cells_[cell.idx].segments[segment.idx].synapses.size(); i++) {
synapse.idx = i;
synapse.segment = segment;
synapses.push_back(synapse);
}
return synapses;
}
SynapseData Connections::getDataForSynapse(const Synapse& synapse) const
{
const Segment& segment = synapse.segment;
const Cell& cell = segment.cell;
return cells_[cell.idx].segments[segment.idx].synapses[synapse.idx];
}
bool Connections::getMostActiveSegmentForCells(const std::vector<Cell>& cells,
const std::vector<Cell>& input,
UInt synapseThreshold,
Segment& segment) const
{
// UInt numSynapses, maxSynapses = synapseThreshold;
// vector<SegmentData> segments;
// vector<SynapseData> synapses;
bool found = false;
// for (vector<Cell>::const_iterator c = cells.begin(); c != cells.end(); c++) {
// segments = cells_[c->idx].segments;
// for (vector<SegmentData>::const_iterator s = segments.begin(); s != segments.end(); s++) {
// synapses = s->synapses;
// numSynapses = 0;
// for (vector<SynapseData>::const_iterator syn = synapses.begin(); syn != synapses.end(); syn++) {
// if (find(input.begin(), input.end(), syn->presynapticCell) != input.end()) { // TODO: Optimize this
// numSynapses++;
// }
// }
// if (numSynapses >= maxSynapses) {
// maxSynapses = numSynapses;
// segment.idx = s - segments.begin();
// segment.cell = *c;
// found = true;
// }
// }
// }
return found;
}
Activity Connections::computeActivity(const std::vector<Cell>& input,
Permanence permanenceThreshold,
UInt synapseThreshold) const
{
Activity activity;
// vector<Synapse> synapses;
// SynapseData synapseData;
// Synapse synapse;
// for (vector<Cell>::const_iterator c = input.begin(); c != input.end(); c++) {
// synapses = synapsesForPresynapticCell_[*c];
// for (vector<Synapse>::const_iterator s = synapses.begin(); s != synapses.end(); s++) {
// synapseData = getDataForSynapse(*s);
// if (synapseData.permanence >= permanenceThreshold) {
// activity.numActiveSynapsesForSegment[synapse.segment] += 1;
// }
// if (activity.numActiveSynapsesForSegment[synapse.segment]) {
// activity.numActiveSegmentsForCell[*c] += 1;
// }
// }
// }
return activity;
}
<|endoftext|>
|
<commit_before>/*******************************************************************************
* c7a/net/select-dispatcher.hpp
*
* Asynchronous callback wrapper around select()
*
* Part of Project c7a.
*
* Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#ifndef C7A_NET_SELECT_DISPATCHER_HEADER
#define C7A_NET_SELECT_DISPATCHER_HEADER
#include <c7a/net/socket.hpp>
#include <c7a/net/select.hpp>
#include <deque>
namespace c7a {
//! \addtogroup netsock Low Level Socket API
//! \{
/**
* SelectDispatcher is a higher level wrapper for select(). One can register
* Socket objects for readability and writability checks, buffered reads and
* writes with completion callbacks, and also timer functions.
*/
class SelectDispatcher : protected Select
{
static const bool debug = false;
public:
typedef std::function<bool (Socket&)> Callback;
//! Register a buffered read callback and a default exception callback.
void AddRead(Socket& s, const Callback& read_cb)
{
Select::SetRead(s.GetFileDescriptor());
Select::SetException(s.GetFileDescriptor());
watch_.emplace_back(s.GetFileDescriptor(), s,
read_cb, nullptr, ExceptionCallback);
}
//! Register a buffered write callback and a default exception callback.
void AddWrite(Socket& s, const Callback& write_cb)
{
Select::SetWrite(s.GetFileDescriptor());
Select::SetException(s.GetFileDescriptor());
watch_.emplace_back(s.GetFileDescriptor(), s,
nullptr, write_cb, ExceptionCallback);
}
//! Register a buffered write callback and a default exception callback.
void AddReadWrite(Socket& s,
const Callback& read_cb, const Callback& write_cb)
{
Select::SetRead(s.GetFileDescriptor());
Select::SetWrite(s.GetFileDescriptor());
Select::SetException(s.GetFileDescriptor());
watch_.emplace_back(s.GetFileDescriptor(), s,
read_cb, write_cb, ExceptionCallback);
}
void Dispatch(double timeout)
{
// copy select fdset
Select fdset = *this;
if (debug)
{
std::ostringstream oss;
for (Watch& w : watch_) {
oss << w.fd << " ";
}
oss << "| ";
for (int i = 0; i < Select::max_fd_ + 1; ++i) {
if (Select::InRead(i))
oss << "r" << i << " ";
if (Select::InWrite(i))
oss << "w" << i << " ";
if (Select::InException(i))
oss << "e" << i << " ";
}
LOG << "Performing select() on " << oss.str();
}
int r = fdset.select_timeout(timeout);
if (r < 0) {
throw NetException("OpenConnections() select() failed!", errno);
}
if (r == 0) return;
// save _current_ size, as it may change.
size_t watch_size = watch_.size();
for (size_t i = 0; i != watch_size; ++i)
{
Watch& w = watch_[i];
if (w.fd < 0) continue;
if (fdset.InRead(w.fd))
{
if (w.read_cb) {
// have to clear the read flag since the callback may add a
// new (other) callback for the same fd.
Select::ClearRead(w.fd);
Select::ClearException(w.fd);
if (!w.read_cb(w.socket)) {
// callback returned false: remove fd from set
w.fd = -1;
}
else {
Select::SetRead(w.fd);
Select::SetException(w.fd);
}
}
else {
LOG << "SelectDispatcher: got read event for fd "
<< w.fd << " without a read handler.";
Select::ClearRead(w.fd);
}
}
if (w.fd < 0) continue;
if (fdset.InWrite(w.fd))
{
if (w.write_cb) {
// have to clear the read flag since the callback may add a
// new (other) callback for the same fd.
Select::ClearWrite(w.fd);
Select::ClearException(w.fd);
if (!w.write_cb(w.socket)) {
// callback returned false: remove fd from set
w.fd = -1;
}
else {
Select::SetWrite(w.fd);
Select::SetException(w.fd);
}
}
else {
LOG << "SelectDispatcher: got write event for fd "
<< w.fd << " without a write handler.";
Select::ClearWrite(w.fd);
}
}
if (w.fd < 0) continue;
if (fdset.InException(w.fd))
{
if (w.except_cb) {
Select::ClearException(w.fd);
if (!w.except_cb(w.socket)) {
// callback returned false: remove fd from set
w.fd = -1;
}
else {
Select::SetException(w.fd);
}
}
else {
LOG << "SelectDispatcher: got exception event for fd "
<< w.fd << " without an exception handler.";
Select::ClearException(w.fd);
}
}
}
}
private:
//! struct to entries per watched file descriptor
struct Watch
{
int fd;
Socket socket;
Callback read_cb, write_cb, except_cb;
Watch(int _fd, Socket& _socket,
const Callback& _read_cb, const Callback& _write_cb,
const Callback& _except_cb)
: fd(_fd),
socket(_socket),
read_cb(_read_cb),
write_cb(_write_cb),
except_cb(_except_cb)
{ }
};
//! handlers for all registered file descriptors, we have to keep them
//! address local.
std::deque<Watch> watch_;
//! Default exception handler
static bool ExceptionCallback(Socket& s)
{
// exception on listen socket ?
throw NetException("SelectDispatcher() exception on socket fd "
+ std::to_string(s.GetFileDescriptor()) + "!",
errno);
}
};
//! \}
} // namespace c7a
#endif // !C7A_NET_SELECT_DISPATCHER_HEADER
/******************************************************************************/
<commit_msg>#include net-exception<commit_after>/*******************************************************************************
* c7a/net/select-dispatcher.hpp
*
* Asynchronous callback wrapper around select()
*
* Part of Project c7a.
*
* Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#ifndef C7A_NET_SELECT_DISPATCHER_HEADER
#define C7A_NET_SELECT_DISPATCHER_HEADER
#include <c7a/net/socket.hpp>
#include <c7a/net/select.hpp>
#include <c7a/net/net-exception.hpp>
#include <deque>
namespace c7a {
//! \addtogroup netsock Low Level Socket API
//! \{
/**
* SelectDispatcher is a higher level wrapper for select(). One can register
* Socket objects for readability and writability checks, buffered reads and
* writes with completion callbacks, and also timer functions.
*/
class SelectDispatcher : protected Select
{
static const bool debug = false;
public:
typedef std::function<bool (Socket&)> Callback;
//! Register a buffered read callback and a default exception callback.
void AddRead(Socket& s, const Callback& read_cb)
{
Select::SetRead(s.GetFileDescriptor());
Select::SetException(s.GetFileDescriptor());
watch_.emplace_back(s.GetFileDescriptor(), s,
read_cb, nullptr, ExceptionCallback);
}
//! Register a buffered write callback and a default exception callback.
void AddWrite(Socket& s, const Callback& write_cb)
{
Select::SetWrite(s.GetFileDescriptor());
Select::SetException(s.GetFileDescriptor());
watch_.emplace_back(s.GetFileDescriptor(), s,
nullptr, write_cb, ExceptionCallback);
}
//! Register a buffered write callback and a default exception callback.
void AddReadWrite(Socket& s,
const Callback& read_cb, const Callback& write_cb)
{
Select::SetRead(s.GetFileDescriptor());
Select::SetWrite(s.GetFileDescriptor());
Select::SetException(s.GetFileDescriptor());
watch_.emplace_back(s.GetFileDescriptor(), s,
read_cb, write_cb, ExceptionCallback);
}
void Dispatch(double timeout)
{
// copy select fdset
Select fdset = *this;
if (debug)
{
std::ostringstream oss;
for (Watch& w : watch_) {
oss << w.fd << " ";
}
oss << "| ";
for (int i = 0; i < Select::max_fd_ + 1; ++i) {
if (Select::InRead(i))
oss << "r" << i << " ";
if (Select::InWrite(i))
oss << "w" << i << " ";
if (Select::InException(i))
oss << "e" << i << " ";
}
LOG << "Performing select() on " << oss.str();
}
int r = fdset.select_timeout(timeout);
if (r < 0) {
throw NetException("OpenConnections() select() failed!", errno);
}
if (r == 0) return;
// save _current_ size, as it may change.
size_t watch_size = watch_.size();
for (size_t i = 0; i != watch_size; ++i)
{
Watch& w = watch_[i];
if (w.fd < 0) continue;
if (fdset.InRead(w.fd))
{
if (w.read_cb) {
// have to clear the read flag since the callback may add a
// new (other) callback for the same fd.
Select::ClearRead(w.fd);
Select::ClearException(w.fd);
if (!w.read_cb(w.socket)) {
// callback returned false: remove fd from set
w.fd = -1;
}
else {
Select::SetRead(w.fd);
Select::SetException(w.fd);
}
}
else {
LOG << "SelectDispatcher: got read event for fd "
<< w.fd << " without a read handler.";
Select::ClearRead(w.fd);
}
}
if (w.fd < 0) continue;
if (fdset.InWrite(w.fd))
{
if (w.write_cb) {
// have to clear the read flag since the callback may add a
// new (other) callback for the same fd.
Select::ClearWrite(w.fd);
Select::ClearException(w.fd);
if (!w.write_cb(w.socket)) {
// callback returned false: remove fd from set
w.fd = -1;
}
else {
Select::SetWrite(w.fd);
Select::SetException(w.fd);
}
}
else {
LOG << "SelectDispatcher: got write event for fd "
<< w.fd << " without a write handler.";
Select::ClearWrite(w.fd);
}
}
if (w.fd < 0) continue;
if (fdset.InException(w.fd))
{
if (w.except_cb) {
Select::ClearException(w.fd);
if (!w.except_cb(w.socket)) {
// callback returned false: remove fd from set
w.fd = -1;
}
else {
Select::SetException(w.fd);
}
}
else {
LOG << "SelectDispatcher: got exception event for fd "
<< w.fd << " without an exception handler.";
Select::ClearException(w.fd);
}
}
}
}
private:
//! struct to entries per watched file descriptor
struct Watch
{
int fd;
Socket socket;
Callback read_cb, write_cb, except_cb;
Watch(int _fd, Socket& _socket,
const Callback& _read_cb, const Callback& _write_cb,
const Callback& _except_cb)
: fd(_fd),
socket(_socket),
read_cb(_read_cb),
write_cb(_write_cb),
except_cb(_except_cb)
{ }
};
//! handlers for all registered file descriptors, we have to keep them
//! address local.
std::deque<Watch> watch_;
//! Default exception handler
static bool ExceptionCallback(Socket& s)
{
// exception on listen socket ?
throw NetException("SelectDispatcher() exception on socket fd "
+ std::to_string(s.GetFileDescriptor()) + "!",
errno);
}
};
//! \}
} // namespace c7a
#endif // !C7A_NET_SELECT_DISPATCHER_HEADER
/******************************************************************************/
<|endoftext|>
|
<commit_before>// Copyright (c) 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 "courgette/crc.h"
#ifdef OS_CHROMEOS
# include "zlib.h"
#else
extern "C" {
# include "third_party/lzma_sdk/7zCrc.h"
}
#endif
#include "base/basictypes.h"
namespace courgette {
uint32 CalculateCrc(const uint8* buffer, size_t size) {
uint32 crc;
#ifdef OS_CHROMEOS
// Calculate Crc by calling CRC method in zlib
crc = crc32(0, buffer, size);
#else
// Calculate Crc by calling CRC method in LZMA SDK
CrcGenerateTable();
crc = CrcCalc(buffer, size);
#endif
return ~crc;
}
} // namespace
<commit_msg>Revert 112083 - Try a different library for Crc32.<commit_after>// Copyright (c) 2009 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.
// Calculate Crc by calling CRC method in LZMA SDK
#include "courgette/crc.h"
extern "C" {
#include "third_party/lzma_sdk/7zCrc.h"
}
namespace courgette {
uint32 CalculateCrc(const uint8* buffer, size_t size) {
CrcGenerateTable();
uint32 crc = 0xffffffffL;
crc = ~CrcCalc(buffer, size);
return crc;
}
} // namespace
<|endoftext|>
|
<commit_before>// RUN: rm -rf %t
// RUN: mkdir %t
// RUN: c-index-test -test-load-source all -comments-xml-schema=%S/../../bindings/xml/comment-xml-schema.rng -target x86_64-apple-darwin10 std=c++11 %s > %t/out
// RUN: FileCheck %s < %t/out
// Ensure that XML we generate is not invalid.
// RUN: FileCheck %s -check-prefix=WRONG < %t/out
// WRONG-NOT: CommentXMLInvalid
// rdar://12378714
/**
* \brief Aaa
*/
template<typename T> struct A {
/**
* \brief Bbb
*/
A();
/**
* \brief Ccc
*/
~A();
/**
* \brief Ddd
*/
void f() { }
};
// CHECK: <Declaration>template <typename T> struct A {\n}</Declaration>
// CHECL: <Declaration>A<T>()</Declaration>
// CHECK: <Declaration>void ~A<T>()</Declaration>
/**
* \Brief Eee
*/
template <typename T> struct D : A<T> {
/**
* \brief
*/
using A<T>::f;
void f();
};
// CHECK: <Declaration>template <typename T> struct D : A<T> {\n}</Declaration>
// CHECK: <Declaration>using A<T>::f</Declaration>
struct Base {
int foo;
};
/**
* \brief
*/
template<typename T> struct E : Base {
/**
* \brief
*/
using Base::foo;
};
// CHECK: <Declaration>template <typename T> struct E : Base {\n}</Declaration>
// CHECK: <Declaration>using Base::foo</Declaration>
/// \tparam
/// \param AAA Blah blah
template<typename T>
void func_template_1(T AAA);
// CHECK: <Declaration>template <typename T> void func_template_1(T AAA)</Declaration>
template<template<template<typename CCC> class DDD, class BBB> class AAA>
void func_template_2();
<Declaration>template <template <template <typename CCC> class DDD, class BBB> class AAA> void func_template_2()</Declaration>
<commit_msg>Fixes a typo in this test.<commit_after>// RUN: rm -rf %t
// RUN: mkdir %t
// RUN: c-index-test -test-load-source all -comments-xml-schema=%S/../../bindings/xml/comment-xml-schema.rng -target x86_64-apple-darwin10 std=c++11 %s > %t/out
// RUN: FileCheck %s < %t/out
// Ensure that XML we generate is not invalid.
// RUN: FileCheck %s -check-prefix=WRONG < %t/out
// WRONG-NOT: CommentXMLInvalid
// rdar://12378714
/**
* \brief Aaa
*/
template<typename T> struct A {
/**
* \brief Bbb
*/
A();
/**
* \brief Ccc
*/
~A();
/**
* \brief Ddd
*/
void f() { }
};
// CHECK: <Declaration>template <typename T> struct A {\n}</Declaration>
// CHECK: <Declaration>A<T>()</Declaration>
// CHECK: <Declaration>void ~A<T>()</Declaration>
/**
* \Brief Eee
*/
template <typename T> struct D : A<T> {
/**
* \brief
*/
using A<T>::f;
void f();
};
// CHECK: <Declaration>template <typename T> struct D : A<T> {\n}</Declaration>
// CHECK: <Declaration>using A<T>::f</Declaration>
struct Base {
int foo;
};
/**
* \brief
*/
template<typename T> struct E : Base {
/**
* \brief
*/
using Base::foo;
};
// CHECK: <Declaration>template <typename T> struct E : Base {\n}</Declaration>
// CHECK: <Declaration>using Base::foo</Declaration>
/// \tparam
/// \param AAA Blah blah
template<typename T>
void func_template_1(T AAA);
// CHECK: <Declaration>template <typename T> void func_template_1(T AAA)</Declaration>
template<template<template<typename CCC> class DDD, class BBB> class AAA>
void func_template_2();
<Declaration>template <template <template <typename CCC> class DDD, class BBB> class AAA> void func_template_2()</Declaration>
<|endoftext|>
|
<commit_before>/*
* This file is part of ofono-qt
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
*
* Contact: Alexander Kanavin <alex.kanavin@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QtTest/QtTest>
#include "qofonoradiosettings.h"
#include <QtDebug>
class TestQOfonoRadioSettings : public QObject
{
Q_OBJECT
private slots:
void initTestCase()
{
m = new QOfonoRadioSettings(this);
m->setModemPath("/phonesim");
QEXPECT_FAIL("", "FIXME: radio settings interface is not supported by AT modems, "
"and consequently, phonesim", Abort);
QTRY_VERIFY(m->isValid());
}
void testQOfonoRadioSettings()
{
QSignalSpy preference(m, SIGNAL(technologyPreferenceChanged(QString)));
qDebug() << "technologyPreference():" << m->technologyPreference();
}
void cleanupTestCase()
{
}
private:
QOfonoRadioSettings *m;
};
QTEST_MAIN(TestQOfonoRadioSettings)
#include "tst_qofonoradiosettings.moc"
<commit_msg>[tests] Fixed tst_qofonoradiosettings<commit_after>/*
* This file is part of ofono-qt
*
* Copyright (C) 2014-2015 Jolla Ltd.
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
*
* Contact: Alexander Kanavin <alex.kanavin@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QtTest/QtTest>
#include "qofonoradiosettings.h"
class TestQOfonoRadioSettings : public QObject
{
Q_OBJECT
private slots:
void initTestCase()
{
m = new QOfonoRadioSettings(this);
m->setModemPath("/phonesim");
QTRY_VERIFY(m->isValid());
}
void testQOfonoRadioSettings()
{
QCOMPARE(m->technologyPreference(), QString("any"));
}
void cleanupTestCase()
{
}
private:
QOfonoRadioSettings *m;
};
QTEST_MAIN(TestQOfonoRadioSettings)
#include "tst_qofonoradiosettings.moc"
<|endoftext|>
|
<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2019, PickNik LLC
* 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 PickNik LLC 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.
*********************************************************************/
/* Author: Henning Kayser */
#include <stdexcept>
#include <moveit/moveit_cpp/moveit_cpp.h>
namespace moveit_cpp
{
constexpr char LOGNAME[] = "moveit_cpp";
constexpr char PLANNING_PLUGIN_PARAM[] = "planning_plugin";
MoveItCpp::MoveItCpp(const ros::NodeHandle& nh, const std::shared_ptr<tf2_ros::Buffer>& tf_buffer)
: MoveItCpp(Options(nh), nh, tf_buffer)
{
}
MoveItCpp::MoveItCpp(const Options& options, const ros::NodeHandle& nh,
const std::shared_ptr<tf2_ros::Buffer>& tf_buffer)
: tf_buffer_(tf_buffer), node_handle_(nh)
{
if (!tf_buffer_)
tf_buffer_ = std::make_shared<tf2_ros::Buffer>();
tf_listener_ = std::make_shared<tf2_ros::TransformListener>(*tf_buffer_);
// Configure planning scene monitor
if (!loadPlanningSceneMonitor(options.planning_scene_monitor_options))
{
const std::string error = "Unable to configure planning scene monitor";
ROS_FATAL_STREAM_NAMED(LOGNAME, error);
throw std::runtime_error(error);
}
robot_model_ = planning_scene_monitor_->getRobotModel();
if (!robot_model_)
{
const std::string error = "Unable to construct robot model. Please make sure all needed information is on the "
"parameter server.";
ROS_FATAL_STREAM_NAMED(LOGNAME, error);
throw std::runtime_error(error);
}
bool load_planning_pipelines = true;
if (load_planning_pipelines && !loadPlanningPipelines(options.planning_pipeline_options))
{
const std::string error = "Failed to load planning pipelines from parameter server";
ROS_FATAL_STREAM_NAMED(LOGNAME, error);
throw std::runtime_error(error);
}
// TODO(henningkayser): configure trajectory execution manager
trajectory_execution_manager_ = std::make_shared<trajectory_execution_manager::TrajectoryExecutionManager>(
robot_model_, planning_scene_monitor_->getStateMonitor());
ROS_DEBUG_NAMED(LOGNAME, "MoveItCpp running");
}
MoveItCpp::~MoveItCpp()
{
ROS_INFO_NAMED(LOGNAME, "Deleting MoveItCpp");
clearContents();
}
bool MoveItCpp::loadPlanningSceneMonitor(const PlanningSceneMonitorOptions& options)
{
planning_scene_monitor_ = std::make_shared<planning_scene_monitor::PlanningSceneMonitor>(options.robot_description,
tf_buffer_, options.name);
// Allows us to sycronize to Rviz and also publish collision objects to ourselves
ROS_DEBUG_STREAM_NAMED(LOGNAME, "Configuring Planning Scene Monitor");
if (planning_scene_monitor_->getPlanningScene())
{
// Start state and scene monitors
ROS_INFO_NAMED(LOGNAME, "Listening to '%s' for joint states", options.joint_state_topic.c_str());
// Subscribe to JointState sensor messages
planning_scene_monitor_->startStateMonitor(options.joint_state_topic, options.attached_collision_object_topic);
// Publish planning scene updates to remote monitors like RViz
planning_scene_monitor_->startPublishingPlanningScene(planning_scene_monitor::PlanningSceneMonitor::UPDATE_SCENE,
options.monitored_planning_scene_topic);
// Monitor and apply planning scene updates from remote publishers like the PlanningSceneInterface
planning_scene_monitor_->startSceneMonitor(options.publish_planning_scene_topic);
// Monitor requests for changes in the collision environment
planning_scene_monitor_->startWorldGeometryMonitor();
}
else
{
ROS_ERROR_STREAM_NAMED(LOGNAME, "Planning scene not configured");
return false;
}
// Wait for complete state to be recieved
if (options.wait_for_initial_state_timeout > 0.0)
{
return planning_scene_monitor_->getStateMonitor()->waitForCurrentState(ros::Time::now(),
options.wait_for_initial_state_timeout);
}
return true;
}
bool MoveItCpp::loadPlanningPipelines(const PlanningPipelineOptions& options)
{
ros::NodeHandle node_handle(options.parent_namespace.empty() ? "~" : options.parent_namespace);
for (const auto& planning_pipeline_name : options.pipeline_names)
{
if (planning_pipelines_.count(planning_pipeline_name) > 0)
{
ROS_WARN_NAMED(LOGNAME, "Skipping duplicate entry for planning pipeline '%s'.", planning_pipeline_name.c_str());
continue;
}
ROS_INFO_NAMED(LOGNAME, "Loading planning pipeline '%s'", planning_pipeline_name.c_str());
ros::NodeHandle child_nh(node_handle, planning_pipeline_name);
planning_pipeline::PlanningPipelinePtr pipeline;
pipeline = std::make_shared<planning_pipeline::PlanningPipeline>(robot_model_, child_nh, PLANNING_PLUGIN_PARAM);
if (!pipeline->getPlannerManager())
{
ROS_ERROR_NAMED(LOGNAME, "Failed to initialize planning pipeline '%s'.", planning_pipeline_name.c_str());
continue;
}
planning_pipelines_[planning_pipeline_name] = pipeline;
}
if (planning_pipelines_.empty())
{
ROS_ERROR_NAMED(LOGNAME, "Failed to load any planning pipelines.");
return false;
}
// Retrieve group/pipeline mapping for faster lookup
std::vector<std::string> group_names = robot_model_->getJointModelGroupNames();
for (const auto& pipeline_entry : planning_pipelines_)
{
for (const auto& group_name : group_names)
{
groups_pipelines_map_[group_name] = {};
const auto& pipeline = pipeline_entry.second;
for (const auto& planner_configuration : pipeline->getPlannerManager()->getPlannerConfigurations())
{
if (planner_configuration.second.group == group_name)
{
groups_pipelines_map_[group_name].insert(pipeline_entry.first);
}
}
}
}
return true;
}
moveit::core::RobotModelConstPtr MoveItCpp::getRobotModel() const
{
return robot_model_;
}
const ros::NodeHandle& MoveItCpp::getNodeHandle() const
{
return node_handle_;
}
bool MoveItCpp::getCurrentState(moveit::core::RobotStatePtr& current_state, double wait_seconds)
{
if (wait_seconds > 0.0 &&
!planning_scene_monitor_->getStateMonitor()->waitForCurrentState(ros::Time::now(), wait_seconds))
{
ROS_ERROR_NAMED(LOGNAME, "Did not receive robot state");
return false;
}
{ // Lock planning scene
planning_scene_monitor::LockedPlanningSceneRO scene(planning_scene_monitor_);
current_state = std::make_shared<moveit::core::RobotState>(scene->getCurrentState());
} // Unlock planning scene
return true;
}
moveit::core::RobotStatePtr MoveItCpp::getCurrentState(double wait)
{
moveit::core::RobotStatePtr current_state;
getCurrentState(current_state, wait);
return current_state;
}
const std::map<std::string, planning_pipeline::PlanningPipelinePtr>& MoveItCpp::getPlanningPipelines() const
{
return planning_pipelines_;
}
std::set<std::string> MoveItCpp::getPlanningPipelineNames(const std::string& group_name) const
{
std::set<std::string> result_names;
if (!group_name.empty() && groups_pipelines_map_.count(group_name) == 0)
{
ROS_ERROR_NAMED(LOGNAME,
"No planning pipelines loaded for group '%s'. Check planning pipeline and controller setup.",
group_name.c_str());
return result_names; // empty
}
for (const auto& pipeline_entry : planning_pipelines_)
{
const std::string& pipeline_name = pipeline_entry.first;
// If group_name is defined and valid, skip pipelines that don't belong to the planning group
if (!group_name.empty())
{
const auto& group_pipelines = groups_pipelines_map_.at(group_name);
if (group_pipelines.find(pipeline_name) == group_pipelines.end())
continue;
}
result_names.insert(pipeline_name);
}
// No valid planning pipelines
if (result_names.empty())
ROS_ERROR_NAMED(LOGNAME,
"No planning pipelines loaded for group '%s'. Check planning pipeline and controller setup.",
group_name.c_str());
return result_names;
}
const planning_scene_monitor::PlanningSceneMonitorPtr& MoveItCpp::getPlanningSceneMonitor() const
{
return planning_scene_monitor_;
}
planning_scene_monitor::PlanningSceneMonitorPtr MoveItCpp::getPlanningSceneMonitorNonConst()
{
return planning_scene_monitor_;
}
const trajectory_execution_manager::TrajectoryExecutionManagerPtr& MoveItCpp::getTrajectoryExecutionManager() const
{
return trajectory_execution_manager_;
}
trajectory_execution_manager::TrajectoryExecutionManagerPtr MoveItCpp::getTrajectoryExecutionManagerNonConst()
{
return trajectory_execution_manager_;
}
bool MoveItCpp::execute(const std::string& group_name, const robot_trajectory::RobotTrajectoryPtr& robot_trajectory,
bool blocking)
{
if (!robot_trajectory)
{
ROS_ERROR_NAMED(LOGNAME, "Robot trajectory is undefined");
return false;
}
// Check if there are controllers that can handle the execution
if (!trajectory_execution_manager_->ensureActiveControllersForGroup(group_name))
{
ROS_ERROR_NAMED(LOGNAME, "Execution failed! No active controllers configured for group '%s'", group_name.c_str());
return false;
}
// Execute trajectory
moveit_msgs::RobotTrajectory robot_trajectory_msg;
robot_trajectory->getRobotTrajectoryMsg(robot_trajectory_msg);
if (blocking)
{
trajectory_execution_manager_->push(robot_trajectory_msg);
trajectory_execution_manager_->execute();
return trajectory_execution_manager_->waitForExecution();
}
trajectory_execution_manager_->pushAndExecute(robot_trajectory_msg);
return true;
}
const std::shared_ptr<tf2_ros::Buffer>& MoveItCpp::getTFBuffer() const
{
return tf_buffer_;
}
void MoveItCpp::clearContents()
{
tf_listener_.reset();
tf_buffer_.reset();
planning_scene_monitor_.reset();
robot_model_.reset();
planning_pipelines_.clear();
}
} // namespace moveit_cpp
<commit_msg>MoveItCpp: Allow multiple pipelines (#3131)<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2019, PickNik LLC
* 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 PickNik LLC 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.
*********************************************************************/
/* Author: Henning Kayser */
#include <stdexcept>
#include <moveit/moveit_cpp/moveit_cpp.h>
namespace moveit_cpp
{
constexpr char LOGNAME[] = "moveit_cpp";
constexpr char PLANNING_PLUGIN_PARAM[] = "planning_plugin";
MoveItCpp::MoveItCpp(const ros::NodeHandle& nh, const std::shared_ptr<tf2_ros::Buffer>& tf_buffer)
: MoveItCpp(Options(nh), nh, tf_buffer)
{
}
MoveItCpp::MoveItCpp(const Options& options, const ros::NodeHandle& nh,
const std::shared_ptr<tf2_ros::Buffer>& tf_buffer)
: tf_buffer_(tf_buffer), node_handle_(nh)
{
if (!tf_buffer_)
tf_buffer_ = std::make_shared<tf2_ros::Buffer>();
tf_listener_ = std::make_shared<tf2_ros::TransformListener>(*tf_buffer_);
// Configure planning scene monitor
if (!loadPlanningSceneMonitor(options.planning_scene_monitor_options))
{
const std::string error = "Unable to configure planning scene monitor";
ROS_FATAL_STREAM_NAMED(LOGNAME, error);
throw std::runtime_error(error);
}
robot_model_ = planning_scene_monitor_->getRobotModel();
if (!robot_model_)
{
const std::string error = "Unable to construct robot model. Please make sure all needed information is on the "
"parameter server.";
ROS_FATAL_STREAM_NAMED(LOGNAME, error);
throw std::runtime_error(error);
}
bool load_planning_pipelines = true;
if (load_planning_pipelines && !loadPlanningPipelines(options.planning_pipeline_options))
{
const std::string error = "Failed to load planning pipelines from parameter server";
ROS_FATAL_STREAM_NAMED(LOGNAME, error);
throw std::runtime_error(error);
}
// TODO(henningkayser): configure trajectory execution manager
trajectory_execution_manager_ = std::make_shared<trajectory_execution_manager::TrajectoryExecutionManager>(
robot_model_, planning_scene_monitor_->getStateMonitor());
ROS_DEBUG_NAMED(LOGNAME, "MoveItCpp running");
}
MoveItCpp::~MoveItCpp()
{
ROS_INFO_NAMED(LOGNAME, "Deleting MoveItCpp");
clearContents();
}
bool MoveItCpp::loadPlanningSceneMonitor(const PlanningSceneMonitorOptions& options)
{
planning_scene_monitor_ = std::make_shared<planning_scene_monitor::PlanningSceneMonitor>(options.robot_description,
tf_buffer_, options.name);
// Allows us to sycronize to Rviz and also publish collision objects to ourselves
ROS_DEBUG_STREAM_NAMED(LOGNAME, "Configuring Planning Scene Monitor");
if (planning_scene_monitor_->getPlanningScene())
{
// Start state and scene monitors
ROS_INFO_NAMED(LOGNAME, "Listening to '%s' for joint states", options.joint_state_topic.c_str());
// Subscribe to JointState sensor messages
planning_scene_monitor_->startStateMonitor(options.joint_state_topic, options.attached_collision_object_topic);
// Publish planning scene updates to remote monitors like RViz
planning_scene_monitor_->startPublishingPlanningScene(planning_scene_monitor::PlanningSceneMonitor::UPDATE_SCENE,
options.monitored_planning_scene_topic);
// Monitor and apply planning scene updates from remote publishers like the PlanningSceneInterface
planning_scene_monitor_->startSceneMonitor(options.publish_planning_scene_topic);
// Monitor requests for changes in the collision environment
planning_scene_monitor_->startWorldGeometryMonitor();
}
else
{
ROS_ERROR_STREAM_NAMED(LOGNAME, "Planning scene not configured");
return false;
}
// Wait for complete state to be recieved
if (options.wait_for_initial_state_timeout > 0.0)
{
return planning_scene_monitor_->getStateMonitor()->waitForCurrentState(ros::Time::now(),
options.wait_for_initial_state_timeout);
}
return true;
}
bool MoveItCpp::loadPlanningPipelines(const PlanningPipelineOptions& options)
{
ros::NodeHandle node_handle(options.parent_namespace.empty() ? "~" : options.parent_namespace);
for (const auto& planning_pipeline_name : options.pipeline_names)
{
if (planning_pipelines_.count(planning_pipeline_name) > 0)
{
ROS_WARN_NAMED(LOGNAME, "Skipping duplicate entry for planning pipeline '%s'.", planning_pipeline_name.c_str());
continue;
}
ROS_INFO_NAMED(LOGNAME, "Loading planning pipeline '%s'", planning_pipeline_name.c_str());
ros::NodeHandle child_nh(node_handle, planning_pipeline_name);
planning_pipeline::PlanningPipelinePtr pipeline;
pipeline = std::make_shared<planning_pipeline::PlanningPipeline>(robot_model_, child_nh, PLANNING_PLUGIN_PARAM);
if (!pipeline->getPlannerManager())
{
ROS_ERROR_NAMED(LOGNAME, "Failed to initialize planning pipeline '%s'.", planning_pipeline_name.c_str());
continue;
}
planning_pipelines_[planning_pipeline_name] = pipeline;
}
if (planning_pipelines_.empty())
{
ROS_ERROR_NAMED(LOGNAME, "Failed to load any planning pipelines.");
return false;
}
// Retrieve group/pipeline mapping for faster lookup
std::vector<std::string> group_names = robot_model_->getJointModelGroupNames();
for (const auto& pipeline_entry : planning_pipelines_)
{
for (const auto& group_name : group_names)
{
const auto& pipeline = pipeline_entry.second;
for (const auto& planner_configuration : pipeline->getPlannerManager()->getPlannerConfigurations())
{
if (planner_configuration.second.group == group_name)
{
groups_pipelines_map_[group_name].insert(pipeline_entry.first);
}
}
}
}
return true;
}
moveit::core::RobotModelConstPtr MoveItCpp::getRobotModel() const
{
return robot_model_;
}
const ros::NodeHandle& MoveItCpp::getNodeHandle() const
{
return node_handle_;
}
bool MoveItCpp::getCurrentState(moveit::core::RobotStatePtr& current_state, double wait_seconds)
{
if (wait_seconds > 0.0 &&
!planning_scene_monitor_->getStateMonitor()->waitForCurrentState(ros::Time::now(), wait_seconds))
{
ROS_ERROR_NAMED(LOGNAME, "Did not receive robot state");
return false;
}
{ // Lock planning scene
planning_scene_monitor::LockedPlanningSceneRO scene(planning_scene_monitor_);
current_state = std::make_shared<moveit::core::RobotState>(scene->getCurrentState());
} // Unlock planning scene
return true;
}
moveit::core::RobotStatePtr MoveItCpp::getCurrentState(double wait)
{
moveit::core::RobotStatePtr current_state;
getCurrentState(current_state, wait);
return current_state;
}
const std::map<std::string, planning_pipeline::PlanningPipelinePtr>& MoveItCpp::getPlanningPipelines() const
{
return planning_pipelines_;
}
std::set<std::string> MoveItCpp::getPlanningPipelineNames(const std::string& group_name) const
{
if (group_name.empty() || groups_pipelines_map_.count(group_name) == 0)
{
ROS_ERROR_NAMED(LOGNAME,
"No planning pipelines loaded for group '%s'. Check planning pipeline and controller setup.",
group_name.c_str());
return {}; // empty
}
return groups_pipelines_map_.at(group_name);
}
const planning_scene_monitor::PlanningSceneMonitorPtr& MoveItCpp::getPlanningSceneMonitor() const
{
return planning_scene_monitor_;
}
planning_scene_monitor::PlanningSceneMonitorPtr MoveItCpp::getPlanningSceneMonitorNonConst()
{
return planning_scene_monitor_;
}
const trajectory_execution_manager::TrajectoryExecutionManagerPtr& MoveItCpp::getTrajectoryExecutionManager() const
{
return trajectory_execution_manager_;
}
trajectory_execution_manager::TrajectoryExecutionManagerPtr MoveItCpp::getTrajectoryExecutionManagerNonConst()
{
return trajectory_execution_manager_;
}
bool MoveItCpp::execute(const std::string& group_name, const robot_trajectory::RobotTrajectoryPtr& robot_trajectory,
bool blocking)
{
if (!robot_trajectory)
{
ROS_ERROR_NAMED(LOGNAME, "Robot trajectory is undefined");
return false;
}
// Check if there are controllers that can handle the execution
if (!trajectory_execution_manager_->ensureActiveControllersForGroup(group_name))
{
ROS_ERROR_NAMED(LOGNAME, "Execution failed! No active controllers configured for group '%s'", group_name.c_str());
return false;
}
// Execute trajectory
moveit_msgs::RobotTrajectory robot_trajectory_msg;
robot_trajectory->getRobotTrajectoryMsg(robot_trajectory_msg);
if (blocking)
{
trajectory_execution_manager_->push(robot_trajectory_msg);
trajectory_execution_manager_->execute();
return trajectory_execution_manager_->waitForExecution();
}
trajectory_execution_manager_->pushAndExecute(robot_trajectory_msg);
return true;
}
const std::shared_ptr<tf2_ros::Buffer>& MoveItCpp::getTFBuffer() const
{
return tf_buffer_;
}
void MoveItCpp::clearContents()
{
tf_listener_.reset();
tf_buffer_.reset();
planning_scene_monitor_.reset();
robot_model_.reset();
planning_pipelines_.clear();
}
} // namespace moveit_cpp
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2010-2013 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2002-2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
*/
#include "arch/arm/linux/atag.hh"
#include "arch/arm/linux/system.hh"
#include "arch/arm/isa_traits.hh"
#include "arch/arm/utility.hh"
#include "arch/generic/linux/threadinfo.hh"
#include "base/loader/dtb_object.hh"
#include "base/loader/object_file.hh"
#include "base/loader/symtab.hh"
#include "cpu/base.hh"
#include "cpu/pc_event.hh"
#include "cpu/thread_context.hh"
#include "debug/Loader.hh"
#include "kern/linux/events.hh"
#include "mem/fs_translating_port_proxy.hh"
#include "mem/physical.hh"
#include "sim/stat_control.hh"
using namespace ArmISA;
using namespace Linux;
LinuxArmSystem::LinuxArmSystem(Params *p)
: GenericArmSystem(p), dumpStatsPCEvent(nullptr),
enableContextSwitchStatsDump(p->enable_context_switch_stats_dump),
taskFile(nullptr), kernelPanicEvent(nullptr), kernelOopsEvent(nullptr)
{
if (p->panic_on_panic) {
kernelPanicEvent = addKernelFuncEventOrPanic<PanicPCEvent>(
"panic", "Kernel panic in simulated kernel");
} else {
#ifndef NDEBUG
kernelPanicEvent = addKernelFuncEventOrPanic<BreakPCEvent>("panic");
#endif
}
if (p->panic_on_oops) {
kernelOopsEvent = addKernelFuncEventOrPanic<PanicPCEvent>(
"oops_exit", "Kernel oops in guest");
}
// With ARM udelay() is #defined to __udelay
// newer kernels use __loop_udelay and __loop_const_udelay symbols
uDelaySkipEvent = addKernelFuncEvent<UDelayEvent>(
"__loop_udelay", "__udelay", 1000, 0);
if (!uDelaySkipEvent)
uDelaySkipEvent = addKernelFuncEventOrPanic<UDelayEvent>(
"__udelay", "__udelay", 1000, 0);
// constant arguments to udelay() have some precomputation done ahead of
// time. Constant comes from code.
constUDelaySkipEvent = addKernelFuncEvent<UDelayEvent>(
"__loop_const_udelay", "__const_udelay", 1000, 107374);
if (!constUDelaySkipEvent)
constUDelaySkipEvent = addKernelFuncEventOrPanic<UDelayEvent>(
"__const_udelay", "__const_udelay", 1000, 107374);
}
void
LinuxArmSystem::initState()
{
// Moved from the constructor to here since it relies on the
// address map being resolved in the interconnect
// Call the initialisation of the super class
GenericArmSystem::initState();
// Load symbols at physical address, we might not want
// to do this permanently, for but early bootup work
// it is helpful.
if (params()->early_kernel_symbols) {
kernel->loadGlobalSymbols(kernelSymtab, 0, 0, loadAddrMask);
kernel->loadGlobalSymbols(debugSymbolTable, 0, 0, loadAddrMask);
}
// Setup boot data structure
Addr addr = 0;
// Check if the kernel image has a symbol that tells us it supports
// device trees.
bool kernel_has_fdt_support =
kernelSymtab->findAddress("unflatten_device_tree", addr);
bool dtb_file_specified = params()->dtb_filename != "";
if (kernel_has_fdt_support && dtb_file_specified) {
// Kernel supports flattened device tree and dtb file specified.
// Using Device Tree Blob to describe system configuration.
inform("Loading DTB file: %s at address %#x\n", params()->dtb_filename,
params()->atags_addr + loadAddrOffset);
ObjectFile *dtb_file = createObjectFile(params()->dtb_filename, true);
if (!dtb_file) {
fatal("couldn't load DTB file: %s\n", params()->dtb_filename);
}
DtbObject *_dtb_file = dynamic_cast<DtbObject*>(dtb_file);
if (_dtb_file) {
if (!_dtb_file->addBootCmdLine(params()->boot_osflags.c_str(),
params()->boot_osflags.size())) {
warn("couldn't append bootargs to DTB file: %s\n",
params()->dtb_filename);
}
} else {
warn("dtb_file cast failed; couldn't append bootargs "
"to DTB file: %s\n", params()->dtb_filename);
}
dtb_file->setTextBase(params()->atags_addr + loadAddrOffset);
dtb_file->loadSections(physProxy);
delete dtb_file;
} else {
// Using ATAGS
// Warn if the kernel supports FDT and we haven't specified one
if (kernel_has_fdt_support) {
assert(!dtb_file_specified);
warn("Kernel supports device tree, but no DTB file specified\n");
}
// Warn if the kernel doesn't support FDT and we have specified one
if (dtb_file_specified) {
assert(!kernel_has_fdt_support);
warn("DTB file specified, but no device tree support in kernel\n");
}
AtagCore ac;
ac.flags(1); // read-only
ac.pagesize(8192);
ac.rootdev(0);
AddrRangeList atagRanges = physmem.getConfAddrRanges();
if (atagRanges.size() != 1) {
fatal("Expected a single ATAG memory entry but got %d\n",
atagRanges.size());
}
AtagMem am;
am.memSize(atagRanges.begin()->size());
am.memStart(atagRanges.begin()->start());
AtagCmdline ad;
ad.cmdline(params()->boot_osflags);
DPRINTF(Loader, "boot command line %d bytes: %s\n",
ad.size() <<2, params()->boot_osflags.c_str());
AtagNone an;
uint32_t size = ac.size() + am.size() + ad.size() + an.size();
uint32_t offset = 0;
uint8_t *boot_data = new uint8_t[size << 2];
offset += ac.copyOut(boot_data + offset);
offset += am.copyOut(boot_data + offset);
offset += ad.copyOut(boot_data + offset);
offset += an.copyOut(boot_data + offset);
DPRINTF(Loader, "Boot atags was %d bytes in total\n", size << 2);
DDUMP(Loader, boot_data, size << 2);
physProxy.writeBlob(params()->atags_addr + loadAddrOffset, boot_data,
size << 2);
delete[] boot_data;
}
// Kernel boot requirements to set up r0, r1 and r2 in ARMv7
for (int i = 0; i < threadContexts.size(); i++) {
threadContexts[i]->setIntReg(0, 0);
threadContexts[i]->setIntReg(1, params()->machine_type);
threadContexts[i]->setIntReg(2, params()->atags_addr + loadAddrOffset);
}
}
LinuxArmSystem::~LinuxArmSystem()
{
if (uDelaySkipEvent)
delete uDelaySkipEvent;
if (constUDelaySkipEvent)
delete constUDelaySkipEvent;
if (dumpStatsPCEvent)
delete dumpStatsPCEvent;
}
LinuxArmSystem *
LinuxArmSystemParams::create()
{
return new LinuxArmSystem(this);
}
void
LinuxArmSystem::startup()
{
if (enableContextSwitchStatsDump) {
dumpStatsPCEvent = addKernelFuncEvent<DumpStatsPCEvent>("__switch_to");
if (!dumpStatsPCEvent)
panic("dumpStatsPCEvent not created!");
std::string task_filename = "tasks.txt";
taskFile = simout.create(name() + "." + task_filename);
for (int i = 0; i < _numContexts; i++) {
ThreadContext *tc = threadContexts[i];
uint32_t pid = tc->getCpuPtr()->getPid();
if (pid != BaseCPU::invldPid) {
mapPid(tc, pid);
tc->getCpuPtr()->taskId(taskMap[pid]);
}
}
}
}
void
LinuxArmSystem::mapPid(ThreadContext *tc, uint32_t pid)
{
// Create a new unique identifier for this pid
std::map<uint32_t, uint32_t>::iterator itr = taskMap.find(pid);
if (itr == taskMap.end()) {
uint32_t map_size = taskMap.size();
if (map_size > ContextSwitchTaskId::MaxNormalTaskId + 1) {
warn_once("Error out of identifiers for cache occupancy stats");
taskMap[pid] = ContextSwitchTaskId::Unknown;
} else {
taskMap[pid] = map_size;
}
}
}
/** This function is called whenever the the kernel function
* "__switch_to" is called to change running tasks.
*
* r0 = task_struct of the previously running process
* r1 = task_info of the previously running process
* r2 = task_info of the next process to run
*/
void
DumpStatsPCEvent::process(ThreadContext *tc)
{
Linux::ThreadInfo ti(tc);
Addr task_descriptor = tc->readIntReg(2);
uint32_t pid = ti.curTaskPID(task_descriptor);
uint32_t tgid = ti.curTaskTGID(task_descriptor);
std::string next_task_str = ti.curTaskName(task_descriptor);
// Streamline treats pid == -1 as the kernel process.
// Also pid == 0 implies idle process (except during Linux boot)
int32_t mm = ti.curTaskMm(task_descriptor);
bool is_kernel = (mm == 0);
if (is_kernel && (pid != 0)) {
pid = -1;
tgid = -1;
next_task_str = "kernel";
}
LinuxArmSystem* sys = dynamic_cast<LinuxArmSystem *>(tc->getSystemPtr());
if (!sys) {
panic("System is not LinuxArmSystem while getting Linux process info!");
}
std::map<uint32_t, uint32_t>& taskMap = sys->taskMap;
// Create a new unique identifier for this pid
sys->mapPid(tc, pid);
// Set cpu task id, output process info, and dump stats
tc->getCpuPtr()->taskId(taskMap[pid]);
tc->getCpuPtr()->setPid(pid);
OutputStream* taskFile = sys->taskFile;
// Task file is read by cache occupancy plotting script or
// Streamline conversion script.
ccprintf(*(taskFile->stream()),
"tick=%lld %d cpu_id=%d next_pid=%d next_tgid=%d next_task=%s\n",
curTick(), taskMap[pid], tc->cpuId(), (int) pid, (int) tgid,
next_task_str);
taskFile->stream()->flush();
// Dump and reset statistics
Stats::schedStatEvent(true, true, curTick(), 0);
}
<commit_msg>arm: Remove BreakPCEvent on guest kernel panic<commit_after>/*
* Copyright (c) 2010-2013 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2002-2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Ali Saidi
*/
#include "arch/arm/linux/atag.hh"
#include "arch/arm/linux/system.hh"
#include "arch/arm/isa_traits.hh"
#include "arch/arm/utility.hh"
#include "arch/generic/linux/threadinfo.hh"
#include "base/loader/dtb_object.hh"
#include "base/loader/object_file.hh"
#include "base/loader/symtab.hh"
#include "cpu/base.hh"
#include "cpu/pc_event.hh"
#include "cpu/thread_context.hh"
#include "debug/Loader.hh"
#include "kern/linux/events.hh"
#include "mem/fs_translating_port_proxy.hh"
#include "mem/physical.hh"
#include "sim/stat_control.hh"
using namespace ArmISA;
using namespace Linux;
LinuxArmSystem::LinuxArmSystem(Params *p)
: GenericArmSystem(p), dumpStatsPCEvent(nullptr),
enableContextSwitchStatsDump(p->enable_context_switch_stats_dump),
taskFile(nullptr), kernelPanicEvent(nullptr), kernelOopsEvent(nullptr)
{
if (p->panic_on_panic) {
kernelPanicEvent = addKernelFuncEventOrPanic<PanicPCEvent>(
"panic", "Kernel panic in simulated kernel");
}
if (p->panic_on_oops) {
kernelOopsEvent = addKernelFuncEventOrPanic<PanicPCEvent>(
"oops_exit", "Kernel oops in guest");
}
// With ARM udelay() is #defined to __udelay
// newer kernels use __loop_udelay and __loop_const_udelay symbols
uDelaySkipEvent = addKernelFuncEvent<UDelayEvent>(
"__loop_udelay", "__udelay", 1000, 0);
if (!uDelaySkipEvent)
uDelaySkipEvent = addKernelFuncEventOrPanic<UDelayEvent>(
"__udelay", "__udelay", 1000, 0);
// constant arguments to udelay() have some precomputation done ahead of
// time. Constant comes from code.
constUDelaySkipEvent = addKernelFuncEvent<UDelayEvent>(
"__loop_const_udelay", "__const_udelay", 1000, 107374);
if (!constUDelaySkipEvent)
constUDelaySkipEvent = addKernelFuncEventOrPanic<UDelayEvent>(
"__const_udelay", "__const_udelay", 1000, 107374);
}
void
LinuxArmSystem::initState()
{
// Moved from the constructor to here since it relies on the
// address map being resolved in the interconnect
// Call the initialisation of the super class
GenericArmSystem::initState();
// Load symbols at physical address, we might not want
// to do this permanently, for but early bootup work
// it is helpful.
if (params()->early_kernel_symbols) {
kernel->loadGlobalSymbols(kernelSymtab, 0, 0, loadAddrMask);
kernel->loadGlobalSymbols(debugSymbolTable, 0, 0, loadAddrMask);
}
// Setup boot data structure
Addr addr = 0;
// Check if the kernel image has a symbol that tells us it supports
// device trees.
bool kernel_has_fdt_support =
kernelSymtab->findAddress("unflatten_device_tree", addr);
bool dtb_file_specified = params()->dtb_filename != "";
if (kernel_has_fdt_support && dtb_file_specified) {
// Kernel supports flattened device tree and dtb file specified.
// Using Device Tree Blob to describe system configuration.
inform("Loading DTB file: %s at address %#x\n", params()->dtb_filename,
params()->atags_addr + loadAddrOffset);
ObjectFile *dtb_file = createObjectFile(params()->dtb_filename, true);
if (!dtb_file) {
fatal("couldn't load DTB file: %s\n", params()->dtb_filename);
}
DtbObject *_dtb_file = dynamic_cast<DtbObject*>(dtb_file);
if (_dtb_file) {
if (!_dtb_file->addBootCmdLine(params()->boot_osflags.c_str(),
params()->boot_osflags.size())) {
warn("couldn't append bootargs to DTB file: %s\n",
params()->dtb_filename);
}
} else {
warn("dtb_file cast failed; couldn't append bootargs "
"to DTB file: %s\n", params()->dtb_filename);
}
dtb_file->setTextBase(params()->atags_addr + loadAddrOffset);
dtb_file->loadSections(physProxy);
delete dtb_file;
} else {
// Using ATAGS
// Warn if the kernel supports FDT and we haven't specified one
if (kernel_has_fdt_support) {
assert(!dtb_file_specified);
warn("Kernel supports device tree, but no DTB file specified\n");
}
// Warn if the kernel doesn't support FDT and we have specified one
if (dtb_file_specified) {
assert(!kernel_has_fdt_support);
warn("DTB file specified, but no device tree support in kernel\n");
}
AtagCore ac;
ac.flags(1); // read-only
ac.pagesize(8192);
ac.rootdev(0);
AddrRangeList atagRanges = physmem.getConfAddrRanges();
if (atagRanges.size() != 1) {
fatal("Expected a single ATAG memory entry but got %d\n",
atagRanges.size());
}
AtagMem am;
am.memSize(atagRanges.begin()->size());
am.memStart(atagRanges.begin()->start());
AtagCmdline ad;
ad.cmdline(params()->boot_osflags);
DPRINTF(Loader, "boot command line %d bytes: %s\n",
ad.size() <<2, params()->boot_osflags.c_str());
AtagNone an;
uint32_t size = ac.size() + am.size() + ad.size() + an.size();
uint32_t offset = 0;
uint8_t *boot_data = new uint8_t[size << 2];
offset += ac.copyOut(boot_data + offset);
offset += am.copyOut(boot_data + offset);
offset += ad.copyOut(boot_data + offset);
offset += an.copyOut(boot_data + offset);
DPRINTF(Loader, "Boot atags was %d bytes in total\n", size << 2);
DDUMP(Loader, boot_data, size << 2);
physProxy.writeBlob(params()->atags_addr + loadAddrOffset, boot_data,
size << 2);
delete[] boot_data;
}
// Kernel boot requirements to set up r0, r1 and r2 in ARMv7
for (int i = 0; i < threadContexts.size(); i++) {
threadContexts[i]->setIntReg(0, 0);
threadContexts[i]->setIntReg(1, params()->machine_type);
threadContexts[i]->setIntReg(2, params()->atags_addr + loadAddrOffset);
}
}
LinuxArmSystem::~LinuxArmSystem()
{
if (uDelaySkipEvent)
delete uDelaySkipEvent;
if (constUDelaySkipEvent)
delete constUDelaySkipEvent;
if (dumpStatsPCEvent)
delete dumpStatsPCEvent;
}
LinuxArmSystem *
LinuxArmSystemParams::create()
{
return new LinuxArmSystem(this);
}
void
LinuxArmSystem::startup()
{
if (enableContextSwitchStatsDump) {
dumpStatsPCEvent = addKernelFuncEvent<DumpStatsPCEvent>("__switch_to");
if (!dumpStatsPCEvent)
panic("dumpStatsPCEvent not created!");
std::string task_filename = "tasks.txt";
taskFile = simout.create(name() + "." + task_filename);
for (int i = 0; i < _numContexts; i++) {
ThreadContext *tc = threadContexts[i];
uint32_t pid = tc->getCpuPtr()->getPid();
if (pid != BaseCPU::invldPid) {
mapPid(tc, pid);
tc->getCpuPtr()->taskId(taskMap[pid]);
}
}
}
}
void
LinuxArmSystem::mapPid(ThreadContext *tc, uint32_t pid)
{
// Create a new unique identifier for this pid
std::map<uint32_t, uint32_t>::iterator itr = taskMap.find(pid);
if (itr == taskMap.end()) {
uint32_t map_size = taskMap.size();
if (map_size > ContextSwitchTaskId::MaxNormalTaskId + 1) {
warn_once("Error out of identifiers for cache occupancy stats");
taskMap[pid] = ContextSwitchTaskId::Unknown;
} else {
taskMap[pid] = map_size;
}
}
}
/** This function is called whenever the the kernel function
* "__switch_to" is called to change running tasks.
*
* r0 = task_struct of the previously running process
* r1 = task_info of the previously running process
* r2 = task_info of the next process to run
*/
void
DumpStatsPCEvent::process(ThreadContext *tc)
{
Linux::ThreadInfo ti(tc);
Addr task_descriptor = tc->readIntReg(2);
uint32_t pid = ti.curTaskPID(task_descriptor);
uint32_t tgid = ti.curTaskTGID(task_descriptor);
std::string next_task_str = ti.curTaskName(task_descriptor);
// Streamline treats pid == -1 as the kernel process.
// Also pid == 0 implies idle process (except during Linux boot)
int32_t mm = ti.curTaskMm(task_descriptor);
bool is_kernel = (mm == 0);
if (is_kernel && (pid != 0)) {
pid = -1;
tgid = -1;
next_task_str = "kernel";
}
LinuxArmSystem* sys = dynamic_cast<LinuxArmSystem *>(tc->getSystemPtr());
if (!sys) {
panic("System is not LinuxArmSystem while getting Linux process info!");
}
std::map<uint32_t, uint32_t>& taskMap = sys->taskMap;
// Create a new unique identifier for this pid
sys->mapPid(tc, pid);
// Set cpu task id, output process info, and dump stats
tc->getCpuPtr()->taskId(taskMap[pid]);
tc->getCpuPtr()->setPid(pid);
OutputStream* taskFile = sys->taskFile;
// Task file is read by cache occupancy plotting script or
// Streamline conversion script.
ccprintf(*(taskFile->stream()),
"tick=%lld %d cpu_id=%d next_pid=%d next_tgid=%d next_task=%s\n",
curTick(), taskMap[pid], tc->cpuId(), (int) pid, (int) tgid,
next_task_str);
taskFile->stream()->flush();
// Dump and reset statistics
Stats::schedStatEvent(true, true, curTick(), 0);
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
* Ali Saidi
*/
#ifndef __ARCH_SPARC_INTREGFILE_HH__
#define __ARCH_SPARC_INTREGFILE_HH__
#include "arch/sparc/isa_traits.hh"
#include "arch/sparc/types.hh"
#include "base/bitfield.hh"
#include <string>
class Checkpoint;
namespace SparcISA
{
class RegFile;
//This function translates integer register file indices into names
std::string getIntRegName(RegIndex);
const int NumIntArchRegs = 32;
const int NumIntRegs = (MaxGL + 1) * 8 + NWindows * 16 + NumMicroIntRegs;
class IntRegFile
{
private:
friend class RegFile;
protected:
//The number of bits needed to index into each 8 register frame
static const int FrameOffsetBits = 3;
//The number of bits to choose between the 4 sets of 8 registers
static const int FrameNumBits = 2;
//The number of registers per "frame" (8)
static const int RegsPerFrame = 1 << FrameOffsetBits;
//A mask to get the frame number
static const uint64_t FrameNumMask =
(FrameNumBits == sizeof(int)) ?
(unsigned int)(-1) :
(1 << FrameNumBits) - 1;
static const uint64_t FrameOffsetMask =
(FrameOffsetBits == sizeof(int)) ?
(unsigned int)(-1) :
(1 << FrameOffsetBits) - 1;
IntReg regGlobals[MaxGL+1][RegsPerFrame];
IntReg regSegments[2 * NWindows][RegsPerFrame];
IntReg microRegs[NumMicroIntRegs];
IntReg regs[NumIntRegs];
enum regFrame {Globals, Outputs, Locals, Inputs, NumFrames};
IntReg * regView[NumFrames];
static const int RegGlobalOffset = 0;
static const int FrameOffset = MaxGL * RegsPerFrame;
int offset[NumFrames];
public:
int flattenIndex(int reg);
void clear();
IntRegFile();
IntReg readReg(int intReg);
void setReg(int intReg, const IntReg &val);
void serialize(std::ostream &os);
void unserialize(Checkpoint *cp, const std::string §ion);
protected:
//This doesn't effect the actual CWP register.
//It's purpose is to adjust the view of the register file
//to what it would be if CWP = cwp.
void setCWP(int cwp);
void setGlobals(int gl);
};
}
#endif
<commit_msg>Fixed an off-by-one error.<commit_after>/*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
* Ali Saidi
*/
#ifndef __ARCH_SPARC_INTREGFILE_HH__
#define __ARCH_SPARC_INTREGFILE_HH__
#include "arch/sparc/isa_traits.hh"
#include "arch/sparc/types.hh"
#include "base/bitfield.hh"
#include <string>
class Checkpoint;
namespace SparcISA
{
class RegFile;
//This function translates integer register file indices into names
std::string getIntRegName(RegIndex);
const int NumIntArchRegs = 32;
const int NumIntRegs = (MaxGL + 1) * 8 + NWindows * 16 + NumMicroIntRegs;
class IntRegFile
{
private:
friend class RegFile;
protected:
//The number of bits needed to index into each 8 register frame
static const int FrameOffsetBits = 3;
//The number of bits to choose between the 4 sets of 8 registers
static const int FrameNumBits = 2;
//The number of registers per "frame" (8)
static const int RegsPerFrame = 1 << FrameOffsetBits;
//A mask to get the frame number
static const uint64_t FrameNumMask =
(FrameNumBits == sizeof(int)) ?
(unsigned int)(-1) :
(1 << FrameNumBits) - 1;
static const uint64_t FrameOffsetMask =
(FrameOffsetBits == sizeof(int)) ?
(unsigned int)(-1) :
(1 << FrameOffsetBits) - 1;
IntReg regGlobals[MaxGL+1][RegsPerFrame];
IntReg regSegments[2 * NWindows][RegsPerFrame];
IntReg microRegs[NumMicroIntRegs];
IntReg regs[NumIntRegs];
enum regFrame {Globals, Outputs, Locals, Inputs, NumFrames};
IntReg * regView[NumFrames];
static const int RegGlobalOffset = 0;
static const int FrameOffset = (MaxGL + 1) * RegsPerFrame;
int offset[NumFrames];
public:
int flattenIndex(int reg);
void clear();
IntRegFile();
IntReg readReg(int intReg);
void setReg(int intReg, const IntReg &val);
void serialize(std::ostream &os);
void unserialize(Checkpoint *cp, const std::string §ion);
protected:
//This doesn't effect the actual CWP register.
//It's purpose is to adjust the view of the register file
//to what it would be if CWP = cwp.
void setCWP(int cwp);
void setGlobals(int gl);
};
}
#endif
<|endoftext|>
|
<commit_before>/**
* @file keyboard.cpp
* @date 28.06.2013
* @author Denise Ratasich
*
* @brief ROS node reading from stdin to steer the robot via keyboard.
*
* A new speed is only published when a key is pressed. Note reading
* vom stdin (console) is blocking.
*
* - subscribe: none
* - publish: ~cmd_vel [geometry_msgs/Twist]
*
* parameters
* - ~pub_period_ms: The publishing period of cmd_vel in ms. Default
* is set to 500ms.
*/
// c includes (for terminal, threading)
#include <stdio.h>
#include <termios.h> //termios, TCSANOW, ECHO, ICANON
#include <unistd.h> //STDIN_FILENO
#include <boost/thread.hpp>
// ROS includes
#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
// Pioneer includes
#include "pioneer3.hpp"
using namespace std;
#define MSG_BUFFER_SIZE 1
// Parameters.
int pub_period_ms = 500;
/**
* @brief Guards a twist object and an additional running flag for the
* keyboard thread, i.e., ensures mutual exclusion of the variables to
* exchange.
*/
class MutexedData {
boost::mutex mtx_;
geometry_msgs::Twist twist_;
int running_;
public:
MutexedData() {
twist_.linear.x = 0;
twist_.angular.z = 0;
running_ = 0;
}
void setTwist(geometry_msgs::Twist& twist) {
mtx_.lock();
twist_.linear.x = twist.linear.x;
twist_.angular.z = twist.angular.z;
mtx_.unlock();
}
void setTwist(float lin, float ang) {
mtx_.lock();
twist_.linear.x = lin;
twist_.angular.z = ang;
mtx_.unlock();
}
geometry_msgs::Twist getTwist() {
geometry_msgs::Twist twist;
mtx_.lock();
twist.linear.x = twist_.linear.x;
twist.angular.z = twist_.angular.z;
mtx_.unlock();
return twist;
}
void setRunning(int running) {
mtx_.lock();
running_ = running;
mtx_.unlock();
}
int getRunning() {
int r;
mtx_.lock();
r = running_;
mtx_.unlock();
return r;
}
};
// Instantiate the guarded twist object.
MutexedData mtxData;
// Forward declarations.
void applyParameters(ros::NodeHandle& n);
void getTwistFromKeyboard();
/**
* This node publishes to cmd_vel to steer the robot according to a
* key pressed in the terminal window this application is running.
*/
int main(int argc, char **argv)
{
static struct termios oldt, newt;
// Disable buffering (till ENTER is pressed) and echo of terminal.
tcgetattr( STDIN_FILENO, &oldt); // get the parameters of the current terminal
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr( STDIN_FILENO, TCSANOW, &newt); // change attributes immediately
// Initialize for ROS.
ros::init(argc, argv, "pioneer_teleop");
if (ros::this_node::getNamespace() == "/")
ROS_WARN("Started in the global namespace.");
// Create main access point to communicate with the ROS system.
ros::NodeHandle n("~");
// Apply parameters from parameter server.
applyParameters(n);
// Note, how to terminate this node!
ROS_WARN("This node can only be terminated by pressing 'q'.");
// Tell ROS that we want to publish on the topic cmd_vel (for steering the robot).
ros::Publisher pub_cmdVel = n.advertise < geometry_msgs::Twist > ("cmd_vel", MSG_BUFFER_SIZE);
// Wait a little bit to be sure that the connection is established.
ros::Duration duration(0.5);
duration.sleep();
duration.sec = 0;
duration.nsec = pub_period_ms * 1e6;
// Start thread to read from keyboard, updates mtxTwist if a key is
// pressed.
boost::thread keyboardThread(getTwistFromKeyboard);
mtxData.setRunning(1); // set running flag of the thread
geometry_msgs::Twist twist; // only local variable
while (ros::ok() && mtxData.getRunning())
{
// Send message.
twist = mtxData.getTwist();
pub_cmdVel.publish(twist);
ROS_DEBUG("%.2f m/s, %.2f degree", twist.linear.x, twist.angular.z);
// Handle callbacks if any.
ros::spinOnce();
// Timeout.
duration.sleep();
}
if (mtxData.getRunning())
ROS_ERROR("Ctrl-C received. Press 'q' to quit the node!");
keyboardThread.join();
// Send "stop" for robot.
twist.linear.x = 0;
twist.angular.z = 0;
pub_cmdVel.publish(twist);
ROS_INFO("Robot stopped.");
// Close connections.
pub_cmdVel.shutdown();
ROS_INFO("Closed connection.");
// Restore old terminal settings.
tcsetattr( STDIN_FILENO, TCSANOW, &oldt);
return 0;
}
void applyParameters(ros::NodeHandle& n)
{
// ROS params ---
if (n.hasParam("pub_period_ms")) {
n.getParam("pub_period_ms", pub_period_ms);
ROS_INFO("Publishing period set to %d ms.", pub_period_ms);
} else {
ROS_INFO("Publishing period set to default %d ms.", pub_period_ms);
}
}
/**
* @brief Waits on a key pressed and sets the twist according to this
* key.
*/
void getTwistFromKeyboard()
{
float speed_lin = 0;
float speed_ang = 0;
char keyPressed;
bool run = 1;
while(run)
{
//cin >> keyPressed; // cin cannot read space
keyPressed = getchar(); // blocking!!!
switch (keyPressed)
{
case ' ': // space
// stop
speed_lin = 0;
speed_ang = 0;
ROS_INFO("stop");
break;
case 'a':
// left
if (speed_ang < SPEED_MAX)
speed_ang += SPEED_STEP;
break;
case 'd':
// right
if (speed_ang > -SPEED_MAX)
speed_ang -= SPEED_STEP;
break;
case 's':
// backward
if (speed_lin > -SPEED_MAX)
speed_lin -= SPEED_STEP;
if (speed_ang != 0) {
speed_ang = 0;
ROS_INFO("straight backward");
}
break;
case 'w':
// forward
if (speed_lin < SPEED_MAX)
speed_lin += SPEED_STEP;
if (speed_ang != 0) {
speed_ang = 0;
ROS_INFO("straight forward");
}
break;
case 'q':
// quit
ROS_INFO("quit");
mtxData.setRunning(0);
run = 0; // leave loop and terminate this thread
}
mtxData.setTwist(speed_lin * SCALE_TRANSLATION, speed_ang * SCALE_ROTATION);
}
}
<commit_msg>[pioneer_teleop] publish when key pressed (additionally to periodic publishing)<commit_after>/**
* @file keyboard.cpp
* @date 28.06.2013
* @author Denise Ratasich
*
* @brief ROS node reading from stdin to steer the robot via keyboard.
*
* A new speed is only published when a key is pressed. Note reading
* vom stdin (console) is blocking.
*
* - subscribe: none
* - publish: ~cmd_vel [geometry_msgs/Twist]
*
* parameters
* - ~pub_period_ms: The publishing period of cmd_vel in ms. Default
* is set to 500ms.
*/
// c includes (for terminal, threading)
#include <stdio.h>
#include <termios.h> //termios, TCSANOW, ECHO, ICANON
#include <unistd.h> //STDIN_FILENO
#include <boost/thread.hpp>
// ROS includes
#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
// Pioneer includes
#include "pioneer3.hpp"
using namespace std;
#define MSG_BUFFER_SIZE 1
// Parameters.
int pub_period_ms = 500;
/**
* @brief Guards a twist object and an additional running flag for the
* keyboard thread, i.e., ensures mutual exclusion of the variables to
* exchange.
*/
class MutexedData {
boost::mutex mtx_; // for mutual exclusion
geometry_msgs::Twist twist_; // the data to send
ros::Publisher pub_cmdVel_; // the publisher (thread is also able to publish)
int running_;
public:
void init(ros::NodeHandle& n) {
twist_.linear.x = 0;
twist_.angular.z = 0;
pub_cmdVel_ = n.advertise < geometry_msgs::Twist > ("cmd_vel", MSG_BUFFER_SIZE);
running_ = 0;
}
void shutdown() {
pub_cmdVel_.shutdown();
}
void setTwist(geometry_msgs::Twist& twist) {
mtx_.lock();
twist_.linear.x = twist.linear.x;
twist_.angular.z = twist.angular.z;
mtx_.unlock();
}
void setTwist(float lin, float ang) {
mtx_.lock();
twist_.linear.x = lin;
twist_.angular.z = ang;
mtx_.unlock();
}
geometry_msgs::Twist getTwist() {
geometry_msgs::Twist twist;
mtx_.lock();
twist.linear.x = twist_.linear.x;
twist.angular.z = twist_.angular.z;
mtx_.unlock();
return twist;
}
void publish() {
mtx_.lock();
pub_cmdVel_.publish(twist_);
ROS_DEBUG("%.2f m/s, %.2f degree", twist_.linear.x, twist_.angular.z);
mtx_.unlock();
}
void publish(float lin, float ang) {
mtx_.lock();
twist_.linear.x = lin;
twist_.angular.z = ang;
pub_cmdVel_.publish(twist_);
ROS_DEBUG("%.2f m/s, %.2f degree", twist_.linear.x, twist_.angular.z);
mtx_.unlock();
}
void setRunning(int running) {
mtx_.lock();
running_ = running;
mtx_.unlock();
}
int isRunning() {
int r;
mtx_.lock();
r = running_;
mtx_.unlock();
return r;
}
};
// Instantiate the guarded twist object.
MutexedData mtxData;
// Forward declarations.
void applyParameters(ros::NodeHandle& n);
void getTwistFromKeyboard();
/**
* This node publishes to cmd_vel to steer the robot according to a
* key pressed in the terminal window this application is running.
*/
int main(int argc, char **argv)
{
static struct termios oldt, newt;
// Disable buffering (till ENTER is pressed) and echo of terminal.
tcgetattr( STDIN_FILENO, &oldt); // get the parameters of the current terminal
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr( STDIN_FILENO, TCSANOW, &newt); // change attributes immediately
// Initialize for ROS.
ros::init(argc, argv, "pioneer_teleop");
if (ros::this_node::getNamespace() == "/")
ROS_WARN("Started in the global namespace.");
// Create main access point to communicate with the ROS system.
ros::NodeHandle n("~");
// Apply parameters from parameter server.
applyParameters(n);
// Note, how to terminate this node!
ROS_WARN("This node can only be terminated by pressing 'q'.");
// Initialize data and tell ROS that we want to publish on the topic
// cmd_vel (for steering the robot).
mtxData.init(n);
// Wait a little bit to be sure that the connection is established.
ros::Duration duration(0.5);
duration.sleep();
duration.sec = 0;
duration.nsec = pub_period_ms * 1e6;
// Start thread to read from keyboard, updates mtxData if a key is
// pressed.
boost::thread keyboardThread(getTwistFromKeyboard);
mtxData.setRunning(1); // set running flag of the thread
while (ros::ok() && mtxData.isRunning())
{
// Send message periodically.
mtxData.publish();
// Handle callbacks if any.
ros::spinOnce();
// Timeout.
duration.sleep();
}
if (mtxData.isRunning())
ROS_ERROR("Ctrl-C received. Press 'q' to quit the node!");
keyboardThread.join();
// Send "stop" for robot.
mtxData.publish(0,0);
ROS_INFO("Robot stopped.");
// Close connections.
mtxData.shutdown();
ROS_INFO("Closed connection.");
// Restore old terminal settings.
tcsetattr( STDIN_FILENO, TCSANOW, &oldt);
return 0;
}
/**
* @brief Fetches available params from the parameter server and
* configures this node.
*/
void applyParameters(ros::NodeHandle& n)
{
// ROS params ---
if (n.hasParam("pub_period_ms")) {
n.getParam("pub_period_ms", pub_period_ms);
ROS_INFO("Publishing period set to %d ms.", pub_period_ms);
} else {
ROS_INFO("Publishing period set to default %d ms.", pub_period_ms);
}
}
/**
* @brief Waits on a key pressed and sets the twist according to this
* key.
*/
void getTwistFromKeyboard()
{
float speed_lin = 0;
float speed_ang = 0;
char keyPressed;
bool run = 1;
while(run)
{
//cin >> keyPressed; // cin cannot read space
keyPressed = getchar(); // blocking!!!
switch (keyPressed)
{
case ' ': // space
// stop
speed_lin = 0;
speed_ang = 0;
ROS_INFO("stop");
break;
case 'a':
// left
if (speed_ang < SPEED_MAX)
speed_ang += SPEED_STEP;
break;
case 'd':
// right
if (speed_ang > -SPEED_MAX)
speed_ang -= SPEED_STEP;
break;
case 's':
// backward
if (speed_lin > -SPEED_MAX)
speed_lin -= SPEED_STEP;
if (speed_ang != 0) {
speed_ang = 0;
ROS_INFO("straight backward");
}
break;
case 'w':
// forward
if (speed_lin < SPEED_MAX)
speed_lin += SPEED_STEP;
if (speed_ang != 0) {
speed_ang = 0;
ROS_INFO("straight forward");
}
break;
case 'q':
// quit
ROS_INFO("quit");
mtxData.setRunning(0);
run = 0; // leave loop and terminate this thread
}
mtxData.publish(speed_lin * SCALE_TRANSLATION, speed_ang * SCALE_ROTATION);
}
}
<|endoftext|>
|
<commit_before>#include "GameController.h"
#include "Tools/Debug/DebugRequest.h"
#include <PlatformInterface/Platform.h>
GameController::GameController()
:
lastWhistleCount(0),
returnMessage(GameReturnData::alive)
{
DEBUG_REQUEST_REGISTER("gamecontroller:play", "force the play state", false);
DEBUG_REQUEST_REGISTER("gamecontroller:penalized", "force the penalized state", false);
DEBUG_REQUEST_REGISTER("gamecontroller:initial", "force the initial state", false);
DEBUG_REQUEST_REGISTER("gamecontroller:ready", "force the ready state", false);
DEBUG_REQUEST_REGISTER("gamecontroller:set", "force the set state", false);
// TODO: make it parameters?
// load values from config
const Configuration& config = naoth::Platform::getInstance().theConfiguration;
if (config.hasKey("player", "NumOfPlayer")) {
getPlayerInfo().playersPerTeam = config.getInt("player", "NumOfPlayer");
} else {
std::cerr << "[GameData] " << "No number of players (NumOfPlayers) given" << std::endl;
}
if (config.hasKey("player", "PlayerNumber")) {
getPlayerInfo().playerNumber = config.getInt("player", "PlayerNumber");
} else {
std::cerr << "[PlayerInfo] " << "No player number (PlayerNumber) given" << std::endl;
getPlayerInfo().playerNumber = 3;
}
if (config.hasKey("player", "TeamNumber")) {
getPlayerInfo().teamNumber = config.getInt("player", "TeamNumber");
} else {
std::cerr << "[PlayerInfo] " << "No team number (TeamNumber) given" << std::endl;
getPlayerInfo().teamNumber = 0;
}
if (config.hasKey("player", "TeamName")) {
getPlayerInfo().teamName = config.getString("player", "TeamName");
} else {
std::cerr << "[PlayerInfo] " << "No team name (TeamName) given" << std::endl;
getPlayerInfo().teamName = "unknown";
}
// NOTE: default team color is red
getPlayerInfo().teamColor = GameData::red;
if (config.hasKey("player", "TeamColor"))
{
getPlayerInfo().teamColor = GameData::teamColorFromString(config.getString("player", "TeamColor"));
if (getPlayerInfo().teamColor == GameData::unknown_team_color)
{
std::cerr << "[GameData] " << "Invalid team color (TeamColor) \""
<< config.getString("player", "TeamColor") << "\" given" << std::endl;
}
} else {
std::cerr << "[GameData] " << "No team color (TeamColor) given" << std::endl;
}
}
void GameController::execute()
{
PlayerInfo::RobotState oldRobotState = getPlayerInfo().robotState;
GameData::TeamColor oldTeamColor = getPlayerInfo().teamColor;
// try update from the game controller message
if ( getGameData().valid )
{
// HACK: needed by SimSpark - overide the player number
if(getGameData().newPlayerNumber > 0) {
getPlayerInfo().playerNumber = getGameData().newPlayerNumber;
}
getPlayerInfo().update(getGameData());
// reset return message if old message was accepted
if( returnMessage == GameReturnData::manual_penalise
&& getGameData().getOwnRobotInfo(getPlayerInfo().playerNumber).penalty != GameData::none)
{
returnMessage = GameReturnData::alive;
}
else if(returnMessage == GameReturnData::manual_unpenalise
&& getGameData().getOwnRobotInfo(getPlayerInfo().playerNumber).penalty == GameData::none)
{
returnMessage = GameReturnData::alive;
}
}
// keep the manual penalized state
if(returnMessage == GameReturnData::manual_penalise) {
getPlayerInfo().robotState = PlayerInfo::penalized;
}
handleButtons();
handleHeadButtons();
handleDebugRequest();
// remember the whistle counter before set
if(getPlayerInfo().robotState == PlayerInfo::ready) {
lastWhistleCount = getWhistlePercept().counter;
}
// whistle overrides gamecontroller when in set
else if(getGameData().gameState == GameData::set)
{
// switch from set to play
if(getWhistlePercept().counter > lastWhistleCount) {
getPlayerInfo().robotState = PlayerInfo::playing;
}
}
if( oldRobotState != getPlayerInfo().robotState
|| oldTeamColor != getPlayerInfo().teamColor
|| getPlayerInfo().robotState == PlayerInfo::initial)
{
updateLEDs();
}
// provide the return message
getGameReturnData().team = getPlayerInfo().teamNumber;
getGameReturnData().player = getPlayerInfo().playerNumber;
getGameReturnData().message = returnMessage;
} // end execute
void GameController::handleDebugRequest()
{
PlayerInfo::RobotState debugState = getPlayerInfo().robotState;
DEBUG_REQUEST("gamecontroller:initial",
debugState = PlayerInfo::initial;
);
DEBUG_REQUEST("gamecontroller:ready",
debugState = PlayerInfo::ready;
);
DEBUG_REQUEST("gamecontroller:set",
debugState = PlayerInfo::set;
);
DEBUG_REQUEST("gamecontroller:play",
debugState = PlayerInfo::playing;
);
DEBUG_REQUEST("gamecontroller:penalized",
debugState = PlayerInfo::penalized;
);
// NOTE: same behavior as the button interface
if(debugState != getPlayerInfo().robotState) {
getPlayerInfo().robotState = debugState;
// NOTE: logic is reverted in relation to button interface
switch (getPlayerInfo().robotState)
{
case PlayerInfo::initial:
case PlayerInfo::ready:
case PlayerInfo::set:
case PlayerInfo::playing:
case PlayerInfo::finished:
{
returnMessage = GameReturnData::manual_unpenalise;
break;
}
case PlayerInfo::penalized:
{
returnMessage = GameReturnData::manual_penalise;
break;
}
default:
ASSERT(false);
}
}
} // end handleDebugRequest
void GameController::handleButtons()
{
if (getButtonState()[ButtonState::Chest] == ButtonEvent::CLICKED)
{
switch (getPlayerInfo().robotState)
{
case PlayerInfo::initial:
case PlayerInfo::ready:
case PlayerInfo::set:
case PlayerInfo::playing:
case PlayerInfo::finished:
{
getPlayerInfo().robotState = PlayerInfo::penalized;
returnMessage = GameReturnData::manual_penalise;
break;
}
case PlayerInfo::penalized:
{
getPlayerInfo().robotState = PlayerInfo::playing;
returnMessage = GameReturnData::manual_unpenalise;
break;
}
default:
ASSERT(false);
}
}
// re-set team color or kickoff in initial
if (getPlayerInfo().robotState == PlayerInfo::initial)
{
if ( getButtonState()[ButtonState::LeftFoot] == ButtonEvent::PRESSED )
{
// switch team color
GameData::TeamColor oldColor = getPlayerInfo().teamColor;
if (oldColor == GameData::blue) {
getPlayerInfo().teamColor = GameData::red;
} else if (oldColor == GameData::red) {
getPlayerInfo().teamColor = GameData::yellow;
} else if (oldColor == GameData::yellow) {
getPlayerInfo().teamColor = GameData::black;
} else if (oldColor == GameData::black) {
getPlayerInfo().teamColor = GameData::blue;
} else { // set to red by default
getPlayerInfo().teamColor = GameData::red;
}
}
if ( getButtonState()[ButtonState::RightFoot] == ButtonEvent::PRESSED )
{
// switch kick off team
getPlayerInfo().kickoff = !getPlayerInfo().kickoff;
}
}
// go back from penalized to initial both foot bumpers are pressed for more than 1s
else if (getPlayerInfo().robotState == PlayerInfo::penalized &&
( getButtonState()[ButtonState::LeftFoot].isPressed &&
getFrameInfo().getTimeSince(getButtonState()[ButtonState::LeftFoot].timeOfLastEvent) > 1000 )
&&
( getButtonState()[ButtonState::RightFoot].isPressed &&
getFrameInfo().getTimeSince(getButtonState()[ButtonState::RightFoot].timeOfLastEvent) > 1000 )
)
{
getPlayerInfo().robotState = PlayerInfo::initial;
returnMessage = GameReturnData::manual_unpenalise;
}
} // end handleButtons
void GameController::handleHeadButtons()
{
getSoundPlayData().mute = true;
getSoundPlayData().soundFile = "";
if( getButtonState().buttons[ButtonState::HeadMiddle] == ButtonEvent::CLICKED
&& getPlayerInfo().robotState == PlayerInfo::initial)
{
int playerNumber = getPlayerInfo().playerNumber;
if(playerNumber <= 9)
{
std::stringstream ssWav;
ssWav << playerNumber;
ssWav << ".wav";
getSoundPlayData().mute = false;
getSoundPlayData().soundFile = ssWav.str();
}
}
}
void GameController::updateLEDs()
{
// reset
getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 0.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 0.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::BLUE] = 0.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 0.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::GREEN] = 0.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 0.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::RED] = 0.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::GREEN] = 0.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::BLUE] = 0.0;
for(unsigned int i=LEDData::HeadFrontLeft0; i <= LEDData::HeadRearRight2; i++)
{
getGameControllerLEDRequest().request.theMonoLED[i] = 0.0;
}
// show game state in torso
switch (getPlayerInfo().robotState)
{
case PlayerInfo::ready:
getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::BLUE] = 1.0;
break;
case PlayerInfo::set:
getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 1.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 1.0;
break;
case PlayerInfo::playing:
getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 1.0;
break;
case PlayerInfo::penalized:
getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 1.0;
break;
default:
break;
}
// show team color on left foot
if (getPlayerInfo().teamColor == GameData::red)
{
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 0.3;
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 0.1;
}
else if (getPlayerInfo().teamColor == GameData::blue)
{
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 1.0;
}
else if(getPlayerInfo().teamColor == GameData::yellow)
{
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 1.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::GREEN] = 1.0;
}
else if(getPlayerInfo().teamColor == GameData::black)
{
// LED off
}
// show kickoff state on right foot and head in initial, ready and set
if (getPlayerInfo().robotState == PlayerInfo::initial
|| getPlayerInfo().robotState == PlayerInfo::ready
|| getPlayerInfo().robotState == PlayerInfo::set)
{
if (getPlayerInfo().kickoff)
{
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::RED] = 0.7;
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::GREEN] = 1.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::BLUE] = 1.0;
for(unsigned int i=LEDData::HeadFrontLeft0; i <= LEDData::HeadRearRight2; i++)
{
getGameControllerLEDRequest().request.theMonoLED[i] = 1.0;
}
}
}
} // end updateLEDs
GameController::~GameController()
{
}
<commit_msg>trigger finished game state by debug request<commit_after>#include "GameController.h"
#include "Tools/Debug/DebugRequest.h"
#include <PlatformInterface/Platform.h>
GameController::GameController()
:
lastWhistleCount(0),
returnMessage(GameReturnData::alive)
{
DEBUG_REQUEST_REGISTER("gamecontroller:play", "force the play state", false);
DEBUG_REQUEST_REGISTER("gamecontroller:penalized", "force the penalized state", false);
DEBUG_REQUEST_REGISTER("gamecontroller:initial", "force the initial state", false);
DEBUG_REQUEST_REGISTER("gamecontroller:ready", "force the ready state", false);
DEBUG_REQUEST_REGISTER("gamecontroller:set", "force the set state", false);
DEBUG_REQUEST_REGISTER("gamecontroller:finished", "force the finished state", false);
// TODO: make it parameters?
// load values from config
const Configuration& config = naoth::Platform::getInstance().theConfiguration;
if (config.hasKey("player", "NumOfPlayer")) {
getPlayerInfo().playersPerTeam = config.getInt("player", "NumOfPlayer");
} else {
std::cerr << "[GameData] " << "No number of players (NumOfPlayers) given" << std::endl;
}
if (config.hasKey("player", "PlayerNumber")) {
getPlayerInfo().playerNumber = config.getInt("player", "PlayerNumber");
} else {
std::cerr << "[PlayerInfo] " << "No player number (PlayerNumber) given" << std::endl;
getPlayerInfo().playerNumber = 3;
}
if (config.hasKey("player", "TeamNumber")) {
getPlayerInfo().teamNumber = config.getInt("player", "TeamNumber");
} else {
std::cerr << "[PlayerInfo] " << "No team number (TeamNumber) given" << std::endl;
getPlayerInfo().teamNumber = 0;
}
if (config.hasKey("player", "TeamName")) {
getPlayerInfo().teamName = config.getString("player", "TeamName");
} else {
std::cerr << "[PlayerInfo] " << "No team name (TeamName) given" << std::endl;
getPlayerInfo().teamName = "unknown";
}
// NOTE: default team color is red
getPlayerInfo().teamColor = GameData::red;
if (config.hasKey("player", "TeamColor"))
{
getPlayerInfo().teamColor = GameData::teamColorFromString(config.getString("player", "TeamColor"));
if (getPlayerInfo().teamColor == GameData::unknown_team_color)
{
std::cerr << "[GameData] " << "Invalid team color (TeamColor) \""
<< config.getString("player", "TeamColor") << "\" given" << std::endl;
}
} else {
std::cerr << "[GameData] " << "No team color (TeamColor) given" << std::endl;
}
}
void GameController::execute()
{
PlayerInfo::RobotState oldRobotState = getPlayerInfo().robotState;
GameData::TeamColor oldTeamColor = getPlayerInfo().teamColor;
// try update from the game controller message
if ( getGameData().valid )
{
// HACK: needed by SimSpark - overide the player number
if(getGameData().newPlayerNumber > 0) {
getPlayerInfo().playerNumber = getGameData().newPlayerNumber;
}
getPlayerInfo().update(getGameData());
// reset return message if old message was accepted
if( returnMessage == GameReturnData::manual_penalise
&& getGameData().getOwnRobotInfo(getPlayerInfo().playerNumber).penalty != GameData::none)
{
returnMessage = GameReturnData::alive;
}
else if(returnMessage == GameReturnData::manual_unpenalise
&& getGameData().getOwnRobotInfo(getPlayerInfo().playerNumber).penalty == GameData::none)
{
returnMessage = GameReturnData::alive;
}
}
// keep the manual penalized state
if(returnMessage == GameReturnData::manual_penalise) {
getPlayerInfo().robotState = PlayerInfo::penalized;
}
handleButtons();
handleHeadButtons();
handleDebugRequest();
// remember the whistle counter before set
if(getPlayerInfo().robotState == PlayerInfo::ready) {
lastWhistleCount = getWhistlePercept().counter;
}
// whistle overrides gamecontroller when in set
else if(getGameData().gameState == GameData::set)
{
// switch from set to play
if(getWhistlePercept().counter > lastWhistleCount) {
getPlayerInfo().robotState = PlayerInfo::playing;
}
}
if( oldRobotState != getPlayerInfo().robotState
|| oldTeamColor != getPlayerInfo().teamColor
|| getPlayerInfo().robotState == PlayerInfo::initial)
{
updateLEDs();
}
// provide the return message
getGameReturnData().team = getPlayerInfo().teamNumber;
getGameReturnData().player = getPlayerInfo().playerNumber;
getGameReturnData().message = returnMessage;
} // end execute
void GameController::handleDebugRequest()
{
PlayerInfo::RobotState debugState = getPlayerInfo().robotState;
DEBUG_REQUEST("gamecontroller:initial",
debugState = PlayerInfo::initial;
);
DEBUG_REQUEST("gamecontroller:ready",
debugState = PlayerInfo::ready;
);
DEBUG_REQUEST("gamecontroller:set",
debugState = PlayerInfo::set;
);
DEBUG_REQUEST("gamecontroller:play",
debugState = PlayerInfo::playing;
);
DEBUG_REQUEST("gamecontroller:penalized",
debugState = PlayerInfo::penalized;
);
DEBUG_REQUEST("gamecontroller:finished",
debugState = PlayerInfo::finished;
);
// NOTE: same behavior as the button interface
if(debugState != getPlayerInfo().robotState) {
getPlayerInfo().robotState = debugState;
// NOTE: logic is reverted in relation to button interface
switch (getPlayerInfo().robotState)
{
case PlayerInfo::initial:
case PlayerInfo::ready:
case PlayerInfo::set:
case PlayerInfo::playing:
case PlayerInfo::finished:
{
returnMessage = GameReturnData::manual_unpenalise;
break;
}
case PlayerInfo::penalized:
{
returnMessage = GameReturnData::manual_penalise;
break;
}
default:
ASSERT(false);
}
}
} // end handleDebugRequest
void GameController::handleButtons()
{
if (getButtonState()[ButtonState::Chest] == ButtonEvent::CLICKED)
{
switch (getPlayerInfo().robotState)
{
case PlayerInfo::initial:
case PlayerInfo::ready:
case PlayerInfo::set:
case PlayerInfo::playing:
case PlayerInfo::finished:
{
getPlayerInfo().robotState = PlayerInfo::penalized;
returnMessage = GameReturnData::manual_penalise;
break;
}
case PlayerInfo::penalized:
{
getPlayerInfo().robotState = PlayerInfo::playing;
returnMessage = GameReturnData::manual_unpenalise;
break;
}
default:
ASSERT(false);
}
}
// re-set team color or kickoff in initial
if (getPlayerInfo().robotState == PlayerInfo::initial)
{
if ( getButtonState()[ButtonState::LeftFoot] == ButtonEvent::PRESSED )
{
// switch team color
GameData::TeamColor oldColor = getPlayerInfo().teamColor;
if (oldColor == GameData::blue) {
getPlayerInfo().teamColor = GameData::red;
} else if (oldColor == GameData::red) {
getPlayerInfo().teamColor = GameData::yellow;
} else if (oldColor == GameData::yellow) {
getPlayerInfo().teamColor = GameData::black;
} else if (oldColor == GameData::black) {
getPlayerInfo().teamColor = GameData::blue;
} else { // set to red by default
getPlayerInfo().teamColor = GameData::red;
}
}
if ( getButtonState()[ButtonState::RightFoot] == ButtonEvent::PRESSED )
{
// switch kick off team
getPlayerInfo().kickoff = !getPlayerInfo().kickoff;
}
}
// go back from penalized to initial both foot bumpers are pressed for more than 1s
else if (getPlayerInfo().robotState == PlayerInfo::penalized &&
( getButtonState()[ButtonState::LeftFoot].isPressed &&
getFrameInfo().getTimeSince(getButtonState()[ButtonState::LeftFoot].timeOfLastEvent) > 1000 )
&&
( getButtonState()[ButtonState::RightFoot].isPressed &&
getFrameInfo().getTimeSince(getButtonState()[ButtonState::RightFoot].timeOfLastEvent) > 1000 )
)
{
getPlayerInfo().robotState = PlayerInfo::initial;
returnMessage = GameReturnData::manual_unpenalise;
}
} // end handleButtons
void GameController::handleHeadButtons()
{
getSoundPlayData().mute = true;
getSoundPlayData().soundFile = "";
if( getButtonState().buttons[ButtonState::HeadMiddle] == ButtonEvent::CLICKED
&& getPlayerInfo().robotState == PlayerInfo::initial)
{
int playerNumber = getPlayerInfo().playerNumber;
if(playerNumber <= 9)
{
std::stringstream ssWav;
ssWav << playerNumber;
ssWav << ".wav";
getSoundPlayData().mute = false;
getSoundPlayData().soundFile = ssWav.str();
}
}
}
void GameController::updateLEDs()
{
// reset
getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 0.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 0.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::BLUE] = 0.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 0.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::GREEN] = 0.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 0.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::RED] = 0.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::GREEN] = 0.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::BLUE] = 0.0;
for(unsigned int i=LEDData::HeadFrontLeft0; i <= LEDData::HeadRearRight2; i++)
{
getGameControllerLEDRequest().request.theMonoLED[i] = 0.0;
}
// show game state in torso
switch (getPlayerInfo().robotState)
{
case PlayerInfo::ready:
getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::BLUE] = 1.0;
break;
case PlayerInfo::set:
getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 1.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 1.0;
break;
case PlayerInfo::playing:
getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::GREEN] = 1.0;
break;
case PlayerInfo::penalized:
getGameControllerLEDRequest().request.theMultiLED[LEDData::ChestButton][LEDData::RED] = 1.0;
break;
default:
break;
}
// show team color on left foot
if (getPlayerInfo().teamColor == GameData::red)
{
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 0.3;
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 0.1;
}
else if (getPlayerInfo().teamColor == GameData::blue)
{
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::BLUE] = 1.0;
}
else if(getPlayerInfo().teamColor == GameData::yellow)
{
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::RED] = 1.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootLeft][LEDData::GREEN] = 1.0;
}
else if(getPlayerInfo().teamColor == GameData::black)
{
// LED off
}
// show kickoff state on right foot and head in initial, ready and set
if (getPlayerInfo().robotState == PlayerInfo::initial
|| getPlayerInfo().robotState == PlayerInfo::ready
|| getPlayerInfo().robotState == PlayerInfo::set)
{
if (getPlayerInfo().kickoff)
{
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::RED] = 0.7;
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::GREEN] = 1.0;
getGameControllerLEDRequest().request.theMultiLED[LEDData::FootRight][LEDData::BLUE] = 1.0;
for(unsigned int i=LEDData::HeadFrontLeft0; i <= LEDData::HeadRearRight2; i++)
{
getGameControllerLEDRequest().request.theMonoLED[i] = 1.0;
}
}
}
} // end updateLEDs
GameController::~GameController()
{
}
<|endoftext|>
|
<commit_before>//
// MathUtils.cpp
// Bomber
//
// Created by Jeremias Nunez on 3/20/14.
//
//
#include "MathUtils.h"
#include <random>
int MathUtils::randIntInRange(int min, int max)
{
return min + (rand() % (int)(max - min + 1));
}<commit_msg>changed random int generation algorithm to use better rand function<commit_after>//
// MathUtils.cpp
// Bomber
//
// Created by Jeremias Nunez on 3/20/14.
//
//
#include "MathUtils.h"
#include <random>
int MathUtils::randIntInRange(int min, int max)
{
return min + (arc4random() % (int)(max - min + 1));
}<|endoftext|>
|
<commit_before>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
/// \file dem_profile2.cc
///
// Standard
#include <iostream>
// Vision Workbench
#include <vw/Image.h>
#include <vw/FileIO.h>
#include <vw/Cartography.h>
using namespace vw;
// Boost
#include <boost/program_options.hpp>
namespace po = boost::program_options;
// Main
int main ( int argc, char *argv[] ) {
std::string input_file;
std::string start_ll, end_ll;
std::string start_px, end_px;
double idx_column, idx_row;
double nodata_value;
po::variables_map vm;
po::options_description general_options("Options");
general_options.add_options()
("col", po::value<double>(&idx_column), "Process only a single column at this index")
("row", po::value<double>(&idx_row), "Process only a single row at this index")
("nodata-value", po::value<double>(&nodata_value), "Set the nodata value that is used in the DEM")
//("ll-start", po::value<std::string>(&start_ll), "Start a profile at this Lon Lat location")
//("ll-end", po::value<std::string>(&end_ll), "End a profile at this Lon Lat location")
("px-start", po::value<std::string>(&start_px)->composing(), "Start a profile at this pixel location")
("px-end", po::value<std::string>(&end_px), "End a profile at this pixel location")
("help,h", "Display this help message");
po::options_description hidden_options("");
hidden_options.add_options()
("input-dem", po::value<std::string>(&input_file));
po::options_description options("Allowed Options");
options.add(general_options).add(hidden_options);
po::positional_options_description pos;
pos.add("input-dem", 1);
po::store( po::command_line_parser( argc, argv ).options(options).positional(pos).run(), vm );
po::notify( vm );
std::ostringstream usage;
usage << "Usage: " << argv[0] << " <dem-file> [options] \n\n";
usage << general_options << "\n";
if ( vm.count("help") || !vm.count("input-dem") ) {
vw_out() << usage.str() << "\n";
return 1;
} else if ( vm.count("ll-start") ^ vm.count("ll-end") ) {
vw_out() << "Must specify both ends if creating a Lat Lon Profile!\n";
vw_out() << usage.str() << "\n";
return 1;
} else if ( vm.count("px-start") ^ vm.count("px-end") ) {
vw_out() << "Must specify both ends if creating a Pixel Profile!\n";
vw_out() << usage.str() << "\n";
return 1;
} else if ( vm.count("ll-start") && ( start_ll.size() != 2 ||
end_ll.size() != 2 ) ) {
vw_out() << "Start and End Lon Lat locations require 2 values, longitude and latitude.\n";
}
// Finally starting to perform some work
cartography::GeoReference georef;
cartography::read_georeference(georef, input_file);
DiskImageView<float> disk_dem_file( input_file );
ImageViewRef<PixelMask<float> > dem;
if ( vm.count("nodata-value") ) {
vw_out() << "\t--> Masking nodata value: " << nodata_value << "\n";
dem = interpolate(create_mask( disk_dem_file, nodata_value ),
BicubicInterpolation(),
ZeroEdgeExtension());
} else {
DiskImageResource *disk_dem_rsrc = DiskImageResource::open(input_file);
if ( disk_dem_rsrc->has_nodata_value() ) {
nodata_value = disk_dem_rsrc->nodata_value();
vw_out() << "\t--> Extracted nodata value from file: " << nodata_value << "\n";
dem = interpolate(create_mask( disk_dem_file, nodata_value ),
BicubicInterpolation(),
ZeroEdgeExtension());
} else {
dem = interpolate(pixel_cast<PixelMask<float> >(disk_dem_file),
BicubicInterpolation(),
ZeroEdgeExtension());
}
}
Vector2 start, end; // Pixel Locations (everything boils down to it
// at the moment :/. Maybe in the future where
// flying cars are possible, when a user
// provides LL coordinates .. SLERP is used.
if ( vm.count("col") ) {
start = Vector2(idx_column, 0);
end = Vector2(idx_column, dem.rows()-1);
} else if ( vm.count("row") ) {
start = Vector2(0,idx_row);
end = Vector2(dem.cols()-1,idx_row);
} else if ( vm.count("ll-start") && vm.count("ll-end") ) {
// Parsing string into a ll coordinate.
if ( start_ll.find(',') == std::string::npos ||
end_ll.find(',') == std::string::npos ) {
vw_out() << "Longitude and Latitude values must be delimited by a comma.\n";
vw_out() << "\tEx: --ll-start -109.54,33.483\n\n";
vw_out() << usage.str() << "\n";
return 1;
}
size_t s_break = start_px.find(',');
size_t e_break = end_px.find(',');
Vector2 ll_start, ll_end;
} else if ( vm.count("px-start") && vm.count("px-end") ) {
// Parsing string into pixel coordinates.
if ( start_px.find(',') == std::string::npos ||
end_px.find(',') == std::string::npos ) {
vw_out() << "Column and Row pixel values must be delimited by a comma.\n";
vw_out() << "\tEx: --px-start 65,109\n\n";
vw_out() << usage.str() << "\n";
return 1;
}
size_t s_break = start_px.find(',');
size_t e_break = end_px.find(',');
start.x() = atof(start_px.substr(0,s_break).c_str());
start.y() = atof(start_px.substr(s_break+1, start_px.size()-s_break-1).c_str());
end.x() = atof(end_px.substr(0,e_break).c_str());
end.y() = atof(end_px.substr(e_break+1, end_px.size()-e_break-1).c_str());
} else {
// Dial down the middle if the user provides only a DEM.
start = Vector2( dem.cols()/2, 0);
end = Vector2( dem.cols()/2, dem.rows()-1);
}
// Debug
vw_out() << "Start: " << start << "\n";
vw_out() << "End: " << end << "\n";
// Working out the output file
BBox2i bound = bounding_box( dem );
if ( !bound.contains( start ) ||
!bound.contains( end ) ) {
vw_out() << "Given coordinates are not with in the image!\nExiting early .....\n";
return 1;
}
std::ofstream output_file( "profile.csv" );
output_file << std::setprecision(12) << "lon,lat,pix_x,pix_y,altitude,radius\n";
Vector2i delta = end - start;
for ( float r = 0; r < 1.0; r +=1/norm_2(delta) ) {
Vector2 c_idx = Vector2(0.5,0.5) + start + r*delta;
if ( !dem(int(c_idx.x()),int(c_idx.y())).valid() )
continue;
Vector2 lonlat_loc = georef.pixel_to_lonlat( c_idx );
double altitude = dem( c_idx.x(), c_idx.y() );
Vector3 xyz_pos = georef.datum().geodetic_to_cartesian( Vector3( lonlat_loc.x(),
lonlat_loc.y(),
altitude ));
double radius = norm_2( xyz_pos );
output_file << lonlat_loc.x() << "," << lonlat_loc.y() << "," << c_idx.x()
<< "," << c_idx.y() << "," << altitude << "," << radius << "\n";
}
output_file.close();
return 0;
}
<commit_msg>Missed one correction for nodata<commit_after>// __BEGIN_LICENSE__
// Copyright (C) 2006-2010 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
/// \file dem_profile2.cc
///
// Standard
#include <iostream>
// Vision Workbench
#include <vw/Image.h>
#include <vw/FileIO.h>
#include <vw/Cartography.h>
using namespace vw;
// Boost
#include <boost/program_options.hpp>
namespace po = boost::program_options;
// Main
int main ( int argc, char *argv[] ) {
std::string input_file;
std::string start_ll, end_ll;
std::string start_px, end_px;
double idx_column, idx_row;
double nodata_value;
po::variables_map vm;
po::options_description general_options("Options");
general_options.add_options()
("col", po::value<double>(&idx_column), "Process only a single column at this index")
("row", po::value<double>(&idx_row), "Process only a single row at this index")
("nodata-value", po::value<double>(&nodata_value), "Set the nodata value that is used in the DEM")
//("ll-start", po::value<std::string>(&start_ll), "Start a profile at this Lon Lat location")
//("ll-end", po::value<std::string>(&end_ll), "End a profile at this Lon Lat location")
("px-start", po::value<std::string>(&start_px)->composing(), "Start a profile at this pixel location")
("px-end", po::value<std::string>(&end_px), "End a profile at this pixel location")
("help,h", "Display this help message");
po::options_description hidden_options("");
hidden_options.add_options()
("input-dem", po::value<std::string>(&input_file));
po::options_description options("Allowed Options");
options.add(general_options).add(hidden_options);
po::positional_options_description pos;
pos.add("input-dem", 1);
po::store( po::command_line_parser( argc, argv ).options(options).positional(pos).run(), vm );
po::notify( vm );
std::ostringstream usage;
usage << "Usage: " << argv[0] << " <dem-file> [options] \n\n";
usage << general_options << "\n";
if ( vm.count("help") || !vm.count("input-dem") ) {
vw_out() << usage.str() << "\n";
return 1;
} else if ( vm.count("ll-start") ^ vm.count("ll-end") ) {
vw_out() << "Must specify both ends if creating a Lat Lon Profile!\n";
vw_out() << usage.str() << "\n";
return 1;
} else if ( vm.count("px-start") ^ vm.count("px-end") ) {
vw_out() << "Must specify both ends if creating a Pixel Profile!\n";
vw_out() << usage.str() << "\n";
return 1;
} else if ( vm.count("ll-start") && ( start_ll.size() != 2 ||
end_ll.size() != 2 ) ) {
vw_out() << "Start and End Lon Lat locations require 2 values, longitude and latitude.\n";
}
// Finally starting to perform some work
cartography::GeoReference georef;
cartography::read_georeference(georef, input_file);
DiskImageView<float> disk_dem_file( input_file );
ImageViewRef<PixelMask<float> > dem;
if ( vm.count("nodata-value") ) {
vw_out() << "\t--> Masking nodata value: " << nodata_value << "\n";
dem = interpolate(create_mask( disk_dem_file, nodata_value ),
BicubicInterpolation(),
ZeroEdgeExtension());
} else {
DiskImageResource *disk_dem_rsrc = DiskImageResource::open(input_file);
if ( disk_dem_rsrc->has_nodata_read() ) {
nodata_value = disk_dem_rsrc->nodata_read();
vw_out() << "\t--> Extracted nodata value from file: " << nodata_value << "\n";
dem = interpolate(create_mask( disk_dem_file, nodata_value ),
BicubicInterpolation(),
ZeroEdgeExtension());
} else {
dem = interpolate(pixel_cast<PixelMask<float> >(disk_dem_file),
BicubicInterpolation(),
ZeroEdgeExtension());
}
}
Vector2 start, end; // Pixel Locations (everything boils down to it
// at the moment :/. Maybe in the future where
// flying cars are possible, when a user
// provides LL coordinates .. SLERP is used.
if ( vm.count("col") ) {
start = Vector2(idx_column, 0);
end = Vector2(idx_column, dem.rows()-1);
} else if ( vm.count("row") ) {
start = Vector2(0,idx_row);
end = Vector2(dem.cols()-1,idx_row);
} else if ( vm.count("ll-start") && vm.count("ll-end") ) {
// Parsing string into a ll coordinate.
if ( start_ll.find(',') == std::string::npos ||
end_ll.find(',') == std::string::npos ) {
vw_out() << "Longitude and Latitude values must be delimited by a comma.\n";
vw_out() << "\tEx: --ll-start -109.54,33.483\n\n";
vw_out() << usage.str() << "\n";
return 1;
}
size_t s_break = start_px.find(',');
size_t e_break = end_px.find(',');
Vector2 ll_start, ll_end;
} else if ( vm.count("px-start") && vm.count("px-end") ) {
// Parsing string into pixel coordinates.
if ( start_px.find(',') == std::string::npos ||
end_px.find(',') == std::string::npos ) {
vw_out() << "Column and Row pixel values must be delimited by a comma.\n";
vw_out() << "\tEx: --px-start 65,109\n\n";
vw_out() << usage.str() << "\n";
return 1;
}
size_t s_break = start_px.find(',');
size_t e_break = end_px.find(',');
start.x() = atof(start_px.substr(0,s_break).c_str());
start.y() = atof(start_px.substr(s_break+1, start_px.size()-s_break-1).c_str());
end.x() = atof(end_px.substr(0,e_break).c_str());
end.y() = atof(end_px.substr(e_break+1, end_px.size()-e_break-1).c_str());
} else {
// Dial down the middle if the user provides only a DEM.
start = Vector2( dem.cols()/2, 0);
end = Vector2( dem.cols()/2, dem.rows()-1);
}
// Debug
vw_out() << "Start: " << start << "\n";
vw_out() << "End: " << end << "\n";
// Working out the output file
BBox2i bound = bounding_box( dem );
if ( !bound.contains( start ) ||
!bound.contains( end ) ) {
vw_out() << "Given coordinates are not with in the image!\nExiting early .....\n";
return 1;
}
std::ofstream output_file( "profile.csv" );
output_file << std::setprecision(12) << "lon,lat,pix_x,pix_y,altitude,radius\n";
Vector2i delta = end - start;
for ( float r = 0; r < 1.0; r +=1/norm_2(delta) ) {
Vector2 c_idx = Vector2(0.5,0.5) + start + r*delta;
if ( !dem(int(c_idx.x()),int(c_idx.y())).valid() )
continue;
Vector2 lonlat_loc = georef.pixel_to_lonlat( c_idx );
double altitude = dem( c_idx.x(), c_idx.y() );
Vector3 xyz_pos = georef.datum().geodetic_to_cartesian( Vector3( lonlat_loc.x(),
lonlat_loc.y(),
altitude ));
double radius = norm_2( xyz_pos );
output_file << lonlat_loc.x() << "," << lonlat_loc.y() << "," << c_idx.x()
<< "," << c_idx.y() << "," << altitude << "," << radius << "\n";
}
output_file.close();
return 0;
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include <ctime>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "console.h"
#include "note.h"
#include "text.h"
namespace note {
void Note::pretty_print() const
{
std::string dc = format_time(&m_date_created);
std::string dm = format_time(&m_date_modified);
std::string sub_str;
if (m_text.size() > MAINCOLSIZE)
sub_str = m_text.substr(0, MAINCOLSIZE - 5) + "...";
else
sub_str = m_text;
std::cout << std::left
<< std::setw(5) << m_tmpId
<< std::setw(MAINCOLSIZE) << sub_str
<< std::setw(DATECOLSIZE) << "[" + dm + "]"
<< std::setw(DATECOLSIZE) << "[" + dc + "]"
<< std::endl
<< std::endl;
}
// prints a header for collection / collection list
void print_header()
{
// consider changiing (and resetting) console color? maybe wrap each part in function...
CONSOLE_SCREEN_BUFFER_INFO csbi;
change_console_color(11, &csbi);
std::cout << std::left
<< std::setw(5) << "#"
<< std::setw(MAINCOLSIZE) << "Note"
<< std::setw(DATECOLSIZE) << "Last Modified"
<< std::setw(DATECOLSIZE) << "Date Created"
<< std::endl
<< std::setw(5) << "---"
<< std::setw(MAINCOLSIZE) << "---"
<< std::setw(DATECOLSIZE) << "---"
<< std::setw(DATECOLSIZE) << "---"
<< std::endl;
reset_console_color(csbi);
}
/**
* Serialize the note.
*/
std::ostream& operator<< (std::ostream &out, const Note &n) {
out << n.m_date_created
<< ','
<< n.m_date_modified
<< ','
<< n.m_text.size()
<< ','
<< n.m_text
<< std::endl;
return out;
}
/**
* Deserialize the note.
*/
std::istream& operator>> (std::istream &in, Note &n) {
// TODO: we are losing a character when we read it in!!!
int len = 0;
char comma;
in >> n.m_date_created
>> comma
>> n.m_date_modified
>> comma
>> len
>> comma;
if (in && len) {
std::vector<char> tmp_txt(len);
// get seems to work better than read for non-binary...
in.get(&tmp_txt[0], len);
n.m_text = std::string(&tmp_txt[0]);
}
return in;
}
/**
* Got a little funky here. Wanted to make use of the overloaded i/o operators,
* but also wanted to inherit base recordable's save methods.
* So base uses serialize/deserialize member methods (pure virtuals), and
* derived forms can call them and simply use the friend ops within.
*/
std::ostream& Note::serialize(std::ostream &out) const {
out << *this;
return out;
}
std::istream& Note::deserialize(std::istream &in) {
in >> *this;
return in;
}
/**
* Adds a note to a collection's note file.
* Returns false if unable to save.
* Command should handle validation of the collection, as
* well as any updates to date modified field for the collection.
*/
bool add_note(std::string text, std::string path) {
bool inserted = false;
Note n(text);
if (n.save(path))
inserted = true;
return inserted;
}
/**
* Gets all notes in a collection.
*/
std::vector<Note> get_all_notes(std::string path) {
std::vector<Note> notes;
std::ifstream inf(path);
if (!inf)
std::cerr << "Oh no!!! Notesy can't find or open this collection!!! :(" << std::endl << std::endl;
else {
Note n;
int ct = 0;
while (inf >> n) {
n.set_tmpId(++ct);
notes.push_back(n);
inf.ignore(1, '\n');
}
inf.close();
}
return notes;
}
/**
* Lists all notes.
*/
void list_all_notes(std::vector<Note> ¬es)
{
print_header();
// use the const ref so we don't copy
for (const auto &iter : notes) {
iter.pretty_print();
}
}
/**
* Lists all notes.
*/
void list_all_notes(std::string path)
{
auto notes = get_all_notes(path);
list_all_notes(notes);
}
}
<commit_msg>adjust note read for missing last char<commit_after>#include "stdafx.h"
#include <ctime>
#include <iomanip>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include "console.h"
#include "note.h"
#include "text.h"
namespace note {
void Note::pretty_print() const
{
std::string dc = format_time(&m_date_created);
std::string dm = format_time(&m_date_modified);
std::string sub_str;
if (m_text.size() > MAINCOLSIZE)
sub_str = m_text.substr(0, MAINCOLSIZE - 5) + "...";
else
sub_str = m_text;
std::cout << std::left
<< std::setw(5) << m_tmpId
<< std::setw(MAINCOLSIZE) << sub_str
<< std::setw(DATECOLSIZE) << "[" + dm + "]"
<< std::setw(DATECOLSIZE) << "[" + dc + "]"
<< std::endl
<< std::endl;
}
// prints a header for collection / collection list
void print_header()
{
// consider changiing (and resetting) console color? maybe wrap each part in function...
CONSOLE_SCREEN_BUFFER_INFO csbi;
change_console_color(11, &csbi);
std::cout << std::left
<< std::setw(5) << "#"
<< std::setw(MAINCOLSIZE) << "Note"
<< std::setw(DATECOLSIZE) << "Last Modified"
<< std::setw(DATECOLSIZE) << "Date Created"
<< std::endl
<< std::setw(5) << "---"
<< std::setw(MAINCOLSIZE) << "---"
<< std::setw(DATECOLSIZE) << "---"
<< std::setw(DATECOLSIZE) << "---"
<< std::endl;
reset_console_color(csbi);
}
/**
* Serialize the note.
*/
std::ostream& operator<< (std::ostream &out, const Note &n) {
out << n.m_date_created
<< ','
<< n.m_date_modified
<< ','
<< n.m_text.size()
<< ','
<< n.m_text
<< std::endl;
return out;
}
/**
* Deserialize the note.
*/
std::istream& operator>> (std::istream &in, Note &n) {
int len = 0;
char comma;
in >> n.m_date_created
>> comma
>> n.m_date_modified
>> comma
>> len
>> comma;
if (in && len) {
std::vector<char> tmp_txt(len);
// leave room for the null terminator, or buffer will be too small
char *buf = new char[len + 1];
in.get(buf, len + 1);
n.m_text = std::string(buf);
delete buf;
}
return in;
}
/**
* Got a little funky here. Wanted to make use of the overloaded i/o operators,
* but also wanted to inherit base recordable's save methods.
* So base uses serialize/deserialize member methods (pure virtuals), and
* derived forms can call them and simply use the friend ops within.
*/
std::ostream& Note::serialize(std::ostream &out) const {
out << *this;
return out;
}
std::istream& Note::deserialize(std::istream &in) {
in >> *this;
return in;
}
/**
* Adds a note to a collection's note file.
* Returns false if unable to save.
* Command should handle validation of the collection, as
* well as any updates to date modified field for the collection.
*/
bool add_note(std::string text, std::string path) {
bool inserted = false;
Note n(text);
if (n.save(path))
inserted = true;
return inserted;
}
/**
* Gets all notes in a collection.
*/
std::vector<Note> get_all_notes(std::string path) {
std::vector<Note> notes;
std::ifstream inf(path);
if (!inf)
std::cerr << "Oh no!!! Notesy can't find or open this collection!!! :(" << std::endl << std::endl;
else {
Note n;
int ct = 0;
while (inf >> n) {
n.set_tmpId(++ct);
notes.push_back(n);
inf.ignore(1, '\n');
}
inf.close();
}
return notes;
}
/**
* Lists all notes.
*/
void list_all_notes(std::vector<Note> ¬es)
{
print_header();
// use the const ref so we don't copy
for (const auto &iter : notes) {
iter.pretty_print();
}
}
/**
* Lists all notes.
*/
void list_all_notes(std::string path)
{
auto notes = get_all_notes(path);
list_all_notes(notes);
}
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: propread.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: sj $ $Date: 2002-11-18 12:58:25 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _PROPREAD_HXX_
#define _PROPREAD_HXX_
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#ifndef _SVSTOR_HXX
#include <so3/svstor.hxx>
#endif
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _DATETIME_HXX
#include <tools/datetime.hxx>
#endif
#include <tools/string.hxx>
// SummaryInformation
#define PID_TITLE 0x02
#define PID_SUBJECT 0x03
#define PID_AUTHOR 0x04
#define PID_KEYWORDS 0x05
#define PID_COMMENTS 0x06
#define PID_TEMPLATE 0x07
#define PID_LASTAUTHOR 0x08
#define PID_REVNUMBER 0x09
#define PID_EDITTIME 0x0a
#define PID_LASTPRINTED_DTM 0x0b
#define PID_CREATE_DTM 0x0c
#define PID_LASTSAVED_DTM 0x0d
// DocumentSummaryInformation
#define PID_CATEGORY 0x02
#define PID_PRESFORMAT 0x03
#define PID_BYTECOUNT 0x04
#define PID_LINECOUNT 0x05
#define PID_PARACOUNT 0x06
#define PID_SLIDECOUNT 0x07
#define PID_NOTECOUNT 0x08
#define PID_HIDDENCOUNT 0x09
#define PID_MMCLIPCOUNT 0x0a
#define PID_SCALE 0x0b
#define PID_HEADINGPAIR 0x0c
#define PID_DOCPARTS 0x0d
#define PID_MANAGER 0x0e
#define PID_COMPANY 0x0f
#define PID_LINKSDIRTY 0x10
#define VT_EMPTY 0
#define VT_NULL 1
#define VT_I2 2
#define VT_I4 3
#define VT_R4 4
#define VT_R8 5
#define VT_CY 6
#define VT_DATE 7
#define VT_BSTR 8
#define VT_UI4 9
#define VT_ERROR 10
#define VT_BOOL 11
#define VT_VARIANT 12
#define VT_DECIMAL 14
#define VT_I1 16
#define VT_UI1 17
#define VT_UI2 18
#define VT_I8 20
#define VT_UI8 21
#define VT_INT 22
#define VT_UINT 23
#define VT_LPSTR 30
#define VT_LPWSTR 31
#define VT_FILETIME 64
#define VT_BLOB 65
#define VT_STREAM 66
#define VT_STORAGE 67
#define VT_STREAMED_OBJECT 68
#define VT_STORED_OBJECT 69
#define VT_BLOB_OBJECT 70
#define VT_CF 71
#define VT_CLSID 72
#define VT_VECTOR 0x1000
#define VT_ARRAY 0x2000
#define VT_BYREF 0x4000
#define VT_TYPEMASK 0xFFF
// ------------------------------------------------------------------------
class PropItem : public SvMemoryStream
{
sal_uInt16 mnTextEnc;
public :
PropItem(){};
void Clear();
void SetTextEncoding( sal_uInt16 nTextEnc ){ mnTextEnc = nTextEnc; };
sal_Bool Read( String& rString, sal_uInt32 nType = VT_EMPTY, sal_Bool bDwordAlign = sal_True );
PropItem& operator=( PropItem& rPropItem );
};
// ------------------------------------------------------------------------
class Dictionary : protected List
{
friend class Section;
void AddProperty( UINT32 nId, const String& rString );
public :
Dictionary(){};
~Dictionary();
Dictionary& operator=( Dictionary& rDictionary );
UINT32 GetProperty( const String& rPropName );
};
// ------------------------------------------------------------------------
class Section : private List
{
sal_uInt16 mnTextEnc;
protected:
BYTE aFMTID[ 16 ];
void AddProperty( sal_uInt32 nId, const sal_uInt8* pBuf, sal_uInt32 nBufSize );
public:
Section( const sal_uInt8* pFMTID );
Section( Section& rSection );
~Section();
Section& operator=( Section& rSection );
sal_Bool GetProperty( sal_uInt32 nId, PropItem& rPropItem );
sal_Bool GetDictionary( Dictionary& rDict );
const sal_uInt8* GetFMTID() const { return aFMTID; };
void Read( SvStorageStream* pStrm );
};
// ------------------------------------------------------------------------
class PropRead : private List
{
sal_Bool mbStatus;
SvStorageStream* mpSvStream;
sal_uInt16 mnByteOrder;
sal_uInt16 mnFormat;
sal_uInt16 mnVersionLo;
sal_uInt16 mnVersionHi;
sal_uInt8 mApplicationCLSID[ 16 ];
void AddSection( Section& rSection );
public:
PropRead( SvStorage& rSvStorage, const String& rName );
~PropRead();
PropRead& operator=( PropRead& rPropRead );
const Section* GetSection( const BYTE* pFMTID );
sal_Bool IsValid() const { return mbStatus; };
void Read();
};
#endif
<commit_msg>INTEGRATION: CWS mav09 (1.3.386); FILE MERGED 2004/04/14 14:11:55 mba 1.3.386.1: #i27773#: remove so3; new storage API<commit_after>/*************************************************************************
*
* $RCSfile: propread.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2004-10-04 18:17:45 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _PROPREAD_HXX_
#define _PROPREAD_HXX_
#ifndef _SOLAR_H
#include <tools/solar.h>
#endif
#include <sot/storage.hxx>
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#ifndef _LIST_HXX
#include <tools/list.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _DATETIME_HXX
#include <tools/datetime.hxx>
#endif
#include <tools/string.hxx>
// SummaryInformation
#define PID_TITLE 0x02
#define PID_SUBJECT 0x03
#define PID_AUTHOR 0x04
#define PID_KEYWORDS 0x05
#define PID_COMMENTS 0x06
#define PID_TEMPLATE 0x07
#define PID_LASTAUTHOR 0x08
#define PID_REVNUMBER 0x09
#define PID_EDITTIME 0x0a
#define PID_LASTPRINTED_DTM 0x0b
#define PID_CREATE_DTM 0x0c
#define PID_LASTSAVED_DTM 0x0d
// DocumentSummaryInformation
#define PID_CATEGORY 0x02
#define PID_PRESFORMAT 0x03
#define PID_BYTECOUNT 0x04
#define PID_LINECOUNT 0x05
#define PID_PARACOUNT 0x06
#define PID_SLIDECOUNT 0x07
#define PID_NOTECOUNT 0x08
#define PID_HIDDENCOUNT 0x09
#define PID_MMCLIPCOUNT 0x0a
#define PID_SCALE 0x0b
#define PID_HEADINGPAIR 0x0c
#define PID_DOCPARTS 0x0d
#define PID_MANAGER 0x0e
#define PID_COMPANY 0x0f
#define PID_LINKSDIRTY 0x10
#define VT_EMPTY 0
#define VT_NULL 1
#define VT_I2 2
#define VT_I4 3
#define VT_R4 4
#define VT_R8 5
#define VT_CY 6
#define VT_DATE 7
#define VT_BSTR 8
#define VT_UI4 9
#define VT_ERROR 10
#define VT_BOOL 11
#define VT_VARIANT 12
#define VT_DECIMAL 14
#define VT_I1 16
#define VT_UI1 17
#define VT_UI2 18
#define VT_I8 20
#define VT_UI8 21
#define VT_INT 22
#define VT_UINT 23
#define VT_LPSTR 30
#define VT_LPWSTR 31
#define VT_FILETIME 64
#define VT_BLOB 65
#define VT_STREAM 66
#define VT_STORAGE 67
#define VT_STREAMED_OBJECT 68
#define VT_STORED_OBJECT 69
#define VT_BLOB_OBJECT 70
#define VT_CF 71
#define VT_CLSID 72
#define VT_VECTOR 0x1000
#define VT_ARRAY 0x2000
#define VT_BYREF 0x4000
#define VT_TYPEMASK 0xFFF
// ------------------------------------------------------------------------
class PropItem : public SvMemoryStream
{
sal_uInt16 mnTextEnc;
public :
PropItem(){};
void Clear();
void SetTextEncoding( sal_uInt16 nTextEnc ){ mnTextEnc = nTextEnc; };
sal_Bool Read( String& rString, sal_uInt32 nType = VT_EMPTY, sal_Bool bDwordAlign = sal_True );
PropItem& operator=( PropItem& rPropItem );
};
// ------------------------------------------------------------------------
class Dictionary : protected List
{
friend class Section;
void AddProperty( UINT32 nId, const String& rString );
public :
Dictionary(){};
~Dictionary();
Dictionary& operator=( Dictionary& rDictionary );
UINT32 GetProperty( const String& rPropName );
};
// ------------------------------------------------------------------------
class Section : private List
{
sal_uInt16 mnTextEnc;
protected:
BYTE aFMTID[ 16 ];
void AddProperty( sal_uInt32 nId, const sal_uInt8* pBuf, sal_uInt32 nBufSize );
public:
Section( const sal_uInt8* pFMTID );
Section( Section& rSection );
~Section();
Section& operator=( Section& rSection );
sal_Bool GetProperty( sal_uInt32 nId, PropItem& rPropItem );
sal_Bool GetDictionary( Dictionary& rDict );
const sal_uInt8* GetFMTID() const { return aFMTID; };
void Read( SvStorageStream* pStrm );
};
// ------------------------------------------------------------------------
class PropRead : private List
{
sal_Bool mbStatus;
SvStorageStream* mpSvStream;
sal_uInt16 mnByteOrder;
sal_uInt16 mnFormat;
sal_uInt16 mnVersionLo;
sal_uInt16 mnVersionHi;
sal_uInt8 mApplicationCLSID[ 16 ];
void AddSection( Section& rSection );
public:
PropRead( SvStorage& rSvStorage, const String& rName );
~PropRead();
PropRead& operator=( PropRead& rPropRead );
const Section* GetSection( const BYTE* pFMTID );
sal_Bool IsValid() const { return mbStatus; };
void Read();
};
#endif
<|endoftext|>
|
<commit_before><commit_msg>coverity#1265810 Dereference null return value<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: fusldlg.cxx,v $
*
* $Revision: 1.1.1.1 $
*
* last change: $Author: hr $ $Date: 2000-09-18 16:48:36 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#include "drawdoc.hxx"
#include "sdpage.hxx"
#include "present.hxx"
#include "sdresid.hxx"
#include "strings.hrc"
#include "sdattr.hxx"
#include "fusldlg.hxx"
#include "glob.hrc"
#include "sdmod.hxx"
#include "viewshel.hxx"
#include "optsitem.hxx"
#define ITEMVALUE(ItemSet,Id,Cast) ((const Cast&)(ItemSet).Get(Id)).GetValue()
TYPEINIT1( FuSlideShowDlg, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuSlideShowDlg::FuSlideShowDlg( SdViewShell* pViewSh, SdWindow* pWin,
SdView* pView, SdDrawDocument* pDoc, SfxRequest& rReq) :
FuPoor( pViewSh, pWin, pView, pDoc, rReq )
{
SfxItemSet aDlgSet( pDoc->GetPool(), ATTR_PRESENT_START, ATTR_PRESENT_END );
List aPageNameList;
const String& rPresPage = pDoc->GetPresPage();
String aFirstPage;
String aStandardName( SdResId( STR_PAGE ) );
SdPage* pPage = NULL;
long nPage;
for( nPage = pDoc->GetSdPageCount( PK_STANDARD ) - 1L; nPage >= 0L; nPage-- )
{
pPage = pDoc->GetSdPage( (USHORT) nPage, PK_STANDARD );
String* pStr = new String( pPage->GetName() );
if ( !pStr->Len() )
{
*pStr = String( SdResId( STR_PAGE ) );
(*pStr).Append( UniString::CreateFromInt32( nPage + 1 ) );
}
aPageNameList.Insert( pStr, (ULONG) 0 );
// ist dies unsere (vorhandene) erste Seite?
if ( rPresPage == *pStr )
aFirstPage = rPresPage;
else if ( pPage->IsSelected() && !aFirstPage.Len() )
aFirstPage = *pStr;
}
List* pCustomShowList = pDoc->GetCustomShowList(); // No Create
/// NEU
BOOL bStartWithActualPage = SD_MOD()->GetSdOptions( pDoc->GetDocumentType() )->IsStartWithActualPage();
if( bStartWithActualPage )
{
aFirstPage = pViewSh->GetActualPage()->GetName();
pCustomShowList = NULL;
}
if( !aFirstPage.Len() && pPage )
aFirstPage = pPage->GetName();
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_ALL, pDoc->GetPresAll() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_CUSTOMSHOW, pDoc->IsCustomShow() ) );
aDlgSet.Put( SfxStringItem( ATTR_PRESENT_DIANAME, aFirstPage ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_ENDLESS, pDoc->GetPresEndless() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_MANUEL, pDoc->GetPresManual() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_MOUSE, pDoc->GetPresMouseVisible() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_PEN, pDoc->GetPresMouseAsPen() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_NAVIGATOR, pDoc->GetStartPresWithNavigator() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_ANIMATION_ALLOWED, pDoc->IsAnimationAllowed() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_CHANGE_PAGE, !pDoc->GetPresLockedPages() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_ALWAYS_ON_TOP, pDoc->GetPresAlwaysOnTop() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_FULLSCREEN, pDoc->GetPresFullScreen() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_START_ACTUAL_PAGE, bStartWithActualPage ) );
aDlgSet.Put( SfxUInt32Item( ATTR_PRESENT_PAUSE_TIMEOUT, pDoc->GetPresPause() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_SHOW_PAUSELOGO, pDoc->IsPresShowLogo() ) );
SdStartPresentationDlg aDlg( (Window*) pWindow, aDlgSet, aPageNameList, pCustomShowList );
if( aDlg.Execute() == RET_OK )
{
String aPage;
ULONG nValue32;
BOOL bValue;
BOOL bValuesChanged = FALSE;
aDlg.GetAttr( aDlgSet );
aPage = ITEMVALUE( aDlgSet, ATTR_PRESENT_DIANAME, SfxStringItem );
if( aPage != pDoc->GetPresPage() )
{
bValuesChanged = TRUE;
pDoc->SetPresPage( aPage );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_ALL, SfxBoolItem );
if ( bValue != pDoc->GetPresAll() )
{
bValuesChanged = TRUE;
pDoc->SetPresAll( bValue );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_CUSTOMSHOW, SfxBoolItem );
if ( bValue != pDoc->IsCustomShow() )
{
bValuesChanged = TRUE;
pDoc->SetCustomShow( bValue );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_ENDLESS, SfxBoolItem );
if ( bValue != pDoc->GetPresEndless() )
{
bValuesChanged = TRUE;
pDoc->SetPresEndless( bValue );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_MANUEL, SfxBoolItem );
if ( bValue != pDoc->GetPresManual() )
{
bValuesChanged = TRUE;
pDoc->SetPresManual( bValue );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_MOUSE, SfxBoolItem );
if ( bValue != pDoc->GetPresMouseVisible() )
{
bValuesChanged = TRUE;
pDoc->SetPresMouseVisible( bValue );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_PEN, SfxBoolItem );
if ( bValue != pDoc->GetPresMouseAsPen() )
{
bValuesChanged = TRUE;
pDoc->SetPresMouseAsPen( bValue );
}
bValue = !ITEMVALUE( aDlgSet, ATTR_PRESENT_CHANGE_PAGE, SfxBoolItem );
if ( bValue != pDoc->GetPresLockedPages() )
{
bValuesChanged = TRUE;
pDoc->SetPresLockedPages( bValue );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_NAVIGATOR, SfxBoolItem );
if ( bValue != pDoc->GetStartPresWithNavigator() )
{
bValuesChanged = TRUE;
pDoc->SetStartPresWithNavigator( bValue );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_ANIMATION_ALLOWED, SfxBoolItem );
if ( bValue != pDoc->IsAnimationAllowed() )
{
bValuesChanged = TRUE;
pDoc->SetAnimationAllowed( bValue );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_ALWAYS_ON_TOP, SfxBoolItem );
if ( bValue != pDoc->GetPresAlwaysOnTop() )
{
bValuesChanged = TRUE;
pDoc->SetPresAlwaysOnTop( bValue );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_FULLSCREEN, SfxBoolItem );
if ( bValue != pDoc->GetPresFullScreen() )
{
bValuesChanged = TRUE;
pDoc->SetPresFullScreen( bValue );
}
nValue32 = ITEMVALUE( aDlgSet, ATTR_PRESENT_PAUSE_TIMEOUT, SfxUInt32Item );
if( nValue32 != pDoc->GetPresPause() )
{
bValuesChanged = TRUE;
pDoc->SetPresPause( nValue32 );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_SHOW_PAUSELOGO, SfxBoolItem );
if ( bValue != pDoc->IsPresShowLogo() )
{
bValuesChanged = TRUE;
pDoc->SetPresShowLogo( bValue );
}
// wenn sich etwas geaendert hat, setzen wir das Modified-Flag,
if ( bValuesChanged )
pDoc->SetChanged( TRUE );
}
// Strings aus Liste loeschen
for( void* pStr = aPageNameList.First(); pStr; pStr = aPageNameList.Next() )
delete (String*) pStr;
}
<commit_msg>INTEGRATION: CWS draw14 (1.1.1.1.182); FILE MERGED 2003/05/28 09:19:26 cl 1.1.1.1.182.1: #109180# changed start from current page feature<commit_after>/*************************************************************************
*
* $RCSfile: fusldlg.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2003-06-04 12:27:46 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#ifndef _SFXITEMSET_HXX //autogen
#include <svtools/itemset.hxx>
#endif
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#include "drawdoc.hxx"
#include "sdpage.hxx"
#include "present.hxx"
#include "sdresid.hxx"
#include "strings.hrc"
#include "sdattr.hxx"
#include "fusldlg.hxx"
#include "glob.hrc"
#include "sdmod.hxx"
#include "viewshel.hxx"
#include "optsitem.hxx"
#define ITEMVALUE(ItemSet,Id,Cast) ((const Cast&)(ItemSet).Get(Id)).GetValue()
TYPEINIT1( FuSlideShowDlg, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuSlideShowDlg::FuSlideShowDlg( SdViewShell* pViewSh, SdWindow* pWin,
SdView* pView, SdDrawDocument* pDoc, SfxRequest& rReq) :
FuPoor( pViewSh, pWin, pView, pDoc, rReq )
{
SfxItemSet aDlgSet( pDoc->GetPool(), ATTR_PRESENT_START, ATTR_PRESENT_END );
List aPageNameList;
const String& rPresPage = pDoc->GetPresPage();
String aFirstPage;
String aStandardName( SdResId( STR_PAGE ) );
SdPage* pPage = NULL;
long nPage;
for( nPage = pDoc->GetSdPageCount( PK_STANDARD ) - 1L; nPage >= 0L; nPage-- )
{
pPage = pDoc->GetSdPage( (USHORT) nPage, PK_STANDARD );
String* pStr = new String( pPage->GetName() );
if ( !pStr->Len() )
{
*pStr = String( SdResId( STR_PAGE ) );
(*pStr).Append( UniString::CreateFromInt32( nPage + 1 ) );
}
aPageNameList.Insert( pStr, (ULONG) 0 );
// ist dies unsere (vorhandene) erste Seite?
if ( rPresPage == *pStr )
aFirstPage = rPresPage;
else if ( pPage->IsSelected() && !aFirstPage.Len() )
aFirstPage = *pStr;
}
List* pCustomShowList = pDoc->GetCustomShowList(); // No Create
BOOL bStartWithActualPage = SD_MOD()->GetSdOptions( pDoc->GetDocumentType() )->IsStartWithActualPage();
/* #109180# change in behaviour, even when always start with current page is enabled, range settings are
still used
if( bStartWithActualPage )
{
aFirstPage = pViewSh->GetActualPage()->GetName();
pCustomShowList = NULL;
}
*/
if( !aFirstPage.Len() && pPage )
aFirstPage = pPage->GetName();
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_ALL, pDoc->GetPresAll() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_CUSTOMSHOW, pDoc->IsCustomShow() ) );
aDlgSet.Put( SfxStringItem( ATTR_PRESENT_DIANAME, aFirstPage ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_ENDLESS, pDoc->GetPresEndless() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_MANUEL, pDoc->GetPresManual() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_MOUSE, pDoc->GetPresMouseVisible() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_PEN, pDoc->GetPresMouseAsPen() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_NAVIGATOR, pDoc->GetStartPresWithNavigator() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_ANIMATION_ALLOWED, pDoc->IsAnimationAllowed() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_CHANGE_PAGE, !pDoc->GetPresLockedPages() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_ALWAYS_ON_TOP, pDoc->GetPresAlwaysOnTop() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_FULLSCREEN, pDoc->GetPresFullScreen() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_START_ACTUAL_PAGE, bStartWithActualPage ) );
aDlgSet.Put( SfxUInt32Item( ATTR_PRESENT_PAUSE_TIMEOUT, pDoc->GetPresPause() ) );
aDlgSet.Put( SfxBoolItem( ATTR_PRESENT_SHOW_PAUSELOGO, pDoc->IsPresShowLogo() ) );
SdStartPresentationDlg aDlg( (Window*) pWindow, aDlgSet, aPageNameList, pCustomShowList );
if( aDlg.Execute() == RET_OK )
{
String aPage;
ULONG nValue32;
BOOL bValue;
BOOL bValuesChanged = FALSE;
aDlg.GetAttr( aDlgSet );
aPage = ITEMVALUE( aDlgSet, ATTR_PRESENT_DIANAME, SfxStringItem );
if( aPage != pDoc->GetPresPage() )
{
bValuesChanged = TRUE;
pDoc->SetPresPage( aPage );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_ALL, SfxBoolItem );
if ( bValue != pDoc->GetPresAll() )
{
bValuesChanged = TRUE;
pDoc->SetPresAll( bValue );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_CUSTOMSHOW, SfxBoolItem );
if ( bValue != pDoc->IsCustomShow() )
{
bValuesChanged = TRUE;
pDoc->SetCustomShow( bValue );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_ENDLESS, SfxBoolItem );
if ( bValue != pDoc->GetPresEndless() )
{
bValuesChanged = TRUE;
pDoc->SetPresEndless( bValue );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_MANUEL, SfxBoolItem );
if ( bValue != pDoc->GetPresManual() )
{
bValuesChanged = TRUE;
pDoc->SetPresManual( bValue );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_MOUSE, SfxBoolItem );
if ( bValue != pDoc->GetPresMouseVisible() )
{
bValuesChanged = TRUE;
pDoc->SetPresMouseVisible( bValue );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_PEN, SfxBoolItem );
if ( bValue != pDoc->GetPresMouseAsPen() )
{
bValuesChanged = TRUE;
pDoc->SetPresMouseAsPen( bValue );
}
bValue = !ITEMVALUE( aDlgSet, ATTR_PRESENT_CHANGE_PAGE, SfxBoolItem );
if ( bValue != pDoc->GetPresLockedPages() )
{
bValuesChanged = TRUE;
pDoc->SetPresLockedPages( bValue );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_NAVIGATOR, SfxBoolItem );
if ( bValue != pDoc->GetStartPresWithNavigator() )
{
bValuesChanged = TRUE;
pDoc->SetStartPresWithNavigator( bValue );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_ANIMATION_ALLOWED, SfxBoolItem );
if ( bValue != pDoc->IsAnimationAllowed() )
{
bValuesChanged = TRUE;
pDoc->SetAnimationAllowed( bValue );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_ALWAYS_ON_TOP, SfxBoolItem );
if ( bValue != pDoc->GetPresAlwaysOnTop() )
{
bValuesChanged = TRUE;
pDoc->SetPresAlwaysOnTop( bValue );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_FULLSCREEN, SfxBoolItem );
if ( bValue != pDoc->GetPresFullScreen() )
{
bValuesChanged = TRUE;
pDoc->SetPresFullScreen( bValue );
}
nValue32 = ITEMVALUE( aDlgSet, ATTR_PRESENT_PAUSE_TIMEOUT, SfxUInt32Item );
if( nValue32 != pDoc->GetPresPause() )
{
bValuesChanged = TRUE;
pDoc->SetPresPause( nValue32 );
}
bValue = ITEMVALUE( aDlgSet, ATTR_PRESENT_SHOW_PAUSELOGO, SfxBoolItem );
if ( bValue != pDoc->IsPresShowLogo() )
{
bValuesChanged = TRUE;
pDoc->SetPresShowLogo( bValue );
}
// wenn sich etwas geaendert hat, setzen wir das Modified-Flag,
if ( bValuesChanged )
pDoc->SetChanged( TRUE );
}
// Strings aus Liste loeschen
for( void* pStr = aPageNameList.First(); pStr; pStr = aPageNameList.Next() )
delete (String*) pStr;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: fuinsfil.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2005-01-18 15:17:26 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef SD_FU_INSERT_FILE_HXX
#define SD_FU_INSERT_FILE_HXX
#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif
#include <vector>
class SfxMedium;
struct StyleRequestData;
namespace sd {
class FuInsertFile
: public FuPoor
{
public:
TYPEINFO();
FuInsertFile (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq);
virtual ~FuInsertFile (void);
virtual void Activate(); // Function aktivieren
virtual void Deactivate(); // Function deaktivieren
static void GetSupportedFilterVector( ::std::vector< String >& rFilterVector );
private:
String aLayoutName; // Layoutname der aktuell eingefuegten Seite
String aFilterName; // gewaehlter Dateifilter
String aFile; // gewaehlter Dateiname
void InsTextOrRTFinOlMode(SfxMedium* pMedium);
BOOL InsSDDinOlMode(SfxMedium* pMedium);
void InsTextOrRTFinDrMode(SfxMedium* pMedium);
BOOL InsSDDinDrMode(SfxMedium* pMedium);
};
} // end of namespace sd
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.236); FILE MERGED 2005/09/05 13:23:07 rt 1.4.236.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fuinsfil.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 05:34:42 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef SD_FU_INSERT_FILE_HXX
#define SD_FU_INSERT_FILE_HXX
#ifndef SD_FU_POOR_HXX
#include "fupoor.hxx"
#endif
#include <vector>
class SfxMedium;
struct StyleRequestData;
namespace sd {
class FuInsertFile
: public FuPoor
{
public:
TYPEINFO();
FuInsertFile (
ViewShell* pViewSh,
::sd::Window* pWin,
::sd::View* pView,
SdDrawDocument* pDoc,
SfxRequest& rReq);
virtual ~FuInsertFile (void);
virtual void Activate(); // Function aktivieren
virtual void Deactivate(); // Function deaktivieren
static void GetSupportedFilterVector( ::std::vector< String >& rFilterVector );
private:
String aLayoutName; // Layoutname der aktuell eingefuegten Seite
String aFilterName; // gewaehlter Dateifilter
String aFile; // gewaehlter Dateiname
void InsTextOrRTFinOlMode(SfxMedium* pMedium);
BOOL InsSDDinOlMode(SfxMedium* pMedium);
void InsTextOrRTFinDrMode(SfxMedium* pMedium);
BOOL InsSDDinDrMode(SfxMedium* pMedium);
};
} // end of namespace sd
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: StorageNativeInputStream.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: hr $ $Date: 2004-11-09 12:09:23 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): Ocke Janssen
*
*
************************************************************************/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_
#include <com/sun/star/io/XStream.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTSUBSTORAGESUPPLIER_HPP_
#include <com/sun/star/document/XDocumentSubStorageSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_
#include <com/sun/star/embed/XStorage.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_
#include <com/sun/star/embed/ElementModes.hpp>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#include "hsqldb/HStorageAccess.h"
#include "hsqldb/HStorageMap.hxx"
#include "hsqldb/StorageNativeInputStream.h"
#include "jvmaccess/virtualmachine.hxx"
#include "com/sun/star/lang/XSingleComponentFactory.hpp"
#include <rtl/logfile.hxx>
#include <limits>
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::document;
using namespace ::com::sun::star::embed;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;
using namespace ::connectivity::hsqldb;
#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
/*****************************************************************************/
/* exception macros */
#define ThrowException(env, type, msg) { \
env->ThrowNew(env->FindClass(type), msg); }
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream
* Method: openStream
* Signature: (Ljava/lang/String;Ljava/lang/String;I)V
*/
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_openStream
(JNIEnv * env, jobject obj_this,jstring key, jstring name, jint mode)
{
Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_openStream(env,obj_this,name,key,mode);
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream
* Method: read
* Signature: (Ljava/lang/String;Ljava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2
(JNIEnv * env, jobject obj_this,jstring key, jstring name)
{
return Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_read__Ljava_lang_String_2Ljava_lang_String_2(env,obj_this,name,key);
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream
* Method: read
* Signature: (Ljava/lang/String;Ljava/lang/String;[BII)I
*/
JNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2_3BII
(JNIEnv * env, jobject obj_this,jstring key, jstring name, jbyteArray buffer, jint off, jint len)
{
::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);
Reference< XInputStream> xIn = pHelper.get() ? pHelper->getInputStream() : Reference< XInputStream>();
OSL_ENSURE(xIn.is(),"Input stream is NULL!");
if ( xIn.is() )
{
sal_Int32 nBytesRead = 0;
jsize nLen = env->GetArrayLength(buffer);
Sequence< ::sal_Int8 > aData(nLen);
sal_Int32 av = xIn->available();
if ( av != 0 && nLen > av)
nBytesRead = xIn->readBytes(aData, av);
else
nBytesRead = xIn->readBytes(aData,nLen);
// Casting bytesRead to an int is okay, since the user can
// only pass in an integer length to read, so the bytesRead
// must <= len.
//
if (nBytesRead <= 0) {
return -1;
} else if (nBytesRead < len) {
env->SetByteArrayRegion(buffer,off,nBytesRead,&aData[0]);
} else {
env->SetByteArrayRegion(buffer,off,len,&aData[0]);
}
return nBytesRead;
}
ThrowException( env,
"java/io/IOException",
"Stream is not valid");
return -1;
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream
* Method: close
* Signature: (Ljava/lang/String;Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_close
(JNIEnv * env, jobject obj_this,jstring key, jstring name)
{
StorageContainer::revokeStream(env,name,key);
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream
* Method: skip
* Signature: (Ljava/lang/String;Ljava/lang/String;J)J
*/
JNIEXPORT jlong JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_skip
(JNIEnv * env, jobject obj_this,jstring key, jstring name, jlong n)
{
::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);
OSL_ENSURE(pHelper.get(),"No stream helper!");
if ( pHelper.get() )
{
Reference<XInputStream> xIn = pHelper->getInputStream();
if ( xIn.is() )
{
try
{
sal_Int32 avail = xIn->available();
sal_Int64 tmpLongVal = n;
sal_Int32 tmpIntVal;
do {
if (tmpLongVal >= ::std::numeric_limits<sal_Int64>::max() )
tmpIntVal = ::std::numeric_limits<sal_Int32>::max();
else // Casting is safe here.
tmpIntVal = static_cast<sal_Int32>(tmpLongVal);
tmpLongVal -= tmpIntVal;
xIn->skipBytes(tmpIntVal);
} while (tmpLongVal > 0);
if ( avail != 0 && avail < n) {
return(avail);
} else {
return(n);
}
}
catch(Exception& e)
{
OSL_ENSURE(0,"Exception catched! : writeBytes(aData);");
if (JNI_FALSE != env->ExceptionCheck())
env->ExceptionClear();
::rtl::OString cstr( ::rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_JAVA_UTF8 ) );
OSL_TRACE( __FILE__": forwarding Exception: %s", cstr.getStr() );
ThrowException( env,
"java/io/IOException",
cstr.getStr());
}
}
}
else
{
ThrowException( env,
"java/io/IOException",
"Stream is not valid");
}
return 0;
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream
* Method: available
* Signature: (Ljava/lang/String;Ljava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_available
(JNIEnv * env, jobject obj_this,jstring key, jstring name)
{
::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);
OSL_ENSURE(pHelper.get(),"No stream helper!");
Reference<XInputStream> xIn = pHelper.get() ? pHelper->getInputStream() : Reference<XInputStream>();
if ( xIn.is() )
{
try
{
return xIn->available();
}
catch(Exception& e)
{
OSL_ENSURE(0,"Exception catched! : writeBytes(aData);");
if (JNI_FALSE != env->ExceptionCheck())
env->ExceptionClear();
::rtl::OString cstr( ::rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_JAVA_UTF8 ) );
OSL_TRACE( __FILE__": forwarding Exception: %s", cstr.getStr() );
ThrowException( env,
"java/io/IOException",
cstr.getStr());
}
}
else
{
ThrowException( env,
"java/io/IOException",
"Stream is not valid");
}
return 0;
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream
* Method: read
* Signature: (Ljava/lang/String;Ljava/lang/String;[B)I
*/
JNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2_3B
(JNIEnv * env, jobject obj_this,jstring key, jstring name, jbyteArray buffer)
{
::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);
Reference< XInputStream> xIn = pHelper.get() ? pHelper->getInputStream() : Reference< XInputStream>();
OSL_ENSURE(xIn.is(),"Input stream is NULL!");
sal_Int32 nBytesRead = 0;
if ( xIn.is() )
{
jsize nLen = env->GetArrayLength(buffer);
Sequence< ::sal_Int8 > aData(nLen);
sal_Int32 av = xIn->available();
if ( av != 0 && nLen > av)
nBytesRead = xIn->readBytes(aData, av);
else
nBytesRead = xIn->readBytes(aData,nLen);
// Casting bytesRead to an int is okay, since the user can
// only pass in an integer length to read, so the bytesRead
// must <= len.
//
if (nBytesRead <= 0) {
return -1;
}
env->SetByteArrayRegion(buffer,0,nLen,&aData[0]);
}
return nBytesRead;
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS hsqldb2 (1.2.20); FILE MERGED 2005/01/28 12:21:54 oj 1.2.20.2: #i39922# new interfaces in hsqldb and some debug info 2005/01/25 08:42:51 oj 1.2.20.1: #i39922# correct stream handling<commit_after>/*************************************************************************
*
* $RCSfile: StorageNativeInputStream.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2005-02-16 15:52:28 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): Ocke Janssen
*
*
************************************************************************/
#if HAVE_CONFIG_H
#include <config.h>
#endif
#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_
#include <com/sun/star/io/XStream.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_DOCUMENT_XDOCUMENTSUBSTORAGESUPPLIER_HPP_
#include <com/sun/star/document/XDocumentSubStorageSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_XSTORAGE_HPP_
#include <com/sun/star/embed/XStorage.hpp>
#endif
#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_
#include <com/sun/star/embed/ElementModes.hpp>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#include "hsqldb/HStorageAccess.h"
#include "hsqldb/HStorageMap.hxx"
#include "hsqldb/StorageNativeInputStream.h"
#include "jvmaccess/virtualmachine.hxx"
#include "com/sun/star/lang/XSingleComponentFactory.hpp"
#include <rtl/logfile.hxx>
#include <limits>
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::document;
using namespace ::com::sun::star::embed;
using namespace ::com::sun::star::io;
using namespace ::com::sun::star::lang;
using namespace ::connectivity::hsqldb;
#define OUSTR(x) ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(x) )
/*****************************************************************************/
/* exception macros */
#define ThrowException(env, type, msg) { \
env->ThrowNew(env->FindClass(type), msg); }
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream
* Method: openStream
* Signature: (Ljava/lang/String;Ljava/lang/String;I)V
*/
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_openStream
(JNIEnv * env, jobject obj_this,jstring key, jstring name, jint mode)
{
#if OSL_DEBUG_LEVEL > 1
{
::rtl::OUString sOrgName = StorageContainer::jstring2ustring(env,name);
sOrgName += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".input"));
::rtl::OString sName = ::rtl::OUStringToOString(sOrgName,RTL_TEXTENCODING_ASCII_US);
getStreams()[sOrgName] = fopen( sName.getStr(), "a+" );
}
#endif
StorageContainer::registerStream(env,name,key,mode);
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream
* Method: read
* Signature: (Ljava/lang/String;Ljava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2
(JNIEnv * env, jobject obj_this,jstring key, jstring name)
{
return Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_read__Ljava_lang_String_2Ljava_lang_String_2(env,obj_this,name,key);
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream
* Method: read
* Signature: (Ljava/lang/String;Ljava/lang/String;[BII)I
*/
JNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2_3BII
(JNIEnv * env, jobject obj_this,jstring key, jstring name, jbyteArray buffer, jint off, jint len)
{
return Java_com_sun_star_sdbcx_comp_hsqldb_NativeStorageAccess_read__Ljava_lang_String_2Ljava_lang_String_2_3BII(env,obj_this,name,key,buffer,off,len);
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream
* Method: close
* Signature: (Ljava/lang/String;Ljava/lang/String;)V
*/
JNIEXPORT void JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_close
(JNIEnv * env, jobject obj_this,jstring key, jstring name)
{
#if OSL_DEBUG_LEVEL > 1
{
::rtl::OUString sOrgName = StorageContainer::jstring2ustring(env,name);
sOrgName += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".input"));
fclose( getStreams()[sOrgName] );
getStreams().erase(sOrgName);
}
#endif
StorageContainer::revokeStream(env,name,key);
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream
* Method: skip
* Signature: (Ljava/lang/String;Ljava/lang/String;J)J
*/
JNIEXPORT jlong JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_skip
(JNIEnv * env, jobject obj_this,jstring key, jstring name, jlong n)
{
::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);
OSL_ENSURE(pHelper.get(),"No stream helper!");
if ( pHelper.get() )
{
Reference<XInputStream> xIn = pHelper->getInputStream();
if ( xIn.is() )
{
try
{
sal_Int32 avail = xIn->available();
sal_Int64 tmpLongVal = n;
sal_Int32 tmpIntVal;
do {
if (tmpLongVal >= ::std::numeric_limits<sal_Int64>::max() )
tmpIntVal = ::std::numeric_limits<sal_Int32>::max();
else // Casting is safe here.
tmpIntVal = static_cast<sal_Int32>(tmpLongVal);
tmpLongVal -= tmpIntVal;
xIn->skipBytes(tmpIntVal);
} while (tmpLongVal > 0);
if ( avail != 0 && avail < n) {
return(avail);
} else {
return(n);
}
}
catch(Exception& e)
{
OSL_ENSURE(0,"Exception catched! : skip();");
if (JNI_FALSE != env->ExceptionCheck())
env->ExceptionClear();
::rtl::OString cstr( ::rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_JAVA_UTF8 ) );
OSL_TRACE( __FILE__": forwarding Exception: %s", cstr.getStr() );
ThrowException( env,
"java/io/IOException",
cstr.getStr());
}
}
}
else
{
ThrowException( env,
"java/io/IOException",
"Stream is not valid");
}
return 0;
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream
* Method: available
* Signature: (Ljava/lang/String;Ljava/lang/String;)I
*/
JNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_available
(JNIEnv * env, jobject obj_this,jstring key, jstring name)
{
::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);
OSL_ENSURE(pHelper.get(),"No stream helper!");
Reference<XInputStream> xIn = pHelper.get() ? pHelper->getInputStream() : Reference<XInputStream>();
if ( xIn.is() )
{
try
{
return xIn->available();
}
catch(Exception& e)
{
OSL_ENSURE(0,"Exception catched! : available();");
if (JNI_FALSE != env->ExceptionCheck())
env->ExceptionClear();
::rtl::OString cstr( ::rtl::OUStringToOString(e.Message, RTL_TEXTENCODING_JAVA_UTF8 ) );
OSL_TRACE( __FILE__": forwarding Exception: %s", cstr.getStr() );
ThrowException( env,
"java/io/IOException",
cstr.getStr());
}
}
else
{
ThrowException( env,
"java/io/IOException",
"Stream is not valid");
}
return 0;
}
// -----------------------------------------------------------------------------
/*
* Class: com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream
* Method: read
* Signature: (Ljava/lang/String;Ljava/lang/String;[B)I
*/
JNIEXPORT jint JNICALL Java_com_sun_star_sdbcx_comp_hsqldb_StorageNativeInputStream_read__Ljava_lang_String_2Ljava_lang_String_2_3B
(JNIEnv * env, jobject obj_this,jstring key, jstring name, jbyteArray buffer)
{
::boost::shared_ptr<StreamHelper> pHelper = StorageContainer::getRegisteredStream(env,name,key);
Reference< XInputStream> xIn = pHelper.get() ? pHelper->getInputStream() : Reference< XInputStream>();
OSL_ENSURE(xIn.is(),"Input stream is NULL!");
sal_Int32 nBytesRead = 0;
if ( xIn.is() )
{
jsize nLen = env->GetArrayLength(buffer);
Sequence< ::sal_Int8 > aData(nLen);
sal_Int32 av = xIn->available();
if ( av > 0 )
{
if (nLen > av)
nBytesRead = xIn->readBytes(aData, av);
else
nBytesRead = xIn->readBytes(aData,nLen);
}
// Casting bytesRead to an int is okay, since the user can
// only pass in an integer length to read, so the bytesRead
// must <= len.
//
if (nBytesRead <= 0) {
return -1;
}
OSL_ENSURE(nLen >= nBytesRead,"Buffer is too small!");
OSL_ENSURE(aData.getLength() >= nBytesRead,"Buffer is too small!");
env->SetByteArrayRegion(buffer,0,nBytesRead,&aData[0]);
#if OSL_DEBUG_LEVEL > 1
::rtl::OUString sOrgName = StorageContainer::jstring2ustring(env,name);
sOrgName += ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(".input"));
fwrite(&aData[0],sizeof(sal_Int8),nBytesRead,getStreams()[sOrgName]);
#endif
}
return nBytesRead;
}
// -----------------------------------------------------------------------------
<|endoftext|>
|
<commit_before><commit_msg>coverity#1187866 unused bStartWithActualPage<commit_after><|endoftext|>
|
<commit_before>// Copyright (c) 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 "content/browser/in_process_webkit/dom_storage_message_filter.h"
#include "base/nullable_string16.h"
#include "content/browser/browser_thread.h"
#include "content/browser/in_process_webkit/dom_storage_area.h"
#include "content/browser/in_process_webkit/dom_storage_context.h"
#include "content/browser/in_process_webkit/dom_storage_namespace.h"
#include "content/common/dom_storage_messages.h"
#include "googleurl/src/gurl.h"
using WebKit::WebStorageArea;
DOMStorageMessageFilter* DOMStorageMessageFilter::storage_event_message_filter =
NULL;
const GURL* DOMStorageMessageFilter::storage_event_url_ = NULL;
DOMStorageMessageFilter::
ScopedStorageEventContext::ScopedStorageEventContext(
DOMStorageMessageFilter* dispatcher_message_filter, const GURL* url) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DCHECK(!storage_event_message_filter);
DCHECK(!storage_event_url_);
storage_event_message_filter = dispatcher_message_filter;
storage_event_url_ = url;
DCHECK(storage_event_message_filter);
DCHECK(storage_event_url_);
}
DOMStorageMessageFilter::
ScopedStorageEventContext::~ScopedStorageEventContext() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DCHECK(storage_event_message_filter);
DCHECK(storage_event_url_);
storage_event_message_filter = NULL;
storage_event_url_ = NULL;
}
DOMStorageMessageFilter::DOMStorageMessageFilter(
int process_id, WebKitContext* webkit_context)
: webkit_context_(webkit_context),
process_id_(process_id) {
}
DOMStorageMessageFilter::~DOMStorageMessageFilter() {
// This is not always true during testing.
if (peer_handle())
Context()->UnregisterMessageFilter(this);
}
void DOMStorageMessageFilter::OnChannelConnected(int32 peer_pid) {
BrowserMessageFilter::OnChannelConnected(peer_pid);
Context()->RegisterMessageFilter(this);
}
/* static */
void DOMStorageMessageFilter::DispatchStorageEvent(const NullableString16& key,
const NullableString16& old_value, const NullableString16& new_value,
const string16& origin, const GURL& url, bool is_local_storage) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DCHECK(is_local_storage); // Only LocalStorage is implemented right now.
DCHECK(storage_event_message_filter);
DOMStorageMsg_Event_Params params;
params.key = key;
params.old_value = old_value;
params.new_value = new_value;
params.origin = origin;
params.url = *storage_event_url_; // The url passed in is junk.
params.storage_type = is_local_storage ? DOM_STORAGE_LOCAL
: DOM_STORAGE_SESSION;
// The storage_event_message_filter is the DOMStorageMessageFilter that is up
// in the current call stack since it caused the storage event to fire.
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
NewRunnableMethod(storage_event_message_filter,
&DOMStorageMessageFilter::OnStorageEvent, params));
}
bool DOMStorageMessageFilter::OnMessageReceived(const IPC::Message& message,
bool* message_was_ok) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_EX(DOMStorageMessageFilter, message, *message_was_ok)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_StorageAreaId, OnStorageAreaId)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_Length, OnLength)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_Key, OnKey)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_GetItem, OnGetItem)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_SetItem, OnSetItem)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_RemoveItem, OnRemoveItem)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_Clear, OnClear)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void DOMStorageMessageFilter::OnDestruct() const {
BrowserThread::DeleteOnIOThread::Destruct(this);
}
void DOMStorageMessageFilter::OverrideThreadForMessage(
const IPC::Message& message,
BrowserThread::ID* thread) {
if (IPC_MESSAGE_CLASS(message) == DOMStorageMsgStart)
*thread = BrowserThread::WEBKIT;
}
void DOMStorageMessageFilter::OnStorageAreaId(int64 namespace_id,
const string16& origin,
int64* storage_area_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DOMStorageNamespace* storage_namespace =
Context()->GetStorageNamespace(namespace_id, true);
if (!storage_namespace) {
*storage_area_id = DOMStorageContext::kInvalidStorageId;
return;
}
DOMStorageArea* storage_area = storage_namespace->GetStorageArea(origin);
*storage_area_id = storage_area->id();
}
void DOMStorageMessageFilter::OnLength(int64 storage_area_id,
unsigned* length) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);
if (!storage_area) {
*length = 0;
} else {
*length = storage_area->Length();
}
}
void DOMStorageMessageFilter::OnKey(int64 storage_area_id, unsigned index,
NullableString16* key) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);
if (!storage_area) {
*key = NullableString16(true);
} else {
*key = storage_area->Key(index);
}
}
void DOMStorageMessageFilter::OnGetItem(int64 storage_area_id,
const string16& key,
NullableString16* value) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);
if (!storage_area) {
*value = NullableString16(true);
} else {
*value = storage_area->GetItem(key);
}
}
void DOMStorageMessageFilter::OnSetItem(
int64 storage_area_id, const string16& key,
const string16& value, const GURL& url,
WebKit::WebStorageArea::Result* result, NullableString16* old_value) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);
if (!storage_area) {
*old_value = NullableString16(true);
*result = WebKit::WebStorageArea::ResultOK;
return;
}
ScopedStorageEventContext scope(this, &url);
*old_value = storage_area->SetItem(key, value, result);
}
void DOMStorageMessageFilter::OnRemoveItem(
int64 storage_area_id, const string16& key, const GURL& url,
NullableString16* old_value) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);
if (!storage_area) {
*old_value = NullableString16(true);
return;
}
ScopedStorageEventContext scope(this, &url);
*old_value = storage_area->RemoveItem(key);
}
void DOMStorageMessageFilter::OnClear(int64 storage_area_id, const GURL& url,
bool* something_cleared) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);
if (!storage_area) {
*something_cleared = false;
return;
}
ScopedStorageEventContext scope(this, &url);
*something_cleared = storage_area->Clear();
}
void DOMStorageMessageFilter::OnStorageEvent(
const DOMStorageMsg_Event_Params& params) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const DOMStorageContext::MessageFilterSet* set =
Context()->GetMessageFilterSet();
DOMStorageContext::MessageFilterSet::const_iterator cur = set->begin();
while (cur != set->end()) {
// The renderer that generates the event handles it itself.
if (*cur != this)
(*cur)->Send(new DOMStorageMsg_Event(params));
++cur;
}
}
<commit_msg>A stab at fixing a frequent crasher in the DOMStorage stuff.<commit_after>// Copyright (c) 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 "content/browser/in_process_webkit/dom_storage_message_filter.h"
#include "base/nullable_string16.h"
#include "content/browser/browser_thread.h"
#include "content/browser/in_process_webkit/dom_storage_area.h"
#include "content/browser/in_process_webkit/dom_storage_context.h"
#include "content/browser/in_process_webkit/dom_storage_namespace.h"
#include "content/common/dom_storage_messages.h"
#include "googleurl/src/gurl.h"
using WebKit::WebStorageArea;
DOMStorageMessageFilter* DOMStorageMessageFilter::storage_event_message_filter =
NULL;
const GURL* DOMStorageMessageFilter::storage_event_url_ = NULL;
DOMStorageMessageFilter::
ScopedStorageEventContext::ScopedStorageEventContext(
DOMStorageMessageFilter* dispatcher_message_filter, const GURL* url) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DCHECK(!storage_event_message_filter);
DCHECK(!storage_event_url_);
storage_event_message_filter = dispatcher_message_filter;
storage_event_url_ = url;
DCHECK(storage_event_message_filter);
DCHECK(storage_event_url_);
}
DOMStorageMessageFilter::
ScopedStorageEventContext::~ScopedStorageEventContext() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DCHECK(storage_event_message_filter);
DCHECK(storage_event_url_);
storage_event_message_filter = NULL;
storage_event_url_ = NULL;
}
DOMStorageMessageFilter::DOMStorageMessageFilter(
int process_id, WebKitContext* webkit_context)
: webkit_context_(webkit_context),
process_id_(process_id) {
}
DOMStorageMessageFilter::~DOMStorageMessageFilter() {
if (peer_handle())
Context()->UnregisterMessageFilter(this);
}
void DOMStorageMessageFilter::OnChannelConnected(int32 peer_pid) {
BrowserMessageFilter::OnChannelConnected(peer_pid);
if (peer_handle())
Context()->RegisterMessageFilter(this);
}
/* static */
void DOMStorageMessageFilter::DispatchStorageEvent(const NullableString16& key,
const NullableString16& old_value, const NullableString16& new_value,
const string16& origin, const GURL& url, bool is_local_storage) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DCHECK(is_local_storage); // Only LocalStorage is implemented right now.
DCHECK(storage_event_message_filter);
DOMStorageMsg_Event_Params params;
params.key = key;
params.old_value = old_value;
params.new_value = new_value;
params.origin = origin;
params.url = *storage_event_url_; // The url passed in is junk.
params.storage_type = is_local_storage ? DOM_STORAGE_LOCAL
: DOM_STORAGE_SESSION;
// The storage_event_message_filter is the DOMStorageMessageFilter that is up
// in the current call stack since it caused the storage event to fire.
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
NewRunnableMethod(storage_event_message_filter,
&DOMStorageMessageFilter::OnStorageEvent, params));
}
bool DOMStorageMessageFilter::OnMessageReceived(const IPC::Message& message,
bool* message_was_ok) {
bool handled = true;
IPC_BEGIN_MESSAGE_MAP_EX(DOMStorageMessageFilter, message, *message_was_ok)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_StorageAreaId, OnStorageAreaId)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_Length, OnLength)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_Key, OnKey)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_GetItem, OnGetItem)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_SetItem, OnSetItem)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_RemoveItem, OnRemoveItem)
IPC_MESSAGE_HANDLER(DOMStorageHostMsg_Clear, OnClear)
IPC_MESSAGE_UNHANDLED(handled = false)
IPC_END_MESSAGE_MAP()
return handled;
}
void DOMStorageMessageFilter::OnDestruct() const {
BrowserThread::DeleteOnIOThread::Destruct(this);
}
void DOMStorageMessageFilter::OverrideThreadForMessage(
const IPC::Message& message,
BrowserThread::ID* thread) {
if (IPC_MESSAGE_CLASS(message) == DOMStorageMsgStart)
*thread = BrowserThread::WEBKIT;
}
void DOMStorageMessageFilter::OnStorageAreaId(int64 namespace_id,
const string16& origin,
int64* storage_area_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DOMStorageNamespace* storage_namespace =
Context()->GetStorageNamespace(namespace_id, true);
if (!storage_namespace) {
*storage_area_id = DOMStorageContext::kInvalidStorageId;
return;
}
DOMStorageArea* storage_area = storage_namespace->GetStorageArea(origin);
*storage_area_id = storage_area->id();
}
void DOMStorageMessageFilter::OnLength(int64 storage_area_id,
unsigned* length) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);
if (!storage_area) {
*length = 0;
} else {
*length = storage_area->Length();
}
}
void DOMStorageMessageFilter::OnKey(int64 storage_area_id, unsigned index,
NullableString16* key) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);
if (!storage_area) {
*key = NullableString16(true);
} else {
*key = storage_area->Key(index);
}
}
void DOMStorageMessageFilter::OnGetItem(int64 storage_area_id,
const string16& key,
NullableString16* value) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);
if (!storage_area) {
*value = NullableString16(true);
} else {
*value = storage_area->GetItem(key);
}
}
void DOMStorageMessageFilter::OnSetItem(
int64 storage_area_id, const string16& key,
const string16& value, const GURL& url,
WebKit::WebStorageArea::Result* result, NullableString16* old_value) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);
if (!storage_area) {
*old_value = NullableString16(true);
*result = WebKit::WebStorageArea::ResultOK;
return;
}
ScopedStorageEventContext scope(this, &url);
*old_value = storage_area->SetItem(key, value, result);
}
void DOMStorageMessageFilter::OnRemoveItem(
int64 storage_area_id, const string16& key, const GURL& url,
NullableString16* old_value) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);
if (!storage_area) {
*old_value = NullableString16(true);
return;
}
ScopedStorageEventContext scope(this, &url);
*old_value = storage_area->RemoveItem(key);
}
void DOMStorageMessageFilter::OnClear(int64 storage_area_id, const GURL& url,
bool* something_cleared) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::WEBKIT));
DOMStorageArea* storage_area = Context()->GetStorageArea(storage_area_id);
if (!storage_area) {
*something_cleared = false;
return;
}
ScopedStorageEventContext scope(this, &url);
*something_cleared = storage_area->Clear();
}
void DOMStorageMessageFilter::OnStorageEvent(
const DOMStorageMsg_Event_Params& params) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
const DOMStorageContext::MessageFilterSet* set =
Context()->GetMessageFilterSet();
DOMStorageContext::MessageFilterSet::const_iterator cur = set->begin();
while (cur != set->end()) {
// The renderer that generates the event handles it itself.
if (*cur != this)
(*cur)->Send(new DOMStorageMsg_Event(params));
++cur;
}
}
<|endoftext|>
|
<commit_before>/*
FUSE: Filesystem in Userspace
Copyright (C) 2001-2007 Miklos Szeredi <miklos@szeredi.hu>
This program can be distributed under the terms of the GNU GPL.
See the file COPYING.
gcc -Wall hello.c `pkg-config fuse --cflags --libs` -o hello
*/
#define FUSE_USE_VERSION 30
#include <fuse.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <iostream>
#include <fstream>
#include <loss/fs/virtual_fileystem.h>
#include <loss/fs/ram_filesystem.h>
#include <loss/fs/ram_filesystem_drive.h>
static const char *hello_str = "Hello World!\n";
static const char *hello_path = "/hello";
static loss::VirtualFileSystem *vfs = nullptr;
static loss::RamFileSystem *ramfs = nullptr;
static int hello_getattr(const char *path, struct stat *stbuf)
{
int res = 0;
memset(stbuf, 0, sizeof(struct stat));
// Not really used at the moment
stbuf->st_nlink = 1;
/*
if (strcmp(path, "/") == 0) {
stbuf->st_mode = S_IFDIR | 0755;
stbuf->st_nlink = 2;
} else if (strcmp(path, hello_path) == 0) {
stbuf->st_mode = S_IFREG | 0444;
stbuf->st_nlink = 1;
stbuf->st_size = strlen(hello_str);
} else
res = -ENOENT;
*/
loss::MetadataDef metadata;
auto read_result = vfs->entry_metadata(path, metadata);
if (read_result != loss::SUCCESS)
{
res = -ENOENT;
}
else
{
if (metadata.type() == loss::FOLDER_ENTRY)
{
stbuf->st_mode = S_IFDIR | 0755;
}
else if (metadata.type() == loss::FILE_ENTRY)
{
stbuf->st_mode = S_IFREG | 0444;
uint32_t size;
vfs->entry_size(path, size);
stbuf->st_size = size;
}
}
return res;
}
static int hello_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
off_t offset, struct fuse_file_info *fi)
{
(void) offset;
(void) fi;
filler(buf, ".", NULL, 0);
filler(buf, "..", NULL, 0);
loss::FolderEntry folder;
auto read_result = vfs->read_folder(path, folder);
if (read_result == loss::SUCCESS)
{
for (auto &iter : folder)
{
filler(buf, iter.first.c_str(), NULL, 0);
}
}
else
{
return -ENOENT;
}
return 0;
}
static int hello_open(const char *path, struct fuse_file_info *fi)
{
loss::MetadataDef metadata;
if (vfs->entry_metadata(path, metadata) != loss::SUCCESS)
{
return -ENOENT;
}
if ((fi->flags & 3) != O_RDONLY)
{
return -EACCES;
}
return 0;
}
static int hello_read(const char *path, char *buf, size_t size, off_t offset,
struct fuse_file_info *fi)
{
auto read_result = vfs->read(path, offset, size, (uint8_t*)buf);
if (read_result.status() != loss::SUCCESS)
{
return -ENOENT;
}
return read_result.bytes();
/*
size_t len;
(void) fi;
if(strcmp(path, hello_path) != 0)
return -ENOENT;
len = strlen(hello_str);
if (offset < len) {
if (offset + size > len)
size = len - offset;
memcpy(buf, hello_str + offset, size);
} else
size = 0;
return size;
*/
}
static struct fuse_operations hello_oper = {
.getattr = hello_getattr,
.readdir = hello_readdir,
.open = hello_open,
.read = hello_read,
};
int main(int argc, char *argv[])
{
int i;
for(i = 1; i < argc && (argv[i][0] == '-'); i++)
{
if(i == argc)
{
return (-1);
}
}
vfs = new loss::VirtualFileSystem();
ramfs = new loss::RamFileSystem();
vfs->root_filesystem(ramfs);
const char *file_to_open = argv[i];
{
std::ifstream input(file_to_open);
loss::RamFileSystemDeserialise deserialise(input, ramfs);
deserialise.load();
}
for(; i < argc; i++)
{
argv[i] = argv[i+1];
}
argc--;
auto result = fuse_main(argc, argv, &hello_oper, NULL);
delete vfs;
return result;
}
<commit_msg>- Added debug to lossfs, trying to get writing working.<commit_after>/*
FUSE: Filesystem in Userspace
Copyright (C) 2001-2007 Miklos Szeredi <miklos@szeredi.hu>
This program can be distributed under the terms of the GNU GPL.
See the file COPYING.
gcc -Wall hello.c `pkg-config fuse --cflags --libs` -o hello
*/
#define FUSE_USE_VERSION 30
#include <fuse.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <iostream>
#include <fstream>
#include <loss/fs/virtual_fileystem.h>
#include <loss/fs/ram_filesystem.h>
#include <loss/fs/ram_filesystem_drive.h>
static const char *hello_str = "Hello World!\n";
static const char *hello_path = "/hello";
static loss::VirtualFileSystem *vfs = nullptr;
static loss::RamFileSystem *ramfs = nullptr;
static int hello_getattr(const char *path, struct stat *stbuf)
{
std::cout << "Getattr: " << path << "\n";
int res = 0;
memset(stbuf, 0, sizeof(struct stat));
// Not really used at the moment
stbuf->st_nlink = 1;
/*
if (strcmp(path, "/") == 0) {
stbuf->st_mode = S_IFDIR | 0755;
stbuf->st_nlink = 2;
} else if (strcmp(path, hello_path) == 0) {
stbuf->st_mode = S_IFREG | 0444;
stbuf->st_nlink = 1;
stbuf->st_size = strlen(hello_str);
} else
res = -ENOENT;
*/
loss::MetadataDef metadata;
auto read_result = vfs->entry_metadata(path, metadata);
if (read_result != loss::SUCCESS)
{
res = -ENOENT;
}
else
{
if (metadata.type() == loss::FOLDER_ENTRY)
{
stbuf->st_mode = S_IFDIR | 0755;
}
else if (metadata.type() == loss::FILE_ENTRY)
{
stbuf->st_mode = S_IFREG | 0666;
uint32_t size;
vfs->entry_size(path, size);
stbuf->st_size = size;
}
}
return res;
}
static int hello_readdir(const char *path, void *buf, fuse_fill_dir_t filler,
off_t offset, struct fuse_file_info *fi)
{
std::cout << "Readdir: " << path << "\n";
(void) offset;
(void) fi;
filler(buf, ".", NULL, 0);
filler(buf, "..", NULL, 0);
loss::FolderEntry folder;
auto read_result = vfs->read_folder(path, folder);
if (read_result == loss::SUCCESS)
{
for (auto &iter : folder)
{
filler(buf, iter.first.c_str(), NULL, 0);
}
}
else
{
return -ENOENT;
}
return 0;
}
static int hello_open(const char *path, struct fuse_file_info *fi)
{
std::cout << "Open: " << path << "\n";
loss::MetadataDef metadata;
if (vfs->entry_metadata(path, metadata) != loss::SUCCESS)
{
return -ENOENT;
}
return 0;
}
static int hello_read(const char *path, char *buf, size_t size, off_t offset,
struct fuse_file_info *fi)
{
std::cout << "Read: " << path << ": " << size << ": " << offset << "\n";
auto read_result = vfs->read(path, offset, size, (uint8_t*)buf);
if (read_result.status() != loss::SUCCESS)
{
return -ENOENT;
}
return read_result.bytes();
/*
size_t len;
(void) fi;
if(strcmp(path, hello_path) != 0)
return -ENOENT;
len = strlen(hello_str);
if (offset < len) {
if (offset + size > len)
size = len - offset;
memcpy(buf, hello_str + offset, size);
} else
size = 0;
return size;
*/
}
static int hello_write(const char *path, const char *buf, size_t size, off_t off, struct fuse_file_info *fi)
{
std::cout << "Write: " << path << ": " << size << ": " << off << "\n";
auto write_result = vfs->write(path, off, size, (const uint8_t *)buf);
return write_result.bytes();
}
static struct fuse_operations hello_oper = {
.getattr = hello_getattr,
.readdir = hello_readdir,
.open = hello_open,
.read = hello_read,
.write = hello_write,
};
int main(int argc, char *argv[])
{
int i;
for(i = 1; i < argc && (argv[i][0] == '-'); i++)
{
if(i == argc)
{
return (-1);
}
}
vfs = new loss::VirtualFileSystem();
ramfs = new loss::RamFileSystem();
vfs->root_filesystem(ramfs);
const char *file_to_open = argv[i];
{
std::ifstream input(file_to_open);
loss::RamFileSystemDeserialise deserialise(input, ramfs);
deserialise.load();
}
for(; i < argc; i++)
{
argv[i] = argv[i+1];
}
argc--;
auto result = fuse_main(argc, argv, &hello_oper, NULL);
delete vfs;
return result;
}
<|endoftext|>
|
<commit_before>/*
* DynApproxBetweenness.cpp
*
* Created on: 31.07.2014
* Author: ebergamini
*/
#include "DynApproxBetweenness.h"
#include "../auxiliary/Random.h"
#include "../properties/Diameter.h"
#include "../graph/Sampling.h"
#include "../graph/DynDijkstra.h"
#include "../graph/DynBFS.h"
#include "../auxiliary/Log.h"
#include "../auxiliary/NumericTools.h"
namespace NetworKit {
DynApproxBetweenness::DynApproxBetweenness(const Graph& G, double epsilon, double delta, bool storePredecessors) : Centrality(G, true),
storePreds(storePredecessors), epsilon(epsilon), delta(delta) {
}
count DynApproxBetweenness::getNumberOfSamples() {
return r;
}
void DynApproxBetweenness::run() {
if (G.isDirected()) {
throw std::runtime_error("Invalid argument: G must be undirected.");
}
scoreData.clear();
scoreData.resize(G.upperNodeIdBound());
u.clear();
v.clear();
sampledPaths.clear();
double c = 0.5; // universal positive constant - see reference in paper
edgeweight vd = Diameter::estimatedVertexDiameterPedantic(G);
INFO("estimated diameter: ", vd);
r = ceil((c / (epsilon * epsilon)) * (floor(log(vd - 2)) + 1 + log(1 / delta)));
INFO("taking ", r, " path samples");
sssp.clear();
sssp.resize(r);
u.resize(r);
v.resize(r);
sampledPaths.resize(r);
for (count i = 0; i < r; i++) {
DEBUG("sample ", i);
// sample random node pair
u[i] = Sampling::randomNode(G);
do {
v[i] = Sampling::randomNode(G);
} while (v[i] == u[i]);
if (G.isWeighted()) {
sssp[i].reset(new DynDijkstra(G, u[i], storePreds));
} else {
sssp[i].reset(new DynBFS(G, u[i], storePreds));
}
DEBUG("running shortest path algorithm for node ", u[i]);
sssp[i]->setTargetNode(v[i]);
sssp[i]->run();
if (sssp[i]->distances[v[i]] > 0) { // at least one path between {u, v} exists
DEBUG("updating estimate for path ", u[i], " <-> ", v[i]);
// random path sampling and estimation update
sampledPaths[i].clear();
node t = v[i];
while (t != u[i]) {
// sample z in P_u(t) with probability sigma_uz / sigma_us
std::vector<std::pair<node, double> > choices;
if (storePreds) {
for (node z : sssp[i]->previous[t]) {
// workaround for integer overflow in large graphs
bigfloat tmp = sssp[i]->numberOfPaths(z) / sssp[i]->numberOfPaths(t);
double weight;
tmp.ToDouble(weight);
choices.emplace_back(z, weight); // sigma_uz / sigma_us
}
}
else {
G.forInEdgesOf(t, [&](node t, node z, edgeweight w){
if (Aux::NumericTools::logically_equal(sssp[i]->distances[t], sssp[i]->distances[z] + w)) {
// workaround for integer overflow in large graphs
bigfloat tmp = sssp[i]->numberOfPaths(z) / sssp[i]->numberOfPaths(t);
double weight;
tmp.ToDouble(weight);
choices.emplace_back(z, weight);
}
});
}
INFO("Node considered: ", t);
INFO("Source considered: ", u[i]);
assert (choices.size() > 0);
node z = Aux::Random::weightedChoice(choices);
assert (z <= G.upperNodeIdBound());
if (z != u[i]) {
scoreData[z] += 1 / (double) r;
sampledPaths[i].push_back(z);
}
t = z;
}
}
}
}
void DynApproxBetweenness::update(const std::vector<GraphEvent>& batch) {
INFO ("Updating");
for (node i = 0; i < r; i++) {
sssp[i]->update(batch);
if (sssp[i]->modified()) {
// subtract contributions to nodes in the old sampled path
for (node z: sampledPaths[i]) {
scoreData[z] -= 1 / (double) r;
}
// sample a new shortest path
sampledPaths[i].clear();
node t = v[i];
while (t != u[i]) {
// sample z in P_u(t) with probability sigma_uz / sigma_us
std::vector<std::pair<node, double> > choices;
if (storePreds) {
for (node z : sssp[i]->previous[t]) {
// workaround for integer overflow in large graphs
bigfloat tmp = sssp[i]->numberOfPaths(z) / sssp[i]->numberOfPaths(t);
double weight;
tmp.ToDouble(weight);
choices.emplace_back(z, weight);
}
}
else {
G.forEdgesOf(t, [&](node t, node z, edgeweight w){
if (Aux::NumericTools::logically_equal(sssp[i]->distances[t], sssp[i]->distances[z] + w)) {
// workaround for integer overflow in large graphs
bigfloat tmp = sssp[i]->numberOfPaths(z) / sssp[i]->numberOfPaths(t);
double weight;
tmp.ToDouble(weight);
choices.emplace_back(z, weight);
}
});
}
assert (choices.size() > 0); // this should fail only if the graph is not connected
if (choices.size() == 0) {
INFO ("node: ", t);
INFO ("source: ", u[i]);
INFO ("distance: ", sssp[i]->distances[t]);
}
node z = Aux::Random::weightedChoice(choices);
assert (z <= G.upperNodeIdBound());
if (z != u[i]) {
scoreData[z] += 1 / (double) r;
sampledPaths[i].push_back(z);
}
t = z;
}
}
}
}
} /* namespace NetworKit */
<commit_msg>replaced forInEdges with forEdges in dyn approx betweenness<commit_after>/*
* DynApproxBetweenness.cpp
*
* Created on: 31.07.2014
* Author: ebergamini
*/
#include "DynApproxBetweenness.h"
#include "../auxiliary/Random.h"
#include "../properties/Diameter.h"
#include "../graph/Sampling.h"
#include "../graph/DynDijkstra.h"
#include "../graph/DynBFS.h"
#include "../auxiliary/Log.h"
#include "../auxiliary/NumericTools.h"
namespace NetworKit {
DynApproxBetweenness::DynApproxBetweenness(const Graph& G, double epsilon, double delta, bool storePredecessors) : Centrality(G, true),
storePreds(storePredecessors), epsilon(epsilon), delta(delta) {
}
count DynApproxBetweenness::getNumberOfSamples() {
return r;
}
void DynApproxBetweenness::run() {
if (G.isDirected()) {
throw std::runtime_error("Invalid argument: G must be undirected.");
}
scoreData.clear();
scoreData.resize(G.upperNodeIdBound());
u.clear();
v.clear();
sampledPaths.clear();
double c = 0.5; // universal positive constant - see reference in paper
edgeweight vd = Diameter::estimatedVertexDiameterPedantic(G);
INFO("estimated diameter: ", vd);
r = ceil((c / (epsilon * epsilon)) * (floor(log(vd - 2)) + 1 + log(1 / delta)));
INFO("taking ", r, " path samples");
sssp.clear();
sssp.resize(r);
u.resize(r);
v.resize(r);
sampledPaths.resize(r);
for (count i = 0; i < r; i++) {
DEBUG("sample ", i);
// sample random node pair
u[i] = Sampling::randomNode(G);
do {
v[i] = Sampling::randomNode(G);
} while (v[i] == u[i]);
if (G.isWeighted()) {
sssp[i].reset(new DynDijkstra(G, u[i], storePreds));
} else {
sssp[i].reset(new DynBFS(G, u[i], storePreds));
}
DEBUG("running shortest path algorithm for node ", u[i]);
sssp[i]->setTargetNode(v[i]);
sssp[i]->run();
if (sssp[i]->distances[v[i]] > 0) { // at least one path between {u, v} exists
DEBUG("updating estimate for path ", u[i], " <-> ", v[i]);
// random path sampling and estimation update
sampledPaths[i].clear();
node t = v[i];
while (t != u[i]) {
// sample z in P_u(t) with probability sigma_uz / sigma_us
std::vector<std::pair<node, double> > choices;
if (storePreds) {
for (node z : sssp[i]->previous[t]) {
// workaround for integer overflow in large graphs
bigfloat tmp = sssp[i]->numberOfPaths(z) / sssp[i]->numberOfPaths(t);
double weight;
tmp.ToDouble(weight);
choices.emplace_back(z, weight); // sigma_uz / sigma_us
}
}
else {
G.forEdgesOf(t, [&](node t, node z, edgeweight w){
if (Aux::NumericTools::logically_equal(sssp[i]->distances[t], sssp[i]->distances[z] + w)) {
// workaround for integer overflow in large graphs
bigfloat tmp = sssp[i]->numberOfPaths(z) / sssp[i]->numberOfPaths(t);
double weight;
tmp.ToDouble(weight);
choices.emplace_back(z, weight);
}
});
}
INFO("Node considered: ", t);
INFO("Source considered: ", u[i]);
assert (choices.size() > 0);
node z = Aux::Random::weightedChoice(choices);
assert (z <= G.upperNodeIdBound());
if (z != u[i]) {
scoreData[z] += 1 / (double) r;
sampledPaths[i].push_back(z);
}
t = z;
}
}
}
}
void DynApproxBetweenness::update(const std::vector<GraphEvent>& batch) {
INFO ("Updating");
for (node i = 0; i < r; i++) {
sssp[i]->update(batch);
if (sssp[i]->modified()) {
// subtract contributions to nodes in the old sampled path
for (node z: sampledPaths[i]) {
scoreData[z] -= 1 / (double) r;
}
// sample a new shortest path
sampledPaths[i].clear();
node t = v[i];
while (t != u[i]) {
// sample z in P_u(t) with probability sigma_uz / sigma_us
std::vector<std::pair<node, double> > choices;
if (storePreds) {
for (node z : sssp[i]->previous[t]) {
// workaround for integer overflow in large graphs
bigfloat tmp = sssp[i]->numberOfPaths(z) / sssp[i]->numberOfPaths(t);
double weight;
tmp.ToDouble(weight);
choices.emplace_back(z, weight);
}
}
else {
G.forEdgesOf(t, [&](node t, node z, edgeweight w){
if (Aux::NumericTools::logically_equal(sssp[i]->distances[t], sssp[i]->distances[z] + w)) {
// workaround for integer overflow in large graphs
bigfloat tmp = sssp[i]->numberOfPaths(z) / sssp[i]->numberOfPaths(t);
double weight;
tmp.ToDouble(weight);
choices.emplace_back(z, weight);
}
});
}
assert (choices.size() > 0); // this should fail only if the graph is not connected
if (choices.size() == 0) {
INFO ("node: ", t);
INFO ("source: ", u[i]);
INFO ("distance: ", sssp[i]->distances[t]);
}
node z = Aux::Random::weightedChoice(choices);
assert (z <= G.upperNodeIdBound());
if (z != u[i]) {
scoreData[z] += 1 / (double) r;
sampledPaths[i].push_back(z);
}
t = z;
}
}
}
}
} /* namespace NetworKit */
<|endoftext|>
|
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
* 2019 Nina Engelhardt <nak@symbioticeda.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct ScratchpadPass : public Pass {
ScratchpadPass() : Pass("scratchpad", "get/set values in the scratchpad") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" scratchpad [options]\n");
log("\n");
log("This pass allows to read and modify values from the scratchpad of the current\n");
log("design. Options:\n");
log(" -get <identifier>\n");
log(" print the value saved in the scratchpad under the given identifier\n");
log(" -set <identifier> <value>\n");
log(" save the given value in the scratchpad under the given identifier\n");
log(" -unset <identifier>\n");
log(" remove the entry for the given identifier from the scratchpad\n");
log(" -copy <identifier_from> <identifier_to>\n");
log(" copy the value of the first identifier to the second identifier\n");
log("The identifier may not contain whitespace. By convention, it is usually prefixed\n");
log("by the name of the pass that uses it, e.g. 'opt.did_something'. If the value\n");
log("contains whitespace, it must be enclosed in double quotes.\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-get" && argidx+1 < args.size()) {
string identifier = args[++argidx];
if (design->scratchpad.count(identifier)){
log("%s\n", design->scratchpad_get_string(identifier).c_str());
} else {
log("\"%s\" not set\n", identifier.c_str());
}
continue;
}
if (args[argidx] == "-set" && argidx+2 < args.size()) {
string identifier = args[++argidx];
string value = args[++argidx];
if (value.front() == '\"' && value.back() == '\"') value = value.substr(1, value.size() - 2);
design->scratchpad_set_string(identifier, value);
continue;
}
if (args[argidx] == "-unset" && argidx+1 < args.size()) {
string identifier = args[++argidx];
design->scratchpad_unset(identifier);
continue;
}
if (args[argidx] == "-copy" && argidx+2 < args.size()) {
string identifier_from = args[++argidx];
string identifier_to = args[++argidx];
if (design->scratchpad.count(identifier_from) == 0) log_error("\"%s\" not set\n", identifier_from.c_str());
string value = design->scratchpad_get_string(identifier_from);
design->scratchpad_set_string(identifier_to, value);
continue;
}
log("Unrecognized argument: %s\n", args[argidx].c_str());
break;
}
}
} ScratchpadPass;
PRIVATE_NAMESPACE_END
<commit_msg>add periods and newlines to help message<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
* 2019 Nina Engelhardt <nak@symbioticeda.com>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct ScratchpadPass : public Pass {
ScratchpadPass() : Pass("scratchpad", "get/set values in the scratchpad") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" scratchpad [options]\n");
log("\n");
log("This pass allows to read and modify values from the scratchpad of the current\n");
log("design. Options:\n\n");
log(" -get <identifier>\n");
log(" print the value saved in the scratchpad under the given identifier.\n\n");
log(" -set <identifier> <value>\n");
log(" save the given value in the scratchpad under the given identifier.\n\n");
log(" -unset <identifier>\n");
log(" remove the entry for the given identifier from the scratchpad.\n\n");
log(" -copy <identifier_from> <identifier_to>\n");
log(" copy the value of the first identifier to the second identifier.\n\n");
log("The identifier may not contain whitespace. By convention, it is usually prefixed\n");
log("by the name of the pass that uses it, e.g. 'opt.did_something'. If the value\n");
log("contains whitespace, it must be enclosed in double quotes.\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-get" && argidx+1 < args.size()) {
string identifier = args[++argidx];
if (design->scratchpad.count(identifier)){
log("%s\n", design->scratchpad_get_string(identifier).c_str());
} else {
log("\"%s\" not set\n", identifier.c_str());
}
continue;
}
if (args[argidx] == "-set" && argidx+2 < args.size()) {
string identifier = args[++argidx];
string value = args[++argidx];
if (value.front() == '\"' && value.back() == '\"') value = value.substr(1, value.size() - 2);
design->scratchpad_set_string(identifier, value);
continue;
}
if (args[argidx] == "-unset" && argidx+1 < args.size()) {
string identifier = args[++argidx];
design->scratchpad_unset(identifier);
continue;
}
if (args[argidx] == "-copy" && argidx+2 < args.size()) {
string identifier_from = args[++argidx];
string identifier_to = args[++argidx];
if (design->scratchpad.count(identifier_from) == 0) log_error("\"%s\" not set\n", identifier_from.c_str());
string value = design->scratchpad_get_string(identifier_from);
design->scratchpad_set_string(identifier_to, value);
continue;
}
log("Unrecognized argument: %s\n", args[argidx].c_str());
break;
}
}
} ScratchpadPass;
PRIVATE_NAMESPACE_END
<|endoftext|>
|
<commit_before>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2018 whitequark <whitequark@whitequark.org>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct EquivOptPass:public ScriptPass
{
EquivOptPass() : ScriptPass("equiv_opt", "prove equivalence for optimized circuit") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" equiv_opt [options] [command]\n");
log("\n");
log("This command checks circuit equivalence before and after an optimization pass.\n");
log("\n");
log(" -run <from_label>:<to_label>\n");
log(" only run the commands between the labels (see below). an empty\n");
log(" from label is synonymous to the start of the command list, and empty to\n");
log(" label is synonymous to the end of the command list.\n");
log("\n");
log(" -map <filename>\n");
log(" expand the modules in this file before proving equivalence. this is\n");
log(" useful for handling architecture-specific primitives.\n");
log("\n");
log(" -assert\n");
log(" produce an error if the circuits are not equivalent.\n");
log("\n");
log(" -multiclock\n");
log(" run clk2fflogic before equivalence checking.\n");
log("\n");
log(" -undef\n");
log(" enable modelling of undef states during equiv_induct.\n");
log("\n");
log("The following commands are executed by this verification command:\n");
help_script();
log("\n");
}
std::string command, techmap_opts;
bool assert, undef, multiclock;
void clear_flags() YS_OVERRIDE
{
command = "";
techmap_opts = "";
assert = false;
undef = false;
multiclock = false;
}
void execute(std::vector < std::string > args, RTLIL::Design * design) YS_OVERRIDE
{
string run_from, run_to;
clear_flags();
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-run" && argidx + 1 < args.size()) {
size_t pos = args[argidx + 1].find(':');
if (pos == std::string::npos)
break;
run_from = args[++argidx].substr(0, pos);
run_to = args[argidx].substr(pos + 1);
continue;
}
if (args[argidx] == "-map" && argidx + 1 < args.size()) {
techmap_opts += " -map " + args[++argidx];
continue;
}
if (args[argidx] == "-assert") {
assert = true;
continue;
}
if (args[argidx] == "-undef") {
undef = true;
continue;
}
if (args[argidx] == "-multiclock") {
multiclock = true;
continue;
}
break;
}
for (; argidx < args.size(); argidx++) {
if (command.empty()) {
if (args[argidx].compare(0, 1, "-") == 0)
cmd_error(args, argidx, "Unknown option.");
} else {
command += " ";
}
command += args[argidx];
}
if (command.empty())
log_cmd_error("No optimization pass specified!\n");
if (!design->full_selection())
log_cmd_error("This command only operates on fully selected designs!\n");
log_header(design, "Executing EQUIV_OPT pass.\n");
log_push();
run_script(design, run_from, run_to);
log_pop();
}
void script() YS_OVERRIDE
{
if (check_label("run_pass")) {
run("hierarchy -auto-top");
run("design -save preopt");
if (help_mode)
run("[command]");
else
run(command);
run("design -stash postopt");
}
if (check_label("prepare")) {
run("design -copy-from preopt -as gold A:top");
run("design -copy-from postopt -as gate A:top");
}
if ((!techmap_opts.empty() || help_mode) && check_label("techmap", "(only with -map)")) {
string opts;
if (help_mode)
opts = " -map <filename> ...";
else
opts = techmap_opts;
run("techmap -wb -D EQUIV -autoproc" + opts);
}
if (check_label("prove")) {
if (multiclock || help_mode)
run("clk2fflogic", "(only with -multiclock)");
run("equiv_make gold gate equiv");
if (help_mode)
run("equiv_induct [-undef] equiv");
else if (undef)
run("equiv_induct -undef equiv");
else
run("equiv_induct equiv");
if (help_mode)
run("equiv_status [-assert] equiv");
else if (assert)
run("equiv_status -assert equiv");
else
run("equiv_status equiv");
}
if (check_label("restore")) {
run("design -load preopt");
}
}
} EquivOptPass;
PRIVATE_NAMESPACE_END
<commit_msg>Add new -async2sync option<commit_after>/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2018 whitequark <whitequark@whitequark.org>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct EquivOptPass:public ScriptPass
{
EquivOptPass() : ScriptPass("equiv_opt", "prove equivalence for optimized circuit") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" equiv_opt [options] [command]\n");
log("\n");
log("This command checks circuit equivalence before and after an optimization pass.\n");
log("\n");
log(" -run <from_label>:<to_label>\n");
log(" only run the commands between the labels (see below). an empty\n");
log(" from label is synonymous to the start of the command list, and empty to\n");
log(" label is synonymous to the end of the command list.\n");
log("\n");
log(" -map <filename>\n");
log(" expand the modules in this file before proving equivalence. this is\n");
log(" useful for handling architecture-specific primitives.\n");
log("\n");
log(" -assert\n");
log(" produce an error if the circuits are not equivalent.\n");
log("\n");
log(" -multiclock\n");
log(" run clk2fflogic before equivalence checking.\n");
log("\n");
log(" -undef\n");
log(" enable modelling of undef states during equiv_induct.\n");
log("\n");
log("The following commands are executed by this verification command:\n");
help_script();
log("\n");
}
std::string command, techmap_opts;
bool assert, undef, multiclock, async2sync;
void clear_flags() YS_OVERRIDE
{
command = "";
techmap_opts = "";
assert = false;
undef = false;
multiclock = false;
async2sync = false;
}
void execute(std::vector < std::string > args, RTLIL::Design * design) YS_OVERRIDE
{
string run_from, run_to;
clear_flags();
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-run" && argidx + 1 < args.size()) {
size_t pos = args[argidx + 1].find(':');
if (pos == std::string::npos)
break;
run_from = args[++argidx].substr(0, pos);
run_to = args[argidx].substr(pos + 1);
continue;
}
if (args[argidx] == "-map" && argidx + 1 < args.size()) {
techmap_opts += " -map " + args[++argidx];
continue;
}
if (args[argidx] == "-assert") {
assert = true;
continue;
}
if (args[argidx] == "-undef") {
undef = true;
continue;
}
if (args[argidx] == "-multiclock") {
multiclock = true;
continue;
}
if (args[argidx] == "-async2sync") {
async2sync = true;
continue;
}
break;
}
for (; argidx < args.size(); argidx++) {
if (command.empty()) {
if (args[argidx].compare(0, 1, "-") == 0)
cmd_error(args, argidx, "Unknown option.");
} else {
command += " ";
}
command += args[argidx];
}
if (command.empty())
log_cmd_error("No optimization pass specified!\n");
if (!design->full_selection())
log_cmd_error("This command only operates on fully selected designs!\n");
if (async2sync && multiclock)
log_cmd_error("The '-async2sync' and '-multiclock' options are mutually exclusive!\n");
log_header(design, "Executing EQUIV_OPT pass.\n");
log_push();
run_script(design, run_from, run_to);
log_pop();
}
void script() YS_OVERRIDE
{
if (check_label("run_pass")) {
run("hierarchy -auto-top");
run("design -save preopt");
if (help_mode)
run("[command]");
else
run(command);
run("design -stash postopt");
}
if (check_label("prepare")) {
run("design -copy-from preopt -as gold A:top");
run("design -copy-from postopt -as gate A:top");
}
if ((!techmap_opts.empty() || help_mode) && check_label("techmap", "(only with -map)")) {
string opts;
if (help_mode)
opts = " -map <filename> ...";
else
opts = techmap_opts;
run("techmap -wb -D EQUIV -autoproc" + opts);
}
if (check_label("prove")) {
if (multiclock || help_mode)
run("clk2fflogic", "(only with -multiclock)");
if (async2sync || help_mode)
run("async2sync", "(only with -async2sync)");
run("equiv_make gold gate equiv");
if (help_mode)
run("equiv_induct [-undef] equiv");
else if (undef)
run("equiv_induct -undef equiv");
else
run("equiv_induct equiv");
if (help_mode)
run("equiv_status [-assert] equiv");
else if (assert)
run("equiv_status -assert equiv");
else
run("equiv_status equiv");
}
if (check_label("restore")) {
run("design -load preopt");
}
}
} EquivOptPass;
PRIVATE_NAMESPACE_END
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mvdGLImageWidget.h"
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//#include <QKeyEvent>
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
#include "itkImageRegionConstIteratorWithIndex.h"
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdAbstractImageModel.h"
#include "mvdApplication.h"
#include "mvdDatasetModel.h"
namespace mvd
{
/*
TRANSLATOR mvd::GLImageWidget
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*******************************************************************************/
GLImageWidget
::GLImageWidget( AbstractViewManipulator * manipulator,
AbstractModelRenderer * renderer,
QWidget* parent,
const QGLWidget* shareWidget,
Qt::WindowFlags flags ) :
QGLWidget( parent, shareWidget, flags ),
m_ImageViewManipulator( NULL ),
m_ImageModelRenderer( NULL ),
m_ImageModel( NULL )
{
// Set focus policy so that the widget gets the focus if it is clicked
setFocusPolicy(Qt::StrongFocus);
Initialize(manipulator, renderer);
}
/*******************************************************************************/
GLImageWidget
::GLImageWidget( AbstractViewManipulator * manipulator,
AbstractModelRenderer * renderer,
QGLContext* context,
QWidget* parent,
const QGLWidget* shareWidget,
Qt::WindowFlags flags ) :
QGLWidget( context, parent, shareWidget, flags ),
m_ImageViewManipulator( NULL ),
m_ImageModelRenderer( NULL ),
m_ImageModel( NULL )
{
// Set focus policy so that the widget gets the focus if it is clicked
setFocusPolicy(Qt::StrongFocus);
Initialize(manipulator, renderer);
}
/*******************************************************************************/
GLImageWidget
::GLImageWidget( AbstractViewManipulator * manipulator,
AbstractModelRenderer * renderer,
const QGLFormat& format,
QWidget* parent,
const QGLWidget* shareWidget,
Qt::WindowFlags flags ) :
QGLWidget( format, parent, shareWidget, flags ),
m_ImageViewManipulator( NULL ),
m_ImageModelRenderer( NULL ),
m_ImageModel( NULL )
{
// Set focus policy so that the widget gets the focus if it is clicked
setFocusPolicy(Qt::StrongFocus);
Initialize(manipulator, renderer);
}
/*******************************************************************************/
GLImageWidget
::~GLImageWidget()
{
// m_ImageViewManipulator (deleted as a child of a QObjet parent).
// m_ImageModelRenderer (deleted as a child of a QObjet parent).
}
/*******************************************************************************/
void
GLImageWidget
::Initialize( AbstractViewManipulator* manipulator,
AbstractModelRenderer* renderer )
{
assert( manipulator!=NULL );
assert( renderer!=NULL );
m_ImageViewManipulator = manipulator;
m_ImageViewManipulator->setParent(this);
m_ImageModelRenderer = renderer;
m_ImageModelRenderer->setParent(this);
QObject::connect(
this, SIGNAL( movingMouse() ),
m_ImageModelRenderer, SLOT( onMovingEvent() )
);
QObject::connect(
this, SIGNAL( releasingMouse() ),
m_ImageModelRenderer, SLOT(onReleasedMouse())
);
// Connect this model region changed.
QObject::connect(
this,
SIGNAL( ModelImageRegionChanged( const ImageRegionType& , const SpacingType&) ),
// to:
m_ImageViewManipulator,
SLOT( OnModelImageRegionChanged( const ImageRegionType&, const SpacingType& ) )
);
// Connect the renderer origin (of extent) changed to the manipulator
QObject::connect(
m_ImageModelRenderer,
SIGNAL( ViewportOriginChanged( const IndexType& ) ),
// to:
m_ImageViewManipulator,
SLOT( OnViewportOriginChanged( const IndexType&) )
);
}
/*******************************************************************************/
void
GLImageWidget
::initializeGL()
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_FLAT);
}
/*******************************************************************************/
void
GLImageWidget
::resizeGL(int width, int height)
{
// TODO: Replace (GLint) casts with safer casts or no cast (if there is no compile-time warning).
glViewport(0, 0, (GLint)width, (GLint)height);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, (GLint)width, 0, (GLint)height, -1, 1);
}
/*******************************************************************************/
void
GLImageWidget
::paintGL()
{
// Clear back-buffer(s) before rendering sub-components.
glClear( GL_COLOR_BUFFER_BIT );
// Get the region to draw from the ImageViewManipulator navigation
// context.
const ImageRegionType region(
m_ImageViewManipulator->GetViewportImageRegion() );
// Get the zoom
const double isotropicZoom = m_ImageViewManipulator->GetIsotropicZoom();
// Setup rendering context with image-model and redering information.
AbstractModelRenderer::RenderingContext context(
m_ImageModel,
region, isotropicZoom,
width(), height(),
m_ImageViewManipulator->HasZoomChanged()
);
// use the model renderer to paint the requested region of the image.
m_ImageModelRenderer->paintGL( context );
}
/*******************************************************************************/
// Delegate the event to the ImageViewManipulator
void
GLImageWidget
::mousePressEvent( QMouseEvent* event )
{
QCursor dragCursor;
dragCursor.setShape(Qt::ClosedHandCursor) ;
this->setCursor(dragCursor);
//
m_ImageViewManipulator->mousePressEvent(event);
this->update();
}
/*******************************************************************************/
void
GLImageWidget
::mouseMoveEvent( QMouseEvent* event )
{
// if a button is clicked == drag
if ( event->buttons() & Qt::LeftButton ||
event->buttons() & Qt::RightButton ||
event->buttons() & Qt::MidButton ||
event->buttons() & Qt::XButton1 ||
event->buttons() & Qt::XButton2 )
{
// emit a signal movingMouse to update the renderer status
emit movingMouse();
// drag detected
m_ImageViewManipulator->mouseMoveEvent(event);
// repaint the buffer
this->update();
// emited to update to force the ql widget (if any) to update
emit CentralWidgetUpdated();
}
else // just mouse cursor moving
{
// no mouse button is grabbed here -> no drag detected
m_ImageViewManipulator->PropagatePointUnderCursorCoordinates(event->pos());
}
}
/*******************************************************************************/
void
GLImageWidget
::mouseReleaseEvent( QMouseEvent* event )
{
QCursor stdCursor;
stdCursor.setShape(Qt::ArrowCursor) ;
this->setCursor(stdCursor);
// emit a signal releasingMouse to update the renderer status
emit releasingMouse();
// call paintGL
this->update();
// emited to update to force the ql widget (if any) to update
emit CentralWidgetUpdated();
}
/*******************************************************************************/
void
GLImageWidget
::wheelEvent( QWheelEvent* event )
{
// emit a signal releasingMouse to update the renderer status
emit releasingMouse();
m_ImageViewManipulator->wheelEvent(event);
// repaint the buffer
this->update();
// emited to update to force the ql widget (if any) to update
emit CentralWidgetUpdated();
}
/*******************************************************************************/
void
GLImageWidget
::resizeEvent( QResizeEvent* event )
{
// First, call superclass implementation
QGLWidget::resizeEvent(event);
m_ImageViewManipulator->resizeEvent(event);
// emit a signal releasingMouse to update the renderer status
emit releasingMouse();
// emited to update to force the ql widget (if any) to update
emit CentralWidgetUpdated();
}
/*******************************************************************************/
void
GLImageWidget
::keyPressEvent( QKeyEvent* event )
{
m_ImageViewManipulator->keyPressEvent(event);
this->update();
// emited to update to force the ql widget (if any) to update
emit CentralWidgetUpdated();
}
/*******************************************************************************/
/* SLOTS */
/******************************************************************************/
void
GLImageWidget
::OnSpacingChanged(const SpacingType& spacing)
{
m_ImageViewManipulator->SetSpacing(spacing);
}
/*******************************************************************************/
}
<commit_msg>ENH: enable receiving mouse move events even if no button is pressed<commit_after>/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mvdGLImageWidget.h"
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//#include <QKeyEvent>
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
#include "itkImageRegionConstIteratorWithIndex.h"
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
#include "mvdAbstractImageModel.h"
#include "mvdApplication.h"
#include "mvdDatasetModel.h"
namespace mvd
{
/*
TRANSLATOR mvd::GLImageWidget
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*******************************************************************************/
GLImageWidget
::GLImageWidget( AbstractViewManipulator * manipulator,
AbstractModelRenderer * renderer,
QWidget* parent,
const QGLWidget* shareWidget,
Qt::WindowFlags flags ) :
QGLWidget( parent, shareWidget, flags ),
m_ImageViewManipulator( NULL ),
m_ImageModelRenderer( NULL ),
m_ImageModel( NULL )
{
// Set focus policy so that the widget gets the focus if it is clicked
setMouseTracking(true);
setFocusPolicy(Qt::StrongFocus);
Initialize(manipulator, renderer);
}
/*******************************************************************************/
GLImageWidget
::GLImageWidget( AbstractViewManipulator * manipulator,
AbstractModelRenderer * renderer,
QGLContext* context,
QWidget* parent,
const QGLWidget* shareWidget,
Qt::WindowFlags flags ) :
QGLWidget( context, parent, shareWidget, flags ),
m_ImageViewManipulator( NULL ),
m_ImageModelRenderer( NULL ),
m_ImageModel( NULL )
{
// Set focus policy so that the widget gets the focus if it is clicked
setMouseTracking(true);
setFocusPolicy(Qt::StrongFocus);
Initialize(manipulator, renderer);
}
/*******************************************************************************/
GLImageWidget
::GLImageWidget( AbstractViewManipulator * manipulator,
AbstractModelRenderer * renderer,
const QGLFormat& format,
QWidget* parent,
const QGLWidget* shareWidget,
Qt::WindowFlags flags ) :
QGLWidget( format, parent, shareWidget, flags ),
m_ImageViewManipulator( NULL ),
m_ImageModelRenderer( NULL ),
m_ImageModel( NULL )
{
// Set focus policy so that the widget gets the focus if it is clicked
setMouseTracking(true);
setFocusPolicy(Qt::StrongFocus);
Initialize(manipulator, renderer);
}
/*******************************************************************************/
GLImageWidget
::~GLImageWidget()
{
// m_ImageViewManipulator (deleted as a child of a QObjet parent).
// m_ImageModelRenderer (deleted as a child of a QObjet parent).
}
/*******************************************************************************/
void
GLImageWidget
::Initialize( AbstractViewManipulator* manipulator,
AbstractModelRenderer* renderer )
{
assert( manipulator!=NULL );
assert( renderer!=NULL );
m_ImageViewManipulator = manipulator;
m_ImageViewManipulator->setParent(this);
m_ImageModelRenderer = renderer;
m_ImageModelRenderer->setParent(this);
QObject::connect(
this, SIGNAL( movingMouse() ),
m_ImageModelRenderer, SLOT( onMovingEvent() )
);
QObject::connect(
this, SIGNAL( releasingMouse() ),
m_ImageModelRenderer, SLOT(onReleasedMouse())
);
// Connect this model region changed.
QObject::connect(
this,
SIGNAL( ModelImageRegionChanged( const ImageRegionType& , const SpacingType&) ),
// to:
m_ImageViewManipulator,
SLOT( OnModelImageRegionChanged( const ImageRegionType&, const SpacingType& ) )
);
// Connect the renderer origin (of extent) changed to the manipulator
QObject::connect(
m_ImageModelRenderer,
SIGNAL( ViewportOriginChanged( const IndexType& ) ),
// to:
m_ImageViewManipulator,
SLOT( OnViewportOriginChanged( const IndexType&) )
);
}
/*******************************************************************************/
void
GLImageWidget
::initializeGL()
{
glClearColor(0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_FLAT);
}
/*******************************************************************************/
void
GLImageWidget
::resizeGL(int width, int height)
{
// TODO: Replace (GLint) casts with safer casts or no cast (if there is no compile-time warning).
glViewport(0, 0, (GLint)width, (GLint)height);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, (GLint)width, 0, (GLint)height, -1, 1);
}
/*******************************************************************************/
void
GLImageWidget
::paintGL()
{
// Clear back-buffer(s) before rendering sub-components.
glClear( GL_COLOR_BUFFER_BIT );
// Get the region to draw from the ImageViewManipulator navigation
// context.
const ImageRegionType region(
m_ImageViewManipulator->GetViewportImageRegion() );
// Get the zoom
const double isotropicZoom = m_ImageViewManipulator->GetIsotropicZoom();
// Setup rendering context with image-model and redering information.
AbstractModelRenderer::RenderingContext context(
m_ImageModel,
region, isotropicZoom,
width(), height(),
m_ImageViewManipulator->HasZoomChanged()
);
// use the model renderer to paint the requested region of the image.
m_ImageModelRenderer->paintGL( context );
}
/*******************************************************************************/
// Delegate the event to the ImageViewManipulator
void
GLImageWidget
::mousePressEvent( QMouseEvent* event )
{
QCursor dragCursor;
dragCursor.setShape(Qt::ClosedHandCursor) ;
this->setCursor(dragCursor);
//
m_ImageViewManipulator->mousePressEvent(event);
this->update();
}
/*******************************************************************************/
void
GLImageWidget
::mouseMoveEvent( QMouseEvent* event )
{
// if a button is clicked == drag
if ( event->buttons() & Qt::LeftButton ||
event->buttons() & Qt::RightButton ||
event->buttons() & Qt::MidButton ||
event->buttons() & Qt::XButton1 ||
event->buttons() & Qt::XButton2 )
{
// emit a signal movingMouse to update the renderer status
emit movingMouse();
// drag detected
m_ImageViewManipulator->mouseMoveEvent(event);
// repaint the buffer
this->update();
// emited to update to force the ql widget (if any) to update
emit CentralWidgetUpdated();
}
else // just mouse cursor moving
{
// no mouse button is grabbed here -> no drag detected
m_ImageViewManipulator->PropagatePointUnderCursorCoordinates(event->pos());
}
}
/*******************************************************************************/
void
GLImageWidget
::mouseReleaseEvent( QMouseEvent* event )
{
QCursor stdCursor;
stdCursor.setShape(Qt::ArrowCursor) ;
this->setCursor(stdCursor);
// emit a signal releasingMouse to update the renderer status
emit releasingMouse();
// call paintGL
this->update();
// emited to update to force the ql widget (if any) to update
emit CentralWidgetUpdated();
}
/*******************************************************************************/
void
GLImageWidget
::wheelEvent( QWheelEvent* event )
{
// emit a signal releasingMouse to update the renderer status
emit releasingMouse();
m_ImageViewManipulator->wheelEvent(event);
// repaint the buffer
this->update();
// emited to update to force the ql widget (if any) to update
emit CentralWidgetUpdated();
}
/*******************************************************************************/
void
GLImageWidget
::resizeEvent( QResizeEvent* event )
{
// First, call superclass implementation
QGLWidget::resizeEvent(event);
m_ImageViewManipulator->resizeEvent(event);
// emit a signal releasingMouse to update the renderer status
emit releasingMouse();
// emited to update to force the ql widget (if any) to update
emit CentralWidgetUpdated();
}
/*******************************************************************************/
void
GLImageWidget
::keyPressEvent( QKeyEvent* event )
{
m_ImageViewManipulator->keyPressEvent(event);
this->update();
// emited to update to force the ql widget (if any) to update
emit CentralWidgetUpdated();
}
/*******************************************************************************/
/* SLOTS */
/******************************************************************************/
void
GLImageWidget
::OnSpacingChanged(const SpacingType& spacing)
{
m_ImageViewManipulator->SetSpacing(spacing);
}
/*******************************************************************************/
}
<|endoftext|>
|
<commit_before>#include "Actor.h"
#include "DrawUtils.h"
#include "Math/ofDraw.h"
using namespace std;
using namespace math;
void Actor::updateAnimationFrames()
{
if (frames.size() > 1) {
if (ofGetElapsedTimef() > timeSpent + framerate) {
timeSpent = ofGetElapsedTimef();
frame = (frame + 1) % frames.size();
}
} else {
frame = 0;
}
}
Actor::Actor(float _width, float _height, std::initializer_list<unsigned> _frames, float _framerate)
: frames(_frames), frame(0), framerate(_framerate), timeSpent(0), centered(true), color(Vector3D(255, 255, 255))
{
size = Vector2D(
_width > 0 ? _width : image.getWidth(),
_height > 0 ? _height : image.getHeight());
if (frames.empty())
frames.push_back(0);
frames.resize(frames.size());
setAngle(0.0f);
setPosition(Vector2D());
setScale(Vector2D(1, 1));
box.position.set(0, 0);
box.size = getSizeScaled();
}
void Actor::init(const std::string fileName)
{
image.load(fileName);
bitmask = Bitmask(image, box,);
}
Vector2D Actor::getSizeScaled() const
{
return Vector2D(localScale.x * size.x, localScale.y * size.y);
}
math::AABB Actor::getBox() const
{
return box;
}
void Actor::setPosition(float x, float y)
{
this->position.set(x, y);
}
void Actor::setPosition(Vector2D position)
{
this->position = position;
}
void Actor::setAngle(float angle)
{
this->angle = angle;
}
void Actor::setScale(math::Vector2D scale)
{
this->localScale.set(scale);
}
void Actor::setColor(Vector3D color)
{
this->color = color;
}
void Actor::translate(float x, float y)
{
translate(Vector2D(x, y));
}
void Actor::translate(Vector2D translation)
{
setPosition(position + translation);
}
void Actor::rotate(float angle)
{
setAngle(this->angle + angle);
}
void Actor::scale(float ratio)
{
setScale(localScale + localScale * ratio);
}
void Actor::scale(Vector2D ratio)
{
setScale(Vector2D(localScale.x * ratio.x, localScale.y * ratio.y));
}
void Actor::update()
{
//Update animation
updateAnimationFrames();
box.transform(position, angle, getSizeScaled(), centered);
//Uncomment for an automatic AABB rotation example in AABBRotationExample
//rotate(toRadians(30 * ofGetLastFrameTime()));
}
void Actor::draw() const
{
auto world =
lh::newAffineScale(localScale.x, localScale.y) *
lh::newAffineRotation(angle) *
lh::newAffineTranslation(position);
cg::setColor(color);
lh::draw(lh::flipY(world), image, size, frame);
cg::setColor(Vector3D(255, 0, 0));
box.draw(make_shared<ofAABB_DrawHelper>());
}
void Actor::drawIntersection(const Actor& other) const
{
if (!box.intersects(other.box)) return;
auto iBox = box.intersection(other.box);
cg::setColor(Vector3D(0, 0, 255));
iBox.draw(make_shared<ofAABB_DrawHelper>());
}
bool Actor::testCollision(const Actor& other) const
{
//Broad Phase
if (!box.intersects(other.box)) return false;
//If you want to ignore Narrow Phase, uncomment
//return true;
//Narrow Phase
return bitmask.testCollision(other.bitmask);
}
Actor::~Actor(void)
{
}
<commit_msg>Bitmask algorithm first version complete<commit_after>#include "Actor.h"
#include "DrawUtils.h"
#include "Math/ofDraw.h"
using namespace std;
using namespace math;
void Actor::updateAnimationFrames()
{
if (frames.size() > 1) {
if (ofGetElapsedTimef() > timeSpent + framerate) {
timeSpent = ofGetElapsedTimef();
frame = (frame + 1) % frames.size();
}
} else {
frame = 0;
}
}
Actor::Actor(float _width, float _height, std::initializer_list<unsigned> _frames, float _framerate)
: frames(_frames), frame(0), framerate(_framerate), timeSpent(0), centered(true), color(Vector3D(255, 255, 255))
{
size = Vector2D(
_width > 0 ? _width : image.getWidth(),
_height > 0 ? _height : image.getHeight());
if (frames.empty())
frames.push_back(0);
frames.resize(frames.size());
setAngle(0.0f);
setPosition(Vector2D());
setScale(Vector2D(1, 1));
box.position.set(0, 0);
box.size = getSizeScaled();
}
void Actor::init(const std::string fileName)
{
image.load(fileName);
bitmask = Bitmask(image, box);
}
Vector2D Actor::getSizeScaled() const
{
return Vector2D(localScale.x * size.x, localScale.y * size.y);
}
math::AABB Actor::getBox() const
{
return box;
}
void Actor::setPosition(float x, float y)
{
this->position.set(x, y);
}
void Actor::setPosition(Vector2D position)
{
this->position = position;
}
void Actor::setAngle(float angle)
{
this->angle = angle;
}
void Actor::setScale(math::Vector2D scale)
{
this->localScale.set(scale);
}
void Actor::setColor(Vector3D color)
{
this->color = color;
}
void Actor::translate(float x, float y)
{
translate(Vector2D(x, y));
}
void Actor::translate(Vector2D translation)
{
setPosition(position + translation);
}
void Actor::rotate(float angle)
{
setAngle(this->angle + angle);
}
void Actor::scale(float ratio)
{
setScale(localScale + localScale * ratio);
}
void Actor::scale(Vector2D ratio)
{
setScale(Vector2D(localScale.x * ratio.x, localScale.y * ratio.y));
}
void Actor::update()
{
//Update animation
updateAnimationFrames();
box.transform(position, angle, getSizeScaled(), centered);
//Uncomment for an automatic AABB rotation example in AABBRotationExample
//rotate(toRadians(30 * ofGetLastFrameTime()));
}
void Actor::draw() const
{
auto world =
lh::newAffineScale(localScale.x, localScale.y) *
lh::newAffineRotation(angle) *
lh::newAffineTranslation(position);
cg::setColor(color);
lh::draw(lh::flipY(world), image, size, frame);
cg::setColor(Vector3D(255, 0, 0));
box.draw(make_shared<ofAABB_DrawHelper>());
}
void Actor::drawIntersection(const Actor& other) const
{
if (!box.intersects(other.box)) return;
auto iBox = box.intersection(other.box);
cg::setColor(Vector3D(0, 0, 255));
iBox.draw(make_shared<ofAABB_DrawHelper>());
}
bool Actor::testCollision(const Actor& other) const
{
//Broad Phase
if (!box.intersects(other.box)) return false;
//If you want to ignore Narrow Phase, uncomment
//return true;
//Narrow Phase
return bitmask.testCollision(other.bitmask);
}
Actor::~Actor(void)
{
}
<|endoftext|>
|
<commit_before>/* net6 - Library providing IPv4/IPv6 network access
* Copyright (C) 2005 Armin Burgmeier / 0x539 dev group
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdexcept>
#include "config.hpp"
#include "common.hpp"
#include "gettext_package.hpp"
#ifdef ENABLE_NLS
namespace
{
net6::gettext_package* local_package = NULL;
}
#endif
void net6::init_gettext(gettext_package& package)
{
#ifdef ENABLE_NLS
local_package = &package;
#endif
}
const char* net6::_(const char* msgid)
{
#ifdef ENABLE_NLS
if(local_package == NULL)
{
throw std::logic_error(
"net6::_:\n"
"init_gettext() has not yet been called. Most "
"This certainly means that you have\n"
"not created a net6::main object."
);
}
return local_package->gettext(msgid);
#else
return msgid;
#endif
}
<commit_msg>[project @ Removed a superfluous word]<commit_after>/* net6 - Library providing IPv4/IPv6 network access
* Copyright (C) 2005 Armin Burgmeier / 0x539 dev group
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdexcept>
#include "config.hpp"
#include "common.hpp"
#include "gettext_package.hpp"
#ifdef ENABLE_NLS
namespace
{
net6::gettext_package* local_package = NULL;
}
#endif
void net6::init_gettext(gettext_package& package)
{
#ifdef ENABLE_NLS
local_package = &package;
#endif
}
const char* net6::_(const char* msgid)
{
#ifdef ENABLE_NLS
if(local_package == NULL)
{
throw std::logic_error(
"net6::_:\n"
"init_gettext() has not yet been called. "
"This certainly means that you have\n"
"not created a net6::main object."
);
}
return local_package->gettext(msgid);
#else
return msgid;
#endif
}
<|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 "chrome/common/chrome_paths.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/sys_info.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_switches.h"
#if defined(OS_MACOSX)
#include "base/mac_util.h"
#endif
namespace chrome {
bool GetGearsPluginPathFromCommandLine(FilePath* path) {
#ifndef NDEBUG
// for debugging, support a cmd line based override
std::wstring plugin_path = CommandLine::ForCurrentProcess()->GetSwitchValue(
switches::kGearsPluginPathOverride);
// TODO(tc): After GetSwitchNativeValue lands, we don't need to use
// FromWStringHack.
*path = FilePath::FromWStringHack(plugin_path);
return !plugin_path.empty();
#else
return false;
#endif
}
bool PathProvider(int key, FilePath* result) {
// Some keys are just aliases...
switch (key) {
case chrome::DIR_APP:
return PathService::Get(base::DIR_MODULE, result);
case chrome::DIR_LOGS:
#ifdef NDEBUG
// Release builds write to the data dir
return PathService::Get(chrome::DIR_USER_DATA, result);
#else
// Debug builds write next to the binary (in the build tree)
#if defined(OS_MACOSX)
if (!PathService::Get(base::DIR_EXE, result))
return false;
if (mac_util::AmIBundled()) {
// If we're called from chrome, dump it beside the app (outside the
// app bundle), if we're called from a unittest, we'll already
// outside the bundle so use the exe dir.
// exe_dir gave us .../Chromium.app/Contents/MacOS/Chromium.
*result = result->DirName();
*result = result->DirName();
*result = result->DirName();
}
return true;
#else
return PathService::Get(base::DIR_EXE, result);
#endif // defined(OS_MACOSX)
#endif // NDEBUG
case chrome::FILE_RESOURCE_MODULE:
return PathService::Get(base::FILE_MODULE, result);
}
// Assume that we will not need to create the directory if it does not exist.
// This flag can be set to true for the cases where we want to create it.
bool create_dir = false;
FilePath cur;
switch (key) {
case chrome::DIR_USER_DATA:
if (!GetDefaultUserDataDirectory(&cur))
return false;
create_dir = true;
break;
case chrome::DIR_USER_CACHE:
#if defined(OS_LINUX)
if (!GetUserCacheDirectory(&cur))
return false;
create_dir = true;
#else
// No concept of a separate cache directory on non-Linux systems.
return false;
#endif
break;
case chrome::DIR_USER_DOCUMENTS:
if (!GetUserDocumentsDirectory(&cur))
return false;
create_dir = true;
break;
case chrome::DIR_DEFAULT_DOWNLOADS:
if (!GetUserDownloadsDirectory(&cur))
return false;
break;
case chrome::DIR_CRASH_DUMPS:
// The crash reports are always stored relative to the default user data
// directory. This avoids the problem of having to re-initialize the
// exception handler after parsing command line options, which may
// override the location of the app's profile directory.
if (!GetDefaultUserDataDirectory(&cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("Crash Reports"));
create_dir = true;
break;
case chrome::DIR_USER_DESKTOP:
if (!GetUserDesktop(&cur))
return false;
break;
case chrome::DIR_INSPECTOR:
if (!PathService::Get(chrome::DIR_APP, &cur))
return false;
#if defined(OS_MACOSX)
cur = cur.DirName();
cur = cur.Append(FILE_PATH_LITERAL("Resources"));
cur = cur.Append(FILE_PATH_LITERAL("inspector"));
#else
cur = cur.Append(FILE_PATH_LITERAL("resources"));
cur = cur.Append(FILE_PATH_LITERAL("inspector"));
#endif
break;
case chrome::DIR_APP_DICTIONARIES:
#if defined(OS_LINUX) || defined(OS_MACOSX)
// We can't write into the EXE dir on Linux, so keep dictionaries
// alongside the safe browsing database in the user data dir.
// And we don't want to write into the bundle on the Mac, so push
// it to the user data dir there also.
if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
return false;
#else
if (!PathService::Get(base::DIR_EXE, &cur))
return false;
#endif
cur = cur.Append(FILE_PATH_LITERAL("Dictionaries"));
create_dir = true;
break;
case chrome::FILE_LOCAL_STATE:
if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
return false;
cur = cur.Append(chrome::kLocalStateFilename);
break;
case chrome::FILE_RECORDED_SCRIPT:
if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("script.log"));
break;
case chrome::FILE_GEARS_PLUGIN:
if (!GetGearsPluginPathFromCommandLine(&cur)) {
#if defined(OS_WIN)
// Search for gears.dll alongside chrome.dll first. This new model
// allows us to package gears.dll with the Chrome installer and update
// it while Chrome is running.
if (!PathService::Get(base::DIR_MODULE, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("gears.dll"));
if (!file_util::PathExists(cur)) {
if (!PathService::Get(base::DIR_EXE, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("plugins"));
cur = cur.Append(FILE_PATH_LITERAL("gears"));
cur = cur.Append(FILE_PATH_LITERAL("gears.dll"));
}
#else
// No gears.dll on non-Windows systems.
return false;
#endif
}
break;
// The following are only valid in the development environment, and
// will fail if executed from an installed executable (because the
// generated path won't exist).
case chrome::DIR_TEST_DATA:
if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("chrome"));
cur = cur.Append(FILE_PATH_LITERAL("test"));
cur = cur.Append(FILE_PATH_LITERAL("data"));
if (!file_util::PathExists(cur)) // we don't want to create this
return false;
break;
case chrome::DIR_TEST_TOOLS:
if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("chrome"));
cur = cur.Append(FILE_PATH_LITERAL("tools"));
cur = cur.Append(FILE_PATH_LITERAL("test"));
if (!file_util::PathExists(cur)) // we don't want to create this
return false;
break;
default:
return false;
}
if (create_dir && !file_util::PathExists(cur) &&
!file_util::CreateDirectory(cur))
return false;
*result = cur;
return true;
}
// This cannot be done as a static initializer sadly since Visual Studio will
// eliminate this object file if there is no direct entry point into it.
void RegisterPathProvider() {
PathService::RegisterProvider(PathProvider, PATH_START, PATH_END);
}
} // namespace chrome
<commit_msg>Create the download folder if it doesn't exist.<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 "chrome/common/chrome_paths.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "base/sys_info.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths_internal.h"
#include "chrome/common/chrome_switches.h"
#if defined(OS_MACOSX)
#include "base/mac_util.h"
#endif
namespace chrome {
bool GetGearsPluginPathFromCommandLine(FilePath* path) {
#ifndef NDEBUG
// for debugging, support a cmd line based override
std::wstring plugin_path = CommandLine::ForCurrentProcess()->GetSwitchValue(
switches::kGearsPluginPathOverride);
// TODO(tc): After GetSwitchNativeValue lands, we don't need to use
// FromWStringHack.
*path = FilePath::FromWStringHack(plugin_path);
return !plugin_path.empty();
#else
return false;
#endif
}
bool PathProvider(int key, FilePath* result) {
// Some keys are just aliases...
switch (key) {
case chrome::DIR_APP:
return PathService::Get(base::DIR_MODULE, result);
case chrome::DIR_LOGS:
#ifdef NDEBUG
// Release builds write to the data dir
return PathService::Get(chrome::DIR_USER_DATA, result);
#else
// Debug builds write next to the binary (in the build tree)
#if defined(OS_MACOSX)
if (!PathService::Get(base::DIR_EXE, result))
return false;
if (mac_util::AmIBundled()) {
// If we're called from chrome, dump it beside the app (outside the
// app bundle), if we're called from a unittest, we'll already
// outside the bundle so use the exe dir.
// exe_dir gave us .../Chromium.app/Contents/MacOS/Chromium.
*result = result->DirName();
*result = result->DirName();
*result = result->DirName();
}
return true;
#else
return PathService::Get(base::DIR_EXE, result);
#endif // defined(OS_MACOSX)
#endif // NDEBUG
case chrome::FILE_RESOURCE_MODULE:
return PathService::Get(base::FILE_MODULE, result);
}
// Assume that we will not need to create the directory if it does not exist.
// This flag can be set to true for the cases where we want to create it.
bool create_dir = false;
FilePath cur;
switch (key) {
case chrome::DIR_USER_DATA:
if (!GetDefaultUserDataDirectory(&cur))
return false;
create_dir = true;
break;
case chrome::DIR_USER_CACHE:
#if defined(OS_LINUX)
if (!GetUserCacheDirectory(&cur))
return false;
create_dir = true;
#else
// No concept of a separate cache directory on non-Linux systems.
return false;
#endif
break;
case chrome::DIR_USER_DOCUMENTS:
if (!GetUserDocumentsDirectory(&cur))
return false;
create_dir = true;
break;
case chrome::DIR_DEFAULT_DOWNLOADS:
if (!GetUserDownloadsDirectory(&cur))
return false;
create_dir = true;
break;
case chrome::DIR_CRASH_DUMPS:
// The crash reports are always stored relative to the default user data
// directory. This avoids the problem of having to re-initialize the
// exception handler after parsing command line options, which may
// override the location of the app's profile directory.
if (!GetDefaultUserDataDirectory(&cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("Crash Reports"));
create_dir = true;
break;
case chrome::DIR_USER_DESKTOP:
if (!GetUserDesktop(&cur))
return false;
break;
case chrome::DIR_INSPECTOR:
if (!PathService::Get(chrome::DIR_APP, &cur))
return false;
#if defined(OS_MACOSX)
cur = cur.DirName();
cur = cur.Append(FILE_PATH_LITERAL("Resources"));
cur = cur.Append(FILE_PATH_LITERAL("inspector"));
#else
cur = cur.Append(FILE_PATH_LITERAL("resources"));
cur = cur.Append(FILE_PATH_LITERAL("inspector"));
#endif
break;
case chrome::DIR_APP_DICTIONARIES:
#if defined(OS_LINUX) || defined(OS_MACOSX)
// We can't write into the EXE dir on Linux, so keep dictionaries
// alongside the safe browsing database in the user data dir.
// And we don't want to write into the bundle on the Mac, so push
// it to the user data dir there also.
if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
return false;
#else
if (!PathService::Get(base::DIR_EXE, &cur))
return false;
#endif
cur = cur.Append(FILE_PATH_LITERAL("Dictionaries"));
create_dir = true;
break;
case chrome::FILE_LOCAL_STATE:
if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
return false;
cur = cur.Append(chrome::kLocalStateFilename);
break;
case chrome::FILE_RECORDED_SCRIPT:
if (!PathService::Get(chrome::DIR_USER_DATA, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("script.log"));
break;
case chrome::FILE_GEARS_PLUGIN:
if (!GetGearsPluginPathFromCommandLine(&cur)) {
#if defined(OS_WIN)
// Search for gears.dll alongside chrome.dll first. This new model
// allows us to package gears.dll with the Chrome installer and update
// it while Chrome is running.
if (!PathService::Get(base::DIR_MODULE, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("gears.dll"));
if (!file_util::PathExists(cur)) {
if (!PathService::Get(base::DIR_EXE, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("plugins"));
cur = cur.Append(FILE_PATH_LITERAL("gears"));
cur = cur.Append(FILE_PATH_LITERAL("gears.dll"));
}
#else
// No gears.dll on non-Windows systems.
return false;
#endif
}
break;
// The following are only valid in the development environment, and
// will fail if executed from an installed executable (because the
// generated path won't exist).
case chrome::DIR_TEST_DATA:
if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("chrome"));
cur = cur.Append(FILE_PATH_LITERAL("test"));
cur = cur.Append(FILE_PATH_LITERAL("data"));
if (!file_util::PathExists(cur)) // we don't want to create this
return false;
break;
case chrome::DIR_TEST_TOOLS:
if (!PathService::Get(base::DIR_SOURCE_ROOT, &cur))
return false;
cur = cur.Append(FILE_PATH_LITERAL("chrome"));
cur = cur.Append(FILE_PATH_LITERAL("tools"));
cur = cur.Append(FILE_PATH_LITERAL("test"));
if (!file_util::PathExists(cur)) // we don't want to create this
return false;
break;
default:
return false;
}
if (create_dir && !file_util::PathExists(cur) &&
!file_util::CreateDirectory(cur))
return false;
*result = cur;
return true;
}
// This cannot be done as a static initializer sadly since Visual Studio will
// eliminate this object file if there is no direct entry point into it.
void RegisterPathProvider() {
PathService::RegisterProvider(PathProvider, PATH_START, PATH_END);
}
} // namespace chrome
<|endoftext|>
|
<commit_before>#include "filename-parser-test.h"
#include <QMap>
#include <QString>
#include <QtTest>
#include "filename/filename-parser.h"
#include "filename/ast/filename-node-conditional.h"
#include "filename/ast/filename-node-condition-invert.h"
#include "filename/ast/filename-node-condition-op.h"
#include "filename/ast/filename-node-condition-tag.h"
#include "filename/ast/filename-node-condition-token.h"
#include "filename/ast/filename-node-root.h"
#include "filename/ast/filename-node-text.h"
#include "filename/ast/filename-node-variable.h"
void FilenameParserTest::testParseText()
{
FilenameParser parser("image.png");
auto filename = parser.parseRoot();
QCOMPARE(filename->exprs.count(), 1);
auto txt = dynamic_cast<FilenameNodeText*>(filename->exprs[0]);
QVERIFY(txt != nullptr);
QCOMPARE(txt->text, QString("image.png"));
}
void FilenameParserTest::testParseVariable()
{
FilenameParser parser("%md5%");
auto filename = parser.parseRoot();
QCOMPARE(filename->exprs.count(), 1);
auto var = dynamic_cast<FilenameNodeVariable*>(filename->exprs[0]);
QVERIFY(var != nullptr);
QCOMPARE(var->name, QString("md5"));
QCOMPARE(var->opts.count(), 0);
}
void FilenameParserTest::testParseVariableWithOptions()
{
FilenameParser parser("%md5:flag,opt=val%");
auto filename = parser.parseRoot();
QCOMPARE(filename->exprs.count(), 1);
auto var = dynamic_cast<FilenameNodeVariable*>(filename->exprs[0]);
QVERIFY(var != nullptr);
QCOMPARE(var->name, QString("md5"));
QCOMPARE(var->opts.count(), 2);
QCOMPARE(var->opts.keys(), QStringList() << "flag" << "opt");
QCOMPARE(var->opts["flag"], QString());
QCOMPARE(var->opts["opt"], QString("val"));
}
void FilenameParserTest::testParseMixed()
{
FilenameParser parser("out/%md5%.%ext%");
auto filename = parser.parseRoot();
QCOMPARE(filename->exprs.count(), 4);
}
void FilenameParserTest::testParseConditional()
{
FilenameParser parser("out/<\"tag\"?some tag is present:%artist%>/image.png");
auto filename = parser.parseRoot();
QCOMPARE(filename->exprs.count(), 3);
auto txt1 = dynamic_cast<FilenameNodeText*>(filename->exprs[0]);
QVERIFY(txt1 != nullptr);
QCOMPARE(txt1->text, QString("out/"));
auto conditional = dynamic_cast<FilenameNodeConditional*>(filename->exprs[1]);
QVERIFY(conditional != nullptr);
QVERIFY(conditional->ifTrue != nullptr);
QVERIFY(conditional->ifFalse != nullptr);
auto cond = dynamic_cast<FilenameNodeConditionTag*>(conditional->condition);
QVERIFY(cond != nullptr);
QCOMPARE(cond->tag.text(), QString("tag"));
auto ifTrue = dynamic_cast<FilenameNodeText*>(conditional->ifTrue);
QVERIFY(ifTrue != nullptr);
QCOMPARE(ifTrue->text, QString("some tag is present"));
auto ifFalse = dynamic_cast<FilenameNodeVariable*>(conditional->ifFalse);
QVERIFY(ifFalse != nullptr);
QCOMPARE(ifFalse->name, QString("artist"));
auto txt2 = dynamic_cast<FilenameNodeText*>(filename->exprs[2]);
QVERIFY(txt2 != nullptr);
QCOMPARE(txt2->text, QString("/image.png"));
}
void FilenameParserTest::testParseConditionalLegacy()
{
FilenameParser parser("out/<some \"tag\" is present/>image.png");
auto filename = parser.parseRoot();
QCOMPARE(filename->exprs.count(), 3);
auto txt1 = dynamic_cast<FilenameNodeText*>(filename->exprs[0]);
QVERIFY(txt1 != nullptr);
QCOMPARE(txt1->text, QString("out/"));
auto conditional = dynamic_cast<FilenameNodeConditional*>(filename->exprs[1]);
QVERIFY(conditional != nullptr);
QVERIFY(conditional->ifTrue != nullptr);
QVERIFY(conditional->ifFalse == nullptr);
auto cond = dynamic_cast<FilenameNodeConditionTag*>(conditional->condition);
QVERIFY(cond != nullptr);
QCOMPARE(cond->tag.text(), QString("tag"));
auto ifTrue = dynamic_cast<FilenameNodeRoot*>(conditional->ifTrue);
QVERIFY(ifTrue != nullptr);
QCOMPARE(ifTrue->exprs.count(), 3);
auto ifTrue1 = dynamic_cast<FilenameNodeText*>(ifTrue->exprs[0]);
QVERIFY(ifTrue1 != nullptr);
QCOMPARE(ifTrue1->text, QString("some "));
auto ifTrue2 = dynamic_cast<FilenameNodeConditionTag*>(ifTrue->exprs[1]);
QVERIFY(ifTrue2 != nullptr);
QCOMPARE(ifTrue2->tag.text(), QString("tag"));
auto ifTrue3 = dynamic_cast<FilenameNodeText*>(ifTrue->exprs[2]);
QVERIFY(ifTrue3 != nullptr);
QCOMPARE(ifTrue3->text, QString(" is present/"));
auto txt2 = dynamic_cast<FilenameNodeText*>(filename->exprs[2]);
QVERIFY(txt2 != nullptr);
QCOMPARE(txt2->text, QString("image.png"));
}
void FilenameParserTest::testParseConditionTag()
{
FilenameParser parser("\"my_tag\"");
auto cond = parser.parseCondition();
auto tagCond = dynamic_cast<FilenameNodeConditionTag*>(cond);
QVERIFY(tagCond != nullptr);
QCOMPARE(tagCond->tag.text(), QString("my_tag"));
}
void FilenameParserTest::testParseConditionToken()
{
FilenameParser parser("%my_token%");
auto cond = parser.parseCondition();
auto tokenCond = dynamic_cast<FilenameNodeConditionToken*>(cond);
QVERIFY(tokenCond != nullptr);
QCOMPARE(tokenCond->token, QString("my_token"));
}
void FilenameParserTest::testParseConditionInvert()
{
FilenameParser parser("!%my_token%");
auto cond = parser.parseCondition();
auto invertCond = dynamic_cast<FilenameNodeConditionInvert*>(cond);
QVERIFY(invertCond != nullptr);
auto tokenCond = dynamic_cast<FilenameNodeConditionToken*>(invertCond->node);
QVERIFY(tokenCond != nullptr);
QCOMPARE(tokenCond->token, QString("my_token"));
}
void FilenameParserTest::testParseConditionOperator()
{
FilenameParser parser("\"my_tag\" & %my_token%");
auto cond = parser.parseCondition();
auto opCond = dynamic_cast<FilenameNodeConditionOp*>(cond);
QVERIFY(opCond != nullptr);
QCOMPARE(opCond->op, FilenameNodeConditionOp::Operator::And);
auto left = dynamic_cast<FilenameNodeConditionTag*>(opCond->left);
QVERIFY(left != nullptr);
QCOMPARE(left->tag.text(), QString("my_tag"));
auto right = dynamic_cast<FilenameNodeConditionToken*>(opCond->right);
QVERIFY(right != nullptr);
QCOMPARE(right->token, QString("my_token"));
}
void FilenameParserTest::testParseConditionMixedOperators()
{
FilenameParser parser("\"my_tag\" | %some_token% & !%my_token%");
auto cond = parser.parseCondition();
auto opCond = dynamic_cast<FilenameNodeConditionOp*>(cond);
QVERIFY(opCond != nullptr);
QCOMPARE(opCond->op, FilenameNodeConditionOp::Operator::Or);
auto right = dynamic_cast<FilenameNodeConditionOp*>(opCond->right);
QVERIFY(right != nullptr);
QCOMPARE(right->op, FilenameNodeConditionOp::Operator::And);
auto invert = dynamic_cast<FilenameNodeConditionInvert*>(right->right);
QVERIFY(invert != nullptr);
}
void FilenameParserTest::testParseConditionTagParenthesis()
{
FilenameParser parser("(\"my_tag\")");
auto cond = parser.parseCondition();
auto tagCond = dynamic_cast<FilenameNodeConditionTag*>(cond);
QVERIFY(tagCond != nullptr);
QCOMPARE(tagCond->tag.text(), QString("my_tag"));
}
void FilenameParserTest::testParseConditionMixedParenthesis()
{
FilenameParser parser("(\"my_tag\" | %some_token%) & %my_token%");
auto cond = parser.parseCondition();
auto opCond = dynamic_cast<FilenameNodeConditionOp*>(cond);
QVERIFY(opCond != nullptr);
QCOMPARE(opCond->op, FilenameNodeConditionOp::Operator::And);
auto right = dynamic_cast<FilenameNodeConditionOp*>(opCond->left);
QVERIFY(right != nullptr);
QCOMPARE(right->op, FilenameNodeConditionOp::Operator::Or);
}
QTEST_MAIN(FilenameParserTest)
<commit_msg>Fix GCC qCompare between QList<QString> and QStringList<commit_after>#include "filename-parser-test.h"
#include <QMap>
#include <QString>
#include <QtTest>
#include "filename/filename-parser.h"
#include "filename/ast/filename-node-conditional.h"
#include "filename/ast/filename-node-condition-invert.h"
#include "filename/ast/filename-node-condition-op.h"
#include "filename/ast/filename-node-condition-tag.h"
#include "filename/ast/filename-node-condition-token.h"
#include "filename/ast/filename-node-root.h"
#include "filename/ast/filename-node-text.h"
#include "filename/ast/filename-node-variable.h"
void FilenameParserTest::testParseText()
{
FilenameParser parser("image.png");
auto filename = parser.parseRoot();
QCOMPARE(filename->exprs.count(), 1);
auto txt = dynamic_cast<FilenameNodeText*>(filename->exprs[0]);
QVERIFY(txt != nullptr);
QCOMPARE(txt->text, QString("image.png"));
}
void FilenameParserTest::testParseVariable()
{
FilenameParser parser("%md5%");
auto filename = parser.parseRoot();
QCOMPARE(filename->exprs.count(), 1);
auto var = dynamic_cast<FilenameNodeVariable*>(filename->exprs[0]);
QVERIFY(var != nullptr);
QCOMPARE(var->name, QString("md5"));
QCOMPARE(var->opts.count(), 0);
}
void FilenameParserTest::testParseVariableWithOptions()
{
FilenameParser parser("%md5:flag,opt=val%");
auto filename = parser.parseRoot();
QCOMPARE(filename->exprs.count(), 1);
auto var = dynamic_cast<FilenameNodeVariable*>(filename->exprs[0]);
QVERIFY(var != nullptr);
QCOMPARE(var->name, QString("md5"));
QCOMPARE(var->opts.count(), 2);
QCOMPARE(var->opts.keys(), QList<QString>() << "flag" << "opt");
QCOMPARE(var->opts["flag"], QString());
QCOMPARE(var->opts["opt"], QString("val"));
}
void FilenameParserTest::testParseMixed()
{
FilenameParser parser("out/%md5%.%ext%");
auto filename = parser.parseRoot();
QCOMPARE(filename->exprs.count(), 4);
}
void FilenameParserTest::testParseConditional()
{
FilenameParser parser("out/<\"tag\"?some tag is present:%artist%>/image.png");
auto filename = parser.parseRoot();
QCOMPARE(filename->exprs.count(), 3);
auto txt1 = dynamic_cast<FilenameNodeText*>(filename->exprs[0]);
QVERIFY(txt1 != nullptr);
QCOMPARE(txt1->text, QString("out/"));
auto conditional = dynamic_cast<FilenameNodeConditional*>(filename->exprs[1]);
QVERIFY(conditional != nullptr);
QVERIFY(conditional->ifTrue != nullptr);
QVERIFY(conditional->ifFalse != nullptr);
auto cond = dynamic_cast<FilenameNodeConditionTag*>(conditional->condition);
QVERIFY(cond != nullptr);
QCOMPARE(cond->tag.text(), QString("tag"));
auto ifTrue = dynamic_cast<FilenameNodeText*>(conditional->ifTrue);
QVERIFY(ifTrue != nullptr);
QCOMPARE(ifTrue->text, QString("some tag is present"));
auto ifFalse = dynamic_cast<FilenameNodeVariable*>(conditional->ifFalse);
QVERIFY(ifFalse != nullptr);
QCOMPARE(ifFalse->name, QString("artist"));
auto txt2 = dynamic_cast<FilenameNodeText*>(filename->exprs[2]);
QVERIFY(txt2 != nullptr);
QCOMPARE(txt2->text, QString("/image.png"));
}
void FilenameParserTest::testParseConditionalLegacy()
{
FilenameParser parser("out/<some \"tag\" is present/>image.png");
auto filename = parser.parseRoot();
QCOMPARE(filename->exprs.count(), 3);
auto txt1 = dynamic_cast<FilenameNodeText*>(filename->exprs[0]);
QVERIFY(txt1 != nullptr);
QCOMPARE(txt1->text, QString("out/"));
auto conditional = dynamic_cast<FilenameNodeConditional*>(filename->exprs[1]);
QVERIFY(conditional != nullptr);
QVERIFY(conditional->ifTrue != nullptr);
QVERIFY(conditional->ifFalse == nullptr);
auto cond = dynamic_cast<FilenameNodeConditionTag*>(conditional->condition);
QVERIFY(cond != nullptr);
QCOMPARE(cond->tag.text(), QString("tag"));
auto ifTrue = dynamic_cast<FilenameNodeRoot*>(conditional->ifTrue);
QVERIFY(ifTrue != nullptr);
QCOMPARE(ifTrue->exprs.count(), 3);
auto ifTrue1 = dynamic_cast<FilenameNodeText*>(ifTrue->exprs[0]);
QVERIFY(ifTrue1 != nullptr);
QCOMPARE(ifTrue1->text, QString("some "));
auto ifTrue2 = dynamic_cast<FilenameNodeConditionTag*>(ifTrue->exprs[1]);
QVERIFY(ifTrue2 != nullptr);
QCOMPARE(ifTrue2->tag.text(), QString("tag"));
auto ifTrue3 = dynamic_cast<FilenameNodeText*>(ifTrue->exprs[2]);
QVERIFY(ifTrue3 != nullptr);
QCOMPARE(ifTrue3->text, QString(" is present/"));
auto txt2 = dynamic_cast<FilenameNodeText*>(filename->exprs[2]);
QVERIFY(txt2 != nullptr);
QCOMPARE(txt2->text, QString("image.png"));
}
void FilenameParserTest::testParseConditionTag()
{
FilenameParser parser("\"my_tag\"");
auto cond = parser.parseCondition();
auto tagCond = dynamic_cast<FilenameNodeConditionTag*>(cond);
QVERIFY(tagCond != nullptr);
QCOMPARE(tagCond->tag.text(), QString("my_tag"));
}
void FilenameParserTest::testParseConditionToken()
{
FilenameParser parser("%my_token%");
auto cond = parser.parseCondition();
auto tokenCond = dynamic_cast<FilenameNodeConditionToken*>(cond);
QVERIFY(tokenCond != nullptr);
QCOMPARE(tokenCond->token, QString("my_token"));
}
void FilenameParserTest::testParseConditionInvert()
{
FilenameParser parser("!%my_token%");
auto cond = parser.parseCondition();
auto invertCond = dynamic_cast<FilenameNodeConditionInvert*>(cond);
QVERIFY(invertCond != nullptr);
auto tokenCond = dynamic_cast<FilenameNodeConditionToken*>(invertCond->node);
QVERIFY(tokenCond != nullptr);
QCOMPARE(tokenCond->token, QString("my_token"));
}
void FilenameParserTest::testParseConditionOperator()
{
FilenameParser parser("\"my_tag\" & %my_token%");
auto cond = parser.parseCondition();
auto opCond = dynamic_cast<FilenameNodeConditionOp*>(cond);
QVERIFY(opCond != nullptr);
QCOMPARE(opCond->op, FilenameNodeConditionOp::Operator::And);
auto left = dynamic_cast<FilenameNodeConditionTag*>(opCond->left);
QVERIFY(left != nullptr);
QCOMPARE(left->tag.text(), QString("my_tag"));
auto right = dynamic_cast<FilenameNodeConditionToken*>(opCond->right);
QVERIFY(right != nullptr);
QCOMPARE(right->token, QString("my_token"));
}
void FilenameParserTest::testParseConditionMixedOperators()
{
FilenameParser parser("\"my_tag\" | %some_token% & !%my_token%");
auto cond = parser.parseCondition();
auto opCond = dynamic_cast<FilenameNodeConditionOp*>(cond);
QVERIFY(opCond != nullptr);
QCOMPARE(opCond->op, FilenameNodeConditionOp::Operator::Or);
auto right = dynamic_cast<FilenameNodeConditionOp*>(opCond->right);
QVERIFY(right != nullptr);
QCOMPARE(right->op, FilenameNodeConditionOp::Operator::And);
auto invert = dynamic_cast<FilenameNodeConditionInvert*>(right->right);
QVERIFY(invert != nullptr);
}
void FilenameParserTest::testParseConditionTagParenthesis()
{
FilenameParser parser("(\"my_tag\")");
auto cond = parser.parseCondition();
auto tagCond = dynamic_cast<FilenameNodeConditionTag*>(cond);
QVERIFY(tagCond != nullptr);
QCOMPARE(tagCond->tag.text(), QString("my_tag"));
}
void FilenameParserTest::testParseConditionMixedParenthesis()
{
FilenameParser parser("(\"my_tag\" | %some_token%) & %my_token%");
auto cond = parser.parseCondition();
auto opCond = dynamic_cast<FilenameNodeConditionOp*>(cond);
QVERIFY(opCond != nullptr);
QCOMPARE(opCond->op, FilenameNodeConditionOp::Operator::And);
auto right = dynamic_cast<FilenameNodeConditionOp*>(opCond->left);
QVERIFY(right != nullptr);
QCOMPARE(right->op, FilenameNodeConditionOp::Operator::Or);
}
QTEST_MAIN(FilenameParserTest)
<|endoftext|>
|
<commit_before>/*
* SessionPanmirrorCrossref.cpp
*
* Copyright (C) 2009-16 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionPanmirrorCrossref.hpp"
#include <shared_core/Error.hpp>
#include <shared_core/json/Json.hpp>
#include <core/Exec.hpp>
#include <core/json/JsonRpc.hpp>
#include <core/http/Util.hpp>
#include <r/ROptions.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionAsyncDownloadFile.hpp>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace panmirror {
namespace crossref {
namespace {
void crossrefContentRequestHandler(const core::json::Value& value, core::json::JsonRpcResponse* pResponse)
{
pResponse->setResult(value);
}
void crossrefApiRequestHandler(const core::json::Value& value, core::json::JsonRpcResponse* pResponse)
{
if (json::isType<json::Object>(value))
{
json::Object responseJson = value.getObject();
std::string status;
json::Object message;
Error error = json::readObject(responseJson, "status", status,
"message", message);
if (error)
{
json::setErrorResponse(error, pResponse);
}
else if (status != "ok")
{
Error error = systemError(boost::system::errc::state_not_recoverable,
"Unexpected status from crossref api: " + status,
ERROR_LOCATION);
json::setErrorResponse(error, pResponse);
}
else
{
pResponse->setResult(message);
}
}
else
{
Error error = systemError(boost::system::errc::state_not_recoverable,
"Unexpected response from crossref api",
ERROR_LOCATION);
json::setErrorResponse(error, pResponse);
}
}
void crossrefRequest(const std::string& resource,
const http::Fields& params,
const session::JsonRpcResponseHandler& handler,
const json::JsonRpcFunctionContinuation& cont)
{
// build user agent
std::string userAgent = r::options::getOption<std::string>("HTTPUserAgent", "RStudio") +
"; RStudio Crossref Cite (mailto:crossref@rstudio.com)";
// build query string
std::string queryString;
core::http::util::buildQueryString(params, &queryString);
if (queryString.length() > 0)
queryString = "?" + queryString;
// build the url and make the request
boost::format fmt("%s/%s%s");
const std::string url = boost::str(fmt % kCrossrefApiHost % resource % queryString);
http::Fields headers;
asyncJsonRpcRequest(url, userAgent, headers, handler, cont);
}
void crossrefWorks(const json::JsonRpcRequest& request,
const json::JsonRpcFunctionContinuation& cont)
{
// extract query
std::string query;
Error error = json::readParams(request.params, &query);
if (error)
{
json::JsonRpcResponse response;
setErrorResponse(error, &response);
cont(Success(), &response);
return;
}
// build params
core::http::Fields params;
params.push_back(std::make_pair("query", query));
// make the request
crossrefRequest(kCrossrefWorks, params, crossrefApiRequestHandler, cont);
}
void crossrefDoi(const json::JsonRpcRequest& request,
const json::JsonRpcFunctionContinuation& cont)
{
std::string doi;
Error error = json::readParams(request.params, &doi);
if (error)
{
json::JsonRpcResponse response;
setErrorResponse(error, &response);
cont(Success(), &response);
return;
}
// Path to DOI metadata works/{doi}/transform/{format} (see: https://citation.crosscite.org/docs.html#sec-5)
const char * const kCitationFormat = "application/vnd.citationstyles.csl+json";
boost::format fmt("%s/%s/transform/%s");
const std::string resourcePath = boost::str(fmt % kCrossrefWorks % doi % kCitationFormat);
// No parameters
core::http::Fields params;
// make the request
crossrefRequest(resourcePath, params, crossrefContentRequestHandler, cont);
}
} // end anonymous namespace
Error initialize()
{
ExecBlock initBlock;
initBlock.addFunctions()
(boost::bind(module_context::registerAsyncRpcMethod, "crossref_works", crossrefWorks))
(boost::bind(module_context::registerAsyncRpcMethod, "crossref_doi", crossrefDoi))
;
return initBlock.execute();
}
} // end namespace crossref
} // end namespace panmirror
} // end namespace modules
} // end namespace session
} // end namespace rstudio
<commit_msg>ability to specify crossref email<commit_after>/*
* SessionPanmirrorCrossref.cpp
*
* Copyright (C) 2009-16 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionPanmirrorCrossref.hpp"
#include <shared_core/Error.hpp>
#include <shared_core/json/Json.hpp>
#include <core/Exec.hpp>
#include <core/json/JsonRpc.hpp>
#include <core/http/Util.hpp>
#include <r/ROptions.hpp>
#include <session/SessionModuleContext.hpp>
#include <session/SessionAsyncDownloadFile.hpp>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace panmirror {
namespace crossref {
namespace {
void crossrefContentRequestHandler(const core::json::Value& value, core::json::JsonRpcResponse* pResponse)
{
pResponse->setResult(value);
}
void crossrefApiRequestHandler(const core::json::Value& value, core::json::JsonRpcResponse* pResponse)
{
if (json::isType<json::Object>(value))
{
json::Object responseJson = value.getObject();
std::string status;
json::Object message;
Error error = json::readObject(responseJson, "status", status,
"message", message);
if (error)
{
json::setErrorResponse(error, pResponse);
}
else if (status != "ok")
{
Error error = systemError(boost::system::errc::state_not_recoverable,
"Unexpected status from crossref api: " + status,
ERROR_LOCATION);
json::setErrorResponse(error, pResponse);
}
else
{
pResponse->setResult(message);
}
}
else
{
Error error = systemError(boost::system::errc::state_not_recoverable,
"Unexpected response from crossref api",
ERROR_LOCATION);
json::setErrorResponse(error, pResponse);
}
}
void crossrefRequest(const std::string& resource,
const http::Fields& params,
const session::JsonRpcResponseHandler& handler,
const json::JsonRpcFunctionContinuation& cont)
{
// email address
std::string email = r::options::getOption<std::string>("rstudio.crossref_email",
"crossref@rstudio.com", false);
// build user agent
std::string userAgent = r::options::getOption<std::string>("HTTPUserAgent", "RStudio") +
"; RStudio Crossref Cite (mailto:" + email + ")";
// build query string
std::string queryString;
core::http::util::buildQueryString(params, &queryString);
if (queryString.length() > 0)
queryString = "?" + queryString;
// build the url and make the request
boost::format fmt("%s/%s%s");
const std::string url = boost::str(fmt % kCrossrefApiHost % resource % queryString);
http::Fields headers;
asyncJsonRpcRequest(url, userAgent, headers, handler, cont);
}
void crossrefWorks(const json::JsonRpcRequest& request,
const json::JsonRpcFunctionContinuation& cont)
{
// extract query
std::string query;
Error error = json::readParams(request.params, &query);
if (error)
{
json::JsonRpcResponse response;
setErrorResponse(error, &response);
cont(Success(), &response);
return;
}
// build params
core::http::Fields params;
params.push_back(std::make_pair("query", query));
// make the request
crossrefRequest(kCrossrefWorks, params, crossrefApiRequestHandler, cont);
}
void crossrefDoi(const json::JsonRpcRequest& request,
const json::JsonRpcFunctionContinuation& cont)
{
std::string doi;
Error error = json::readParams(request.params, &doi);
if (error)
{
json::JsonRpcResponse response;
setErrorResponse(error, &response);
cont(Success(), &response);
return;
}
// Path to DOI metadata works/{doi}/transform/{format} (see: https://citation.crosscite.org/docs.html#sec-5)
const char * const kCitationFormat = "application/vnd.citationstyles.csl+json";
boost::format fmt("%s/%s/transform/%s");
const std::string resourcePath = boost::str(fmt % kCrossrefWorks % doi % kCitationFormat);
// No parameters
core::http::Fields params;
// make the request
crossrefRequest(resourcePath, params, crossrefContentRequestHandler, cont);
}
} // end anonymous namespace
Error initialize()
{
ExecBlock initBlock;
initBlock.addFunctions()
(boost::bind(module_context::registerAsyncRpcMethod, "crossref_works", crossrefWorks))
(boost::bind(module_context::registerAsyncRpcMethod, "crossref_doi", crossrefDoi))
;
return initBlock.execute();
}
} // end namespace crossref
} // end namespace panmirror
} // end namespace modules
} // end namespace session
} // end namespace rstudio
<|endoftext|>
|
<commit_before>#include "overlay.hpp"
#include "../proxy/mouse_proxy.hpp"
#include "../../context.hpp"
#include "size_container.hpp"
using namespace morda;
namespace{
class context_menu_wrapper : public size_container{
public:
context_menu_wrapper(std::shared_ptr<morda::context> c, const puu::forest& desc) :
widget(std::move(c), desc),
size_container(this->context, desc)
{}
};
}
overlay::overlay(std::shared_ptr<morda::context> c, const puu::forest& desc) :
widget(std::move(c), desc),
pile(this->context, desc)
{}
std::shared_ptr<widget> overlay::show_context_menu(std::shared_ptr<widget> w, vector2 anchor){
auto c = std::make_shared<context_menu_wrapper>(this->context, puu::read(R"qwertyuiop(
layout{
dx{fill} dy{fill}
}
@mouse_proxy{
layout{
dx{fill} dy{fill}
}
x{0} y{0}
}
)qwertyuiop"));
auto& mp = *std::dynamic_pointer_cast<mouse_proxy>(c->children().back());
mp.mouse_button_handler = [](widget& w, bool is_down, const vector2& pos, mouse_button button, unsigned pointer_id) -> bool{
ASSERT(w.parent())
auto wsp = utki::make_shared_from_this(*w.parent());
w.context->run_from_ui_thread([wsp](){
wsp->remove_from_parent();
});
return false;
};
c->push_back(w);
auto& lp = c->get_layout_params(*w);
vector2 dim = this->dims_for_widget(*w, lp);
for(unsigned i = 0; i != 2; ++i){
utki::clampTop(dim[i], this->rect().d[i]);
}
w->resize(dim);
for(unsigned i = 0; i != 2; ++i){
utki::clampRange(anchor[i], 0.0f, this->rect().d[i] - w->rect().d[i]);
}
w->move_to(anchor);
auto sp = utki::make_shared_from_this(*this);
ASSERT(sp)
this->context->run_from_ui_thread([this, c, sp](){
sp->push_back(c);
});
return c;
}
void overlay::close_all_context_menus(){
while(dynamic_cast<context_menu_wrapper*>(this->children().back().get())){
this->pop_back();
}
}
<commit_msg>macosx build fix<commit_after>#include "overlay.hpp"
#include "../proxy/mouse_proxy.hpp"
#include "../../context.hpp"
#include "size_container.hpp"
using namespace morda;
namespace{
class context_menu_wrapper : public size_container{
public:
context_menu_wrapper(std::shared_ptr<morda::context> c, const puu::forest& desc) :
widget(std::move(c), desc),
size_container(this->context, desc)
{}
};
}
overlay::overlay(std::shared_ptr<morda::context> c, const puu::forest& desc) :
widget(std::move(c), desc),
pile(this->context, desc)
{}
std::shared_ptr<widget> overlay::show_context_menu(std::shared_ptr<widget> w, vector2 anchor){
auto c = std::make_shared<context_menu_wrapper>(this->context, puu::read(R"qwertyuiop(
layout{
dx{fill} dy{fill}
}
@mouse_proxy{
layout{
dx{fill} dy{fill}
}
x{0} y{0}
}
)qwertyuiop"));
auto& mp = *std::dynamic_pointer_cast<mouse_proxy>(c->children().back());
mp.mouse_button_handler = [](widget& w, bool is_down, const vector2& pos, mouse_button button, unsigned pointer_id) -> bool{
ASSERT(w.parent())
auto wsp = utki::make_shared_from_this(*w.parent());
w.context->run_from_ui_thread([wsp](){
wsp->remove_from_parent();
});
return false;
};
c->push_back(w);
auto& lp = c->get_layout_params(*w);
vector2 dim = this->dims_for_widget(*w, lp);
for(unsigned i = 0; i != 2; ++i){
utki::clampTop(dim[i], this->rect().d[i]);
}
w->resize(dim);
for(unsigned i = 0; i != 2; ++i){
utki::clampRange(anchor[i], 0.0f, this->rect().d[i] - w->rect().d[i]);
}
w->move_to(anchor);
auto sp = utki::make_shared_from_this(*this);
ASSERT(sp)
this->context->run_from_ui_thread([c, sp](){
sp->push_back(c);
});
return c;
}
void overlay::close_all_context_menus(){
while(dynamic_cast<context_menu_wrapper*>(this->children().back().get())){
this->pop_back();
}
}
<|endoftext|>
|
<commit_before>/*
* The Mana World
* Copyright (C) 2009 The Mana World Development Team
*
* This file is part of The Mana World.
*
* 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
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "net/manaserv/generalhandler.h"
#include "gui/changeemaildialog.h"
#include "gui/charselectdialog.h"
#include "gui/inventorywindow.h"
#include "gui/partywindow.h"
#include "gui/register.h"
#include "gui/skilldialog.h"
#include "gui/specialswindow.h"
#include "gui/statuswindow.h"
#include "net/manaserv/network.h"
#include "net/manaserv/connection.h"
#include "net/manaserv/beinghandler.h"
#include "net/manaserv/buysellhandler.h"
#include "net/manaserv/charhandler.h"
#include "net/manaserv/chathandler.h"
#include "net/manaserv/effecthandler.h"
#include "net/manaserv/gamehandler.h"
#include "net/manaserv/guildhandler.h"
#include "net/manaserv/inventoryhandler.h"
#include "net/manaserv/itemhandler.h"
#include "net/manaserv/loginhandler.h"
#include "net/manaserv/npchandler.h"
#include "net/manaserv/partyhandler.h"
#include "net/manaserv/playerhandler.h"
#include "net/manaserv/specialhandler.h"
#include "net/manaserv/tradehandler.h"
#include "utils/gettext.h"
#include "main.h"
#include <list>
extern Net::GeneralHandler *generalHandler;
extern ManaServ::LoginHandler *loginHandler;
namespace ManaServ {
Connection *accountServerConnection = 0;
Connection *chatServerConnection = 0;
Connection *gameServerConnection = 0;
std::string netToken = "";
ServerInfo gameServer;
ServerInfo chatServer;
GeneralHandler::GeneralHandler():
mBeingHandler(new BeingHandler),
mBuySellHandler(new BuySellHandler),
mCharHandler(new CharHandler),
mChatHandler(new ChatHandler),
mEffectHandler(new EffectHandler),
mGameHandler(new GameHandler),
mGuildHandler(new GuildHandler),
mInventoryHandler(new InventoryHandler),
mItemHandler(new ItemHandler),
mLoginHandler(new LoginHandler),
mNpcHandler(new NpcHandler),
mPartyHandler(new PartyHandler),
mPlayerHandler(new PlayerHandler),
mTradeHandler(new TradeHandler),
mSpecialHandler(new SpecialHandler)
{
initialize();
accountServerConnection = getConnection();
gameServerConnection = getConnection();
chatServerConnection = getConnection();
generalHandler = this;
std::list<ItemDB::Stat> stats;
stats.push_back(ItemDB::Stat("str", N_("Strength %+d")));
stats.push_back(ItemDB::Stat("agi", N_("Agility %+d")));
stats.push_back(ItemDB::Stat("dex", N_("Dexterity %+d")));
stats.push_back(ItemDB::Stat("vit", N_("Vitality %+d")));
stats.push_back(ItemDB::Stat("int", N_("Intelligence %+d")));
stats.push_back(ItemDB::Stat("will", N_("Willpower %+d")));
ItemDB::setStatsList(stats);
}
void GeneralHandler::load()
{
registerHandler(mBeingHandler.get());
registerHandler(mBuySellHandler.get());
registerHandler(mCharHandler.get());
registerHandler(mChatHandler.get());
registerHandler(mEffectHandler.get());
registerHandler(mGameHandler.get());
registerHandler(mGuildHandler.get());
registerHandler(mInventoryHandler.get());
registerHandler(mItemHandler.get());
registerHandler(mLoginHandler.get());
registerHandler(mNpcHandler.get());
registerHandler(mPartyHandler.get());
registerHandler(mPlayerHandler.get());
registerHandler(mTradeHandler.get());
}
void GeneralHandler::reload()
{
// Nothing needed yet
}
void GeneralHandler::unload()
{
clearHandlers();
if (accountServerConnection)
accountServerConnection->disconnect();
if (gameServerConnection)
gameServerConnection->disconnect();
if (chatServerConnection)
chatServerConnection->disconnect();
delete accountServerConnection;
delete gameServerConnection;
delete chatServerConnection;
finalize();
}
void GeneralHandler::flushNetwork()
{
flush();
if (state == STATE_SWITCH_CHARACTER &&
Net::getLoginHandler()->isConnected())
{
loginHandler->reconnect();
state = STATE_GET_CHARACTERS;
}
}
void GeneralHandler::guiWindowsLoaded()
{
inventoryWindow->setSplitAllowed(true);
partyWindow->clearPartyName();
skillDialog->loadSkills("tmw-skills.xml");
specialsWindow->loadSpecials("specials.xml");
player_node->setExpNeeded(100);
statusWindow->addAttribute(16, _("Strength"), true);
statusWindow->addAttribute(17, _("Agility"), true);
statusWindow->addAttribute(18, _("Dexterity"), true);
statusWindow->addAttribute(19, _("Vitality"), true);
statusWindow->addAttribute(20, _("Intelligence"), true);
statusWindow->addAttribute(21, _("Willpower"), true);
}
void GeneralHandler::guiWindowsUnloaded()
{
// TODO
}
void GeneralHandler::clearHandlers()
{
clearNetworkHandlers();
}
} // namespace ManaServ
<commit_msg>Update des Sourcecodes.<commit_after>/*
* The Mana World
* Copyright (C) 2009 The Mana World Development Team
*
* This file is part of The Mana World.
*
* 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
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "net/manaserv/generalhandler.h"
#include "gui/changeemaildialog.h"
#include "gui/charselectdialog.h"
#include "gui/inventorywindow.h"
#include "gui/partywindow.h"
#include "gui/register.h"
#include "gui/skilldialog.h"
#include "gui/specialswindow.h"
#include "gui/statuswindow.h"
#include "net/manaserv/network.h"
#include "net/manaserv/connection.h"
#include "net/manaserv/beinghandler.h"
#include "net/manaserv/buysellhandler.h"
#include "net/manaserv/charhandler.h"
#include "net/manaserv/chathandler.h"
#include "net/manaserv/effecthandler.h"
#include "net/manaserv/gamehandler.h"
#include "net/manaserv/guildhandler.h"
#include "net/manaserv/inventoryhandler.h"
#include "net/manaserv/itemhandler.h"
#include "net/manaserv/loginhandler.h"
#include "net/manaserv/npchandler.h"
#include "net/manaserv/partyhandler.h"
#include "net/manaserv/playerhandler.h"
#include "net/manaserv/specialhandler.h"
#include "net/manaserv/tradehandler.h"
#include "utils/gettext.h"
#include "main.h"
#include <list>
extern Net::GeneralHandler *generalHandler;
extern ManaServ::LoginHandler *loginHandler;
namespace ManaServ {
Connection *accountServerConnection = 0;
Connection *chatServerConnection = 0;
Connection *gameServerConnection = 0;
std::string netToken = "";
ServerInfo gameServer;
ServerInfo chatServer;
GeneralHandler::GeneralHandler():
mBeingHandler(new BeingHandler),
mBuySellHandler(new BuySellHandler),
mCharHandler(new CharHandler),
mChatHandler(new ChatHandler),
mEffectHandler(new EffectHandler),
mGameHandler(new GameHandler),
mGuildHandler(new GuildHandler),
mInventoryHandler(new InventoryHandler),
mItemHandler(new ItemHandler),
mLoginHandler(new LoginHandler),
mNpcHandler(new NpcHandler),
mPartyHandler(new PartyHandler),
mPlayerHandler(new PlayerHandler),
mTradeHandler(new TradeHandler),
mSpecialHandler(new SpecialHandler)
{
initialize();
accountServerConnection = getConnection();
gameServerConnection = getConnection();
chatServerConnection = getConnection();
generalHandler = this;
std::list<ItemDB::Stat> stats;
stats.push_back(ItemDB::Stat("str", N_("Strength %+d")));
stats.push_back(ItemDB::Stat("agi", N_("Agility %+d")));
stats.push_back(ItemDB::Stat("dex", N_("Dexterity %+d")));
stats.push_back(ItemDB::Stat("vit", N_("Vitality %+d")));
stats.push_back(ItemDB::Stat("int", N_("Intelligence %+d")));
stats.push_back(ItemDB::Stat("will", N_("Willpower %+d")));
ItemDB::setStatsList(stats);
}
void GeneralHandler::load()
{
registerHandler(mBeingHandler.get());
registerHandler(mBuySellHandler.get());
registerHandler(mCharHandler.get());
registerHandler(mChatHandler.get());
registerHandler(mEffectHandler.get());
registerHandler(mGameHandler.get());
registerHandler(mGuildHandler.get());
registerHandler(mInventoryHandler.get());
registerHandler(mItemHandler.get());
registerHandler(mLoginHandler.get());
registerHandler(mNpcHandler.get());
registerHandler(mPartyHandler.get());
registerHandler(mPlayerHandler.get());
registerHandler(mTradeHandler.get());
}
void GeneralHandler::reload()
{
// Nothing needed yet
}
void GeneralHandler::unload()
{
clearHandlers();
if (accountServerConnection)
accountServerConnection->disconnect();
if (gameServerConnection)
gameServerConnection->disconnect();
if (chatServerConnection)
chatServerConnection->disconnect();
delete accountServerConnection;
delete gameServerConnection;
delete chatServerConnection;
finalize();
}
void GeneralHandler::flushNetwork()
{
flush();
if (state == STATE_SWITCH_CHARACTER &&
Net::getLoginHandler()->isConnected())
{
loginHandler->reconnect();
state = STATE_GET_CHARACTERS;
}
}
void GeneralHandler::guiWindowsLoaded()
{
inventoryWindow->setSplitAllowed(true);
partyWindow->clearPartyName();
skillDialog->loadSkills("mana-skills.xml");
specialsWindow->loadSpecials("specials.xml");
player_node->setExpNeeded(100);
statusWindow->addAttribute(16, _("Strength"), true);
statusWindow->addAttribute(17, _("Agility"), true);
statusWindow->addAttribute(18, _("Dexterity"), true);
statusWindow->addAttribute(19, _("Vitality"), true);
statusWindow->addAttribute(20, _("Intelligence"), true);
statusWindow->addAttribute(21, _("Willpower"), true);
}
void GeneralHandler::guiWindowsUnloaded()
{
// TODO
}
void GeneralHandler::clearHandlers()
{
clearNetworkHandlers();
}
} // namespace ManaServ
<|endoftext|>
|
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2013 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Local includes
#include "libmesh/libmesh_singleton.h"
#include "libmesh/threads.h"
// C/C++ includes
#include <vector>
// --------------------------------------------------------
// Local anonymous namespace to hold miscelaneous bits
namespace
{
using namespace libMesh;
// Mutex object for required locking
typedef Threads::spin_mutex SingletonMutex;
SingletonMutex singleton_mtx, setup_mtx;
// global list of runtime Singleton objects - created dynamically,
// cleaned up in reverse order.
typedef std::vector<Singleton*> SingletonList;
SingletonList& get_singleton_cache()
{
static SingletonList singleton_cache;
return singleton_cache;
}
typedef std::vector<Singleton::Setup*> SetupList;
SetupList& get_setup_cache()
{
static SetupList setup_cache;
return setup_cache;
}
} // end anonymous namespace
// --------------------------------------------------------
// Local anonymous namespace to hold miscelaneous bits
namespace libMesh
{
Singleton::Singleton ()
{
SingletonMutex::scoped_lock lock(singleton_mtx);
get_singleton_cache().push_back (this);
}
Singleton::Setup::Setup ()
{
SingletonMutex::scoped_lock lock(setup_mtx);
get_setup_cache().push_back (this);
}
void Singleton::setup ()
{
SingletonMutex::scoped_lock lock(setup_mtx);
SetupList& setup_cache = get_setup_cache();
for (SetupList::iterator it = setup_cache.begin();
it!=setup_cache.end(); ++it)
{
libmesh_assert (*it != NULL);
(*it)->setup();
}
}
void Singleton::cleanup ()
{
SingletonMutex::scoped_lock lock(singleton_mtx);
SetupList& singleton_cache = get_singleton_cache();
for (SingletonList::reverse_iterator it = singleton_cache.rbegin();
it!=singleton_cache.rend(); ++it)
{
libmesh_assert (*it != NULL);
delete *it;
*it = NULL;
}
singleton_cache.clear();
}
} // namespace libMesh
<commit_msg>Fix cut-n-paste typo<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2013 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Local includes
#include "libmesh/libmesh_singleton.h"
#include "libmesh/threads.h"
// C/C++ includes
#include <vector>
// --------------------------------------------------------
// Local anonymous namespace to hold miscelaneous bits
namespace
{
using namespace libMesh;
// Mutex object for required locking
typedef Threads::spin_mutex SingletonMutex;
SingletonMutex singleton_mtx, setup_mtx;
// global list of runtime Singleton objects - created dynamically,
// cleaned up in reverse order.
typedef std::vector<Singleton*> SingletonList;
SingletonList& get_singleton_cache()
{
static SingletonList singleton_cache;
return singleton_cache;
}
typedef std::vector<Singleton::Setup*> SetupList;
SetupList& get_setup_cache()
{
static SetupList setup_cache;
return setup_cache;
}
} // end anonymous namespace
// --------------------------------------------------------
// Local anonymous namespace to hold miscelaneous bits
namespace libMesh
{
Singleton::Singleton ()
{
SingletonMutex::scoped_lock lock(singleton_mtx);
get_singleton_cache().push_back (this);
}
Singleton::Setup::Setup ()
{
SingletonMutex::scoped_lock lock(setup_mtx);
get_setup_cache().push_back (this);
}
void Singleton::setup ()
{
SingletonMutex::scoped_lock lock(setup_mtx);
SetupList& setup_cache = get_setup_cache();
for (SetupList::iterator it = setup_cache.begin();
it!=setup_cache.end(); ++it)
{
libmesh_assert (*it != NULL);
(*it)->setup();
}
}
void Singleton::cleanup ()
{
SingletonMutex::scoped_lock lock(singleton_mtx);
SingletonList& singleton_cache = get_singleton_cache();
for (SingletonList::reverse_iterator it = singleton_cache.rbegin();
it!=singleton_cache.rend(); ++it)
{
libmesh_assert (*it != NULL);
delete *it;
*it = NULL;
}
singleton_cache.clear();
}
} // namespace libMesh
<|endoftext|>
|
<commit_before>#ifndef context_hh_INCLUDED
#define context_hh_INCLUDED
#include "window.hh"
#include "client.hh"
#include "user_interface.hh"
namespace Kakoune
{
// A Context is provided to all commands, it permits
// to access a client, window, editor or buffer if available.
struct Context
{
Context() {}
Context(Editor& editor)
: m_editor(&editor) {}
Context(Client& client)
: m_client(&client) {}
// to allow func(Context(Editor(...)))
Context(Editor&& editor)
: m_editor(&editor) {}
Context(const Context&) = delete;
Context& operator=(const Context&) = delete;
Buffer& buffer() const
{
if (not has_buffer())
throw runtime_error("no buffer in context");
return m_editor->buffer();
}
bool has_buffer() const { return (bool)m_editor; }
Editor& editor() const
{
if (not has_editor())
throw runtime_error("no editor in context");
return *m_editor.get();
}
bool has_editor() const { return (bool)m_editor; }
Window& window() const
{
if (not has_window())
throw runtime_error("no window in context");
return *dynamic_cast<Window*>(m_editor.get());
}
bool has_window() const { return (bool)m_editor and dynamic_cast<Window*>(m_editor.get()); }
Client& client() const
{
if (not has_client())
throw runtime_error("no client in context");
return *m_client;
}
bool has_client() const { return (bool)m_client; }
UserInterface& ui() const
{
if (not has_ui())
throw runtime_error("no user interface in context");
return *m_ui;
}
bool has_ui() const { return (bool)m_ui; }
void change_editor(Editor& editor)
{
m_editor.reset(&editor);
}
void change_ui(UserInterface& ui)
{
m_ui.reset(&ui);
}
OptionManager& option_manager() const
{
if (has_window())
return window().option_manager();
if (has_buffer())
return buffer().option_manager();
return GlobalOptionManager::instance();
}
void draw_ifn() const
{
if (has_ui() and has_window())
ui().draw_window(window());
}
void print_status(const String& status) const
{
if (has_ui())
ui().print_status(status);
}
using Insertion = std::pair<InsertMode, std::vector<Key>>;
Insertion& last_insert() { return m_last_insert; }
int& numeric_param() { return m_numeric_param; }
private:
safe_ptr<Editor> m_editor;
safe_ptr<Client> m_client;
safe_ptr<UserInterface> m_ui;
Insertion m_last_insert = {InsertMode::Insert, {}};
int m_numeric_param = 0;
};
}
#endif // context_hh_INCLUDED
<commit_msg>Context: explicit constructors and more comments<commit_after>#ifndef context_hh_INCLUDED
#define context_hh_INCLUDED
#include "window.hh"
#include "client.hh"
#include "user_interface.hh"
namespace Kakoune
{
// A Context is used to access non singleton objects for various services
// in commands.
//
// The Context object links a Client, an Editor (which may be a Window),
// and a UserInterface. It may represent an interactive user window, or
// a hook execution or a macro replay.
struct Context
{
Context() {}
explicit Context(Editor& editor)
: m_editor(&editor) {}
explicit Context(Client& client)
: m_client(&client) {}
// to allow func(Context(Editor(...)))
// make sure the context will not survive the next ';'
explicit Context(Editor&& editor)
: m_editor(&editor) {}
Context(const Context&) = delete;
Context& operator=(const Context&) = delete;
Buffer& buffer() const
{
if (not has_buffer())
throw runtime_error("no buffer in context");
return m_editor->buffer();
}
bool has_buffer() const { return (bool)m_editor; }
Editor& editor() const
{
if (not has_editor())
throw runtime_error("no editor in context");
return *m_editor.get();
}
bool has_editor() const { return (bool)m_editor; }
Window& window() const
{
if (not has_window())
throw runtime_error("no window in context");
return *dynamic_cast<Window*>(m_editor.get());
}
bool has_window() const { return (bool)m_editor and dynamic_cast<Window*>(m_editor.get()); }
Client& client() const
{
if (not has_client())
throw runtime_error("no client in context");
return *m_client;
}
bool has_client() const { return (bool)m_client; }
UserInterface& ui() const
{
if (not has_ui())
throw runtime_error("no user interface in context");
return *m_ui;
}
bool has_ui() const { return (bool)m_ui; }
void change_editor(Editor& editor)
{
m_editor.reset(&editor);
}
void change_ui(UserInterface& ui)
{
m_ui.reset(&ui);
}
OptionManager& option_manager() const
{
if (has_window())
return window().option_manager();
if (has_buffer())
return buffer().option_manager();
return GlobalOptionManager::instance();
}
void draw_ifn() const
{
if (has_ui() and has_window())
ui().draw_window(window());
}
void print_status(const String& status) const
{
if (has_ui())
ui().print_status(status);
}
using Insertion = std::pair<InsertMode, std::vector<Key>>;
Insertion& last_insert() { return m_last_insert; }
int& numeric_param() { return m_numeric_param; }
private:
safe_ptr<Editor> m_editor;
safe_ptr<Client> m_client;
safe_ptr<UserInterface> m_ui;
Insertion m_last_insert = {InsertMode::Insert, {}};
int m_numeric_param = 0;
};
}
#endif // context_hh_INCLUDED
<|endoftext|>
|
<commit_before>// -*- C++ -*-
// httpd.conf:
//
// LoadModule acmacs_module "mod_acmacs.so"
// AddHandler acmacs .ace .save .save.xz .acd1 .acd1.xz
//
// /etc/apache2/envvars:
//
// export ACMACSD_ROOT="/home/.../AD"
#include <iostream>
#include <string>
#include <typeinfo>
#include "apache2/httpd.h"
#include "apache2/http_core.h"
#include "apache2/http_protocol.h"
#include "apache2/http_request.h"
#include "apache2/http_log.h"
#include "apache2/util_script.h"
#include "acmacs-base/filesystem.hh"
#include "acmacs-base/gzip.hh"
#include "acmacs-base/range.hh"
#include "acmacs-base/virus-name.hh"
#include "locationdb/locdb.hh"
#include "seqdb/seqdb.hh"
#include "acmacs-chart-2/chart-modify.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "acmacs-chart-2/ace-export.hh"
static void register_hooks(apr_pool_t *pool);
static int acmacs_handler(request_rec *r);
static void make_html(request_rec *r, const char* view_mode, const char* coloring);
static void make_ace(request_rec *r);
// ----------------------------------------------------------------------
extern "C" module acmacs_module;
extern "C" {
module AP_MODULE_DECLARE_DATA acmacs_module = {
STANDARD20_MODULE_STUFF, nullptr, nullptr, nullptr, nullptr, nullptr, register_hooks
};
}
APLOG_USE_MODULE(acmacs);
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wused-but-marked-unused"
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
#pragma GCC diagnostic ignored "-Wunused-macros"
#endif
static void register_hooks(apr_pool_t * /*pool*/) {
ap_hook_handler(acmacs_handler, nullptr, nullptr, APR_HOOK_LAST);
}
#define AP_WARN APLOG_MARK, APLOG_WARNING, 0
#define AP_ERR APLOG_MARK, APLOG_ERR, 0
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
static int acmacs_handler(request_rec *r) {
if (!r->handler || r->handler != std::string("acmacs"))
return DECLINED;
apr_table_t *GET;
ap_args_to_table(r, &GET);
const char* acv_c = apr_table_get(GET, "acv");
const std::string acv = acv_c ? acv_c : "";
if (!fs::exists(fs::path(r->filename)))
return HTTP_NOT_FOUND;
try {
if (acv == "html") {
const char* view_mode = apr_table_get(GET, "view-mode");
const char* coloring = apr_table_get(GET, "coloring");
make_html(r, view_mode ? view_mode : "best-projection", coloring ? coloring : "default");
}
else if (acv == "ace") {
make_ace(r);
}
else {
return DECLINED;
}
return OK;
}
catch (std::exception& err) {
ap_log_rerror(AP_ERR, r, "%s: %s", typeid(err).name(), err.what());
return HTTP_INTERNAL_SERVER_ERROR;
}
return HTTP_INTERNAL_SERVER_ERROR;
}
// ----------------------------------------------------------------------
static const char* sHtml = R"(
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>%s</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="module">
import * as acv_m from "/js/ad/map-draw/ace-view-1/ace-view.js";
const options = {view_mode: "%s", coloring: "%s"};
$(document).ready(() => new acv_m.AntigenicMapWidget($("#map1"), "%s?acv=ace", options));
</script>
</head>
<body>
<div id="map1"></div>
</body>
</html>
)";
void make_html(request_rec *r, const char* view_mode, const char* coloring)
{
// ap_log_rerror(AP_WARN, r, "uri: %s", r->uri);
// ap_log_rerror(AP_WARN, r, "path_info: %s", r->path_info);
ap_set_content_type(r, "text/html");
ap_rprintf(r, sHtml, r->filename, view_mode, coloring, r->uri);
} // make_html
// ----------------------------------------------------------------------
void make_ace(request_rec* r)
{
const auto& locdb = get_locdb(report_time::Yes);
const auto& seqdb = seqdb::get(report_time::Yes);
acmacs::chart::ChartModify chart(acmacs::chart::import_from_file(r->filename, acmacs::chart::Verify::None, report_time::No));
auto antigens = chart.antigens_modify();
// set continent info
for (auto antigen_no : acmacs::range(antigens->size())) {
auto& antigen = antigens->at(antigen_no);
if (antigen.continent().empty()) {
try {
antigen.continent(locdb.continent(virus_name::location(antigen.name())));
}
catch (std::exception& err) {
ap_log_rerror(AP_WARN, r, "cannot figure out continent for \"%s\": %s", antigen.name().data(), err.what());
}
catch (...) {
ap_log_rerror(AP_WARN, r, "cannot figure out continent for \"%s\": unknown exception", antigen.name().data());
}
}
}
// set clade info
for (auto antigen_no : acmacs::range(antigens->size())) {
auto& antigen = antigens->at(antigen_no);
try {
const auto* entry_seq = seqdb.find_hi_name(antigen.full_name());
if (entry_seq) {
for (const auto& clade : entry_seq->seq().clades()) {
antigen.add_clade(clade);
}
}
}
catch (std::exception& err) {
ap_log_rerror(AP_WARN, r, "cannot figure out clade for \"%s\": %s", antigen.name().data(), err.what());
}
catch (...) {
ap_log_rerror(AP_WARN, r, "cannot figure out clade for \"%s\": unknown exception", antigen.name().data());
}
}
ap_set_content_type(r, "application/json");
r->content_encoding = "gzip";
const auto exported = ace_export(chart, "mod_acmacs");
const auto compressed = acmacs::file::gzip_compress(exported);
ap_rwrite(compressed.data(), static_cast<int>(compressed.size()), r);
} // make_ace
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>exporting ace without json pretty printing for apache mod_acmacs<commit_after>// -*- C++ -*-
// httpd.conf:
//
// LoadModule acmacs_module "mod_acmacs.so"
// AddHandler acmacs .ace .save .save.xz .acd1 .acd1.xz
//
// /etc/apache2/envvars:
//
// export ACMACSD_ROOT="/home/.../AD"
#include <iostream>
#include <string>
#include <typeinfo>
#include "apache2/httpd.h"
#include "apache2/http_core.h"
#include "apache2/http_protocol.h"
#include "apache2/http_request.h"
#include "apache2/http_log.h"
#include "apache2/util_script.h"
#include "acmacs-base/filesystem.hh"
#include "acmacs-base/gzip.hh"
#include "acmacs-base/range.hh"
#include "acmacs-base/virus-name.hh"
#include "locationdb/locdb.hh"
#include "seqdb/seqdb.hh"
#include "acmacs-chart-2/chart-modify.hh"
#include "acmacs-chart-2/factory-import.hh"
#include "acmacs-chart-2/ace-export.hh"
static void register_hooks(apr_pool_t *pool);
static int acmacs_handler(request_rec *r);
static void make_html(request_rec *r, const char* view_mode, const char* coloring);
static void make_ace(request_rec *r);
// ----------------------------------------------------------------------
extern "C" module acmacs_module;
extern "C" {
module AP_MODULE_DECLARE_DATA acmacs_module = {
STANDARD20_MODULE_STUFF, nullptr, nullptr, nullptr, nullptr, nullptr, register_hooks
};
}
APLOG_USE_MODULE(acmacs);
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wused-but-marked-unused"
#pragma GCC diagnostic ignored "-Wformat-nonliteral"
#pragma GCC diagnostic ignored "-Wunused-macros"
#endif
static void register_hooks(apr_pool_t * /*pool*/) {
ap_hook_handler(acmacs_handler, nullptr, nullptr, APR_HOOK_LAST);
}
#define AP_WARN APLOG_MARK, APLOG_WARNING, 0
#define AP_ERR APLOG_MARK, APLOG_ERR, 0
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
static int acmacs_handler(request_rec *r) {
if (!r->handler || r->handler != std::string("acmacs"))
return DECLINED;
apr_table_t *GET;
ap_args_to_table(r, &GET);
const char* acv_c = apr_table_get(GET, "acv");
const std::string acv = acv_c ? acv_c : "";
if (!fs::exists(fs::path(r->filename)))
return HTTP_NOT_FOUND;
try {
if (acv == "html") {
const char* view_mode = apr_table_get(GET, "view-mode");
const char* coloring = apr_table_get(GET, "coloring");
make_html(r, view_mode ? view_mode : "best-projection", coloring ? coloring : "default");
}
else if (acv == "ace") {
make_ace(r);
}
else {
return DECLINED;
}
return OK;
}
catch (std::exception& err) {
ap_log_rerror(AP_ERR, r, "%s: %s", typeid(err).name(), err.what());
return HTTP_INTERNAL_SERVER_ERROR;
}
return HTTP_INTERNAL_SERVER_ERROR;
}
// ----------------------------------------------------------------------
static const char* sHtml = R"(
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>%s</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="module">
import * as acv_m from "/js/ad/map-draw/ace-view-1/ace-view.js";
const options = {view_mode: "%s", coloring: "%s"};
$(document).ready(() => new acv_m.AntigenicMapWidget($("#map1"), "%s?acv=ace", options));
</script>
</head>
<body>
<div id="map1"></div>
</body>
</html>
)";
void make_html(request_rec *r, const char* view_mode, const char* coloring)
{
// ap_log_rerror(AP_WARN, r, "uri: %s", r->uri);
// ap_log_rerror(AP_WARN, r, "path_info: %s", r->path_info);
ap_set_content_type(r, "text/html");
ap_rprintf(r, sHtml, r->filename, view_mode, coloring, r->uri);
} // make_html
// ----------------------------------------------------------------------
void make_ace(request_rec* r)
{
const auto& locdb = get_locdb(report_time::Yes);
const auto& seqdb = seqdb::get(report_time::Yes);
acmacs::chart::ChartModify chart(acmacs::chart::import_from_file(r->filename, acmacs::chart::Verify::None, report_time::No));
auto antigens = chart.antigens_modify();
// set continent info
for (auto antigen_no : acmacs::range(antigens->size())) {
auto& antigen = antigens->at(antigen_no);
if (antigen.continent().empty()) {
try {
antigen.continent(locdb.continent(virus_name::location(antigen.name())));
}
catch (std::exception& err) {
ap_log_rerror(AP_WARN, r, "cannot figure out continent for \"%s\": %s", antigen.name().data(), err.what());
}
catch (...) {
ap_log_rerror(AP_WARN, r, "cannot figure out continent for \"%s\": unknown exception", antigen.name().data());
}
}
}
// set clade info
for (auto antigen_no : acmacs::range(antigens->size())) {
auto& antigen = antigens->at(antigen_no);
try {
const auto* entry_seq = seqdb.find_hi_name(antigen.full_name());
if (entry_seq) {
for (const auto& clade : entry_seq->seq().clades()) {
antigen.add_clade(clade);
}
}
}
catch (std::exception& err) {
ap_log_rerror(AP_WARN, r, "cannot figure out clade for \"%s\": %s", antigen.name().data(), err.what());
}
catch (...) {
ap_log_rerror(AP_WARN, r, "cannot figure out clade for \"%s\": unknown exception", antigen.name().data());
}
}
ap_set_content_type(r, "application/json");
r->content_encoding = "gzip";
const auto exported = ace_export(chart, "mod_acmacs", 0);
const auto compressed = acmacs::file::gzip_compress(exported);
ap_rwrite(compressed.data(), static_cast<int>(compressed.size()), r);
} // make_ace
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>
|
<commit_before><commit_msg>Added a comment.<commit_after><|endoftext|>
|
<commit_before>//
// Reference : Chapter 6, "Introduction to Algorithms 3rd ed", aka CLRS.
//
#pragma once
#include <vector>
#include <functional>
#include <stdexcept>
#include <algorithm>
using std::move;
using std::find_if;
namespace search
{
//
// parent
// O(1)
//
template<typename Iterator>
auto inline parent(Iterator first, Iterator it) -> Iterator
{
return first + (it - first - 1) / 2;
}
//
// left_child
// O(1)
//
template<typename Iterator>
auto inline left_child(Iterator first, Iterator last, Iterator it) -> Iterator
{
auto size = last - first;
auto offset = 2 * (it - first) + 1;
return offset > size ? last : first + offset;
}
//
// right_child
// O(1)
//
template<typename Iterator>
auto inline right_child(Iterator first, Iterator last, Iterator it) -> Iterator
{
auto left = left_child(first, last, it);
return left != last ? left + 1 : last;
}
//
// heapify
// O(lg n)
// maintain heap's peroperties with a float down way
//
template<typename Iterator, typename CompareFunc>
auto heapify(Iterator first, Iterator last, Iterator curr, CompareFunc && compare) -> void
{
while (true)
{
auto left = left_child(first, last, curr);
auto right = right_child(first, last, curr);
//! find max or min amoung curr, left and right children, depending on the CommpareFunc passed in.
auto max_min = (left != last && compare(*left, *curr)) ? left : curr;
if (right != last && compare(*right, *max_min)) max_min = right;
//! exchange.
if (max_min != curr)
{
std::swap(*max_min, *curr);
curr = max_min;
}
else
{
return;
}
}
}
//
// build_heap
// O(n)
//
template<typename Iterator, typename CompareFunc>
auto inline build_heap(Iterator first, Iterator last, CompareFunc && compare) -> void
{
auto size = last - first;
for (auto curr = first + size / 2 - 1; /* */; --curr)
{
heapify(first, last, curr, compare);
if (curr == first) return;
}
}
template<typename Iterator, typename CompareFunc>
auto inline sift_up(Iterator first, Iterator curr, CompareFunc && compare) -> bool
{
auto c = curr;
auto p = [&] { return parent(first, c); };
auto is_needed = [&] { return c != first && !compare(*p(), *c); };
if (!is_needed()) return false;
for (; is_needed(); c = p()) std::swap(*p(), *c);
return true;
}
//
// PriorityQueue
//
template<typename Value, typename CompareFunc>
class PriorityQueue
{
public:
using Vector = std::vector < Value >;
using SizeType = typename Vector::size_type;
using Iterator = typename Vector::iterator;
PriorityQueue() = default;
PriorityQueue(CompareFunc c)
: _seq{}, _compare{ c }
{ }
PriorityQueue(std::initializer_list<Value>&& list, CompareFunc&& c)
: _seq(std::move(list)), _compare{ std::move(c) }
{
if (!empty())
build_heap(_seq.begin(), _seq.end(), _compare);
}
template<typename Iterator>
PriorityQueue(Iterator first, Iterator last, CompareFunc&& c)
: _seq(first, last), _compare{ std::move(c) }
{
if (!empty())
build_heap(_seq.begin(), _seq.end(), _compare);
}
auto top() const -> Value const&
{
return _seq.front();
}
auto size() const -> SizeType
{
return _seq.size();
}
auto empty() const -> bool
{
return _seq.empty();
}
auto contains(Value const& value) const -> bool
{
return _seq.cend() != std::find(_seq.cbegin(), _seq.cend(), value);
}
template<typename Predicate>
auto any(Predicate predicate) const -> bool
{
return std::any_of(_seq.cbegin(), _seq.cend(), predicate);
}
auto push(Value const& new_val) -> void
{
// find the right place for new_val
_seq.resize(size() + 1);
auto curr = _seq.end() - 1;
for (; curr > _seq.begin() && _compare(new_val, *parent(_seq.begin(), curr)); curr = parent(_seq.begin(), curr))
*curr = *parent(_seq.begin(), curr);
// insert
*curr = new_val;
}
auto pop() -> Value
{
if (empty())
throw std::underflow_error{ "underflow." };
auto popped = _seq.front();
_seq.front() = _seq.back();
_seq.resize(_seq.size() - 1);
heapify(_seq.begin(), _seq.end(), _seq.begin(), _compare);
return popped;
}
auto remove(Value const& item) -> void
{
auto it = std::find(_seq.begin(), _seq.end(), item);
if (_seq.end() != it)
remove(it);
}
//
// O(lg n)
//
auto substitute(Value const& old_value, Value const& new_value) -> void
{
remove(old_value);
push(new_value);
}
template<typename Predicate>
auto update_with_if(Value const& new_value, Predicate predicate) -> void
{
auto iterator = find_if(_seq.begin(), _seq.end(), [&](Value const& value) {
return predicate(value);
});
if (iterator != _seq.end() && _compare(new_value, *iterator))
substitute(*iterator, new_value);
}
void reset()
{
_seq.clear();
}
void reset(CompareFunc && c)
{
_compare = move(c);
reset();
}
private:
Vector _seq;
CompareFunc _compare;
//
// Make sure vector is not empty.
// O(lg n)
//
template<typename Iterator>
auto remove(Iterator at) -> void
{
std::swap(*at, *(_seq.end() - 1));
if (!sift_up(_seq.begin(), at, _compare))
heapify(_seq.begin(), _seq.end() - 1, at, _compare);//avoid involving the last item.
_seq.resize(size() - 1);
}
};
}<commit_msg>polishing modified: planning/lib/priority_queue.hpp<commit_after>//
// Reference : Chapter 6, "Introduction to Algorithms 3rd ed", aka CLRS.
//
#pragma once
#include <vector>
#include <functional>
#include <stdexcept>
#include <algorithm>
using std::move;
using std::find_if;
using std::swap;
namespace search
{
//
// parent
// O(1)
//
template<typename Iterator>
auto inline parent(Iterator first, Iterator it) -> Iterator
{
return first + (it - first - 1) / 2;
}
//
// left_child
// O(1)
//
template<typename Iterator>
auto inline left_child(Iterator first, Iterator last, Iterator it) -> Iterator
{
auto size = last - first;
auto offset = 2 * (it - first) + 1;
return offset > size ? last : first + offset;
}
//
// right_child
// O(1)
//
template<typename Iterator>
auto inline right_child(Iterator first, Iterator last, Iterator it) -> Iterator
{
auto left = left_child(first, last, it);
return left != last ? left + 1 : last;
}
//
// heapify
// O(lg n)
// maintain heap's peroperties with a float down way
//
template<typename Iterator, typename CompareFunc>
auto heapify(Iterator first, Iterator last, Iterator curr, CompareFunc && compare) -> void
{
while (true)
{
auto left = left_child(first, last, curr);
auto right = right_child(first, last, curr);
//! find max or min amoung curr, left and right children, depending on the CommpareFunc passed in.
auto max_min = (left != last && compare(*left, *curr)) ? left : curr;
if (right != last && compare(*right, *max_min)) max_min = right;
if (curr == max_min) return;
//! exchange.
swap(*max_min, *curr);
curr = max_min;
}
}
//
// build_heap
// O(n)
//
template<typename Iterator, typename CompareFunc>
auto inline build_heap(Iterator first, Iterator last, CompareFunc && compare) -> void
{
auto size = last - first;
for (auto curr = first + size / 2 - 1; /* */; --curr)
{
heapify(first, last, curr, compare);
if (curr == first) return;
}
}
template<typename Iterator, typename CompareFunc>
auto inline sift_up(Iterator first, Iterator curr, CompareFunc && compare) -> bool
{
auto c = curr;
auto p = [&] { return parent(first, c); };
auto is_needed = [&] { return c != first && !compare(*p(), *c); };
if (!is_needed()) return false;
for (; is_needed(); c = p()) std::swap(*p(), *c);
return true;
}
//
// PriorityQueue
//
template<typename Value, typename CompareFunc>
class PriorityQueue
{
public:
using Vector = std::vector < Value >;
using SizeType = typename Vector::size_type;
using Iterator = typename Vector::iterator;
PriorityQueue() = default;
PriorityQueue(CompareFunc c)
: _seq{}, _compare{ c }
{ }
PriorityQueue(std::initializer_list<Value>&& list, CompareFunc&& c)
: _seq(std::move(list)), _compare{ std::move(c) }
{
if (!empty())
build_heap(_seq.begin(), _seq.end(), _compare);
}
template<typename Iterator>
PriorityQueue(Iterator first, Iterator last, CompareFunc&& c)
: _seq(first, last), _compare{ std::move(c) }
{
if (!empty())
build_heap(_seq.begin(), _seq.end(), _compare);
}
auto top() const -> Value const&
{
return _seq.front();
}
auto size() const -> SizeType
{
return _seq.size();
}
auto empty() const -> bool
{
return _seq.empty();
}
auto contains(Value const& value) const -> bool
{
return _seq.cend() != std::find(_seq.cbegin(), _seq.cend(), value);
}
template<typename Predicate>
auto any(Predicate predicate) const -> bool
{
return std::any_of(_seq.cbegin(), _seq.cend(), predicate);
}
auto push(Value const& new_val) -> void
{
// find the right place for new_val
_seq.resize(size() + 1);
auto curr = _seq.end() - 1;
for (; curr > _seq.begin() && _compare(new_val, *parent(_seq.begin(), curr)); curr = parent(_seq.begin(), curr))
*curr = *parent(_seq.begin(), curr);
// insert
*curr = new_val;
}
auto pop() -> Value
{
if (empty())
throw std::underflow_error{ "underflow." };
auto popped = _seq.front();
_seq.front() = _seq.back();
_seq.resize(_seq.size() - 1);
heapify(_seq.begin(), _seq.end(), _seq.begin(), _compare);
return popped;
}
auto remove(Value const& item) -> void
{
auto it = std::find(_seq.begin(), _seq.end(), item);
if (_seq.end() != it)
remove(it);
}
//
// O(lg n)
//
auto substitute(Value const& old_value, Value const& new_value) -> void
{
remove(old_value);
push(new_value);
}
template<typename Predicate>
auto update_with_if(Value const& new_value, Predicate predicate) -> void
{
auto iterator = find_if(_seq.begin(), _seq.end(), [&](Value const& value) {
return predicate(value);
});
if (iterator != _seq.end() && _compare(new_value, *iterator))
substitute(*iterator, new_value);
}
void reset()
{
_seq.clear();
}
void reset(CompareFunc && c)
{
_compare = move(c);
reset();
}
private:
Vector _seq;
CompareFunc _compare;
//
// Make sure vector is not empty.
// O(lg n)
//
template<typename Iterator>
auto remove(Iterator at) -> void
{
std::swap(*at, *(_seq.end() - 1));
if (!sift_up(_seq.begin(), at, _compare))
heapify(_seq.begin(), _seq.end() - 1, at, _compare);//avoid involving the last item.
_seq.resize(size() - 1);
}
};
}<|endoftext|>
|
<commit_before>#include "logger_metrics_mongo.h"
#include "mongo/bson/bson.h"
#include "mongo/util/net/hostandport.h"
#include "jml/utils/string_functions.h"
namespace Datacratic{
using namespace std;
using namespace mongo;
LoggerMetricsMongo::LoggerMetricsMongo(Json::Value config,
const string& coll, const string& appName) : ILoggerMetrics(coll)
{
for(string s: {"hostAndPort", "database", "user", "pwd"}){
if(config[s].isNull()){
throw ML::Exception("Missing LoggerMetricsMongo parameter [%s]",
s.c_str());
}
}
vector<string> hapStrs = ML::split(config["hostAndPort"].asString(), ',');
if (hapStrs.size() > 1) {
vector<HostAndPort> haps;
for (const string & hapStr: hapStrs) {
haps.emplace_back(hapStr);
}
conn.reset(new mongo::DBClientReplicaSet(hapStrs[0], haps, 100));
}
else {
std::shared_ptr<DBClientConnection> tmpConn =
make_shared<DBClientConnection>();
tmpConn->connect(hapStrs[0]);
conn = tmpConn;
}
db = config["database"].asString();
string err;
if(!conn->auth(db, config["user"].asString(),
config["pwd"].asString(), err))
{
cerr << __FILE__ << ":" << __LINE__ << endl;
throw ML::Exception(
"MongoDB connection failed with msg [%s]", err.c_str());
}
BSONObj obj = BSON(GENOID);
conn->insert(db + "." + coll, obj);
objectId = obj["_id"].OID();
logToTerm = config["logToTerm"].asBool();
}
void LoggerMetricsMongo::logInCategory(const string& category,
const Json::Value& json)
{
BSONObjBuilder bson;
vector<string> stack;
function<void(const Json::Value&)> doit;
auto format = [](const Json::Value& v) -> string{
string str = v.toString();
if(v.isInt() || v.isUInt() || v.isDouble() || v.isNumeric()){
return str.substr(0, str.length() - 1);
}
return str.substr(1, str.length() - 3);
};
doit = [&](const Json::Value& v){
for(auto it = v.begin(); it != v.end(); ++it){
if(v[it.memberName()].isObject()){
stack.push_back(it.memberName());
doit(v[it.memberName()]);
stack.pop_back();
}else{
Json::Value current = v[it.memberName()];
stringstream key;
key << category;
for(string s: stack){
key << "." << s;
}
key << "." << it.memberName();
if(current.isArray()){
BSONArrayBuilder arr;
for(const Json::Value el: current){
arr.append(format(el));
}
bson.append(key.str(), arr.arr());
}else{
bson.append(key.str(), format(current));
}
}
}
};
doit(json);
if(logToTerm){
cout << objectId << "." << coll << "." << category
<< ": " << json.toStyledString() << endl;
}
conn->update(db + "." + coll,
BSON("_id" << objectId),
BSON("$set" << bson.obj()),
true);
}
void LoggerMetricsMongo
::logInCategory(const std::string& category,
const std::vector<std::string>& path,
const NumOrStr& val)
{
if(path.size() == 0){
throw new ML::Exception(
"You need to specify a path where to log the value");
}
stringstream ss;
ss << val;
stringstream newCat;
newCat << category;
for(string part: path){
newCat << "." << part;
}
string newCatStr = newCat.str();
string str = ss.str();
if(logToTerm){
cout << newCatStr << ": " << str << endl;
}
conn->update(db + "." + coll,
BSON("_id" << objectId),
BSON("$set"
<< BSON(newCatStr << str)),
true);
}
const std::string LoggerMetricsMongo::getProcessId() const{
return objectId.toString();
}
}//namespace Datacratic
<commit_msg>Removed debug line<commit_after>#include "logger_metrics_mongo.h"
#include "mongo/bson/bson.h"
#include "mongo/util/net/hostandport.h"
#include "jml/utils/string_functions.h"
namespace Datacratic{
using namespace std;
using namespace mongo;
LoggerMetricsMongo::LoggerMetricsMongo(Json::Value config,
const string& coll, const string& appName) : ILoggerMetrics(coll)
{
for(string s: {"hostAndPort", "database", "user", "pwd"}){
if(config[s].isNull()){
throw ML::Exception("Missing LoggerMetricsMongo parameter [%s]",
s.c_str());
}
}
vector<string> hapStrs = ML::split(config["hostAndPort"].asString(), ',');
if (hapStrs.size() > 1) {
vector<HostAndPort> haps;
for (const string & hapStr: hapStrs) {
haps.emplace_back(hapStr);
}
conn.reset(new mongo::DBClientReplicaSet(hapStrs[0], haps, 100));
}
else {
std::shared_ptr<DBClientConnection> tmpConn =
make_shared<DBClientConnection>();
tmpConn->connect(hapStrs[0]);
conn = tmpConn;
}
db = config["database"].asString();
string err;
if(!conn->auth(db, config["user"].asString(),
config["pwd"].asString(), err))
{
throw ML::Exception(
"MongoDB connection failed with msg [%s]", err.c_str());
}
BSONObj obj = BSON(GENOID);
conn->insert(db + "." + coll, obj);
objectId = obj["_id"].OID();
logToTerm = config["logToTerm"].asBool();
}
void LoggerMetricsMongo::logInCategory(const string& category,
const Json::Value& json)
{
BSONObjBuilder bson;
vector<string> stack;
function<void(const Json::Value&)> doit;
auto format = [](const Json::Value& v) -> string{
string str = v.toString();
if(v.isInt() || v.isUInt() || v.isDouble() || v.isNumeric()){
return str.substr(0, str.length() - 1);
}
return str.substr(1, str.length() - 3);
};
doit = [&](const Json::Value& v){
for(auto it = v.begin(); it != v.end(); ++it){
if(v[it.memberName()].isObject()){
stack.push_back(it.memberName());
doit(v[it.memberName()]);
stack.pop_back();
}else{
Json::Value current = v[it.memberName()];
stringstream key;
key << category;
for(string s: stack){
key << "." << s;
}
key << "." << it.memberName();
if(current.isArray()){
BSONArrayBuilder arr;
for(const Json::Value el: current){
arr.append(format(el));
}
bson.append(key.str(), arr.arr());
}else{
bson.append(key.str(), format(current));
}
}
}
};
doit(json);
if(logToTerm){
cout << objectId << "." << coll << "." << category
<< ": " << json.toStyledString() << endl;
}
conn->update(db + "." + coll,
BSON("_id" << objectId),
BSON("$set" << bson.obj()),
true);
}
void LoggerMetricsMongo
::logInCategory(const std::string& category,
const std::vector<std::string>& path,
const NumOrStr& val)
{
if(path.size() == 0){
throw new ML::Exception(
"You need to specify a path where to log the value");
}
stringstream ss;
ss << val;
stringstream newCat;
newCat << category;
for(string part: path){
newCat << "." << part;
}
string newCatStr = newCat.str();
string str = ss.str();
if(logToTerm){
cout << newCatStr << ": " << str << endl;
}
conn->update(db + "." + coll,
BSON("_id" << objectId),
BSON("$set"
<< BSON(newCatStr << str)),
true);
}
const std::string LoggerMetricsMongo::getProcessId() const{
return objectId.toString();
}
}//namespace Datacratic
<|endoftext|>
|
<commit_before>#include "filesystem.h"
#include <sstream>
#include <algorithm>
namespace alpr
{
bool startsWith(std::string const &fullString, std::string const &prefix)
{
if(fullString.substr(0, prefix.size()).compare(prefix) == 0) {
return true;
}
return false;
}
bool hasEnding (std::string const &fullString, std::string const &ending)
{
if (fullString.length() >= ending.length())
{
return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));
}
else
{
return false;
}
}
bool hasEndingInsensitive(const std::string& fullString, const std::string& ending)
{
if (fullString.length() < ending.length())
return false;
int startidx = fullString.length() - ending.length();
for (unsigned int i = startidx; i < fullString.length(); ++i)
if (tolower(fullString[i]) != tolower(ending[i - startidx]))
return false;
return true;
}
bool DirectoryExists( const char* pzPath )
{
if ( pzPath == NULL) return false;
DIR *pDir;
bool bExists = false;
pDir = opendir (pzPath);
if (pDir != NULL)
{
bExists = true;
(void) closedir (pDir);
}
return bExists;
}
bool fileExists( const char* pzPath )
{
if (pzPath == NULL) return false;
bool fExists = false;
std::ifstream f(pzPath);
fExists = f.is_open();
f.close();
return fExists;
}
std::vector<std::string> getFilesInDir(const char* dirPath)
{
DIR *dir;
std::vector<std::string> files;
struct dirent *ent;
if ((dir = opendir (dirPath)) != NULL)
{
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL)
{
if (strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "..") != 0)
files.push_back(ent->d_name);
}
closedir (dir);
}
else
{
/* could not open directory */
perror ("");
return files;
}
return files;
}
bool stringCompare( const std::string &left, const std::string &right )
{
for( std::string::const_iterator lit = left.begin(), rit = right.begin(); lit != left.end() && rit != right.end(); ++lit, ++rit )
if( tolower( *lit ) < tolower( *rit ) )
return true;
else if( tolower( *lit ) > tolower( *rit ) )
return false;
if( left.size() < right.size() )
return true;
return false;
}
std::string filenameWithoutExtension(std::string filename)
{
int lastslash = filename.find_last_of("/");
if (lastslash >= filename.size())
lastslash = 0;
else
lastslash += 1;
int lastindex = filename.find_last_of(".");
return filename.substr(lastslash, lastindex - lastslash);
}
std::string get_filename_from_path(std::string file_path)
{
size_t found;
found=file_path.find_last_of("/\\");
if (found >= 0)
return file_path.substr(found+1);
return "";
}
std::string get_directory_from_path(std::string file_path)
{
if (DirectoryExists(file_path.c_str()))
return file_path;
size_t found;
found=file_path.find_last_of("/\\");
if (found >= 0)
return file_path.substr(0,found);
return "";
}
#ifdef WINDOWS
// Stub out these functions on Windows. They're used for the daemon anyway, which isn't supported on Windows.
static int makeDir(const char *path, mode_t mode) { return 0; }
bool makePath(const char* path, mode_t mode) {
std::stringstream pathstream;
pathstream << "mkdir " << path;
std::string candidate_path = pathstream.str();
std::replace(candidate_path.begin(), candidate_path.end(), '/', '\\');
system(candidate_path.c_str());
return true;
}
FileInfo getFileInfo(std::string filename) {
FileInfo response;
response.creation_time = 0;
response.size = 0;
return response;
}
#else
FileInfo getFileInfo(std::string filename)
{
FileInfo response;
struct stat stat_buf;
int rc = stat(filename.c_str(), &stat_buf);
//return rc == 0 ? stat_buf.st_size : -1;
// 512 bytes is the standard block size
if (rc == 0)
{
#if defined(__APPLE__)
double milliseconds = (stat_buf.st_ctimespec.tv_sec * 1000) + (((double) stat_buf.st_ctimespec.tv_nsec) / 1000000.0);
#else
double milliseconds = (stat_buf.st_ctim.tv_sec * 1000) + (((double) stat_buf.st_ctim.tv_nsec) / 1000000.0);
#endif
response.size = 512 * stat_buf.st_blocks;
response.creation_time = (int64_t) milliseconds;
}
else
{
response.creation_time = 0;
response.size = 0;
}
return response;
}
static int makeDir(const char *path, mode_t mode)
{
struct stat st;
int status = 0;
if (stat(path, &st) != 0)
{
/* Directory does not exist. EEXIST for race condition */
if (mkdir(path, mode) != 0 && errno != EEXIST)
status = -1;
}
else if (!S_ISDIR(st.st_mode))
{
errno = ENOTDIR;
status = -1;
}
return(status);
}
/**
** makePath - ensure all directories in path exist
** Algorithm takes the pessimistic view and works top-down to ensure
** each directory in path exists, rather than optimistically creating
** the last element and working backwards.
*/
bool makePath(const char* path, mode_t mode)
{
char *pp;
char *sp;
int status;
char *copypath = strdup(path);
status = 0;
pp = copypath;
while (status == 0 && (sp = strchr(pp, '/')) != 0)
{
if (sp != pp)
{
/* Neither root nor double slash in path */
*sp = '\0';
status = makeDir(copypath, mode);
*sp = '/';
}
pp = sp + 1;
}
if (status == 0)
status = makeDir(path, mode);
free(copypath);
return (status == 0);
}
#endif
}
<commit_msg>Fix ifs that were always true<commit_after>#include "filesystem.h"
#include <sstream>
#include <algorithm>
namespace alpr
{
bool startsWith(std::string const &fullString, std::string const &prefix)
{
if(fullString.substr(0, prefix.size()).compare(prefix) == 0) {
return true;
}
return false;
}
bool hasEnding (std::string const &fullString, std::string const &ending)
{
if (fullString.length() >= ending.length())
{
return (0 == fullString.compare (fullString.length() - ending.length(), ending.length(), ending));
}
else
{
return false;
}
}
bool hasEndingInsensitive(const std::string& fullString, const std::string& ending)
{
if (fullString.length() < ending.length())
return false;
int startidx = fullString.length() - ending.length();
for (unsigned int i = startidx; i < fullString.length(); ++i)
if (tolower(fullString[i]) != tolower(ending[i - startidx]))
return false;
return true;
}
bool DirectoryExists( const char* pzPath )
{
if ( pzPath == NULL) return false;
DIR *pDir;
bool bExists = false;
pDir = opendir (pzPath);
if (pDir != NULL)
{
bExists = true;
(void) closedir (pDir);
}
return bExists;
}
bool fileExists( const char* pzPath )
{
if (pzPath == NULL) return false;
bool fExists = false;
std::ifstream f(pzPath);
fExists = f.is_open();
f.close();
return fExists;
}
std::vector<std::string> getFilesInDir(const char* dirPath)
{
DIR *dir;
std::vector<std::string> files;
struct dirent *ent;
if ((dir = opendir (dirPath)) != NULL)
{
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL)
{
if (strcmp(ent->d_name, ".") != 0 && strcmp(ent->d_name, "..") != 0)
files.push_back(ent->d_name);
}
closedir (dir);
}
else
{
/* could not open directory */
perror ("");
return files;
}
return files;
}
bool stringCompare( const std::string &left, const std::string &right )
{
for( std::string::const_iterator lit = left.begin(), rit = right.begin(); lit != left.end() && rit != right.end(); ++lit, ++rit )
if( tolower( *lit ) < tolower( *rit ) )
return true;
else if( tolower( *lit ) > tolower( *rit ) )
return false;
if( left.size() < right.size() )
return true;
return false;
}
std::string filenameWithoutExtension(std::string filename)
{
int lastslash = filename.find_last_of("/");
if (lastslash >= filename.size())
lastslash = 0;
else
lastslash += 1;
int lastindex = filename.find_last_of(".");
return filename.substr(lastslash, lastindex - lastslash);
}
std::string get_filename_from_path(std::string file_path)
{
size_t found;
found=file_path.find_last_of("/\\");
if (found != std::string::npos)
return file_path.substr(found+1);
return "";
}
std::string get_directory_from_path(std::string file_path)
{
if (DirectoryExists(file_path.c_str()))
return file_path;
size_t found;
found=file_path.find_last_of("/\\");
if (found != std::string::npos)
return file_path.substr(0,found);
return "";
}
#ifdef WINDOWS
// Stub out these functions on Windows. They're used for the daemon anyway, which isn't supported on Windows.
static int makeDir(const char *path, mode_t mode) { return 0; }
bool makePath(const char* path, mode_t mode) {
std::stringstream pathstream;
pathstream << "mkdir " << path;
std::string candidate_path = pathstream.str();
std::replace(candidate_path.begin(), candidate_path.end(), '/', '\\');
system(candidate_path.c_str());
return true;
}
FileInfo getFileInfo(std::string filename) {
FileInfo response;
response.creation_time = 0;
response.size = 0;
return response;
}
#else
FileInfo getFileInfo(std::string filename)
{
FileInfo response;
struct stat stat_buf;
int rc = stat(filename.c_str(), &stat_buf);
//return rc == 0 ? stat_buf.st_size : -1;
// 512 bytes is the standard block size
if (rc == 0)
{
#if defined(__APPLE__)
double milliseconds = (stat_buf.st_ctimespec.tv_sec * 1000) + (((double) stat_buf.st_ctimespec.tv_nsec) / 1000000.0);
#else
double milliseconds = (stat_buf.st_ctim.tv_sec * 1000) + (((double) stat_buf.st_ctim.tv_nsec) / 1000000.0);
#endif
response.size = 512 * stat_buf.st_blocks;
response.creation_time = (int64_t) milliseconds;
}
else
{
response.creation_time = 0;
response.size = 0;
}
return response;
}
static int makeDir(const char *path, mode_t mode)
{
struct stat st;
int status = 0;
if (stat(path, &st) != 0)
{
/* Directory does not exist. EEXIST for race condition */
if (mkdir(path, mode) != 0 && errno != EEXIST)
status = -1;
}
else if (!S_ISDIR(st.st_mode))
{
errno = ENOTDIR;
status = -1;
}
return(status);
}
/**
** makePath - ensure all directories in path exist
** Algorithm takes the pessimistic view and works top-down to ensure
** each directory in path exists, rather than optimistically creating
** the last element and working backwards.
*/
bool makePath(const char* path, mode_t mode)
{
char *pp;
char *sp;
int status;
char *copypath = strdup(path);
status = 0;
pp = copypath;
while (status == 0 && (sp = strchr(pp, '/')) != 0)
{
if (sp != pp)
{
/* Neither root nor double slash in path */
*sp = '\0';
status = makeDir(copypath, mode);
*sp = '/';
}
pp = sp + 1;
}
if (status == 0)
status = makeDir(path, mode);
free(copypath);
return (status == 0);
}
#endif
}
<|endoftext|>
|
<commit_before>/* Copyright (c) 2008-2019 the MRtrix3 contributors.
*
* 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/.
*
* Covered Software is provided under this License on an "as is"
* basis, without warranty of any kind, either expressed, implied, or
* statutory, including, without limitation, warranties that the
* Covered Software is free of defects, merchantable, fit for a
* particular purpose or non-infringing.
* See the Mozilla Public License v. 2.0 for more details.
*
* For more details, see http://www.mrtrix.org/.
*/
#include "command.h"
#include "header.h"
#include "image.h"
#include "phase_encoding.h"
#include "algo/threaded_loop.h"
#include "dwi/gradient.h"
#include "dwi/shells.h"
#include "dwi/sdeconv/csd.h"
#include "dwi/sdeconv/msmt_csd.h"
#include "math/SH.h"
using namespace MR;
using namespace App;
const char* const algorithms[] = { "csd", "msmt_csd", NULL };
OptionGroup CommonOptions = OptionGroup ("Options common to more than one algorithm")
+ Option ("directions",
"specify the directions over which to apply the non-negativity constraint "
"(by default, the built-in 300 direction set is used). These should be "
"supplied as a text file containing [ az el ] pairs for the directions.")
+ Argument ("file").type_file_in()
+ Option ("lmax",
"the maximum spherical harmonic order for the output FOD(s)."
"For algorithms with multiple outputs, this should be "
"provided as a comma-separated list of integers, one for "
"each output image; for single-output algorithms, only "
"a single integer should be provided. If omitted, the "
"command will use the highest possible lmax given the "
"diffusion gradient table, up to a maximum of 8.")
+ Argument ("order").type_sequence_int()
+ Option ("mask",
"only perform computation within the specified binary brain mask image.")
+ Argument ("image").type_image_in();
void usage ()
{
AUTHOR = "J-Donald Tournier (jdtournier@gmail.com) and Ben Jeurissen (ben.jeurissen@uantwerpen.be)";
SYNOPSIS = "Estimate fibre orientation distributions from diffusion data using spherical deconvolution";
DESCRIPTION
+ Math::SH::encoding_description;
EXAMPLES
+ Example ("Perform single-shell single-tissue CSD",
"dwi2fod csd dwi.mif response_wm.txt wmfod.mif",
"This algorithm is designed for single-shell data and only uses a single "
"b-value. The response function text file provided should only contain a "
"a single row, corresponding to the b-value used for CSD.")
+ Example ("Perform multi-shell multi-tissue CSD",
"dwi2fod msmt_csd dwi.mif response_wm.txt wmfod.mif response_gm.txt gm.mif response_csf.txt csf.mif",
"This example is the most common use case of multi-tissue CSD, estimating "
"a white matter FOD, and grey matter and CSF compartments. This algorithm "
"requires at least three unique b-values to estimate three tissue compartments. "
"Each response function text file should have a number of rows equal to the "
"number of b-values used. If only two unique b-values are available, it's also "
"possible to estimate only two tissue compartments, e.g., white matter and CSF.");
REFERENCES
+ "* If using csd algorithm:\n"
"Tournier, J.-D.; Calamante, F. & Connelly, A. " // Internal
"Robust determination of the fibre orientation distribution in diffusion MRI: "
"Non-negativity constrained super-resolved spherical deconvolution. "
"NeuroImage, 2007, 35, 1459-1472"
+ "* If using msmt_csd algorithm:\n"
"Jeurissen, B; Tournier, J-D; Dhollander, T; Connelly, A & Sijbers, J. " // Internal
"Multi-tissue constrained spherical deconvolution for improved analysis of multi-shell diffusion MRI data "
"NeuroImage, 2014, 103, 411-426"
+ "Tournier, J.-D.; Calamante, F., Gadian, D.G. & Connelly, A. " // Internal
"Direct estimation of the fiber orientation density function from "
"diffusion-weighted MRI data using spherical deconvolution."
"NeuroImage, 2004, 23, 1176-1185";
ARGUMENTS
+ Argument ("algorithm", "the algorithm to use for FOD estimation. "
"(options are: " + join(algorithms, ",") + ")").type_choice (algorithms)
+ Argument ("dwi", "the input diffusion-weighted image").type_image_in()
+ Argument ("response odf", "pairs of input tissue response and output ODF images").allow_multiple();
OPTIONS
+ DWI::GradImportOptions()
+ DWI::ShellsOption
+ CommonOptions
+ DWI::SDeconv::CSD_options
+ DWI::SDeconv::MSMT_CSD_options
+ Stride::Options;
}
class CSD_Processor { MEMALIGN(CSD_Processor)
public:
CSD_Processor (const DWI::SDeconv::CSD::Shared& shared, Image<bool>& mask) :
sdeconv (shared),
data (shared.dwis.size()),
mask (mask) { }
void operator () (Image<float>& dwi, Image<float>& fod) {
if (!load_data (dwi)) {
for (auto l = Loop (3) (fod); l; ++l)
fod.value() = 0.0;
return;
}
sdeconv.set (data);
size_t n;
for (n = 0; n < sdeconv.shared.niter; n++)
if (sdeconv.iterate())
break;
if (sdeconv.shared.niter && n >= sdeconv.shared.niter)
INFO ("voxel [ " + str (dwi.index(0)) + " " + str (dwi.index(1)) + " " + str (dwi.index(2)) +
" ] did not reach full convergence");
fod.row(3) = sdeconv.FOD();
}
private:
DWI::SDeconv::CSD sdeconv;
Eigen::VectorXd data;
Image<bool> mask;
bool load_data (Image<float>& dwi) {
if (mask.valid()) {
assign_pos_of (dwi, 0, 3).to (mask);
if (!mask.value())
return false;
}
for (size_t n = 0; n < sdeconv.shared.dwis.size(); n++) {
dwi.index(3) = sdeconv.shared.dwis[n];
data[n] = dwi.value();
if (!std::isfinite (data[n]))
return false;
if (data[n] < 0.0)
data[n] = 0.0;
}
return true;
}
};
class MSMT_Processor { MEMALIGN (MSMT_Processor)
public:
MSMT_Processor (const DWI::SDeconv::MSMT_CSD::Shared& shared, Image<bool>& mask_image,
vector< Image<float> > odf_images, Image<float> dwi_modelled = Image<float>()) :
sdeconv (shared),
mask_image (mask_image),
odf_images (odf_images),
modelled_image (dwi_modelled),
dwi_data (shared.grad.rows()),
output_data (shared.problem.H.cols()) { }
void operator() (Image<float>& dwi_image)
{
if (mask_image.valid()) {
assign_pos_of (dwi_image, 0, 3).to (mask_image);
if (!mask_image.value())
return;
}
dwi_data = dwi_image.row(3);
sdeconv (dwi_data, output_data);
if (sdeconv.niter >= sdeconv.shared.problem.max_niter) {
INFO ("voxel [ " + str (dwi_image.index(0)) + " " + str (dwi_image.index(1)) + " " + str (dwi_image.index(2)) +
" ] did not reach full convergence");
}
size_t j = 0;
for (size_t i = 0; i < odf_images.size(); ++i) {
assign_pos_of (dwi_image, 0, 3).to (odf_images[i]);
for (auto l = Loop(3)(odf_images[i]); l; ++l)
odf_images[i].value() = output_data[j++];
}
if (modelled_image.valid()) {
assign_pos_of (dwi_image, 0, 3).to (modelled_image);
dwi_data = sdeconv.shared.problem.H * output_data;
modelled_image.row(3) = dwi_data;
}
}
private:
DWI::SDeconv::MSMT_CSD sdeconv;
Image<bool> mask_image;
vector< Image<float> > odf_images;
Image<float> modelled_image;
Eigen::VectorXd dwi_data;
Eigen::VectorXd output_data;
};
void run ()
{
auto header_in = Header::open (argument[1]);
Header header_out (header_in);
header_out.ndim() = 4;
header_out.datatype() = DataType::Float32;
header_out.datatype().set_byte_order_native();
Stride::set_from_command_line (header_out, Stride::contiguous_along_axis (3, header_in));
auto mask = Image<bool>();
auto opt = get_options ("mask");
if (opt.size()) {
mask = Header::open (opt[0][0]).get_image<bool>();
check_dimensions (header_in, mask, 0, 3);
}
int algorithm = argument[0];
if (algorithm == 0) {
if (argument.size() != 4)
throw Exception ("CSD algorithm expects a single input response function and single output FOD image");
DWI::SDeconv::CSD::Shared shared (header_in);
shared.parse_cmdline_options();
try {
shared.set_response (argument[2]);
} catch (Exception& e) {
throw Exception (e, "CSD algorithm expects second argument to be the input response function file");
}
shared.init();
header_out.size(3) = shared.nSH();
DWI::stash_DW_scheme (header_out, shared.grad);
PhaseEncoding::clear_scheme (header_out);
auto fod = Image<float>::create (argument[3], header_out);
CSD_Processor processor (shared, mask);
auto dwi = header_in.get_image<float>().with_direct_io (3);
ThreadedLoop ("performing constrained spherical deconvolution", dwi, 0, 3)
.run (processor, dwi, fod);
} else if (algorithm == 1) {
if (argument.size() % 2)
throw Exception ("MSMT_CSD algorithm expects pairs of (input response function & output FOD image) to be provided");
DWI::SDeconv::MSMT_CSD::Shared shared (header_in);
shared.parse_cmdline_options();
const size_t num_tissues = (argument.size()-2)/2;
vector<std::string> response_paths;
vector<std::string> odf_paths;
for (size_t i = 0; i < num_tissues; ++i) {
response_paths.push_back (argument[i*2+2]);
odf_paths.push_back (argument[i*2+3]);
}
try {
shared.set_responses (response_paths);
} catch (Exception& e) {
throw Exception (e, "MSMT_CSD algorithm expects the first file in each argument pair to be an input response function file");
}
shared.init();
DWI::stash_DW_scheme (header_out, shared.grad);
vector< Image<float> > odfs;
for (size_t i = 0; i < num_tissues; ++i) {
header_out.size (3) = Math::SH::NforL (shared.lmax[i]);
odfs.push_back (Image<float> (Image<float>::create (odf_paths[i], header_out)));
}
Image<float> dwi_modelled;
auto opt = get_options ("predicted_signal");
if (opt.size())
dwi_modelled = Image<float>::create (opt[0][0], header_in);
MSMT_Processor processor (shared, mask, odfs, dwi_modelled);
auto dwi = header_in.get_image<float>().with_direct_io (3);
ThreadedLoop ("performing multi-shell, multi-tissue CSD", dwi, 0, 3)
.run (processor, dwi);
} else {
assert (0);
}
}
<commit_msg>dwi2fod: update documentation around default for lmax<commit_after>/* Copyright (c) 2008-2019 the MRtrix3 contributors.
*
* 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/.
*
* Covered Software is provided under this License on an "as is"
* basis, without warranty of any kind, either expressed, implied, or
* statutory, including, without limitation, warranties that the
* Covered Software is free of defects, merchantable, fit for a
* particular purpose or non-infringing.
* See the Mozilla Public License v. 2.0 for more details.
*
* For more details, see http://www.mrtrix.org/.
*/
#include "command.h"
#include "header.h"
#include "image.h"
#include "phase_encoding.h"
#include "algo/threaded_loop.h"
#include "dwi/gradient.h"
#include "dwi/shells.h"
#include "dwi/sdeconv/csd.h"
#include "dwi/sdeconv/msmt_csd.h"
#include "math/SH.h"
using namespace MR;
using namespace App;
const char* const algorithms[] = { "csd", "msmt_csd", NULL };
OptionGroup CommonOptions = OptionGroup ("Options common to more than one algorithm")
+ Option ("directions",
"specify the directions over which to apply the non-negativity constraint "
"(by default, the built-in 300 direction set is used). These should be "
"supplied as a text file containing [ az el ] pairs for the directions.")
+ Argument ("file").type_file_in()
+ Option ("lmax",
"the maximum spherical harmonic order for the output FOD(s)."
"For algorithms with multiple outputs, this should be "
"provided as a comma-separated list of integers, one for "
"each output image; for single-output algorithms, only "
"a single integer should be provided. If omitted, the "
"command will use the lmax of the corresponding response "
"function (i.e based on its number of coefficients), "
"up to a maximum of 8.")
+ Argument ("order").type_sequence_int()
+ Option ("mask",
"only perform computation within the specified binary brain mask image.")
+ Argument ("image").type_image_in();
void usage ()
{
AUTHOR = "J-Donald Tournier (jdtournier@gmail.com) and Ben Jeurissen (ben.jeurissen@uantwerpen.be)";
SYNOPSIS = "Estimate fibre orientation distributions from diffusion data using spherical deconvolution";
DESCRIPTION
+ Math::SH::encoding_description;
EXAMPLES
+ Example ("Perform single-shell single-tissue CSD",
"dwi2fod csd dwi.mif response_wm.txt wmfod.mif",
"This algorithm is designed for single-shell data and only uses a single "
"b-value. The response function text file provided should only contain a "
"a single row, corresponding to the b-value used for CSD.")
+ Example ("Perform multi-shell multi-tissue CSD",
"dwi2fod msmt_csd dwi.mif response_wm.txt wmfod.mif response_gm.txt gm.mif response_csf.txt csf.mif",
"This example is the most common use case of multi-tissue CSD, estimating "
"a white matter FOD, and grey matter and CSF compartments. This algorithm "
"requires at least three unique b-values to estimate three tissue compartments. "
"Each response function text file should have a number of rows equal to the "
"number of b-values used. If only two unique b-values are available, it's also "
"possible to estimate only two tissue compartments, e.g., white matter and CSF.");
REFERENCES
+ "* If using csd algorithm:\n"
"Tournier, J.-D.; Calamante, F. & Connelly, A. " // Internal
"Robust determination of the fibre orientation distribution in diffusion MRI: "
"Non-negativity constrained super-resolved spherical deconvolution. "
"NeuroImage, 2007, 35, 1459-1472"
+ "* If using msmt_csd algorithm:\n"
"Jeurissen, B; Tournier, J-D; Dhollander, T; Connelly, A & Sijbers, J. " // Internal
"Multi-tissue constrained spherical deconvolution for improved analysis of multi-shell diffusion MRI data "
"NeuroImage, 2014, 103, 411-426"
+ "Tournier, J.-D.; Calamante, F., Gadian, D.G. & Connelly, A. " // Internal
"Direct estimation of the fiber orientation density function from "
"diffusion-weighted MRI data using spherical deconvolution."
"NeuroImage, 2004, 23, 1176-1185";
ARGUMENTS
+ Argument ("algorithm", "the algorithm to use for FOD estimation. "
"(options are: " + join(algorithms, ",") + ")").type_choice (algorithms)
+ Argument ("dwi", "the input diffusion-weighted image").type_image_in()
+ Argument ("response odf", "pairs of input tissue response and output ODF images").allow_multiple();
OPTIONS
+ DWI::GradImportOptions()
+ DWI::ShellsOption
+ CommonOptions
+ DWI::SDeconv::CSD_options
+ DWI::SDeconv::MSMT_CSD_options
+ Stride::Options;
}
class CSD_Processor { MEMALIGN(CSD_Processor)
public:
CSD_Processor (const DWI::SDeconv::CSD::Shared& shared, Image<bool>& mask) :
sdeconv (shared),
data (shared.dwis.size()),
mask (mask) { }
void operator () (Image<float>& dwi, Image<float>& fod) {
if (!load_data (dwi)) {
for (auto l = Loop (3) (fod); l; ++l)
fod.value() = 0.0;
return;
}
sdeconv.set (data);
size_t n;
for (n = 0; n < sdeconv.shared.niter; n++)
if (sdeconv.iterate())
break;
if (sdeconv.shared.niter && n >= sdeconv.shared.niter)
INFO ("voxel [ " + str (dwi.index(0)) + " " + str (dwi.index(1)) + " " + str (dwi.index(2)) +
" ] did not reach full convergence");
fod.row(3) = sdeconv.FOD();
}
private:
DWI::SDeconv::CSD sdeconv;
Eigen::VectorXd data;
Image<bool> mask;
bool load_data (Image<float>& dwi) {
if (mask.valid()) {
assign_pos_of (dwi, 0, 3).to (mask);
if (!mask.value())
return false;
}
for (size_t n = 0; n < sdeconv.shared.dwis.size(); n++) {
dwi.index(3) = sdeconv.shared.dwis[n];
data[n] = dwi.value();
if (!std::isfinite (data[n]))
return false;
if (data[n] < 0.0)
data[n] = 0.0;
}
return true;
}
};
class MSMT_Processor { MEMALIGN (MSMT_Processor)
public:
MSMT_Processor (const DWI::SDeconv::MSMT_CSD::Shared& shared, Image<bool>& mask_image,
vector< Image<float> > odf_images, Image<float> dwi_modelled = Image<float>()) :
sdeconv (shared),
mask_image (mask_image),
odf_images (odf_images),
modelled_image (dwi_modelled),
dwi_data (shared.grad.rows()),
output_data (shared.problem.H.cols()) { }
void operator() (Image<float>& dwi_image)
{
if (mask_image.valid()) {
assign_pos_of (dwi_image, 0, 3).to (mask_image);
if (!mask_image.value())
return;
}
dwi_data = dwi_image.row(3);
sdeconv (dwi_data, output_data);
if (sdeconv.niter >= sdeconv.shared.problem.max_niter) {
INFO ("voxel [ " + str (dwi_image.index(0)) + " " + str (dwi_image.index(1)) + " " + str (dwi_image.index(2)) +
" ] did not reach full convergence");
}
size_t j = 0;
for (size_t i = 0; i < odf_images.size(); ++i) {
assign_pos_of (dwi_image, 0, 3).to (odf_images[i]);
for (auto l = Loop(3)(odf_images[i]); l; ++l)
odf_images[i].value() = output_data[j++];
}
if (modelled_image.valid()) {
assign_pos_of (dwi_image, 0, 3).to (modelled_image);
dwi_data = sdeconv.shared.problem.H * output_data;
modelled_image.row(3) = dwi_data;
}
}
private:
DWI::SDeconv::MSMT_CSD sdeconv;
Image<bool> mask_image;
vector< Image<float> > odf_images;
Image<float> modelled_image;
Eigen::VectorXd dwi_data;
Eigen::VectorXd output_data;
};
void run ()
{
auto header_in = Header::open (argument[1]);
Header header_out (header_in);
header_out.ndim() = 4;
header_out.datatype() = DataType::Float32;
header_out.datatype().set_byte_order_native();
Stride::set_from_command_line (header_out, Stride::contiguous_along_axis (3, header_in));
auto mask = Image<bool>();
auto opt = get_options ("mask");
if (opt.size()) {
mask = Header::open (opt[0][0]).get_image<bool>();
check_dimensions (header_in, mask, 0, 3);
}
int algorithm = argument[0];
if (algorithm == 0) {
if (argument.size() != 4)
throw Exception ("CSD algorithm expects a single input response function and single output FOD image");
DWI::SDeconv::CSD::Shared shared (header_in);
shared.parse_cmdline_options();
try {
shared.set_response (argument[2]);
} catch (Exception& e) {
throw Exception (e, "CSD algorithm expects second argument to be the input response function file");
}
shared.init();
header_out.size(3) = shared.nSH();
DWI::stash_DW_scheme (header_out, shared.grad);
PhaseEncoding::clear_scheme (header_out);
auto fod = Image<float>::create (argument[3], header_out);
CSD_Processor processor (shared, mask);
auto dwi = header_in.get_image<float>().with_direct_io (3);
ThreadedLoop ("performing constrained spherical deconvolution", dwi, 0, 3)
.run (processor, dwi, fod);
} else if (algorithm == 1) {
if (argument.size() % 2)
throw Exception ("MSMT_CSD algorithm expects pairs of (input response function & output FOD image) to be provided");
DWI::SDeconv::MSMT_CSD::Shared shared (header_in);
shared.parse_cmdline_options();
const size_t num_tissues = (argument.size()-2)/2;
vector<std::string> response_paths;
vector<std::string> odf_paths;
for (size_t i = 0; i < num_tissues; ++i) {
response_paths.push_back (argument[i*2+2]);
odf_paths.push_back (argument[i*2+3]);
}
try {
shared.set_responses (response_paths);
} catch (Exception& e) {
throw Exception (e, "MSMT_CSD algorithm expects the first file in each argument pair to be an input response function file");
}
shared.init();
DWI::stash_DW_scheme (header_out, shared.grad);
vector< Image<float> > odfs;
for (size_t i = 0; i < num_tissues; ++i) {
header_out.size (3) = Math::SH::NforL (shared.lmax[i]);
odfs.push_back (Image<float> (Image<float>::create (odf_paths[i], header_out)));
}
Image<float> dwi_modelled;
auto opt = get_options ("predicted_signal");
if (opt.size())
dwi_modelled = Image<float>::create (opt[0][0], header_in);
MSMT_Processor processor (shared, mask, odfs, dwi_modelled);
auto dwi = header_in.get_image<float>().with_direct_io (3);
ThreadedLoop ("performing multi-shell, multi-tissue CSD", dwi, 0, 3)
.run (processor, dwi);
} else {
assert (0);
}
}
<|endoftext|>
|
<commit_before>#include <fstream>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
bool writeBug = false;
bool writeFileNames = false;
string patStr;
string tesStr;
bool isWhite(char _c)
{
if (_c == ' ' || _c == ' ' || _c == '\n')
return true;
else
return false;
}
bool readNext(ifstream &_file, string &_str)
{
while(isWhite(_file.peek()))
_file.get();
if (_file.eof() == false)
{
_file >> _str;
return true;
}
else
return false;
}
int main(int _argc, char *_argv[])
{
for (int i = 1; i < _argc; i++)
{
if (_argv[i][0] != '-')
{
if (i + 1 < _argc)
{
patStr = string(_argv[i]);
tesStr = string(_argv[i + 1]);
break;
}
else
{
cerr << "CMP: cmp/default: No second output file path" << endl;
return -2;
}
}
else
{
if (strcmp(_argv[i], "-bug") == 0)
writeBug = true;
else if (strcmp(_argv[i], "-fname") == 0)
writeFileNames = true;
else
{
cerr << "CMP: No arg called \"" << _argv[i] << "\" exists" << endl;
}
}
}
if (writeFileNames)
cout << patStr << " " << tesStr << endl;
ifstream pat(patStr.c_str());
ifstream tes(tesStr.c_str());
if (pat.is_open() == false)
{
cerr << "CMP: Can't open:" << patStr << endl;
return -2;
}
if (tes.is_open() == false)
{
cerr << "CMP: Can't open: " << tesStr << endl;
return -2;
}
int strNr = 1;
bool pb, tb;
while (true)
{
pb = readNext(pat, patStr);
tb = readNext(tes, tesStr);
if (pb == false && tb == false)
break;
else if (pb == false || tb == false)
{
if (writeBug)
cout << (pb == false ? "Output file is too long" : "Output file is too short") << endl;
pat.close();
tes.close();
return -1;
}
if (patStr != tesStr)
{
if (writeBug)
{
pat.close();
tes.close();
cout << "String:" << strNr << " Expected:" << patStr << " Readed:" << tesStr << endl;
}
return -1;
}
strNr++;
}
pat.close();
tes.close();
return 0;
}
<commit_msg>DOS/Windows line ending support for cmp/default.cpp<commit_after>#include <fstream>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
bool writeBug = false;
bool writeFileNames = false;
string patStr;
string tesStr;
bool isWhite(char _c)
{
if (_c == ' ' || _c == ' ' || _c == '\n' || _c == '\r')
return true;
else
return false;
}
bool readNext(ifstream &_file, string &_str)
{
while(isWhite(_file.peek()))
_file.get();
if (_file.eof() == false)
{
_file >> _str;
return true;
}
else
return false;
}
int main(int _argc, char *_argv[])
{
for (int i = 1; i < _argc; i++)
{
if (_argv[i][0] != '-')
{
if (i + 1 < _argc)
{
patStr = string(_argv[i]);
tesStr = string(_argv[i + 1]);
break;
}
else
{
cerr << "CMP: cmp/default: No second output file path" << endl;
return -2;
}
}
else
{
if (strcmp(_argv[i], "-bug") == 0)
writeBug = true;
else if (strcmp(_argv[i], "-fname") == 0)
writeFileNames = true;
else
{
cerr << "CMP: No arg called \"" << _argv[i] << "\" exists" << endl;
}
}
}
if (writeFileNames)
cout << patStr << " " << tesStr << endl;
ifstream pat(patStr.c_str());
ifstream tes(tesStr.c_str());
if (pat.is_open() == false)
{
cerr << "CMP: Can't open:" << patStr << endl;
return -2;
}
if (tes.is_open() == false)
{
cerr << "CMP: Can't open: " << tesStr << endl;
return -2;
}
int strNr = 1;
bool pb, tb;
while (true)
{
pb = readNext(pat, patStr);
tb = readNext(tes, tesStr);
if (pb == false && tb == false)
break;
else if (pb == false || tb == false)
{
if (writeBug)
cout << (pb == false ? "Output file is too long" : "Output file is too short") << endl;
pat.close();
tes.close();
return -1;
}
if (patStr != tesStr)
{
if (writeBug)
{
pat.close();
tes.close();
cout << "String:" << strNr << " Expected:" << patStr << " Readed:" << tesStr << endl;
}
return -1;
}
strNr++;
}
pat.close();
tes.close();
return 0;
}
<|endoftext|>
|
<commit_before>#include "dialogs.h"
#include <cmath>
namespace sigc {
#ifndef SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE
template <typename Functor>
struct functor_trait<Functor, false> {
typedef decltype (::sigc::mem_fun(std::declval<Functor&>(),
&Functor::operator())) _intermediate;
typedef typename _intermediate::result_type result_type;
typedef Functor functor_type;
};
#else
SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE
#endif
}
Dialog::Message::Message(const std::string &text): Gtk::MessageDialog(text, false, Gtk::MessageType::MESSAGE_INFO, Gtk::ButtonsType::BUTTONS_NONE, true) {
auto g_application=g_application_get_default();
auto gio_application=Glib::wrap(g_application, true);
auto application=Glib::RefPtr<Gtk::Application>::cast_static(gio_application);
set_transient_for(*application->get_active_window());
set_position(Gtk::WindowPosition::WIN_POS_CENTER_ON_PARENT);
show_now();
while(g_main_context_pending(NULL))
g_main_context_iteration(NULL, false);
}
std::string Dialog::gtk_dialog(const boost::filesystem::path &path, const std::string &title,
const std::vector<std::pair<std::string, Gtk::ResponseType>> &buttons,
Gtk::FileChooserAction gtk_options) {
Gtk::FileChooserDialog dialog(title, gtk_options);
auto g_application=g_application_get_default();
auto gio_application=Glib::wrap(g_application, true);
auto application=Glib::RefPtr<Gtk::Application>::cast_static(gio_application);
dialog.set_transient_for(*application->get_active_window());
dialog.set_position(Gtk::WindowPosition::WIN_POS_CENTER_ON_PARENT);
if(title=="Save File As")
gtk_file_chooser_set_filename(reinterpret_cast<GtkFileChooser*>(dialog.gobj()), path.string().c_str());
else if(!path.empty())
gtk_file_chooser_set_current_folder(reinterpret_cast<GtkFileChooser*>(dialog.gobj()), path.string().c_str());
else {
boost::system::error_code ec;
auto current_path=boost::filesystem::current_path(ec);
if(!ec)
gtk_file_chooser_set_current_folder(reinterpret_cast<GtkFileChooser*>(dialog.gobj()), current_path.string().c_str());
}
dialog.set_position(Gtk::WindowPosition::WIN_POS_CENTER_ON_PARENT);
for (auto &button : buttons)
dialog.add_button(button.first, button.second);
return dialog.run() == Gtk::RESPONSE_OK ? dialog.get_filename() : "";
}
<commit_msg>Got rid of double dialog.set_position calls in dialogs.cc<commit_after>#include "dialogs.h"
#include <cmath>
namespace sigc {
#ifndef SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE
template <typename Functor>
struct functor_trait<Functor, false> {
typedef decltype (::sigc::mem_fun(std::declval<Functor&>(),
&Functor::operator())) _intermediate;
typedef typename _intermediate::result_type result_type;
typedef Functor functor_type;
};
#else
SIGC_FUNCTORS_DEDUCE_RESULT_TYPE_WITH_DECLTYPE
#endif
}
Dialog::Message::Message(const std::string &text): Gtk::MessageDialog(text, false, Gtk::MessageType::MESSAGE_INFO, Gtk::ButtonsType::BUTTONS_NONE, true) {
auto g_application=g_application_get_default();
auto gio_application=Glib::wrap(g_application, true);
auto application=Glib::RefPtr<Gtk::Application>::cast_static(gio_application);
set_transient_for(*application->get_active_window());
set_position(Gtk::WindowPosition::WIN_POS_CENTER_ON_PARENT);
show_now();
while(g_main_context_pending(NULL))
g_main_context_iteration(NULL, false);
}
std::string Dialog::gtk_dialog(const boost::filesystem::path &path, const std::string &title,
const std::vector<std::pair<std::string, Gtk::ResponseType>> &buttons,
Gtk::FileChooserAction gtk_options) {
Gtk::FileChooserDialog dialog(title, gtk_options);
auto g_application=g_application_get_default();
auto gio_application=Glib::wrap(g_application, true);
auto application=Glib::RefPtr<Gtk::Application>::cast_static(gio_application);
dialog.set_transient_for(*application->get_active_window());
dialog.set_position(Gtk::WindowPosition::WIN_POS_CENTER_ON_PARENT);
if(title=="Save File As")
gtk_file_chooser_set_filename(reinterpret_cast<GtkFileChooser*>(dialog.gobj()), path.string().c_str());
else if(!path.empty())
gtk_file_chooser_set_current_folder(reinterpret_cast<GtkFileChooser*>(dialog.gobj()), path.string().c_str());
else {
boost::system::error_code ec;
auto current_path=boost::filesystem::current_path(ec);
if(!ec)
gtk_file_chooser_set_current_folder(reinterpret_cast<GtkFileChooser*>(dialog.gobj()), current_path.string().c_str());
}
for (auto &button : buttons)
dialog.add_button(button.first, button.second);
return dialog.run() == Gtk::RESPONSE_OK ? dialog.get_filename() : "";
}
<|endoftext|>
|
<commit_before>// Copyright 2020 Chia Network Inc
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in coiance 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 iied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef SRC_BLSSCHEMES_HPP_
#define SRC_BLSSCHEMES_HPP_
#include <iostream>
#include <vector>
#include <relic_conf.h>
#if defined GMP && ARITH == GMP
#include <gmp.h>
#endif
#include "elements.hpp"
#include "privatekey.hpp"
using std::vector;
// These are all MPL schemes
namespace bls {
class Bytes;
class CoreMPL {
public:
virtual ~CoreMPL() {};
CoreMPL() = delete;
CoreMPL(const std::string& strId) : strCiphersuiteId(strId) {}
// Generates a private key from a seed, similar to HD key generation
// (hashes the seed), and reduces it mod the group order
virtual PrivateKey KeyGen(const vector<uint8_t>& seed);
virtual PrivateKey KeyGen(const Bytes& seed);
// Generates a public key from a secret key
virtual vector<uint8_t> SkToPk(const PrivateKey &seckey);
virtual G1Element SkToG1(const PrivateKey &seckey);
virtual G2Element Sign(const PrivateKey &seckey, const vector<uint8_t> &message);
virtual G2Element Sign(const PrivateKey& seckey, const Bytes& message);
virtual bool Verify(const vector<uint8_t> &pubkey,
const vector<uint8_t> &message,
const vector<uint8_t> &signature);
virtual bool Verify(const Bytes& pubkey, const Bytes& message, const Bytes& signature);
virtual bool Verify(const G1Element &pubkey,
const vector<uint8_t> &message,
const G2Element &signature);
virtual bool Verify(const G1Element& pubkey, const Bytes& message, const G2Element& signature);
virtual vector<uint8_t> Aggregate(const vector<vector<uint8_t>> &signatures);
virtual vector<uint8_t> Aggregate(const vector<Bytes>& signatures);
virtual G2Element Aggregate(const vector<G2Element> &signatures);
virtual G1Element Aggregate(const vector<G1Element> &publicKeys);
virtual G2Element AggregateSecure(const std::vector<G1Element>& vecPublicKeys,
const std::vector<G2Element>& vecSignatures,
const Bytes& message);
virtual bool VerifySecure(const std::vector<G1Element>& vecPublicKeys,
const G2Element& signature,
const Bytes& message);
virtual bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys,
const vector<vector<uint8_t>> &messages,
const vector<uint8_t> &signature);
virtual bool AggregateVerify(const vector<Bytes>& pubkeys,
const vector<Bytes>& messages,
const Bytes& signature);
virtual bool AggregateVerify(const vector<G1Element> &pubkeys,
const vector<vector<uint8_t>> &messages,
const G2Element &signature);
virtual bool AggregateVerify(const vector<G1Element>& pubkeys,
const vector<Bytes>& messages,
const G2Element& signature);
PrivateKey DeriveChildSk(const PrivateKey& sk, uint32_t index);
PrivateKey DeriveChildSkUnhardened(const PrivateKey& sk, uint32_t index);
G1Element DeriveChildPkUnhardened(const G1Element& sk, uint32_t index);
protected:
const std::string& strCiphersuiteId;
bool NativeVerify(g1_t *pubKeys, g2_t *mappedHashes, size_t length);
G2Element AggregateSecure(std::vector<G1Element> const &vecPublicKeys,
std::vector<G2Element> const &vecSignatures,
const Bytes& message,
bool fLegacy);
bool VerifySecure(const std::vector<G1Element>& vecPublicKeys,
const G2Element& signature,
const Bytes& message,
bool fLegacy);
};
class BasicSchemeMPL : public CoreMPL {
public:
virtual ~BasicSchemeMPL() {};
static const std::string CIPHERSUITE_ID;
BasicSchemeMPL() : CoreMPL(BasicSchemeMPL::CIPHERSUITE_ID) {}
bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys,
const vector<vector<uint8_t>> &messages,
const vector<uint8_t> &signature) override;
bool AggregateVerify(const vector<Bytes>& pubkeys,
const vector<Bytes>& messages,
const Bytes& signature) override;
bool AggregateVerify(const vector<G1Element> &pubkeys,
const vector<vector<uint8_t>> &messages,
const G2Element &signature) override;
bool AggregateVerify(const vector<G1Element>& pubkeys,
const vector<Bytes>& messages,
const G2Element& signature) override;
};
class AugSchemeMPL : public CoreMPL {
public:
virtual ~AugSchemeMPL() {};
static const std::string CIPHERSUITE_ID;
AugSchemeMPL() : CoreMPL(AugSchemeMPL::CIPHERSUITE_ID) {}
G2Element Sign(const PrivateKey &seckey, const vector<uint8_t> &message) override;
G2Element Sign(const PrivateKey& seckey, const Bytes& message) override;
// Used for prepending different augMessage
G2Element Sign(const PrivateKey &seckey,
const vector<uint8_t> &message,
const G1Element &prepend_pk);
// Used for prepending different augMessage
G2Element Sign(const PrivateKey& seckey,
const Bytes& message,
const G1Element& prepend_pk);
bool Verify(const vector<uint8_t> &pubkey,
const vector<uint8_t> &message,
const vector<uint8_t> &signature) override;
bool Verify(const Bytes& pubkey,
const Bytes& message,
const Bytes& signature) override;
bool Verify(const G1Element &pubkey,
const vector<uint8_t> &message,
const G2Element &signature) override;
bool Verify(const G1Element& pubkey,
const Bytes& message,
const G2Element& signature) override;
bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys,
const vector<vector<uint8_t>> &messages,
const vector<uint8_t> &signature) override;
bool AggregateVerify(const vector<Bytes>& pubkeys,
const vector<Bytes>& messages,
const Bytes& signature) override;
bool AggregateVerify(const vector<G1Element> &pubkeys,
const vector<vector<uint8_t>> &messages,
const G2Element &signature) override;
bool AggregateVerify(const vector<G1Element>& pubkeys,
const vector<Bytes>& messages,
const G2Element& signature) override;
};
class PopSchemeMPL : public CoreMPL {
public:
virtual ~PopSchemeMPL() {};
static const std::string CIPHERSUITE_ID;
static const std::string POP_CIPHERSUITE_ID;
PopSchemeMPL() : CoreMPL(PopSchemeMPL::CIPHERSUITE_ID) {}
G2Element PopProve(const PrivateKey &seckey);
bool PopVerify(const G1Element &pubkey, const G2Element &signature_proof);
bool PopVerify(const vector<uint8_t> &pubkey, const vector<uint8_t> &proof);
bool PopVerify(const Bytes& pubkey, const Bytes& proof);
bool FastAggregateVerify(const vector<G1Element> &pubkeys,
const vector<uint8_t> &message,
const G2Element &signature);
bool FastAggregateVerify(const vector<G1Element>& pubkeys,
const Bytes& message,
const G2Element& signature);
bool FastAggregateVerify(const vector<vector<uint8_t>> &pubkeys,
const vector<uint8_t> &message,
const vector<uint8_t> &signature);
bool FastAggregateVerify(const vector<Bytes>& pubkeys,
const Bytes& message,
const Bytes& signature);
};
/**
* This scheme reflects the Sign/Verify behaviour of older bls-signatures library versions (<0.1.29).
*/
class LegacySchemeMPL : public CoreMPL {
public:
virtual ~LegacySchemeMPL() {};
LegacySchemeMPL() : CoreMPL(std::string{}) {}
virtual vector<uint8_t> SkToPk(const PrivateKey &seckey) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); }
G2Element Sign(const PrivateKey &seckey, const vector<uint8_t> &message) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); }
G2Element Sign(const PrivateKey &seckey, const Bytes& message) final;
bool Verify(const vector<uint8_t>& pubkey,
const vector<uint8_t>& message,
const vector<uint8_t>& signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); }
bool Verify(const G1Element& pubkey,
const vector<uint8_t>& message,
const G2Element& signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); }
bool Verify(const Bytes& pubkey, const Bytes& message, const Bytes& signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); }
bool Verify(const G1Element &pubkey, const Bytes& message, const G2Element &signature) final;
vector<uint8_t> Aggregate(const vector<vector<uint8_t>> &signatures) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); }
G2Element AggregateSecure(const std::vector<G1Element>& vecPublicKeys,
const std::vector<G2Element>& vecSignatures,
const Bytes& message) final;
bool VerifySecure(const std::vector<G1Element>& vecPublicKeys,
const G2Element& signature,
const Bytes& message) final;
bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys,
const vector<vector<uint8_t>> &messages,
const vector<uint8_t> &signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); }
bool AggregateVerify(const vector<Bytes> &pubkeys,
const vector<Bytes> &messages,
const Bytes &signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); }
bool AggregateVerify(const vector<G1Element> &pubkeys,
const vector<vector<uint8_t>> &messages,
const G2Element &signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); }
bool AggregateVerify(const vector<G1Element> &pubkeys,
const vector<Bytes> &messages,
const G2Element &signature) final;
};
} // end namespace bls
#endif // SRC_BLSSCHEMES_HPP_
<commit_msg>Update schemes.hpp<commit_after>// Copyright 2020 Chia Network Inc
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in coiance 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 iied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef SRC_BLSSCHEMES_HPP_
#define SRC_BLSSCHEMES_HPP_
#include <iostream>
#include <vector>
#include <relic_conf.h>
#if defined GMP && ARITH == GMP
#include <gmp.h>
#endif
#include "elements.hpp"
#include "privatekey.hpp"
using std::vector;
// These are all MPL schemes
namespace bls {
class Bytes;
class CoreMPL {
public:
virtual ~CoreMPL() {};
CoreMPL() = delete;
CoreMPL(const std::string& strId) : strCiphersuiteId(strId) {}
// Generates a private key from a seed, similar to HD key generation
// (hashes the seed), and reduces it mod the group order
virtual PrivateKey KeyGen(const vector<uint8_t>& seed);
virtual PrivateKey KeyGen(const Bytes& seed);
// Generates a public key from a secret key
virtual vector<uint8_t> SkToPk(const PrivateKey &seckey);
virtual G1Element SkToG1(const PrivateKey &seckey);
virtual G2Element Sign(const PrivateKey &seckey, const vector<uint8_t> &message);
virtual G2Element Sign(const PrivateKey& seckey, const Bytes& message);
virtual bool Verify(const vector<uint8_t> &pubkey,
const vector<uint8_t> &message,
const vector<uint8_t> &signature);
virtual bool Verify(const Bytes& pubkey, const Bytes& message, const Bytes& signature);
virtual bool Verify(const G1Element &pubkey,
const vector<uint8_t> &message,
const G2Element &signature);
virtual bool Verify(const G1Element& pubkey, const Bytes& message, const G2Element& signature);
virtual vector<uint8_t> Aggregate(const vector<vector<uint8_t>> &signatures);
virtual vector<uint8_t> Aggregate(const vector<Bytes>& signatures);
virtual G2Element Aggregate(const vector<G2Element> &signatures);
virtual G1Element Aggregate(const vector<G1Element> &publicKeys);
virtual G2Element AggregateSecure(const std::vector<G1Element>& vecPublicKeys,
const std::vector<G2Element>& vecSignatures,
const Bytes& message);
virtual bool VerifySecure(const std::vector<G1Element>& vecPublicKeys,
const G2Element& signature,
const Bytes& message);
virtual bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys,
const vector<vector<uint8_t>> &messages,
const vector<uint8_t> &signature);
virtual bool AggregateVerify(const vector<Bytes>& pubkeys,
const vector<Bytes>& messages,
const Bytes& signature);
virtual bool AggregateVerify(const vector<G1Element> &pubkeys,
const vector<vector<uint8_t>> &messages,
const G2Element &signature);
virtual bool AggregateVerify(const vector<G1Element>& pubkeys,
const vector<Bytes>& messages,
const G2Element& signature);
PrivateKey DeriveChildSk(const PrivateKey& sk, uint32_t index);
PrivateKey DeriveChildSkUnhardened(const PrivateKey& sk, uint32_t index);
G1Element DeriveChildPkUnhardened(const G1Element& sk, uint32_t index);
protected:
const std::string& strCiphersuiteId;
bool NativeVerify(g1_t *pubKeys, g2_t *mappedHashes, size_t length);
G2Element AggregateSecure(std::vector<G1Element> const &vecPublicKeys,
std::vector<G2Element> const &vecSignatures,
const Bytes& message,
bool fLegacy);
bool VerifySecure(const std::vector<G1Element>& vecPublicKeys,
const G2Element& signature,
const Bytes& message,
bool fLegacy);
};
class BasicSchemeMPL : public CoreMPL {
public:
virtual ~BasicSchemeMPL() {};
static const std::string CIPHERSUITE_ID;
BasicSchemeMPL() : CoreMPL(BasicSchemeMPL::CIPHERSUITE_ID) {}
bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys,
const vector<vector<uint8_t>> &messages,
const vector<uint8_t> &signature) override;
bool AggregateVerify(const vector<Bytes>& pubkeys,
const vector<Bytes>& messages,
const Bytes& signature) override;
bool AggregateVerify(const vector<G1Element> &pubkeys,
const vector<vector<uint8_t>> &messages,
const G2Element &signature) override;
bool AggregateVerify(const vector<G1Element>& pubkeys,
const vector<Bytes>& messages,
const G2Element& signature) override;
};
class AugSchemeMPL : public CoreMPL {
public:
virtual ~AugSchemeMPL() {};
static const std::string CIPHERSUITE_ID;
AugSchemeMPL() : CoreMPL(AugSchemeMPL::CIPHERSUITE_ID) {}
G2Element Sign(const PrivateKey &seckey, const vector<uint8_t> &message) override;
G2Element Sign(const PrivateKey& seckey, const Bytes& message) override;
// Used for prepending different augMessage
G2Element Sign(const PrivateKey &seckey,
const vector<uint8_t> &message,
const G1Element &prepend_pk);
// Used for prepending different augMessage
G2Element Sign(const PrivateKey& seckey,
const Bytes& message,
const G1Element& prepend_pk);
bool Verify(const vector<uint8_t> &pubkey,
const vector<uint8_t> &message,
const vector<uint8_t> &signature) override;
bool Verify(const Bytes& pubkey,
const Bytes& message,
const Bytes& signature) override;
bool Verify(const G1Element &pubkey,
const vector<uint8_t> &message,
const G2Element &signature) override;
bool Verify(const G1Element& pubkey,
const Bytes& message,
const G2Element& signature) override;
bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys,
const vector<vector<uint8_t>> &messages,
const vector<uint8_t> &signature) override;
bool AggregateVerify(const vector<Bytes>& pubkeys,
const vector<Bytes>& messages,
const Bytes& signature) override;
bool AggregateVerify(const vector<G1Element> &pubkeys,
const vector<vector<uint8_t>> &messages,
const G2Element &signature) override;
bool AggregateVerify(const vector<G1Element>& pubkeys,
const vector<Bytes>& messages,
const G2Element& signature) override;
};
class PopSchemeMPL : public CoreMPL {
public:
virtual ~PopSchemeMPL() {};
static const std::string CIPHERSUITE_ID;
static const std::string POP_CIPHERSUITE_ID;
PopSchemeMPL() : CoreMPL(PopSchemeMPL::CIPHERSUITE_ID) {}
G2Element PopProve(const PrivateKey &seckey);
bool PopVerify(const G1Element &pubkey, const G2Element &signature_proof);
bool PopVerify(const vector<uint8_t> &pubkey, const vector<uint8_t> &proof);
bool PopVerify(const Bytes& pubkey, const Bytes& proof);
bool FastAggregateVerify(const vector<G1Element> &pubkeys,
const vector<uint8_t> &message,
const G2Element &signature);
bool FastAggregateVerify(const vector<G1Element>& pubkeys,
const Bytes& message,
const G2Element& signature);
bool FastAggregateVerify(const vector<vector<uint8_t>> &pubkeys,
const vector<uint8_t> &message,
const vector<uint8_t> &signature);
bool FastAggregateVerify(const vector<Bytes>& pubkeys,
const Bytes& message,
const Bytes& signature);
};
/**
* This scheme reflects the Sign/Verify behaviour of older bls-signatures library versions (<0.1.29).
*/
class LegacySchemeMPL : public CoreMPL {
public:
virtual ~LegacySchemeMPL() {};
LegacySchemeMPL() : CoreMPL(std::string{}) {}
virtual vector<uint8_t> SkToPk(const PrivateKey &seckey) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); }
G2Element Sign(const PrivateKey &seckey, const vector<uint8_t> &message) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); }
G2Element Sign(const PrivateKey &seckey, const Bytes& message) final;
bool Verify(const vector<uint8_t>& pubkey,
const vector<uint8_t>& message,
const vector<uint8_t>& signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); }
bool Verify(const G1Element& pubkey,
const vector<uint8_t>& message,
const G2Element& signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); }
bool Verify(const Bytes& pubkey, const Bytes& message, const Bytes& signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); }
bool Verify(const G1Element &pubkey, const Bytes& message, const G2Element &signature) final;
virtual vector<uint8_t> Aggregate(const vector<vector<uint8_t>> &signatures) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); }
G2Element AggregateSecure(const std::vector<G1Element>& vecPublicKeys,
const std::vector<G2Element>& vecSignatures,
const Bytes& message) final;
bool VerifySecure(const std::vector<G1Element>& vecPublicKeys,
const G2Element& signature,
const Bytes& message) final;
bool AggregateVerify(const vector<vector<uint8_t>> &pubkeys,
const vector<vector<uint8_t>> &messages,
const vector<uint8_t> &signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); }
bool AggregateVerify(const vector<Bytes> &pubkeys,
const vector<Bytes> &messages,
const Bytes &signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); }
bool AggregateVerify(const vector<G1Element> &pubkeys,
const vector<vector<uint8_t>> &messages,
const G2Element &signature) final { throw std::runtime_error("Not supported in LegacySchemeMPL"); }
bool AggregateVerify(const vector<G1Element> &pubkeys,
const vector<Bytes> &messages,
const G2Element &signature) final;
};
} // end namespace bls
#endif // SRC_BLSSCHEMES_HPP_
<|endoftext|>
|
<commit_before>/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2003 - 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
#include "base/winlog.h"
#include "base/util/utils.h"
#ifdef _WIN32_WCE
#define FUNAMBOL_HEADER "Funambol Windows Mobile Plug-in Log"
#elif WIN32
#define FUNAMBOL_HEADER "Funambol Win32 Plug-in Log"
#endif
//winLog LOG = winLog(false);
char logmsg[512];
static FILE* logFile = NULL;
static WCHAR wlogDir[512] = TEXT("\\");
static char logName[128] = LOG_NAME;
static char logPath[256] = "\\" ;
winLog::winLog(bool resetLog, const char* path, const char* name) {
setLogPath(path);
setLogName(name);
// MUST use a wchar_t* logDir to manage correctly international chars.
// If using char* logDir and UTF-8, fopen() is not working correctly and
// will fail to open the log file. (with UTF-8... why?)
// So we use _wfopen() and a wchar_t* logDir.
char logDir[512];
sprintf(logDir, "%s\\%s", logPath, logName);
WCHAR* tmp = toWideChar(logDir);
wcscpy(wlogDir, tmp);
delete [] tmp;
//
// Test to ensure the log file is writable (only if path is set)
//
if (path) {
logFile = _wfopen(wlogDir, TEXT("a+"));
if (logFile == NULL) {
WCHAR tmp[512];
wsprintf(tmp, TEXT("Unable to write log file: \"%s\".\nPlease check your user's permissions."), wlogDir);
MessageBox(NULL, tmp, TEXT("Funambol"), MB_SETFOREGROUND | MB_OK);
}
else {
fclose(logFile);
if (resetLog) {
reset(FUNAMBOL_HEADER);
}
}
}
}
winLog::~winLog() {
if (logFile != NULL) {
fclose(logFile);
}
}
void winLog::setLogPath(const char* configLogPath) {
if (configLogPath != NULL) {
sprintf(logPath, "%s", configLogPath);
} else {
sprintf(logPath, ".");
}
if (logName ){
char logDir[512];
sprintf(logDir, "%s\\%s", logPath, logName);
WCHAR* tmp = toWideChar(logDir);
wcscpy(wlogDir, tmp);
}
}
void winLog::setLogName(const char* configLogName) {
if (configLogName != NULL) {
sprintf(logName, "%s", configLogName);
}
else {
sprintf(logName, "%s", LOG_NAME);
}
if (logPath ){
char logDir[512];
sprintf(logDir, "%s\\%s", logPath, logName);
WCHAR* tmp = toWideChar(logDir);
wcscpy(wlogDir, tmp);
}
}
/*
* return a the time to write into log file. If complete is true, it return
* the date too, else only hours, minutes, seconds and milliseconds
*/
static char* createCurrentTime(bool complete) {
SYSTEMTIME sys_time;
TIME_ZONE_INFORMATION timezone;
GetLocalTime(&sys_time);
GetTimeZoneInformation(&timezone);
char fmtComplete[] = "%04d-%02d-%02d %02d:%02d:%02d GMT %c%d:%02d";
char fmt[] = "%02d:%02d:%02d GMT %c%d:%02d";
char* ret = new char [64];
// calculate offset from UTC/GMT in hours:min, positive value
// means east of Greenwich (e.g. CET = GMT +1)
char direction = timezone.Bias <= 0 ? '+' : '-';
int hours = abs(timezone.Bias / 60) ;
int minutes = abs(timezone.Bias % 60);
if (complete) {
sprintf(ret, fmtComplete, sys_time.wYear, sys_time.wMonth, sys_time.wDay,
sys_time.wHour, sys_time.wMinute, sys_time.wSecond,
direction, hours, minutes);
} else {
sprintf(ret, fmt, sys_time.wHour, sys_time.wMinute, sys_time.wSecond,
direction, hours, minutes);
}
return ret;
}
void winLog::error(const char* msg, ...) {
va_list argList;
va_start (argList, msg);
printMessage(LOG_ERROR, msg, argList);
va_end(argList);
}
void winLog::info(const char* msg, ...) {
if (isLoggable(LOG_LEVEL_INFO)) {
va_list argList;
va_start (argList, msg);
printMessage(LOG_INFO, msg, argList);
va_end(argList);
}
}
void winLog::debug(const char* msg, ...) {
if (isLoggable(LOG_LEVEL_DEBUG)) {
va_list argList;
va_start (argList, msg);
printMessage(LOG_DEBUG, msg, argList);
va_end(argList);
}
}
void winLog::developer(const char* msg, ...) {
if (isLoggable(LOG_LEVEL_INFO)) {
va_list argList;
va_start (argList, msg);
printMessage(LOG_DEBUG, msg, argList);
va_end(argList);
}
}
void winLog::printMessage(const char* level, const char* msg, va_list argList) {
char* currentTime = createCurrentTime(false);
logFile = _wfopen(wlogDir, TEXT("a+"));
if (logFile) {
fprintf(logFile, "%s [%s] - ", currentTime, level);
vfprintf(logFile, msg, argList);
fprintf(logFile, "\n");
fclose(logFile);
}
delete[] currentTime;
}
void winLog::reset(const char* title) {
const char *t = (title) ? title : FUNAMBOL_HEADER;
char* currentTime = createCurrentTime(true);
logFile = _wfopen(wlogDir, TEXT("w+"));
if (logFile) {
fprintf(logFile, "%s - # %s\n\n", currentTime, t);
fclose(logFile);
}
delete[] currentTime;
}
size_t winLog::getLogSize() {
size_t ret = 0;
logFile = _wfopen(wlogDir, TEXT("r"));
if (logFile) {
ret = fgetsize(logFile);
fclose(logFile);
}
return ret;
}
Log *Log::logger;
Log &Log::instance() {
if (!logger) {
logger = new winLog();
}
return *logger;
}
<commit_msg>removed char[] in log.cpp, using StringBuffer<commit_after>/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2003 - 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
#include "base/winlog.h"
#include "base/util/utils.h"
#include "base/util/StringBuffer.h"
#include "base/util/WString.h"
#ifdef _WIN32_WCE
#define FUNAMBOL_HEADER "Funambol Windows Mobile Plug-in Log"
#elif WIN32
#define FUNAMBOL_HEADER "Funambol Win32 Plug-in Log"
#endif
static FILE* logFile = NULL;
static WString wlogDir(TEXT("\\"));
static StringBuffer logName(LOG_NAME);
static StringBuffer logPath("\\");
winLog::winLog(bool resetLog, const char* path, const char* name) {
setLogPath(path);
setLogName(name);
// MUST use a wchar_t* logDir to manage correctly international chars.
// If using char* logDir and UTF-8, fopen() is not working correctly and
// will fail to open the log file. (with UTF-8... why?)
// So we use _wfopen() and a wchar_t* logDir.
StringBuffer logDir;
logDir.sprintf("%s\\%s", logPath.c_str(), logName.c_str());
WCHAR* tmp = toWideChar(logDir.c_str());
wlogDir = tmp;
delete [] tmp;
//
// Test to ensure the log file is writable (only if path is set)
//
if (path) {
logFile = _wfopen(wlogDir.c_str(), TEXT("a+"));
if (logFile == NULL) {
WCHAR tmp[512];
wsprintf(tmp, TEXT("Unable to write log file: \"%s\".\nPlease check your user's permissions."), wlogDir.c_str());
MessageBox(NULL, tmp, TEXT("Funambol"), MB_SETFOREGROUND | MB_OK);
}
else {
fclose(logFile);
if (resetLog) {
reset(FUNAMBOL_HEADER);
}
}
}
}
winLog::~winLog() {
if (logFile != NULL) {
fclose(logFile);
}
}
void winLog::setLogPath(const char* configLogPath) {
if (configLogPath != NULL) {
logPath = configLogPath;
} else {
logPath = ".";
}
if (logName.length() > 0){
StringBuffer logDir;
logDir.sprintf("%s\\%s", logPath.c_str(), logName.c_str());
WCHAR* tmp = toWideChar(logDir.c_str());
wlogDir = tmp;
delete [] tmp;
}
}
void winLog::setLogName(const char* configLogName) {
if (configLogName != NULL) {
logName = configLogName;
}
else {
logName = LOG_NAME;
}
if (logPath){
StringBuffer logDir;
logDir.sprintf("%s\\%s", logPath.c_str(), logName.c_str());
WCHAR* tmp = toWideChar(logDir.c_str());
wlogDir = tmp;
delete [] tmp;
}
}
/*
* return a the time to write into log file. If complete is true, it return
* the date too, else only hours, minutes, seconds and milliseconds
*/
static StringBuffer createCurrentTime(bool complete) {
SYSTEMTIME sys_time;
TIME_ZONE_INFORMATION timezone;
GetLocalTime(&sys_time);
GetTimeZoneInformation(&timezone);
StringBuffer ret;
// calculate offset from UTC/GMT in hours:min, positive value
// means east of Greenwich (e.g. CET = GMT +1)
char direction = timezone.Bias <= 0 ? '+' : '-';
int hours = abs(timezone.Bias / 60) ;
int minutes = abs(timezone.Bias % 60);
if (complete) {
char fmtComplete[] = "%04d-%02d-%02d %02d:%02d:%02d GMT %c%d:%02d";
ret.sprintf(fmtComplete, sys_time.wYear, sys_time.wMonth, sys_time.wDay,
sys_time.wHour, sys_time.wMinute, sys_time.wSecond,
direction, hours, minutes);
}
else {
char fmt[] = "%02d:%02d:%02d GMT %c%d:%02d";
ret.sprintf(fmt, sys_time.wHour, sys_time.wMinute, sys_time.wSecond,
direction, hours, minutes);
}
return ret;
}
void winLog::error(const char* msg, ...) {
va_list argList;
va_start (argList, msg);
printMessage(LOG_ERROR, msg, argList);
va_end(argList);
}
void winLog::info(const char* msg, ...) {
if (isLoggable(LOG_LEVEL_INFO)) {
va_list argList;
va_start (argList, msg);
printMessage(LOG_INFO, msg, argList);
va_end(argList);
}
}
void winLog::debug(const char* msg, ...) {
if (isLoggable(LOG_LEVEL_DEBUG)) {
va_list argList;
va_start (argList, msg);
printMessage(LOG_DEBUG, msg, argList);
va_end(argList);
}
}
void winLog::developer(const char* msg, ...) {
if (isLoggable(LOG_LEVEL_INFO)) {
va_list argList;
va_start (argList, msg);
printMessage(LOG_DEBUG, msg, argList);
va_end(argList);
}
}
void winLog::printMessage(const char* level, const char* msg, va_list argList) {
StringBuffer currentTime = createCurrentTime(false);
logFile = _wfopen(wlogDir.c_str(), TEXT("a+"));
if (logFile) {
fprintf(logFile, "%s [%s] - ", currentTime.c_str(), level);
vfprintf(logFile, msg, argList);
fprintf(logFile, "\n");
fclose(logFile);
}
}
void winLog::reset(const char* title) {
const char *t = (title) ? title : FUNAMBOL_HEADER;
StringBuffer currentTime = createCurrentTime(true);
logFile = _wfopen(wlogDir.c_str(), TEXT("w+"));
if (logFile) {
fprintf(logFile, "%s - # %s\n\n", currentTime.c_str(), t);
fclose(logFile);
}
}
size_t winLog::getLogSize() {
size_t ret = 0;
logFile = _wfopen(wlogDir.c_str(), TEXT("r"));
if (logFile) {
ret = fgetsize(logFile);
fclose(logFile);
}
return ret;
}
Log *Log::logger;
Log &Log::instance() {
if (!logger) {
logger = new winLog();
}
return *logger;
}
<|endoftext|>
|
<commit_before><commit_msg>refactoring<commit_after><|endoftext|>
|
<commit_before>#pragma once
// Mantella
#include <mantella_bits/optimisationAlgorithm/trajectoryBasedAlgorithm.hpp>
namespace mant {
template <typename ParameterType, class DistanceFunction>
class HillClimbing : public TrajectoryBasedAlgorithm<ParameterType, DistanceFunction> {
public:
explicit HillClimbing(
const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem) noexcept;
HillClimbing(const HillClimbing&) = delete;
HillClimbing& operator=(const HillClimbing&) = delete;
void setMaximalStepSize(
const arma::Col<ParameterType>& maximalStepSize);
std::string to_string() const noexcept override;
protected:
arma::Col<ParameterType> maximalStepSize_;
void optimiseImplementation() noexcept override;
private:
void setDefaultMaximalStepSize(std::true_type) noexcept;
void setDefaultMaximalStepSize(std::false_type) noexcept;
};
template <typename ParameterType, class DistanceFunction>
HillClimbing<ParameterType, DistanceFunction>::HillClimbing(
const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem) noexcept
: TrajectoryBasedAlgorithm<ParameterType, DistanceFunction>(optimisationProblem) {
setDefaultMaximalStepSize(std::is_same<ParameterType, double>());
}
template <typename ParameterType, class DistanceFunction>
void HillClimbing<ParameterType, DistanceFunction>::optimiseImplementation() noexcept {
++this->numberOfIterations_;
this->bestParameter_ = this->initialParameter_;
this->bestSoftConstraintsValue_ = this->optimisationProblem_->getSoftConstraintsValue(this->initialParameter_);
this->bestObjectiveValue_ = this->optimisationProblem_->getObjectiveValue(this->initialParameter_);
while(!this->isFinished() && !this->isTerminated()) {
++this->numberOfIterations_;
arma::Col<ParameterType> candidateParameter = this->distanceFunction_.getNeighbour(this->bestParameter_, arma::zeros<arma::Col<double>>(this->optimisationProblem_->getNumberOfDimensions), maximalStepSize_);
const arma::Col<unsigned int>& belowLowerBound = arma::find(candidateParameter < this->optimisationProblem_->getLowerBounds());
const arma::Col<unsigned int>& aboveUpperBound = arma::find(candidateParameter > this->optimisationProblem_->getUpperBounds());
candidateParameter.elem(belowLowerBound) = this->optimisationProblem_->getLowerBounds().elem(belowLowerBound);
candidateParameter.elem(aboveUpperBound) = this->optimisationProblem_->getUpperBounds().elem(aboveUpperBound);
const double& candidateSoftConstraintsValue = this->optimisationProblem_->getSoftConstraintsValue(candidateParameter);
const double& candidateObjectiveValue = this->optimisationProblem_->getObjectiveValue(candidateParameter);
if(candidateSoftConstraintsValue < this->bestSoftConstraintsValue_ || (candidateSoftConstraintsValue == this->bestSoftConstraintsValue_ && candidateObjectiveValue < this->bestObjectiveValue_)) {
this->bestParameter_ = candidateParameter;
this->bestSoftConstraintsValue_ = candidateSoftConstraintsValue;
this->bestObjectiveValue_ = candidateObjectiveValue;
}
}
}
template <typename ParameterType, class DistanceFunction>
void HillClimbing<ParameterType, DistanceFunction>::setMaximalStepSize(
const arma::Col<ParameterType>& maximalStepSize) {
if(maximalStepSize.n_rows != this->optimisationProblem_->getNumberOfDimensions()) {
throw std::logic_error("The number of dimensions of the maximal step size (" + std::to_string(maximalStepSize.n_elem) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(this->optimisationProblem_->getNumberOfDimensions()) + ").");
} else if (arma::any(maximalStepSize <= 0)) {
throw std::logic_error("The maximal step size must be strict greater than 0.");
}
maximalStepSize_ = maximalStepSize;
}
template <typename ParameterType, class DistanceFunction>
std::string HillClimbing<ParameterType, DistanceFunction>::to_string() const noexcept {
return "HillClimbing";
}
template <typename ParameterType, class DistanceFunction>
void HillClimbing<ParameterType, DistanceFunction>::setDefaultMaximalStepSize(
std::true_type) noexcept {
setMaximalStepSize(this->distanceFunction_.getDistance(this->optimisationProblem_->getLowerBounds(), this->optimisationProblem_->getUpperBounds()) / 10.0);
}
template <typename ParameterType, class DistanceFunction>
void HillClimbing<ParameterType, DistanceFunction>::setDefaultMaximalStepSize(
std::false_type) noexcept {
setMaximalStepSize(arma::max(arma::ones<arma::Col<unsigned int>>(this->optimisationProblem_->getNumberOfDimensions()), this->distanceFunction_.getDistance(this->optimisationProblem_->getLowerBounds(), this->optimisationProblem_->getUpperBounds()) / 10.0));
}
}
<commit_msg>devel: Use more precise is_floating_point<commit_after>#pragma once
// Mantella
#include <mantella_bits/optimisationAlgorithm/trajectoryBasedAlgorithm.hpp>
namespace mant {
template <typename ParameterType, class DistanceFunction>
class HillClimbing : public TrajectoryBasedAlgorithm<ParameterType, DistanceFunction> {
public:
explicit HillClimbing(
const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem) noexcept;
HillClimbing(const HillClimbing&) = delete;
HillClimbing& operator=(const HillClimbing&) = delete;
void setMaximalStepSize(
const arma::Col<ParameterType>& maximalStepSize);
std::string to_string() const noexcept override;
protected:
arma::Col<ParameterType> maximalStepSize_;
void optimiseImplementation() noexcept override;
private:
void setDefaultMaximalStepSize(std::true_type) noexcept;
void setDefaultMaximalStepSize(std::false_type) noexcept;
};
template <typename ParameterType, class DistanceFunction>
HillClimbing<ParameterType, DistanceFunction>::HillClimbing(
const std::shared_ptr<OptimisationProblem<ParameterType>> optimisationProblem) noexcept
: TrajectoryBasedAlgorithm<ParameterType, DistanceFunction>(optimisationProblem) {
setDefaultMaximalStepSize(std::is_floating_point<ParameterType>());
}
template <typename ParameterType, class DistanceFunction>
void HillClimbing<ParameterType, DistanceFunction>::optimiseImplementation() noexcept {
++this->numberOfIterations_;
this->bestParameter_ = this->initialParameter_;
this->bestSoftConstraintsValue_ = this->optimisationProblem_->getSoftConstraintsValue(this->initialParameter_);
this->bestObjectiveValue_ = this->optimisationProblem_->getObjectiveValue(this->initialParameter_);
while(!this->isFinished() && !this->isTerminated()) {
++this->numberOfIterations_;
arma::Col<ParameterType> candidateParameter = this->distanceFunction_.getNeighbour(this->bestParameter_, arma::zeros<arma::Col<double>>(this->optimisationProblem_->getNumberOfDimensions), maximalStepSize_);
const arma::Col<unsigned int>& belowLowerBound = arma::find(candidateParameter < this->optimisationProblem_->getLowerBounds());
const arma::Col<unsigned int>& aboveUpperBound = arma::find(candidateParameter > this->optimisationProblem_->getUpperBounds());
candidateParameter.elem(belowLowerBound) = this->optimisationProblem_->getLowerBounds().elem(belowLowerBound);
candidateParameter.elem(aboveUpperBound) = this->optimisationProblem_->getUpperBounds().elem(aboveUpperBound);
const double& candidateSoftConstraintsValue = this->optimisationProblem_->getSoftConstraintsValue(candidateParameter);
const double& candidateObjectiveValue = this->optimisationProblem_->getObjectiveValue(candidateParameter);
if(candidateSoftConstraintsValue < this->bestSoftConstraintsValue_ || (candidateSoftConstraintsValue == this->bestSoftConstraintsValue_ && candidateObjectiveValue < this->bestObjectiveValue_)) {
this->bestParameter_ = candidateParameter;
this->bestSoftConstraintsValue_ = candidateSoftConstraintsValue;
this->bestObjectiveValue_ = candidateObjectiveValue;
}
}
}
template <typename ParameterType, class DistanceFunction>
void HillClimbing<ParameterType, DistanceFunction>::setMaximalStepSize(
const arma::Col<ParameterType>& maximalStepSize) {
if(maximalStepSize.n_rows != this->optimisationProblem_->getNumberOfDimensions()) {
throw std::logic_error("The number of dimensions of the maximal step size (" + std::to_string(maximalStepSize.n_elem) + ") must match the number of dimensions of the optimisation problem (" + std::to_string(this->optimisationProblem_->getNumberOfDimensions()) + ").");
} else if (arma::any(maximalStepSize <= 0)) {
throw std::logic_error("The maximal step size must be strict greater than 0.");
}
maximalStepSize_ = maximalStepSize;
}
template <typename ParameterType, class DistanceFunction>
std::string HillClimbing<ParameterType, DistanceFunction>::to_string() const noexcept {
return "HillClimbing";
}
template <typename ParameterType, class DistanceFunction>
void HillClimbing<ParameterType, DistanceFunction>::setDefaultMaximalStepSize(
std::true_type) noexcept {
setMaximalStepSize(this->distanceFunction_.getDistance(this->optimisationProblem_->getLowerBounds(), this->optimisationProblem_->getUpperBounds()) / 10.0);
}
template <typename ParameterType, class DistanceFunction>
void HillClimbing<ParameterType, DistanceFunction>::setDefaultMaximalStepSize(
std::false_type) noexcept {
setMaximalStepSize(arma::max(arma::ones<arma::Col<unsigned int>>(this->optimisationProblem_->getNumberOfDimensions()), this->distanceFunction_.getDistance(this->optimisationProblem_->getLowerBounds(), this->optimisationProblem_->getUpperBounds()) / 10.0));
}
}
<|endoftext|>
|
<commit_before>// 5.exercise.12.cpp
//
// Implement a little guessing game called (for some obscure reason) "Bulls and
// Cows". The program has a vector of four different integers in the range 0 to
// 9 (e.g., 1234 but not 1122) and it is the user's task to discover those
// numbers by repeated guesses. Say the number to be guessed is 1234 andd the
// user guesses 1359; the response should be "1 bull and 1 cow" because the
// user got one digit (1) right and in the right position (a bull) and one
// digit (3) right but in the wrong position (a cow). The guessing continues
// until the user gets four bulls, that is, has the four digits correct and in
// the correct order.
#include "std_lib_facilities.h"
vector<int> _guess()
// read a number from
{
}
int main()
try
{
bool guessed = false;
// Number to guess: 3461
vector<int> digits = {3, 4, 6 , 1};
int guess = 0;
cout << "Welcome to Bulls and Cows.\n"
<< "Try to guess the four digit sequence I'm thinking about.\n"
<< "No digit appears more than once and I will give you clues,\n"
<< "with \"bulls\" being correct digits in the right position\n"
<< "and \"cows\" being correct digits in wrong position.\n"
<< "Let's start! Your guess ...\n? ";
while (!guessed) {
while (cin >> guess) {
// smallest and biggest combination of 4 distinct digits on [0, 9]
if (guess >= 123 && guess <= 9876) {
}
else {
cout "Not a four digit number! Please try again.\n? ";
}
}
if (cin.eof()) {
cout << "Bye, bye!\n";
return 0;
} else {
cout "Not a four digit number! Please try again.\n? ";
}
}
}
catch (exception& e)
{
cout << "Error: " << e.what() << '\n';
return 1;
}
catch (...)
{
cout << "Unknown exception!\n";
return 2;
}
<commit_msg>Advancing in exercise 12 from chapter 5<commit_after>// 5.exercise.12.cpp
//
// Implement a little guessing game called (for some obscure reason) "Bulls and
// Cows". The program has a vector of four different integers in the range 0 to
// 9 (e.g., 1234 but not 1122) and it is the user's task to discover those
// numbers by repeated guesses. Say the number to be guessed is 1234 andd the
// user guesses 1359; the response should be "1 bull and 1 cow" because the
// user got one digit (1) right and in the right position (a bull) and one
// digit (3) right but in the wrong position (a cow). The guessing continues
// until the user gets four bulls, that is, has the four digits correct and in
// the correct order.
//
// Comments:
// String input is our best bet. The user input sould start by 0 (no one tell
// us this isn't possible) and by reading an int we loose that leading 0 and
// thus, we cannot determine if the user input has been 0123 (correct) or
// 123 (wrong). Reading char by char, on the other hand, makes it more compicated.
#include "std_lib_facilities.h"
static const string ex_msg_no_four_digit = "Your input is not a four digit number.";
static const string ex_msg_repeated_digits = "You've enetered repeated digits. "
"This way you're never going to guess it.";
bool check_input(const string& input)
// Checks input to be a 4-unique-digit string.
// Pre-conditions:
// The length of the string must be exactly 4
// Each character of the string must be an ASCII (or compatible, as ISO or UTF8)
// value for chars from '0' to '9' (they are consecutive).
// Each character of the string must be different
try
{
if (input.length() != 4) throw runtime_error(ex_msg_no_four_digit);
for (size_t i = 0; i < input.length(); ++i)
if (input[i] < '0' || input [i] > '9')
throw runtime_error(ex_msg_no_four_digit);
for (size_t i = 0; i < input.length(); ++i)
for (size_t j = i + 1; j < input.length(); ++j)
if (i != j && input[i] == input[j])
throw runtime_error(ex_msg_repeated_digits);
return true;
}
catch (exception& e)
{
cout << e.what() << '\n';
return false;
}
int main()
try
{
bool guessed = false;
// Number to guess: 3461
vector<int> digits = {3, 4, 6 , 1};
string input = "";
vector<int> guess;
cout << "Welcome to Bulls and Cows.\n"
<< "Try to guess the four digit sequence I'm thinking about.\n"
<< "No digit appears more than once and I will give you clues,\n"
<< "with \"bulls\" being correct digits in the right position\n"
<< "and \"cows\" being correct digits in wrong position.\n"
<< "Let's start! Your guess ...\n? ";
while (!guessed) {
while (cin >> input) {
if (check_input(input)) {
//guess = parse_input(input);
cout << "Correct input!\n";
}
else {
cout << "INCORRECT input!\n";
}
}
if (cin.eof()) {
cout << "Bye, bye!\n";
return 0;
}
}
}
catch (exception& e)
{
cout << "Error: " << e.what() << '\n';
return 1;
}
catch (...)
{
cout << "Unknown exception!\n";
return 2;
}
<|endoftext|>
|
<commit_before>
#ifndef __ERRORS_HPP__
#define __ERRORS_HPP__
#include <errno.h>
#include <stdio.h>
#include <cstdlib>
#include <signal.h>
#include <stdexcept>
/* Error handling
*
* There are several ways to report errors in RethinkDB:
* fail_due_to_user_error(msg, ...) fail and report line number/stack trace. Should only be used when the user
* is at fault (e.g. provided wrong database file name) and it is reasonable to
* fail instead of handling the problem more gracefully.
*
* The following macros are used only for the cases of programmer error checking. For the time being they are also used
* for system error checking (especially the *_err variants).
*
* crash(msg, ...) always fails and reports line number and such. Never returns.
* crash_or_trap(msg, ...) same as above, but traps into debugger if it is present instead of terminating.
* That means that it possibly can return, and one can continue stepping through the code in the debugger.
* All off the assert/guarantee functions use crash_or_trap.
* assert(cond) makes sure cond is true and is a no-op in release mode
* assert(cond, msg, ...) ditto, with additional message and possibly some arguments used for formatting
* guarantee(cond) same as assert(cond), but the check is still done in release mode. Do not use for expensive checks!
* guarantee(cond, msg, ...) same as assert(cond, msg, ...), but the check is still done in release mode. Do not use for expensive checks!
* guarantee_err(cond) same as guarantee(cond), but also print errno error description
* guarantee_err(cond, msg, ...) same as guarantee(cond, msg, ...), but also print errno error description
*/
#ifdef __linux__
#if defined __i386 || defined __x86_64
#define BREAKPOINT __asm__ volatile ("int3")
#else /* x86/amd64 */
#define BREAKPOINT raise(SIGTRAP)
#endif /* x86/amd64 */
#endif /* __linux__ */
// TODO: Abort probably is not the right thing to do here.
#define fail_due_to_user_error(msg, ...) do { \
report_user_error(msg, ##__VA_ARGS__); \
abort(); \
} while (0)
#define crash(msg, ...) do { \
report_fatal_error(__FILE__, __LINE__, msg, ##__VA_ARGS__); \
abort(); \
} while (0)
#define crash_or_trap(msg, ...) do { \
report_fatal_error(__FILE__, __LINE__, msg, ##__VA_ARGS__); \
BREAKPOINT; \
} while (0)
void report_fatal_error(const char*, int, const char*, ...);
void report_user_error(const char*, ...);
#define stringify(x) #x
#define format_assert_message(assert_type, cond) assert_type " failed: [" stringify(cond) "] "
#define guarantee(cond, msg...) do { \
if (!(cond)) { \
crash_or_trap(format_assert_message("Guarantee", cond) msg); \
} \
} while (0)
#define guarantee_err(cond, msg, args...) do { \
if (!(cond)) { \
if (errno == 0) { \
crash_or_trap(format_assert_message("Guarantee", cond) msg); \
} else { \
crash_or_trap(format_assert_message("Guarantee", cond) " (errno %d - %s) " msg, errno, strerror(errno), ##args); \
} \
} \
} while (0)
#define unreachable(msg, ...) crash("Unreachable code: " msg, ##__VA_ARGS__) // can't use crash_or_trap since code needs to depend on its noreturn property
#define not_implemented(msg, ...) crash_or_trap("Not implemented: " msg, ##__VA_ARGS__)
#define UNUSED(x) ((void) x)
#ifdef NDEBUG
#define assert(cond, msg...) ((void)(0))
#else
#define assert(cond, msg...) do { \
if (!(cond)) { \
crash_or_trap(format_assert_message("Assertion", cond) msg); \
} \
} while (0)
#endif
#ifndef NDEBUG
void print_backtrace(FILE *out = stderr, bool use_addr2line = true);
char *demangle_cpp_name(const char *mangled_name);
#endif
#endif /* __ERRORS_HPP__ */
<commit_msg>Added assert_err.<commit_after>
#ifndef __ERRORS_HPP__
#define __ERRORS_HPP__
#include <errno.h>
#include <stdio.h>
#include <cstdlib>
#include <signal.h>
#include <stdexcept>
/* Error handling
*
* There are several ways to report errors in RethinkDB:
* fail_due_to_user_error(msg, ...) fail and report line number/stack trace. Should only be used when the user
* is at fault (e.g. provided wrong database file name) and it is reasonable to
* fail instead of handling the problem more gracefully.
*
* The following macros are used only for the cases of programmer error checking. For the time being they are also used
* for system error checking (especially the *_err variants).
*
* crash(msg, ...) always fails and reports line number and such. Never returns.
* crash_or_trap(msg, ...) same as above, but traps into debugger if it is present instead of terminating.
* That means that it possibly can return, and one can continue stepping through the code in the debugger.
* All off the assert/guarantee functions use crash_or_trap.
* assert(cond) makes sure cond is true and is a no-op in release mode
* assert(cond, msg, ...) ditto, with additional message and possibly some arguments used for formatting
* assert_err(cond) same as assert(cond), but also print errno error description
* assert_err(cond, msg, ...) same as assert(cond, msg, ...), but also print errno error description
* guarantee(cond) same as assert(cond), but the check is still done in release mode. Do not use for expensive checks!
* guarantee(cond, msg, ...) same as assert(cond, msg, ...), but the check is still done in release mode. Do not use for expensive checks!
* guarantee_err(cond) same as guarantee(cond), but also print errno error description
* guarantee_err(cond, msg, ...) same as guarantee(cond, msg, ...), but also print errno error description
*/
#ifdef __linux__
#if defined __i386 || defined __x86_64
#define BREAKPOINT __asm__ volatile ("int3")
#else /* x86/amd64 */
#define BREAKPOINT raise(SIGTRAP)
#endif /* x86/amd64 */
#endif /* __linux__ */
// TODO: Abort probably is not the right thing to do here.
#define fail_due_to_user_error(msg, ...) do { \
report_user_error(msg, ##__VA_ARGS__); \
abort(); \
} while (0)
#define crash(msg, ...) do { \
report_fatal_error(__FILE__, __LINE__, msg, ##__VA_ARGS__); \
abort(); \
} while (0)
#define crash_or_trap(msg, ...) do { \
report_fatal_error(__FILE__, __LINE__, msg, ##__VA_ARGS__); \
BREAKPOINT; \
} while (0)
void report_fatal_error(const char*, int, const char*, ...);
void report_user_error(const char*, ...);
#define stringify(x) #x
#define format_assert_message(assert_type, cond) assert_type " failed: [" stringify(cond) "] "
#define guarantee(cond, msg...) do { \
if (!(cond)) { \
crash_or_trap(format_assert_message("Guarantee", cond) msg); \
} \
} while (0)
#define guarantee_err(cond, msg, args...) do { \
if (!(cond)) { \
if (errno == 0) { \
crash_or_trap(format_assert_message("Guarantee", cond) msg); \
} else { \
crash_or_trap(format_assert_message("Guarantee", cond) " (errno %d - %s) " msg, errno, strerror(errno), ##args); \
} \
} \
} while (0)
#define unreachable(msg, ...) crash("Unreachable code: " msg, ##__VA_ARGS__) // can't use crash_or_trap since code needs to depend on its noreturn property
#define not_implemented(msg, ...) crash_or_trap("Not implemented: " msg, ##__VA_ARGS__)
#define UNUSED(x) ((void) x)
#ifdef NDEBUG
#define assert(cond, msg...) ((void)(0))
#define assert_err(cond, msg...) ((void)(0))
#else
#define assert(cond, msg...) do { \
if (!(cond)) { \
crash_or_trap(format_assert_message("Assertion", cond) msg); \
} \
} while (0)
#define assert_err(cond, msg, args...) do { \
if (!(cond)) { \
if (errno == 0) { \
crash_or_trap(format_assert_message("Assert", cond) msg); \
} else { \
crash_or_trap(format_assert_message("Assert", cond) " (errno %d - %s) " msg, errno, strerror(errno), ##args); \
} \
} \
} while (0)
#endif
#ifndef NDEBUG
void print_backtrace(FILE *out = stderr, bool use_addr2line = true);
char *demangle_cpp_name(const char *mangled_name);
#endif
#endif /* __ERRORS_HPP__ */
<|endoftext|>
|
<commit_before>/* Gobby - GTK-based collaborative text editor
* Copyright (C) 2008, 2009 Armin Burgmeier <armin@arbur.net>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "features.hpp"
#include "window.hpp"
#include "commands/file-tasks/task-open-multiple.hpp"
#include "core/docwindow.hpp"
#include "core/iconmanager.hpp"
#include "core/noteplugin.hpp"
#include "core/closableframe.hpp"
#include "util/i18n.hpp"
#include <gtkmm/frame.h>
Gobby::Window::Window(const IconManager& icon_mgr,
Config& config,
UniqueApp* app):
Gtk::Window(Gtk::WINDOW_TOPLEVEL), m_config(config),
m_lang_manager(gtk_source_language_manager_get_default()),
m_preferences(m_config), m_icon_mgr(icon_mgr), m_app(app),
m_header(m_preferences, m_lang_manager),
m_browser(*this, Plugins::TEXT, m_statusbar, m_preferences),
m_folder(m_preferences, m_lang_manager),
m_statusbar(m_folder, m_preferences),
m_info_storage(INF_GTK_BROWSER_MODEL(m_browser.get_store())),
m_operations(m_info_storage, m_statusbar),
m_commands_autosave(m_folder, m_operations, m_info_storage,
m_preferences),
m_commands_browser(m_browser, m_folder, m_info_storage, m_statusbar,
m_preferences),
m_commands_browser_context(*this, m_browser, m_file_chooser,
m_operations, m_preferences),
m_commands_folder(m_folder),
m_commands_file(*this, m_header, m_browser, m_folder, m_statusbar,
m_file_chooser, m_operations, m_info_storage,
m_preferences),
m_commands_edit(*this, m_header, m_folder, m_statusbar,
m_preferences),
m_commands_view(m_header, m_folder, m_preferences),
m_commands_help(*this, m_header, m_icon_mgr),
m_title_bar(*this, m_folder)
{
g_object_ref(app);
unique_app_watch_window(app, gobj());
g_signal_connect(app, "message-received",
G_CALLBACK(on_message_received_static), this);
m_header.show();
m_browser.show();
m_folder.show();
// Build UI
add_accel_group(m_header.get_accel_group() );
Gtk::Frame* frame_browser = Gtk::manage(new ClosableFrame(
_("Document Browser"), IconManager::STOCK_DOCLIST,
m_preferences.appearance.show_browser));
frame_browser->set_shadow_type(Gtk::SHADOW_IN);
frame_browser->add(m_browser);
// frame_browser manages visibility itself
Gtk::Frame* frame_text = Gtk::manage(new Gtk::Frame);
frame_text->set_shadow_type(Gtk::SHADOW_IN);
frame_text->add(m_folder);
frame_text->show();
m_paned.pack1(*frame_browser, false, false);
m_paned.pack2(*frame_text, true, false);
m_paned.show();
m_mainbox.pack_start(m_header, Gtk::PACK_SHRINK);
m_mainbox.pack_start(m_paned, Gtk::PACK_EXPAND_WIDGET);
m_mainbox.pack_start(m_statusbar, Gtk::PACK_SHRINK);
m_mainbox.show();
// Give initial focus to the browser, which will in turn give focus
// to the "Direct Connection" expander, so people can quickly
// get going.
set_focus_child(m_browser);
add(m_mainbox);
set_default_size(800, 600);
set_role("Gobby");
}
Gobby::Window::~Window()
{
// Serialise preferences into config
m_preferences.serialize(m_config);
g_object_unref(m_app);
}
bool Gobby::Window::on_delete_event(GdkEventAny* event)
{
#if 0
if(m_buffer.get() == NULL) return false;
if(!m_buffer->is_open() ) return false;
Gtk::MessageDialog dlg(
*this,
_("You are still connected to a session"),
false,
Gtk::MESSAGE_WARNING,
Gtk::BUTTONS_NONE,
true
);
dlg.set_secondary_text(
_("Do you want to close Gobby nevertheless?")
);
Gtk::Image* img = Gtk::manage(new Gtk::Image(Gtk::Stock::CANCEL,
Gtk::ICON_SIZE_BUTTON));
Gtk::Button* cancel_button
= dlg.add_button(_("C_ancel"), Gtk::RESPONSE_CANCEL);
dlg.add_button(Gtk::Stock::CLOSE, Gtk::RESPONSE_YES);
cancel_button->set_image(*img);
cancel_button->grab_focus();
return dlg.run() != Gtk::RESPONSE_YES;
#endif
return false;
}
// GtkWindow catches keybindings for the menu items _before_ passing them to
// the focused widget. This is unfortunate and means that pressing ctrl+V
// in an entry on the browser ends up pasting text in the TextView.
// Here we override GtkWindow's handler to do the same things that it
// does, but in the opposite order and then we chain up to the grand
// parent handler, skipping Gtk::Window::key_press_event().
// This code is basically stolen from gedit, but ported to C++.
bool Gobby::Window::on_key_press_event(GdkEventKey* event)
{
// We can't let GtkSourceView handle this, since we override
// Undo/Redo. TODO: This is a bit of a hack. A proper solution would
// perhaps be to subclass GtkSourceView, and either
// unregister/reregister the keybinding there, or making sure the
// key-press-event default handler returns false.
if(event->keyval == GDK_z || event->keyval == GDK_Z)
return Gtk::Window::on_key_press_event(event);
bool handled = gtk_window_propagate_key_event(gobj(), event);
if(!handled) handled = gtk_window_activate_key(gobj(), event);
// Skip Gtk::Window default handler here:
if(!handled) handled = Gtk::Container::on_key_press_event(event);
return handled;
}
void Gobby::Window::on_realize()
{
Gtk::Window::on_realize();
m_paned.set_position(m_paned.get_width() * 2 / 5);
}
void Gobby::Window::on_show()
{
Gtk::Window::on_show();
if(!m_config.get_root()["initial"].get_value<bool>("run", false))
{
m_initial_dlg.reset(new InitialDialog(*this, m_preferences,
m_icon_mgr));
m_initial_dlg->present();
m_initial_dlg->signal_hide().connect(
sigc::mem_fun(*this,
&Window::on_initial_dialog_hide));
}
}
void Gobby::Window::on_initial_dialog_hide()
{
m_initial_dlg.reset(NULL);
// Don't show again
m_config.get_root()["initial"].set_value("run", true);
}
UniqueResponse Gobby::Window::on_message_received(UniqueCommand command,
UniqueMessageData* message,
guint time)
try {
UniqueResponse res;
switch (command) {
case UNIQUE_ACTIVATE:
gtk_window_set_screen(gobj(),
unique_message_data_get_screen(message));
present(time);
return UNIQUE_RESPONSE_OK;
case UNIQUE_OPEN:
{
gchar** uris = unique_message_data_get_uris(message);
if (!uris)
return UNIQUE_RESPONSE_FAIL;
TaskOpenMultiple* task = new TaskOpenMultiple(m_commands_file);
m_commands_file.set_task(task);
for (const gchar* const* p = uris; *p; ++p)
task->add_file(Gio::File::create_for_uri(*p));
g_strfreev(uris);
return UNIQUE_RESPONSE_OK;
}
default:
return UNIQUE_RESPONSE_PASSTHROUGH;
}
} catch (...) {
g_assert_not_reached();
}
<commit_msg>uniqueapp command handler: return/unused variable<commit_after>/* Gobby - GTK-based collaborative text editor
* Copyright (C) 2008, 2009 Armin Burgmeier <armin@arbur.net>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "features.hpp"
#include "window.hpp"
#include "commands/file-tasks/task-open-multiple.hpp"
#include "core/docwindow.hpp"
#include "core/iconmanager.hpp"
#include "core/noteplugin.hpp"
#include "core/closableframe.hpp"
#include "util/i18n.hpp"
#include <gtkmm/frame.h>
Gobby::Window::Window(const IconManager& icon_mgr,
Config& config,
UniqueApp* app):
Gtk::Window(Gtk::WINDOW_TOPLEVEL), m_config(config),
m_lang_manager(gtk_source_language_manager_get_default()),
m_preferences(m_config), m_icon_mgr(icon_mgr), m_app(app),
m_header(m_preferences, m_lang_manager),
m_browser(*this, Plugins::TEXT, m_statusbar, m_preferences),
m_folder(m_preferences, m_lang_manager),
m_statusbar(m_folder, m_preferences),
m_info_storage(INF_GTK_BROWSER_MODEL(m_browser.get_store())),
m_operations(m_info_storage, m_statusbar),
m_commands_autosave(m_folder, m_operations, m_info_storage,
m_preferences),
m_commands_browser(m_browser, m_folder, m_info_storage, m_statusbar,
m_preferences),
m_commands_browser_context(*this, m_browser, m_file_chooser,
m_operations, m_preferences),
m_commands_folder(m_folder),
m_commands_file(*this, m_header, m_browser, m_folder, m_statusbar,
m_file_chooser, m_operations, m_info_storage,
m_preferences),
m_commands_edit(*this, m_header, m_folder, m_statusbar,
m_preferences),
m_commands_view(m_header, m_folder, m_preferences),
m_commands_help(*this, m_header, m_icon_mgr),
m_title_bar(*this, m_folder)
{
g_object_ref(app);
unique_app_watch_window(app, gobj());
g_signal_connect(app, "message-received",
G_CALLBACK(on_message_received_static), this);
m_header.show();
m_browser.show();
m_folder.show();
// Build UI
add_accel_group(m_header.get_accel_group() );
Gtk::Frame* frame_browser = Gtk::manage(new ClosableFrame(
_("Document Browser"), IconManager::STOCK_DOCLIST,
m_preferences.appearance.show_browser));
frame_browser->set_shadow_type(Gtk::SHADOW_IN);
frame_browser->add(m_browser);
// frame_browser manages visibility itself
Gtk::Frame* frame_text = Gtk::manage(new Gtk::Frame);
frame_text->set_shadow_type(Gtk::SHADOW_IN);
frame_text->add(m_folder);
frame_text->show();
m_paned.pack1(*frame_browser, false, false);
m_paned.pack2(*frame_text, true, false);
m_paned.show();
m_mainbox.pack_start(m_header, Gtk::PACK_SHRINK);
m_mainbox.pack_start(m_paned, Gtk::PACK_EXPAND_WIDGET);
m_mainbox.pack_start(m_statusbar, Gtk::PACK_SHRINK);
m_mainbox.show();
// Give initial focus to the browser, which will in turn give focus
// to the "Direct Connection" expander, so people can quickly
// get going.
set_focus_child(m_browser);
add(m_mainbox);
set_default_size(800, 600);
set_role("Gobby");
}
Gobby::Window::~Window()
{
// Serialise preferences into config
m_preferences.serialize(m_config);
g_object_unref(m_app);
}
bool Gobby::Window::on_delete_event(GdkEventAny* event)
{
#if 0
if(m_buffer.get() == NULL) return false;
if(!m_buffer->is_open() ) return false;
Gtk::MessageDialog dlg(
*this,
_("You are still connected to a session"),
false,
Gtk::MESSAGE_WARNING,
Gtk::BUTTONS_NONE,
true
);
dlg.set_secondary_text(
_("Do you want to close Gobby nevertheless?")
);
Gtk::Image* img = Gtk::manage(new Gtk::Image(Gtk::Stock::CANCEL,
Gtk::ICON_SIZE_BUTTON));
Gtk::Button* cancel_button
= dlg.add_button(_("C_ancel"), Gtk::RESPONSE_CANCEL);
dlg.add_button(Gtk::Stock::CLOSE, Gtk::RESPONSE_YES);
cancel_button->set_image(*img);
cancel_button->grab_focus();
return dlg.run() != Gtk::RESPONSE_YES;
#endif
return false;
}
// GtkWindow catches keybindings for the menu items _before_ passing them to
// the focused widget. This is unfortunate and means that pressing ctrl+V
// in an entry on the browser ends up pasting text in the TextView.
// Here we override GtkWindow's handler to do the same things that it
// does, but in the opposite order and then we chain up to the grand
// parent handler, skipping Gtk::Window::key_press_event().
// This code is basically stolen from gedit, but ported to C++.
bool Gobby::Window::on_key_press_event(GdkEventKey* event)
{
// We can't let GtkSourceView handle this, since we override
// Undo/Redo. TODO: This is a bit of a hack. A proper solution would
// perhaps be to subclass GtkSourceView, and either
// unregister/reregister the keybinding there, or making sure the
// key-press-event default handler returns false.
if(event->keyval == GDK_z || event->keyval == GDK_Z)
return Gtk::Window::on_key_press_event(event);
bool handled = gtk_window_propagate_key_event(gobj(), event);
if(!handled) handled = gtk_window_activate_key(gobj(), event);
// Skip Gtk::Window default handler here:
if(!handled) handled = Gtk::Container::on_key_press_event(event);
return handled;
}
void Gobby::Window::on_realize()
{
Gtk::Window::on_realize();
m_paned.set_position(m_paned.get_width() * 2 / 5);
}
void Gobby::Window::on_show()
{
Gtk::Window::on_show();
if(!m_config.get_root()["initial"].get_value<bool>("run", false))
{
m_initial_dlg.reset(new InitialDialog(*this, m_preferences,
m_icon_mgr));
m_initial_dlg->present();
m_initial_dlg->signal_hide().connect(
sigc::mem_fun(*this,
&Window::on_initial_dialog_hide));
}
}
void Gobby::Window::on_initial_dialog_hide()
{
m_initial_dlg.reset(NULL);
// Don't show again
m_config.get_root()["initial"].set_value("run", true);
}
UniqueResponse Gobby::Window::on_message_received(UniqueCommand command,
UniqueMessageData* message,
guint time)
try {
switch (command) {
case UNIQUE_ACTIVATE:
gtk_window_set_screen(gobj(),
unique_message_data_get_screen(message));
present(time);
return UNIQUE_RESPONSE_OK;
case UNIQUE_OPEN:
{
gchar** uris = unique_message_data_get_uris(message);
if (!uris)
return UNIQUE_RESPONSE_FAIL;
TaskOpenMultiple* task = new TaskOpenMultiple(m_commands_file);
m_commands_file.set_task(task);
for (const gchar* const* p = uris; *p; ++p)
task->add_file(Gio::File::create_for_uri(*p));
g_strfreev(uris);
return UNIQUE_RESPONSE_OK;
}
default:
return UNIQUE_RESPONSE_PASSTHROUGH;
}
} catch (...) {
g_assert_not_reached();
return UNIQUE_RESPONSE_FAIL;
}
<|endoftext|>
|
<commit_before>/*
* See ffx.h for details.
*
* References:
* [FFX2] http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/ffx/ffx-spec2.pdf
*/
#include "ffx/ffx.h"
#include <math.h>
#include <string>
#include "third_party/aes/aes.h"
namespace ffx {
static bool ValidateKey(const std::string & key) {
if (key.length() != kFfxKeyLengthInNibbles) {
return false;
}
for (uint32_t i = 0; i < key.length(); ++i) {
if (isxdigit(key[i])) {
continue;
} else {
return false;
}
}
return true;
}
/*
* This function has an unfortunate number of input parameters.
* However, this is a direct implementation of the round-function algorithm
* F_K(n,T,i,B) defined in [FFX2].
*/
static bool RoundFunction(const std::string & K,
uint32_t n,
const mpz_class & tweak,
uint32_t tweak_len_in_bits,
uint32_t i,
const mpz_class & B,
uint32_t B_len,
mpz_class * retval) {
// [FFX2] pg 3., line 31
uint32_t vers = 1;
uint32_t t = ceil(tweak_len_in_bits / 8.0);
uint32_t beta = ceil(n / 2.0);
uint32_t b = ceil(beta / 8.0);
uint32_t d = 4 * ceil(b / 4.0);
// [FFX2] pg 3., line 32
uint32_t m = 0;
if ((i & 1) == 0) {
m = n / 2;
} else {
m = ceil(n / 2.0);
}
// [FFX2] pg 3., line 33
mpz_class P = 0;
uint32_t P_len = (1 + 1 + 1 + 3 + 1 + 1 + 4 + 4) * 8;
P += mpz_class(vers) << (1 + 1 + 3 + 1 + 1 + 4 + 4) * 8;
P += mpz_class(2) << (1 + 3 + 1 + 1 + 4 + 4) * 8;
P += mpz_class(1) << (3 + 1 + 1 + 4 + 4) * 8;
P += mpz_class(2) << (1 + 1 + 4 + 4) * 8;
P += mpz_class(10) << (1 + 4 + 4) * 8;
P += mpz_class(n / 2) << (4 + 4) * 8;
P += mpz_class(n) << (4) * 8;
P += t;
uint32_t B_bits = b * 8;
// [FFX2] pg 3., line 34
mpz_class Q = 0;
uint32_t T_offset = ((((-1 * t) - b - 1) % 16) * 8);
T_offset += 8;
T_offset += B_bits;
uint32_t Q_len = tweak_len_in_bits + T_offset;
Q += mpz_class(tweak) << T_offset;
Q += mpz_class(i) << B_bits;
Q += B;
mpz_class Y = 0;
// [FFX2] pg 3., line 35
bool cbc_success = AesCbcMac(K, (P << Q_len) + Q, P_len + Q_len, &Y);
if (!cbc_success) {
return false;
}
// [FFX2] pg 3., line 36
mpz_class Z = Y;
uint32_t Z_len = 16;
mpz_class counter = 1;
while (Z_len < (d + 4)) {
mpz_class ctxt;
AesEcbEncrypt(K, (Y + counter), 128, &ctxt);
Z_len += 16;
Z = Z << 128;
Z += ctxt;
++counter;
}
// [FFX2] pg 3., line 37
BitMask(Z, Z_len * 8, 0, ((d + 4) * 8) - 1, &Y);
// [FFX2] pg 3., line 3=8
mpz_class modulus = 0;
mpz_ui_pow_ui(modulus.get_mpz_t(), 2, m);
Y = Y % modulus;
// [FFX2] pg 3., line 39
*retval = Y;
}
bool Ffx::Encrypt(const std::string & key ,
const mpz_class & tweak,
uint32_t tweak_len_in_bits,
const mpz_class & plaintext,
uint32_t plaintext_len_in_bits,
mpz_class * ciphertext) {
// [FFX2] pg 3., line 11
if (!ValidateKey(key)) {
return false;
}
mpz_class & retval = *ciphertext;
// [FFX2] pg 3., line 14-15
uint32_t n = plaintext_len_in_bits;
uint32_t l = plaintext_len_in_bits / 2;
uint32_t r = kDefaultFfxRounds;
mpz_class A, B;
BitMask(plaintext, plaintext_len_in_bits, 0, l - 1, &A);
BitMask(plaintext, plaintext_len_in_bits, l, n - 1, &B);
uint32_t B_len = n - l;
mpz_class C = 0;
mpz_class D = 0;
uint32_t m = 0;
mpz_class modulus = 0;
// [FFX2] pg 3., line 16
for (uint32_t i = 0; i <= (r - 1); ++i) {
if ((i & 1) == 0) {
m = n / 2;
} else {
m = ceil(n / 2.0);
}
mpz_ui_pow_ui(modulus.get_mpz_t(), 2, m);
RoundFunction(key, n, tweak, tweak_len_in_bits, i, B, m, &D);
mpz_add(C.get_mpz_t(),
A.get_mpz_t(),
D.get_mpz_t());
C = C % modulus;
A = B;
B = C;
}
// [FFX2] pg 3., line 19
retval = (A << B_len) + B;
mpz_ui_pow_ui(modulus.get_mpz_t(), 2, plaintext_len_in_bits);
retval = retval % modulus;
}
bool Ffx::Decrypt(const std::string & key,
const mpz_class & tweak,
uint32_t tweak_len_in_bits,
const mpz_class & cihpertext,
uint32_t cihpertext_len_bits,
mpz_class * plaintext) {
// [FFX2] pg 3., line 21
if (!ValidateKey(key)) {
return false;
}
mpz_class & retval = *plaintext;
// [FFX2] pg 3., line 24-25
uint32_t n = cihpertext_len_bits;
uint32_t l = cihpertext_len_bits / 2;
uint32_t r = kDefaultFfxRounds;
mpz_class A, B;
BitMask(cihpertext, cihpertext_len_bits, 0, l - 1, &A);
BitMask(cihpertext, cihpertext_len_bits, l, n - 1, &B);
uint32_t B_len = n - l;
mpz_class C = 0;
mpz_class D = 0;
uint32_t m = 0;
mpz_class modulus = 0;
// [FFX2] pg 3., line 26
for (int32_t i = r - 1; i >= 0; --i) {
if ((i & 1) == 0) {
m = n / 2;
} else {
m = ceil(n / 2.0);
}
mpz_ui_pow_ui(modulus.get_mpz_t(), 2, m);
C = B;
B = A;
RoundFunction(key, n, tweak, tweak_len_in_bits, i, B, m, &D);
mpz_sub(A.get_mpz_t(),
C.get_mpz_t(),
D.get_mpz_t());
while(A < 0) A += modulus;
A = A % modulus;
}
// [FFX2] pg 3., line 29
retval = (A << B_len) + B;
mpz_ui_pow_ui(modulus.get_mpz_t(), 2, cihpertext_len_bits);
retval = retval % modulus;
}
/*
* These are the main entry points with NULL tweaks.
*/
bool Ffx::Encrypt(const std::string & key,
const mpz_class & plaintext,
uint32_t plaintext_len_in_bits,
mpz_class * ciphertext) {
return Ffx::Encrypt(key, 0, 0, plaintext, plaintext_len_in_bits, ciphertext);
}
bool Ffx::Decrypt(const std::string & key,
const mpz_class & ciphertext,
uint32_t ciphertext_len_in_bits,
mpz_class * plaintext) {
return Ffx::Decrypt(key, 0, 0, ciphertext, ciphertext_len_in_bits, plaintext);
}
} // namespace ffx
<commit_msg>ensure we return in all functions<commit_after>/*
* See ffx.h for details.
*
* References:
* [FFX2] http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/ffx/ffx-spec2.pdf
*/
#include "ffx/ffx.h"
#include <math.h>
#include <string>
#include "third_party/aes/aes.h"
namespace ffx {
static bool ValidateKey(const std::string & key) {
if (key.length() != kFfxKeyLengthInNibbles) {
return false;
}
for (uint32_t i = 0; i < key.length(); ++i) {
if (isxdigit(key[i])) {
continue;
} else {
return false;
}
}
return true;
}
/*
* This function has an unfortunate number of input parameters.
* However, this is a direct implementation of the round-function algorithm
* F_K(n,T,i,B) defined in [FFX2].
*/
static bool RoundFunction(const std::string & K,
uint32_t n,
const mpz_class & tweak,
uint32_t tweak_len_in_bits,
uint32_t i,
const mpz_class & B,
uint32_t B_len,
mpz_class * retval) {
// [FFX2] pg 3., line 31
uint32_t vers = 1;
uint32_t t = ceil(tweak_len_in_bits / 8.0);
uint32_t beta = ceil(n / 2.0);
uint32_t b = ceil(beta / 8.0);
uint32_t d = 4 * ceil(b / 4.0);
// [FFX2] pg 3., line 32
uint32_t m = 0;
if ((i & 1) == 0) {
m = n / 2;
} else {
m = ceil(n / 2.0);
}
// [FFX2] pg 3., line 33
mpz_class P = 0;
uint32_t P_len = (1 + 1 + 1 + 3 + 1 + 1 + 4 + 4) * 8;
P += mpz_class(vers) << (1 + 1 + 3 + 1 + 1 + 4 + 4) * 8;
P += mpz_class(2) << (1 + 3 + 1 + 1 + 4 + 4) * 8;
P += mpz_class(1) << (3 + 1 + 1 + 4 + 4) * 8;
P += mpz_class(2) << (1 + 1 + 4 + 4) * 8;
P += mpz_class(10) << (1 + 4 + 4) * 8;
P += mpz_class(n / 2) << (4 + 4) * 8;
P += mpz_class(n) << (4) * 8;
P += t;
uint32_t B_bits = b * 8;
// [FFX2] pg 3., line 34
mpz_class Q = 0;
uint32_t T_offset = ((((-1 * t) - b - 1) % 16) * 8);
T_offset += 8;
T_offset += B_bits;
uint32_t Q_len = tweak_len_in_bits + T_offset;
Q += mpz_class(tweak) << T_offset;
Q += mpz_class(i) << B_bits;
Q += B;
mpz_class Y = 0;
// [FFX2] pg 3., line 35
bool cbc_success = AesCbcMac(K, (P << Q_len) + Q, P_len + Q_len, &Y);
if (!cbc_success) {
return false;
}
// [FFX2] pg 3., line 36
mpz_class Z = Y;
uint32_t Z_len = 16;
mpz_class counter = 1;
while (Z_len < (d + 4)) {
mpz_class ctxt;
AesEcbEncrypt(K, (Y + counter), 128, &ctxt);
Z_len += 16;
Z = Z << 128;
Z += ctxt;
++counter;
}
// [FFX2] pg 3., line 37
BitMask(Z, Z_len * 8, 0, ((d + 4) * 8) - 1, &Y);
// [FFX2] pg 3., line 3=8
mpz_class modulus = 0;
mpz_ui_pow_ui(modulus.get_mpz_t(), 2, m);
Y = Y % modulus;
// [FFX2] pg 3., line 39
*retval = Y;
return true;
}
bool Ffx::Encrypt(const std::string & key ,
const mpz_class & tweak,
uint32_t tweak_len_in_bits,
const mpz_class & plaintext,
uint32_t plaintext_len_in_bits,
mpz_class * ciphertext) {
// [FFX2] pg 3., line 11
if (!ValidateKey(key)) {
return false;
}
mpz_class & retval = *ciphertext;
// [FFX2] pg 3., line 14-15
uint32_t n = plaintext_len_in_bits;
uint32_t l = plaintext_len_in_bits / 2;
uint32_t r = kDefaultFfxRounds;
mpz_class A, B;
BitMask(plaintext, plaintext_len_in_bits, 0, l - 1, &A);
BitMask(plaintext, plaintext_len_in_bits, l, n - 1, &B);
uint32_t B_len = n - l;
mpz_class C = 0;
mpz_class D = 0;
uint32_t m = 0;
mpz_class modulus = 0;
// [FFX2] pg 3., line 16
for (uint32_t i = 0; i <= (r - 1); ++i) {
if ((i & 1) == 0) {
m = n / 2;
} else {
m = ceil(n / 2.0);
}
mpz_ui_pow_ui(modulus.get_mpz_t(), 2, m);
RoundFunction(key, n, tweak, tweak_len_in_bits, i, B, m, &D);
mpz_add(C.get_mpz_t(),
A.get_mpz_t(),
D.get_mpz_t());
C = C % modulus;
A = B;
B = C;
}
// [FFX2] pg 3., line 19
retval = (A << B_len) + B;
mpz_ui_pow_ui(modulus.get_mpz_t(), 2, plaintext_len_in_bits);
retval = retval % modulus;
return true;
}
bool Ffx::Decrypt(const std::string & key,
const mpz_class & tweak,
uint32_t tweak_len_in_bits,
const mpz_class & cihpertext,
uint32_t cihpertext_len_bits,
mpz_class * plaintext) {
// [FFX2] pg 3., line 21
if (!ValidateKey(key)) {
return false;
}
mpz_class & retval = *plaintext;
// [FFX2] pg 3., line 24-25
uint32_t n = cihpertext_len_bits;
uint32_t l = cihpertext_len_bits / 2;
uint32_t r = kDefaultFfxRounds;
mpz_class A, B;
BitMask(cihpertext, cihpertext_len_bits, 0, l - 1, &A);
BitMask(cihpertext, cihpertext_len_bits, l, n - 1, &B);
uint32_t B_len = n - l;
mpz_class C = 0;
mpz_class D = 0;
uint32_t m = 0;
mpz_class modulus = 0;
// [FFX2] pg 3., line 26
for (int32_t i = r - 1; i >= 0; --i) {
if ((i & 1) == 0) {
m = n / 2;
} else {
m = ceil(n / 2.0);
}
mpz_ui_pow_ui(modulus.get_mpz_t(), 2, m);
C = B;
B = A;
RoundFunction(key, n, tweak, tweak_len_in_bits, i, B, m, &D);
mpz_sub(A.get_mpz_t(),
C.get_mpz_t(),
D.get_mpz_t());
while(A < 0) A += modulus;
A = A % modulus;
}
// [FFX2] pg 3., line 29
retval = (A << B_len) + B;
mpz_ui_pow_ui(modulus.get_mpz_t(), 2, cihpertext_len_bits);
retval = retval % modulus;
return true;
}
/*
* These are the main entry points with NULL tweaks.
*/
bool Ffx::Encrypt(const std::string & key,
const mpz_class & plaintext,
uint32_t plaintext_len_in_bits,
mpz_class * ciphertext) {
return Ffx::Encrypt(key, 0, 0, plaintext, plaintext_len_in_bits, ciphertext);
}
bool Ffx::Decrypt(const std::string & key,
const mpz_class & ciphertext,
uint32_t ciphertext_len_in_bits,
mpz_class * plaintext) {
return Ffx::Decrypt(key, 0, 0, ciphertext, ciphertext_len_in_bits, plaintext);
}
} // namespace ffx
<|endoftext|>
|
<commit_before>#include <vector>
#include <cstdlib>
#include <iostream>
#include <unordered_map>
#include <sstream>
#include <string>
#include "vg.hpp"
#include "xg.hpp"
#include "vg.pb.h"
/**
* Provides a way to filter Edits contained
* within Alignments. This can be used to clean out
* sequencing errors and to find high-quality candidates
* for variant calling.
*
*/
namespace vg{
class Filter{
public:
Filter();
~Filter();
/* Filter functions.
* Take an Alignment and walk it.
* Perform the desired summary statistics.
* Output the Alignment if it passes OR
* A new, modified Alignment if we allow it OR
* an empty Alignment if the alignment fails and we don't allow
* modified alignments.
*/
Alignment depth_filter(Alignment& aln);
Alignment qual_filter(Alignment& aln);
Alignment coverage_filter(Alignment& aln);
Alignment avg_qual_filter(Alignment& aln);
Alignment percent_identity_filter(Alignment& aln);
Alignment soft_clip_filter(Alignment& aln);
Alignment split_read_filter(Alignment& aln);
Alignment path_divergence_filter(Alignment& aln);
Alignment reversing_filter(Alignment& aln);
Alignment kmer_filter(Alignment& aln);
void set_min_depth(int depth);
//void set_min_kmer_depth(int d);
void set_min_qual(int qual);
void set_min_percent_identity(double pct_id);
void set_avg_qual(double avg_qual);
void set_filter_matches(bool fm);
void set_remove_failing_edits(bool fm);
void set_soft_clip_limit(int max_clip);
void set_split_read_limit(int split_limit);
void set_reversing(bool do_reversing_filter);
void set_path_divergence(bool do_path_divergence);
void set_window_length(int window_length);
void set_my_vg(vg::VG* vg);
void set_my_xg_idx(xg::XG* xg_idx);
void set_inverse(bool do_inv);
int get_min_depth();
int get_min_qual();
int get_window_length();
int get_soft_clip_limit();
int get_split_read_limit();
double get_min_percent_identity();
double get_min_avg_qual();
bool get_inverse();
bool get_filter_matches();
bool get_remove_failing_edits();
bool get_do_path_divergence();
bool get_do_reversing();
private:
vg::VG* my_vg;
xg::XG* my_xg_idx;
//Position: NodeID + offset
// different edits may be present at each position.
// is there some way to just hash the mappings?
unordered_map<string, unordered_map<string, int> > pos_to_edit_to_depth;
unordered_map<int, int> pos_to_qual;
bool inverse = false;
bool remove_failing_edits = false;
bool filter_matches = false;
bool do_path_divergence;
bool do_reversing;
int min_depth = 0;
int min_qual = 0;
int min_cov = 0;
int window_length = 0;
int qual_offset = 0;
int soft_clip_limit = -1;
int split_read_limit = -1;
double min_percent_identity = 0.0;
double min_avg_qual = 0.0;
};
}
<commit_msg>Add include guards to filter.hpp<commit_after>#ifndef VG_FILTER_HPP
#define VG_FILTER_HPP
#include <vector>
#include <cstdlib>
#include <iostream>
#include <unordered_map>
#include <sstream>
#include <string>
#include "vg.hpp"
#include "xg.hpp"
#include "vg.pb.h"
/**
* Provides a way to filter Edits contained
* within Alignments. This can be used to clean out
* sequencing errors and to find high-quality candidates
* for variant calling.
*
*/
namespace vg{
class Filter{
public:
Filter();
~Filter();
/* Filter functions.
* Take an Alignment and walk it.
* Perform the desired summary statistics.
* Output the Alignment if it passes OR
* A new, modified Alignment if we allow it OR
* an empty Alignment if the alignment fails and we don't allow
* modified alignments.
*/
Alignment depth_filter(Alignment& aln);
Alignment qual_filter(Alignment& aln);
Alignment coverage_filter(Alignment& aln);
Alignment avg_qual_filter(Alignment& aln);
Alignment percent_identity_filter(Alignment& aln);
Alignment soft_clip_filter(Alignment& aln);
Alignment split_read_filter(Alignment& aln);
Alignment path_divergence_filter(Alignment& aln);
Alignment reversing_filter(Alignment& aln);
Alignment kmer_filter(Alignment& aln);
void set_min_depth(int depth);
//void set_min_kmer_depth(int d);
void set_min_qual(int qual);
void set_min_percent_identity(double pct_id);
void set_avg_qual(double avg_qual);
void set_filter_matches(bool fm);
void set_remove_failing_edits(bool fm);
void set_soft_clip_limit(int max_clip);
void set_split_read_limit(int split_limit);
void set_reversing(bool do_reversing_filter);
void set_path_divergence(bool do_path_divergence);
void set_window_length(int window_length);
void set_my_vg(vg::VG* vg);
void set_my_xg_idx(xg::XG* xg_idx);
void set_inverse(bool do_inv);
int get_min_depth();
int get_min_qual();
int get_window_length();
int get_soft_clip_limit();
int get_split_read_limit();
double get_min_percent_identity();
double get_min_avg_qual();
bool get_inverse();
bool get_filter_matches();
bool get_remove_failing_edits();
bool get_do_path_divergence();
bool get_do_reversing();
private:
vg::VG* my_vg;
xg::XG* my_xg_idx;
//Position: NodeID + offset
// different edits may be present at each position.
// is there some way to just hash the mappings?
unordered_map<string, unordered_map<string, int> > pos_to_edit_to_depth;
unordered_map<int, int> pos_to_qual;
bool inverse = false;
bool remove_failing_edits = false;
bool filter_matches = false;
bool do_path_divergence;
bool do_reversing;
int min_depth = 0;
int min_qual = 0;
int min_cov = 0;
int window_length = 0;
int qual_offset = 0;
int soft_clip_limit = -1;
int split_read_limit = -1;
double min_percent_identity = 0.0;
double min_avg_qual = 0.0;
};
}
#endif
<|endoftext|>
|
<commit_before>/*
* mod_dup - duplicates apache requests
*
* Copyright (C) 2013 Orange
*
* 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 "mod_dup.hh"
#include <http_config.h>
namespace DupModule {
const unsigned int CMaxBytes = 8192;
bool
extractBrigadeContent(apr_bucket_brigade *bb, request_rec *pRequest, std::string &content) {
if (ap_get_brigade(pRequest->input_filters,
bb, AP_MODE_READBYTES, APR_BLOCK_READ, CMaxBytes) == APR_SUCCESS) {
// Read brigade content
for (apr_bucket *b = APR_BRIGADE_FIRST(bb);
b != APR_BRIGADE_SENTINEL(bb);
b = APR_BUCKET_NEXT(b) ) {
// Metadata end of stream
if (APR_BUCKET_IS_EOS(b)) {
return true;
}
const char *data = 0;
apr_size_t len = 0;
apr_status_t rv = apr_bucket_read(b, &data, &len, APR_BLOCK_READ);
if (rv != APR_SUCCESS) {
Log::error(42, "Bucket read failed, skipping the rest of the body");
return true;
}
if (len) {
content.append(data, len);
}
}
}
else {
Log::error(42, "Get brigade failed, skipping the rest of the body");
return true;
}
return false;
}
int
translateHook(request_rec *pRequest) {
if (!pRequest->per_dir_config)
return DECLINED;
DupConf *tConf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));
if (!tConf || !tConf->dirName) {
// Not a location that we treat, we decline the request
return DECLINED;
}
RequestInfo *info = new RequestInfo(tConf->getNextReqId());
// Backup in request context
ap_set_module_config(pRequest->request_config, &dup_module, (void *)info);
if (!pRequest->connection->pool) {
Log::error(42, "No connection pool associated to the request");
return DECLINED;
}
if (!pRequest->connection->bucket_alloc) {
pRequest->connection->bucket_alloc = apr_bucket_alloc_create(pRequest->connection->pool);
if (!pRequest->connection->bucket_alloc) {
Log::error(42, "Request bucket allocation failed");
return DECLINED;
}
}
apr_bucket_brigade *bb = apr_brigade_create(pRequest->connection->pool, pRequest->connection->bucket_alloc);
if (!bb) {
Log::error(42, "Bucket brigade allocation failed");
return DECLINED;
}
while (!extractBrigadeContent(bb, pRequest, info->mBody)){
apr_brigade_cleanup(bb);
}
apr_brigade_cleanup(bb);
// Body read :)
// Copy Request ID in both headers
std::string reqId = boost::lexical_cast<std::string>(info->mId);
apr_table_set(pRequest->headers_in, c_UNIQUE_ID, reqId.c_str());
apr_table_set(pRequest->headers_out, c_UNIQUE_ID, reqId.c_str());
// Synchronous context enrichment
info->mConfPath = tConf->dirName;
info->mArgs = pRequest->args ? pRequest->args : "";
gProcessor->enrichContext(pRequest, *info);
return DECLINED;
}
/**
* Reinject the body we saved in earlyHook into a brigade
*/
apr_status_t
inputFilterBody2Brigade(ap_filter_t *pF, apr_bucket_brigade *pB, ap_input_mode_t pMode, apr_read_type_e pBlock, apr_off_t pReadbytes)
{
request_rec *pRequest = pF->r;
if (!pRequest || !pRequest->per_dir_config) {
apr_bucket *e = apr_bucket_eos_create(pF->c->bucket_alloc);
assert(e);
APR_BRIGADE_INSERT_TAIL(pB, e);
return APR_SUCCESS;
}
// Retrieve request info from context
RequestInfo *info = reinterpret_cast<RequestInfo *>(ap_get_module_config(pRequest->request_config, &dup_module));
if (!info) {
// Should not happen
apr_bucket *e = apr_bucket_eos_create(pF->c->bucket_alloc);
assert(e);
APR_BRIGADE_INSERT_TAIL(pB, e);
return APR_SUCCESS;
}
if (!pF->ctx) {
if (!info->mBody.empty()) {
apr_status_t st;
Log::warn(1, "Wrote body to brigade: %s", info->mBody.c_str());
if ((st = apr_brigade_write(pB, NULL, NULL, info->mBody.c_str(), info->mBody.size())) != APR_SUCCESS ) {
Log::warn(1, "Failed to write request body in a brigade: %s", info->mBody.c_str());
return st;
}
}
// Marks the body as sent
pF->ctx = (void *) -1;
}
// Marks that we do not have any more data to read
apr_bucket *e = apr_bucket_eos_create(pF->c->bucket_alloc);
assert(e);
APR_BRIGADE_INSERT_TAIL(pB, e);
return APR_SUCCESS;
}
/*
* Callback to iterate over the headers tables
* Pushes a copy of key => value in a list
*/
static int iterateOverHeadersCallBack(void *d, const char *key, const char *value) {
RequestInfo::tHeaders *headers = reinterpret_cast<RequestInfo::tHeaders *>(d);
headers->push_back(std::pair<std::string, std::string>(key, value));
return 1;
}
static void
prepareRequestInfo(DupConf *tConf, request_rec *pRequest, RequestInfo &r, bool withAnswer) {
// Basic
r.mPoison = false;
r.mConfPath = tConf->dirName;
r.mPath = pRequest->uri;
r.mArgs = pRequest->args ? pRequest->args : "";
// Copy headers in
apr_table_do(&iterateOverHeadersCallBack, &r.mHeadersIn, pRequest->headers_in, NULL);
if (withAnswer) {
// Copy headers out
apr_table_do(&iterateOverHeadersCallBack, &r.mHeadersOut, pRequest->headers_out, NULL);
}
}
static void
printRequest(request_rec *pRequest, RequestInfo *pBH, DupConf *tConf) {
const char *reqId = apr_table_get(pRequest->headers_in, c_UNIQUE_ID);
Log::debug("### Pushing a request with ID: %s, body size:%ld", reqId, pBH->mBody.size());
Log::debug("### Uri:%s, dir name:%s", pRequest->uri, tConf->dirName);
Log::debug("### Request args: %s", pRequest->args);
}
/*
* Request context used during brigade run
*/
class RequestContext {
public:
apr_bucket_brigade *mTmpBB;
RequestInfo *mReq; /** Req is pushed to requestprocessor for duplication and will be deleted later*/
RequestContext(ap_filter_t *pFilter) {
mTmpBB = apr_brigade_create(pFilter->r->pool, pFilter->c->bucket_alloc);
mReq = reinterpret_cast<RequestInfo *>(ap_get_module_config(pFilter->r->request_config,
&dup_module));
assert(mReq);
}
RequestContext()
: mTmpBB(NULL)
, mReq(NULL) {
}
~RequestContext() {
if (mTmpBB) {
apr_brigade_cleanup(mTmpBB);
}
}
};
/**
* Here we can get the response body and finally duplicate or not
*/
apr_status_t
outputFilterHandler(ap_filter_t *pFilter, apr_bucket_brigade *pBrigade) {
request_rec *pRequest = pFilter->r;
// Reject requests that do not meet our requirements
if (!pRequest || !pRequest->per_dir_config)
return ap_pass_brigade(pFilter->next, pBrigade);
struct DupConf *tConf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));
if ((!tConf) || (!tConf->dirName) || (tConf->getHighestDuplicationType() == DuplicationType::NONE)) {
return ap_pass_brigade(pFilter->next, pBrigade);
}
// Request answer analyse
RequestContext *ctx = static_cast<RequestContext *>(pFilter->ctx);
if (ctx == NULL) {
// First pass in the output filter => context init
ctx = new RequestContext(pFilter);
pFilter->ctx = ctx;
} else if (ctx == (void *) -1) {
// Output filter already did his job, we return
return ap_pass_brigade(pFilter->next, pBrigade);
}
// We need to get the highest one as we haven't matched which rule it is yet
if (tConf->getHighestDuplicationType() != DuplicationType::REQUEST_WITH_ANSWER) {
// Asynchronous push of request WITHOUT the answer
RequestInfo *rH = ctx->mReq;
prepareRequestInfo(tConf, pRequest, *rH, false);
printRequest(pRequest, rH, tConf);
gThreadPool->push(rH);
delete ctx;
pFilter->ctx = (void *) -1;
return ap_pass_brigade(pFilter->next, pBrigade);
}
// Asynchronous push of request WITH the answer
apr_bucket *currentBucket;
while ((currentBucket = APR_BRIGADE_FIRST(pBrigade)) != APR_BRIGADE_SENTINEL(pBrigade)) {
const char *data;
apr_size_t len;
apr_status_t rv;
rv = apr_bucket_read(currentBucket, &data, &len, APR_BLOCK_READ);
if ((rv == APR_SUCCESS) && (data != NULL)) {
ctx->mReq->mAnswer.append(data, len);
}
/* Remove bucket e from bb. */
APR_BUCKET_REMOVE(currentBucket);
/* Insert it into temporary brigade. */
APR_BRIGADE_INSERT_HEAD(ctx->mTmpBB, currentBucket);
/* Pass brigade downstream. */
rv = ap_pass_brigade(pFilter->next, ctx->mTmpBB);
if (rv != APR_SUCCESS) {
// Something went wrong, no duplication performed
delete ctx;
pFilter->ctx = (void *) -1;
return rv;
}
if (APR_BUCKET_IS_EOS(currentBucket)) {
// Pushing the answer to the processor
prepareRequestInfo(tConf, pRequest, *(ctx->mReq), true);
printRequest(pRequest, ctx->mReq, tConf);
gThreadPool->push(ctx->mReq);
delete ctx;
pFilter->ctx = (void *) -1;
}
else {
apr_brigade_cleanup(ctx->mTmpBB);
}
}
return OK;
}
};
<commit_msg>Modified request context with shared pointer<commit_after>/*
* mod_dup - duplicates apache requests
*
* Copyright (C) 2013 Orange
*
* 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 "mod_dup.hh"
#include <boost/shared_ptr.hpp>
#include <http_config.h>
namespace DupModule {
const unsigned int CMaxBytes = 8192;
bool
extractBrigadeContent(apr_bucket_brigade *bb, request_rec *pRequest, std::string &content) {
if (ap_get_brigade(pRequest->input_filters,
bb, AP_MODE_READBYTES, APR_BLOCK_READ, CMaxBytes) == APR_SUCCESS) {
// Read brigade content
for (apr_bucket *b = APR_BRIGADE_FIRST(bb);
b != APR_BRIGADE_SENTINEL(bb);
b = APR_BUCKET_NEXT(b) ) {
// Metadata end of stream
if (APR_BUCKET_IS_EOS(b)) {
return true;
}
const char *data = 0;
apr_size_t len = 0;
apr_status_t rv = apr_bucket_read(b, &data, &len, APR_BLOCK_READ);
if (rv != APR_SUCCESS) {
Log::error(42, "Bucket read failed, skipping the rest of the body");
return true;
}
if (len) {
content.append(data, len);
}
}
}
else {
Log::error(42, "Get brigade failed, skipping the rest of the body");
return true;
}
return false;
}
int
translateHook(request_rec *pRequest) {
if (!pRequest->per_dir_config)
return DECLINED;
DupConf *tConf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));
if (!tConf || !tConf->dirName) {
// Not a location that we treat, we decline the request
return DECLINED;
}
RequestInfo *info = new RequestInfo(tConf->getNextReqId());
// Allocation on a shared pointer on the request pool
// We guarantee that whatever happens, the RequestInfo will be deleted
void *space = apr_palloc(pRequest->pool, sizeof(boost::shared_ptr<RequestInfo>));
new (space) boost::shared_ptr<RequestInfo>(info);
// Registering of the shared pointer destructor on the pool
apr_pool_cleanup_register(pRequest->pool, space, cleaner<boost::shared_ptr<RequestInfo> >,
apr_pool_cleanup_null);
// Backup in request context
ap_set_module_config(pRequest->request_config, &dup_module, (void *)info);
if (!pRequest->connection->pool) {
Log::error(42, "No connection pool associated to the request");
return DECLINED;
}
if (!pRequest->connection->bucket_alloc) {
pRequest->connection->bucket_alloc = apr_bucket_alloc_create(pRequest->connection->pool);
if (!pRequest->connection->bucket_alloc) {
Log::error(42, "Request bucket allocation failed");
return DECLINED;
}
}
apr_bucket_brigade *bb = apr_brigade_create(pRequest->connection->pool, pRequest->connection->bucket_alloc);
if (!bb) {
Log::error(42, "Bucket brigade allocation failed");
return DECLINED;
}
while (!extractBrigadeContent(bb, pRequest, info->mBody)){
apr_brigade_cleanup(bb);
}
apr_brigade_cleanup(bb);
// Body read :)
// Copy Request ID in both headers
std::string reqId = boost::lexical_cast<std::string>(info->mId);
apr_table_set(pRequest->headers_in, c_UNIQUE_ID, reqId.c_str());
apr_table_set(pRequest->headers_out, c_UNIQUE_ID, reqId.c_str());
// Synchronous context enrichment
info->mConfPath = tConf->dirName;
info->mArgs = pRequest->args ? pRequest->args : "";
gProcessor->enrichContext(pRequest, *info);
return DECLINED;
}
/**
* Reinject the body we saved in earlyHook into a brigade
*/
apr_status_t
inputFilterBody2Brigade(ap_filter_t *pF, apr_bucket_brigade *pB, ap_input_mode_t pMode, apr_read_type_e pBlock, apr_off_t pReadbytes)
{
request_rec *pRequest = pF->r;
if (!pRequest || !pRequest->per_dir_config) {
apr_bucket *e = apr_bucket_eos_create(pF->c->bucket_alloc);
assert(e);
APR_BRIGADE_INSERT_TAIL(pB, e);
return APR_SUCCESS;
}
// Retrieve request info from context
boost::shared_ptr<RequestInfo> *shPtr = reinterpret_cast<boost::shared_ptr<RequestInfo> *>(ap_get_module_config(pRequest->request_config, &dup_module));
RequestInfo *info = shPtr->get();
if (!info) {
// Should not happen
apr_bucket *e = apr_bucket_eos_create(pF->c->bucket_alloc);
assert(e);
APR_BRIGADE_INSERT_TAIL(pB, e);
return APR_SUCCESS;
}
if (!pF->ctx) {
if (!info->mBody.empty()) {
apr_status_t st;
Log::warn(1, "Wrote body to brigade: %s", info->mBody.c_str());
if ((st = apr_brigade_write(pB, NULL, NULL, info->mBody.c_str(), info->mBody.size())) != APR_SUCCESS ) {
Log::warn(1, "Failed to write request body in a brigade: %s", info->mBody.c_str());
return st;
}
}
// Marks the body as sent
pF->ctx = (void *) -1;
}
// Marks that we do not have any more data to read
apr_bucket *e = apr_bucket_eos_create(pF->c->bucket_alloc);
assert(e);
APR_BRIGADE_INSERT_TAIL(pB, e);
return APR_SUCCESS;
}
/*
* Callback to iterate over the headers tables
* Pushes a copy of key => value in a list
*/
static int iterateOverHeadersCallBack(void *d, const char *key, const char *value) {
RequestInfo::tHeaders *headers = reinterpret_cast<RequestInfo::tHeaders *>(d);
headers->push_back(std::pair<std::string, std::string>(key, value));
return 1;
}
static void
prepareRequestInfo(DupConf *tConf, request_rec *pRequest, RequestInfo &r, bool withAnswer) {
// Basic
r.mPoison = false;
r.mConfPath = tConf->dirName;
r.mPath = pRequest->uri;
r.mArgs = pRequest->args ? pRequest->args : "";
// Copy headers in
apr_table_do(&iterateOverHeadersCallBack, &r.mHeadersIn, pRequest->headers_in, NULL);
if (withAnswer) {
// Copy headers out
apr_table_do(&iterateOverHeadersCallBack, &r.mHeadersOut, pRequest->headers_out, NULL);
}
}
static void
printRequest(request_rec *pRequest, RequestInfo *pBH, DupConf *tConf) {
const char *reqId = apr_table_get(pRequest->headers_in, c_UNIQUE_ID);
Log::debug("### Pushing a request with ID: %s, body size:%ld", reqId, pBH->mBody.size());
Log::debug("### Uri:%s, dir name:%s", pRequest->uri, tConf->dirName);
Log::debug("### Request args: %s", pRequest->args);
}
/*
* Request context used during brigade run
*/
class RequestContext {
public:
apr_bucket_brigade *mTmpBB;
RequestInfo *mReq; /** Req is pushed to requestprocessor for duplication and will be deleted later*/
RequestContext(ap_filter_t *pFilter) {
mTmpBB = apr_brigade_create(pFilter->r->pool, pFilter->c->bucket_alloc);
boost::shared_ptr<RequestInfo> *shPtr = reinterpret_cast<boost::shared_ptr<RequestInfo> *>(ap_get_module_config(pFilter->r->request_config, &dup_module));
mReq = shPtr->get();
assert(mReq);
}
RequestContext()
: mTmpBB(NULL)
, mReq(NULL) {
}
~RequestContext() {
if (mTmpBB) {
apr_brigade_cleanup(mTmpBB);
}
}
};
/**
* Here we can get the response body and finally duplicate or not
*/
apr_status_t
outputFilterHandler(ap_filter_t *pFilter, apr_bucket_brigade *pBrigade) {
request_rec *pRequest = pFilter->r;
// Reject requests that do not meet our requirements
if (!pRequest || !pRequest->per_dir_config)
return ap_pass_brigade(pFilter->next, pBrigade);
struct DupConf *tConf = reinterpret_cast<DupConf *>(ap_get_module_config(pRequest->per_dir_config, &dup_module));
if ((!tConf) || (!tConf->dirName) || (tConf->getHighestDuplicationType() == DuplicationType::NONE)) {
return ap_pass_brigade(pFilter->next, pBrigade);
}
// Request answer analyse
RequestContext *ctx = static_cast<RequestContext *>(pFilter->ctx);
if (ctx == NULL) {
// First pass in the output filter => context init
ctx = new RequestContext(pFilter);
pFilter->ctx = ctx;
} else if (ctx == (void *) -1) {
// Output filter already did his job, we return
return ap_pass_brigade(pFilter->next, pBrigade);
}
// We need to get the highest one as we haven't matched which rule it is yet
if (tConf->getHighestDuplicationType() != DuplicationType::REQUEST_WITH_ANSWER) {
// Asynchronous push of request WITHOUT the answer
RequestInfo *rH = ctx->mReq;
prepareRequestInfo(tConf, pRequest, *rH, false);
printRequest(pRequest, rH, tConf);
gThreadPool->push(rH);
delete ctx;
pFilter->ctx = (void *) -1;
return ap_pass_brigade(pFilter->next, pBrigade);
}
// Asynchronous push of request WITH the answer
apr_bucket *currentBucket;
while ((currentBucket = APR_BRIGADE_FIRST(pBrigade)) != APR_BRIGADE_SENTINEL(pBrigade)) {
const char *data;
apr_size_t len;
apr_status_t rv;
rv = apr_bucket_read(currentBucket, &data, &len, APR_BLOCK_READ);
if ((rv == APR_SUCCESS) && (data != NULL)) {
ctx->mReq->mAnswer.append(data, len);
}
/* Remove bucket e from bb. */
APR_BUCKET_REMOVE(currentBucket);
/* Insert it into temporary brigade. */
APR_BRIGADE_INSERT_HEAD(ctx->mTmpBB, currentBucket);
/* Pass brigade downstream. */
rv = ap_pass_brigade(pFilter->next, ctx->mTmpBB);
if (rv != APR_SUCCESS) {
// Something went wrong, no duplication performed
delete ctx;
pFilter->ctx = (void *) -1;
return rv;
}
if (APR_BUCKET_IS_EOS(currentBucket)) {
// Pushing the answer to the processor
prepareRequestInfo(tConf, pRequest, *(ctx->mReq), true);
printRequest(pRequest, ctx->mReq, tConf);
gThreadPool->push(ctx->mReq);
delete ctx;
pFilter->ctx = (void *) -1;
}
else {
apr_brigade_cleanup(ctx->mTmpBB);
}
}
return OK;
}
};
<|endoftext|>
|
<commit_before>/*
* Copyright 2015 Cloudius Systems
*/
#pragma once
#include "types.hh"
#include "atomic_cell.hh"
#include "query-request.hh"
#include "query-result.hh"
// Refer to query-result.hh for the query result format
namespace query {
class result::row_writer {
bytes_ostream& _w;
const partition_slice& _slice;
bytes_ostream::place_holder<uint32_t> _size_ph;
size_t _start_pos;
bool _finished = false;
public:
row_writer(
const partition_slice& slice,
bytes_ostream& w,
bytes_ostream::place_holder<uint32_t> size_ph)
: _w(w)
, _slice(slice)
, _size_ph(size_ph)
, _start_pos(w.size())
{ }
~row_writer() {
assert(_finished);
}
void add_empty() {
// FIXME: store this in a bitmap
_w.write<int8_t>(false);
}
void add(::atomic_cell_view c) {
// FIXME: store this in a bitmap
_w.write<int8_t>(true);
assert(c.is_live());
if (_slice.options.contains<partition_slice::option::send_timestamp_and_expiry>()) {
_w.write(c.timestamp());
if (c.is_live_and_has_ttl()) {
_w.write<gc_clock::rep>(c.expiry().time_since_epoch().count());
} else {
_w.write<gc_clock::rep>(std::numeric_limits<gc_clock::rep>::max());
}
}
_w.write_blob(c.value());
}
void add(collection_mutation::view v) {
// FIXME: store this in a bitmap
_w.write<int8_t>(true);
_w.write_blob(v.data);
}
void finish() {
auto row_size = _w.size() - _start_pos;
assert((uint32_t)row_size == row_size);
_w.set(_size_ph, (uint32_t)row_size);
_finished = true;
}
};
// Call finish() or retract() when done.
class result::partition_writer {
bytes_ostream& _w;
const partition_slice& _slice;
bytes_ostream::place_holder<uint32_t> _count_ph;
bytes_ostream::position _pos;
uint32_t _row_count = 0;
bool _static_row_added = false;
bool _finished = false;
public:
partition_writer(
const partition_slice& slice,
bytes_ostream::place_holder<uint32_t> count_ph,
bytes_ostream::position pos,
bytes_ostream& w)
: _w(w)
, _slice(slice)
, _count_ph(count_ph)
, _pos(pos)
{ }
~partition_writer() {
assert(_finished);
}
row_writer add_row(const clustering_key& key) {
if (_slice.options.contains<partition_slice::option::send_clustering_key>()) {
_w.write_blob(key);
}
++_row_count;
auto size_placeholder = _w.write_place_holder<uint32_t>();
return row_writer(_slice, _w, size_placeholder);
}
// Call before any add_row()
row_writer add_static_row() {
assert(!_static_row_added); // Static row can be added only once
assert(!_row_count); // Static row must be added before clustered rows
_static_row_added = true;
auto size_placeholder = _w.write_place_holder<uint32_t>();
return row_writer(_slice, _w, size_placeholder);
}
uint32_t row_count() const {
return _row_count;
}
void finish() {
_w.set(_count_ph, _row_count);
// The partition is live. If there are no clustered rows, there
// must be something live in the static row, which counts as one row.
_row_count = std::max<uint32_t>(_row_count, 1);
_finished = true;
}
void retract() {
_row_count = 0;
_w.retract(_pos);
_finished = true;
}
const partition_slice& slice() const {
return _slice;
}
};
class result::builder {
bytes_ostream _w;
const partition_slice& _slice;
public:
builder(const partition_slice& slice) : _slice(slice) { }
// Starts new partition and returns a builder for its contents.
// Invalidates all previously obtained builders
partition_writer add_partition(const partition_key& key) {
auto pos = _w.pos();
auto count_place_holder = _w.write_place_holder<uint32_t>();
if (_slice.options.contains<partition_slice::option::send_partition_key>()) {
_w.write_blob(key);
}
return partition_writer(_slice, count_place_holder, pos, _w);
}
result build() {
return result(std::move(_w));
};
const partition_slice& slice() const {
return _slice;
}
};
}
<commit_msg>query-result-writer: Remove assert(_finished) guards from destructors<commit_after>/*
* Copyright 2015 Cloudius Systems
*/
#pragma once
#include "types.hh"
#include "atomic_cell.hh"
#include "query-request.hh"
#include "query-result.hh"
// Refer to query-result.hh for the query result format
namespace query {
class result::row_writer {
bytes_ostream& _w;
const partition_slice& _slice;
bytes_ostream::place_holder<uint32_t> _size_ph;
size_t _start_pos;
public:
row_writer(
const partition_slice& slice,
bytes_ostream& w,
bytes_ostream::place_holder<uint32_t> size_ph)
: _w(w)
, _slice(slice)
, _size_ph(size_ph)
, _start_pos(w.size())
{ }
void add_empty() {
// FIXME: store this in a bitmap
_w.write<int8_t>(false);
}
void add(::atomic_cell_view c) {
// FIXME: store this in a bitmap
_w.write<int8_t>(true);
assert(c.is_live());
if (_slice.options.contains<partition_slice::option::send_timestamp_and_expiry>()) {
_w.write(c.timestamp());
if (c.is_live_and_has_ttl()) {
_w.write<gc_clock::rep>(c.expiry().time_since_epoch().count());
} else {
_w.write<gc_clock::rep>(std::numeric_limits<gc_clock::rep>::max());
}
}
_w.write_blob(c.value());
}
void add(collection_mutation::view v) {
// FIXME: store this in a bitmap
_w.write<int8_t>(true);
_w.write_blob(v.data);
}
void finish() {
auto row_size = _w.size() - _start_pos;
assert((uint32_t)row_size == row_size);
_w.set(_size_ph, (uint32_t)row_size);
}
};
// Call finish() or retract() when done.
class result::partition_writer {
bytes_ostream& _w;
const partition_slice& _slice;
bytes_ostream::place_holder<uint32_t> _count_ph;
bytes_ostream::position _pos;
uint32_t _row_count = 0;
bool _static_row_added = false;
public:
partition_writer(
const partition_slice& slice,
bytes_ostream::place_holder<uint32_t> count_ph,
bytes_ostream::position pos,
bytes_ostream& w)
: _w(w)
, _slice(slice)
, _count_ph(count_ph)
, _pos(pos)
{ }
row_writer add_row(const clustering_key& key) {
if (_slice.options.contains<partition_slice::option::send_clustering_key>()) {
_w.write_blob(key);
}
++_row_count;
auto size_placeholder = _w.write_place_holder<uint32_t>();
return row_writer(_slice, _w, size_placeholder);
}
// Call before any add_row()
row_writer add_static_row() {
assert(!_static_row_added); // Static row can be added only once
assert(!_row_count); // Static row must be added before clustered rows
_static_row_added = true;
auto size_placeholder = _w.write_place_holder<uint32_t>();
return row_writer(_slice, _w, size_placeholder);
}
uint32_t row_count() const {
return _row_count;
}
void finish() {
_w.set(_count_ph, _row_count);
// The partition is live. If there are no clustered rows, there
// must be something live in the static row, which counts as one row.
_row_count = std::max<uint32_t>(_row_count, 1);
}
void retract() {
_row_count = 0;
_w.retract(_pos);
}
const partition_slice& slice() const {
return _slice;
}
};
class result::builder {
bytes_ostream _w;
const partition_slice& _slice;
public:
builder(const partition_slice& slice) : _slice(slice) { }
// Starts new partition and returns a builder for its contents.
// Invalidates all previously obtained builders
partition_writer add_partition(const partition_key& key) {
auto pos = _w.pos();
auto count_place_holder = _w.write_place_holder<uint32_t>();
if (_slice.options.contains<partition_slice::option::send_partition_key>()) {
_w.write_blob(key);
}
return partition_writer(_slice, count_place_holder, pos, _w);
}
result build() {
return result(std::move(_w));
};
const partition_slice& slice() const {
return _slice;
}
};
}
<|endoftext|>
|
<commit_before><commit_msg>Already sync not necessary to sync twice<commit_after><|endoftext|>
|
<commit_before>/*
* Copyright 2019 The Android Open Source Project
*
* 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 <oboe/AudioStreamBuilder.h>
#include <oboe/Oboe.h>
#include "OboeDebug.h"
#include "QuirksManager.h"
using namespace oboe;
int32_t QuirksManager::DeviceQuirks::clipBufferSize(AudioStream &stream,
int32_t requestedSize) {
if (!OboeGlobals::areWorkaroundsEnabled()) {
return requestedSize;
}
int bottomMargin = kDefaultBottomMarginInBursts;
int topMargin = kDefaultTopMarginInBursts;
if (isMMapUsed(stream)) {
if (stream.getSharingMode() == SharingMode::Exclusive) {
bottomMargin = getExclusiveBottomMarginInBursts();
topMargin = getExclusiveTopMarginInBursts();
}
} else {
bottomMargin = kLegacyBottomMarginInBursts;
}
int32_t burst = stream.getFramesPerBurst();
int32_t minSize = bottomMargin * burst;
int32_t adjustedSize = requestedSize;
if (adjustedSize < minSize ) {
adjustedSize = minSize;
} else {
int32_t maxSize = stream.getBufferCapacityInFrames() - (topMargin * burst);
if (adjustedSize > maxSize ) {
adjustedSize = maxSize;
}
}
return adjustedSize;
}
bool QuirksManager::DeviceQuirks::isAAudioMMapPossible(const AudioStreamBuilder &builder) const {
bool isSampleRateCompatible =
builder.getSampleRate() == oboe::Unspecified
|| builder.getSampleRate() == kCommonNativeRate
|| builder.getSampleRateConversionQuality() != SampleRateConversionQuality::None;
return builder.getPerformanceMode() == PerformanceMode::LowLatency
&& isSampleRateCompatible
&& builder.getChannelCount() <= kChannelCountStereo;
}
class SamsungDeviceQuirks : public QuirksManager::DeviceQuirks {
public:
SamsungDeviceQuirks() {
std::string arch = getPropertyString("ro.arch");
isExynos = (arch.rfind("exynos", 0) == 0); // starts with?
std::string chipname = getPropertyString("ro.hardware.chipname");
isExynos9810 = (chipname == "exynos9810");
isExynos990 = (chipname == "exynos990");
isExynos850 = (chipname == "exynos850");
mBuildChangelist = getPropertyInteger("ro.build.changelist", 0);
}
virtual ~SamsungDeviceQuirks() = default;
int32_t getExclusiveBottomMarginInBursts() const override {
// TODO Make this conditional on build version when MMAP timing improves.
return isExynos ? kBottomMarginExynos : kBottomMarginOther;
}
int32_t getExclusiveTopMarginInBursts() const override {
return kTopMargin;
}
// See Oboe issues #824 and #1247 for more information.
bool isMonoMMapActuallyStereo() const override {
return isExynos9810 || isExynos850; // TODO We can make this version specific if it gets fixed.
}
bool isAAudioMMapPossible(const AudioStreamBuilder &builder) const override {
return DeviceQuirks::isAAudioMMapPossible(builder)
// Samsung says they use Legacy for Camcorder
&& builder.getInputPreset() != oboe::InputPreset::Camcorder;
}
bool isMMapSafe(const AudioStreamBuilder &builder) override {
const bool isInput = builder.getDirection() == Direction::Input;
// This detects b/159066712 , S20 LSI has corrupt low latency audio recording
// and turns off MMAP.
// See also https://github.com/google/oboe/issues/892
bool mRecordingCorrupted = isInput
&& isExynos990
&& mBuildChangelist < 19350896;
return !mRecordingCorrupted;
}
private:
// Stay farther away from DSP position on Exynos devices.
static constexpr int32_t kBottomMarginExynos = 2;
static constexpr int32_t kBottomMarginOther = 1;
static constexpr int32_t kTopMargin = 1;
bool isExynos = false;
bool isExynos9810 = false;
bool isExynos990 = false;
bool isExynos850 = false;
int mBuildChangelist = 0;
};
QuirksManager::QuirksManager() {
std::string manufacturer = getPropertyString("ro.product.manufacturer");
if (manufacturer == "samsung") {
mDeviceQuirks = std::make_unique<SamsungDeviceQuirks>();
} else {
mDeviceQuirks = std::make_unique<DeviceQuirks>();
}
}
bool QuirksManager::isConversionNeeded(
const AudioStreamBuilder &builder,
AudioStreamBuilder &childBuilder) {
bool conversionNeeded = false;
const bool isLowLatency = builder.getPerformanceMode() == PerformanceMode::LowLatency;
const bool isInput = builder.getDirection() == Direction::Input;
const bool isFloat = builder.getFormat() == AudioFormat::Float;
// There are multiple bugs involving using callback with a specified callback size.
// Issue #778: O to Q had a problem with Legacy INPUT streams for FLOAT streams
// and a specified callback size. It would assert because of a bad buffer size.
//
// Issue #973: O to R had a problem with Legacy output streams using callback and a specified callback size.
// An AudioTrack stream could still be running when the AAudio FixedBlockReader was closed.
// Internally b/161914201#comment25
//
// Issue #983: O to R would glitch if the framesPerCallback was too small.
//
// Most of these problems were related to Legacy stream. MMAP was OK. But we don't
// know if we will get an MMAP stream. So, to be safe, just do the conversion in Oboe.
if (OboeGlobals::areWorkaroundsEnabled()
&& builder.willUseAAudio()
&& builder.isDataCallbackSpecified()
&& builder.getFramesPerDataCallback() != 0
&& getSdkVersion() <= __ANDROID_API_R__) {
LOGI("QuirksManager::%s() avoid setFramesPerCallback(n>0)", __func__);
childBuilder.setFramesPerCallback(oboe::Unspecified);
conversionNeeded = true;
}
// If a SAMPLE RATE is specified for low latency then let the native code choose an optimal rate.
// TODO There may be a problem if the devices supports low latency
// at a higher rate than the default.
if (builder.getSampleRate() != oboe::Unspecified
&& builder.getSampleRateConversionQuality() != SampleRateConversionQuality::None
&& isLowLatency
) {
childBuilder.setSampleRate(oboe::Unspecified); // native API decides the best sample rate
conversionNeeded = true;
}
// Data Format
// OpenSL ES and AAudio before P do not support FAST path for FLOAT capture.
if (isFloat
&& isInput
&& builder.isFormatConversionAllowed()
&& isLowLatency
&& (!builder.willUseAAudio() || (getSdkVersion() < __ANDROID_API_P__))
) {
childBuilder.setFormat(AudioFormat::I16); // needed for FAST track
conversionNeeded = true;
LOGI("QuirksManager::%s() forcing internal format to I16 for low latency", __func__);
}
// Add quirk for float output on API <21
if (isFloat
&& !isInput
&& getSdkVersion() < __ANDROID_API_L__ && builder.isFormatConversionAllowed()) {
childBuilder.setFormat(AudioFormat::I16);
conversionNeeded = true;
LOGI("QuirksManager::%s() float was requested but not supported on pre-L devices, "
"creating an underlying I16 stream and using format conversion to provide a float "
"stream", __func__);
}
// Channel Count conversions
if (OboeGlobals::areWorkaroundsEnabled()
&& builder.isChannelConversionAllowed()
&& builder.getChannelCount() == kChannelCountStereo
&& isInput
&& isLowLatency
&& (!builder.willUseAAudio() && (getSdkVersion() == __ANDROID_API_O__))
) {
// Workaround for heap size regression in O.
// b/66967812 AudioRecord does not allow FAST track for stereo capture in O
childBuilder.setChannelCount(kChannelCountMono);
conversionNeeded = true;
LOGI("QuirksManager::%s() using mono internally for low latency on O", __func__);
} else if (OboeGlobals::areWorkaroundsEnabled()
&& builder.getChannelCount() == kChannelCountMono
&& isInput
&& mDeviceQuirks->isMonoMMapActuallyStereo()
&& builder.willUseAAudio()
// Note: we might use this workaround on a device that supports
// MMAP but will use Legacy for this stream. But this will only happen
// on devices that have the broken mono.
&& mDeviceQuirks->isAAudioMMapPossible(builder)
) {
// Workaround for mono actually running in stereo mode.
childBuilder.setChannelCount(kChannelCountStereo); // Use stereo and extract first channel.
conversionNeeded = true;
LOGI("QuirksManager::%s() using stereo internally to avoid broken mono", __func__);
}
// Note that MMAP does not support mono in 8.1. But that would only matter on Pixel 1
// phones and they have almost all been updated to 9.0.
return conversionNeeded;
}
bool QuirksManager::isMMapSafe(AudioStreamBuilder &builder) {
if (!OboeGlobals::areWorkaroundsEnabled()) return true;
return mDeviceQuirks->isMMapSafe(builder);
}
<commit_msg>Fix formatting<commit_after>/*
* Copyright 2019 The Android Open Source Project
*
* 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 <oboe/AudioStreamBuilder.h>
#include <oboe/Oboe.h>
#include "OboeDebug.h"
#include "QuirksManager.h"
using namespace oboe;
int32_t QuirksManager::DeviceQuirks::clipBufferSize(AudioStream &stream,
int32_t requestedSize) {
if (!OboeGlobals::areWorkaroundsEnabled()) {
return requestedSize;
}
int bottomMargin = kDefaultBottomMarginInBursts;
int topMargin = kDefaultTopMarginInBursts;
if (isMMapUsed(stream)) {
if (stream.getSharingMode() == SharingMode::Exclusive) {
bottomMargin = getExclusiveBottomMarginInBursts();
topMargin = getExclusiveTopMarginInBursts();
}
} else {
bottomMargin = kLegacyBottomMarginInBursts;
}
int32_t burst = stream.getFramesPerBurst();
int32_t minSize = bottomMargin * burst;
int32_t adjustedSize = requestedSize;
if (adjustedSize < minSize ) {
adjustedSize = minSize;
} else {
int32_t maxSize = stream.getBufferCapacityInFrames() - (topMargin * burst);
if (adjustedSize > maxSize ) {
adjustedSize = maxSize;
}
}
return adjustedSize;
}
bool QuirksManager::DeviceQuirks::isAAudioMMapPossible(const AudioStreamBuilder &builder) const {
bool isSampleRateCompatible =
builder.getSampleRate() == oboe::Unspecified
|| builder.getSampleRate() == kCommonNativeRate
|| builder.getSampleRateConversionQuality() != SampleRateConversionQuality::None;
return builder.getPerformanceMode() == PerformanceMode::LowLatency
&& isSampleRateCompatible
&& builder.getChannelCount() <= kChannelCountStereo;
}
class SamsungDeviceQuirks : public QuirksManager::DeviceQuirks {
public:
SamsungDeviceQuirks() {
std::string arch = getPropertyString("ro.arch");
isExynos = (arch.rfind("exynos", 0) == 0); // starts with?
std::string chipname = getPropertyString("ro.hardware.chipname");
isExynos9810 = (chipname == "exynos9810");
isExynos990 = (chipname == "exynos990");
isExynos850 = (chipname == "exynos850");
mBuildChangelist = getPropertyInteger("ro.build.changelist", 0);
}
virtual ~SamsungDeviceQuirks() = default;
int32_t getExclusiveBottomMarginInBursts() const override {
// TODO Make this conditional on build version when MMAP timing improves.
return isExynos ? kBottomMarginExynos : kBottomMarginOther;
}
int32_t getExclusiveTopMarginInBursts() const override {
return kTopMargin;
}
// See Oboe issues #824 and #1247 for more information.
bool isMonoMMapActuallyStereo() const override {
return isExynos9810 || isExynos850; // TODO We can make this version specific if it gets fixed.
}
bool isAAudioMMapPossible(const AudioStreamBuilder &builder) const override {
return DeviceQuirks::isAAudioMMapPossible(builder)
// Samsung says they use Legacy for Camcorder
&& builder.getInputPreset() != oboe::InputPreset::Camcorder;
}
bool isMMapSafe(const AudioStreamBuilder &builder) override {
const bool isInput = builder.getDirection() == Direction::Input;
// This detects b/159066712 , S20 LSI has corrupt low latency audio recording
// and turns off MMAP.
// See also https://github.com/google/oboe/issues/892
bool mRecordingCorrupted = isInput
&& isExynos990
&& mBuildChangelist < 19350896;
return !mRecordingCorrupted;
}
private:
// Stay farther away from DSP position on Exynos devices.
static constexpr int32_t kBottomMarginExynos = 2;
static constexpr int32_t kBottomMarginOther = 1;
static constexpr int32_t kTopMargin = 1;
bool isExynos = false;
bool isExynos9810 = false;
bool isExynos990 = false;
bool isExynos850 = false;
int mBuildChangelist = 0;
};
QuirksManager::QuirksManager() {
std::string manufacturer = getPropertyString("ro.product.manufacturer");
if (manufacturer == "samsung") {
mDeviceQuirks = std::make_unique<SamsungDeviceQuirks>();
} else {
mDeviceQuirks = std::make_unique<DeviceQuirks>();
}
}
bool QuirksManager::isConversionNeeded(
const AudioStreamBuilder &builder,
AudioStreamBuilder &childBuilder) {
bool conversionNeeded = false;
const bool isLowLatency = builder.getPerformanceMode() == PerformanceMode::LowLatency;
const bool isInput = builder.getDirection() == Direction::Input;
const bool isFloat = builder.getFormat() == AudioFormat::Float;
// There are multiple bugs involving using callback with a specified callback size.
// Issue #778: O to Q had a problem with Legacy INPUT streams for FLOAT streams
// and a specified callback size. It would assert because of a bad buffer size.
//
// Issue #973: O to R had a problem with Legacy output streams using callback and a specified callback size.
// An AudioTrack stream could still be running when the AAudio FixedBlockReader was closed.
// Internally b/161914201#comment25
//
// Issue #983: O to R would glitch if the framesPerCallback was too small.
//
// Most of these problems were related to Legacy stream. MMAP was OK. But we don't
// know if we will get an MMAP stream. So, to be safe, just do the conversion in Oboe.
if (OboeGlobals::areWorkaroundsEnabled()
&& builder.willUseAAudio()
&& builder.isDataCallbackSpecified()
&& builder.getFramesPerDataCallback() != 0
&& getSdkVersion() <= __ANDROID_API_R__) {
LOGI("QuirksManager::%s() avoid setFramesPerCallback(n>0)", __func__);
childBuilder.setFramesPerCallback(oboe::Unspecified);
conversionNeeded = true;
}
// If a SAMPLE RATE is specified for low latency then let the native code choose an optimal rate.
// TODO There may be a problem if the devices supports low latency
// at a higher rate than the default.
if (builder.getSampleRate() != oboe::Unspecified
&& builder.getSampleRateConversionQuality() != SampleRateConversionQuality::None
&& isLowLatency
) {
childBuilder.setSampleRate(oboe::Unspecified); // native API decides the best sample rate
conversionNeeded = true;
}
// Data Format
// OpenSL ES and AAudio before P do not support FAST path for FLOAT capture.
if (isFloat
&& isInput
&& builder.isFormatConversionAllowed()
&& isLowLatency
&& (!builder.willUseAAudio() || (getSdkVersion() < __ANDROID_API_P__))
) {
childBuilder.setFormat(AudioFormat::I16); // needed for FAST track
conversionNeeded = true;
LOGI("QuirksManager::%s() forcing internal format to I16 for low latency", __func__);
}
// Add quirk for float output on API <21
if (isFloat
&& !isInput
&& getSdkVersion() < __ANDROID_API_L__
&& builder.isFormatConversionAllowed()
) {
childBuilder.setFormat(AudioFormat::I16);
conversionNeeded = true;
LOGI("QuirksManager::%s() float was requested but not supported on pre-L devices, "
"creating an underlying I16 stream and using format conversion to provide a float "
"stream", __func__);
}
// Channel Count conversions
if (OboeGlobals::areWorkaroundsEnabled()
&& builder.isChannelConversionAllowed()
&& builder.getChannelCount() == kChannelCountStereo
&& isInput
&& isLowLatency
&& (!builder.willUseAAudio() && (getSdkVersion() == __ANDROID_API_O__))
) {
// Workaround for heap size regression in O.
// b/66967812 AudioRecord does not allow FAST track for stereo capture in O
childBuilder.setChannelCount(kChannelCountMono);
conversionNeeded = true;
LOGI("QuirksManager::%s() using mono internally for low latency on O", __func__);
} else if (OboeGlobals::areWorkaroundsEnabled()
&& builder.getChannelCount() == kChannelCountMono
&& isInput
&& mDeviceQuirks->isMonoMMapActuallyStereo()
&& builder.willUseAAudio()
// Note: we might use this workaround on a device that supports
// MMAP but will use Legacy for this stream. But this will only happen
// on devices that have the broken mono.
&& mDeviceQuirks->isAAudioMMapPossible(builder)
) {
// Workaround for mono actually running in stereo mode.
childBuilder.setChannelCount(kChannelCountStereo); // Use stereo and extract first channel.
conversionNeeded = true;
LOGI("QuirksManager::%s() using stereo internally to avoid broken mono", __func__);
}
// Note that MMAP does not support mono in 8.1. But that would only matter on Pixel 1
// phones and they have almost all been updated to 9.0.
return conversionNeeded;
}
bool QuirksManager::isMMapSafe(AudioStreamBuilder &builder) {
if (!OboeGlobals::areWorkaroundsEnabled()) return true;
return mDeviceQuirks->isMMapSafe(builder);
}
<|endoftext|>
|
<commit_before>/*********************************************************************
*
* Condor ClassAd library
* Copyright (C) 1990-2003, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI and Rajesh Raman.
*
* This source code is covered by the Condor Public License, which can
* be found in the accompanying LICENSE file, or online at
* www.condorproject.org.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS
* FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT
* HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON
* MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS,
* ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY
* PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY
* RIGHT.
*
*********************************************************************/
#include "common.h"
#include "util.h"
using namespace std;
BEGIN_NAMESPACE( classad )
#ifdef WIN32
#define BIGGEST_RANDOM_INT RAND_MAX
int get_random_integer(void)
{
static char initialized = 0;
if (!initialized) {
int seed = time(NULL);
srand(seed);
initialized = 1;
}
return rand();
}
#else
#define BIGGEST_RANDOM_INT INT_MAX
int get_random_integer(void)
{
static char initialized = 0;
if (!initialized) {
int seed = time(NULL);
srand48(seed);
initialized = 1;
}
return (int) (lrand48() & INT_MAX);
}
#endif
double get_random_real(void)
{
return (get_random_integer() / (double) BIGGEST_RANDOM_INT);
}
long timezone_offset(void)
{
#ifdef __APPLE_CC__
static long tz_offset = 0;
static bool have_tz_offset = false;
if (!have_tz_offset) {
struct tm *tms;
time_t clock;
time(&clock);
tms = localtime(&clock);
tz_offset = -tms->tm_gmtoff;
if (0 != tms->tm_isdst) {
tz_offset += 3600;
}
}
return tz_offset;
#else
extern DLL_IMPORT_MAGIC long timezone;
return timezone;
#endif
}
void convert_escapes(string &text, bool &validStr)
{
char *copy;
int length;
int source, dest;
// We now it will be no longer than the original.
length = text.length();
copy = new char[length + 1];
// We scan up to one less than the length, because we ignore
// a terminating slash: it can't be an escape.
dest = 0;
for (source = 0; source < length - 1; source++) {
if (text[source] != '\\' || source == length - 1) {
copy[dest++]= text[source];
}
else {
source++;
char new_char;
switch(text[source]) {
case 'a': new_char = '\a'; break;
case 'b': new_char = '\b'; break;
case 'f': new_char = '\f'; break;
case 'n': new_char = '\n'; break;
case 'r': new_char = '\r'; break;
case 't': new_char = '\t'; break;
case 'v': new_char = '\v'; break;
case '\\': new_char = '\\'; break;
case '\?': new_char = '\?'; break;
case '\'': new_char = '\''; break;
case '\"': new_char = '\"'; break;
default:
if (isodigit(text[source])) {
int number;
// There are three allowed ways to have octal escape characters:
// \[0..3]nn or \nn or \n. We check for them in that order.
if ( source <= length - 3
&& text[source] >= '0' && text[source] <= '3'
&& isodigit(text[source+1])
&& isodigit(text[source+2])) {
// We have the \[0..3]nn case
char octal[4];
octal[0] = text[source];
octal[1] = text[source+1];
octal[2] = text[source+2];
octal[3] = 0;
sscanf(octal, "%o", &number);
new_char = number;
source += 2; // to account for the two extra digits
} else if ( source <= length -2
&& isodigit(text[source+1])) {
// We have the \nn case
char octal[3];
octal[0] = text[source];
octal[1] = text[source+1];
octal[2] = 0;
sscanf(octal, "%o", &number);
new_char = number;
source += 1; // to account for the extra digit
} else if (source <= length - 1) {
char octal[2];
octal[0] = text[source];
octal[1] = 0;
sscanf(octal, "%o", &number);
new_char = number;
} else {
new_char = text[source];
}
if(number == 0) { // "\\0" is an invalid substring within a string literal
validStr = false;
delete [] copy;
return;
}
} else {
new_char = text[source];
}
break;
}
copy[dest++] = new_char;
}
}
copy[dest] = 0;
text = copy;
delete [] copy;
return;
}
void
getLocalTime(time_t *now, struct tm *localtm)
{
#ifndef WIN32
localtime_r( now, localtm );
#else
// there is no localtime_r() on Windows, so for now
// we just call localtime() and deep copy the result.
struct tm *lt_ptr;
lt_ptr = localtime(now);
if (localtm == NULL) { return; }
localtm->tm_sec = lt_ptr->tm_sec; /* seconds */
localtm->tm_min = lt_ptr->tm_min; /* minutes */
localtm->tm_hour = lt_ptr->tm_hour; /* hours */
localtm->tm_mday = lt_ptr->tm_mday; /* day of the month */
localtm->tm_mon = lt_ptr->tm_mon; /* month */
localtm->tm_year = lt_ptr->tm_year; /* year */
localtm->tm_wday = lt_ptr->tm_wday; /* day of the week */
localtm->tm_yday = lt_ptr->tm_yday; /* day in the year */
localtm->tm_isdst = lt_ptr->tm_isdst; /* daylight saving time */
#endif
return;
}
void
getGMTime(time_t *now, struct tm *gtm)
{
#ifndef WIN32
gmtime_r( now, gtm );
#else
// there is no localtime_r() on Windows, so for now
// we just call localtime() and deep copy the result.
struct tm *gt_ptr;
gt_ptr = gmtime(now);
if (gtm == NULL) { return; }
gtm->tm_sec = gt_ptr->tm_sec; /* seconds */
gtm->tm_min = gt_ptr->tm_min; /* minutes */
gtm->tm_hour = gt_ptr->tm_hour; /* hours */
gtm->tm_mday = gt_ptr->tm_mday; /* day of the month */
gtm->tm_mon = gt_ptr->tm_mon; /* month */
gtm->tm_year = gt_ptr->tm_year; /* year */
gtm->tm_wday = gt_ptr->tm_wday; /* day of the week */
gtm->tm_yday = gt_ptr->tm_yday; /* day in the year */
gtm->tm_isdst = gt_ptr->tm_isdst; /* daylight saving time */
#endif
return;
}
void absTimeToString(const abstime_t &atime, string &buffer)
{
int tzsecs;
time_t epoch_time;
char timebuf[32], sign;
struct tm tms;
tzsecs = atime.offset;
epoch_time = atime.secs;
if (tzsecs > 0) {
sign = '+'; // timezone offset's sign
} else {
sign = '-';
tzsecs = -tzsecs;
}
getGMTime(&epoch_time, &tms);
strftime(timebuf, sizeof(timebuf), "%Y-%m-%dT%H:%M:%S", &tms);
buffer += timebuf;
sprintf(timebuf, "%c%02d%02d", sign, tzsecs / 3600, (tzsecs / 60) % 60);
buffer += timebuf;
return;
}
void relTimeToString(double rsecs, string &buffer)
{
double fractional_seconds;
int days, hrs, mins;
double secs;
char timebuf[128];
if( rsecs < 0 ) {
buffer += "-";
rsecs = -rsecs;
}
fractional_seconds = rsecs - floor(rsecs);
days = (int) rsecs;
hrs = days % 86400;
mins = hrs % 3600;
secs = (mins % 60) + fractional_seconds;
days = days / 86400;
hrs = hrs / 3600;
mins = mins / 60;
if (days) {
if (fractional_seconds == 0) {
sprintf(timebuf, "%d+%02d:%02d:%02d", days, hrs, mins, (int) secs);
} else {
sprintf(timebuf, "%d+%02d:%02d:%02g", days, hrs, mins, secs);
}
buffer += timebuf;
} else if (hrs) {
if (fractional_seconds == 0) {
sprintf(timebuf, "%02d:%02d:%02d", hrs, mins, (int) secs);
} else {
sprintf(timebuf, "%02d:%02d:%02g", hrs, mins, secs);
}
buffer += timebuf;
} else if (mins) {
if (fractional_seconds == 0) {
sprintf(timebuf, "%02d:%02d", mins, (int) secs);
} else {
sprintf(timebuf, "%02d:%02g", mins, secs);
}
buffer += timebuf;
return;
} else {
if (fractional_seconds == 0) {
sprintf(timebuf, "%02d", (int) secs);
} else {
sprintf(timebuf, "%02g", secs);
}
buffer += timebuf;
}
return;
}
#ifdef WIN32
int classad_isinf(double x)
{
int result;
result = _fpclass(x);
if (result == _FPCLASS_NINF ) {
/* negative infinity */
return -1;
} else if ( result == _FPCLASS_PINF ) {
/* positive infinity */
return 1;
} else {
/* otherwise */
return 0;
}
}
#elif (defined (__SVR4) && defined (__sun)) || defined(__APPLE_CC__)
#ifndef __APPLE_CC__
#include <ieeefp.h>
#endif
int classad_isinf(double x)
{
if (finite(x) || x != x) {
return 0;
} else if (x > 0) {
return 1;
} else {
return -1;
}
}
#else
int classad_isinf(double x)
{
return isinf(x);
}
#endif
#ifdef __APPLE_CC__
int classad_isnan(double x)
{
return __isnan(x);
}
#else
int classad_isnan(double x)
{
return isnan(x);
}
#endif
END_NAMESPACE // classad
<commit_msg>Fixed namespace problem when compiling with the ClassAd namespace.<commit_after>/*********************************************************************
*
* Condor ClassAd library
* Copyright (C) 1990-2003, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI and Rajesh Raman.
*
* This source code is covered by the Condor Public License, which can
* be found in the accompanying LICENSE file, or online at
* www.condorproject.org.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* AND THE UNIVERSITY OF WISCONSIN-MADISON "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS
* FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT
* HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON
* MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS,
* ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY
* PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY
* RIGHT.
*
*********************************************************************/
#include "common.h"
#include "util.h"
using namespace std;
BEGIN_NAMESPACE( classad )
#ifdef WIN32
#define BIGGEST_RANDOM_INT RAND_MAX
int get_random_integer(void)
{
static char initialized = 0;
if (!initialized) {
int seed = time(NULL);
srand(seed);
initialized = 1;
}
return rand();
}
#else
#define BIGGEST_RANDOM_INT INT_MAX
int get_random_integer(void)
{
static char initialized = 0;
if (!initialized) {
int seed = time(NULL);
srand48(seed);
initialized = 1;
}
return (int) (lrand48() & INT_MAX);
}
#endif
double get_random_real(void)
{
return (get_random_integer() / (double) BIGGEST_RANDOM_INT);
}
long timezone_offset(void)
{
#ifdef __APPLE_CC__
static long tz_offset = 0;
static bool have_tz_offset = false;
if (!have_tz_offset) {
struct tm *tms;
time_t clock;
time(&clock);
tms = localtime(&clock);
tz_offset = -tms->tm_gmtoff;
if (0 != tms->tm_isdst) {
tz_offset += 3600;
}
}
return tz_offset;
#else
extern DLL_IMPORT_MAGIC long timezone;
return ::timezone;
#endif
}
void convert_escapes(string &text, bool &validStr)
{
char *copy;
int length;
int source, dest;
// We now it will be no longer than the original.
length = text.length();
copy = new char[length + 1];
// We scan up to one less than the length, because we ignore
// a terminating slash: it can't be an escape.
dest = 0;
for (source = 0; source < length - 1; source++) {
if (text[source] != '\\' || source == length - 1) {
copy[dest++]= text[source];
}
else {
source++;
char new_char;
switch(text[source]) {
case 'a': new_char = '\a'; break;
case 'b': new_char = '\b'; break;
case 'f': new_char = '\f'; break;
case 'n': new_char = '\n'; break;
case 'r': new_char = '\r'; break;
case 't': new_char = '\t'; break;
case 'v': new_char = '\v'; break;
case '\\': new_char = '\\'; break;
case '\?': new_char = '\?'; break;
case '\'': new_char = '\''; break;
case '\"': new_char = '\"'; break;
default:
if (isodigit(text[source])) {
int number;
// There are three allowed ways to have octal escape characters:
// \[0..3]nn or \nn or \n. We check for them in that order.
if ( source <= length - 3
&& text[source] >= '0' && text[source] <= '3'
&& isodigit(text[source+1])
&& isodigit(text[source+2])) {
// We have the \[0..3]nn case
char octal[4];
octal[0] = text[source];
octal[1] = text[source+1];
octal[2] = text[source+2];
octal[3] = 0;
sscanf(octal, "%o", &number);
new_char = number;
source += 2; // to account for the two extra digits
} else if ( source <= length -2
&& isodigit(text[source+1])) {
// We have the \nn case
char octal[3];
octal[0] = text[source];
octal[1] = text[source+1];
octal[2] = 0;
sscanf(octal, "%o", &number);
new_char = number;
source += 1; // to account for the extra digit
} else if (source <= length - 1) {
char octal[2];
octal[0] = text[source];
octal[1] = 0;
sscanf(octal, "%o", &number);
new_char = number;
} else {
new_char = text[source];
}
if(number == 0) { // "\\0" is an invalid substring within a string literal
validStr = false;
delete [] copy;
return;
}
} else {
new_char = text[source];
}
break;
}
copy[dest++] = new_char;
}
}
copy[dest] = 0;
text = copy;
delete [] copy;
return;
}
void
getLocalTime(time_t *now, struct tm *localtm)
{
#ifndef WIN32
localtime_r( now, localtm );
#else
// there is no localtime_r() on Windows, so for now
// we just call localtime() and deep copy the result.
struct tm *lt_ptr;
lt_ptr = localtime(now);
if (localtm == NULL) { return; }
localtm->tm_sec = lt_ptr->tm_sec; /* seconds */
localtm->tm_min = lt_ptr->tm_min; /* minutes */
localtm->tm_hour = lt_ptr->tm_hour; /* hours */
localtm->tm_mday = lt_ptr->tm_mday; /* day of the month */
localtm->tm_mon = lt_ptr->tm_mon; /* month */
localtm->tm_year = lt_ptr->tm_year; /* year */
localtm->tm_wday = lt_ptr->tm_wday; /* day of the week */
localtm->tm_yday = lt_ptr->tm_yday; /* day in the year */
localtm->tm_isdst = lt_ptr->tm_isdst; /* daylight saving time */
#endif
return;
}
void
getGMTime(time_t *now, struct tm *gtm)
{
#ifndef WIN32
gmtime_r( now, gtm );
#else
// there is no localtime_r() on Windows, so for now
// we just call localtime() and deep copy the result.
struct tm *gt_ptr;
gt_ptr = gmtime(now);
if (gtm == NULL) { return; }
gtm->tm_sec = gt_ptr->tm_sec; /* seconds */
gtm->tm_min = gt_ptr->tm_min; /* minutes */
gtm->tm_hour = gt_ptr->tm_hour; /* hours */
gtm->tm_mday = gt_ptr->tm_mday; /* day of the month */
gtm->tm_mon = gt_ptr->tm_mon; /* month */
gtm->tm_year = gt_ptr->tm_year; /* year */
gtm->tm_wday = gt_ptr->tm_wday; /* day of the week */
gtm->tm_yday = gt_ptr->tm_yday; /* day in the year */
gtm->tm_isdst = gt_ptr->tm_isdst; /* daylight saving time */
#endif
return;
}
void absTimeToString(const abstime_t &atime, string &buffer)
{
int tzsecs;
time_t epoch_time;
char timebuf[32], sign;
struct tm tms;
tzsecs = atime.offset;
epoch_time = atime.secs;
if (tzsecs > 0) {
sign = '+'; // timezone offset's sign
} else {
sign = '-';
tzsecs = -tzsecs;
}
getGMTime(&epoch_time, &tms);
strftime(timebuf, sizeof(timebuf), "%Y-%m-%dT%H:%M:%S", &tms);
buffer += timebuf;
sprintf(timebuf, "%c%02d%02d", sign, tzsecs / 3600, (tzsecs / 60) % 60);
buffer += timebuf;
return;
}
void relTimeToString(double rsecs, string &buffer)
{
double fractional_seconds;
int days, hrs, mins;
double secs;
char timebuf[128];
if( rsecs < 0 ) {
buffer += "-";
rsecs = -rsecs;
}
fractional_seconds = rsecs - floor(rsecs);
days = (int) rsecs;
hrs = days % 86400;
mins = hrs % 3600;
secs = (mins % 60) + fractional_seconds;
days = days / 86400;
hrs = hrs / 3600;
mins = mins / 60;
if (days) {
if (fractional_seconds == 0) {
sprintf(timebuf, "%d+%02d:%02d:%02d", days, hrs, mins, (int) secs);
} else {
sprintf(timebuf, "%d+%02d:%02d:%02g", days, hrs, mins, secs);
}
buffer += timebuf;
} else if (hrs) {
if (fractional_seconds == 0) {
sprintf(timebuf, "%02d:%02d:%02d", hrs, mins, (int) secs);
} else {
sprintf(timebuf, "%02d:%02d:%02g", hrs, mins, secs);
}
buffer += timebuf;
} else if (mins) {
if (fractional_seconds == 0) {
sprintf(timebuf, "%02d:%02d", mins, (int) secs);
} else {
sprintf(timebuf, "%02d:%02g", mins, secs);
}
buffer += timebuf;
return;
} else {
if (fractional_seconds == 0) {
sprintf(timebuf, "%02d", (int) secs);
} else {
sprintf(timebuf, "%02g", secs);
}
buffer += timebuf;
}
return;
}
#ifdef WIN32
int classad_isinf(double x)
{
int result;
result = _fpclass(x);
if (result == _FPCLASS_NINF ) {
/* negative infinity */
return -1;
} else if ( result == _FPCLASS_PINF ) {
/* positive infinity */
return 1;
} else {
/* otherwise */
return 0;
}
}
#elif (defined (__SVR4) && defined (__sun)) || defined(__APPLE_CC__)
#ifndef __APPLE_CC__
#include <ieeefp.h>
#endif
int classad_isinf(double x)
{
if (finite(x) || x != x) {
return 0;
} else if (x > 0) {
return 1;
} else {
return -1;
}
}
#else
int classad_isinf(double x)
{
return isinf(x);
}
#endif
#ifdef __APPLE_CC__
int classad_isnan(double x)
{
return __isnan(x);
}
#else
int classad_isnan(double x)
{
return isnan(x);
}
#endif
END_NAMESPACE // classad
<|endoftext|>
|
<commit_before>//===-- HostInfoBase.cpp ----------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Host/Config.h"
#include "lldb/Core/ArchSpec.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/StreamString.h"
#include "lldb/Host/FileSystem.h"
#include "lldb/Host/Host.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Host/HostInfoBase.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/raw_ostream.h"
#include <thread>
#include <mutex> // std::once
using namespace lldb;
using namespace lldb_private;
namespace
{
void
CleanupProcessSpecificLLDBTempDir()
{
// Get the process specific LLDB temporary directory and delete it.
FileSpec tmpdir_file_spec;
if (!HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
return;
// Remove the LLDB temporary directory if we have one. Set "recurse" to
// true to all files that were created for the LLDB process can be cleaned up.
FileSystem::DeleteDirectory(tmpdir_file_spec.GetDirectory().GetCString(), true);
}
//----------------------------------------------------------------------
// The HostInfoBaseFields is a work around for windows not supporting
// static variables correctly in a thread safe way. Really each of the
// variables in HostInfoBaseFields should live in the functions in which
// they are used and each one should be static, but the work around is
// in place to avoid this restriction. Ick.
//----------------------------------------------------------------------
struct HostInfoBaseFields
{
uint32_t m_number_cpus;
std::string m_vendor_string;
std::string m_os_string;
std::string m_host_triple;
ArchSpec m_host_arch_32;
ArchSpec m_host_arch_64;
FileSpec m_lldb_so_dir;
FileSpec m_lldb_support_exe_dir;
FileSpec m_lldb_headers_dir;
FileSpec m_lldb_python_dir;
FileSpec m_lldb_clang_resource_dir;
FileSpec m_lldb_system_plugin_dir;
FileSpec m_lldb_user_plugin_dir;
FileSpec m_lldb_tmp_dir;
};
HostInfoBaseFields *g_fields = nullptr;
}
void
HostInfoBase::Initialize()
{
g_fields = new HostInfoBaseFields();
}
uint32_t
HostInfoBase::GetNumberCPUS()
{
static std::once_flag g_once_flag;
std::call_once(g_once_flag, []() {
g_fields->m_number_cpus = std::thread::hardware_concurrency();
});
return g_fields->m_number_cpus;
}
uint32_t
HostInfoBase::GetMaxThreadNameLength()
{
return 0;
}
llvm::StringRef
HostInfoBase::GetVendorString()
{
static std::once_flag g_once_flag;
std::call_once(g_once_flag, []() {
g_fields->m_vendor_string = std::move(HostInfo::GetArchitecture().GetTriple().getVendorName().str());
});
return g_fields->m_vendor_string;
}
llvm::StringRef
HostInfoBase::GetOSString()
{
static std::once_flag g_once_flag;
std::call_once(g_once_flag, []() {
g_fields->m_os_string = std::move(HostInfo::GetArchitecture().GetTriple().getOSName());
});
return g_fields->m_os_string;
}
llvm::StringRef
HostInfoBase::GetTargetTriple()
{
static std::once_flag g_once_flag;
std::call_once(g_once_flag, []() {
g_fields->m_host_triple = HostInfo::GetArchitecture().GetTriple().getTriple();
});
return g_fields->m_host_triple;
}
const ArchSpec &
HostInfoBase::GetArchitecture(ArchitectureKind arch_kind)
{
static std::once_flag g_once_flag;
std::call_once(g_once_flag, []() {
HostInfo::ComputeHostArchitectureSupport(g_fields->m_host_arch_32, g_fields->m_host_arch_64);
});
// If an explicit 32 or 64-bit architecture was requested, return that.
if (arch_kind == eArchKind32)
return g_fields->m_host_arch_32;
if (arch_kind == eArchKind64)
return g_fields->m_host_arch_64;
// Otherwise prefer the 64-bit architecture if it is valid.
return (g_fields->m_host_arch_64.IsValid()) ? g_fields->m_host_arch_64 : g_fields->m_host_arch_32;
}
bool
HostInfoBase::GetLLDBPath(lldb::PathType type, FileSpec &file_spec)
{
file_spec.Clear();
#if defined(LLDB_DISABLE_PYTHON)
if (type == lldb::ePathTypePythonDir)
return false;
#endif
FileSpec *result = nullptr;
switch (type)
{
case lldb::ePathTypeLLDBShlibDir:
{
static std::once_flag g_once_flag;
static bool success = false;
std::call_once(g_once_flag, []() {
success = HostInfo::ComputeSharedLibraryDirectory (g_fields->m_lldb_so_dir);
Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
if (log)
log->Printf("HostInfoBase::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'", g_fields->m_lldb_so_dir.GetPath().c_str());
});
if (success)
result = &g_fields->m_lldb_so_dir;
}
break;
case lldb::ePathTypeSupportExecutableDir:
{
static std::once_flag g_once_flag;
static bool success = false;
std::call_once(g_once_flag, []() {
success = HostInfo::ComputeSupportExeDirectory (g_fields->m_lldb_support_exe_dir);
Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
if (log)
log->Printf("HostInfoBase::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'",
g_fields->m_lldb_support_exe_dir.GetPath().c_str());
});
if (success)
result = &g_fields->m_lldb_support_exe_dir;
}
break;
case lldb::ePathTypeHeaderDir:
{
static std::once_flag g_once_flag;
static bool success = false;
std::call_once(g_once_flag, []() {
success = HostInfo::ComputeHeaderDirectory (g_fields->m_lldb_headers_dir);
Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
if (log)
log->Printf("HostInfoBase::GetLLDBPath(ePathTypeHeaderDir) => '%s'", g_fields->m_lldb_headers_dir.GetPath().c_str());
});
if (success)
result = &g_fields->m_lldb_headers_dir;
}
break;
case lldb::ePathTypePythonDir:
{
static std::once_flag g_once_flag;
static bool success = false;
std::call_once(g_once_flag, []() {
success = HostInfo::ComputePythonDirectory (g_fields->m_lldb_python_dir);
Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
if (log)
log->Printf("HostInfoBase::GetLLDBPath(ePathTypePythonDir) => '%s'", g_fields->m_lldb_python_dir.GetPath().c_str());
});
if (success)
result = &g_fields->m_lldb_python_dir;
}
break;
case lldb::ePathTypeClangDir:
{
static std::once_flag g_once_flag;
static bool success = false;
std::call_once(g_once_flag, []() {
success = HostInfo::ComputeClangDirectory (g_fields->m_lldb_clang_resource_dir);
Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
if (log)
log->Printf("HostInfoBase::GetLLDBPath(ePathTypeClangResourceDir) => '%s'", g_fields->m_lldb_clang_resource_dir.GetPath().c_str());
});
if (success)
result = &g_fields->m_lldb_clang_resource_dir;
}
break;
case lldb::ePathTypeLLDBSystemPlugins:
{
static std::once_flag g_once_flag;
static bool success = false;
std::call_once(g_once_flag, []() {
success = HostInfo::ComputeSystemPluginsDirectory (g_fields->m_lldb_system_plugin_dir);
Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
if (log)
log->Printf("HostInfoBase::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'",
g_fields->m_lldb_system_plugin_dir.GetPath().c_str());
});
if (success)
result = &g_fields->m_lldb_system_plugin_dir;
}
break;
case lldb::ePathTypeLLDBUserPlugins:
{
static std::once_flag g_once_flag;
static bool success = false;
std::call_once(g_once_flag, []() {
success = HostInfo::ComputeUserPluginsDirectory (g_fields->m_lldb_user_plugin_dir);
Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
if (log)
log->Printf("HostInfoBase::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'",
g_fields->m_lldb_user_plugin_dir.GetPath().c_str());
});
if (success)
result = &g_fields->m_lldb_user_plugin_dir;
}
break;
case lldb::ePathTypeLLDBTempSystemDir:
{
static std::once_flag g_once_flag;
static bool success = false;
std::call_once(g_once_flag, []() {
success = HostInfo::ComputeTempFileDirectory (g_fields->m_lldb_tmp_dir);
Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
if (log)
log->Printf("HostInfoBase::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_fields->m_lldb_tmp_dir.GetPath().c_str());
});
if (success)
result = &g_fields->m_lldb_tmp_dir;
}
break;
}
if (!result)
return false;
file_spec = *result;
return true;
}
bool
HostInfoBase::ComputeSharedLibraryDirectory(FileSpec &file_spec)
{
// To get paths related to LLDB we get the path to the executable that
// contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
// on linux this is assumed to be the "lldb" main executable. If LLDB on
// linux is actually in a shared library (liblldb.so) then this function will
// need to be modified to "do the right thing".
FileSpec lldb_file_spec(
Host::GetModuleFileSpecForHostAddress(reinterpret_cast<void *>(reinterpret_cast<intptr_t>(HostInfoBase::GetLLDBPath))));
// Remove the filename so that this FileSpec only represents the directory.
file_spec.GetDirectory() = lldb_file_spec.GetDirectory();
return (bool)file_spec.GetDirectory();
}
bool
HostInfoBase::ComputeSupportExeDirectory(FileSpec &file_spec)
{
return GetLLDBPath(lldb::ePathTypeLLDBShlibDir, file_spec);
}
bool
HostInfoBase::ComputeTempFileDirectory(FileSpec &file_spec)
{
const char *tmpdir_cstr = getenv("TMPDIR");
if (tmpdir_cstr == NULL)
{
tmpdir_cstr = getenv("TMP");
if (tmpdir_cstr == NULL)
tmpdir_cstr = getenv("TEMP");
}
if (!tmpdir_cstr)
return false;
FileSpec temp_file_spec(tmpdir_cstr, false);
temp_file_spec.AppendPathComponent("lldb");
if (!FileSystem::MakeDirectory(temp_file_spec.GetPath().c_str(), eFilePermissionsDirectoryDefault).Success())
return false;
std::string pid_str;
llvm::raw_string_ostream pid_stream(pid_str);
pid_stream << Host::GetCurrentProcessID();
temp_file_spec.AppendPathComponent(pid_stream.str().c_str());
std::string final_path = temp_file_spec.GetPath();
if (!FileSystem::MakeDirectory(final_path.c_str(), eFilePermissionsDirectoryDefault).Success())
return false;
// Make an atexit handler to clean up the process specify LLDB temp dir
// and all of its contents.
::atexit(CleanupProcessSpecificLLDBTempDir);
file_spec.GetDirectory().SetCStringWithLength(final_path.c_str(), final_path.size());
return true;
}
bool
HostInfoBase::ComputeHeaderDirectory(FileSpec &file_spec)
{
// TODO(zturner): Figure out how to compute the header directory for all platforms.
return false;
}
bool
HostInfoBase::ComputeSystemPluginsDirectory(FileSpec &file_spec)
{
// TODO(zturner): Figure out how to compute the system plugins directory for all platforms.
return false;
}
bool
HostInfoBase::ComputeClangDirectory(FileSpec &file_spec)
{
return false;
}
bool
HostInfoBase::ComputeUserPluginsDirectory(FileSpec &file_spec)
{
// TODO(zturner): Figure out how to compute the user plugins directory for all platforms.
return false;
}
void
HostInfoBase::ComputeHostArchitectureSupport(ArchSpec &arch_32, ArchSpec &arch_64)
{
llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
arch_32.Clear();
arch_64.Clear();
switch (triple.getArch())
{
default:
arch_32.SetTriple(triple);
break;
case llvm::Triple::ppc64:
case llvm::Triple::x86_64:
arch_64.SetTriple(triple);
arch_32.SetTriple(triple.get32BitArchVariant());
break;
case llvm::Triple::aarch64:
case llvm::Triple::mips64:
case llvm::Triple::sparcv9:
arch_64.SetTriple(triple);
break;
}
}
<commit_msg>Use getProcessTriple inside HostInfoBase::ComputeHostArchitectureSupport instead of getDefaultTargetTriple.<commit_after>//===-- HostInfoBase.cpp ----------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lldb/Host/Config.h"
#include "lldb/Core/ArchSpec.h"
#include "lldb/Core/Log.h"
#include "lldb/Core/StreamString.h"
#include "lldb/Host/FileSystem.h"
#include "lldb/Host/Host.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Host/HostInfoBase.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/raw_ostream.h"
#include <thread>
#include <mutex> // std::once
using namespace lldb;
using namespace lldb_private;
namespace
{
void
CleanupProcessSpecificLLDBTempDir()
{
// Get the process specific LLDB temporary directory and delete it.
FileSpec tmpdir_file_spec;
if (!HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
return;
// Remove the LLDB temporary directory if we have one. Set "recurse" to
// true to all files that were created for the LLDB process can be cleaned up.
FileSystem::DeleteDirectory(tmpdir_file_spec.GetDirectory().GetCString(), true);
}
//----------------------------------------------------------------------
// The HostInfoBaseFields is a work around for windows not supporting
// static variables correctly in a thread safe way. Really each of the
// variables in HostInfoBaseFields should live in the functions in which
// they are used and each one should be static, but the work around is
// in place to avoid this restriction. Ick.
//----------------------------------------------------------------------
struct HostInfoBaseFields
{
uint32_t m_number_cpus;
std::string m_vendor_string;
std::string m_os_string;
std::string m_host_triple;
ArchSpec m_host_arch_32;
ArchSpec m_host_arch_64;
FileSpec m_lldb_so_dir;
FileSpec m_lldb_support_exe_dir;
FileSpec m_lldb_headers_dir;
FileSpec m_lldb_python_dir;
FileSpec m_lldb_clang_resource_dir;
FileSpec m_lldb_system_plugin_dir;
FileSpec m_lldb_user_plugin_dir;
FileSpec m_lldb_tmp_dir;
};
HostInfoBaseFields *g_fields = nullptr;
}
void
HostInfoBase::Initialize()
{
g_fields = new HostInfoBaseFields();
}
uint32_t
HostInfoBase::GetNumberCPUS()
{
static std::once_flag g_once_flag;
std::call_once(g_once_flag, []() {
g_fields->m_number_cpus = std::thread::hardware_concurrency();
});
return g_fields->m_number_cpus;
}
uint32_t
HostInfoBase::GetMaxThreadNameLength()
{
return 0;
}
llvm::StringRef
HostInfoBase::GetVendorString()
{
static std::once_flag g_once_flag;
std::call_once(g_once_flag, []() {
g_fields->m_vendor_string = std::move(HostInfo::GetArchitecture().GetTriple().getVendorName().str());
});
return g_fields->m_vendor_string;
}
llvm::StringRef
HostInfoBase::GetOSString()
{
static std::once_flag g_once_flag;
std::call_once(g_once_flag, []() {
g_fields->m_os_string = std::move(HostInfo::GetArchitecture().GetTriple().getOSName());
});
return g_fields->m_os_string;
}
llvm::StringRef
HostInfoBase::GetTargetTriple()
{
static std::once_flag g_once_flag;
std::call_once(g_once_flag, []() {
g_fields->m_host_triple = HostInfo::GetArchitecture().GetTriple().getTriple();
});
return g_fields->m_host_triple;
}
const ArchSpec &
HostInfoBase::GetArchitecture(ArchitectureKind arch_kind)
{
static std::once_flag g_once_flag;
std::call_once(g_once_flag, []() {
HostInfo::ComputeHostArchitectureSupport(g_fields->m_host_arch_32, g_fields->m_host_arch_64);
});
// If an explicit 32 or 64-bit architecture was requested, return that.
if (arch_kind == eArchKind32)
return g_fields->m_host_arch_32;
if (arch_kind == eArchKind64)
return g_fields->m_host_arch_64;
// Otherwise prefer the 64-bit architecture if it is valid.
return (g_fields->m_host_arch_64.IsValid()) ? g_fields->m_host_arch_64 : g_fields->m_host_arch_32;
}
bool
HostInfoBase::GetLLDBPath(lldb::PathType type, FileSpec &file_spec)
{
file_spec.Clear();
#if defined(LLDB_DISABLE_PYTHON)
if (type == lldb::ePathTypePythonDir)
return false;
#endif
FileSpec *result = nullptr;
switch (type)
{
case lldb::ePathTypeLLDBShlibDir:
{
static std::once_flag g_once_flag;
static bool success = false;
std::call_once(g_once_flag, []() {
success = HostInfo::ComputeSharedLibraryDirectory (g_fields->m_lldb_so_dir);
Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
if (log)
log->Printf("HostInfoBase::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'", g_fields->m_lldb_so_dir.GetPath().c_str());
});
if (success)
result = &g_fields->m_lldb_so_dir;
}
break;
case lldb::ePathTypeSupportExecutableDir:
{
static std::once_flag g_once_flag;
static bool success = false;
std::call_once(g_once_flag, []() {
success = HostInfo::ComputeSupportExeDirectory (g_fields->m_lldb_support_exe_dir);
Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
if (log)
log->Printf("HostInfoBase::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'",
g_fields->m_lldb_support_exe_dir.GetPath().c_str());
});
if (success)
result = &g_fields->m_lldb_support_exe_dir;
}
break;
case lldb::ePathTypeHeaderDir:
{
static std::once_flag g_once_flag;
static bool success = false;
std::call_once(g_once_flag, []() {
success = HostInfo::ComputeHeaderDirectory (g_fields->m_lldb_headers_dir);
Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
if (log)
log->Printf("HostInfoBase::GetLLDBPath(ePathTypeHeaderDir) => '%s'", g_fields->m_lldb_headers_dir.GetPath().c_str());
});
if (success)
result = &g_fields->m_lldb_headers_dir;
}
break;
case lldb::ePathTypePythonDir:
{
static std::once_flag g_once_flag;
static bool success = false;
std::call_once(g_once_flag, []() {
success = HostInfo::ComputePythonDirectory (g_fields->m_lldb_python_dir);
Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
if (log)
log->Printf("HostInfoBase::GetLLDBPath(ePathTypePythonDir) => '%s'", g_fields->m_lldb_python_dir.GetPath().c_str());
});
if (success)
result = &g_fields->m_lldb_python_dir;
}
break;
case lldb::ePathTypeClangDir:
{
static std::once_flag g_once_flag;
static bool success = false;
std::call_once(g_once_flag, []() {
success = HostInfo::ComputeClangDirectory (g_fields->m_lldb_clang_resource_dir);
Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
if (log)
log->Printf("HostInfoBase::GetLLDBPath(ePathTypeClangResourceDir) => '%s'", g_fields->m_lldb_clang_resource_dir.GetPath().c_str());
});
if (success)
result = &g_fields->m_lldb_clang_resource_dir;
}
break;
case lldb::ePathTypeLLDBSystemPlugins:
{
static std::once_flag g_once_flag;
static bool success = false;
std::call_once(g_once_flag, []() {
success = HostInfo::ComputeSystemPluginsDirectory (g_fields->m_lldb_system_plugin_dir);
Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
if (log)
log->Printf("HostInfoBase::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'",
g_fields->m_lldb_system_plugin_dir.GetPath().c_str());
});
if (success)
result = &g_fields->m_lldb_system_plugin_dir;
}
break;
case lldb::ePathTypeLLDBUserPlugins:
{
static std::once_flag g_once_flag;
static bool success = false;
std::call_once(g_once_flag, []() {
success = HostInfo::ComputeUserPluginsDirectory (g_fields->m_lldb_user_plugin_dir);
Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
if (log)
log->Printf("HostInfoBase::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'",
g_fields->m_lldb_user_plugin_dir.GetPath().c_str());
});
if (success)
result = &g_fields->m_lldb_user_plugin_dir;
}
break;
case lldb::ePathTypeLLDBTempSystemDir:
{
static std::once_flag g_once_flag;
static bool success = false;
std::call_once(g_once_flag, []() {
success = HostInfo::ComputeTempFileDirectory (g_fields->m_lldb_tmp_dir);
Log *log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST);
if (log)
log->Printf("HostInfoBase::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_fields->m_lldb_tmp_dir.GetPath().c_str());
});
if (success)
result = &g_fields->m_lldb_tmp_dir;
}
break;
}
if (!result)
return false;
file_spec = *result;
return true;
}
bool
HostInfoBase::ComputeSharedLibraryDirectory(FileSpec &file_spec)
{
// To get paths related to LLDB we get the path to the executable that
// contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
// on linux this is assumed to be the "lldb" main executable. If LLDB on
// linux is actually in a shared library (liblldb.so) then this function will
// need to be modified to "do the right thing".
FileSpec lldb_file_spec(
Host::GetModuleFileSpecForHostAddress(reinterpret_cast<void *>(reinterpret_cast<intptr_t>(HostInfoBase::GetLLDBPath))));
// Remove the filename so that this FileSpec only represents the directory.
file_spec.GetDirectory() = lldb_file_spec.GetDirectory();
return (bool)file_spec.GetDirectory();
}
bool
HostInfoBase::ComputeSupportExeDirectory(FileSpec &file_spec)
{
return GetLLDBPath(lldb::ePathTypeLLDBShlibDir, file_spec);
}
bool
HostInfoBase::ComputeTempFileDirectory(FileSpec &file_spec)
{
const char *tmpdir_cstr = getenv("TMPDIR");
if (tmpdir_cstr == NULL)
{
tmpdir_cstr = getenv("TMP");
if (tmpdir_cstr == NULL)
tmpdir_cstr = getenv("TEMP");
}
if (!tmpdir_cstr)
return false;
FileSpec temp_file_spec(tmpdir_cstr, false);
temp_file_spec.AppendPathComponent("lldb");
if (!FileSystem::MakeDirectory(temp_file_spec.GetPath().c_str(), eFilePermissionsDirectoryDefault).Success())
return false;
std::string pid_str;
llvm::raw_string_ostream pid_stream(pid_str);
pid_stream << Host::GetCurrentProcessID();
temp_file_spec.AppendPathComponent(pid_stream.str().c_str());
std::string final_path = temp_file_spec.GetPath();
if (!FileSystem::MakeDirectory(final_path.c_str(), eFilePermissionsDirectoryDefault).Success())
return false;
// Make an atexit handler to clean up the process specify LLDB temp dir
// and all of its contents.
::atexit(CleanupProcessSpecificLLDBTempDir);
file_spec.GetDirectory().SetCStringWithLength(final_path.c_str(), final_path.size());
return true;
}
bool
HostInfoBase::ComputeHeaderDirectory(FileSpec &file_spec)
{
// TODO(zturner): Figure out how to compute the header directory for all platforms.
return false;
}
bool
HostInfoBase::ComputeSystemPluginsDirectory(FileSpec &file_spec)
{
// TODO(zturner): Figure out how to compute the system plugins directory for all platforms.
return false;
}
bool
HostInfoBase::ComputeClangDirectory(FileSpec &file_spec)
{
return false;
}
bool
HostInfoBase::ComputeUserPluginsDirectory(FileSpec &file_spec)
{
// TODO(zturner): Figure out how to compute the user plugins directory for all platforms.
return false;
}
void
HostInfoBase::ComputeHostArchitectureSupport(ArchSpec &arch_32, ArchSpec &arch_64)
{
llvm::Triple triple(llvm::sys::getProcessTriple());
arch_32.Clear();
arch_64.Clear();
switch (triple.getArch())
{
default:
arch_32.SetTriple(triple);
break;
case llvm::Triple::ppc64:
case llvm::Triple::x86_64:
arch_64.SetTriple(triple);
arch_32.SetTriple(triple.get32BitArchVariant());
break;
case llvm::Triple::aarch64:
case llvm::Triple::mips64:
case llvm::Triple::sparcv9:
arch_64.SetTriple(triple);
break;
}
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.