text
stringlengths 54
60.6k
|
|---|
<commit_before>/*
***********************************************************************************************************************
*
* Copyright (c) 2020 Advanced Micro Devices, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************************************************************/
/**
***********************************************************************************************************************
* @file llpcGfxRegHandler.cpp
* @brief LLPC source file: Implementation of LLPC utility class GfxRegHandler
***********************************************************************************************************************
*/
#include "llpcGfxRegHandler.h"
#include "llvm/IR/IntrinsicsAMDGPU.h"
using namespace lgc;
using namespace llvm;
// =====================================================================================================================
GfxRegHandler::GfxRegHandler(
Builder* pBuilder, // [in] The builder handle
Value* pRegister) // [in] The registered target vec <n x i32>
:
GfxRegHandlerBase(pBuilder, pRegister)
{
m_pOne = pBuilder->getInt32(1);
}
// =====================================================================================================================
// Common function for getting the current value for the hardware register
Value* GfxRegHandler::GetRegCommon(
uint32_t regId) // The register ID, which is the index of BitsInfo and BitsState
{
// Under two condition, we need to fetch the range of bits
// - The register has not being initialized
// - The register is being modified
if ((m_pBitsState[regId].pValue == nullptr) ||
(m_pBitsState[regId].isModified))
{
// Fetch bits according to BitsInfo
m_pBitsState[regId].pValue = GetBits(m_pBitsInfo[regId]);
}
// Since the specified range of bits is cached, set it unmodified
m_pBitsState[regId].isModified = 0;
// Return the cached value
return m_pBitsState[regId].pValue;
}
// =====================================================================================================================
// Get combined data from two seperate DWORDs
// Note: The return type is one DWORD, it doesn't support two DWORDs for now.
// TODO: Expand to support 2-DWORDs combination result.
Value* GfxRegHandler::GetRegCombine(
uint32_t regIdLo, // The ID of low part register
uint32_t regIdHi) // Reg ID of high part register
{
Value* pRegValueLo = GetRegCommon(regIdLo);
Value* pRegValueHi = GetRegCommon(regIdHi);
return m_pBuilder->CreateOr(m_pBuilder->CreateShl(pRegValueHi, m_pBitsInfo[regIdLo].offset), pRegValueLo);
}
// =====================================================================================================================
// Set register value into two seperate DWORDs
// Note: The input pRegValue only supports one DWORD
void GfxRegHandler::SetRegCombine(
uint32_t regIdLo, // The ID of low part register
uint32_t regIdHi, // Reg ID of high part register
Value* pRegValue) // [in] Data used for setting
{
Value* pRegValueLo = m_pBuilder->CreateIntrinsic(Intrinsic::amdgcn_ubfe,
m_pBuilder->getInt32Ty(),
{ pRegValue,
m_pBuilder->getInt32(0),
m_pBuilder->getInt32(m_pBitsInfo[regIdLo].offset) });
Value* pRegValueHi = m_pBuilder->CreateLShr(pRegValue, m_pBuilder->getInt32(m_pBitsInfo[regIdLo].offset));
SetRegCommon(regIdLo, pRegValueLo);
SetRegCommon(regIdHi, pRegValueHi);
}
// =====================================================================================================================
// SqImgSampReg Bits infomation look up table (Gfx9-10)
// Refer to imported/chip/gfx9/gfx9_plus_merged_registers.h : SQ_IMG_SAMP_WORD
static constexpr BitsInfo SqImgSampRegBitsGfx9[static_cast<uint32_t>(SqSampRegs::Count)] =
{
{ 0, 30, 2 }, // FilterMode
{ 2, 20, 2 }, // XyMagFilter
{ 2, 22, 2 }, // XyMinFilter
};
// =====================================================================================================================
// Helper class for handling Registers defined in SQ_IMG_SAMP_WORD
SqImgSampRegHandler::SqImgSampRegHandler(
Builder* pBuilder, // [in] Bound builder context
Value* pRegister, // [in] Bound register vec <n x i32>
GfxIpVersion* pGfxIpVersion) // [in] Target GFX IP version
:
GfxRegHandler(pBuilder, pRegister)
{
m_pGfxIpVersion = pGfxIpVersion;
switch (pGfxIpVersion->major)
{
case 9:
case 10:
m_pBitsInfo = SqImgSampRegBitsGfx9;
break;
default:
llvm_unreachable("GFX IP is not supported!");
break;
}
SetBitsState(m_pBitsState);
}
// =====================================================================================================================
// Get the current value for the hardware register
Value* SqImgSampRegHandler::GetReg(
SqSampRegs regId) // Register ID
{
switch (regId)
{
case SqSampRegs::FilterMode:
case SqSampRegs::xyMagFilter:
case SqSampRegs::xyMinFilter:
return GetRegCommon(static_cast<uint32_t>(regId));
default:
// TODO: More will be implemented.
llvm_unreachable("Not implemented!");
break;
}
return nullptr;
}
// =====================================================================================================================
// Set the current value for the hardware register
void SqImgSampRegHandler::SetReg(
SqSampRegs regId, // Register ID
Value* pRegValue ) // [in] Value to set to this register
{
switch (regId)
{
case SqSampRegs::FilterMode:
case SqSampRegs::xyMagFilter:
case SqSampRegs::xyMinFilter:
SetRegCommon(static_cast<uint32_t>(regId), pRegValue);
break;
default:
llvm_unreachable("Set \"IsTileOpt\" is not allowed!");
break;
}
}
// =====================================================================================================================
// SqImgSampReg Bits infomation look up table (Gfx9)
// Refer to imported/chip/gfx9/gfx9_plus_merged_registers.h : SQ_IMG_RSRC_WORD
static constexpr BitsInfo SqImgRsrcRegBitsGfx9[static_cast<uint32_t>(SqRsrcRegs::Count)] =
{
{ 0, 0, 32 }, // BaseAddress
{ 1, 0, 8 }, // BaseAddressHi
{ 1, 20, 9 }, // Format
{ 2, 0, 14 }, // Width
{ 2, 14, 14 }, // Height
{ 3, 0, 12 }, // DstSelXYZW
{ 3, 20, 5 }, // IsTileOpt
{ 4, 0, 13 }, // Depth
{ 4, 13, 12 }, // Pitch
{ 4, 29, 3 }, // BcSwizzle
{}, // WidthLo
{}, // WidthHi
};
// =====================================================================================================================
// SqImgSampReg Bits infomation look up table (Gfx10)
// TODO: update comment when the registers file is available
static constexpr BitsInfo SqImgRsrcRegBitsGfx10[static_cast<uint32_t>(SqRsrcRegs::Count)] =
{
{ 0, 0, 32 }, // BaseAddress
{ 1, 0, 8 }, // BaseAddressHi
{ 1, 20, 9 }, // Format
{}, // Width
{ 2, 14, 16 }, // Height
{ 3, 0, 12 }, // DstSelXYZW
{ 3, 20, 5 }, // IsTileOpt
{ 4, 0, 16 }, // Depth
{}, // Pitch
{ 3, 25, 3 }, // BcSwizzle
{ 1, 30, 2 }, // WidthLo
{ 2, 0, 14 }, // WidthHi
};
// =====================================================================================================================
// Helper class for handling Registers defined in SQ_IMG_RSRC_WORD
SqImgRsrcRegHandler::SqImgRsrcRegHandler(
Builder* pBuilder, // [in] Bound builder context
Value* pRegister, // [in] Bound register vec <n x i32>
GfxIpVersion* pGfxIpVersion) // [in] Current GFX IP version
:
GfxRegHandler(pBuilder, pRegister)
{
m_pGfxIpVersion = pGfxIpVersion;
switch (pGfxIpVersion->major)
{
case 9:
m_pBitsInfo = SqImgRsrcRegBitsGfx9;
break;
case 10:
m_pBitsInfo = SqImgRsrcRegBitsGfx10;
break;
default:
llvm_unreachable("GFX IP is not supported!");
break;
}
SetBitsState(m_pBitsState);
}
// =====================================================================================================================
// Get the current value for the hardware register
Value* SqImgRsrcRegHandler::GetReg(
SqRsrcRegs regId) // Register ID
{
switch (regId)
{
case SqRsrcRegs::BaseAddress:
case SqRsrcRegs::Format:
case SqRsrcRegs::DstSelXYZW:
case SqRsrcRegs::Depth:
case SqRsrcRegs::BcSwizzle:
return GetRegCommon(static_cast<uint32_t>(regId));
case SqRsrcRegs::Height:
case SqRsrcRegs::Pitch:
return m_pBuilder->CreateAdd(GetRegCommon(static_cast<uint32_t>(regId)), m_pOne);
case SqRsrcRegs::Width:
switch (m_pGfxIpVersion->major)
{
case 9:
return m_pBuilder->CreateAdd(GetRegCommon(static_cast<uint32_t>(regId)), m_pOne);
case 10:
return m_pBuilder->CreateAdd(GetRegCombine(static_cast<uint32_t>(SqRsrcRegs::WidthLo),
static_cast<uint32_t>(SqRsrcRegs::WidthHi)),
m_pOne);
default:
llvm_unreachable("GFX IP is not supported!");
break;
}
case SqRsrcRegs::IsTileOpt:
return m_pBuilder->CreateICmpNE(GetRegCommon(static_cast<uint32_t>(regId)), m_pBuilder->getInt32(0));
default:
// TODO: More will be implemented.
llvm_unreachable("Not implemented!");
}
return nullptr;
}
// =====================================================================================================================
// Set the current value for the hardware register
void SqImgRsrcRegHandler::SetReg(
SqRsrcRegs regId, // Register ID
Value* pRegValue) // [in] Value to set to this register
{
switch (regId)
{
case SqRsrcRegs::BaseAddress:
case SqRsrcRegs::BaseAddressHi:
case SqRsrcRegs::Format:
case SqRsrcRegs::DstSelXYZW:
case SqRsrcRegs::Depth:
case SqRsrcRegs::BcSwizzle:
SetRegCommon(static_cast<uint32_t>(regId), pRegValue);
break;
case SqRsrcRegs::Height:
case SqRsrcRegs::Pitch:
SetRegCommon(static_cast<uint32_t>(regId), m_pBuilder->CreateSub(pRegValue, m_pOne));
break;
case SqRsrcRegs::Width:
switch (m_pGfxIpVersion->major)
{
case 9:
SetRegCommon(static_cast<uint32_t>(regId), m_pBuilder->CreateSub(pRegValue, m_pOne));
break;
case 10:
SetRegCombine(static_cast<uint32_t>(SqRsrcRegs::WidthLo),
static_cast<uint32_t>(SqRsrcRegs::WidthHi),
m_pBuilder->CreateSub(pRegValue, m_pOne));
break;
default:
llvm_unreachable("GFX IP is not supported!");
break;
}
break;
case SqRsrcRegs::IsTileOpt:
llvm_unreachable("Set \"IsTileOpt\" is not allowed!");
break;
}
}
<commit_msg>Fixed GfxRegHandler clang compile error<commit_after>/*
***********************************************************************************************************************
*
* Copyright (c) 2020 Advanced Micro Devices, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************************************************************/
/**
***********************************************************************************************************************
* @file llpcGfxRegHandler.cpp
* @brief LLPC source file: Implementation of LLPC utility class GfxRegHandler
***********************************************************************************************************************
*/
#include "llpcGfxRegHandler.h"
#include "llvm/IR/IntrinsicsAMDGPU.h"
using namespace lgc;
using namespace llvm;
// =====================================================================================================================
GfxRegHandler::GfxRegHandler(
Builder* pBuilder, // [in] The builder handle
Value* pRegister) // [in] The registered target vec <n x i32>
:
GfxRegHandlerBase(pBuilder, pRegister)
{
m_pOne = pBuilder->getInt32(1);
}
// =====================================================================================================================
// Common function for getting the current value for the hardware register
Value* GfxRegHandler::GetRegCommon(
uint32_t regId) // The register ID, which is the index of BitsInfo and BitsState
{
// Under two condition, we need to fetch the range of bits
// - The register has not being initialized
// - The register is being modified
if ((m_pBitsState[regId].pValue == nullptr) ||
(m_pBitsState[regId].isModified))
{
// Fetch bits according to BitsInfo
m_pBitsState[regId].pValue = GetBits(m_pBitsInfo[regId]);
}
// Since the specified range of bits is cached, set it unmodified
m_pBitsState[regId].isModified = 0;
// Return the cached value
return m_pBitsState[regId].pValue;
}
// =====================================================================================================================
// Get combined data from two seperate DWORDs
// Note: The return type is one DWORD, it doesn't support two DWORDs for now.
// TODO: Expand to support 2-DWORDs combination result.
Value* GfxRegHandler::GetRegCombine(
uint32_t regIdLo, // The ID of low part register
uint32_t regIdHi) // Reg ID of high part register
{
Value* pRegValueLo = GetRegCommon(regIdLo);
Value* pRegValueHi = GetRegCommon(regIdHi);
return m_pBuilder->CreateOr(m_pBuilder->CreateShl(pRegValueHi, m_pBitsInfo[regIdLo].offset), pRegValueLo);
}
// =====================================================================================================================
// Set register value into two seperate DWORDs
// Note: The input pRegValue only supports one DWORD
void GfxRegHandler::SetRegCombine(
uint32_t regIdLo, // The ID of low part register
uint32_t regIdHi, // Reg ID of high part register
Value* pRegValue) // [in] Data used for setting
{
Value* pRegValueLo = m_pBuilder->CreateIntrinsic(Intrinsic::amdgcn_ubfe,
m_pBuilder->getInt32Ty(),
{ pRegValue,
m_pBuilder->getInt32(0),
m_pBuilder->getInt32(m_pBitsInfo[regIdLo].offset) });
Value* pRegValueHi = m_pBuilder->CreateLShr(pRegValue, m_pBuilder->getInt32(m_pBitsInfo[regIdLo].offset));
SetRegCommon(regIdLo, pRegValueLo);
SetRegCommon(regIdHi, pRegValueHi);
}
// =====================================================================================================================
// SqImgSampReg Bits infomation look up table (Gfx9-10)
// Refer to imported/chip/gfx9/gfx9_plus_merged_registers.h : SQ_IMG_SAMP_WORD
static constexpr BitsInfo SqImgSampRegBitsGfx9[static_cast<uint32_t>(SqSampRegs::Count)] =
{
{ 0, 30, 2 }, // FilterMode
{ 2, 20, 2 }, // XyMagFilter
{ 2, 22, 2 }, // XyMinFilter
};
// =====================================================================================================================
// Helper class for handling Registers defined in SQ_IMG_SAMP_WORD
SqImgSampRegHandler::SqImgSampRegHandler(
Builder* pBuilder, // [in] Bound builder context
Value* pRegister, // [in] Bound register vec <n x i32>
GfxIpVersion* pGfxIpVersion) // [in] Target GFX IP version
:
GfxRegHandler(pBuilder, pRegister)
{
m_pGfxIpVersion = pGfxIpVersion;
switch (pGfxIpVersion->major)
{
case 9:
case 10:
m_pBitsInfo = SqImgSampRegBitsGfx9;
break;
default:
llvm_unreachable("GFX IP is not supported!");
break;
}
SetBitsState(m_pBitsState);
}
// =====================================================================================================================
// Get the current value for the hardware register
Value* SqImgSampRegHandler::GetReg(
SqSampRegs regId) // Register ID
{
switch (regId)
{
case SqSampRegs::FilterMode:
case SqSampRegs::xyMagFilter:
case SqSampRegs::xyMinFilter:
return GetRegCommon(static_cast<uint32_t>(regId));
default:
// TODO: More will be implemented.
llvm_unreachable("Not implemented!");
break;
}
return nullptr;
}
// =====================================================================================================================
// Set the current value for the hardware register
void SqImgSampRegHandler::SetReg(
SqSampRegs regId, // Register ID
Value* pRegValue ) // [in] Value to set to this register
{
switch (regId)
{
case SqSampRegs::FilterMode:
case SqSampRegs::xyMagFilter:
case SqSampRegs::xyMinFilter:
SetRegCommon(static_cast<uint32_t>(regId), pRegValue);
break;
default:
llvm_unreachable("Set \"IsTileOpt\" is not allowed!");
break;
}
}
// =====================================================================================================================
// SqImgSampReg Bits infomation look up table (Gfx9)
// Refer to imported/chip/gfx9/gfx9_plus_merged_registers.h : SQ_IMG_RSRC_WORD
static constexpr BitsInfo SqImgRsrcRegBitsGfx9[static_cast<uint32_t>(SqRsrcRegs::Count)] =
{
{ 0, 0, 32 }, // BaseAddress
{ 1, 0, 8 }, // BaseAddressHi
{ 1, 20, 9 }, // Format
{ 2, 0, 14 }, // Width
{ 2, 14, 14 }, // Height
{ 3, 0, 12 }, // DstSelXYZW
{ 3, 20, 5 }, // IsTileOpt
{ 4, 0, 13 }, // Depth
{ 4, 13, 12 }, // Pitch
{ 4, 29, 3 }, // BcSwizzle
{}, // WidthLo
{}, // WidthHi
};
// =====================================================================================================================
// SqImgSampReg Bits infomation look up table (Gfx10)
// TODO: update comment when the registers file is available
static constexpr BitsInfo SqImgRsrcRegBitsGfx10[static_cast<uint32_t>(SqRsrcRegs::Count)] =
{
{ 0, 0, 32 }, // BaseAddress
{ 1, 0, 8 }, // BaseAddressHi
{ 1, 20, 9 }, // Format
{}, // Width
{ 2, 14, 16 }, // Height
{ 3, 0, 12 }, // DstSelXYZW
{ 3, 20, 5 }, // IsTileOpt
{ 4, 0, 16 }, // Depth
{}, // Pitch
{ 3, 25, 3 }, // BcSwizzle
{ 1, 30, 2 }, // WidthLo
{ 2, 0, 14 }, // WidthHi
};
// =====================================================================================================================
// Helper class for handling Registers defined in SQ_IMG_RSRC_WORD
SqImgRsrcRegHandler::SqImgRsrcRegHandler(
Builder* pBuilder, // [in] Bound builder context
Value* pRegister, // [in] Bound register vec <n x i32>
GfxIpVersion* pGfxIpVersion) // [in] Current GFX IP version
:
GfxRegHandler(pBuilder, pRegister)
{
m_pGfxIpVersion = pGfxIpVersion;
switch (pGfxIpVersion->major)
{
case 9:
m_pBitsInfo = SqImgRsrcRegBitsGfx9;
break;
case 10:
m_pBitsInfo = SqImgRsrcRegBitsGfx10;
break;
default:
llvm_unreachable("GFX IP is not supported!");
break;
}
SetBitsState(m_pBitsState);
}
// =====================================================================================================================
// Get the current value for the hardware register
Value* SqImgRsrcRegHandler::GetReg(
SqRsrcRegs regId) // Register ID
{
switch (regId)
{
case SqRsrcRegs::BaseAddress:
case SqRsrcRegs::Format:
case SqRsrcRegs::DstSelXYZW:
case SqRsrcRegs::Depth:
case SqRsrcRegs::BcSwizzle:
return GetRegCommon(static_cast<uint32_t>(regId));
case SqRsrcRegs::Height:
case SqRsrcRegs::Pitch:
return m_pBuilder->CreateAdd(GetRegCommon(static_cast<uint32_t>(regId)), m_pOne);
case SqRsrcRegs::Width:
switch (m_pGfxIpVersion->major)
{
case 9:
return m_pBuilder->CreateAdd(GetRegCommon(static_cast<uint32_t>(regId)), m_pOne);
case 10:
return m_pBuilder->CreateAdd(GetRegCombine(static_cast<uint32_t>(SqRsrcRegs::WidthLo),
static_cast<uint32_t>(SqRsrcRegs::WidthHi)),
m_pOne);
default:
llvm_unreachable("GFX IP is not supported!");
break;
}
case SqRsrcRegs::IsTileOpt:
return m_pBuilder->CreateICmpNE(GetRegCommon(static_cast<uint32_t>(regId)), m_pBuilder->getInt32(0));
default:
// TODO: More will be implemented.
llvm_unreachable("Not implemented!");
}
return nullptr;
}
// =====================================================================================================================
// Set the current value for the hardware register
void SqImgRsrcRegHandler::SetReg(
SqRsrcRegs regId, // Register ID
Value* pRegValue) // [in] Value to set to this register
{
switch (regId)
{
case SqRsrcRegs::BaseAddress:
case SqRsrcRegs::BaseAddressHi:
case SqRsrcRegs::Format:
case SqRsrcRegs::DstSelXYZW:
case SqRsrcRegs::Depth:
case SqRsrcRegs::BcSwizzle:
SetRegCommon(static_cast<uint32_t>(regId), pRegValue);
break;
case SqRsrcRegs::Height:
case SqRsrcRegs::Pitch:
SetRegCommon(static_cast<uint32_t>(regId), m_pBuilder->CreateSub(pRegValue, m_pOne));
break;
case SqRsrcRegs::Width:
switch (m_pGfxIpVersion->major)
{
case 9:
SetRegCommon(static_cast<uint32_t>(regId), m_pBuilder->CreateSub(pRegValue, m_pOne));
break;
case 10:
SetRegCombine(static_cast<uint32_t>(SqRsrcRegs::WidthLo),
static_cast<uint32_t>(SqRsrcRegs::WidthHi),
m_pBuilder->CreateSub(pRegValue, m_pOne));
break;
default:
llvm_unreachable("GFX IP is not supported!");
break;
}
break;
case SqRsrcRegs::IsTileOpt:
case SqRsrcRegs::WidthLo:
case SqRsrcRegs::WidthHi:
case SqRsrcRegs::Count:
llvm_unreachable("Bad SqImgRsrcRegHandler::SetReg!");
break;
}
}
<|endoftext|>
|
<commit_before><commit_msg>Fix: fix filling of event/track cuts values histogram<commit_after><|endoftext|>
|
<commit_before>AliAnalysisVertexingHF* ConfigVertexingHF() {
printf("Call to AliAnalysisVertexingHF parameters setting :\n");
vHF = new AliAnalysisVertexingHF();
//--- switch-off candidates finding (default: all on)
//vHF->SetD0toKpiOff();
//vHF->SetJPSItoEleOff();
//vHF->Set3ProngOff();
//vHF->SetLikeSignOn();
vHF->Set4ProngOff();
//vHF->SetDstarOff();
//--- secondary vertex with KF?
//vHF->SetSecVtxWithKF();
//--- set cuts for single-track selection
AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts("AliESDtrackCuts","default");
esdTrackCuts->SetRequireITSRefit(kTRUE);
esdTrackCuts->SetMinNClustersITS(5);
esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,
AliESDtrackCuts::kBoth);
esdTrackCuts->SetMinDCAToVertexXY(0.);
esdTrackCuts->SetPtRange(0.3,1.e10);
AliAnalysisFilter *trkFilter = new AliAnalysisFilter("trackFilter");
trkFilter->AddCuts(esdTrackCuts);
vHF->SetTrackFilter(trkFilter);
AliESDtrackCuts *esdTrackCutsSoftPi = new AliESDtrackCuts("AliESDtrackCuts","default");
AliAnalysisFilter *trkFilterSoftPi = new AliAnalysisFilter("trackFilterSoftPi");
trkFilterSoftPi->AddCuts(esdTrackCutsSoftPi);
vHF->SetTrackFilterSoftPi(trkFilterSoftPi);
//--- set cuts for candidates selection
vHF->SetD0toKpiCuts(0.7,999999.,1.1,0.,0.,999999.,999999.,999999.,0.);
vHF->SetBtoJPSICuts(0.350);
vHF->SetDplusCuts(0.2,0.,0.,0.,0.,0.01,0.06,0.,0.,0.8);
vHF->SetDsCuts(0.2,0.,0.,0.,0.,0.005,0.06,0.,0.,0.8,0.,0.1,0.1);
vHF->SetLcCuts(0.2,0.,0.,0.,0.,0.01,0.06,0.,0.,0.8);
vHF->SetDstarCuts(999999., 999999., 0.1, 1.0, 0.5);
vHF->SetD0fromDstarCuts(0.7,999999.,1.1,0.,0.,999999.,999999.,999999.,0.);
//--- set this if you want to reconstruct primary vertex candidate by
// candidate using other tracks in the event (for pp, broad
// interaction region)
//vHF->SetRecoPrimVtxSkippingTrks();
//--- OR set this if you want to remove the candidate daughters from
// the primary vertex, without recostructing it from scratch
//vHF->SetRmTrksFromPrimVtx();
//--- check the settings
vHF->PrintStatus();
//--- verbose
//AliLog::SetClassDebugLevel("AliAnalysisVertexingHF",2);
return vHF;
}
<commit_msg>Added possibility to use the event primary vertex as the decay vertex of the D* (no secondary vertex tried between D0 and pi_s)<commit_after>AliAnalysisVertexingHF* ConfigVertexingHF() {
printf("Call to AliAnalysisVertexingHF parameters setting :\n");
vHF = new AliAnalysisVertexingHF();
//--- switch-off candidates finding (default: all on)
//vHF->SetD0toKpiOff();
//vHF->SetJPSItoEleOff();
//vHF->Set3ProngOff();
//vHF->SetLikeSignOn();
vHF->Set4ProngOff();
//vHF->SetDstarOff();
vHF->SetFindVertexForDstar(kTRUE);
//--- secondary vertex with KF?
//vHF->SetSecVtxWithKF();
//--- set cuts for single-track selection
AliESDtrackCuts *esdTrackCuts = new AliESDtrackCuts("AliESDtrackCuts","default");
esdTrackCuts->SetRequireITSRefit(kTRUE);
esdTrackCuts->SetMinNClustersITS(5);
esdTrackCuts->SetClusterRequirementITS(AliESDtrackCuts::kSPD,
AliESDtrackCuts::kBoth);
esdTrackCuts->SetMinDCAToVertexXY(0.);
esdTrackCuts->SetPtRange(0.3,1.e10);
AliAnalysisFilter *trkFilter = new AliAnalysisFilter("trackFilter");
trkFilter->AddCuts(esdTrackCuts);
vHF->SetTrackFilter(trkFilter);
AliESDtrackCuts *esdTrackCutsSoftPi = new AliESDtrackCuts("AliESDtrackCuts","default");
esdTrackCutsSoftPi->SetRequireITSRefit(kTRUE);
AliAnalysisFilter *trkFilterSoftPi = new AliAnalysisFilter("trackFilterSoftPi");
trkFilterSoftPi->AddCuts(esdTrackCutsSoftPi);
vHF->SetTrackFilterSoftPi(trkFilterSoftPi);
//--- set cuts for candidates selection
vHF->SetD0toKpiCuts(0.7,999999.,1.1,0.,0.,999999.,999999.,999999.,0.);
vHF->SetBtoJPSICuts(0.350);
vHF->SetDplusCuts(0.2,0.,0.,0.,0.,0.01,0.06,0.,0.,0.8);
vHF->SetDsCuts(0.2,0.,0.,0.,0.,0.005,0.06,0.,0.,0.8,0.,0.1,0.1);
vHF->SetLcCuts(0.2,0.,0.,0.,0.,0.01,0.06,0.,0.,0.8);
vHF->SetDstarCuts(999999., 999999., 0.1, 1.0, 0.5);
vHF->SetD0fromDstarCuts(0.7,999999.,1.1,0.,0.,999999.,999999.,999999.,0.);
//--- set this if you want to reconstruct primary vertex candidate by
// candidate using other tracks in the event (for pp, broad
// interaction region)
//vHF->SetRecoPrimVtxSkippingTrks();
//--- OR set this if you want to remove the candidate daughters from
// the primary vertex, without recostructing it from scratch
//vHF->SetRmTrksFromPrimVtx();
//--- check the settings
vHF->PrintStatus();
//--- verbose
//AliLog::SetClassDebugLevel("AliAnalysisVertexingHF",2);
return vHF;
}
<|endoftext|>
|
<commit_before>//===- lib/Driver/GnuLdInputGraph.cpp -------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lld/Driver/GnuLdInputGraph.h"
#include "lld/ReaderWriter/LinkerScript.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
using namespace lld;
/// \brief Parse the input file to lld::File.
error_code ELFFileNode::parse(const LinkingContext &ctx,
raw_ostream &diagnostics) {
ErrorOr<StringRef> filePath = getPath(ctx);
if (error_code ec = filePath.getError())
return ec;
if (error_code ec = getBuffer(*filePath))
return ec;
if (ctx.logInputFiles())
diagnostics << *filePath << "\n";
if (_attributes._isWholeArchive) {
std::vector<std::unique_ptr<File>> parsedFiles;
error_code ec = ctx.registry().parseFile(_buffer, parsedFiles);
if (ec)
return ec;
assert(parsedFiles.size() == 1);
std::unique_ptr<File> f(parsedFiles[0].release());
if (auto archive = reinterpret_cast<const ArchiveLibraryFile *>(f.get())) {
// Have this node own the FileArchive object.
_archiveFile.reset(archive);
f.release();
// Add all members to _files vector
return archive->parseAllMembers(_files);
}
// if --whole-archive is around non-archive, just use it as normal.
_files.push_back(std::move(f));
return error_code::success();
}
return ctx.registry().parseFile(_buffer, _files);
}
/// \brief Parse the GnuLD Script
error_code GNULdScript::parse(const LinkingContext &ctx,
raw_ostream &diagnostics) {
ErrorOr<StringRef> filePath = getPath(ctx);
if (error_code ec = filePath.getError())
return ec;
if (error_code ec = getBuffer(*filePath))
return ec;
if (ctx.logInputFiles())
diagnostics << *filePath << "\n";
_lexer.reset(new script::Lexer(std::move(_buffer)));
_parser.reset(new script::Parser(*_lexer.get()));
_linkerScript = _parser->parse();
if (!_linkerScript)
return LinkerScriptReaderError::parse_error;
return error_code::success();
}
static bool isPathUnderSysroot(StringRef sysroot, StringRef path) {
// TODO: Handle the case when 'sysroot' and/or 'path' are symlinks.
if (sysroot.empty() || sysroot.size() >= path.size())
return false;
if (llvm::sys::path::is_separator(sysroot.back()))
sysroot = sysroot.substr(0, sysroot.size() - 1);
if (!llvm::sys::path::is_separator(path[sysroot.size()]))
return false;
return llvm::sys::fs::equivalent(sysroot, path.substr(0, sysroot.size()));
}
/// \brief Handle GnuLD script for ELF.
error_code ELFGNULdScript::parse(const LinkingContext &ctx,
raw_ostream &diagnostics) {
ELFFileNode::Attributes attributes;
if (error_code ec = GNULdScript::parse(ctx, diagnostics))
return ec;
StringRef sysRoot = _elfLinkingContext.getSysroot();
if (!sysRoot.empty() && isPathUnderSysroot(sysRoot, *getPath(ctx)))
attributes.setSysRooted(true);
for (const script::Command *c : _linkerScript->_commands) {
auto *group = dyn_cast<script::Group>(c);
if (!group)
continue;
std::unique_ptr<Group> groupStart(new Group());
for (const script::Path &path : group->getPaths()) {
// TODO : Propagate Set WholeArchive/dashlPrefix
attributes.setAsNeeded(path._asNeeded);
auto inputNode = new ELFFileNode(
_elfLinkingContext, _elfLinkingContext.allocateString(path._path),
attributes);
std::unique_ptr<InputElement> inputFile(inputNode);
groupStart.get()->addFile(std::move(inputFile));
}
_expandElements.push_back(std::move(groupStart));
}
return error_code::success();
}
<commit_msg>Trivial simplification<commit_after>//===- lib/Driver/GnuLdInputGraph.cpp -------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "lld/Driver/GnuLdInputGraph.h"
#include "lld/ReaderWriter/LinkerScript.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
using namespace lld;
/// \brief Parse the input file to lld::File.
error_code ELFFileNode::parse(const LinkingContext &ctx,
raw_ostream &diagnostics) {
ErrorOr<StringRef> filePath = getPath(ctx);
if (error_code ec = filePath.getError())
return ec;
if (error_code ec = getBuffer(*filePath))
return ec;
if (ctx.logInputFiles())
diagnostics << *filePath << "\n";
if (_attributes._isWholeArchive) {
std::vector<std::unique_ptr<File>> parsedFiles;
if (error_code ec = ctx.registry().parseFile(_buffer, parsedFiles))
return ec;
assert(parsedFiles.size() == 1);
std::unique_ptr<File> f(parsedFiles[0].release());
if (auto archive = reinterpret_cast<const ArchiveLibraryFile *>(f.get())) {
// Have this node own the FileArchive object.
_archiveFile.reset(archive);
f.release();
// Add all members to _files vector
return archive->parseAllMembers(_files);
}
// if --whole-archive is around non-archive, just use it as normal.
_files.push_back(std::move(f));
return error_code::success();
}
return ctx.registry().parseFile(_buffer, _files);
}
/// \brief Parse the GnuLD Script
error_code GNULdScript::parse(const LinkingContext &ctx,
raw_ostream &diagnostics) {
ErrorOr<StringRef> filePath = getPath(ctx);
if (error_code ec = filePath.getError())
return ec;
if (error_code ec = getBuffer(*filePath))
return ec;
if (ctx.logInputFiles())
diagnostics << *filePath << "\n";
_lexer.reset(new script::Lexer(std::move(_buffer)));
_parser.reset(new script::Parser(*_lexer.get()));
_linkerScript = _parser->parse();
if (!_linkerScript)
return LinkerScriptReaderError::parse_error;
return error_code::success();
}
static bool isPathUnderSysroot(StringRef sysroot, StringRef path) {
// TODO: Handle the case when 'sysroot' and/or 'path' are symlinks.
if (sysroot.empty() || sysroot.size() >= path.size())
return false;
if (llvm::sys::path::is_separator(sysroot.back()))
sysroot = sysroot.substr(0, sysroot.size() - 1);
if (!llvm::sys::path::is_separator(path[sysroot.size()]))
return false;
return llvm::sys::fs::equivalent(sysroot, path.substr(0, sysroot.size()));
}
/// \brief Handle GnuLD script for ELF.
error_code ELFGNULdScript::parse(const LinkingContext &ctx,
raw_ostream &diagnostics) {
ELFFileNode::Attributes attributes;
if (error_code ec = GNULdScript::parse(ctx, diagnostics))
return ec;
StringRef sysRoot = _elfLinkingContext.getSysroot();
if (!sysRoot.empty() && isPathUnderSysroot(sysRoot, *getPath(ctx)))
attributes.setSysRooted(true);
for (const script::Command *c : _linkerScript->_commands) {
auto *group = dyn_cast<script::Group>(c);
if (!group)
continue;
std::unique_ptr<Group> groupStart(new Group());
for (const script::Path &path : group->getPaths()) {
// TODO : Propagate Set WholeArchive/dashlPrefix
attributes.setAsNeeded(path._asNeeded);
auto inputNode = new ELFFileNode(
_elfLinkingContext, _elfLinkingContext.allocateString(path._path),
attributes);
std::unique_ptr<InputElement> inputFile(inputNode);
groupStart.get()->addFile(std::move(inputFile));
}
_expandElements.push_back(std::move(groupStart));
}
return error_code::success();
}
<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <vvasilev@cern.ch>
//------------------------------------------------------------------------------
#include "MetaSema.h"
#include "Display.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/MetaProcessor/MetaProcessor.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/CompilerInstance.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h" // for llvm::outs() FIXME
#include <cstdlib>
namespace cling {
void MetaSema::actOnLCommand(llvm::sys::Path file) const {
m_Interpreter.loadFile(file.str());
// TODO: extra checks. Eg if the path is readable, if the file exists...
}
void MetaSema::actOnComment(llvm::StringRef comment) const {
// Some of the comments are meaningful for the cling::Interpreter
m_Interpreter.declare(comment);
}
void MetaSema::actOnxCommand(llvm::sys::Path file, llvm::StringRef args)
{
// Fall back to the meta processor for now.
m_LastResultedValue = StoredValueRef::invalidValue();
m_MetaProcessor.executeFile(file.str(), args.str(), &m_LastResultedValue);
//m_Interpreter.loadFile(path.str());
// TODO: extra checks. Eg if the path is readable, if the file exists...
}
void MetaSema::actOnqCommand() {
m_IsQuitRequested = true;
}
void MetaSema::actOnUCommand() const {
m_Interpreter.unload();
}
void MetaSema::actOnICommand(llvm::sys::Path path) const {
if (path.isEmpty())
m_Interpreter.DumpIncludePath();
else
m_Interpreter.AddIncludePath(path.str());
}
void MetaSema::actOnrawInputCommand(SwitchMode mode/* = kToggle*/) const {
if (mode == kToggle) {
bool flag = !m_Interpreter.isRawInputEnabled();
m_Interpreter.enableRawInput(flag);
// FIXME:
llvm::outs() << (flag ? "U" :"Not u") << "sing raw input\n";
}
else
m_Interpreter.enableRawInput(mode);
}
void MetaSema::actOnprintASTCommand(SwitchMode mode/* = kToggle*/) const {
if (mode == kToggle) {
bool flag = !m_Interpreter.isPrintingAST();
m_Interpreter.enablePrintAST(flag);
// FIXME:
llvm::outs() << (flag ? "P" : "Not p") << "rinting AST\n";
}
else
m_Interpreter.enablePrintAST(mode);
}
void MetaSema::actOndynamicExtensionsCommand(SwitchMode mode/* = kToggle*/)
const {
if (mode == kToggle) {
bool flag = !m_Interpreter.isDynamicLookupEnabled();
m_Interpreter.enableDynamicLookup(flag);
// FIXME:
llvm::outs() << (flag ? "U" : "Not u") << "sing dynamic extensions\n";
}
else
m_Interpreter.enableDynamicLookup(mode);
}
void MetaSema::actOnhelpCommand() const {
std::string& metaString = m_Interpreter.getOptions().MetaString;
llvm::outs() << "Cling meta commands usage\n";
llvm::outs() << "Syntax: .Command [arg0 arg1 ... argN]\n";
llvm::outs() << "\n";
llvm::outs() << metaString << "q\t\t\t\t- Exit the program\n";
llvm::outs() << metaString << "L <filename>\t\t\t - Load file or library\n";
llvm::outs() << metaString << "(x|X) <filename>[args]\t\t- Same as .L and runs a ";
llvm::outs() << "function with signature ";
llvm::outs() << "\t\t\t\tret_type filename(args)\n";
llvm::outs() << metaString << "I [path]\t\t\t- Shows the include path. If a path is ";
llvm::outs() << "given - \n\t\t\t\tadds the path to the include paths\n";
llvm::outs() << metaString << "@ \t\t\t\t- Cancels and ignores the multiline input\n";
llvm::outs() << metaString << "rawInput [0|1]\t\t\t- Toggle wrapping and printing ";
llvm::outs() << "the execution\n\t\t\t\tresults of the input\n";
llvm::outs() << metaString << "dynamicExtensions [0|1]\t- Toggles the use of the ";
llvm::outs() << "dynamic scopes and the \t\t\t\tlate binding\n";
llvm::outs() << metaString << "printAST [0|1]\t\t\t- Toggles the printing of input's ";
llvm::outs() << "corresponding \t\t\t\tAST nodes\n";
llvm::outs() << metaString << "help\t\t\t\t- Shows this information\n";
}
void MetaSema::actOnfileExCommand() const {
const clang::SourceManager& SM = m_Interpreter.getCI()->getSourceManager();
SM.getFileManager().PrintStats();
llvm::outs() << "\n***\n\n";
for (clang::SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
llvm::outs() << (*I).first->getName();
llvm::outs() << "\n";
}
}
void MetaSema::actOnfilesCommand() const {
typedef llvm::SmallVectorImpl<Interpreter::LoadedFileInfo*> LoadedFiles_t;
const LoadedFiles_t& LoadedFiles = m_Interpreter.getLoadedFiles();
for (LoadedFiles_t::const_iterator I = LoadedFiles.begin(),
E = LoadedFiles.end(); I != E; ++I) {
char cType[] = { 'S', 'D', 'B' };
llvm::outs() << '[' << cType[(*I)->getType()] << "] "
<< (*I)->getName() << '\n';
}
}
void MetaSema::actOnclassCommand(llvm::StringRef className) const {
if (!className.empty())
DisplayClass(llvm::outs(), &m_Interpreter, className.str().c_str(), true);
else
DisplayClasses(llvm::outs(), &m_Interpreter, false);
}
void MetaSema::actOnClassCommand() const {
DisplayClasses(llvm::outs(), &m_Interpreter, true);
}
void MetaSema::actOngCommand(llvm::StringRef varName) const {
if (varName.empty())
DisplayGlobals(llvm::outs(), &m_Interpreter);
else
DisplayGlobal(llvm::outs(), &m_Interpreter, varName.str().c_str());
}
void MetaSema::actOnTypedefCommand(llvm::StringRef typedefName) const {
if (typedefName.empty())
DisplayTypedefs(llvm::outs(), &m_Interpreter);
else
DisplayTypedef(llvm::outs(), &m_Interpreter, typedefName.str().c_str());
}
void MetaSema::actOnShellCommand(llvm::StringRef commandLine) const {
llvm::StringRef trimmed(commandLine.trim(" \t\n\v\f\r "));
if (!trimmed.empty()) {
int ret = std::system(trimmed.str().c_str());
(void) ret; // Silence warning unused return result of system.
}
}
} // end namespace cling
<commit_msg>Also print headers from modules - once we update clang as it doesn't exist yet in our revision...<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author: Vassil Vassilev <vvasilev@cern.ch>
//------------------------------------------------------------------------------
#include "MetaSema.h"
#include "Display.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/MetaProcessor/MetaProcessor.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Serialization/ASTReader.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h" // for llvm::outs() FIXME
#include <cstdlib>
namespace cling {
void MetaSema::actOnLCommand(llvm::sys::Path file) const {
m_Interpreter.loadFile(file.str());
// TODO: extra checks. Eg if the path is readable, if the file exists...
}
void MetaSema::actOnComment(llvm::StringRef comment) const {
// Some of the comments are meaningful for the cling::Interpreter
m_Interpreter.declare(comment);
}
void MetaSema::actOnxCommand(llvm::sys::Path file, llvm::StringRef args)
{
// Fall back to the meta processor for now.
m_LastResultedValue = StoredValueRef::invalidValue();
m_MetaProcessor.executeFile(file.str(), args.str(), &m_LastResultedValue);
//m_Interpreter.loadFile(path.str());
// TODO: extra checks. Eg if the path is readable, if the file exists...
}
void MetaSema::actOnqCommand() {
m_IsQuitRequested = true;
}
void MetaSema::actOnUCommand() const {
m_Interpreter.unload();
}
void MetaSema::actOnICommand(llvm::sys::Path path) const {
if (path.isEmpty())
m_Interpreter.DumpIncludePath();
else
m_Interpreter.AddIncludePath(path.str());
}
void MetaSema::actOnrawInputCommand(SwitchMode mode/* = kToggle*/) const {
if (mode == kToggle) {
bool flag = !m_Interpreter.isRawInputEnabled();
m_Interpreter.enableRawInput(flag);
// FIXME:
llvm::outs() << (flag ? "U" :"Not u") << "sing raw input\n";
}
else
m_Interpreter.enableRawInput(mode);
}
void MetaSema::actOnprintASTCommand(SwitchMode mode/* = kToggle*/) const {
if (mode == kToggle) {
bool flag = !m_Interpreter.isPrintingAST();
m_Interpreter.enablePrintAST(flag);
// FIXME:
llvm::outs() << (flag ? "P" : "Not p") << "rinting AST\n";
}
else
m_Interpreter.enablePrintAST(mode);
}
void MetaSema::actOndynamicExtensionsCommand(SwitchMode mode/* = kToggle*/)
const {
if (mode == kToggle) {
bool flag = !m_Interpreter.isDynamicLookupEnabled();
m_Interpreter.enableDynamicLookup(flag);
// FIXME:
llvm::outs() << (flag ? "U" : "Not u") << "sing dynamic extensions\n";
}
else
m_Interpreter.enableDynamicLookup(mode);
}
void MetaSema::actOnhelpCommand() const {
std::string& metaString = m_Interpreter.getOptions().MetaString;
llvm::outs() << "Cling meta commands usage\n";
llvm::outs() << "Syntax: .Command [arg0 arg1 ... argN]\n";
llvm::outs() << "\n";
llvm::outs() << metaString << "q\t\t\t\t- Exit the program\n";
llvm::outs() << metaString << "L <filename>\t\t\t - Load file or library\n";
llvm::outs() << metaString << "(x|X) <filename>[args]\t\t- Same as .L and runs a ";
llvm::outs() << "function with signature ";
llvm::outs() << "\t\t\t\tret_type filename(args)\n";
llvm::outs() << metaString << "I [path]\t\t\t- Shows the include path. If a path is ";
llvm::outs() << "given - \n\t\t\t\tadds the path to the include paths\n";
llvm::outs() << metaString << "@ \t\t\t\t- Cancels and ignores the multiline input\n";
llvm::outs() << metaString << "rawInput [0|1]\t\t\t- Toggle wrapping and printing ";
llvm::outs() << "the execution\n\t\t\t\tresults of the input\n";
llvm::outs() << metaString << "dynamicExtensions [0|1]\t- Toggles the use of the ";
llvm::outs() << "dynamic scopes and the \t\t\t\tlate binding\n";
llvm::outs() << metaString << "printAST [0|1]\t\t\t- Toggles the printing of input's ";
llvm::outs() << "corresponding \t\t\t\tAST nodes\n";
llvm::outs() << metaString << "help\t\t\t\t- Shows this information\n";
}
void MetaSema::actOnfileExCommand() const {
const clang::SourceManager& SM = m_Interpreter.getCI()->getSourceManager();
SM.getFileManager().PrintStats();
llvm::outs() << "\n***\n\n";
for (clang::SourceManager::fileinfo_iterator I = SM.fileinfo_begin(),
E = SM.fileinfo_end(); I != E; ++I) {
llvm::outs() << (*I).first->getName();
llvm::outs() << "\n";
}
/* Only available in clang's trunk:
clang::ASTReader* Reader = m_Interpreter.getCI()->getModuleManager();
const clang::serialization::ModuleManager& ModMan
= Reader->getModuleManager();
for (clang::serialization::ModuleManager::ModuleConstIterator I
= ModMan.begin(), E = ModMan.end(); I != E; ++I) {
typedef
std::vector<llvm::PointerIntPair<const clang::FileEntry*, 1, bool> >
InputFiles_t;
const InputFiles_t& InputFiles = (*I)->InputFilesLoaded;
for (InputFiles_t::const_iterator IFI = InputFiles.begin(),
IFE = InputFiles.end(); IFI != IFE; ++IFI) {
llvm::outs() << IFI->getPointer()->getName();
llvm::outs() << "\n";
}
}
*/
}
void MetaSema::actOnfilesCommand() const {
typedef llvm::SmallVectorImpl<Interpreter::LoadedFileInfo*> LoadedFiles_t;
const LoadedFiles_t& LoadedFiles = m_Interpreter.getLoadedFiles();
for (LoadedFiles_t::const_iterator I = LoadedFiles.begin(),
E = LoadedFiles.end(); I != E; ++I) {
char cType[] = { 'S', 'D', 'B' };
llvm::outs() << '[' << cType[(*I)->getType()] << "] "
<< (*I)->getName() << '\n';
}
}
void MetaSema::actOnclassCommand(llvm::StringRef className) const {
if (!className.empty())
DisplayClass(llvm::outs(), &m_Interpreter, className.str().c_str(), true);
else
DisplayClasses(llvm::outs(), &m_Interpreter, false);
}
void MetaSema::actOnClassCommand() const {
DisplayClasses(llvm::outs(), &m_Interpreter, true);
}
void MetaSema::actOngCommand(llvm::StringRef varName) const {
if (varName.empty())
DisplayGlobals(llvm::outs(), &m_Interpreter);
else
DisplayGlobal(llvm::outs(), &m_Interpreter, varName.str().c_str());
}
void MetaSema::actOnTypedefCommand(llvm::StringRef typedefName) const {
if (typedefName.empty())
DisplayTypedefs(llvm::outs(), &m_Interpreter);
else
DisplayTypedef(llvm::outs(), &m_Interpreter, typedefName.str().c_str());
}
void MetaSema::actOnShellCommand(llvm::StringRef commandLine) const {
llvm::StringRef trimmed(commandLine.trim(" \t\n\v\f\r "));
if (!trimmed.empty()) {
int ret = std::system(trimmed.str().c_str());
(void) ret; // Silence warning unused return result of system.
}
}
} // end namespace cling
<|endoftext|>
|
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// $Id$
#include <mapnik/map.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/font_engine_freetype.hpp>
#include <mapnik/agg_renderer.hpp>
#include <mapnik/filter_factory.hpp>
#include <mapnik/color_factory.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/config_error.hpp>
#include <iostream>
int main ( int argc , char** argv)
{
if (argc != 2)
{
std::cout << "usage: ./rundemo <plugins_dir>\n";
return EXIT_SUCCESS;
}
using namespace mapnik;
try {
std::cout << " running demo ... \n";
datasource_cache::instance()->register_datasources(argv[1]);
freetype_engine::register_font("/usr/local/lib/mapnik/fonts/DejaVuSans.ttf");
Map m(800,600);
m.set_background(color_factory::from_string("white"));
// create styles
// Provinces (polygon)
feature_type_style provpoly_style;
rule_type provpoly_rule_on;
provpoly_rule_on.set_filter(create_filter("[NAME_EN] = 'Ontario'"));
provpoly_rule_on.append(polygon_symbolizer(Color(250, 190, 183)));
provpoly_style.add_rule(provpoly_rule_on);
rule_type provpoly_rule_qc;
provpoly_rule_qc.set_filter(create_filter("[NAME_EN] = 'Quebec'"));
provpoly_rule_qc.append(polygon_symbolizer(Color(217, 235, 203)));
provpoly_style.add_rule(provpoly_rule_qc);
m.insert_style("provinces",provpoly_style);
// Provinces (polyline)
feature_type_style provlines_style;
stroke provlines_stk (Color(0,0,0),1.0);
provlines_stk.add_dash(8, 4);
provlines_stk.add_dash(2, 2);
provlines_stk.add_dash(2, 2);
rule_type provlines_rule;
provlines_rule.append(line_symbolizer(provlines_stk));
provlines_style.add_rule(provlines_rule);
m.insert_style("provlines",provlines_style);
// Drainage
feature_type_style qcdrain_style;
rule_type qcdrain_rule;
qcdrain_rule.set_filter(create_filter("[HYC] = 8"));
qcdrain_rule.append(polygon_symbolizer(Color(153, 204, 255)));
qcdrain_style.add_rule(qcdrain_rule);
m.insert_style("drainage",qcdrain_style);
// Roads 3 and 4 (The "grey" roads)
feature_type_style roads34_style;
rule_type roads34_rule;
roads34_rule.set_filter(create_filter("[CLASS] = 3 or [CLASS] = 4"));
stroke roads34_rule_stk(Color(171,158,137),2.0);
roads34_rule_stk.set_line_cap(ROUND_CAP);
roads34_rule_stk.set_line_join(ROUND_JOIN);
roads34_rule.append(line_symbolizer(roads34_rule_stk));
roads34_style.add_rule(roads34_rule);
m.insert_style("smallroads",roads34_style);
// Roads 2 (The thin yellow ones)
feature_type_style roads2_style_1;
rule_type roads2_rule_1;
roads2_rule_1.set_filter(create_filter("[CLASS] = 2"));
stroke roads2_rule_stk_1(Color(171,158,137),4.0);
roads2_rule_stk_1.set_line_cap(ROUND_CAP);
roads2_rule_stk_1.set_line_join(ROUND_JOIN);
roads2_rule_1.append(line_symbolizer(roads2_rule_stk_1));
roads2_style_1.add_rule(roads2_rule_1);
m.insert_style("road-border", roads2_style_1);
feature_type_style roads2_style_2;
rule_type roads2_rule_2;
roads2_rule_2.set_filter(create_filter("[CLASS] = 2"));
stroke roads2_rule_stk_2(Color(255,250,115),2.0);
roads2_rule_stk_2.set_line_cap(ROUND_CAP);
roads2_rule_stk_2.set_line_join(ROUND_JOIN);
roads2_rule_2.append(line_symbolizer(roads2_rule_stk_2));
roads2_style_2.add_rule(roads2_rule_2);
m.insert_style("road-fill", roads2_style_2);
// Roads 1 (The big orange ones, the highways)
feature_type_style roads1_style_1;
rule_type roads1_rule_1;
roads1_rule_1.set_filter(create_filter("[CLASS] = 1"));
stroke roads1_rule_stk_1(Color(188,149,28),7.0);
roads1_rule_stk_1.set_line_cap(ROUND_CAP);
roads1_rule_stk_1.set_line_join(ROUND_JOIN);
roads1_rule_1.append(line_symbolizer(roads1_rule_stk_1));
roads1_style_1.add_rule(roads1_rule_1);
m.insert_style("highway-border", roads1_style_1);
feature_type_style roads1_style_2;
rule_type roads1_rule_2;
roads1_rule_2.set_filter(create_filter("[CLASS] = 1"));
stroke roads1_rule_stk_2(Color(242,191,36),5.0);
roads1_rule_stk_2.set_line_cap(ROUND_CAP);
roads1_rule_stk_2.set_line_join(ROUND_JOIN);
roads1_rule_2.append(line_symbolizer(roads1_rule_stk_2));
roads1_style_2.add_rule(roads1_rule_2);
m.insert_style("highway-fill", roads1_style_2);
// Populated Places
feature_type_style popplaces_style;
rule_type popplaces_rule;
text_symbolizer popplaces_text_symbolizer("GEONAME","DejaVu Sans Book",10,Color(0,0,0));
popplaces_text_symbolizer.set_halo_fill(Color(255,255,200));
popplaces_text_symbolizer.set_halo_radius(1);
popplaces_rule.append(popplaces_text_symbolizer);
popplaces_style.add_rule(popplaces_rule);
m.insert_style("popplaces",popplaces_style );
// Layers
// Provincial polygons
{
parameters p;
p["type"]="shape";
p["file"]="../data/boundaries";
Layer lyr("Provinces");
lyr.set_datasource(datasource_cache::instance()->create(p));
lyr.add_style("provinces");
m.addLayer(lyr);
}
// Drainage
{
parameters p;
p["type"]="shape";
p["file"]="../data/qcdrainage";
Layer lyr("Quebec Hydrography");
lyr.set_datasource(datasource_cache::instance()->create(p));
lyr.add_style("drainage");
m.addLayer(lyr);
}
{
parameters p;
p["type"]="shape";
p["file"]="../data/ontdrainage";
Layer lyr("Ontario Hydrography");
lyr.set_datasource(datasource_cache::instance()->create(p));
lyr.add_style("drainage");
m.addLayer(lyr);
}
// Provincial boundaries
{
parameters p;
p["type"]="shape";
p["file"]="../data/boundaries_l";
Layer lyr("Provincial borders");
lyr.set_datasource(datasource_cache::instance()->create(p));
lyr.add_style("provlines");
m.addLayer(lyr);
}
// Roads
{
parameters p;
p["type"]="shape";
p["file"]="../data/roads";
Layer lyr("Roads");
lyr.set_datasource(datasource_cache::instance()->create(p));
lyr.add_style("smallroads");
lyr.add_style("road-border");
lyr.add_style("road-fill");
lyr.add_style("highway-border");
lyr.add_style("highway-fill");
m.addLayer(lyr);
}
// popplaces
{
parameters p;
p["type"]="shape";
p["file"]="../data/popplaces";
p["encoding"] = "latin1";
Layer lyr("Populated Places");
lyr.set_datasource(datasource_cache::instance()->create(p));
lyr.add_style("popplaces");
m.addLayer(lyr);
}
m.zoomToBox(Envelope<double>(1405120.04127408,-247003.813399447,
1706357.31328276,-25098.593149577));
Image32 buf(m.getWidth(),m.getHeight());
agg_renderer<Image32> ren(m,buf);
ren.apply();
save_to_file<ImageData32>("demo.jpg","jpeg",buf.data());
save_to_file<ImageData32>("demo.png","png",buf.data());
std::cout << "Two maps have been rendered in the current directory:\n"
"- demo.jpg\n"
"- demo.png\n"
"Have a look!\n";
}
catch ( const mapnik::config_error & ex )
{
std::cerr << "### Configuration error: " << ex.what();
return EXIT_FAILURE;
}
catch ( const std::exception & ex )
{
std::cerr << "### std::exception: " << ex.what();
return EXIT_FAILURE;
}
catch ( ... )
{
std::cerr << "### Unknown exception." << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>1. define BOOST_SPIRIT_THREADSAFE (should be defined in config.hpp??) to be compatible with the core library. 2. use mapnik install_dir as input argument. 3. Generate three images as in rundemo.py<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
// $Id$
// define before any includes
#define BOOST_SPIRIT_THREADSAFE
#include <mapnik/map.hpp>
#include <mapnik/datasource_cache.hpp>
#include <mapnik/font_engine_freetype.hpp>
#include <mapnik/agg_renderer.hpp>
#include <mapnik/filter_factory.hpp>
#include <mapnik/color_factory.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/config_error.hpp>
#include <iostream>
int main ( int argc , char** argv)
{
if (argc != 2)
{
std::cout << "usage: ./rundemo <mapnik_install_dir>\n";
return EXIT_SUCCESS;
}
using namespace mapnik;
try {
std::cout << " running demo ... \n";
std::string mapnik_dir(argv[1]);
datasource_cache::instance()->register_datasources(mapnik_dir + "/lib/mapnik/input/");
freetype_engine::register_font(mapnik_dir + "/lib/mapnik/fonts/DejaVuSans.ttf");
Map m(800,600);
m.set_background(color_factory::from_string("white"));
// create styles
// Provinces (polygon)
feature_type_style provpoly_style;
rule_type provpoly_rule_on;
provpoly_rule_on.set_filter(create_filter("[NAME_EN] = 'Ontario'"));
provpoly_rule_on.append(polygon_symbolizer(Color(250, 190, 183)));
provpoly_style.add_rule(provpoly_rule_on);
rule_type provpoly_rule_qc;
provpoly_rule_qc.set_filter(create_filter("[NAME_EN] = 'Quebec'"));
provpoly_rule_qc.append(polygon_symbolizer(Color(217, 235, 203)));
provpoly_style.add_rule(provpoly_rule_qc);
m.insert_style("provinces",provpoly_style);
// Provinces (polyline)
feature_type_style provlines_style;
stroke provlines_stk (Color(0,0,0),1.0);
provlines_stk.add_dash(8, 4);
provlines_stk.add_dash(2, 2);
provlines_stk.add_dash(2, 2);
rule_type provlines_rule;
provlines_rule.append(line_symbolizer(provlines_stk));
provlines_style.add_rule(provlines_rule);
m.insert_style("provlines",provlines_style);
// Drainage
feature_type_style qcdrain_style;
rule_type qcdrain_rule;
qcdrain_rule.set_filter(create_filter("[HYC] = 8"));
qcdrain_rule.append(polygon_symbolizer(Color(153, 204, 255)));
qcdrain_style.add_rule(qcdrain_rule);
m.insert_style("drainage",qcdrain_style);
// Roads 3 and 4 (The "grey" roads)
feature_type_style roads34_style;
rule_type roads34_rule;
roads34_rule.set_filter(create_filter("[CLASS] = 3 or [CLASS] = 4"));
stroke roads34_rule_stk(Color(171,158,137),2.0);
roads34_rule_stk.set_line_cap(ROUND_CAP);
roads34_rule_stk.set_line_join(ROUND_JOIN);
roads34_rule.append(line_symbolizer(roads34_rule_stk));
roads34_style.add_rule(roads34_rule);
m.insert_style("smallroads",roads34_style);
// Roads 2 (The thin yellow ones)
feature_type_style roads2_style_1;
rule_type roads2_rule_1;
roads2_rule_1.set_filter(create_filter("[CLASS] = 2"));
stroke roads2_rule_stk_1(Color(171,158,137),4.0);
roads2_rule_stk_1.set_line_cap(ROUND_CAP);
roads2_rule_stk_1.set_line_join(ROUND_JOIN);
roads2_rule_1.append(line_symbolizer(roads2_rule_stk_1));
roads2_style_1.add_rule(roads2_rule_1);
m.insert_style("road-border", roads2_style_1);
feature_type_style roads2_style_2;
rule_type roads2_rule_2;
roads2_rule_2.set_filter(create_filter("[CLASS] = 2"));
stroke roads2_rule_stk_2(Color(255,250,115),2.0);
roads2_rule_stk_2.set_line_cap(ROUND_CAP);
roads2_rule_stk_2.set_line_join(ROUND_JOIN);
roads2_rule_2.append(line_symbolizer(roads2_rule_stk_2));
roads2_style_2.add_rule(roads2_rule_2);
m.insert_style("road-fill", roads2_style_2);
// Roads 1 (The big orange ones, the highways)
feature_type_style roads1_style_1;
rule_type roads1_rule_1;
roads1_rule_1.set_filter(create_filter("[CLASS] = 1"));
stroke roads1_rule_stk_1(Color(188,149,28),7.0);
roads1_rule_stk_1.set_line_cap(ROUND_CAP);
roads1_rule_stk_1.set_line_join(ROUND_JOIN);
roads1_rule_1.append(line_symbolizer(roads1_rule_stk_1));
roads1_style_1.add_rule(roads1_rule_1);
m.insert_style("highway-border", roads1_style_1);
feature_type_style roads1_style_2;
rule_type roads1_rule_2;
roads1_rule_2.set_filter(create_filter("[CLASS] = 1"));
stroke roads1_rule_stk_2(Color(242,191,36),5.0);
roads1_rule_stk_2.set_line_cap(ROUND_CAP);
roads1_rule_stk_2.set_line_join(ROUND_JOIN);
roads1_rule_2.append(line_symbolizer(roads1_rule_stk_2));
roads1_style_2.add_rule(roads1_rule_2);
m.insert_style("highway-fill", roads1_style_2);
// Populated Places
feature_type_style popplaces_style;
rule_type popplaces_rule;
text_symbolizer popplaces_text_symbolizer("GEONAME","DejaVu Sans Book",10,Color(0,0,0));
popplaces_text_symbolizer.set_halo_fill(Color(255,255,200));
popplaces_text_symbolizer.set_halo_radius(1);
popplaces_rule.append(popplaces_text_symbolizer);
popplaces_style.add_rule(popplaces_rule);
m.insert_style("popplaces",popplaces_style );
// Layers
// Provincial polygons
{
parameters p;
p["type"]="shape";
p["file"]="../data/boundaries";
Layer lyr("Provinces");
lyr.set_datasource(datasource_cache::instance()->create(p));
lyr.add_style("provinces");
m.addLayer(lyr);
}
// Drainage
{
parameters p;
p["type"]="shape";
p["file"]="../data/qcdrainage";
Layer lyr("Quebec Hydrography");
lyr.set_datasource(datasource_cache::instance()->create(p));
lyr.add_style("drainage");
m.addLayer(lyr);
}
{
parameters p;
p["type"]="shape";
p["file"]="../data/ontdrainage";
Layer lyr("Ontario Hydrography");
lyr.set_datasource(datasource_cache::instance()->create(p));
lyr.add_style("drainage");
m.addLayer(lyr);
}
// Provincial boundaries
{
parameters p;
p["type"]="shape";
p["file"]="../data/boundaries_l";
Layer lyr("Provincial borders");
lyr.set_datasource(datasource_cache::instance()->create(p));
lyr.add_style("provlines");
m.addLayer(lyr);
}
// Roads
{
parameters p;
p["type"]="shape";
p["file"]="../data/roads";
Layer lyr("Roads");
lyr.set_datasource(datasource_cache::instance()->create(p));
lyr.add_style("smallroads");
lyr.add_style("road-border");
lyr.add_style("road-fill");
lyr.add_style("highway-border");
lyr.add_style("highway-fill");
m.addLayer(lyr);
}
// popplaces
{
parameters p;
p["type"]="shape";
p["file"]="../data/popplaces";
p["encoding"] = "latin1";
Layer lyr("Populated Places");
lyr.set_datasource(datasource_cache::instance()->create(p));
lyr.add_style("popplaces");
m.addLayer(lyr);
}
m.zoomToBox(Envelope<double>(1405120.04127408,-247003.813399447,
1706357.31328276,-25098.593149577));
Image32 buf(m.getWidth(),m.getHeight());
agg_renderer<Image32> ren(m,buf);
ren.apply();
save_to_file<ImageData32>("demo.jpg","jpeg",buf.data());
save_to_file<ImageData32>("demo.png","png",buf.data());
save_to_file<ImageData32>("demo256.png","png256",buf.data());
std::cout << "Three maps have been rendered in the current directory:\n"
"- demo.jpg\n"
"- demo.png\n"
"- demo256.png\n"
"Have a look!\n";
}
catch ( const mapnik::config_error & ex )
{
std::cerr << "### Configuration error: " << ex.what();
return EXIT_FAILURE;
}
catch ( const std::exception & ex )
{
std::cerr << "### std::exception: " << ex.what();
return EXIT_FAILURE;
}
catch ( ... )
{
std::cerr << "### Unknown exception." << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include "stdafx.h"
#include "util/fixes.h"
#include <temple/dll.h>
#include "temple_functions.h"
#include "config/config.h"
#include "xp.h"
#include "obj.h"
#include "critter.h"
#include "party.h"
#include "d20_level.h"
#include "gamesystems/objects/objsystem.h"
#include "sound.h"
#include "combat.h"
#include "history.h"
#include "float_line.h"
#include "gamesystems/gamesystems.h"
#include "gamesystems/particlesystems.h"
#include "ui/ui_systems.h"
#include "ui/ui_legacysystems.h"
temple::GlobalPrimitive<float, 0x102CF708> experienceMultiplier;
temple::GlobalPrimitive<int, 0x10BCA850> numCrittersSlainByCR;
temple::GlobalPrimitive<int, 0x10BCA8BC> xpPile; // sum of all the XP given to party members before divinding by party size
static_assert(CRMIN == -2, "CRMIN for XP award definition should be at most -2!");
static_assert(CRMAX >= 20, "CRMAX for XP award definition should be at least 20!");
static_assert(XPTABLE_MAXLEVEL >= 20, "XPTABLE_MAXLEVEL for XP award definition should be at least 20!");
// static int XPAwardTable[XPTABLE_MAXLEVEL][CRMAX - CRMIN + 1] = {};
BOOL XPAward::XpGainProcess(objHndl handle, int xpGainRaw){
if (!xpGainRaw || !handle)
return FALSE;
auto obj = objSystem->GetObject(handle);
auto couldAlreadyLevelup = d20LevelSys.CanLevelup(handle);
auto xpReduction = GetMulticlassXpReductionPercent(handle);
//Check if the multiclass xp penalty should be disabled for this character
auto res = d20Sys.D20QueryPython(handle, "No MultiClass XP Penalty");
if (res != 0) {
xpReduction = 0;
}
auto xpGain = (int)((1.0 - xpReduction / 100.0)*xpGainRaw);
std::string text(fmt::format("{} {} {} {}", description.getDisplayName(handle), combatSys.GetCombatMesLine(145), xpGain, combatSys.GetCombatMesLine(146) )); // [obj] gains [xpGain] experience points
if (xpReduction){
text.append(fmt::format(" {}", combatSys.GetCombatMesLine(147)));
}
histSys.CreateFromFreeText( (text + "\n").c_str());
auto xpNew = obj->GetInt32(obj_f_critter_experience) + xpGain;
auto curLvl = critterSys.GetEffectiveLevel(handle);
auto xpCap = d20LevelSys.GetXpRequireForLevel(curLvl + 2) - 1;
if (curLvl >= (int)config.maxLevel)
xpCap = d20LevelSys.GetXpRequireForLevel(config.maxLevel);
if (!config.allowXpOverflow && xpNew > (int)xpCap)
xpNew = xpCap;
d20Sys.d20SendSignal(handle, DK_SIG_Experience_Awarded, xpNew, 0);
obj->SetInt32(obj_f_critter_experience, xpNew);
if (couldAlreadyLevelup || !d20LevelSys.CanLevelup(handle))
return FALSE;
floatSys.FloatCombatLine(handle, 148); // gains a level!
histSys.CreateFromFreeText(fmt::format("{} {}\n", description.getDisplayName(handle), combatSys.GetCombatMesLine(148)).c_str()); // [obj] gains a level!
gameSystems->GetParticleSys().CreateAtObj("LEVEL UP", handle);
return TRUE;
}
int XPAward::GetMulticlassXpReductionPercent(objHndl handle){
auto highestLvl = -1;
auto reductionPct = 0;
if (config.laxRules && config.disableMulticlassXpPenalty)
return reductionPct;
for (auto it: d20ClassSys.baseClassEnums){
auto classEnum = (Stat)it;
auto classLvl = objects.StatLevelGet(handle, classEnum);
if (classLvl > highestLvl && !d20Sys.d20QueryWithData(handle, DK_QUE_FavoredClass, classEnum,0)){
highestLvl = classLvl;
}
}
for (auto it : d20ClassSys.baseClassEnums) {
auto classEnum = (Stat)it;
auto classLvl = objects.StatLevelGet(handle, classEnum);
if (classLvl > 0 && classLvl < highestLvl - 1 && !d20Sys.d20QueryWithData(handle, DK_QUE_FavoredClass, classEnum,0)){
reductionPct += 20;
}
}
if (reductionPct >= 80)
reductionPct = 80;
return reductionPct;
}
XPAward::XPAward(){
int table[XPTABLE_MAXLEVEL][CRMAX - CRMIN + 1];
memset(table, 0, sizeof(table));
// First set the table's "spine" - when CR = Level then XP = 300*level
for (int level = 1; level <= XPTABLE_MAXLEVEL; level++) {
assert(level >= 1);
assert(level - CRMIN < CRCOUNT);
if (!config.slowerLevelling || level < 3)
table[level - 1][level - CRMIN] = level * 300;
else
table[level - 1][level - CRMIN] = (int)(
level * 300 *
(
1 - min(0.66f,
0.66f * powf(level - 2.0f, 0.1f) / powf(16.0f, 0.1f)
)
)
);
}
// Fill out the bottom left portion - CRs less than level - from highest to lowest
for (int level = 1; level <= XPTABLE_MAXLEVEL; level++){
for (int j = level - CRMIN - 1; j >= 2; j--){
int i = level - 1;
int cr = j + CRMIN;
assert(i >= 0 && i < XPTABLE_MAXLEVEL);
assert(j >= 0 && j < CRCOUNT);
// 8 CRs below level grant nothing
if (cr <= level - 8){
table[i][j] = 0;
}
else if (cr == 0){
table[i][2] = table[i][3] / 2; // CR 1/2
table[i][1] = table[i][3] / 3; // CR 1/3
table[i][0] = table[i][3] / 4; // CR 1/4
}
else if (cr == level - 1) {
assert(i >= 1);
if (config.slowerLevelling)
table[i][j] = min(table[i - 1][j], (table[i][j + 1] * 6) / 11);
else
table[i][j] = min(table[i - 1][j], (table[i][j+1] * 2) /3);
}
else {
assert(i >= 1);
assert(j + 2 < CRCOUNT);
if (config.slowerLevelling)
table[i][j] = min(table[i - 1][j], ( table[i][j + 2] * 3) / 10);
else
table[i][j] = min(table[i - 1][j], table[i][j + 2] / 2);
}
}
}
// Fill out the top right portion
for (int cr_off = 1; cr_off < CRMAX; cr_off++){
for (int level = 1; level <= XPTABLE_MAXLEVEL && level + cr_off <= CRMAX; level++){
int i = level - 1;
int j = level - CRMIN + cr_off;
assert(i >= 0 && i < XPTABLE_MAXLEVEL);
assert(j >= 0 && j < CRCOUNT);
if (cr_off >= 10){
table[i][j] = table[level - 1][j - 1]; // repeat the last value
}
else if (cr_off == 1){
assert(j >= 1);
assert(i + 1 < XPTABLE_MAXLEVEL);
table[i][j] = max((table[i][j - 1] * 3) / 2, table[i + 1][j]);
}
else {
assert(i + 1 < XPTABLE_MAXLEVEL);
assert(j >= 2);
table[i][j] = max(table[i][j - 2] * 2, table[i + 1][j]);
}
}
}
memcpy(XPAwardTable, table, sizeof(table));
};
// XP Table Fix for higher levels
class XPTableForHighLevels : public TempleFix {
public:
XPAward *xpawarddd;
void GiveXPAwards();
void apply() override;
} xpTableFix;
void XPTableForHighLevels::GiveXPAwards(){
float fNumLivingPartyMembers = 0.0;
//int XPAwardTable[XPTABLE_MAXLEVEL][CRMAX - CRMIN + 1] = {};
for (uint32_t i = 0; i < party.GroupPCsLen(); i++){
objHndl objHndPC = party.GroupPCsGetMemberN(i);
if (!critterSys.IsDeadNullDestroyed(objHndPC)){
fNumLivingPartyMembers += 1.0;
}
};
for (uint32_t i = 0; i < party.GroupNPCFollowersLen(); i++){
objHndl objHndNPCFollower = party.GroupNPCFollowersGetMemberN(i);
if (!critterSys.IsDeadNullDestroyed(objHndNPCFollower)
&& !d20Sys.d20Query(objHndNPCFollower, DK_QUE_ExperienceExempt)){
fNumLivingPartyMembers += 1.0;
}
};
if (fNumLivingPartyMembers < 0.99){
return;
};
auto killCountByCR = numCrittersSlainByCR.ptr();
bool bShouldUpdatePartyUI = false;
int xpForxpPile = 0;
for (uint32_t i = 0; i < party.GroupListGetLen(); i++){
objHndl objHnd = party.GroupListGetMemberN(i);
if (critterSys.IsDeadNullDestroyed(objHnd)){ continue; };
if (d20Sys.d20Query(objHnd, DK_QUE_ExperienceExempt)) { continue; };
if (party.ObjIsAIFollower(objHnd)) { continue; };
int level = critterSys.GetEffectiveLevel(objHnd);
if (level <= 0) { continue; };
int xpGainRaw = 0; // raw means it's prior to applying multiclass penalties, which is Someone Else's Problem :P
for (int n = 0; n < CR_KILLED_TABLE_SIZE; n++){
float nkill = (float)killCountByCR[n];
float xp = (float)xpawarddd->XPAwardTable[level - 1][n];
if (nkill){
xpGainRaw += (int)(
experienceMultiplier *
nkill * xp
);
}
}
xpForxpPile += xpGainRaw;
xpGainRaw = int((float)(xpGainRaw) / fNumLivingPartyMembers);
//if (templeFuncs.ObjXPGainProcess(objHnd, xpGainRaw)) {
if (xpawarddd->XpGainProcess(objHnd, xpGainRaw)){
auto obj = objSystem->GetObject(objHnd);
if (obj->IsPC() || config.NPCsLevelLikePCs){
bShouldUpdatePartyUI = true;
}
}
}
for (int n = 0; n < CR_KILLED_TABLE_SIZE; n++){
killCountByCR[n] = 0;
};
*(xpPile.ptr()) = xpForxpPile;
if (bShouldUpdatePartyUI){
uiSystems->GetParty().Update();
sound.PlaySound(100001); // LEVEL_UP.WAV
sound.PlaySound(100001); // amp it up a bit
}
return;
}
void XPTableForHighLevels::apply() {
logger->info("Applying XP Table Extension upto Level 20");
replaceFunction<void(__cdecl)()>(0x100B5700, []() {
xpTableFix.GiveXPAwards(); }
);
xpawarddd = new XPAward();
if (config.allowXpOverflow) {
writeNoops(0x100B5608);
}
}
<commit_msg>XP table update: replaced usage of LUT in Restoration spell<commit_after>#include "stdafx.h"
#include "util/fixes.h"
#include <temple/dll.h>
#include "temple_functions.h"
#include "config/config.h"
#include "xp.h"
#include "obj.h"
#include "critter.h"
#include "party.h"
#include "d20_level.h"
#include "gamesystems/objects/objsystem.h"
#include "sound.h"
#include "combat.h"
#include "history.h"
#include "float_line.h"
#include "gamesystems/gamesystems.h"
#include "gamesystems/particlesystems.h"
#include "ui/ui_systems.h"
#include "ui/ui_legacysystems.h"
temple::GlobalPrimitive<float, 0x102CF708> experienceMultiplier;
temple::GlobalPrimitive<int, 0x10BCA850> numCrittersSlainByCR;
temple::GlobalPrimitive<int, 0x10BCA8BC> xpPile; // sum of all the XP given to party members before divinding by party size
static_assert(CRMIN == -2, "CRMIN for XP award definition should be at most -2!");
static_assert(CRMAX >= 20, "CRMAX for XP award definition should be at least 20!");
static_assert(XPTABLE_MAXLEVEL >= 20, "XPTABLE_MAXLEVEL for XP award definition should be at least 20!");
// static int XPAwardTable[XPTABLE_MAXLEVEL][CRMAX - CRMIN + 1] = {};
/* 0x100B5480 */
BOOL XPAward::XpGainProcess(objHndl handle, int xpGainRaw){
if (!xpGainRaw || !handle)
return FALSE;
auto obj = objSystem->GetObject(handle);
auto couldAlreadyLevelup = d20LevelSys.CanLevelup(handle);
auto xpReduction = GetMulticlassXpReductionPercent(handle);
//Check if the multiclass xp penalty should be disabled for this character
auto res = d20Sys.D20QueryPython(handle, "No MultiClass XP Penalty");
if (res != 0) {
xpReduction = 0;
}
auto xpGain = (int)((1.0 - xpReduction / 100.0)*xpGainRaw);
std::string text(fmt::format("{} {} {} {}", description.getDisplayName(handle), combatSys.GetCombatMesLine(145), xpGain, combatSys.GetCombatMesLine(146) )); // [obj] gains [xpGain] experience points
if (xpReduction){
text.append(fmt::format(" {}", combatSys.GetCombatMesLine(147)));
}
histSys.CreateFromFreeText( (text + "\n").c_str());
auto xpNew = obj->GetInt32(obj_f_critter_experience) + xpGain;
auto curLvl = critterSys.GetEffectiveLevel(handle);
auto xpCap = d20LevelSys.GetXpRequireForLevel(curLvl + 2) - 1;
if (curLvl >= (int)config.maxLevel)
xpCap = d20LevelSys.GetXpRequireForLevel(config.maxLevel);
if (!config.allowXpOverflow && xpNew > (int)xpCap)
xpNew = xpCap;
d20Sys.d20SendSignal(handle, DK_SIG_Experience_Awarded, xpNew, 0);
obj->SetInt32(obj_f_critter_experience, xpNew);
if (couldAlreadyLevelup || !d20LevelSys.CanLevelup(handle))
return FALSE;
floatSys.FloatCombatLine(handle, 148); // gains a level!
histSys.CreateFromFreeText(fmt::format("{} {}\n", description.getDisplayName(handle), combatSys.GetCombatMesLine(148)).c_str()); // [obj] gains a level!
gameSystems->GetParticleSys().CreateAtObj("LEVEL UP", handle);
return TRUE;
}
int XPAward::GetMulticlassXpReductionPercent(objHndl handle){
auto highestLvl = -1;
auto reductionPct = 0;
if (config.laxRules && config.disableMulticlassXpPenalty)
return reductionPct;
for (auto it: d20ClassSys.baseClassEnums){
auto classEnum = (Stat)it;
auto classLvl = objects.StatLevelGet(handle, classEnum);
if (classLvl > highestLvl && !d20Sys.d20QueryWithData(handle, DK_QUE_FavoredClass, classEnum,0)){
highestLvl = classLvl;
}
}
for (auto it : d20ClassSys.baseClassEnums) {
auto classEnum = (Stat)it;
auto classLvl = objects.StatLevelGet(handle, classEnum);
if (classLvl > 0 && classLvl < highestLvl - 1 && !d20Sys.d20QueryWithData(handle, DK_QUE_FavoredClass, classEnum,0)){
reductionPct += 20;
}
}
if (reductionPct >= 80)
reductionPct = 80;
return reductionPct;
}
XPAward::XPAward(){
int table[XPTABLE_MAXLEVEL][CRMAX - CRMIN + 1];
memset(table, 0, sizeof(table));
// First set the table's "spine" - when CR = Level then XP = 300*level
for (int level = 1; level <= XPTABLE_MAXLEVEL; level++) {
assert(level >= 1);
assert(level - CRMIN < CRCOUNT);
if (!config.slowerLevelling || level < 3)
table[level - 1][level - CRMIN] = level * 300;
else
table[level - 1][level - CRMIN] = (int)(
level * 300 *
(
1 - min(0.66f,
0.66f * powf(level - 2.0f, 0.1f) / powf(16.0f, 0.1f)
)
)
);
}
// Fill out the bottom left portion - CRs less than level - from highest to lowest
for (int level = 1; level <= XPTABLE_MAXLEVEL; level++){
for (int j = level - CRMIN - 1; j >= 2; j--){
int i = level - 1;
int cr = j + CRMIN;
assert(i >= 0 && i < XPTABLE_MAXLEVEL);
assert(j >= 0 && j < CRCOUNT);
// 8 CRs below level grant nothing
if (cr <= level - 8){
table[i][j] = 0;
}
else if (cr == 0){
table[i][2] = table[i][3] / 2; // CR 1/2
table[i][1] = table[i][3] / 3; // CR 1/3
table[i][0] = table[i][3] / 4; // CR 1/4
}
else if (cr == level - 1) {
assert(i >= 1);
if (config.slowerLevelling)
table[i][j] = min(table[i - 1][j], (table[i][j + 1] * 6) / 11);
else
table[i][j] = min(table[i - 1][j], (table[i][j+1] * 2) /3);
}
else {
assert(i >= 1);
assert(j + 2 < CRCOUNT);
if (config.slowerLevelling)
table[i][j] = min(table[i - 1][j], ( table[i][j + 2] * 3) / 10);
else
table[i][j] = min(table[i - 1][j], table[i][j + 2] / 2);
}
}
}
// Fill out the top right portion
for (int cr_off = 1; cr_off < CRMAX; cr_off++){
for (int level = 1; level <= XPTABLE_MAXLEVEL && level + cr_off <= CRMAX; level++){
int i = level - 1;
int j = level - CRMIN + cr_off;
assert(i >= 0 && i < XPTABLE_MAXLEVEL);
assert(j >= 0 && j < CRCOUNT);
if (cr_off >= 10){
table[i][j] = table[level - 1][j - 1]; // repeat the last value
}
else if (cr_off == 1){
assert(j >= 1);
assert(i + 1 < XPTABLE_MAXLEVEL);
table[i][j] = max((table[i][j - 1] * 3) / 2, table[i + 1][j]);
}
else {
assert(i + 1 < XPTABLE_MAXLEVEL);
assert(j >= 2);
table[i][j] = max(table[i][j - 2] * 2, table[i + 1][j]);
}
}
}
memcpy(XPAwardTable, table, sizeof(table));
};
// XP Table Fix for higher levels
class XPTableForHighLevels : public TempleFix {
public:
XPAward *xpawarddd;
void GiveXPAwards();
void apply() override;
} xpTableFix;
/* 0x100B5700 */
void XPTableForHighLevels::GiveXPAwards(){
float fNumLivingPartyMembers = 0.0;
//int XPAwardTable[XPTABLE_MAXLEVEL][CRMAX - CRMIN + 1] = {};
for (uint32_t i = 0; i < party.GroupPCsLen(); i++){
objHndl objHndPC = party.GroupPCsGetMemberN(i);
if (!critterSys.IsDeadNullDestroyed(objHndPC)){
fNumLivingPartyMembers += 1.0;
}
};
for (uint32_t i = 0; i < party.GroupNPCFollowersLen(); i++){
objHndl objHndNPCFollower = party.GroupNPCFollowersGetMemberN(i);
if (!critterSys.IsDeadNullDestroyed(objHndNPCFollower)
&& !d20Sys.d20Query(objHndNPCFollower, DK_QUE_ExperienceExempt)){
fNumLivingPartyMembers += 1.0;
}
};
if (fNumLivingPartyMembers < 0.99){
return;
};
auto killCountByCR = numCrittersSlainByCR.ptr();
bool bShouldUpdatePartyUI = false;
int xpForxpPile = 0;
for (uint32_t i = 0; i < party.GroupListGetLen(); i++){
objHndl objHnd = party.GroupListGetMemberN(i);
if (critterSys.IsDeadNullDestroyed(objHnd)){ continue; };
if (d20Sys.d20Query(objHnd, DK_QUE_ExperienceExempt)) { continue; };
if (party.ObjIsAIFollower(objHnd)) { continue; };
int level = critterSys.GetEffectiveLevel(objHnd);
if (level <= 0) { continue; };
int xpGainRaw = 0; // raw means it's prior to applying multiclass penalties, which is Someone Else's Problem :P
for (int n = 0; n < CR_KILLED_TABLE_SIZE; n++){
float nkill = (float)killCountByCR[n];
float xp = (float)xpawarddd->XPAwardTable[level - 1][n];
if (nkill){
xpGainRaw += (int)(
experienceMultiplier *
nkill * xp
);
}
}
xpForxpPile += xpGainRaw;
xpGainRaw = int((float)(xpGainRaw) / fNumLivingPartyMembers);
//if (templeFuncs.ObjXPGainProcess(objHnd, xpGainRaw)) {
if (xpawarddd->XpGainProcess(objHnd, xpGainRaw)){
auto obj = objSystem->GetObject(objHnd);
if (obj->IsPC() || config.NPCsLevelLikePCs){
bShouldUpdatePartyUI = true;
}
}
}
for (int n = 0; n < CR_KILLED_TABLE_SIZE; n++){
killCountByCR[n] = 0;
};
*(xpPile.ptr()) = xpForxpPile;
if (bShouldUpdatePartyUI){
uiSystems->GetParty().Update();
sound.PlaySound(100001); // LEVEL_UP.WAV
sound.PlaySound(100001); // amp it up a bit
}
return;
}
void XPTableForHighLevels::apply() {
logger->info("Applying XP Table Extension upto Level 20");
replaceFunction<void(__cdecl)()>(0x100B5700, []() {
xpTableFix.GiveXPAwards(); }
);
// GetLevelForXp (used for restoration)
replaceFunction<int(__cdecl)(int)>(0x10080300, [](int xp)->int {
int maxLvl = (int)config.maxLevel;
auto xpMaxLvl = d20LevelSys.GetXpRequireForLevel(maxLvl);
if (xp <= xpMaxLvl) {
for (int lvl = maxLvl; lvl > 0; --lvl) {
if (xp >= d20LevelSys.GetXpRequireForLevel(lvl)) {
return lvl;
}
}
return 0;
}
else {
return maxLvl + 1;
}
});
xpawarddd = new XPAward();
if (config.allowXpOverflow) {
writeNoops(0x100B5608);
}
}
<|endoftext|>
|
<commit_before>#include "DatagramIterator.h"
#include "../bits/buffers.h"
#include "../values/Value.h"
#include "../module/ArrayType.h"
#include "../module/Struct.h"
#include "../module/Method.h"
#include "../module/Field.h"
#include "../module/Parameter.h"
using namespace std;
namespace bamboo { // close namespace bamboo
// read_value interprets the following data as a
// value for the DistributedType in native endianness.
Value DatagramIterator::read_value(const DistributedType *type) {
// Note: We can probably make this a lot more efficient by constructing the value manually
// from the wire-endian data instead of unpacking it into native endianess first.
// Though that would probably cause some code duplication with Value::from_packed.
vector<uint8_t> packed = read_packed(type);
return Value::from_packed(type, packed);
}
vector<uint8_t> DatagramIterator::read_packed(const DistributedType *type) {
#ifndef PLATFORM_BIG_ENDIAN
// We're little endian so we don't have to worry about byte-swapping the data
const uint8_t *start = m_dg->get_data() + m_offset;
skip_type(type); // note: this will advanced m_offset
return vector<uint8_t>(start, m_dg->get_data() + m_offset);
#else
// Lets go ahead and unpack that manually
vector<uint8_t> buf;
read_packed(type, buf);
return buf;
#endif
}
void DatagramIterator::read_packed(const DistributedType *dtype, vector<uint8_t>& buffer) {
#ifndef PLATFORM_BIG_ENDIAN
if(dtype->has_fixed_size()) {
// If we're a fixed-sized type like uint, int, float, etc
// Also any other type lucky enough to be fixed size will be faster.
vector<uint8_t> data = read_data(dtype->get_size());
pack_value(data, buffer);
}
#endif
// For the unlucky types/machines, we have to figure out their size manually
switch(dtype->get_subtype()) {
case kTypeChar:
pack_value(read_char(), buffer);
break;
case kTypeInt8:
pack_value(read_int8(), buffer);
break;
case kTypeInt16:
pack_value(read_int16(), buffer);
break;
case kTypeInt32:
pack_value(read_int32(), buffer);
break;
case kTypeInt64:
pack_value(read_int64(), buffer);
break;
case kTypeUint8:
pack_value(read_uint8(), buffer);
break;
case kTypeUint16:
pack_value(read_uint16(), buffer);
break;
case kTypeUint32:
pack_value(read_uint32(), buffer);
break;
case kTypeUint64:
pack_value(read_uint64(), buffer);
break;
case kTypeFloat32:
pack_value(read_float32(), buffer);
break;
case kTypeFloat64:
pack_value(read_float64(), buffer);
break;
case kTypeString:
case kTypeBlob:
pack_value(read_data(dtype->get_size()), buffer);
break;
case kTypeArray: {
const ArrayType *arr = dtype->as_array();
if(arr->get_element_type()->get_size() == 1) {
// If the element size is 1, we don't have to worry about endianness
pack_value(read_data(dtype->get_size()), buffer);
break;
}
// Read elements from the array till we reach the expected size
sizetag_t len = dtype->get_size();
sizetag_t array_end = m_offset + len;
while(m_offset < array_end) {
read_packed(arr->get_element_type(), buffer);
}
if(m_offset > array_end) {
stringstream error;
error << "Datagram iterator tried to read array data, but array data"
" exceeded the expected array length of " << len << ".\n";
throw DatagramIteratorEOF(error.str());
}
break;
}
case kTypeVarstring:
case kTypeVarblob: {
sizetag_t len = read_size();
pack_value(len, buffer);
pack_value(read_data(len), buffer);
break;
}
case kTypeVararray: {
sizetag_t len = read_size();
pack_value(len, buffer);
const ArrayType *arr = dtype->as_array();
if(arr->get_element_type()->get_size() == 1) {
// If the element size is 1, we don't have to worry about endianness
pack_value(read_data(len), buffer);
break;
}
// Read elements from the array till we reach the expected size
sizetag_t array_end = m_offset + len;
while(m_offset < array_end) {
read_packed(arr->get_element_type(), buffer);
}
if(m_offset > array_end) {
stringstream error;
error << "Datagram iterator tried to read array data, but array data"
" exceeded the expected array length of " << len << ".\n";
throw DatagramIteratorEOF(error.str());
}
break;
}
case kTypeStruct: {
const Struct *dstruct = dtype->as_struct();
size_t num_fields = dstruct->get_num_fields();
for(unsigned int i = 0; i < num_fields; ++i) {
read_packed(dstruct->get_field(i)->get_type(), buffer);
}
break;
}
case kTypeMethod: {
const Method *dmethod = dtype->as_method();
size_t num_params = dmethod->get_num_parameters();
for(unsigned int i = 0; i < num_params; ++i) {
read_packed(dmethod->get_parameter(i)->get_type(), buffer);
}
break;
}
case kTypeInvalid: {
break;
}
}
}
// skip_type can be used to seek past the packed data for a DistributedType.
// Throws DatagramIteratorEOF if it skips past the end of the datagram.
void DatagramIterator::skip_type(const DistributedType *dtype) {
if(dtype->has_fixed_size()) {
sizetag_t length = dtype->get_size();
check_read_length(length);
m_offset += length;
return;
}
switch(dtype->get_subtype()) {
case kTypeVarstring:
case kTypeVarblob:
case kTypeVararray: {
sizetag_t length = read_size();
check_read_length(length);
m_offset += length;
break;
}
case kTypeStruct: {
const Struct *dstruct = dtype->as_struct();
size_t num_fields = dstruct->get_num_fields();
for(unsigned int i = 0; i < num_fields; ++i) {
skip_type(dstruct->get_field(i)->get_type());
}
break;
}
case kTypeMethod: {
const Method *dmethod = dtype->as_method();
size_t num_params = dmethod->get_num_parameters();
for(unsigned int i = 0; i < num_params; ++i) {
skip_type(dmethod->get_parameter(i)->get_type());
}
break;
}
default: {
// This case should be impossible, but a default is required by compilers
break;
}
}
}
} // close namespace bamboo
<commit_msg>Bugfix: Add missing return in DatagramIterator::read_packed<commit_after>#include "DatagramIterator.h"
#include "../bits/buffers.h"
#include "../values/Value.h"
#include "../module/ArrayType.h"
#include "../module/Struct.h"
#include "../module/Method.h"
#include "../module/Field.h"
#include "../module/Parameter.h"
using namespace std;
namespace bamboo { // close namespace bamboo
// read_value interprets the following data as a
// value for the DistributedType in native endianness.
Value DatagramIterator::read_value(const DistributedType *type) {
// Note: We can probably make this a lot more efficient by constructing the value manually
// from the wire-endian data instead of unpacking it into native endianess first.
// Though that would probably cause some code duplication with Value::from_packed.
vector<uint8_t> packed = read_packed(type);
return Value::from_packed(type, packed);
}
vector<uint8_t> DatagramIterator::read_packed(const DistributedType *type) {
#ifndef PLATFORM_BIG_ENDIAN
// We're little endian so we don't have to worry about byte-swapping the data
const uint8_t *start = m_dg->get_data() + m_offset;
skip_type(type); // note: this will advanced m_offset
return vector<uint8_t>(start, m_dg->get_data() + m_offset);
#else
// Lets go ahead and unpack that manually
vector<uint8_t> buf;
read_packed(type, buf);
return buf;
#endif
}
void DatagramIterator::read_packed(const DistributedType *dtype, vector<uint8_t>& buffer) {
#ifndef PLATFORM_BIG_ENDIAN
if(dtype->has_fixed_size()) {
// If we're a fixed-sized type like uint, int, float, etc
// Also any other type lucky enough to be fixed size will be faster.
vector<uint8_t> data = read_data(dtype->get_size());
pack_value(data, buffer);
return;
}
#endif
// For the unlucky types/machines, we have to figure out their size manually
switch(dtype->get_subtype()) {
case kTypeChar:
pack_value(read_char(), buffer);
break;
case kTypeInt8:
pack_value(read_int8(), buffer);
break;
case kTypeInt16:
pack_value(read_int16(), buffer);
break;
case kTypeInt32:
pack_value(read_int32(), buffer);
break;
case kTypeInt64:
pack_value(read_int64(), buffer);
break;
case kTypeUint8:
pack_value(read_uint8(), buffer);
break;
case kTypeUint16:
pack_value(read_uint16(), buffer);
break;
case kTypeUint32:
pack_value(read_uint32(), buffer);
break;
case kTypeUint64:
pack_value(read_uint64(), buffer);
break;
case kTypeFloat32:
pack_value(read_float32(), buffer);
break;
case kTypeFloat64:
pack_value(read_float64(), buffer);
break;
case kTypeString:
case kTypeBlob:
pack_value(read_data(dtype->get_size()), buffer);
break;
case kTypeArray: {
const ArrayType *arr = dtype->as_array();
if(arr->get_element_type()->get_size() == 1) {
// If the element size is 1, we don't have to worry about endianness
pack_value(read_data(dtype->get_size()), buffer);
break;
}
// Read elements from the array till we reach the expected size
sizetag_t len = dtype->get_size();
sizetag_t array_end = m_offset + len;
while(m_offset < array_end) {
read_packed(arr->get_element_type(), buffer);
}
if(m_offset > array_end) {
stringstream error;
error << "Datagram iterator tried to read array data, but array data"
" exceeded the expected array length of " << len << ".\n";
throw DatagramIteratorEOF(error.str());
}
break;
}
case kTypeVarstring:
case kTypeVarblob: {
sizetag_t len = read_size();
pack_value(len, buffer);
pack_value(read_data(len), buffer);
break;
}
case kTypeVararray: {
sizetag_t len = read_size();
pack_value(len, buffer);
const ArrayType *arr = dtype->as_array();
if(arr->get_element_type()->get_size() == 1) {
// If the element size is 1, we don't have to worry about endianness
pack_value(read_data(len), buffer);
break;
}
// Read elements from the array till we reach the expected size
sizetag_t array_end = m_offset + len;
while(m_offset < array_end) {
read_packed(arr->get_element_type(), buffer);
}
if(m_offset > array_end) {
stringstream error;
error << "Datagram iterator tried to read array data, but array data"
" exceeded the expected array length of " << len << ".\n";
throw DatagramIteratorEOF(error.str());
}
break;
}
case kTypeStruct: {
const Struct *dstruct = dtype->as_struct();
size_t num_fields = dstruct->get_num_fields();
for(unsigned int i = 0; i < num_fields; ++i) {
read_packed(dstruct->get_field(i)->get_type(), buffer);
}
break;
}
case kTypeMethod: {
const Method *dmethod = dtype->as_method();
size_t num_params = dmethod->get_num_parameters();
for(unsigned int i = 0; i < num_params; ++i) {
read_packed(dmethod->get_parameter(i)->get_type(), buffer);
}
break;
}
case kTypeInvalid: {
break;
}
}
}
// skip_type can be used to seek past the packed data for a DistributedType.
// Throws DatagramIteratorEOF if it skips past the end of the datagram.
void DatagramIterator::skip_type(const DistributedType *dtype) {
if(dtype->has_fixed_size()) {
sizetag_t length = dtype->get_size();
check_read_length(length);
m_offset += length;
return;
}
switch(dtype->get_subtype()) {
case kTypeVarstring:
case kTypeVarblob:
case kTypeVararray: {
sizetag_t length = read_size();
check_read_length(length);
m_offset += length;
break;
}
case kTypeStruct: {
const Struct *dstruct = dtype->as_struct();
size_t num_fields = dstruct->get_num_fields();
for(unsigned int i = 0; i < num_fields; ++i) {
skip_type(dstruct->get_field(i)->get_type());
}
break;
}
case kTypeMethod: {
const Method *dmethod = dtype->as_method();
size_t num_params = dmethod->get_num_parameters();
for(unsigned int i = 0; i < num_params; ++i) {
skip_type(dmethod->get_parameter(i)->get_type());
}
break;
}
default: {
// This case should be impossible, but a default is required by compilers
break;
}
}
}
} // close namespace bamboo
<|endoftext|>
|
<commit_before>#include "xlink/XLinkConnection.hpp"
#include <array>
#include <cassert>
#include <chrono>
#include <cstring>
#include <fstream>
#include <iostream>
#include <thread>
#include <vector>
// project
#include "depthai/utility/Initialization.hpp"
// libraries
#include <XLink/XLink.h>
extern "C" {
#include <XLink/XLinkLog.h>
}
#include <spdlog/spdlog.h>
#include "spdlog/details/os.h"
#include "spdlog/fmt/chrono.h"
namespace dai {
// DeviceInfo
DeviceInfo::DeviceInfo(std::string mxId) {
// Add dash at the end of mxId ([mxId]-[xlinkDevName] format)
mxId += "-";
// Construct device info which will points to device with specific mxId
std::strncpy(desc.name, mxId.c_str(), sizeof(desc.name));
// set protocol to any
desc.protocol = X_LINK_ANY_PROTOCOL;
// set platform to any
desc.platform = X_LINK_ANY_PLATFORM;
// set state to any
state = X_LINK_ANY_STATE;
}
DeviceInfo::DeviceInfo(const char* mxId) : DeviceInfo(std::string(mxId)) {}
std::string DeviceInfo::getMxId() const {
std::string mxId = "";
auto len = std::strlen(desc.name);
for(std::size_t i = 0; i < len; i++) {
if(desc.name[i] == '-') break;
mxId += desc.name[i];
}
return mxId;
}
static DeviceInfo deviceInfoFix(const DeviceInfo& d, XLinkDeviceState_t state);
// STATIC
constexpr std::chrono::milliseconds XLinkConnection::WAIT_FOR_BOOTUP_TIMEOUT;
constexpr std::chrono::milliseconds XLinkConnection::WAIT_FOR_CONNECT_TIMEOUT;
std::vector<DeviceInfo> XLinkConnection::getAllConnectedDevices(XLinkDeviceState_t state) {
initialize();
std::vector<DeviceInfo> devices;
std::vector<XLinkDeviceState_t> states;
if(state == X_LINK_ANY_STATE) {
states = {X_LINK_UNBOOTED, X_LINK_BOOTLOADER, X_LINK_BOOTED, X_LINK_FLASH_BOOTED};
} else {
states = {state};
}
// Get all available devices (unbooted & booted)
for(const auto& state : states) {
unsigned int numdev = 0;
std::array<deviceDesc_t, 32> deviceDescAll = {};
deviceDesc_t suitableDevice = {};
suitableDevice.protocol = X_LINK_ANY_PROTOCOL;
suitableDevice.platform = X_LINK_ANY_PLATFORM;
auto status = XLinkFindAllSuitableDevices(state, suitableDevice, deviceDescAll.data(), static_cast<unsigned int>(deviceDescAll.size()), &numdev);
if(status != X_LINK_SUCCESS) throw std::runtime_error("Couldn't retrieve all connected devices");
for(unsigned i = 0; i < numdev; i++) {
DeviceInfo info = {};
info.desc = deviceDescAll.at(i);
info.state = state;
devices.push_back(info);
}
}
return devices;
}
std::tuple<bool, DeviceInfo> XLinkConnection::getFirstDevice(XLinkDeviceState_t state) {
auto devices = getAllConnectedDevices();
for(const auto& d : devices) {
if(d.state == state || state == X_LINK_ANY_STATE) return {true, d};
}
return {false, DeviceInfo()};
}
std::tuple<bool, DeviceInfo> XLinkConnection::getDeviceByMxId(std::string mxId, XLinkDeviceState_t state) {
auto devices = getAllConnectedDevices();
for(const auto& d : devices) {
if(d.state == state || state == X_LINK_ANY_STATE) {
if(d.getMxId() == mxId) {
return {true, d};
}
}
}
return {false, DeviceInfo()};
}
DeviceInfo XLinkConnection::bootBootloader(const DeviceInfo& deviceInfo) {
using namespace std::chrono;
// Device is in flash booted state. Boot to bootloader first
XLinkBootBootloader(&deviceInfo.desc);
// Fix deviceInfo for BOOTLOADER state
DeviceInfo deviceToWait = deviceInfoFix(deviceInfo, X_LINK_BOOTLOADER);
// Device desc if found
deviceDesc_t foundDeviceDesc = {};
// Wait for device to get to bootloader state
XLinkError_t rc;
auto tstart = steady_clock::now();
do {
rc = XLinkFindFirstSuitableDevice(X_LINK_BOOTLOADER, deviceToWait.desc, &foundDeviceDesc);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
if(rc == X_LINK_SUCCESS) break;
} while(steady_clock::now() - tstart < WAIT_FOR_BOOTUP_TIMEOUT);
// If device not found
if(rc != X_LINK_SUCCESS) {
throw std::runtime_error("Failed to find device (" + std::string(deviceToWait.desc.name) + "), error message: " + convertErrorCodeToString(rc));
}
deviceToWait.state = X_LINK_BOOTLOADER;
deviceToWait.desc = foundDeviceDesc;
return deviceToWait;
}
XLinkConnection::XLinkConnection(const DeviceInfo& deviceDesc, std::vector<std::uint8_t> mvcmdBinary, XLinkDeviceState_t expectedState) {
bootDevice = true;
bootWithPath = false;
this->mvcmd = std::move(mvcmdBinary);
initDevice(deviceDesc, expectedState);
}
XLinkConnection::XLinkConnection(const DeviceInfo& deviceDesc, std::string pathToMvcmd, XLinkDeviceState_t expectedState) {
if(!pathToMvcmd.empty()) {
std::ifstream f(pathToMvcmd.c_str());
if(!f.good()) throw std::runtime_error("Error path doesn't exist. Note: Environment variables in path are not expanded. (E.g. '~', '$PATH').");
}
bootDevice = true;
bootWithPath = true;
this->pathToMvcmd = std::move(pathToMvcmd);
initDevice(deviceDesc, expectedState);
}
// Skip boot
XLinkConnection::XLinkConnection(const DeviceInfo& deviceDesc, XLinkDeviceState_t expectedState) {
bootDevice = false;
initDevice(deviceDesc, expectedState);
}
bool XLinkConnection::isClosed() const {
return closed;
}
void XLinkConnection::checkClosed() const {
if(isClosed()) throw std::invalid_argument("XLinkConnection already closed or disconnected");
}
void XLinkConnection::close() {
if(closed.exchange(true)) return;
if(deviceLinkId != -1 && rebootOnDestruction) {
auto tmp = deviceLinkId;
XLinkResetRemote(deviceLinkId);
deviceLinkId = -1;
// TODO(themarpe) - revisit for TCPIP protocol
using namespace std::chrono;
const auto BOOTUP_SEARCH = std::chrono::seconds(5);
// Wait till same device reappears (is rebooted).
// Only in case if device was booted to begin with
if(bootDevice) {
auto t1 = steady_clock::now();
bool found = false;
do {
DeviceInfo tmp;
for(const auto& state : {X_LINK_UNBOOTED, X_LINK_BOOTLOADER}) {
std::tie(found, tmp) = XLinkConnection::getDeviceByMxId(deviceInfo.getMxId(), state);
if(found) break;
}
} while(!found && steady_clock::now() - t1 < BOOTUP_SEARCH);
}
spdlog::debug("XLinkResetRemote of linkId: ({})", tmp);
}
}
XLinkConnection::~XLinkConnection() {
close();
}
void XLinkConnection::setRebootOnDestruction(bool reboot) {
rebootOnDestruction = reboot;
}
bool XLinkConnection::getRebootOnDestruction() const {
return rebootOnDestruction;
}
bool XLinkConnection::bootAvailableDevice(const deviceDesc_t& deviceToBoot, const std::string& pathToMvcmd) {
auto status = XLinkBoot(&deviceToBoot, pathToMvcmd.c_str());
return status == X_LINK_SUCCESS;
}
bool XLinkConnection::bootAvailableDevice(const deviceDesc_t& deviceToBoot, std::vector<std::uint8_t>& mvcmd) {
auto status = XLinkBootMemory(&deviceToBoot, mvcmd.data(), static_cast<unsigned long>(mvcmd.size()));
return status == X_LINK_SUCCESS;
}
void XLinkConnection::initDevice(const DeviceInfo& deviceToInit, XLinkDeviceState_t expectedState) {
initialize();
assert(deviceLinkId == -1);
XLinkError_t rc = X_LINK_ERROR;
deviceDesc_t deviceDesc = {};
using namespace std::chrono;
// if device is in UNBOOTED then boot
bootDevice = deviceToInit.state == X_LINK_UNBOOTED;
std::chrono::milliseconds connectTimeout = WAIT_FOR_CONNECT_TIMEOUT;
std::chrono::milliseconds bootupTimeout = WAIT_FOR_BOOTUP_TIMEOUT;
// Override with environment variables, if set
const std::vector<std::pair<std::string, std::chrono::milliseconds*>> evars = {
{"DEPTHAI_CONNECT_TIMEOUT", &connectTimeout},
{"DEPTHAI_BOOTUP_TIMEOUT", &bootupTimeout},
};
for(auto ev : evars) {
auto name = ev.first;
auto valstr = spdlog::details::os::getenv(name.c_str());
if(!valstr.empty()) {
try {
std::chrono::milliseconds value{std::stoi(valstr)};
auto initial = *ev.second;
*ev.second = value;
spdlog::warn("{} override: {} -> {}", name, initial, value);
} catch(const std::invalid_argument& e) {
spdlog::warn("{} value invalid: {}", name, e.what());
}
}
}
// boot device
if(bootDevice) {
DeviceInfo deviceToBoot = deviceInfoFix(deviceToInit, X_LINK_UNBOOTED);
deviceDesc_t foundDeviceDesc = {};
// Wait for the device to be available
auto tstart = steady_clock::now();
do {
rc = XLinkFindFirstSuitableDevice(X_LINK_UNBOOTED, deviceToBoot.desc, &foundDeviceDesc);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
if(rc == X_LINK_SUCCESS) break;
} while(steady_clock::now() - tstart < bootupTimeout);
// If device not found
if(rc != X_LINK_SUCCESS) {
throw std::runtime_error("Failed to find device (" + std::string(deviceToBoot.desc.name) + "), error message: " + convertErrorCodeToString(rc));
}
bool bootStatus;
if(bootWithPath) {
bootStatus = bootAvailableDevice(foundDeviceDesc, pathToMvcmd);
} else {
bootStatus = bootAvailableDevice(foundDeviceDesc, mvcmd);
}
if(!bootStatus) {
throw std::runtime_error("Failed to boot device!");
}
}
// Search for booted device
{
// Create description of device to look for
DeviceInfo bootedDeviceInfo = deviceToInit;
if(deviceToInit.desc.protocol != X_LINK_TCP_IP) {
bootedDeviceInfo = deviceInfoFix(deviceToInit, expectedState);
}
// Find booted device
auto tstart = steady_clock::now();
do {
rc = XLinkFindFirstSuitableDevice(expectedState, bootedDeviceInfo.desc, &deviceDesc);
if(rc == X_LINK_SUCCESS) break;
} while(steady_clock::now() - tstart < bootupTimeout);
if(rc != X_LINK_SUCCESS) {
throw std::runtime_error("Failed to find device after booting, error message: " + convertErrorCodeToString(rc));
}
}
// Try to connect to device
{
XLinkHandler_t connectionHandler = {};
connectionHandler.devicePath = deviceDesc.name;
connectionHandler.protocol = deviceDesc.protocol;
auto tstart = steady_clock::now();
do {
if((rc = XLinkConnect(&connectionHandler)) == X_LINK_SUCCESS) break;
} while(steady_clock::now() - tstart < connectTimeout);
if(rc != X_LINK_SUCCESS) throw std::runtime_error("Failed to connect to device, error message: " + convertErrorCodeToString(rc));
deviceLinkId = connectionHandler.linkId;
deviceInfo.desc = deviceDesc;
deviceInfo.state = X_LINK_BOOTED;
}
}
int XLinkConnection::getLinkId() const {
return deviceLinkId;
}
std::string XLinkConnection::convertErrorCodeToString(XLinkError_t errorCode) {
switch(errorCode) {
case X_LINK_SUCCESS:
return "X_LINK_SUCCESS";
case X_LINK_ALREADY_OPEN:
return "X_LINK_ALREADY_OPEN";
case X_LINK_COMMUNICATION_NOT_OPEN:
return "X_LINK_COMMUNICATION_NOT_OPEN";
case X_LINK_COMMUNICATION_FAIL:
return "X_LINK_COMMUNICATION_FAIL";
case X_LINK_COMMUNICATION_UNKNOWN_ERROR:
return "X_LINK_COMMUNICATION_UNKNOWN_ERROR";
case X_LINK_DEVICE_NOT_FOUND:
return "X_LINK_DEVICE_NOT_FOUND";
case X_LINK_TIMEOUT:
return "X_LINK_TIMEOUT";
case X_LINK_ERROR:
return "X_LINK_ERROR";
case X_LINK_OUT_OF_MEMORY:
return "X_LINK_OUT_OF_MEMORY";
case X_LINK_NOT_IMPLEMENTED:
return "X_LINK_NOT_IMPLEMENTED";
default:
return "<UNKNOWN ERROR>";
}
}
DeviceInfo deviceInfoFix(const DeviceInfo& dev, XLinkDeviceState_t state) {
if(dev.desc.protocol == X_LINK_TCP_IP) {
// X_LINK_TCP_IP doesn't need a fix
return dev;
}
DeviceInfo fixed(dev);
// Remove everything after dash
for(int i = sizeof(fixed.desc.name) - 1; i >= 0; i--) {
if(fixed.desc.name[i] != '-')
fixed.desc.name[i] = 0;
else
break;
}
// If bootloader state add "bootloader"
if(state == X_LINK_BOOTLOADER) {
std::strncat(fixed.desc.name, "bootloader", sizeof(fixed.desc.name) - std::strlen(fixed.desc.name));
// set platform to any
fixed.desc.platform = X_LINK_ANY_PLATFORM;
} else if(state == X_LINK_UNBOOTED) {
// if unbooted add ending ("ma2480" or "ma2450")
if(fixed.desc.platform == X_LINK_MYRIAD_2) {
std::strncat(fixed.desc.name, "ma2450", sizeof(fixed.desc.name) - std::strlen(fixed.desc.name));
} else {
std::strncat(fixed.desc.name, "ma2480", sizeof(fixed.desc.name) - std::strlen(fixed.desc.name));
}
} else if(state == X_LINK_BOOTED) {
// set platform to any
fixed.desc.platform = X_LINK_ANY_PLATFORM;
}
return fixed;
}
} // namespace dai
<commit_msg>Fix strncpy build warning: specified bound 48 equals destination size [-Wstringop-truncation]<commit_after>#include "xlink/XLinkConnection.hpp"
#include <array>
#include <cassert>
#include <chrono>
#include <cstring>
#include <fstream>
#include <iostream>
#include <thread>
#include <vector>
// project
#include "depthai/utility/Initialization.hpp"
// libraries
#include <XLink/XLink.h>
extern "C" {
#include <XLink/XLinkLog.h>
}
#include <spdlog/spdlog.h>
#include "spdlog/details/os.h"
#include "spdlog/fmt/chrono.h"
namespace dai {
// DeviceInfo
DeviceInfo::DeviceInfo(std::string mxId) {
// Add dash at the end of mxId ([mxId]-[xlinkDevName] format)
mxId += "-";
// Construct device info which will points to device with specific mxId
std::strncpy(desc.name, mxId.c_str(), sizeof(desc.name) - 1);
// set protocol to any
desc.protocol = X_LINK_ANY_PROTOCOL;
// set platform to any
desc.platform = X_LINK_ANY_PLATFORM;
// set state to any
state = X_LINK_ANY_STATE;
}
DeviceInfo::DeviceInfo(const char* mxId) : DeviceInfo(std::string(mxId)) {}
std::string DeviceInfo::getMxId() const {
std::string mxId = "";
auto len = std::strlen(desc.name);
for(std::size_t i = 0; i < len; i++) {
if(desc.name[i] == '-') break;
mxId += desc.name[i];
}
return mxId;
}
static DeviceInfo deviceInfoFix(const DeviceInfo& d, XLinkDeviceState_t state);
// STATIC
constexpr std::chrono::milliseconds XLinkConnection::WAIT_FOR_BOOTUP_TIMEOUT;
constexpr std::chrono::milliseconds XLinkConnection::WAIT_FOR_CONNECT_TIMEOUT;
std::vector<DeviceInfo> XLinkConnection::getAllConnectedDevices(XLinkDeviceState_t state) {
initialize();
std::vector<DeviceInfo> devices;
std::vector<XLinkDeviceState_t> states;
if(state == X_LINK_ANY_STATE) {
states = {X_LINK_UNBOOTED, X_LINK_BOOTLOADER, X_LINK_BOOTED, X_LINK_FLASH_BOOTED};
} else {
states = {state};
}
// Get all available devices (unbooted & booted)
for(const auto& state : states) {
unsigned int numdev = 0;
std::array<deviceDesc_t, 32> deviceDescAll = {};
deviceDesc_t suitableDevice = {};
suitableDevice.protocol = X_LINK_ANY_PROTOCOL;
suitableDevice.platform = X_LINK_ANY_PLATFORM;
auto status = XLinkFindAllSuitableDevices(state, suitableDevice, deviceDescAll.data(), static_cast<unsigned int>(deviceDescAll.size()), &numdev);
if(status != X_LINK_SUCCESS) throw std::runtime_error("Couldn't retrieve all connected devices");
for(unsigned i = 0; i < numdev; i++) {
DeviceInfo info = {};
info.desc = deviceDescAll.at(i);
info.state = state;
devices.push_back(info);
}
}
return devices;
}
std::tuple<bool, DeviceInfo> XLinkConnection::getFirstDevice(XLinkDeviceState_t state) {
auto devices = getAllConnectedDevices();
for(const auto& d : devices) {
if(d.state == state || state == X_LINK_ANY_STATE) return {true, d};
}
return {false, DeviceInfo()};
}
std::tuple<bool, DeviceInfo> XLinkConnection::getDeviceByMxId(std::string mxId, XLinkDeviceState_t state) {
auto devices = getAllConnectedDevices();
for(const auto& d : devices) {
if(d.state == state || state == X_LINK_ANY_STATE) {
if(d.getMxId() == mxId) {
return {true, d};
}
}
}
return {false, DeviceInfo()};
}
DeviceInfo XLinkConnection::bootBootloader(const DeviceInfo& deviceInfo) {
using namespace std::chrono;
// Device is in flash booted state. Boot to bootloader first
XLinkBootBootloader(&deviceInfo.desc);
// Fix deviceInfo for BOOTLOADER state
DeviceInfo deviceToWait = deviceInfoFix(deviceInfo, X_LINK_BOOTLOADER);
// Device desc if found
deviceDesc_t foundDeviceDesc = {};
// Wait for device to get to bootloader state
XLinkError_t rc;
auto tstart = steady_clock::now();
do {
rc = XLinkFindFirstSuitableDevice(X_LINK_BOOTLOADER, deviceToWait.desc, &foundDeviceDesc);
std::this_thread::sleep_for(std::chrono::milliseconds(100));
if(rc == X_LINK_SUCCESS) break;
} while(steady_clock::now() - tstart < WAIT_FOR_BOOTUP_TIMEOUT);
// If device not found
if(rc != X_LINK_SUCCESS) {
throw std::runtime_error("Failed to find device (" + std::string(deviceToWait.desc.name) + "), error message: " + convertErrorCodeToString(rc));
}
deviceToWait.state = X_LINK_BOOTLOADER;
deviceToWait.desc = foundDeviceDesc;
return deviceToWait;
}
XLinkConnection::XLinkConnection(const DeviceInfo& deviceDesc, std::vector<std::uint8_t> mvcmdBinary, XLinkDeviceState_t expectedState) {
bootDevice = true;
bootWithPath = false;
this->mvcmd = std::move(mvcmdBinary);
initDevice(deviceDesc, expectedState);
}
XLinkConnection::XLinkConnection(const DeviceInfo& deviceDesc, std::string pathToMvcmd, XLinkDeviceState_t expectedState) {
if(!pathToMvcmd.empty()) {
std::ifstream f(pathToMvcmd.c_str());
if(!f.good()) throw std::runtime_error("Error path doesn't exist. Note: Environment variables in path are not expanded. (E.g. '~', '$PATH').");
}
bootDevice = true;
bootWithPath = true;
this->pathToMvcmd = std::move(pathToMvcmd);
initDevice(deviceDesc, expectedState);
}
// Skip boot
XLinkConnection::XLinkConnection(const DeviceInfo& deviceDesc, XLinkDeviceState_t expectedState) {
bootDevice = false;
initDevice(deviceDesc, expectedState);
}
bool XLinkConnection::isClosed() const {
return closed;
}
void XLinkConnection::checkClosed() const {
if(isClosed()) throw std::invalid_argument("XLinkConnection already closed or disconnected");
}
void XLinkConnection::close() {
if(closed.exchange(true)) return;
if(deviceLinkId != -1 && rebootOnDestruction) {
auto tmp = deviceLinkId;
XLinkResetRemote(deviceLinkId);
deviceLinkId = -1;
// TODO(themarpe) - revisit for TCPIP protocol
using namespace std::chrono;
const auto BOOTUP_SEARCH = std::chrono::seconds(5);
// Wait till same device reappears (is rebooted).
// Only in case if device was booted to begin with
if(bootDevice) {
auto t1 = steady_clock::now();
bool found = false;
do {
DeviceInfo tmp;
for(const auto& state : {X_LINK_UNBOOTED, X_LINK_BOOTLOADER}) {
std::tie(found, tmp) = XLinkConnection::getDeviceByMxId(deviceInfo.getMxId(), state);
if(found) break;
}
} while(!found && steady_clock::now() - t1 < BOOTUP_SEARCH);
}
spdlog::debug("XLinkResetRemote of linkId: ({})", tmp);
}
}
XLinkConnection::~XLinkConnection() {
close();
}
void XLinkConnection::setRebootOnDestruction(bool reboot) {
rebootOnDestruction = reboot;
}
bool XLinkConnection::getRebootOnDestruction() const {
return rebootOnDestruction;
}
bool XLinkConnection::bootAvailableDevice(const deviceDesc_t& deviceToBoot, const std::string& pathToMvcmd) {
auto status = XLinkBoot(&deviceToBoot, pathToMvcmd.c_str());
return status == X_LINK_SUCCESS;
}
bool XLinkConnection::bootAvailableDevice(const deviceDesc_t& deviceToBoot, std::vector<std::uint8_t>& mvcmd) {
auto status = XLinkBootMemory(&deviceToBoot, mvcmd.data(), static_cast<unsigned long>(mvcmd.size()));
return status == X_LINK_SUCCESS;
}
void XLinkConnection::initDevice(const DeviceInfo& deviceToInit, XLinkDeviceState_t expectedState) {
initialize();
assert(deviceLinkId == -1);
XLinkError_t rc = X_LINK_ERROR;
deviceDesc_t deviceDesc = {};
using namespace std::chrono;
// if device is in UNBOOTED then boot
bootDevice = deviceToInit.state == X_LINK_UNBOOTED;
std::chrono::milliseconds connectTimeout = WAIT_FOR_CONNECT_TIMEOUT;
std::chrono::milliseconds bootupTimeout = WAIT_FOR_BOOTUP_TIMEOUT;
// Override with environment variables, if set
const std::vector<std::pair<std::string, std::chrono::milliseconds*>> evars = {
{"DEPTHAI_CONNECT_TIMEOUT", &connectTimeout},
{"DEPTHAI_BOOTUP_TIMEOUT", &bootupTimeout},
};
for(auto ev : evars) {
auto name = ev.first;
auto valstr = spdlog::details::os::getenv(name.c_str());
if(!valstr.empty()) {
try {
std::chrono::milliseconds value{std::stoi(valstr)};
auto initial = *ev.second;
*ev.second = value;
spdlog::warn("{} override: {} -> {}", name, initial, value);
} catch(const std::invalid_argument& e) {
spdlog::warn("{} value invalid: {}", name, e.what());
}
}
}
// boot device
if(bootDevice) {
DeviceInfo deviceToBoot = deviceInfoFix(deviceToInit, X_LINK_UNBOOTED);
deviceDesc_t foundDeviceDesc = {};
// Wait for the device to be available
auto tstart = steady_clock::now();
do {
rc = XLinkFindFirstSuitableDevice(X_LINK_UNBOOTED, deviceToBoot.desc, &foundDeviceDesc);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
if(rc == X_LINK_SUCCESS) break;
} while(steady_clock::now() - tstart < bootupTimeout);
// If device not found
if(rc != X_LINK_SUCCESS) {
throw std::runtime_error("Failed to find device (" + std::string(deviceToBoot.desc.name) + "), error message: " + convertErrorCodeToString(rc));
}
bool bootStatus;
if(bootWithPath) {
bootStatus = bootAvailableDevice(foundDeviceDesc, pathToMvcmd);
} else {
bootStatus = bootAvailableDevice(foundDeviceDesc, mvcmd);
}
if(!bootStatus) {
throw std::runtime_error("Failed to boot device!");
}
}
// Search for booted device
{
// Create description of device to look for
DeviceInfo bootedDeviceInfo = deviceToInit;
if(deviceToInit.desc.protocol != X_LINK_TCP_IP) {
bootedDeviceInfo = deviceInfoFix(deviceToInit, expectedState);
}
// Find booted device
auto tstart = steady_clock::now();
do {
rc = XLinkFindFirstSuitableDevice(expectedState, bootedDeviceInfo.desc, &deviceDesc);
if(rc == X_LINK_SUCCESS) break;
} while(steady_clock::now() - tstart < bootupTimeout);
if(rc != X_LINK_SUCCESS) {
throw std::runtime_error("Failed to find device after booting, error message: " + convertErrorCodeToString(rc));
}
}
// Try to connect to device
{
XLinkHandler_t connectionHandler = {};
connectionHandler.devicePath = deviceDesc.name;
connectionHandler.protocol = deviceDesc.protocol;
auto tstart = steady_clock::now();
do {
if((rc = XLinkConnect(&connectionHandler)) == X_LINK_SUCCESS) break;
} while(steady_clock::now() - tstart < connectTimeout);
if(rc != X_LINK_SUCCESS) throw std::runtime_error("Failed to connect to device, error message: " + convertErrorCodeToString(rc));
deviceLinkId = connectionHandler.linkId;
deviceInfo.desc = deviceDesc;
deviceInfo.state = X_LINK_BOOTED;
}
}
int XLinkConnection::getLinkId() const {
return deviceLinkId;
}
std::string XLinkConnection::convertErrorCodeToString(XLinkError_t errorCode) {
switch(errorCode) {
case X_LINK_SUCCESS:
return "X_LINK_SUCCESS";
case X_LINK_ALREADY_OPEN:
return "X_LINK_ALREADY_OPEN";
case X_LINK_COMMUNICATION_NOT_OPEN:
return "X_LINK_COMMUNICATION_NOT_OPEN";
case X_LINK_COMMUNICATION_FAIL:
return "X_LINK_COMMUNICATION_FAIL";
case X_LINK_COMMUNICATION_UNKNOWN_ERROR:
return "X_LINK_COMMUNICATION_UNKNOWN_ERROR";
case X_LINK_DEVICE_NOT_FOUND:
return "X_LINK_DEVICE_NOT_FOUND";
case X_LINK_TIMEOUT:
return "X_LINK_TIMEOUT";
case X_LINK_ERROR:
return "X_LINK_ERROR";
case X_LINK_OUT_OF_MEMORY:
return "X_LINK_OUT_OF_MEMORY";
case X_LINK_NOT_IMPLEMENTED:
return "X_LINK_NOT_IMPLEMENTED";
default:
return "<UNKNOWN ERROR>";
}
}
DeviceInfo deviceInfoFix(const DeviceInfo& dev, XLinkDeviceState_t state) {
if(dev.desc.protocol == X_LINK_TCP_IP) {
// X_LINK_TCP_IP doesn't need a fix
return dev;
}
DeviceInfo fixed(dev);
// Remove everything after dash
for(int i = sizeof(fixed.desc.name) - 1; i >= 0; i--) {
if(fixed.desc.name[i] != '-')
fixed.desc.name[i] = 0;
else
break;
}
// If bootloader state add "bootloader"
if(state == X_LINK_BOOTLOADER) {
std::strncat(fixed.desc.name, "bootloader", sizeof(fixed.desc.name) - std::strlen(fixed.desc.name));
// set platform to any
fixed.desc.platform = X_LINK_ANY_PLATFORM;
} else if(state == X_LINK_UNBOOTED) {
// if unbooted add ending ("ma2480" or "ma2450")
if(fixed.desc.platform == X_LINK_MYRIAD_2) {
std::strncat(fixed.desc.name, "ma2450", sizeof(fixed.desc.name) - std::strlen(fixed.desc.name));
} else {
std::strncat(fixed.desc.name, "ma2480", sizeof(fixed.desc.name) - std::strlen(fixed.desc.name));
}
} else if(state == X_LINK_BOOTED) {
// set platform to any
fixed.desc.platform = X_LINK_ANY_PLATFORM;
}
return fixed;
}
} // namespace dai
<|endoftext|>
|
<commit_before>//===--- Stubs.cpp - Swift Language ABI Runtime Stubs ---------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Misc stubs for functions which should be defined in the core standard
// library, but are difficult or impossible to write in Swift at the
// moment.
//
//===----------------------------------------------------------------------===//
#if defined(__FreeBSD__)
#define _WITH_GETLINE
#endif
#include <sys/resource.h>
#include <sys/errno.h>
#include <unistd.h>
#include <climits>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <xlocale.h>
#include <limits>
#include "llvm/ADT/StringExtras.h"
#include "swift/Runtime/Debug.h"
#include "swift/Basic/Lazy.h"
static uint64_t uint64ToStringImpl(char *Buffer, uint64_t Value,
int64_t Radix, bool Uppercase,
bool Negative) {
char *P = Buffer;
uint64_t Y = Value;
if (Y == 0) {
*P++ = '0';
} else if (Radix == 10) {
while (Y) {
*P++ = '0' + char(Y % 10);
Y /= 10;
}
} else {
unsigned Radix32 = Radix;
while (Y) {
*P++ = llvm::hexdigit(Y % Radix32, !Uppercase);
Y /= Radix32;
}
}
if (Negative)
*P++ = '-';
std::reverse(Buffer, P);
return size_t(P - Buffer);
}
extern "C" uint64_t swift_int64ToString(char *Buffer, size_t BufferLength,
int64_t Value, int64_t Radix,
bool Uppercase) {
if ((Radix >= 10 && BufferLength < 32) || (Radix < 10 && BufferLength < 65))
swift::crash("swift_int64ToString: insufficient buffer size");
if (Radix == 0 || Radix > 36)
swift::crash("swift_int64ToString: invalid radix for string conversion");
bool Negative = Value < 0;
// Compute an absolute value safely, without using unary negation on INT_MIN,
// which is undefined behavior.
uint64_t UnsignedValue = Value;
if (Negative) {
// Assumes two's complement representation.
UnsignedValue = ~UnsignedValue + 1;
}
return uint64ToStringImpl(Buffer, UnsignedValue, Radix, Uppercase,
Negative);
}
extern "C" uint64_t swift_uint64ToString(char *Buffer, intptr_t BufferLength,
uint64_t Value, int64_t Radix,
bool Uppercase) {
if ((Radix >= 10 && BufferLength < 32) || (Radix < 10 && BufferLength < 64))
swift::crash("swift_int64ToString: insufficient buffer size");
if (Radix == 0 || Radix > 36)
swift::crash("swift_int64ToString: invalid radix for string conversion");
return uint64ToStringImpl(Buffer, Value, Radix, Uppercase,
/*Negative=*/false);
}
#if defined(__APPLE__) || defined(__FreeBSD__)
static inline locale_t getCLocale() {
// On these platforms convenience functions from xlocale.h interpret nullptr
// as C locale.
return nullptr;
}
#else
static locale_t makeCLocale() {
locale_t CLocale = newlocale(LC_ALL_MASK, "C", nullptr);
if (!CLocale) {
swift::crash("makeCLocale: newlocale() returned a null pointer");
}
return CLocale;
}
static locale_t getCLocale() {
return SWIFT_LAZY_CONSTANT(makeCLocale());
}
#endif
#if defined(__APPLE__)
#define swift_snprintf_l snprintf_l
#else
static int swift_snprintf_l(char *Str, size_t StrSize, locale_t Locale,
const char *Format, ...) {
if (Locale == nullptr) {
Locale = getCLocale();
}
locale_t OldLocale = uselocale(Locale);
va_list Args;
va_start(Args, Format);
int Result = std::vsnprintf(Str, StrSize, Format, Args);
va_end(Args);
uselocale(OldLocale);
return Result;
}
#endif
template <typename T>
static uint64_t swift_floatingPointToString(char *Buffer, size_t BufferLength,
T Value, const char *Format) {
if (BufferLength < 32)
swift::crash("swift_floatingPointToString: insufficient buffer size");
const int Precision = std::numeric_limits<T>::digits10;
// Pass a null locale to use the C locale.
int i = swift_snprintf_l(Buffer, BufferLength, /*locale=*/nullptr, Format,
Precision, Value);
if (i < 0)
swift::crash(
"swift_floatingPointToString: unexpected return value from sprintf");
if (size_t(i) >= BufferLength)
swift::crash("swift_floatingPointToString: insufficient buffer size");
// Add ".0" to a float that (a) is not in scientific notation, (b) does not
// already have a fractional part, (c) is not infinite, and (d) is not a NaN
// value.
if (strchr(Buffer, 'e') == nullptr && strchr(Buffer, '.') == nullptr &&
strchr(Buffer, 'n') == nullptr) {
Buffer[i++] = '.';
Buffer[i++] = '0';
}
return i;
}
extern "C" uint64_t swift_float32ToString(char *Buffer, size_t BufferLength,
float Value) {
return swift_floatingPointToString<float>(Buffer, BufferLength, Value,
"%0.*g");
}
extern "C" uint64_t swift_float64ToString(char *Buffer, size_t BufferLength,
double Value) {
return swift_floatingPointToString<double>(Buffer, BufferLength, Value,
"%0.*g");
}
extern "C" uint64_t swift_float80ToString(char *Buffer, size_t BufferLength,
long double Value) {
return swift_floatingPointToString<long double>(Buffer, BufferLength, Value,
"%0.*Lg");
}
/// \param[out] LinePtr Replaced with the pointer to the malloc()-allocated
/// line. Can be NULL if no characters were read.
///
/// \returns Size of character data returned in \c LinePtr, or -1
/// if an error occurred, or EOF was reached.
extern "C" ssize_t swift_stdlib_readLine_stdin(char **LinePtr) {
size_t Capacity = 0;
return getline(LinePtr, &Capacity, stdin);
}
extern "C" float _swift_fmodf(float lhs, float rhs) {
return fmodf(lhs, rhs);
}
extern "C" double _swift_fmod(double lhs, double rhs) {
return fmod(lhs, rhs);
}
extern "C" long double _swift_fmodl(long double lhs, long double rhs) {
return fmodl(lhs, rhs);
}
// Although this builtin is provided by clang rt builtins,
// it isn't provided by libgcc, which is the default
// runtime library on Linux, even when compiling with clang.
// This implementation is copied here to avoid a new dependency
// on compiler-rt on Linux.
// FIXME: rdar://14883575 Libcompiler_rt omits muloti4
#if (defined(__APPLE__) && defined(__arm64__)) || \
(defined(__linux__) && defined(__x86_64__))
typedef int ti_int __attribute__ ((mode (TI)));
extern "C"
ti_int
__muloti4(ti_int a, ti_int b, int* overflow)
{
const int N = (int)(sizeof(ti_int) * CHAR_BIT);
const ti_int MIN = (ti_int)1 << (N-1);
const ti_int MAX = ~MIN;
*overflow = 0;
ti_int result = a * b;
if (a == MIN)
{
if (b != 0 && b != 1)
*overflow = 1;
return result;
}
if (b == MIN)
{
if (a != 0 && a != 1)
*overflow = 1;
return result;
}
ti_int sa = a >> (N - 1);
ti_int abs_a = (a ^ sa) - sa;
ti_int sb = b >> (N - 1);
ti_int abs_b = (b ^ sb) - sb;
if (abs_a < 2 || abs_b < 2)
return result;
if (sa == sb)
{
if (abs_a > MAX / abs_b)
*overflow = 1;
}
else
{
if (abs_a > MIN / -abs_b)
*overflow = 1;
}
return result;
}
#endif
#if defined(__linux__) && defined(__arm__)
// Similar to above, but with mulodi4. Perhaps this is
// something that shouldn't be done, and is a bandaid over
// some other lower-level architecture issue that I'm
// missing. Perhaps relevant bug report:
// FIXME: https://llvm.org/bugs/show_bug.cgi?id=14469
typedef int di_int __attribute__ ((mode (DI)));
extern "C"
di_int
__mulodi4(di_int a, di_int b, int* overflow)
{
const int N = (int)(sizeof(di_int) * CHAR_BIT);
const di_int MIN = (di_int)1 << (N-1);
const di_int MAX = ~MIN;
*overflow = 0;
di_int result = a * b;
if (a == MIN)
{
if (b != 0 && b != 1)
*overflow = 1;
return result;
}
if (b == MIN)
{
if (a != 0 && a != 1)
*overflow = 1;
return result;
}
di_int sa = a >> (N - 1);
di_int abs_a = (a ^ sa) - sa;
di_int sb = b >> (N - 1);
di_int abs_b = (b ^ sb) - sb;
if (abs_a < 2 || abs_b < 2)
return result;
if (sa == sb)
{
if (abs_a > MAX / abs_b)
*overflow = 1;
}
else
{
if (abs_a > MIN / -abs_b)
*overflow = 1;
}
return result;
}
#endif
// We can't return Float80, but we can receive a pointer to one, so
// switch the return type and the out parameter on strtold.
template <typename T>
static const char *_swift_stdlib_strtoX_clocale_impl(
const char * nptr, T* outResult, T huge,
T (*posixImpl)(const char *, char **, locale_t)
) {
char *EndPtr;
errno = 0;
const auto result = posixImpl(nptr, &EndPtr, getCLocale());
*outResult = result;
if (result == huge || result == -huge || result == 0.0 || result == -0.0) {
if (errno == ERANGE)
EndPtr = NULL;
}
return EndPtr;
}
extern "C" const char *_swift_stdlib_strtold_clocale(
const char * nptr, void *outResult) {
return _swift_stdlib_strtoX_clocale_impl(
nptr, static_cast<long double*>(outResult), HUGE_VALL, strtold_l);
}
extern "C" const char *_swift_stdlib_strtod_clocale(
const char * nptr, double *outResult) {
return _swift_stdlib_strtoX_clocale_impl(
nptr, outResult, HUGE_VAL, strtod_l);
}
extern "C" const char *_swift_stdlib_strtof_clocale(
const char * nptr, float *outResult) {
return _swift_stdlib_strtoX_clocale_impl(
nptr, outResult, HUGE_VALF, strtof_l);
}
extern "C" void _swift_stdlib_flockfile_stdout() {
flockfile(stdout);
}
extern "C" void _swift_stdlib_funlockfile_stdout() {
funlockfile(stdout);
}
extern "C" int _swift_stdlib_putc_stderr(int C) {
return putc(C, stderr);
}
extern "C" size_t _swift_stdlib_getHardwareConcurrency() {
return sysconf(_SC_NPROCESSORS_ONLN);
}
<commit_msg>Fix precision of float to string to max significant decimals<commit_after>//===--- Stubs.cpp - Swift Language ABI Runtime Stubs ---------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Misc stubs for functions which should be defined in the core standard
// library, but are difficult or impossible to write in Swift at the
// moment.
//
//===----------------------------------------------------------------------===//
#if defined(__FreeBSD__)
#define _WITH_GETLINE
#endif
#include <sys/resource.h>
#include <sys/errno.h>
#include <unistd.h>
#include <climits>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <xlocale.h>
#include <limits>
#include "llvm/ADT/StringExtras.h"
#include "swift/Runtime/Debug.h"
#include "swift/Basic/Lazy.h"
static uint64_t uint64ToStringImpl(char *Buffer, uint64_t Value,
int64_t Radix, bool Uppercase,
bool Negative) {
char *P = Buffer;
uint64_t Y = Value;
if (Y == 0) {
*P++ = '0';
} else if (Radix == 10) {
while (Y) {
*P++ = '0' + char(Y % 10);
Y /= 10;
}
} else {
unsigned Radix32 = Radix;
while (Y) {
*P++ = llvm::hexdigit(Y % Radix32, !Uppercase);
Y /= Radix32;
}
}
if (Negative)
*P++ = '-';
std::reverse(Buffer, P);
return size_t(P - Buffer);
}
extern "C" uint64_t swift_int64ToString(char *Buffer, size_t BufferLength,
int64_t Value, int64_t Radix,
bool Uppercase) {
if ((Radix >= 10 && BufferLength < 32) || (Radix < 10 && BufferLength < 65))
swift::crash("swift_int64ToString: insufficient buffer size");
if (Radix == 0 || Radix > 36)
swift::crash("swift_int64ToString: invalid radix for string conversion");
bool Negative = Value < 0;
// Compute an absolute value safely, without using unary negation on INT_MIN,
// which is undefined behavior.
uint64_t UnsignedValue = Value;
if (Negative) {
// Assumes two's complement representation.
UnsignedValue = ~UnsignedValue + 1;
}
return uint64ToStringImpl(Buffer, UnsignedValue, Radix, Uppercase,
Negative);
}
extern "C" uint64_t swift_uint64ToString(char *Buffer, intptr_t BufferLength,
uint64_t Value, int64_t Radix,
bool Uppercase) {
if ((Radix >= 10 && BufferLength < 32) || (Radix < 10 && BufferLength < 64))
swift::crash("swift_int64ToString: insufficient buffer size");
if (Radix == 0 || Radix > 36)
swift::crash("swift_int64ToString: invalid radix for string conversion");
return uint64ToStringImpl(Buffer, Value, Radix, Uppercase,
/*Negative=*/false);
}
#if defined(__APPLE__) || defined(__FreeBSD__)
static inline locale_t getCLocale() {
// On these platforms convenience functions from xlocale.h interpret nullptr
// as C locale.
return nullptr;
}
#else
static locale_t makeCLocale() {
locale_t CLocale = newlocale(LC_ALL_MASK, "C", nullptr);
if (!CLocale) {
swift::crash("makeCLocale: newlocale() returned a null pointer");
}
return CLocale;
}
static locale_t getCLocale() {
return SWIFT_LAZY_CONSTANT(makeCLocale());
}
#endif
#if defined(__APPLE__)
#define swift_snprintf_l snprintf_l
#else
static int swift_snprintf_l(char *Str, size_t StrSize, locale_t Locale,
const char *Format, ...) {
if (Locale == nullptr) {
Locale = getCLocale();
}
locale_t OldLocale = uselocale(Locale);
va_list Args;
va_start(Args, Format);
int Result = std::vsnprintf(Str, StrSize, Format, Args);
va_end(Args);
uselocale(OldLocale);
return Result;
}
#endif
template <typename T>
static uint64_t swift_floatingPointToString(char *Buffer, size_t BufferLength,
T Value, const char *Format) {
if (BufferLength < 32)
swift::crash("swift_floatingPointToString: insufficient buffer size");
const int Precision = std::numeric_limits<T>::max_digits10;
// Pass a null locale to use the C locale.
int i = swift_snprintf_l(Buffer, BufferLength, /*locale=*/nullptr, Format,
Precision, Value);
if (i < 0)
swift::crash(
"swift_floatingPointToString: unexpected return value from sprintf");
if (size_t(i) >= BufferLength)
swift::crash("swift_floatingPointToString: insufficient buffer size");
// Add ".0" to a float that (a) is not in scientific notation, (b) does not
// already have a fractional part, (c) is not infinite, and (d) is not a NaN
// value.
if (strchr(Buffer, 'e') == nullptr && strchr(Buffer, '.') == nullptr &&
strchr(Buffer, 'n') == nullptr) {
Buffer[i++] = '.';
Buffer[i++] = '0';
}
return i;
}
extern "C" uint64_t swift_float32ToString(char *Buffer, size_t BufferLength,
float Value) {
return swift_floatingPointToString<float>(Buffer, BufferLength, Value,
"%0.*g");
}
extern "C" uint64_t swift_float64ToString(char *Buffer, size_t BufferLength,
double Value) {
return swift_floatingPointToString<double>(Buffer, BufferLength, Value,
"%0.*g");
}
extern "C" uint64_t swift_float80ToString(char *Buffer, size_t BufferLength,
long double Value) {
return swift_floatingPointToString<long double>(Buffer, BufferLength, Value,
"%0.*Lg");
}
/// \param[out] LinePtr Replaced with the pointer to the malloc()-allocated
/// line. Can be NULL if no characters were read.
///
/// \returns Size of character data returned in \c LinePtr, or -1
/// if an error occurred, or EOF was reached.
extern "C" ssize_t swift_stdlib_readLine_stdin(char **LinePtr) {
size_t Capacity = 0;
return getline(LinePtr, &Capacity, stdin);
}
extern "C" float _swift_fmodf(float lhs, float rhs) {
return fmodf(lhs, rhs);
}
extern "C" double _swift_fmod(double lhs, double rhs) {
return fmod(lhs, rhs);
}
extern "C" long double _swift_fmodl(long double lhs, long double rhs) {
return fmodl(lhs, rhs);
}
// Although this builtin is provided by clang rt builtins,
// it isn't provided by libgcc, which is the default
// runtime library on Linux, even when compiling with clang.
// This implementation is copied here to avoid a new dependency
// on compiler-rt on Linux.
// FIXME: rdar://14883575 Libcompiler_rt omits muloti4
#if (defined(__APPLE__) && defined(__arm64__)) || \
(defined(__linux__) && defined(__x86_64__))
typedef int ti_int __attribute__ ((mode (TI)));
extern "C"
ti_int
__muloti4(ti_int a, ti_int b, int* overflow)
{
const int N = (int)(sizeof(ti_int) * CHAR_BIT);
const ti_int MIN = (ti_int)1 << (N-1);
const ti_int MAX = ~MIN;
*overflow = 0;
ti_int result = a * b;
if (a == MIN)
{
if (b != 0 && b != 1)
*overflow = 1;
return result;
}
if (b == MIN)
{
if (a != 0 && a != 1)
*overflow = 1;
return result;
}
ti_int sa = a >> (N - 1);
ti_int abs_a = (a ^ sa) - sa;
ti_int sb = b >> (N - 1);
ti_int abs_b = (b ^ sb) - sb;
if (abs_a < 2 || abs_b < 2)
return result;
if (sa == sb)
{
if (abs_a > MAX / abs_b)
*overflow = 1;
}
else
{
if (abs_a > MIN / -abs_b)
*overflow = 1;
}
return result;
}
#endif
#if defined(__linux__) && defined(__arm__)
// Similar to above, but with mulodi4. Perhaps this is
// something that shouldn't be done, and is a bandaid over
// some other lower-level architecture issue that I'm
// missing. Perhaps relevant bug report:
// FIXME: https://llvm.org/bugs/show_bug.cgi?id=14469
typedef int di_int __attribute__ ((mode (DI)));
extern "C"
di_int
__mulodi4(di_int a, di_int b, int* overflow)
{
const int N = (int)(sizeof(di_int) * CHAR_BIT);
const di_int MIN = (di_int)1 << (N-1);
const di_int MAX = ~MIN;
*overflow = 0;
di_int result = a * b;
if (a == MIN)
{
if (b != 0 && b != 1)
*overflow = 1;
return result;
}
if (b == MIN)
{
if (a != 0 && a != 1)
*overflow = 1;
return result;
}
di_int sa = a >> (N - 1);
di_int abs_a = (a ^ sa) - sa;
di_int sb = b >> (N - 1);
di_int abs_b = (b ^ sb) - sb;
if (abs_a < 2 || abs_b < 2)
return result;
if (sa == sb)
{
if (abs_a > MAX / abs_b)
*overflow = 1;
}
else
{
if (abs_a > MIN / -abs_b)
*overflow = 1;
}
return result;
}
#endif
// We can't return Float80, but we can receive a pointer to one, so
// switch the return type and the out parameter on strtold.
template <typename T>
static const char *_swift_stdlib_strtoX_clocale_impl(
const char * nptr, T* outResult, T huge,
T (*posixImpl)(const char *, char **, locale_t)
) {
char *EndPtr;
errno = 0;
const auto result = posixImpl(nptr, &EndPtr, getCLocale());
*outResult = result;
if (result == huge || result == -huge || result == 0.0 || result == -0.0) {
if (errno == ERANGE)
EndPtr = NULL;
}
return EndPtr;
}
extern "C" const char *_swift_stdlib_strtold_clocale(
const char * nptr, void *outResult) {
return _swift_stdlib_strtoX_clocale_impl(
nptr, static_cast<long double*>(outResult), HUGE_VALL, strtold_l);
}
extern "C" const char *_swift_stdlib_strtod_clocale(
const char * nptr, double *outResult) {
return _swift_stdlib_strtoX_clocale_impl(
nptr, outResult, HUGE_VAL, strtod_l);
}
extern "C" const char *_swift_stdlib_strtof_clocale(
const char * nptr, float *outResult) {
return _swift_stdlib_strtoX_clocale_impl(
nptr, outResult, HUGE_VALF, strtof_l);
}
extern "C" void _swift_stdlib_flockfile_stdout() {
flockfile(stdout);
}
extern "C" void _swift_stdlib_funlockfile_stdout() {
funlockfile(stdout);
}
extern "C" int _swift_stdlib_putc_stderr(int C) {
return putc(C, stderr);
}
extern "C" size_t _swift_stdlib_getHardwareConcurrency() {
return sysconf(_SC_NPROCESSORS_ONLN);
}
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2008, Arvid Norberg
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 author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "libtorrent/peer_id.hpp"
#include "libtorrent/io_service.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/thread.hpp"
#include <cstring>
#include <boost/bind.hpp>
#include <iostream>
using namespace libtorrent;
using namespace libtorrent::detail; // for write_* and read_*
struct peer_conn
{
peer_conn(io_service& ios, int num_pieces, int blocks_pp, tcp::endpoint const& ep
, char const* ih)
: s(ios)
, read_pos(0)
, state(handshaking)
// don't request anything from the last piece
// to keep things simple
, pieces(num_pieces - 1)
, block(0)
, blocks_per_piece(blocks_pp)
, info_hash(ih)
, outstanding_requests(0)
{
// build a list of all pieces and request them all!
for (int i = 0; i < int(pieces.size()); ++i)
pieces[i] = i;
std::random_shuffle(pieces.begin(), pieces.end());
s.async_connect(ep, boost::bind(&peer_conn::on_connect, this, _1));
}
stream_socket s;
char buffer[17*1024];
int read_pos;
enum state_t
{
handshaking,
sending_request,
receiving_message
};
int state;
std::vector<int> pieces;
int block;
int blocks_per_piece;
char const* info_hash;
int outstanding_requests;
void on_connect(error_code const& ec)
{
if (ec)
{
fprintf(stderr, "ERROR CONNECT: %s\n", ec.message().c_str());
return;
}
char handshake[] = "\x13" "BitTorrent protocol\0\0\0\0\0\0\0\x04"
" " // space for info-hash
"aaaaaaaaaaaaaaaaaaaa" // peer-id
"\0\0\0\x01\x02"; // interested
char* h = (char*)malloc(sizeof(handshake));
memcpy(h, handshake, sizeof(handshake));
std::memcpy(h + 28, info_hash, 20);
std::generate(h + 48, h + 68, &rand);
boost::asio::async_write(s, libtorrent::asio::buffer(h, sizeof(handshake) - 1)
, boost::bind(&peer_conn::on_handshake, this, h, _1, _2));
}
void on_handshake(char* h, error_code const& ec, size_t bytes_transferred)
{
free(h);
if (ec)
{
fprintf(stderr, "ERROR SEND HANDSHAKE: %s\n", ec.message().c_str());
return;
}
// read handshake
boost::asio::async_read(s, libtorrent::asio::buffer(buffer, 68)
, boost::bind(&peer_conn::on_handshake2, this, _1, _2));
}
void on_handshake2(error_code const& ec, size_t bytes_transferred)
{
if (ec)
{
fprintf(stderr, "ERROR READ HANDSHAKE: %s\n", ec.message().c_str());
return;
}
work();
}
void write_request()
{
if (pieces.empty()) return;
int piece = pieces.back();
char msg[] = "\0\0\0\xd\x06"
" " // piece
" " // offset
" "; // length
char* m = (char*)malloc(sizeof(msg));
memcpy(m, msg, sizeof(msg));
char* ptr = m + 5;
write_uint32(piece, ptr);
write_uint32(block * 16 * 1024, ptr);
write_uint32(16 * 1024, ptr);
error_code ec;
boost::asio::async_write(s, libtorrent::asio::buffer(m, sizeof(msg) - 1)
, boost::bind(&peer_conn::on_req_sent, this, m, _1, _2));
++block;
if (block == blocks_per_piece)
{
block = 0;
pieces.pop_back();
}
}
void on_req_sent(char* m, error_code const& ec, size_t bytes_transferred)
{
free(m);
if (ec)
{
fprintf(stderr, "ERROR SEND REQUEST: %s\n", ec.message().c_str());
return;
}
++outstanding_requests;
work();
}
void work()
{
if (pieces.empty() && outstanding_requests == 0)
{
fprintf(stderr, "COMPLETED DOWNLOAD\n");
return;
}
// send requests
if (outstanding_requests < 20 && !pieces.empty())
{
write_request();
return;
}
// read message
boost::asio::async_read(s, asio::buffer(buffer, 4)
, boost::bind(&peer_conn::on_msg_length, this, _1, _2));
}
void on_msg_length(error_code const& ec, size_t bytes_transferred)
{
if (ec)
{
fprintf(stderr, "ERROR RECEIVE MESSAGE PREFIX: %s\n", ec.message().c_str());
return;
}
char* ptr = buffer;
unsigned int length = read_uint32(ptr);
if (length > sizeof(buffer))
{
fprintf(stderr, "ERROR RECEIVE MESSAGE PREFIX: packet too big\n");
return;
}
boost::asio::async_read(s, asio::buffer(buffer, length)
, boost::bind(&peer_conn::on_message, this, _1, _2));
}
void on_message(error_code const& ec, size_t bytes_transferred)
{
if (ec)
{
fprintf(stderr, "ERROR RECEIVE MESSAGE: %s\n", ec.message().c_str());
return;
}
char* ptr = buffer;
int msg = read_uint8(ptr);
if (msg == 7) --outstanding_requests;
work();
}
};
int main(int argc, char* argv[])
{
if (argc < 5)
{
fprintf(stderr, "usage: connection_tester number-of-connections destination-ip destination-port torrent-file\n");
return 1;
}
int num_connections = atoi(argv[1]);
error_code ec;
address_v4 addr = address_v4::from_string(argv[2], ec);
if (ec)
{
fprintf(stderr, "ERROR RESOLVING %s: %s\n", argv[2], ec.message().c_str());
return 1;
}
int port = atoi(argv[3]);
tcp::endpoint ep(addr, port);
torrent_info ti(argv[4], ec);
if (ec)
{
fprintf(stderr, "ERROR LOADING .TORRENT: %s\n", ec.message().c_str());
return 1;
}
std::list<peer_conn*> conns;
io_service ios;
for (int i = 0; i < num_connections; ++i)
{
conns.push_back(new peer_conn(ios, ti.num_pieces(), ti.piece_length() / 16 / 1024
, ep, (char const*)&ti.info_hash()[0]));
libtorrent::sleep(1);
ios.poll_one(ec);
if (ec)
{
fprintf(stderr, "ERROR: %s\n", ec.message().c_str());
break;
}
}
ios.run(ec);
if (ec) fprintf(stderr, "ERROR: %s\n", ec.message().c_str());
return 0;
}
<commit_msg>extend connection test to support uploading as well<commit_after>/*
Copyright (c) 2008, Arvid Norberg
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 author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "libtorrent/peer_id.hpp"
#include "libtorrent/io_service.hpp"
#include "libtorrent/socket.hpp"
#include "libtorrent/address.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/io.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/thread.hpp"
#include "libtorrent/create_torrent.hpp"
#include "libtorrent/hasher.hpp"
#include <cstring>
#include <boost/bind.hpp>
#include <iostream>
#include <boost/array.hpp>
using namespace libtorrent;
using namespace libtorrent::detail; // for write_* and read_*
void generate_block(boost::uint32_t* buffer, int piece, int start, int length)
{
boost::uint32_t fill = (piece << 16) | (start / 0x4000);
for (int i = 0; i < length / 4; ++i)
{
buffer[i] = fill;
}
}
struct peer_conn
{
peer_conn(io_service& ios, int num_pieces, int blocks_pp, tcp::endpoint const& ep
, char const* ih, bool seed_)
: s(ios)
, read_pos(0)
, state(handshaking)
// don't request anything from the last piece
// to keep things simple
, pieces(num_pieces - 1)
, block(0)
, blocks_per_piece(blocks_pp)
, info_hash(ih)
, outstanding_requests(0)
, seed(seed_)
{
if (!seed_)
{
// build a list of all pieces and request them all!
for (int i = 0; i < int(pieces.size()); ++i)
pieces[i] = i;
std::random_shuffle(pieces.begin(), pieces.end());
}
s.async_connect(ep, boost::bind(&peer_conn::on_connect, this, _1));
}
stream_socket s;
boost::uint32_t write_buffer[17*1024/4];
boost::uint32_t buffer[17*1024/4];
int read_pos;
enum state_t
{
handshaking,
sending_request,
receiving_message
};
int state;
std::vector<int> pieces;
int block;
int blocks_per_piece;
char const* info_hash;
int outstanding_requests;
// if this is true, this connection is a seed
bool seed;
void on_connect(error_code const& ec)
{
if (ec)
{
fprintf(stderr, "ERROR CONNECT: %s\n", ec.message().c_str());
return;
}
char handshake[] = "\x13" "BitTorrent protocol\0\0\0\0\0\0\0\x04"
" " // space for info-hash
"aaaaaaaaaaaaaaaaaaaa" // peer-id
"\0\0\0\x01\x02"; // interested
char* h = (char*)malloc(sizeof(handshake));
memcpy(h, handshake, sizeof(handshake));
std::memcpy(h + 28, info_hash, 20);
std::generate(h + 48, h + 68, &rand);
// for seeds, don't send the interested message
boost::asio::async_write(s, libtorrent::asio::buffer(h, (sizeof(handshake) - 1) - (seed ? 5 : 0))
, boost::bind(&peer_conn::on_handshake, this, h, _1, _2));
}
void on_handshake(char* h, error_code const& ec, size_t bytes_transferred)
{
free(h);
if (ec)
{
fprintf(stderr, "ERROR SEND HANDSHAKE: %s\n", ec.message().c_str());
return;
}
// read handshake
boost::asio::async_read(s, libtorrent::asio::buffer((char*)buffer, 68)
, boost::bind(&peer_conn::on_handshake2, this, _1, _2));
}
void on_handshake2(error_code const& ec, size_t bytes_transferred)
{
if (ec)
{
fprintf(stderr, "ERROR READ HANDSHAKE: %s\n", ec.message().c_str());
return;
}
if (seed)
{
write_have_all();
}
else
{
work_download();
}
}
void write_have_all()
{
// have_all and unchoke
static char msg[] = "\0\0\0\x01\x0e\0\0\0\x01\x01";
error_code ec;
boost::asio::async_write(s, libtorrent::asio::buffer(msg, sizeof(msg) - 1)
, boost::bind(&peer_conn::on_have_all_sent, this, _1, _2));
}
void on_have_all_sent(error_code const& ec, size_t bytes_transferred)
{
if (ec)
{
fprintf(stderr, "ERROR SEND HAVE ALL: %s\n", ec.message().c_str());
return;
}
// read message
boost::asio::async_read(s, asio::buffer((char*)buffer, 4)
, boost::bind(&peer_conn::on_msg_length, this, _1, _2));
}
void write_request()
{
if (pieces.empty()) return;
int piece = pieces.back();
char msg[] = "\0\0\0\xd\x06"
" " // piece
" " // offset
" "; // length
char* m = (char*)malloc(sizeof(msg));
memcpy(m, msg, sizeof(msg));
char* ptr = m + 5;
write_uint32(piece, ptr);
write_uint32(block * 16 * 1024, ptr);
write_uint32(16 * 1024, ptr);
error_code ec;
boost::asio::async_write(s, libtorrent::asio::buffer(m, sizeof(msg) - 1)
, boost::bind(&peer_conn::on_req_sent, this, m, _1, _2));
++block;
if (block == blocks_per_piece)
{
block = 0;
pieces.pop_back();
}
}
void on_req_sent(char* m, error_code const& ec, size_t bytes_transferred)
{
free(m);
if (ec)
{
fprintf(stderr, "ERROR SEND REQUEST: %s\n", ec.message().c_str());
return;
}
++outstanding_requests;
work_download();
}
void work_download()
{
if (pieces.empty() && outstanding_requests == 0)
{
fprintf(stderr, "COMPLETED DOWNLOAD\n");
return;
}
// send requests
if (outstanding_requests < 20 && !pieces.empty())
{
write_request();
return;
}
// read message
boost::asio::async_read(s, asio::buffer((char*)buffer, 4)
, boost::bind(&peer_conn::on_msg_length, this, _1, _2));
}
void on_msg_length(error_code const& ec, size_t bytes_transferred)
{
if (ec)
{
fprintf(stderr, "ERROR RECEIVE MESSAGE PREFIX: %s\n", ec.message().c_str());
return;
}
char* ptr = (char*)buffer;
unsigned int length = read_uint32(ptr);
if (length > sizeof(buffer))
{
fprintf(stderr, "ERROR RECEIVE MESSAGE PREFIX: packet too big\n");
return;
}
boost::asio::async_read(s, asio::buffer((char*)buffer, length)
, boost::bind(&peer_conn::on_message, this, _1, _2));
}
void on_message(error_code const& ec, size_t bytes_transferred)
{
if (ec)
{
fprintf(stderr, "ERROR RECEIVE MESSAGE: %s\n", ec.message().c_str());
return;
}
char* ptr = (char*)buffer;
int msg = read_uint8(ptr);
if (seed)
{
if (msg == 6 && bytes_transferred == 13)
{
int piece = detail::read_int32(ptr);
int start = detail::read_int32(ptr);
int length = detail::read_int32(ptr);
write_piece(piece, start, length);
}
else
{
// read another message
boost::asio::async_read(s, asio::buffer(buffer, 4)
, boost::bind(&peer_conn::on_msg_length, this, _1, _2));
}
}
else
{
if (msg == 7) --outstanding_requests;
work_download();
}
}
void write_piece(int piece, int start, int length)
{
generate_block(write_buffer, piece, start, length);
static char msg[] = " \x07"
" " // piece
" "; // start
char* ptr = msg;
write_uint32(9 + length, ptr);
assert(length == 0x4000);
assert(*ptr == 7);
++ptr; // skip message id
write_uint32(piece, ptr);
write_uint32(start, ptr);
boost::array<libtorrent::asio::const_buffer, 2> vec;
vec[0] = libtorrent::asio::buffer(msg, sizeof(msg)-1);
vec[1] = libtorrent::asio::buffer(write_buffer, length);
boost::asio::async_write(s, vec, boost::bind(&peer_conn::on_have_all_sent, this, _1, _2));
}
};
void print_usage()
{
fprintf(stderr, "usage: connection_tester command ...\n\n"
"command is one of:\n"
" gen-torrent generate a test torrent\n"
" upload start an uploader test\n"
" download start a downloader test\n\n"
"examples:\n\n"
"connection_tester gen-torrent torrent-name\n"
"connection_tester upload number-of-connections destination-ip destination-port torrent-file\n"
"connection_tester download number-of-connections destination-ip destination-port torrent-file\n");
exit(1);
}
void generate_torrent(std::vector<char>& buf)
{
file_storage fs;
// 1 MiB piece size
const int piece_size = 1024 * 1024;
// 50 GiB should be enough to not fit in physical RAM
const int num_pieces = 1 * 1024;
const size_type total_size = size_type(piece_size) * num_pieces;
fs.add_file("stress_test_file", total_size);
libtorrent::create_torrent t(fs, piece_size);
boost::uint32_t piece[0x4000 / 4];
for (int i = 0; i < num_pieces; ++i)
{
hasher ph;
for (int j = 0; j < piece_size; j += 0x4000)
{
generate_block(piece, i, j, 0x4000);
ph.update((char*)piece, 0x4000);
}
t.set_hash(i, ph.final());
}
std::back_insert_iterator<std::vector<char> > out(buf);
bencode(out, t.generate());
}
int main(int argc, char* argv[])
{
if (argc <= 1) print_usage();
bool upload_test = false;
bool download_test = false;
if (strcmp(argv[1], "gen-torrent") == 0)
{
if (argc != 3) print_usage();
std::vector<char> tmp;
generate_torrent(tmp);
FILE* output = stdout;
if (strcmp("-", argv[2]) != 0)
output = fopen(argv[2], "wb+");
fwrite(&tmp[0], 1, tmp.size(), output);
if (output != stdout)
fclose(output);
return 0;
}
else if (strcmp(argv[1], "upload") == 0)
{
if (argc != 6) print_usage();
upload_test = true;
}
else if (strcmp(argv[1], "download") == 0)
{
if (argc != 6) print_usage();
download_test = true;
}
if (!download_test && !upload_test) print_usage();
int num_connections = atoi(argv[2]);
error_code ec;
address_v4 addr = address_v4::from_string(argv[3], ec);
if (ec)
{
fprintf(stderr, "ERROR RESOLVING %s: %s\n", argv[3], ec.message().c_str());
return 1;
}
int port = atoi(argv[4]);
tcp::endpoint ep(addr, port);
torrent_info ti(argv[5], ec);
if (ec)
{
fprintf(stderr, "ERROR LOADING .TORRENT: %s\n", ec.message().c_str());
return 1;
}
std::list<peer_conn*> conns;
io_service ios;
for (int i = 0; i < num_connections; ++i)
{
conns.push_back(new peer_conn(ios, ti.num_pieces(), ti.piece_length() / 16 / 1024
, ep, (char const*)&ti.info_hash()[0], upload_test));
libtorrent::sleep(1);
ios.poll_one(ec);
if (ec)
{
fprintf(stderr, "ERROR: %s\n", ec.message().c_str());
break;
}
}
ios.run(ec);
if (ec) fprintf(stderr, "ERROR: %s\n", ec.message().c_str());
return 0;
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sdrpagewindow.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2007-04-11 16:11:32 $
*
* 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 _SDRPAGEWINDOW_HXX
#define _SDRPAGEWINDOW_HXX
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOWLISTENER_HPP_
#include <com/sun/star/awt/XWindowListener.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYCHANGELISTENER_HPP_
#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XCONTROLCONTAINER_HPP_
#include <com/sun/star/awt/XControlContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_XMODECHANGELISTENER_HPP_
#include <com/sun/star/util/XModeChangeListener.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE4_HXX_
#include <cppuhelper/implbase4.hxx>
#endif
#ifndef _SVDTYPES_HXX
#include <svx/svdtypes.hxx> // fuer SdrLayerID
#endif
#ifndef _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif
#ifndef _CONTNR_HXX
#include <tools/contnr.hxx>
#endif
#ifndef _SDRPAGEWINDOW_HXX
#include <svx/sdrpagewindow.hxx>
#endif
#ifndef INCLUDED_SVXDLLAPI_H
#include "svx/svxdllapi.h"
#endif
#include <vector>
////////////////////////////////////////////////////////////////////////////////////////////////////
// predeclarations
class Region;
class SdrPaintInfoRec;
class SdrUnoObj;
class SdrPageView;
// #110094#
namespace sdr
{
namespace contact
{
class ObjectContact;
class ViewObjectContactRedirector;
} // end of namespace contact
namespace overlay
{
class OverlayManager;
} // end of namespace overlay
} // end of namespace sdr
class SdrUnoControlList;
class SdrPaintWindow;
class Rectangle;
class Link;
////////////////////////////////////////////////////////////////////////////////////////////////////
class SVX_DLLPUBLIC SdrPageWindow
{
// #110094# ObjectContact section
sdr::contact::ObjectContact* mpObjectContact;
// the SdrPageView this window belongs to
SdrPageView& mrPageView;
// the PaintWindow to paint on. Here is access to OutDev etc.
// #i72752# change to pointer to allow patcing it in DrawLayer() if necessary
SdrPaintWindow* mpPaintWindow;
SdrPaintWindow* mpOriginalPaintWindow;
// UNO stuff for xControls
void* mpDummy;
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > mxControlContainer;
// #110094# ObjectContact section
sdr::contact::ObjectContact* CreateViewSpecificObjectContact();
// support method for creating PageInfoRecs for painting
SdrPaintInfoRec* ImpCreateNewPageInfoRec(const Rectangle& rDirtyRect,
sal_uInt16 nPaintMode, const SdrLayerID* pId) const;
public:
SdrPageWindow(SdrPageView& rNewPageView, SdrPaintWindow& rPaintWindow);
~SdrPageWindow();
// data read accesses
SdrPageView& GetPageView() const { return mrPageView; }
SdrPaintWindow& GetPaintWindow() const { return *mpPaintWindow; }
const SdrPaintWindow* GetOriginalPaintWindow() const { return mpOriginalPaintWindow; }
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > GetControlContainer( bool _bCreateIfNecessary = true ) const;
// OVERLAYMANAGER
::sdr::overlay::OverlayManager* GetOverlayManager() const;
// #i72752# allow patcing SdrPaintWindow from SdrPageView::DrawLayer if needed
void patchPaintWindow(SdrPaintWindow& rPaintWindow);
void unpatchPaintWindow();
// the repaint method. For migration from pPaintProc, use one more parameter
void PrepareRedraw(const Region& rReg);
void RedrawAll(sal_uInt16 nPaintMode, ::sdr::contact::ViewObjectContactRedirector* pRedirector) const;
void RedrawLayer(sal_uInt16 nPaintMode, const SdrLayerID* pId, ::sdr::contact::ViewObjectContactRedirector* pRedirector) const;
// Invalidate call, used from ObjectContact(OfPageView) in InvalidatePartOfView(...)
void Invalidate(const Rectangle& rRectangle);
// #110094# ObjectContact section
sdr::contact::ObjectContact& GetObjectContact() const;
/// determines whether there already exists an ObjectContact
bool HasObjectContact() const;
// #i26631#
void ResetObjectContact();
/** sets all elements in the view which support a design and a alive mode into the given mode
*/
void SetDesignMode( bool _bDesignMode ) const;
};
// typedefs for a list of SdrPageWindow
typedef ::std::vector< SdrPageWindow* > SdrPageWindowVector;
////////////////////////////////////////////////////////////////////////////////////////////////////
#endif //_SDRPAGEWINDOW_HXX
<commit_msg>INTEGRATION: CWS changefileheader (1.2.466); FILE MERGED 2008/04/01 15:49:36 thb 1.2.466.3: #i85898# Stripping all external header guards 2008/04/01 12:46:49 thb 1.2.466.2: #i85898# Stripping all external header guards 2008/03/31 14:18:15 rt 1.2.466.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sdrpagewindow.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SDRPAGEWINDOW_HXX
#define _SDRPAGEWINDOW_HXX
#include <tools/debug.hxx>
#include <com/sun/star/awt/XWindowListener.hpp>
#include <com/sun/star/beans/XPropertyChangeListener.hpp>
#include <com/sun/star/awt/XControlContainer.hpp>
#include <com/sun/star/util/XModeChangeListener.hpp>
#include <cppuhelper/implbase4.hxx>
#include <svx/svdtypes.hxx> // fuer SdrLayerID
#include <svtools/svarray.hxx>
#include <tools/contnr.hxx>
#include <svx/sdrpagewindow.hxx>
#include "svx/svxdllapi.h"
#include <vector>
////////////////////////////////////////////////////////////////////////////////////////////////////
// predeclarations
class Region;
class SdrPaintInfoRec;
class SdrUnoObj;
class SdrPageView;
// #110094#
namespace sdr
{
namespace contact
{
class ObjectContact;
class ViewObjectContactRedirector;
} // end of namespace contact
namespace overlay
{
class OverlayManager;
} // end of namespace overlay
} // end of namespace sdr
class SdrUnoControlList;
class SdrPaintWindow;
class Rectangle;
class Link;
////////////////////////////////////////////////////////////////////////////////////////////////////
class SVX_DLLPUBLIC SdrPageWindow
{
// #110094# ObjectContact section
sdr::contact::ObjectContact* mpObjectContact;
// the SdrPageView this window belongs to
SdrPageView& mrPageView;
// the PaintWindow to paint on. Here is access to OutDev etc.
// #i72752# change to pointer to allow patcing it in DrawLayer() if necessary
SdrPaintWindow* mpPaintWindow;
SdrPaintWindow* mpOriginalPaintWindow;
// UNO stuff for xControls
void* mpDummy;
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > mxControlContainer;
// #110094# ObjectContact section
sdr::contact::ObjectContact* CreateViewSpecificObjectContact();
// support method for creating PageInfoRecs for painting
SdrPaintInfoRec* ImpCreateNewPageInfoRec(const Rectangle& rDirtyRect,
sal_uInt16 nPaintMode, const SdrLayerID* pId) const;
public:
SdrPageWindow(SdrPageView& rNewPageView, SdrPaintWindow& rPaintWindow);
~SdrPageWindow();
// data read accesses
SdrPageView& GetPageView() const { return mrPageView; }
SdrPaintWindow& GetPaintWindow() const { return *mpPaintWindow; }
const SdrPaintWindow* GetOriginalPaintWindow() const { return mpOriginalPaintWindow; }
::com::sun::star::uno::Reference< ::com::sun::star::awt::XControlContainer > GetControlContainer( bool _bCreateIfNecessary = true ) const;
// OVERLAYMANAGER
::sdr::overlay::OverlayManager* GetOverlayManager() const;
// #i72752# allow patcing SdrPaintWindow from SdrPageView::DrawLayer if needed
void patchPaintWindow(SdrPaintWindow& rPaintWindow);
void unpatchPaintWindow();
// the repaint method. For migration from pPaintProc, use one more parameter
void PrepareRedraw(const Region& rReg);
void RedrawAll(sal_uInt16 nPaintMode, ::sdr::contact::ViewObjectContactRedirector* pRedirector) const;
void RedrawLayer(sal_uInt16 nPaintMode, const SdrLayerID* pId, ::sdr::contact::ViewObjectContactRedirector* pRedirector) const;
// Invalidate call, used from ObjectContact(OfPageView) in InvalidatePartOfView(...)
void Invalidate(const Rectangle& rRectangle);
// #110094# ObjectContact section
sdr::contact::ObjectContact& GetObjectContact() const;
/// determines whether there already exists an ObjectContact
bool HasObjectContact() const;
// #i26631#
void ResetObjectContact();
/** sets all elements in the view which support a design and a alive mode into the given mode
*/
void SetDesignMode( bool _bDesignMode ) const;
};
// typedefs for a list of SdrPageWindow
typedef ::std::vector< SdrPageWindow* > SdrPageWindowVector;
////////////////////////////////////////////////////////////////////////////////////////////////////
#endif //_SDRPAGEWINDOW_HXX
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile$
*
* $Revision$
*
* last change: $Author$ $Date$
*
* 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 _SVXSWFRAMEVALIDATION_HXX
#define _SVXSWFRAMEVALIDATION_HXX
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#include <limits.h>
/* -----------------03.03.2004 16:31-----------------
struct to determine min/max values for fly frame positioning in Writer
--------------------------------------------------*/
struct SvxSwFrameValidation
{
sal_Int16 nAnchorType; //com::sun::star::text::TextContentAnchorType
sal_Int16 nHoriOrient; //com::sun::star::text::HoriOrientation
sal_Int16 nVertOrient; //com::sun::star::text::VertOrientation
sal_Int16 nHRelOrient; //com::sun::star::text::RelOrientation
sal_Int16 nVRelOrient; //com::sun::star::text::RelOrientation
bool bAutoHeight;
bool bAutoWidth;
bool bMirror;
bool bFollowTextFlow;
sal_Int32 nHPos;
sal_Int32 nMaxHPos;
sal_Int32 nMinHPos;
sal_Int32 nVPos;
sal_Int32 nMaxVPos;
sal_Int32 nMinVPos;
sal_Int32 nWidth;
sal_Int32 nMinWidth;
sal_Int32 nMaxWidth;
sal_Int32 nHeight;
sal_Int32 nMinHeight;
sal_Int32 nMaxHeight;
Size aPercentSize; // Size fuer 100%-Wert
SvxSwFrameValidation() :
bAutoHeight(false),
bAutoWidth(false),
bMirror(false),
bFollowTextFlow( false ),
nHPos(0),
nMaxHPos(LONG_MAX),
nMinHPos(0),
nVPos(0),
nMaxVPos(LONG_MAX),
nMinVPos(0),
nWidth( 283 * 4 ), //2.0 cm
nMinWidth(0),
nMaxWidth(LONG_MAX),
nHeight( 283 ), //0.5 cm
nMaxHeight(LONG_MAX)
{
}
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.3.1256); FILE MERGED 2008/04/01 15:49:23 thb 1.3.1256.2: #i85898# Stripping all external header guards 2008/03/31 14:18:00 rt 1.3.1256.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile$
* $Revision$
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _SVXSWFRAMEVALIDATION_HXX
#define _SVXSWFRAMEVALIDATION_HXX
#include <sal/types.h>
#include <tools/gen.hxx>
#include <limits.h>
/* -----------------03.03.2004 16:31-----------------
struct to determine min/max values for fly frame positioning in Writer
--------------------------------------------------*/
struct SvxSwFrameValidation
{
sal_Int16 nAnchorType; //com::sun::star::text::TextContentAnchorType
sal_Int16 nHoriOrient; //com::sun::star::text::HoriOrientation
sal_Int16 nVertOrient; //com::sun::star::text::VertOrientation
sal_Int16 nHRelOrient; //com::sun::star::text::RelOrientation
sal_Int16 nVRelOrient; //com::sun::star::text::RelOrientation
bool bAutoHeight;
bool bAutoWidth;
bool bMirror;
bool bFollowTextFlow;
sal_Int32 nHPos;
sal_Int32 nMaxHPos;
sal_Int32 nMinHPos;
sal_Int32 nVPos;
sal_Int32 nMaxVPos;
sal_Int32 nMinVPos;
sal_Int32 nWidth;
sal_Int32 nMinWidth;
sal_Int32 nMaxWidth;
sal_Int32 nHeight;
sal_Int32 nMinHeight;
sal_Int32 nMaxHeight;
Size aPercentSize; // Size fuer 100%-Wert
SvxSwFrameValidation() :
bAutoHeight(false),
bAutoWidth(false),
bMirror(false),
bFollowTextFlow( false ),
nHPos(0),
nMaxHPos(LONG_MAX),
nMinHPos(0),
nVPos(0),
nMaxVPos(LONG_MAX),
nMinVPos(0),
nWidth( 283 * 4 ), //2.0 cm
nMinWidth(0),
nMaxWidth(LONG_MAX),
nHeight( 283 ), //0.5 cm
nMaxHeight(LONG_MAX)
{
}
};
#endif
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: anchoreddrawobject.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2004-09-09 10:54:27 $
*
* 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 _ANCHOREDDRAWOBJECT_HXX
#define _ANCHOREDDRAWOBJECT_HXX
#ifndef _ANCHOREDOBJECT_HXX
#include <anchoredobject.hxx>
#endif
#ifndef _GEN_HXX
#include <tools/gen.hxx>
#endif
/** class for the positioning of drawing objects
OD 2004-03-25 #i26791#
@author OD
*/
class SwAnchoredDrawObject : public SwAnchoredObject
{
private:
// boolean, indicating that the object position has been invalidated
// and that a positioning has to be performed.
bool mbValidPos;
// rectangle, keeping the last object rectangle after the postioning
Rectangle maLastObjRect;
// boolean, indicating that anchored drawing object hasn't been attached
// to a anchor frame yet. Once, it is attached to a anchor frame the
// boolean changes its state.
bool mbNotYetAttachedToAnchorFrame;
// --> OD 2004-08-09 #i28749# - boolean, indicating that anchored
// drawing object hasn't been positioned yet. Once, it's positioned the
// boolean changes its state.
bool mbNotYetPositioned;
/** method for the intrinsic positioning of a at-paragraph|at-character
anchored drawing object
OD 2004-08-12 #i32795# - helper method for method <MakeObjPos>
@author OD
*/
void _MakeObjPosAnchoredAtPara();
/** method for the intrinsic positioning of a at-page|at-frame anchored
drawing object
OD 2004-08-12 #i32795# - helper method for method <MakeObjPos>
@author OD
*/
void _MakeObjPosAnchoredAtLayout();
/** method to convert positioning attributes from horizontal
left-to-right layout to the layout direction of its anchor frame
OD 2004-08-09 #i28749#
The positioning attributes are converted by the current object geometry.
Conversion has to be done for drawing objects (not anchored
as-character) imported from OpenOffice.org file format only once
and directly before the first positioning.
@author OD
*/
void _ConvertPositioningAttr();
/** method to set internal anchor position of <SdrObject> instance
of the drawing object
For drawing objects the internal anchor position of the <SdrObject>
instance has to be set.
Note: This adjustment is not be done for as-character anchored
drawing object - the positioning code takes care of this.
OD 2004-07-29 #i31698# - API for drawing objects in Writer has
been adjusted. Thus, this method will only set the internal anchor
position of the <SdrObject> instance to the anchor position given
by its anchor frame.
@author OD
*/
void _SetDrawObjAnchor();
/** method to invalidate the given page frame
OD 2004-07-02 #i28701#
@author OD
*/
void _InvalidatePage( SwPageFrm* _pPageFrm );
protected:
virtual void ObjectAttachedToAnchorFrame();
/** method to assure that anchored object is registered at the correct
page frame
OD 2004-07-02 #i28701#
@author OD
*/
virtual void RegisterAtCorrectPage();
public:
TYPEINFO();
SwAnchoredDrawObject();
virtual ~SwAnchoredDrawObject();
// declaration of pure virtual methods of base class <SwAnchoredObject>
virtual void MakeObjPos();
virtual void InvalidateObjPos();
// accessors to the format
virtual SwFrmFmt& GetFrmFmt();
virtual const SwFrmFmt& GetFrmFmt() const;
// accessors to the object area and its position
virtual const SwRect GetObjRect() const;
virtual void SetObjTop( const SwTwips _nTop);
virtual void SetObjLeft( const SwTwips _nLeft);
const Rectangle& GetLastObjRect() const;
Rectangle& LastObjRect();
/** adjust positioning and alignment attributes for new anchor frame
OD 2004-04-21
Set horizontal and vertical position/alignment to manual position
relative to anchor frame area using the anchor position of the
new anchor frame and the current absolute drawing object position.
Note: For correct Undo/Redo method should only be called inside a
Undo-/Redo-action.
OD 2004-08-24 #i33313# - add second optional parameter <_pNewObjRect>
@author OD
@param <_pNewAnchorFrm>
input parameter - new anchor frame for the anchored object.
@param <_pNewObjRect>
optional input parameter - proposed new object rectangle. If not
provided the current object rectangle is taken.
*/
void AdjustPositioningAttr( const SwFrm* _pNewAnchorFrm,
const SwRect* _pNewObjRect = 0L );
/** anchored drawing object not yet attached to a anchor frame
OD 2004-08-04 #i31698#
@author OD
*/
inline bool NotYetAttachedToAnchorFrm() const
{
return mbNotYetAttachedToAnchorFrame;
}
/** method to notify background of drawing object
OD 2004-06-30 #i28701#
@author OD
*/
virtual void NotifyBackground( SwPageFrm* _pPageFrm,
const SwRect& _rRect,
PrepareHint _eHint );
};
#endif
<commit_msg>INTEGRATION: CWS dbwizard1 (1.4.18); FILE MERGED 2004/10/20 10:52:17 od 1.4.18.3: #i35798# class <SwAnchoredDrawObject> - replace method <_ConvertPositioningAttr()> by <_SetPositioningAttr()> 2004/10/11 14:32:24 tv 1.4.18.2: RESYNC: (1.4-1.5); FILE MERGED 2004/10/01 12:34:51 od 1.4.18.1: #i34748# class <SwAnchoredDrawObject> - change handling of the last object rectangle in order to consider, if already a last object rectangle exists.<commit_after>/*************************************************************************
*
* $RCSfile: anchoreddrawobject.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: pjunck $ $Date: 2004-10-27 12:29:49 $
*
* 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 _ANCHOREDDRAWOBJECT_HXX
#define _ANCHOREDDRAWOBJECT_HXX
#ifndef _ANCHOREDOBJECT_HXX
#include <anchoredobject.hxx>
#endif
#ifndef _GEN_HXX
#include <tools/gen.hxx>
#endif
/** class for the positioning of drawing objects
OD 2004-03-25 #i26791#
@author OD
*/
class SwAnchoredDrawObject : public SwAnchoredObject
{
private:
// boolean, indicating that the object position has been invalidated
// and that a positioning has to be performed.
bool mbValidPos;
// rectangle, keeping the last object rectangle after the postioning
// --> OD 2004-09-29 #i34748# - change <maLastObjRect> to a pointer
Rectangle* mpLastObjRect;
// boolean, indicating that anchored drawing object hasn't been attached
// to a anchor frame yet. Once, it is attached to a anchor frame the
// boolean changes its state.
bool mbNotYetAttachedToAnchorFrame;
// --> OD 2004-08-09 #i28749# - boolean, indicating that anchored
// drawing object hasn't been positioned yet. Once, it's positioned the
// boolean changes its state.
bool mbNotYetPositioned;
/** method for the intrinsic positioning of a at-paragraph|at-character
anchored drawing object
OD 2004-08-12 #i32795# - helper method for method <MakeObjPos>
@author OD
*/
void _MakeObjPosAnchoredAtPara();
/** method for the intrinsic positioning of a at-page|at-frame anchored
drawing object
OD 2004-08-12 #i32795# - helper method for method <MakeObjPos>
@author OD
*/
void _MakeObjPosAnchoredAtLayout();
/** method to set positioning attributes (not for as-character anchored)
OD 2004-10-20 #i35798#
During load the positioning attributes aren't set.
Thus, the positioning attributes are set by the current object geometry.
This method is also used for the conversion for drawing objects
(not anchored as-character) imported from OpenOffice.org file format
once and directly before the first positioning.
@author OD
*/
void _SetPositioningAttr();
/** method to set internal anchor position of <SdrObject> instance
of the drawing object
For drawing objects the internal anchor position of the <SdrObject>
instance has to be set.
Note: This adjustment is not be done for as-character anchored
drawing object - the positioning code takes care of this.
OD 2004-07-29 #i31698# - API for drawing objects in Writer has
been adjusted. Thus, this method will only set the internal anchor
position of the <SdrObject> instance to the anchor position given
by its anchor frame.
@author OD
*/
void _SetDrawObjAnchor();
/** method to invalidate the given page frame
OD 2004-07-02 #i28701#
@author OD
*/
void _InvalidatePage( SwPageFrm* _pPageFrm );
protected:
virtual void ObjectAttachedToAnchorFrame();
/** method to assure that anchored object is registered at the correct
page frame
OD 2004-07-02 #i28701#
@author OD
*/
virtual void RegisterAtCorrectPage();
public:
TYPEINFO();
SwAnchoredDrawObject();
virtual ~SwAnchoredDrawObject();
// declaration of pure virtual methods of base class <SwAnchoredObject>
virtual void MakeObjPos();
virtual void InvalidateObjPos();
// accessors to the format
virtual SwFrmFmt& GetFrmFmt();
virtual const SwFrmFmt& GetFrmFmt() const;
// accessors to the object area and its position
virtual const SwRect GetObjRect() const;
virtual void SetObjTop( const SwTwips _nTop);
virtual void SetObjLeft( const SwTwips _nLeft);
// --> OD 2004-09-29 #i34748# - change return type to a pointer.
// Return value can be NULL.
const Rectangle* GetLastObjRect() const;
// <--
// --> OD 2004-09-29 #i34748# - change method
void SetLastObjRect( const Rectangle& _rNewObjRect );
// <--
/** adjust positioning and alignment attributes for new anchor frame
OD 2004-04-21
Set horizontal and vertical position/alignment to manual position
relative to anchor frame area using the anchor position of the
new anchor frame and the current absolute drawing object position.
Note: For correct Undo/Redo method should only be called inside a
Undo-/Redo-action.
OD 2004-08-24 #i33313# - add second optional parameter <_pNewObjRect>
@author OD
@param <_pNewAnchorFrm>
input parameter - new anchor frame for the anchored object.
@param <_pNewObjRect>
optional input parameter - proposed new object rectangle. If not
provided the current object rectangle is taken.
*/
void AdjustPositioningAttr( const SwFrm* _pNewAnchorFrm,
const SwRect* _pNewObjRect = 0L );
/** anchored drawing object not yet attached to a anchor frame
OD 2004-08-04 #i31698#
@author OD
*/
inline bool NotYetAttachedToAnchorFrm() const
{
return mbNotYetAttachedToAnchorFrame;
}
/** method to notify background of drawing object
OD 2004-06-30 #i28701#
@author OD
*/
virtual void NotifyBackground( SwPageFrm* _pPageFrm,
const SwRect& _rRect,
PrepareHint _eHint );
};
#endif
<|endoftext|>
|
<commit_before>/******************************************************************************
* Evatar_AutoFocus.cpp
*
* Author: Bryan D. Maione
*
* This application uses the Mantis camera API and OpenCV to Autofocus Mcams.
*
*****************************************************************************/
/* gcc -std=c++11 -o Evetar_AutoFocus Evetar_AutoFocus.cpp -lMantisAPI -lpthread -lopencv_core -lopencv_highgui -lopencv_imgcodecs -lopencv_imgproc -lm -lstdc++
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <math.h>
#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include "mantis/MantisAPI.h"
using namespace cv;
using namespace std;
void newMCamCallback(MICRO_CAMERA mcam, void* data)
{
static int mcamCounter = 0;
MICRO_CAMERA* mcamList = (MICRO_CAMERA*) data;
mcamList[mcamCounter++] = mcam;
}
/**
* \brief Function to handle recieving microcamera frames that just
* prints the mcam ID and timestamp of the received frame
**/
void mcamFrameCallback(FRAME frame, void* data)
{
; //do nothing
}
/**
* \ Main Function that steps the focus motors and computes a focus metric
**/
int main()
{
char ip[24] = "10.0.0.152";
int port = 9999;
mCamConnect(ip, port);
initMCamFrameReceiver( 11001, 1 );
/* get cameras from API */
int numMCams = getNumberOfMCams();
printf("API reported that there are %d microcameras available\n", numMCams);
MICRO_CAMERA mcamList[numMCams];
/* create new microcamera callback struct */
NEW_MICRO_CAMERA_CALLBACK mcamCB;
mcamCB.f = newMCamCallback;
mcamCB.data = mcamList;
/* call setNewMCamCallback; this function sets a callback that is
* triggered each time a new microcamera is discovered by the API,
* and also calls the callback function for each microcamera that
* has already been discovered at the time of setting the callback */
setNewMCamCallback(mcamCB);
/* Next we set a callback function to receive the stream of frames
* from the desired microcamera */
MICRO_CAMERA_FRAME_CALLBACK frameCB;
frameCB.f = mcamFrameCallback;
frameCB.data = NULL;
setMCamFrameCallback(frameCB);
//MICRO_CAMERA myMCam = mcamList[0];
/* now if we check our list, we should see a populated list
* of MICRO_CAMERA objects */
for( int i = 0; i < numMCams; i++ ){
printf("Found mcam with ID %u\n", mcamList[i].mcamID);
// Star the stream for each Mcam in the list
if( !startMCamStream(mcamList[i], 11001+i) ){
printf("Failed to start streaming mcam %u\n", mcamList[i].mcamID);
exit(0);
}
}
/* We only want to stream HD frame */
for( int i = 0; i < numMCams; i++ ){
setMCamStreamFilter(mcamList[i], 11001+i, ATL_SCALE_MODE_HD);
}
/* Bring each Mcam to near focus*/
for( int i = 0; i < numMCams; i++ ){
setMCamFocusNear(mcamList[i], 0); // I currently have a modified moveFocusmotors.py that will go to "home" when given 0 for num steps
}
sleep(1);
int step = 100; //Doing a focus sweep with 100 step increments
int numiter = 2300/step;
double metric[numMCams] = {0};
double metricprev[numMCams] = {0};
double localbestmetric[numMCams] = {0};
double globalbestmetric[numMCams] = {0};
int globalbestpos[numMCams] = {0};
/* Start the focus sweep for each micro camera connected to this tegra*/
for ( int i = 0; i <= numiter-1; i++ ){
cout << "Current Position: "+to_string(i*step) << "\n";
/* Step each motor 100 steps */
for (int j = 0; j < numMCams; j++){
setMCamFocusFar(mcamList[j], step);
}
sleep(2);
for (int j = 0; j < numMCams; j++){
int edgeThresh = 1;
int imgsize = 1920*1080;
/*Ideally we want to get rid of this section and replace the saving and loading with a MantisAPI to OpenCV mat construction*/
/**************************************/
FRAME frame = grabMCamFrame(11001+j, 1.0 );
if (!saveMCamFrame(frame, "focustmp")){
printf("Unable to save frame\n");
}
/**************************************/
/* The constructor should look something like this, I just couldn't get it to compile*/
//loaded(1080, 1920, CV_8UC1, frame.m_image, size_t step = AUTO_STEP);
Mat loaded,edge;
loaded = imread("focustmp.jpeg",1);
Canny(loaded, edge, edgeThresh, edgeThresh*100, 3);
metric[j] = cv::sum( edge )[0]/imgsize;
//imshow("Frame",loaded);
//waitKey(1000);
cout << "Current metric value: "+to_string(metric[j]) << "\n";
/* If the metric increased update the best value and position */
if ( metric[j] > metricprev[j]){
cout << "metric value increased" << "\n";
localbestmetric[j] = metric[j];
/* If the current metric is the best we've seen yet, update as current best*/
if ( localbestmetric[j] > globalbestmetric[j] ){
cout << "Global best updated" << "\n";
globalbestmetric[j] = localbestmetric[j];
globalbestpos[j] = i+1;
}
}
metricprev[j] = metric[j];
}
}
/* Bring each Mcam to near focus*/
for( int i = 0; i < numMCams; i++ ){
setMCamFocusNear(mcamList[i], 0); // I currently have a modified moveFocusmotors.py that will go to "home" when given 0 for num steps
}
sleep(4);
//For some reason have to send this command a second time -- Possible error state on motor
/* Bring each Mcam to near focus*/
for( int i = 0; i < numMCams; i++ ){
setMCamFocusNear(mcamList[i], 0); // I currently have a modified moveFocusmotors.py that will go to "home" when given 0 for num steps
}
sleep(3);
/* Bring each Mcam to best focus position*/
for( int i = 0; i < numMCams; i++ ){
setMCamFocusFar(mcamList[i], globalbestpos[i]*step);
}
sleep(3);
for( int i = 0; i < numMCams; i++ ){
closeMCamFrameReceiver( 11001+i );
}
mCamDisconnect(ip, port);
cout << "Best Focus metric of: " + std::to_string(globalbestmetric[0]) + " at position: " + std::to_string(globalbestpos[0]) << "\n";
exit(1);
}
<commit_msg>Updated code to pass image buffer directly to openCV.<commit_after>/******************************************************************************
* Evatar_AutoFocus.cpp
*
* Author: Bryan D. Maione
*
* This application uses the Mantis camera API and OpenCV to Autofocus Mcams.
*
*****************************************************************************/
/* gcc -std=c++11 -o Evetar_AutoFocus Evetar_AutoFocus.cpp -lMantisAPI -lpthread -lopencv_core -lopencv_highgui -lopencv_imgcodecs -lopencv_imgproc -lm -lstdc++
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <math.h>
#include "opencv2/core/mat.hpp"
#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include "mantis/MantisAPI.h"
using namespace cv;
using namespace std;
void newMCamCallback(MICRO_CAMERA mcam, void* data)
{
static int mcamCounter = 0;
MICRO_CAMERA* mcamList = (MICRO_CAMERA*) data;
mcamList[mcamCounter++] = mcam;
}
/**
* \brief Function to handle recieving microcamera frames that just
* prints the mcam ID and timestamp of the received frame
**/
void mcamFrameCallback(FRAME frame, void* data)
{
; //do nothing
}
//double calculateFocusMetric(uint8_t* img){
/* Casting from image buffer goes here */
// Mat edge;
// Canny(img, edge, edgeThresh, edgeThresh*100, 3);
//metric = cv::sum( edge )[0]/imgsize;
// return metric;
//}
/**
* \ Main Function that steps the focus motors and computes a focus metric
**/
int main()
{
char ip[24] = "10.0.0.152";
int port = 9999;
mCamConnect(ip, port);
initMCamFrameReceiver( 13001, 1 );
/* get cameras from API */
int numMCams = getNumberOfMCams();
printf("API reported that there are %d microcameras available\n", numMCams);
MICRO_CAMERA mcamList[numMCams];
/* create new microcamera callback struct */
NEW_MICRO_CAMERA_CALLBACK mcamCB;
mcamCB.f = newMCamCallback;
mcamCB.data = mcamList;
/* call setNewMCamCallback; this function sets a callback that is
* triggered each time a new microcamera is discovered by the API,
* and also calls the callback function for each microcamera that
* has already been discovered at the time of setting the callback */
setNewMCamCallback(mcamCB);
/* Next we set a callback function to receive the stream of frames
* from the desired microcamera */
MICRO_CAMERA_FRAME_CALLBACK frameCB;
frameCB.f = mcamFrameCallback;
frameCB.data = NULL;
setMCamFrameCallback(frameCB);
//MICRO_CAMERA myMCam = mcamList[0];
/* now if we check our list, we should see a populated list
* of MICRO_CAMERA objects */
for( int i = 0; i < numMCams; i++ ){
printf("Found mcam with ID %u\n", mcamList[i].mcamID);
// Star the stream for each Mcam in the list
if( !startMCamStream(mcamList[i], 13001+i) ){
printf("Failed to start streaming mcam %u\n", mcamList[i].mcamID);
exit(0);
}
}
/* We only want to stream HD frame */
for( int i = 0; i < numMCams; i++ ){
setMCamStreamFilter(mcamList[i], 13001+i, ATL_SCALE_MODE_HD);
}
/* Bring each Mcam to near focus*/
for( int i = 0; i < numMCams; i++ ){
setMCamFocusNear(mcamList[i], 0); // I currently have a modified moveFocusmotors.py that will go to "home" when given 0 for num steps
}
sleep(1);
int step = 100; //Doing a focus sweep with 100 step increments
int numiter = 2300/step;
double metric[numMCams] = {0};
double metricprev[numMCams] = {0};
double localbestmetric[numMCams] = {0};
double globalbestmetric[numMCams] = {0};
int globalbestpos[numMCams] = {0};
/* Start the focus sweep for each micro camera connected to this tegra*/
for ( int i = 0; i <= numiter-1; i++ ){
cout << "Current Position: "+to_string(i*step) << "\n";
/* Step each motor 100 steps */
for (int j = 0; j < numMCams; j++){
setMCamFocusFar(mcamList[j], step);
}
sleep(1);
for (int j = 0; j < numMCams; j++){
int edgeThresh = 1;
int imgsize = 1920*1080;
/*Ideally we want to get rid of this section and replace the saving and loading with a MantisAPI to OpenCV mat construction*/
/**************************************/
FRAME frame = grabMCamFrame(13001+j, 1.0 );
//if (!saveMCamFrame(frame, "focustmp")){
//printf("Unable to save frame\n");
//}
/**************************************/
/* The constructor should look something like this, I just couldn't get it to compile*/
size_t step=CV_AUTO_STEP;
Mat rawdata = Mat(1, frame.m_metadata.m_size , CV_8UC1, (void *)frame.m_image); //compressed jpg data
Mat loaded = imdecode(rawdata,1);
if (loaded.data==NULL){
cerr << "Failed to decode data" <<"\n";
}
//imshow("Frame",loaded);
//waitKey(1000);
Mat edge;
//loaded = imread("focustmp.jpeg",1);
Canny(loaded, edge, edgeThresh, edgeThresh*100, 3);
metric[j] = cv::sum( edge )[0]/imgsize;
cout << "Current metric value: "+to_string(metric[j]) << "\n";
/* If the metric increased update the best value and position */
if ( metric[j] > metricprev[j]){
cout << "metric value increased" << "\n";
localbestmetric[j] = metric[j];
/* If the current metric is the best we've seen yet, update as current best*/
if ( localbestmetric[j] > globalbestmetric[j] ){
cout << "Global best updated" << "\n";
globalbestmetric[j] = localbestmetric[j];
globalbestpos[j] = i+1;
}
}
metricprev[j] = metric[j];
}
}/*End Coarse focus sweep*/
/* Bring each Mcam to near focus*/
for( int i = 0; i < numMCams; i++ ){
setMCamFocusNear(mcamList[i], 0); // I currently have a modified moveFocusmotors.py that will go to "home" when given 0 for num steps
}
sleep(3);
//For some reason have to send this command a second time -- Possible error state on motor
/* Bring each Mcam to near focus*/
for( int i = 0; i < numMCams; i++ ){
setMCamFocusNear(mcamList[i], 0); // I currently have a modified moveFocusmotors.py that will go to "home" when given 0 for num steps
}
sleep(3);
/* Bring each Mcam to best focus position*/
for( int i = 0; i < numMCams; i++ ){
setMCamFocusFar(mcamList[i], globalbestpos[i]*step);
}
sleep(4);
for( int i = 0; i < numMCams; i++ ){
closeMCamFrameReceiver( 13001+i );
}
mCamDisconnect(ip, port);
cout << "Best Focus metric of: " + std::to_string(globalbestmetric[0]) + " at position: " + std::to_string(globalbestpos[0]) << "\n";
exit(1);
destroyAllWindows();
}
<|endoftext|>
|
<commit_before>/* medViewerToolBoxTime.h ---
*
* Author: Fatih Arslan and Nicolas Toussaint
* Change log:
*
*/
#include "medViewerToolBoxTime.h"
#include <iomanip>
#include <cmath>
#include <sstream>
#include <QListWidget>
#include <QList>
#include <QMouseEvent>
#include <dtkCore/dtkAbstractView.h>
#include <dtkCore/dtkLog.h>
#include <med4DAbstractViewInteractor.h>
#include <medToolBoxTab.h>
#include <medButton.h>
class medViewerToolBoxTimePrivate
{
public:
QSlider *timeSlider;
medButton *playSequencesButton;
medButton *nextFrameButton;
medButton *previousFrameButton;
medButton *stopButton;
QList <QAction*> actionlist;
QList<dtkAbstractView*> views;
QList<med4DAbstractViewInteractor*> interactors;
QTimeLine *timeLine;
QSpinBox *spinBox;
QLabel *labelmin;
QLabel *labelmax;
QLabel *labelcurr;
QLabel *labelspeed;
double minTime;
double minTimeStep;
double maxTime;
QPixmap playIcon;
};
medViewerToolBoxTime::medViewerToolBoxTime(QWidget *parent) : medToolBox(parent), d(new medViewerToolBoxTimePrivate)
{
QWidget *box = new QWidget (this);
d->labelmin = new QLabel(this);
d->labelmax = new QLabel(this);
d->labelcurr = new QLabel(this);
d->labelspeed = new QLabel(this);
d->labelspeed->setText("Speed %: ");
d->timeSlider = new QSlider (Qt::Horizontal, this);
d->timeSlider->setRange (0, 100);
d->timeSlider->setValue (0);
d->timeSlider->setTracking( false );
d->timeSlider->setToolTip(tr("Follow The Sequence"));
QStringList validDataTypes;
validDataTypes << "itkDataImageChar4"
<< "itkDataImageUChar4"
<< "itkDataImageShort4"
<< "itkDataImageUShort4"
<< "itkDataImageInt4"
<< "itkDataImageUInt4"
<< "itkDataImageLong4"
<< "itkDataImageULong4"
<< "itkDataImageFloat4"
<< "itkDataImageDouble4";
setValidDataTypes(validDataTypes);
d->playIcon = QPixmap(":/icons/play.png");
d->playSequencesButton = new medButton(this,d->playIcon,
tr("Play Sequence"));
d->nextFrameButton = new medButton(this,":/icons/forward.png",
tr("Next Frame"));
d->previousFrameButton = new medButton(this,":/icons/backward.png",
tr("Previous Frame"));
d->stopButton = new medButton(this,":/icons/stop.png",
tr("Stop Sequence"));
d->timeLine = new QTimeLine(1000, this);
d->timeLine->setLoopCount(0);
d->timeLine->setCurveShape (QTimeLine::LinearCurve);
d->spinBox = new QSpinBox(this);
d->spinBox->setRange(1,5000);
d->spinBox->setSingleStep(10);
d->spinBox->setValue(100);
d->spinBox->setToolTip(tr("Control the display speed"));
connect(d->timeLine, SIGNAL(frameChanged(int)), d->timeSlider, SLOT(setValue(int)));
QHBoxLayout *buttonLayout = new QHBoxLayout();
buttonLayout->addWidget( d->previousFrameButton,1,Qt::AlignHCenter);
buttonLayout->addWidget (d->playSequencesButton,1,Qt::AlignHCenter);
buttonLayout->addWidget( d->nextFrameButton,1,Qt::AlignHCenter);
buttonLayout->addWidget( d->stopButton,1,Qt::AlignHCenter);
QHBoxLayout *labelLayout = new QHBoxLayout();
labelLayout->addWidget( d->labelmin);
labelLayout->addStretch();
labelLayout->addWidget( d->labelcurr);
labelLayout->addStretch();
labelLayout->addWidget( d->labelmax);
QHBoxLayout *topLayout = new QHBoxLayout();
topLayout->addStretch();
topLayout->addWidget(d->labelspeed);
topLayout->addWidget(d->spinBox);
QVBoxLayout* boxlayout = new QVBoxLayout ();
boxlayout->addLayout(topLayout);
boxlayout->addLayout( buttonLayout );
boxlayout->addWidget (d->timeSlider);
boxlayout->addLayout(labelLayout);
d->actionlist.insert(0,new QAction("1",this));
d->actionlist.insert(1,new QAction("5",this));
d->actionlist.insert(2,new QAction("10",this));
d->actionlist.insert(3,new QAction("25",this));
d->actionlist.insert(4,new QAction("50",this));
connect(d->timeSlider, SIGNAL(sliderMoved(int)), this, SLOT(onTimeChanged(int)));
connect(d->timeSlider, SIGNAL(valueChanged(int)), this, SLOT(onTimeChanged(int)));
connect(d->playSequencesButton, SIGNAL(triggered()), this, SLOT(onPlaySequences()));
connect(d->nextFrameButton, SIGNAL(triggered()), this, SLOT(onNextFrame()));
connect(d->previousFrameButton, SIGNAL(triggered()), this, SLOT(onPreviousFrame()));
connect(d->spinBox, SIGNAL(valueChanged(int)),this, SLOT(onSpinBoxChanged(int)));
connect(d->stopButton, SIGNAL(triggered()),this, SLOT(onStopButton()));
this->setTitle(tr("Time Management"));
box->setLayout (boxlayout);
this->addWidget (box);
d->minTime = 0.0;
d->minTimeStep = 1.0;
d->maxTime = 0.0;
this->isViewAdded = false;
this->hide();
}
medViewerToolBoxTime::~medViewerToolBoxTime(void)
{
delete d;
d = NULL;
}
void medViewerToolBoxTime::onViewAdded (dtkAbstractView *view)
{
if (!view)
return;
if (med4DAbstractViewInteractor *interactor = dynamic_cast<med4DAbstractViewInteractor*>(view->interactor ("v3dView4DInteractor")))
{
if (!d->views.contains (view))
d->views.append (view);
if (!d->interactors.contains (interactor))
d->interactors.append (interactor);
connect (view, SIGNAL ( dataAdded(dtkAbstractData*)), this, SLOT (onDataAdded (dtkAbstractData*)));
}
this->updateRange();
this->isViewAdded = true;
}
void medViewerToolBoxTime::onDataAdded (dtkAbstractData *data)
{
if (!data)
return;
this->updateRange();
}
void medViewerToolBoxTime::onViewRemoved (dtkAbstractView *view)
{
d->timeLine->stop();
d->timeSlider->setValue(0);
if (!view)
return;
if (med4DAbstractViewInteractor *interactor = dynamic_cast<med4DAbstractViewInteractor*>(view->interactor ("v3dView4DInteractor")))
{
d->views.removeOne (view);
d->interactors.removeOne (interactor);
}
this->updateRange();
this->isViewAdded = false;
}
void medViewerToolBoxTime::AddInteractor (med4DAbstractViewInteractor* interactor)
{
d->interactors.removeOne (interactor);
d->interactors.append (interactor);
}
void medViewerToolBoxTime::RemoveInteractor (med4DAbstractViewInteractor* interactor)
{
d->interactors.removeOne (interactor);
}
void medViewerToolBoxTime::update(dtkAbstractView *view)
{
//JGG qDebug()<<"updating time tb";
medToolBox::update(view);
}
void medViewerToolBoxTime::onPlaySequences ()
{
if ( this->isViewAdded)
{
this->updateRange();
d->timeLine->setDuration((d->maxTime + d->minTimeStep)*(1000/(d->spinBox->value()/100.0)));
if(d->timeLine->state() == QTimeLine::NotRunning)
{
d->timeLine->start();
d->playSequencesButton->setIcon (QPixmap(":/icons/pause.png"));
d->playSequencesButton->setToolTip( tr("Pause Sequence"));
}
else if(d->timeLine->state() == QTimeLine::Paused )
{
d->timeLine->resume();
d->playSequencesButton->setIcon (QPixmap(":/icons/pause.png"));
d->playSequencesButton->setToolTip( tr("Pause Sequence"));
}
else if(d->timeLine->state() == QTimeLine::Running)
{
d->timeLine->setPaused(true);
d->playSequencesButton->setIcon (QPixmap(":/icons/play.png"));
d->playSequencesButton->setToolTip( tr("Play Sequence"));
}
}
}
void medViewerToolBoxTime::onStopButton ()
{
if (d->timeLine->state() == QTimeLine::Running)
{
d->playSequencesButton->setIcon (QPixmap(":/icons/play.png"));
d->playSequencesButton->setToolTip( tr("Play Sequence"));
}
d->timeLine->stop();
d->timeSlider->setValue(0);
}
void medViewerToolBoxTime::onNextFrame ()
{
if ( this->isViewAdded)
d->timeSlider->setValue(d->timeSlider->value()+1);
}
void medViewerToolBoxTime::onPreviousFrame ()
{
if ( this->isViewAdded)
d->timeSlider->setValue(d->timeSlider->value()-1);
}
void medViewerToolBoxTime::onTimeChanged (int val)
{
double time = this->getTimeFromSliderValue (val);
for (int i=0; i<d->interactors.size(); i++)
{
d->interactors[i]->setCurrentTime (time);
}
d->labelcurr->setText( DoubleToQString(( time ) / (d->spinBox->value()/100.0)) + QString(" sec") );
}
void medViewerToolBoxTime::onSpinBoxChanged(int time)
{
this->updateRange();
d->timeLine->setDuration((d->maxTime + d->minTimeStep)*(1000/(time/100.0)));
}
double medViewerToolBoxTime::getTimeFromSliderValue (int s)
{
double value = d->minTime + (double)(s) * (d->minTimeStep);
return value;
}
unsigned int medViewerToolBoxTime::getSliderValueFromTime (double t)
{
unsigned int value = std::ceil ((t - d->minTime) / (d->minTimeStep));
return value;
}
void medViewerToolBoxTime::updateRange (void)
{
if (!d->interactors.size())
return;
double mintime = 3000;
double maxtime = -3000;
double mintimestep = 3000;
for (int i=0; i<d->interactors.size(); i++)
{
double range[2]={0,0};
d->interactors[i]->sequencesRange (range);
mintimestep = std::min (mintimestep, d->interactors[i]->sequencesMinTimeStep ());
mintime = std::min (mintime, range[0]);
maxtime = std::max (maxtime, range[1]);
}
unsigned int numberofsteps = std::ceil ((maxtime - mintime) / (mintimestep) + 1.0);
d->timeSlider->setRange (0, numberofsteps - 1);
d->timeLine->setFrameRange(d->timeSlider->minimum(), d->timeSlider->maximum() );
d->minTime = mintime;
d->minTimeStep = mintimestep;
d->maxTime = maxtime;
d->timeLine->setDuration((maxtime+mintimestep)*1000);
d->labelmin->setText( DoubleToQString(( mintime ) / (d->spinBox->value()/100.0)) + QString(" sec"));
d->labelmax->setText( DoubleToQString(( maxtime ) / (d->spinBox->value()/100.0)) + QString(" sec"));
}
QString medViewerToolBoxTime::DoubleToQString (double val)
{
std::ostringstream strs;
strs << std::fixed << std::setprecision(2)<< val;
std::string str = strs.str();
return QString(str.c_str());
}
void medViewerToolBoxTime::mouseReleaseEvent ( QMouseEvent * mouseEvent)
{
if(mouseEvent->button() == Qt::RightButton)
{
QMenu *menu = new QMenu(this);
QAction *actionNotify = new QAction(tr("Set Speed Increment : "),
this);
actionNotify->setDisabled(true);
menu->addAction(actionNotify);
for (int i = 0; i < d->actionlist.size() ; i++)
{
connect(d->actionlist[i], SIGNAL(triggered()), this, SLOT(onStepIncreased()));
menu->addAction(d->actionlist[i]);
}
menu->exec(mouseEvent->globalPos());
}
}
void medViewerToolBoxTime::onStepIncreased()
{
if (QObject::sender() == d->actionlist[0])
d->spinBox->setSingleStep(1);
else if (QObject::sender() == d->actionlist[1])
d->spinBox->setSingleStep(5);
else if (QObject::sender() == d->actionlist[2])
d->spinBox->setSingleStep(10);
else if (QObject::sender() == d->actionlist[3])
d->spinBox->setSingleStep(25);
else if (QObject::sender() == d->actionlist[4])
d->spinBox->setSingleStep(50);
}
void medViewerToolBoxTime::clear()
{
d->minTime = 0.0;
d->minTimeStep = 1.0;
d->maxTime = 0.0;
d->interactors.clear();
d->views.clear();
}
<commit_msg>Smart pointing what should be smart pointed<commit_after>/* medViewerToolBoxTime.h ---
*
* Author: Fatih Arslan and Nicolas Toussaint
* Change log:
*
*/
#include "medViewerToolBoxTime.h"
#include <iomanip>
#include <cmath>
#include <sstream>
#include <QListWidget>
#include <QList>
#include <QMouseEvent>
#include <dtkCore/dtkAbstractView.h>
#include <dtkCore/dtkLog.h>
#include <dtkCore/dtkSmartPointer.h>
#include <med4DAbstractViewInteractor.h>
#include <medToolBoxTab.h>
#include <medButton.h>
class medViewerToolBoxTimePrivate
{
public:
QSlider *timeSlider;
medButton *playSequencesButton;
medButton *nextFrameButton;
medButton *previousFrameButton;
medButton *stopButton;
QList <QAction*> actionlist;
QList< dtkSmartPointer<dtkAbstractView> > views;
QList<med4DAbstractViewInteractor*> interactors;
QTimeLine *timeLine;
QSpinBox *spinBox;
QLabel *labelmin;
QLabel *labelmax;
QLabel *labelcurr;
QLabel *labelspeed;
double minTime;
double minTimeStep;
double maxTime;
QPixmap playIcon;
};
medViewerToolBoxTime::medViewerToolBoxTime(QWidget *parent) : medToolBox(parent), d(new medViewerToolBoxTimePrivate)
{
QWidget *box = new QWidget (this);
d->labelmin = new QLabel(this);
d->labelmax = new QLabel(this);
d->labelcurr = new QLabel(this);
d->labelspeed = new QLabel(this);
d->labelspeed->setText("Speed %: ");
d->timeSlider = new QSlider (Qt::Horizontal, this);
d->timeSlider->setRange (0, 100);
d->timeSlider->setValue (0);
d->timeSlider->setTracking( false );
d->timeSlider->setToolTip(tr("Follow The Sequence"));
QStringList validDataTypes;
validDataTypes << "itkDataImageChar4"
<< "itkDataImageUChar4"
<< "itkDataImageShort4"
<< "itkDataImageUShort4"
<< "itkDataImageInt4"
<< "itkDataImageUInt4"
<< "itkDataImageLong4"
<< "itkDataImageULong4"
<< "itkDataImageFloat4"
<< "itkDataImageDouble4";
setValidDataTypes(validDataTypes);
d->playIcon = QPixmap(":/icons/play.png");
d->playSequencesButton = new medButton(this,d->playIcon,
tr("Play Sequence"));
d->nextFrameButton = new medButton(this,":/icons/forward.png",
tr("Next Frame"));
d->previousFrameButton = new medButton(this,":/icons/backward.png",
tr("Previous Frame"));
d->stopButton = new medButton(this,":/icons/stop.png",
tr("Stop Sequence"));
d->timeLine = new QTimeLine(1000, this);
d->timeLine->setLoopCount(0);
d->timeLine->setCurveShape (QTimeLine::LinearCurve);
d->spinBox = new QSpinBox(this);
d->spinBox->setRange(1,5000);
d->spinBox->setSingleStep(10);
d->spinBox->setValue(100);
d->spinBox->setToolTip(tr("Control the display speed"));
connect(d->timeLine, SIGNAL(frameChanged(int)), d->timeSlider, SLOT(setValue(int)));
QHBoxLayout *buttonLayout = new QHBoxLayout();
buttonLayout->addWidget( d->previousFrameButton,1,Qt::AlignHCenter);
buttonLayout->addWidget (d->playSequencesButton,1,Qt::AlignHCenter);
buttonLayout->addWidget( d->nextFrameButton,1,Qt::AlignHCenter);
buttonLayout->addWidget( d->stopButton,1,Qt::AlignHCenter);
QHBoxLayout *labelLayout = new QHBoxLayout();
labelLayout->addWidget( d->labelmin);
labelLayout->addStretch();
labelLayout->addWidget( d->labelcurr);
labelLayout->addStretch();
labelLayout->addWidget( d->labelmax);
QHBoxLayout *topLayout = new QHBoxLayout();
topLayout->addStretch();
topLayout->addWidget(d->labelspeed);
topLayout->addWidget(d->spinBox);
QVBoxLayout* boxlayout = new QVBoxLayout ();
boxlayout->addLayout(topLayout);
boxlayout->addLayout( buttonLayout );
boxlayout->addWidget (d->timeSlider);
boxlayout->addLayout(labelLayout);
d->actionlist.insert(0,new QAction("1",this));
d->actionlist.insert(1,new QAction("5",this));
d->actionlist.insert(2,new QAction("10",this));
d->actionlist.insert(3,new QAction("25",this));
d->actionlist.insert(4,new QAction("50",this));
connect(d->timeSlider, SIGNAL(sliderMoved(int)), this, SLOT(onTimeChanged(int)));
connect(d->timeSlider, SIGNAL(valueChanged(int)), this, SLOT(onTimeChanged(int)));
connect(d->playSequencesButton, SIGNAL(triggered()), this, SLOT(onPlaySequences()));
connect(d->nextFrameButton, SIGNAL(triggered()), this, SLOT(onNextFrame()));
connect(d->previousFrameButton, SIGNAL(triggered()), this, SLOT(onPreviousFrame()));
connect(d->spinBox, SIGNAL(valueChanged(int)),this, SLOT(onSpinBoxChanged(int)));
connect(d->stopButton, SIGNAL(triggered()),this, SLOT(onStopButton()));
this->setTitle(tr("Time Management"));
box->setLayout (boxlayout);
this->addWidget (box);
d->minTime = 0.0;
d->minTimeStep = 1.0;
d->maxTime = 0.0;
this->isViewAdded = false;
this->hide();
}
medViewerToolBoxTime::~medViewerToolBoxTime(void)
{
delete d;
d = NULL;
}
void medViewerToolBoxTime::onViewAdded (dtkAbstractView *view)
{
if (!view)
return;
if (med4DAbstractViewInteractor *interactor = dynamic_cast<med4DAbstractViewInteractor*>(view->interactor ("v3dView4DInteractor")))
{
if (!d->views.contains (view))
d->views.append (view);
if (!d->interactors.contains (interactor))
d->interactors.append (interactor);
connect (view, SIGNAL ( dataAdded(dtkAbstractData*)), this, SLOT (onDataAdded (dtkAbstractData*)));
}
this->updateRange();
this->isViewAdded = true;
}
void medViewerToolBoxTime::onDataAdded (dtkAbstractData *data)
{
if (!data)
return;
this->updateRange();
}
void medViewerToolBoxTime::onViewRemoved (dtkAbstractView *view)
{
d->timeLine->stop();
d->timeSlider->setValue(0);
if (!view)
return;
if (med4DAbstractViewInteractor *interactor = dynamic_cast<med4DAbstractViewInteractor*>(view->interactor ("v3dView4DInteractor")))
{
d->views.removeOne (view);
d->interactors.removeOne (interactor);
}
this->updateRange();
this->isViewAdded = false;
}
void medViewerToolBoxTime::AddInteractor (med4DAbstractViewInteractor* interactor)
{
d->interactors.removeOne (interactor);
d->interactors.append (interactor);
}
void medViewerToolBoxTime::RemoveInteractor (med4DAbstractViewInteractor* interactor)
{
d->interactors.removeOne (interactor);
}
void medViewerToolBoxTime::update(dtkAbstractView *view)
{
//JGG qDebug()<<"updating time tb";
medToolBox::update(view);
}
void medViewerToolBoxTime::onPlaySequences ()
{
if ( this->isViewAdded)
{
this->updateRange();
d->timeLine->setDuration((d->maxTime + d->minTimeStep)*(1000/(d->spinBox->value()/100.0)));
if(d->timeLine->state() == QTimeLine::NotRunning)
{
d->timeLine->start();
d->playSequencesButton->setIcon (QPixmap(":/icons/pause.png"));
d->playSequencesButton->setToolTip( tr("Pause Sequence"));
}
else if(d->timeLine->state() == QTimeLine::Paused )
{
d->timeLine->resume();
d->playSequencesButton->setIcon (QPixmap(":/icons/pause.png"));
d->playSequencesButton->setToolTip( tr("Pause Sequence"));
}
else if(d->timeLine->state() == QTimeLine::Running)
{
d->timeLine->setPaused(true);
d->playSequencesButton->setIcon (QPixmap(":/icons/play.png"));
d->playSequencesButton->setToolTip( tr("Play Sequence"));
}
}
}
void medViewerToolBoxTime::onStopButton ()
{
if (d->timeLine->state() == QTimeLine::Running)
{
d->playSequencesButton->setIcon (QPixmap(":/icons/play.png"));
d->playSequencesButton->setToolTip( tr("Play Sequence"));
}
d->timeLine->stop();
d->timeSlider->setValue(0);
}
void medViewerToolBoxTime::onNextFrame ()
{
if ( this->isViewAdded)
d->timeSlider->setValue(d->timeSlider->value()+1);
}
void medViewerToolBoxTime::onPreviousFrame ()
{
if ( this->isViewAdded)
d->timeSlider->setValue(d->timeSlider->value()-1);
}
void medViewerToolBoxTime::onTimeChanged (int val)
{
double time = this->getTimeFromSliderValue (val);
for (int i=0; i<d->interactors.size(); i++)
{
d->interactors[i]->setCurrentTime (time);
}
d->labelcurr->setText( DoubleToQString(( time ) / (d->spinBox->value()/100.0)) + QString(" sec") );
}
void medViewerToolBoxTime::onSpinBoxChanged(int time)
{
this->updateRange();
d->timeLine->setDuration((d->maxTime + d->minTimeStep)*(1000/(time/100.0)));
}
double medViewerToolBoxTime::getTimeFromSliderValue (int s)
{
double value = d->minTime + (double)(s) * (d->minTimeStep);
return value;
}
unsigned int medViewerToolBoxTime::getSliderValueFromTime (double t)
{
unsigned int value = std::ceil ((t - d->minTime) / (d->minTimeStep));
return value;
}
void medViewerToolBoxTime::updateRange (void)
{
if (!d->interactors.size())
return;
double mintime = 3000;
double maxtime = -3000;
double mintimestep = 3000;
for (int i=0; i<d->interactors.size(); i++)
{
double range[2]={0,0};
d->interactors[i]->sequencesRange (range);
mintimestep = std::min (mintimestep, d->interactors[i]->sequencesMinTimeStep ());
mintime = std::min (mintime, range[0]);
maxtime = std::max (maxtime, range[1]);
}
unsigned int numberofsteps = std::ceil ((maxtime - mintime) / (mintimestep) + 1.0);
d->timeSlider->setRange (0, numberofsteps - 1);
d->timeLine->setFrameRange(d->timeSlider->minimum(), d->timeSlider->maximum() );
d->minTime = mintime;
d->minTimeStep = mintimestep;
d->maxTime = maxtime;
d->timeLine->setDuration((maxtime+mintimestep)*1000);
d->labelmin->setText( DoubleToQString(( mintime ) / (d->spinBox->value()/100.0)) + QString(" sec"));
d->labelmax->setText( DoubleToQString(( maxtime ) / (d->spinBox->value()/100.0)) + QString(" sec"));
}
QString medViewerToolBoxTime::DoubleToQString (double val)
{
std::ostringstream strs;
strs << std::fixed << std::setprecision(2)<< val;
std::string str = strs.str();
return QString(str.c_str());
}
void medViewerToolBoxTime::mouseReleaseEvent ( QMouseEvent * mouseEvent)
{
if(mouseEvent->button() == Qt::RightButton)
{
QMenu *menu = new QMenu(this);
QAction *actionNotify = new QAction(tr("Set Speed Increment : "),
this);
actionNotify->setDisabled(true);
menu->addAction(actionNotify);
for (int i = 0; i < d->actionlist.size() ; i++)
{
connect(d->actionlist[i], SIGNAL(triggered()), this, SLOT(onStepIncreased()));
menu->addAction(d->actionlist[i]);
}
menu->exec(mouseEvent->globalPos());
}
}
void medViewerToolBoxTime::onStepIncreased()
{
if (QObject::sender() == d->actionlist[0])
d->spinBox->setSingleStep(1);
else if (QObject::sender() == d->actionlist[1])
d->spinBox->setSingleStep(5);
else if (QObject::sender() == d->actionlist[2])
d->spinBox->setSingleStep(10);
else if (QObject::sender() == d->actionlist[3])
d->spinBox->setSingleStep(25);
else if (QObject::sender() == d->actionlist[4])
d->spinBox->setSingleStep(50);
}
void medViewerToolBoxTime::clear()
{
d->minTime = 0.0;
d->minTimeStep = 1.0;
d->maxTime = 0.0;
d->interactors.clear();
d->views.clear();
}
<|endoftext|>
|
<commit_before>// $Id: patch_recovery_error_estimator.C,v 1.21 2007-01-22 23:36:07 roystgnr Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson
// 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
// C++ includes
#include <algorithm> // for std::fill
#include <cmath> // for std::sqrt std::pow std::abs
// Local Includes
#include "libmesh_common.h"
#include "patch_recovery_error_estimator.h"
#include "dof_map.h"
#include "fe.h"
#include "dense_matrix.h"
#include "dense_vector.h"
#include "error_vector.h"
#include "quadrature_gauss.h"
#include "libmesh_logging.h"
#include "elem.h"
#include "patch.h"
#include "quadrature_grid.h"
#include "system.h"
#include "mesh.h"
//-----------------------------------------------------------------
// PatchRecoveryErrorEstimator implementations
std::vector<Real> PatchRecoveryErrorEstimator::specpoly(const unsigned int dim,
const Order order,
const Point p,
const unsigned int matsize)
{
std::vector<Real> psi;
psi.reserve(matsize);
Real x = p(0), y, z;
if (dim > 1)
y = p(1);
if (dim > 2)
z = p(2);
// builds psi vector of form 1 x y z x^2 xy xz y^2 yz z^2 etc..
// I haven't added 1D support here
for (unsigned int poly_deg=0; poly_deg <= static_cast<unsigned int>(order) ; poly_deg++)
{ // loop over all polynomials of total degreee = poly_deg
switch (dim)
{
// 3D spectral polynomial basis functions
case 3:
{
for (int xexp=poly_deg; xexp >= 0; xexp--) // use an int for xexp since we -- it
for (int yexp=poly_deg-xexp; yexp >= 0; yexp--)
{
int zexp = poly_deg - xexp - yexp;
psi.push_back(std::pow(x,xexp)*std::pow(y,yexp)*std::pow(z,zexp));
}
break;
}
// 2D spectral polynomial basis functions
case 2:
{
for (int xexp=poly_deg; xexp >= 0; xexp--) // use an int for xexp since we -- it
{
int yexp = poly_deg - xexp;
psi.push_back(std::pow(x,xexp)*std::pow(y,yexp));
}
break;
}
// 1D spectral polynomial basis functions
case 1:
{
int xexp = poly_deg;
psi.push_back(std::pow(x,xexp));
break;
}
default:
error();
}
}
return psi;
}
void PatchRecoveryErrorEstimator::estimate_error (const System& system,
ErrorVector& error_per_cell,
bool)
{
START_LOG("estimate_error()", "PatchRecoveryErrorEstimator");
// The current mesh
const Mesh& mesh = system.get_mesh();
// The dimensionality of the mesh
const unsigned int dim = mesh.mesh_dimension();
// The number of variables in the system
const unsigned int n_vars = system.n_vars();
// The DofMap for this system
const DofMap& dof_map = system.get_dof_map();
// Resize the error_per_cell vector to be
// the number of elements, initialize it to 0.
error_per_cell.resize (mesh.n_elem());
std::fill (error_per_cell.begin(), error_per_cell.end(), 0.);
// Check for the use of component_mask
this->convert_component_mask_to_scale();
// Check for a valid component_scale
if (!component_scale.empty())
if (component_scale.size() != n_vars)
{
std::cerr << "ERROR: component_scale is the wrong size:"
<< std::endl
<< " component_scale.size()=" << component_scale.size()
<< std::endl
<< ", n_vars=" << n_vars
<< std::endl;
error();
}
//------------------------------------------------------------
// Iterate over all the active elements in the mesh
// that live on this processor.
MeshBase::const_element_iterator elem_it = mesh.active_local_elements_begin();
const MeshBase::const_element_iterator elem_end = mesh.active_local_elements_end();
for (; elem_it != elem_end; ++elem_it)
{
// elem is necessarily an active element on the local processor
const Elem* elem = *elem_it;
// Build a patch containing the current element
// and its neighbors on the local processor
Patch patch;
// We log the time spent building patches separately
PAUSE_LOG("estimate_error()", "PatchRecoveryErrorEstimator");
// Use default patch size and growth strategy
patch.build_around_element (elem);
RESTART_LOG("estimate_error()", "PatchRecoveryErrorEstimator");
//------------------------------------------------------------
// Process each variable in the system using the current patch
for (unsigned int var=0; var<n_vars; var++)
{
// Possibly skip this variable
if (!component_scale.empty())
if (component_scale[var] == 0.0) continue;
// The type of finite element to use for this variable
const FEType& fe_type = dof_map.variable_type (var);
const Order element_order = static_cast<Order>
(fe_type.order + elem->p_level());
// Finite element object for use in this patch
AutoPtr<FEBase> fe (FEBase::build (dim, fe_type));
// Build an appropriate Gaussian quadrature rule
AutoPtr<QBase> qrule (fe_type.default_quadrature_rule(dim));
// Tell the finite element about the quadrature rule.
fe->attach_quadrature_rule (qrule.get());
// Get Jacobian values, etc..
const std::vector<Real>& JxW = fe->get_JxW();
const std::vector<Point>& q_point = fe->get_xyz();
const std::vector<std::vector<Real> >& phi = fe->get_phi();
const std::vector<std::vector<RealGradient> >& dphi = fe->get_dphi();
// global DOF indices
std::vector<unsigned int> dof_indices;
// Compute the approprite size for the patch projection matrices
// and vectors;
unsigned int matsize;
switch (dim)
{
case 3:
{
matsize = (element_order + 1)*
(element_order + 2)*
(element_order + 3)/6;
break;
}
case 2:
{
matsize = (element_order + 1)*
(element_order + 2)/2;
break;
}
case 1:
{
matsize = element_order + 1;
break;
}
default:
error();
}
DenseMatrix<Number> Kp(matsize,matsize);
DenseVector<Number>
Fx(matsize), Pu_x_h(matsize),
Fy(matsize), Pu_y_h(matsize),
Fz(matsize), Pu_z_h(matsize);
//------------------------------------------------------
// Loop over each element in the patch and compute their
// contribution to the patch gradient projection.
Patch::const_iterator patch_it = patch.begin();
const Patch::const_iterator patch_end = patch.end();
for (; patch_it != patch_end; ++patch_it)
{
// The pth element in the patch
const Elem* e_p = *patch_it;
// Reinitialize the finite element data for this element
fe->reinit (e_p);
// Get the global DOF indices for the current variable
// in the current element
dof_map.dof_indices (e_p, dof_indices, var);
assert (dof_indices.size() == phi.size());
const unsigned int n_dofs = dof_indices.size();
const unsigned int n_qp = qrule->n_points();
// Compute the projection components from this cell.
// \int_{Omega_e} \psi_i \psi_j = \int_{Omega_e} du_h/dx_k \psi_i
for (unsigned int qp=0; qp<n_qp; qp++)
{
// Compute the gradient on the current patch element
// at the quadrature point
Gradient grad_u_h;
for (unsigned int i=0; i<n_dofs; i++)
// grad_u_h += dphi[i][qp]*system.current_solution(dof_indices[i]);
grad_u_h.add_scaled (dphi[i][qp],
system.current_solution(dof_indices[i]));
// Construct the shape function values for the patch projection
std::vector<Real> psi(specpoly(dim, element_order, q_point[qp], matsize));
// Patch matrix contribution
for (unsigned int i=0; i<Kp.m(); i++)
for (unsigned int j=0; j<Kp.n(); j++)
Kp(i,j) += JxW[qp]*psi[i]*psi[j];
// Patch RHS contributions
for (unsigned int i=0; i<psi.size(); i++)
{
Fx(i) += JxW[qp]*grad_u_h(0)*psi[i];
Fy(i) += JxW[qp]*grad_u_h(1)*psi[i];
Fz(i) += JxW[qp]*grad_u_h(2)*psi[i];
}
} // end quadrature loop
} // end patch loop
//--------------------------------------------------
// Now we have fully assembled the projection system
// for this patch. Project the gradient components.
// MAY NEED TO USE PARTIAL PIVOTING!
Kp.lu_solve (Fx, Pu_x_h);
Kp.lu_solve (Fy, Pu_y_h);
Kp.lu_solve (Fz, Pu_z_h);
//--------------------------------------------------
// Finally, estimate the error in the current variable
// for the current element by computing ||Pgrad_u_h - grad_u_h||
fe->reinit(elem);
//reinitialize element
dof_map.dof_indices (elem, dof_indices, var);
const unsigned int n_dofs = dof_indices.size();
// For linear elments, grad is a constant, so we need to compute
// grad u_h once on the element. Also as G_H u_h - gradu_h is linear
// on an element, it assumes its maximum at a vertex of the element
Real error = 0;
// we approximate the max norm by sampling over a set of points
// in future we may add specialized routines for specific cases
// or use some optimization package
const Order qorder = element_order;
// build a "fake" quadrature rule for the element
QGrid samprule (dim, qorder);
fe->attach_quadrature_rule (&samprule);
fe->reinit(elem);
const std::vector<Point>& samppt = fe->get_xyz();
const std::vector<std::vector<RealGradient> >& dphi2 = fe->get_dphi();
const unsigned int n_sp = samprule.n_points();
for (unsigned int sp=0; sp< n_sp; sp++)
{
// Real temperrx=0,temperry=0,temperrz=0;
Number temperrx=0,temperry=0,temperrz=0;
// Comput the gradient at the current sample point
Gradient grad_u_h;
for (unsigned int i=0; i<n_dofs; i++)
grad_u_h.add_scaled (dphi2[i][sp],
system.current_solution(dof_indices[i]));
// Compute the phi values at the current sample point
std::vector<Real> psi(specpoly(dim,element_order, samppt[sp], matsize));
for (unsigned int i=0; i<matsize; i++)
{
temperrx += psi[i]*Pu_x_h(i);
temperry += psi[i]*Pu_y_h(i);
temperrz += psi[i]*Pu_z_h(i);
}
temperrx -= grad_u_h(0);
temperry -= grad_u_h(1);
temperrz -= grad_u_h(2);
// temperrx = std::abs(temperrx);
// temperry = std::abs(temperry);
// temperrz = std::abs(temperrz);
// error = std::max(temperrz,std::max(temperry,temperrx));
error = std::max(std::abs(temperrz),
std::max(std::abs(temperry),
std::abs(temperrx)));
} // end sample_point_loop
const int e_id=elem->id();
error_per_cell[e_id] += error;
} // end variable loop
} // end element loop
// Each processor has now computed the error contribuions
// for its local elements, and error_per_cell contains 0 for all the
// non-local elements. Summing the vector will provide the L_oo value
// for each element, local or remote
this->reduce_error(error_per_cell);
STOP_LOG("estimate_error()", "PatchRecoveryErrorEstimator");
}
<commit_msg>Fix non-initialized variable warning.<commit_after>// $Id: patch_recovery_error_estimator.C,v 1.22 2007-02-09 22:27:20 jwpeterson Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson
// 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
// C++ includes
#include <algorithm> // for std::fill
#include <cmath> // for std::sqrt std::pow std::abs
// Local Includes
#include "libmesh_common.h"
#include "patch_recovery_error_estimator.h"
#include "dof_map.h"
#include "fe.h"
#include "dense_matrix.h"
#include "dense_vector.h"
#include "error_vector.h"
#include "quadrature_gauss.h"
#include "libmesh_logging.h"
#include "elem.h"
#include "patch.h"
#include "quadrature_grid.h"
#include "system.h"
#include "mesh.h"
//-----------------------------------------------------------------
// PatchRecoveryErrorEstimator implementations
std::vector<Real> PatchRecoveryErrorEstimator::specpoly(const unsigned int dim,
const Order order,
const Point p,
const unsigned int matsize)
{
std::vector<Real> psi;
psi.reserve(matsize);
Real x = p(0), y=0., z=0.;
if (dim > 1)
y = p(1);
if (dim > 2)
z = p(2);
// builds psi vector of form 1 x y z x^2 xy xz y^2 yz z^2 etc..
// I haven't added 1D support here
for (unsigned int poly_deg=0; poly_deg <= static_cast<unsigned int>(order) ; poly_deg++)
{ // loop over all polynomials of total degreee = poly_deg
switch (dim)
{
// 3D spectral polynomial basis functions
case 3:
{
for (int xexp=poly_deg; xexp >= 0; xexp--) // use an int for xexp since we -- it
for (int yexp=poly_deg-xexp; yexp >= 0; yexp--)
{
int zexp = poly_deg - xexp - yexp;
psi.push_back(std::pow(x,xexp)*std::pow(y,yexp)*std::pow(z,zexp));
}
break;
}
// 2D spectral polynomial basis functions
case 2:
{
for (int xexp=poly_deg; xexp >= 0; xexp--) // use an int for xexp since we -- it
{
int yexp = poly_deg - xexp;
psi.push_back(std::pow(x,xexp)*std::pow(y,yexp));
}
break;
}
// 1D spectral polynomial basis functions
case 1:
{
int xexp = poly_deg;
psi.push_back(std::pow(x,xexp));
break;
}
default:
error();
}
}
return psi;
}
void PatchRecoveryErrorEstimator::estimate_error (const System& system,
ErrorVector& error_per_cell,
bool)
{
START_LOG("estimate_error()", "PatchRecoveryErrorEstimator");
// The current mesh
const Mesh& mesh = system.get_mesh();
// The dimensionality of the mesh
const unsigned int dim = mesh.mesh_dimension();
// The number of variables in the system
const unsigned int n_vars = system.n_vars();
// The DofMap for this system
const DofMap& dof_map = system.get_dof_map();
// Resize the error_per_cell vector to be
// the number of elements, initialize it to 0.
error_per_cell.resize (mesh.n_elem());
std::fill (error_per_cell.begin(), error_per_cell.end(), 0.);
// Check for the use of component_mask
this->convert_component_mask_to_scale();
// Check for a valid component_scale
if (!component_scale.empty())
if (component_scale.size() != n_vars)
{
std::cerr << "ERROR: component_scale is the wrong size:"
<< std::endl
<< " component_scale.size()=" << component_scale.size()
<< std::endl
<< ", n_vars=" << n_vars
<< std::endl;
error();
}
//------------------------------------------------------------
// Iterate over all the active elements in the mesh
// that live on this processor.
MeshBase::const_element_iterator elem_it = mesh.active_local_elements_begin();
const MeshBase::const_element_iterator elem_end = mesh.active_local_elements_end();
for (; elem_it != elem_end; ++elem_it)
{
// elem is necessarily an active element on the local processor
const Elem* elem = *elem_it;
// Build a patch containing the current element
// and its neighbors on the local processor
Patch patch;
// We log the time spent building patches separately
PAUSE_LOG("estimate_error()", "PatchRecoveryErrorEstimator");
// Use default patch size and growth strategy
patch.build_around_element (elem);
RESTART_LOG("estimate_error()", "PatchRecoveryErrorEstimator");
//------------------------------------------------------------
// Process each variable in the system using the current patch
for (unsigned int var=0; var<n_vars; var++)
{
// Possibly skip this variable
if (!component_scale.empty())
if (component_scale[var] == 0.0) continue;
// The type of finite element to use for this variable
const FEType& fe_type = dof_map.variable_type (var);
const Order element_order = static_cast<Order>
(fe_type.order + elem->p_level());
// Finite element object for use in this patch
AutoPtr<FEBase> fe (FEBase::build (dim, fe_type));
// Build an appropriate Gaussian quadrature rule
AutoPtr<QBase> qrule (fe_type.default_quadrature_rule(dim));
// Tell the finite element about the quadrature rule.
fe->attach_quadrature_rule (qrule.get());
// Get Jacobian values, etc..
const std::vector<Real>& JxW = fe->get_JxW();
const std::vector<Point>& q_point = fe->get_xyz();
const std::vector<std::vector<Real> >& phi = fe->get_phi();
const std::vector<std::vector<RealGradient> >& dphi = fe->get_dphi();
// global DOF indices
std::vector<unsigned int> dof_indices;
// Compute the approprite size for the patch projection matrices
// and vectors;
unsigned int matsize;
switch (dim)
{
case 3:
{
matsize = (element_order + 1)*
(element_order + 2)*
(element_order + 3)/6;
break;
}
case 2:
{
matsize = (element_order + 1)*
(element_order + 2)/2;
break;
}
case 1:
{
matsize = element_order + 1;
break;
}
default:
error();
}
DenseMatrix<Number> Kp(matsize,matsize);
DenseVector<Number>
Fx(matsize), Pu_x_h(matsize),
Fy(matsize), Pu_y_h(matsize),
Fz(matsize), Pu_z_h(matsize);
//------------------------------------------------------
// Loop over each element in the patch and compute their
// contribution to the patch gradient projection.
Patch::const_iterator patch_it = patch.begin();
const Patch::const_iterator patch_end = patch.end();
for (; patch_it != patch_end; ++patch_it)
{
// The pth element in the patch
const Elem* e_p = *patch_it;
// Reinitialize the finite element data for this element
fe->reinit (e_p);
// Get the global DOF indices for the current variable
// in the current element
dof_map.dof_indices (e_p, dof_indices, var);
assert (dof_indices.size() == phi.size());
const unsigned int n_dofs = dof_indices.size();
const unsigned int n_qp = qrule->n_points();
// Compute the projection components from this cell.
// \int_{Omega_e} \psi_i \psi_j = \int_{Omega_e} du_h/dx_k \psi_i
for (unsigned int qp=0; qp<n_qp; qp++)
{
// Compute the gradient on the current patch element
// at the quadrature point
Gradient grad_u_h;
for (unsigned int i=0; i<n_dofs; i++)
// grad_u_h += dphi[i][qp]*system.current_solution(dof_indices[i]);
grad_u_h.add_scaled (dphi[i][qp],
system.current_solution(dof_indices[i]));
// Construct the shape function values for the patch projection
std::vector<Real> psi(specpoly(dim, element_order, q_point[qp], matsize));
// Patch matrix contribution
for (unsigned int i=0; i<Kp.m(); i++)
for (unsigned int j=0; j<Kp.n(); j++)
Kp(i,j) += JxW[qp]*psi[i]*psi[j];
// Patch RHS contributions
for (unsigned int i=0; i<psi.size(); i++)
{
Fx(i) += JxW[qp]*grad_u_h(0)*psi[i];
Fy(i) += JxW[qp]*grad_u_h(1)*psi[i];
Fz(i) += JxW[qp]*grad_u_h(2)*psi[i];
}
} // end quadrature loop
} // end patch loop
//--------------------------------------------------
// Now we have fully assembled the projection system
// for this patch. Project the gradient components.
// MAY NEED TO USE PARTIAL PIVOTING!
Kp.lu_solve (Fx, Pu_x_h);
Kp.lu_solve (Fy, Pu_y_h);
Kp.lu_solve (Fz, Pu_z_h);
//--------------------------------------------------
// Finally, estimate the error in the current variable
// for the current element by computing ||Pgrad_u_h - grad_u_h||
fe->reinit(elem);
//reinitialize element
dof_map.dof_indices (elem, dof_indices, var);
const unsigned int n_dofs = dof_indices.size();
// For linear elments, grad is a constant, so we need to compute
// grad u_h once on the element. Also as G_H u_h - gradu_h is linear
// on an element, it assumes its maximum at a vertex of the element
Real error = 0;
// we approximate the max norm by sampling over a set of points
// in future we may add specialized routines for specific cases
// or use some optimization package
const Order qorder = element_order;
// build a "fake" quadrature rule for the element
QGrid samprule (dim, qorder);
fe->attach_quadrature_rule (&samprule);
fe->reinit(elem);
const std::vector<Point>& samppt = fe->get_xyz();
const std::vector<std::vector<RealGradient> >& dphi2 = fe->get_dphi();
const unsigned int n_sp = samprule.n_points();
for (unsigned int sp=0; sp< n_sp; sp++)
{
// Real temperrx=0,temperry=0,temperrz=0;
Number temperrx=0,temperry=0,temperrz=0;
// Comput the gradient at the current sample point
Gradient grad_u_h;
for (unsigned int i=0; i<n_dofs; i++)
grad_u_h.add_scaled (dphi2[i][sp],
system.current_solution(dof_indices[i]));
// Compute the phi values at the current sample point
std::vector<Real> psi(specpoly(dim,element_order, samppt[sp], matsize));
for (unsigned int i=0; i<matsize; i++)
{
temperrx += psi[i]*Pu_x_h(i);
temperry += psi[i]*Pu_y_h(i);
temperrz += psi[i]*Pu_z_h(i);
}
temperrx -= grad_u_h(0);
temperry -= grad_u_h(1);
temperrz -= grad_u_h(2);
// temperrx = std::abs(temperrx);
// temperry = std::abs(temperry);
// temperrz = std::abs(temperrz);
// error = std::max(temperrz,std::max(temperry,temperrx));
error = std::max(std::abs(temperrz),
std::max(std::abs(temperry),
std::abs(temperrx)));
} // end sample_point_loop
const int e_id=elem->id();
error_per_cell[e_id] += error;
} // end variable loop
} // end element loop
// Each processor has now computed the error contribuions
// for its local elements, and error_per_cell contains 0 for all the
// non-local elements. Summing the vector will provide the L_oo value
// for each element, local or remote
this->reduce_error(error_per_cell);
STOP_LOG("estimate_error()", "PatchRecoveryErrorEstimator");
}
<|endoftext|>
|
<commit_before>#include <boost/test/unit_test.hpp>
#include <boost/lexical_cast.hpp>
struct Interface {
std::string to_string(int i) const { throw std::runtime_error("Not implemented!"); }
};
template <class Derived>
struct printer {
~printer() {
static_assert(
std::is_base_of<Interface, Derived>::value,
"Derived must implement Interface!");
static_assert(
std::is_base_of<printer, Derived>::value,
"Derived must derive from printer!");
static_assert(
std::is_base_of<Interface, Derived>::value,
"Derived must not be Interface!");
}
std::string to_string(int i) const { return static_cast<const Derived*>(this)->to_string(i); }
};
struct Implementation : printer<Implementation>, Interface {
std::string to_string(int i) const { return boost::lexical_cast<std::string>(i); }
};
struct Implementation2 : printer<Implementation> {
std::string to_string(int i) const { return boost::lexical_cast<std::string>(i); }
};
BOOST_AUTO_TEST_CASE( test_static_polymorphism )
{
printer<Implementation> p;
std::string r = p.to_string(1);
BOOST_REQUIRE_EQUAL("1", r);
//printer<Implementation2> p2;
}
<commit_msg>Commented out breaking test<commit_after>#include <boost/test/unit_test.hpp>
#include <boost/lexical_cast.hpp>
struct Interface {
std::string to_string(int i) const { throw std::runtime_error("Not implemented!"); }
};
template <class Derived>
struct printer {
~printer() {
static_assert(
std::is_base_of<Interface, Derived>::value,
"Derived must implement Interface!");
static_assert(
std::is_base_of<printer, Derived>::value,
"Derived must derive from printer!");
static_assert(
std::is_base_of<Interface, Derived>::value,
"Derived must not be Interface!");
}
std::string to_string(int i) const { return static_cast<const Derived*>(this)->to_string(i); }
};
struct Implementation : printer<Implementation>, Interface {
std::string to_string(int i) const { return boost::lexical_cast<std::string>(i); }
};
struct Implementation2 : printer<Implementation> {
std::string to_string(int i) const { return boost::lexical_cast<std::string>(i); }
};
BOOST_AUTO_TEST_CASE( test_static_polymorphism )
{
printer<Implementation> p;
std::string r = p.to_string(1);
BOOST_REQUIRE_EQUAL("1", r);
//Interface* pi = reinterpret_cast<Interface*>(&p);
//std::string s = pi->to_string(2);
//BOOST_REQUIRE_EQUAL("2", r);
//printer<Implementation2> p2;
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <svx/svdpagv.hxx>
#include <svx/svdview.hxx>
#include <svx/ruler.hxx>
#include <idxmrk.hxx>
#include <view.hxx>
#include <wrtsh.hxx>
#include <swmodule.hxx>
#include <viewopt.hxx>
#include <docsh.hxx>
#include <globdoc.hxx>
#include <navipi.hxx>
#include <fldwrap.hxx>
#include <redlndlg.hxx>
#include <dpage.hxx>
#include <edtwin.hxx>
#include "formatclipboard.hxx"
#include <cmdid.h>
// header for class SfxRequest
#include <sfx2/request.hxx>
#include <sfx2/viewfrm.hxx>
extern int bDocSzUpdated;
void SwView::Activate(sal_Bool bMDIActivate)
{
// aktuelle View anmelden an der DocShell
// die View bleibt solange an der DocShell
// aktiv bis Sie zerstoert wird oder durch Activate eine
// neue gesetzt wird
SwDocShell* pDocSh = GetDocShell();
if(pDocSh)
pDocSh->SetView(this);
SwModule* pSwMod = SW_MOD();
pSwMod->SetView(this);
// Dokumentgroesse hat sich geaendert
if(!bDocSzUpdated)
DocSzChgd(aDocSz);
// make selection visible
if(bMakeSelectionVisible)
{
pWrtShell->MakeSelVisible();
bMakeSelectionVisible = sal_False;
}
pHRuler->SetActive( sal_True );
pVRuler->SetActive( sal_True );
if ( bMDIActivate )
{
pWrtShell->ShGetFcs(sal_False); // Selektionen sichtbar
if( sSwViewData.Len() )
{
ReadUserData( sSwViewData, sal_False );
sSwViewData.Erase();
}
AttrChangedNotify(pWrtShell);
// Flddlg ggf neu initialisieren (z.B. fuer TYP_SETVAR)
sal_uInt16 nId = SwFldDlgWrapper::GetChildWindowId();
SfxViewFrame* pVFrame = GetViewFrame();
SwFldDlgWrapper *pWrp = (SwFldDlgWrapper*)pVFrame->GetChildWindow(nId);
if (pWrp)
pWrp->ReInitDlg(GetDocShell());
// RedlineDlg ggf neu initialisieren
nId = SwRedlineAcceptChild::GetChildWindowId();
SwRedlineAcceptChild *pRed = (SwRedlineAcceptChild*)pVFrame->GetChildWindow(nId);
if (pRed)
pRed->ReInitDlg(GetDocShell());
// reinit IdxMarkDlg
nId = SwInsertIdxMarkWrapper::GetChildWindowId();
SwInsertIdxMarkWrapper *pIdxMrk = (SwInsertIdxMarkWrapper*)pVFrame->GetChildWindow(nId);
if (pIdxMrk)
pIdxMrk->ReInitDlg(*pWrtShell);
// reinit AuthMarkDlg
nId = SwInsertAuthMarkWrapper::GetChildWindowId();
SwInsertAuthMarkWrapper *pAuthMrk = (SwInsertAuthMarkWrapper*)pVFrame->
GetChildWindow(nId);
if (pAuthMrk)
pAuthMrk->ReInitDlg(*pWrtShell);
}
else
//Wenigstens das Notify rufen (vorsichtshalber wegen der SlotFilter
AttrChangedNotify(pWrtShell);
SfxViewShell::Activate(bMDIActivate);
}
void SwView::Deactivate(sal_Bool bMDIActivate)
{
extern sal_Bool bFlushCharBuffer ;
// Befinden sich noch Zeichen im Input Buffer?
if( bFlushCharBuffer )
GetEditWin().FlushInBuffer();
if( bMDIActivate )
{
pWrtShell->ShLooseFcs(); // Selektionen unsichtbar
pHRuler->SetActive( sal_False );
pVRuler->SetActive( sal_False );
}
SfxViewShell::Deactivate(bMDIActivate);
}
void SwView::MarginChanged()
{
GetWrtShell().SetBrowseBorder( GetMargin() );
}
void SwView::ExecFormatPaintbrush(SfxRequest& rReq)
{
if(!pFormatClipboard)
return;
if( pFormatClipboard->HasContent() )
{
pFormatClipboard->Erase();
SwApplyTemplate aTemplate;
GetEditWin().SetApplyTemplate(aTemplate);
}
else
{
bool bPersistentCopy = false;
const SfxItemSet *pArgs = rReq.GetArgs();
if( pArgs && pArgs->Count() >= 1 )
{
bPersistentCopy = static_cast<bool>(((SfxBoolItem &)pArgs->Get(
SID_FORMATPAINTBRUSH)).GetValue());
}
pFormatClipboard->Copy( GetWrtShell(), GetPool(), bPersistentCopy );
SwApplyTemplate aTemplate;
aTemplate.pFormatClipboard = pFormatClipboard;
GetEditWin().SetApplyTemplate(aTemplate);
}
GetViewFrame()->GetBindings().Invalidate(SID_FORMATPAINTBRUSH);
}
void SwView::StateFormatPaintbrush(SfxItemSet &rSet)
{
if(!pFormatClipboard)
return;
bool bHasContent = pFormatClipboard && pFormatClipboard->HasContent();
rSet.Put(SfxBoolItem(SID_FORMATPAINTBRUSH, bHasContent));
if(!bHasContent)
{
if( !pFormatClipboard->CanCopyThisType( GetWrtShell().GetSelectionType() ) )
rSet.DisableItem( SID_FORMATPAINTBRUSH );
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>fdo#40438: force calculating layout before Activate to avoid crashes and loops<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include <svx/svdpagv.hxx>
#include <svx/svdview.hxx>
#include <svx/ruler.hxx>
#include <idxmrk.hxx>
#include <view.hxx>
#include <wrtsh.hxx>
#include <swmodule.hxx>
#include <viewopt.hxx>
#include <docsh.hxx>
#include <globdoc.hxx>
#include <navipi.hxx>
#include <fldwrap.hxx>
#include <redlndlg.hxx>
#include <dpage.hxx>
#include <edtwin.hxx>
#include "formatclipboard.hxx"
#include <cmdid.h>
// header for class SfxRequest
#include <sfx2/request.hxx>
#include <sfx2/viewfrm.hxx>
extern int bDocSzUpdated;
void SwView::Activate(sal_Bool bMDIActivate)
{
// fdo#40438 Update the layout to make sure everything is correct before showing the content
pWrtShell->StartAction();
pWrtShell->EndAction( sal_True );
// aktuelle View anmelden an der DocShell
// die View bleibt solange an der DocShell
// aktiv bis Sie zerstoert wird oder durch Activate eine
// neue gesetzt wird
SwDocShell* pDocSh = GetDocShell();
if(pDocSh)
pDocSh->SetView(this);
SwModule* pSwMod = SW_MOD();
pSwMod->SetView(this);
// Dokumentgroesse hat sich geaendert
if(!bDocSzUpdated)
DocSzChgd(aDocSz);
// make selection visible
if(bMakeSelectionVisible)
{
pWrtShell->MakeSelVisible();
bMakeSelectionVisible = sal_False;
}
pHRuler->SetActive( sal_True );
pVRuler->SetActive( sal_True );
if ( bMDIActivate )
{
pWrtShell->ShGetFcs(sal_False); // Selektionen sichtbar
if( sSwViewData.Len() )
{
ReadUserData( sSwViewData, sal_False );
sSwViewData.Erase();
}
AttrChangedNotify(pWrtShell);
// Flddlg ggf neu initialisieren (z.B. fuer TYP_SETVAR)
sal_uInt16 nId = SwFldDlgWrapper::GetChildWindowId();
SfxViewFrame* pVFrame = GetViewFrame();
SwFldDlgWrapper *pWrp = (SwFldDlgWrapper*)pVFrame->GetChildWindow(nId);
if (pWrp)
pWrp->ReInitDlg(GetDocShell());
// RedlineDlg ggf neu initialisieren
nId = SwRedlineAcceptChild::GetChildWindowId();
SwRedlineAcceptChild *pRed = (SwRedlineAcceptChild*)pVFrame->GetChildWindow(nId);
if (pRed)
pRed->ReInitDlg(GetDocShell());
// reinit IdxMarkDlg
nId = SwInsertIdxMarkWrapper::GetChildWindowId();
SwInsertIdxMarkWrapper *pIdxMrk = (SwInsertIdxMarkWrapper*)pVFrame->GetChildWindow(nId);
if (pIdxMrk)
pIdxMrk->ReInitDlg(*pWrtShell);
// reinit AuthMarkDlg
nId = SwInsertAuthMarkWrapper::GetChildWindowId();
SwInsertAuthMarkWrapper *pAuthMrk = (SwInsertAuthMarkWrapper*)pVFrame->
GetChildWindow(nId);
if (pAuthMrk)
pAuthMrk->ReInitDlg(*pWrtShell);
}
else
//Wenigstens das Notify rufen (vorsichtshalber wegen der SlotFilter
AttrChangedNotify(pWrtShell);
SfxViewShell::Activate(bMDIActivate);
}
void SwView::Deactivate(sal_Bool bMDIActivate)
{
extern sal_Bool bFlushCharBuffer ;
// Befinden sich noch Zeichen im Input Buffer?
if( bFlushCharBuffer )
GetEditWin().FlushInBuffer();
if( bMDIActivate )
{
pWrtShell->ShLooseFcs(); // Selektionen unsichtbar
pHRuler->SetActive( sal_False );
pVRuler->SetActive( sal_False );
}
SfxViewShell::Deactivate(bMDIActivate);
}
void SwView::MarginChanged()
{
GetWrtShell().SetBrowseBorder( GetMargin() );
}
void SwView::ExecFormatPaintbrush(SfxRequest& rReq)
{
if(!pFormatClipboard)
return;
if( pFormatClipboard->HasContent() )
{
pFormatClipboard->Erase();
SwApplyTemplate aTemplate;
GetEditWin().SetApplyTemplate(aTemplate);
}
else
{
bool bPersistentCopy = false;
const SfxItemSet *pArgs = rReq.GetArgs();
if( pArgs && pArgs->Count() >= 1 )
{
bPersistentCopy = static_cast<bool>(((SfxBoolItem &)pArgs->Get(
SID_FORMATPAINTBRUSH)).GetValue());
}
pFormatClipboard->Copy( GetWrtShell(), GetPool(), bPersistentCopy );
SwApplyTemplate aTemplate;
aTemplate.pFormatClipboard = pFormatClipboard;
GetEditWin().SetApplyTemplate(aTemplate);
}
GetViewFrame()->GetBindings().Invalidate(SID_FORMATPAINTBRUSH);
}
void SwView::StateFormatPaintbrush(SfxItemSet &rSet)
{
if(!pFormatClipboard)
return;
bool bHasContent = pFormatClipboard && pFormatClipboard->HasContent();
rSet.Put(SfxBoolItem(SID_FORMATPAINTBRUSH, bHasContent));
if(!bHasContent)
{
if( !pFormatClipboard->CanCopyThisType( GetWrtShell().GetSelectionType() ) )
rSet.DisableItem( SID_FORMATPAINTBRUSH );
}
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>#include "rtkTestConfiguration.h"
#include "itkRandomImageSource.h"
#include "rtkTotalVariationImageFilter.h"
#include "rtkTotalVariationDenoisingBPDQImageFilter.h"
#include "rtkMacro.h"
template<class TImage>
#if FAST_TESTS_NO_CHECKS
void CheckTotalVariation(typename TImage::Pointer itkNotUsed(before), typename TImage::Pointer itkNotUsed(after))
{
}
#else
void CheckTotalVariation(typename TImage::Pointer before, typename TImage::Pointer after)
{
typedef rtk::TotalVariationImageFilter<TImage> TotalVariationFilterType;
typename TotalVariationFilterType::Pointer tv = TotalVariationFilterType::New();
double totalVariationBefore;
double totalVariationAfter;
tv->SetInput(before);
tv->Update();
totalVariationBefore = tv->GetTotalVariation();
std::cout << "Total variation before denoising is " << totalVariationBefore << std::endl;
tv->SetInput(after);
tv->Update();
totalVariationAfter = tv->GetTotalVariation();
std::cout << "Total variation after denoising is " << totalVariationAfter << std::endl;
// Checking results
if (totalVariationBefore/2 < totalVariationAfter)
{
std::cerr << "Test Failed: total variation was not reduced" << std::endl;
exit( EXIT_FAILURE);
}
}
#endif
/**
* \file rtktotalvariationtest.cxx
*
* \brief Tests whether the Total Variation denoising filters indeed
* reduce the total variation of a random image
*
* This test generates a random volume and performs TV denoising on this
* volume. It measures its total variation before and after denoising and
* compares. Note that the TV denoising filters do not minimize TV alone,
* but TV + a data attachment term (they compute the proximal operator of TV).
* Nevertheless, in most cases, it is expected that the output has
* a lower TV than the input.
*
* \author Cyril Mory
*/
int main(int, char** )
{
typedef float OutputPixelType;
const unsigned int Dimension = 3;
#ifdef USE_CUDA
typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;
typedef itk::CudaImage< itk::CovariantVector
< OutputPixelType, Dimension >, Dimension > GradientOutputImageType;
#else
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
typedef itk::Image< itk::CovariantVector
< OutputPixelType, Dimension >, Dimension > GradientOutputImageType;
#endif
// Random image sources
typedef itk::RandomImageSource< OutputImageType > RandomImageSourceType;
RandomImageSourceType::Pointer randomVolumeSource = RandomImageSourceType::New();
// Image meta data
RandomImageSourceType::PointType origin;
RandomImageSourceType::SizeType size;
RandomImageSourceType::SpacingType spacing;
// Volume metadata
origin[0] = -127.;
origin[1] = -127.;
origin[2] = -127.;
#if FAST_TESTS_NO_CHECKS
size[0] = 2;
size[1] = 2;
size[2] = 2;
spacing[0] = 252.;
spacing[1] = 252.;
spacing[2] = 252.;
#else
size[0] = 64;
size[1] = 64;
size[2] = 64;
spacing[0] = 4.;
spacing[1] = 4.;
spacing[2] = 4.;
#endif
randomVolumeSource->SetOrigin( origin );
randomVolumeSource->SetSpacing( spacing );
randomVolumeSource->SetSize( size );
randomVolumeSource->SetMin( 0. );
randomVolumeSource->SetMax( 1. );
randomVolumeSource->SetNumberOfThreads(2); //With 1, it's deterministic
// Update the source
TRY_AND_EXIT_ON_ITK_EXCEPTION( randomVolumeSource->Update() );
// Create and set the TV denoising filter
typedef rtk::TotalVariationDenoisingBPDQImageFilter
<OutputImageType, GradientOutputImageType> TVDenoisingFilterType;
TVDenoisingFilterType::Pointer TVdenoising = TVDenoisingFilterType::New();
TVdenoising->SetInput(randomVolumeSource->GetOutput());
TVdenoising->SetNumberOfIterations(15);
TVdenoising->SetLambda(0.005);
bool dimsProcessed[Dimension];
for (int i=0; i<Dimension; i++)
{
dimsProcessed[i] = true;
}
TVdenoising->SetDimensionsProcessed(dimsProcessed);
// Update the TV denoising filter
TRY_AND_EXIT_ON_ITK_EXCEPTION( TVdenoising->Update() );
CheckTotalVariation<OutputImageType>(randomVolumeSource->GetOutput(), TVdenoising->GetOutput());
std::cout << "\n\nTest PASSED! " << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>COMP: Warning<commit_after>#include "rtkTestConfiguration.h"
#include "itkRandomImageSource.h"
#include "rtkTotalVariationImageFilter.h"
#include "rtkTotalVariationDenoisingBPDQImageFilter.h"
#include "rtkMacro.h"
template<class TImage>
#if FAST_TESTS_NO_CHECKS
void CheckTotalVariation(typename TImage::Pointer itkNotUsed(before), typename TImage::Pointer itkNotUsed(after))
{
}
#else
void CheckTotalVariation(typename TImage::Pointer before, typename TImage::Pointer after)
{
typedef rtk::TotalVariationImageFilter<TImage> TotalVariationFilterType;
typename TotalVariationFilterType::Pointer tv = TotalVariationFilterType::New();
double totalVariationBefore;
double totalVariationAfter;
tv->SetInput(before);
tv->Update();
totalVariationBefore = tv->GetTotalVariation();
std::cout << "Total variation before denoising is " << totalVariationBefore << std::endl;
tv->SetInput(after);
tv->Update();
totalVariationAfter = tv->GetTotalVariation();
std::cout << "Total variation after denoising is " << totalVariationAfter << std::endl;
// Checking results
if (totalVariationBefore/2 < totalVariationAfter)
{
std::cerr << "Test Failed: total variation was not reduced" << std::endl;
exit( EXIT_FAILURE);
}
}
#endif
/**
* \file rtktotalvariationtest.cxx
*
* \brief Tests whether the Total Variation denoising filters indeed
* reduce the total variation of a random image
*
* This test generates a random volume and performs TV denoising on this
* volume. It measures its total variation before and after denoising and
* compares. Note that the TV denoising filters do not minimize TV alone,
* but TV + a data attachment term (they compute the proximal operator of TV).
* Nevertheless, in most cases, it is expected that the output has
* a lower TV than the input.
*
* \author Cyril Mory
*/
int main(int, char** )
{
typedef float OutputPixelType;
const unsigned int Dimension = 3;
#ifdef USE_CUDA
typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType;
typedef itk::CudaImage< itk::CovariantVector
< OutputPixelType, Dimension >, Dimension > GradientOutputImageType;
#else
typedef itk::Image< OutputPixelType, Dimension > OutputImageType;
typedef itk::Image< itk::CovariantVector
< OutputPixelType, Dimension >, Dimension > GradientOutputImageType;
#endif
// Random image sources
typedef itk::RandomImageSource< OutputImageType > RandomImageSourceType;
RandomImageSourceType::Pointer randomVolumeSource = RandomImageSourceType::New();
// Image meta data
RandomImageSourceType::PointType origin;
RandomImageSourceType::SizeType size;
RandomImageSourceType::SpacingType spacing;
// Volume metadata
origin[0] = -127.;
origin[1] = -127.;
origin[2] = -127.;
#if FAST_TESTS_NO_CHECKS
size[0] = 2;
size[1] = 2;
size[2] = 2;
spacing[0] = 252.;
spacing[1] = 252.;
spacing[2] = 252.;
#else
size[0] = 64;
size[1] = 64;
size[2] = 64;
spacing[0] = 4.;
spacing[1] = 4.;
spacing[2] = 4.;
#endif
randomVolumeSource->SetOrigin( origin );
randomVolumeSource->SetSpacing( spacing );
randomVolumeSource->SetSize( size );
randomVolumeSource->SetMin( 0. );
randomVolumeSource->SetMax( 1. );
randomVolumeSource->SetNumberOfThreads(2); //With 1, it's deterministic
// Update the source
TRY_AND_EXIT_ON_ITK_EXCEPTION( randomVolumeSource->Update() );
// Create and set the TV denoising filter
typedef rtk::TotalVariationDenoisingBPDQImageFilter
<OutputImageType, GradientOutputImageType> TVDenoisingFilterType;
TVDenoisingFilterType::Pointer TVdenoising = TVDenoisingFilterType::New();
TVdenoising->SetInput(randomVolumeSource->GetOutput());
TVdenoising->SetNumberOfIterations(15);
TVdenoising->SetLambda(0.005);
bool dimsProcessed[Dimension];
for (unsigned int i=0; i<Dimension; i++)
{
dimsProcessed[i] = true;
}
TVdenoising->SetDimensionsProcessed(dimsProcessed);
// Update the TV denoising filter
TRY_AND_EXIT_ON_ITK_EXCEPTION( TVdenoising->Update() );
CheckTotalVariation<OutputImageType>(randomVolumeSource->GetOutput(), TVdenoising->GetOutput());
std::cout << "\n\nTest PASSED! " << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>// Copyright Steinwurf ApS 2015.
// All Rights Reserved
#pragma once
#include <cassert>
#include <cstdint>
#include "descriptor.hpp"
#include "../byte_stream.hpp"
namespace petro
{
namespace descriptor
{
class sl_config_descriptor : public descriptor
{
public:
sl_config_descriptor(byte_stream& bs, uint8_t tag):
descriptor(bs, tag)
{
assert(m_tag == 0x06);
auto predefined = bs.read_uint8_t();
if (predefined == 0)
{
auto d1 = bs.read_uint8_t();
m_remaining_bytes -= 1;
m_use_access_unit_start_flag = ((d1 & 0x01) >> 1) == 1;
m_use_access_unit_end_flag = ((d1 & 0x02) >> 2) == 1;
m_use_random_access_point_flag = ((d1 & 0x04) >> 3) == 1;
m_has_random_access_units_only_flag = ((d1 & 0x08) >> 4) == 1;
m_use_padding_flag = ((d1 & 0x10) >> 5) == 1;
m_use_time_stamps_flag = ((d1 & 0x20) >> 6) == 1;
m_use_idle_flag = ((d1 & 0x40) >> 7) == 1;
m_duration_flag = ((d1 & 0x80) >> 8) == 1;
m_time_stamp_resolution = bs.read_uint32_t();
m_remaining_bytes -= 4;
m_ocr_resolution = bs.read_uint32_t();
m_remaining_bytes -= 4;
m_time_stamp_length = bs.read_uint8_t(); // must be less than 64
m_remaining_bytes -= 1;
m_ocr_length = bs.read_uint8_t(); // must be less than 64
m_remaining_bytes -= 1;
m_au_length = bs.read_uint8_t(); // must be less than 32
m_remaining_bytes -= 1;
m_instant_bitrate_length = bs.read_uint8_t();
m_remaining_bytes -= 1;
auto d2 = bs.read_uint16_t();
m_remaining_bytes -= 2;
m_degradation_priority_length = d2;
m_au_sequence_number_length = d2;
m_packet_sequence_number_length = d2;
if (m_duration_flag)
{
m_time_scale = bs.read_uint32_t();
m_remaining_bytes -= 4;
m_access_unit_duration = bs.read_uint16_t();
m_remaining_bytes -= 2;
m_composition_unit_duration = bs.read_uint16_t();
m_remaining_bytes -= 2;
}
if (!m_use_time_stamps_flag)
{
auto time_stamp_length_bytes = m_time_stamp_length / 8;
if (m_time_stamp_length % 8 != 0)
time_stamp_length_bytes += 1;
//m_start_decoding_time_stamp = bs.read_bits(time_stamp_length_bytes);
bs.skip(time_stamp_length_bytes);
m_remaining_bytes -= time_stamp_length_bytes;
//m_start_composition_time_stamp = bs.read_bits(time_stamp_length_bytes);
bs.skip(time_stamp_length_bytes);
m_remaining_bytes -= time_stamp_length_bytes;
}
}
}
private:
bool m_use_access_unit_start_flag;
bool m_use_access_unit_end_flag;
bool m_use_random_access_point_flag;
bool m_has_random_access_units_only_flag;
bool m_use_padding_flag;
bool m_use_time_stamps_flag;
bool m_use_idle_flag;
bool m_duration_flag;
uint32_t m_time_stamp_resolution;
uint32_t m_ocr_resolution;
uint8_t m_time_stamp_length; // must be less than 64
uint8_t m_ocr_length; // must be less than 64
uint8_t m_au_length; // must be less than 32
uint8_t m_instant_bitrate_length;
uint8_t m_degradation_priority_length; //bit 4
uint8_t m_au_sequence_number_length; //bit 5
uint8_t m_packet_sequence_number_length; //bit 5
uint32_t m_time_scale;
uint16_t m_access_unit_duration;
uint16_t m_composition_unit_duration;
uint64_t m_start_decoding_time_stamp; // bit(timeStampLength)
uint64_t m_start_composition_time_stamp; // bit(timeStampLength)
};
}
}
<commit_msg>readied for new sync layer descriptors<commit_after>// Copyright Steinwurf ApS 2015.
// All Rights Reserved
#pragma once
#include <cassert>
#include <cstdint>
#include "descriptor.hpp"
#include "../byte_stream.hpp"
namespace petro
{
namespace descriptor
{
// sync layer config descriptor
class sl_config_descriptor : public descriptor
{
public:
sl_config_descriptor(byte_stream& bs, uint8_t tag):
descriptor(bs, tag)
{
assert(m_tag == 0x06);
auto predefined = bs.read_uint8_t();
switch(predefined)
{
case 0x00:
{
auto d1 = bs.read_uint8_t();
m_remaining_bytes -= 1;
m_use_access_unit_start_flag = ((d1 & 0x01) >> 1) == 1;
m_use_access_unit_end_flag = ((d1 & 0x02) >> 2) == 1;
m_use_random_access_point_flag = ((d1 & 0x04) >> 3) == 1;
m_has_random_access_units_only_flag =
((d1 & 0x08) >> 4) == 1;
m_use_padding_flag = ((d1 & 0x10) >> 5) == 1;
m_use_timestamps_flag = ((d1 & 0x20) >> 6) == 1;
m_use_idle_flag = ((d1 & 0x40) >> 7) == 1;
m_duration_flag = ((d1 & 0x80) >> 8) == 1;
m_time_stamp_resolution = bs.read_uint32_t();
m_remaining_bytes -= 4;
m_ocr_resolution = bs.read_uint32_t();
m_remaining_bytes -= 4;
// must be less than 64
m_time_stamp_length = bs.read_uint8_t();
m_remaining_bytes -= 1;
// must be less than 64
m_ocr_length = bs.read_uint8_t();
m_remaining_bytes -= 1;
// must be less than 32
m_au_length = bs.read_uint8_t();
m_remaining_bytes -= 1;
m_instant_bitrate_length = bs.read_uint8_t();
m_remaining_bytes -= 1;
auto d2 = bs.read_uint16_t();
m_remaining_bytes -= 2;
m_degradation_priority_length = d2;
m_au_sequence_number_length = d2;
m_packet_sequence_number_length = d2;
if (m_duration_flag)
{
m_time_scale = bs.read_uint32_t();
m_remaining_bytes -= 4;
m_access_unit_duration = bs.read_uint16_t();
m_remaining_bytes -= 2;
m_composition_unit_duration = bs.read_uint16_t();
m_remaining_bytes -= 2;
}
if (!m_use_timestamps_flag)
{
auto time_stamp_length_bytes = m_time_stamp_length / 8;
if (m_time_stamp_length % 8 != 0)
time_stamp_length_bytes += 1;
/// @todo read the next time_stamp_length_bytes
// m_start_decoding_time_stamp =
// bs.read_bits(time_stamp_length_bytes);
bs.skip(time_stamp_length_bytes);
m_remaining_bytes -= time_stamp_length_bytes;
/// @todo read the next time_stamp_length_bytes
// m_start_composition_time_stamp =
// bs.read_bits(time_stamp_length_bytes);
bs.skip(time_stamp_length_bytes);
m_remaining_bytes -= time_stamp_length_bytes;
}
break;
}
default:
{
// unsupported sync layer descriptor predefine
}
}
}
private:
bool m_use_access_unit_start_flag;
bool m_use_access_unit_end_flag;
bool m_use_random_access_point_flag;
bool m_has_random_access_units_only_flag;
bool m_use_padding_flag;
bool m_use_timestamps_flag;
bool m_use_idle_flag;
bool m_duration_flag;
uint32_t m_time_stamp_resolution;
uint32_t m_ocr_resolution;
uint8_t m_time_stamp_length; // must be less than 64
uint8_t m_ocr_length; // must be less than 64
uint8_t m_au_length; // must be less than 32
uint8_t m_instant_bitrate_length;
uint8_t m_degradation_priority_length; //bit 4
uint8_t m_au_sequence_number_length; //bit 5
uint8_t m_packet_sequence_number_length; //bit 5
uint32_t m_time_scale;
uint16_t m_access_unit_duration;
uint16_t m_composition_unit_duration;
uint64_t m_start_decoding_time_stamp; // bit(timeStampLength)
uint64_t m_start_composition_time_stamp; // bit(timeStampLength)
};
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. 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 "source/example_component/example_base_class.hpp"
#include "test.hpp"
using namespace ::testing;
using ::testing::Return;
namespace example
{
namespace test
{
/// @req IOX_SWRS_112, IOX_SWRS_200
/// @brief Test goal: "This test suite verifies that the BaseClass function is verified"
/// @pre describe what needs to be done in setup()
/// @post describe what needs to be done in teardown()
/// @note name of the Testfixture should match to the Class you want to test
template <typename T>
class ExampleBaseClass_test : public Test
{
public:
void SetUp() override
{
}
void TearDown() override
{
}
};
/// @note name of the Testcase shall describe the test case in detail to avoid additional comments
TEST_F(ExampleBaseClass_test, FirstUnitTestCase)
{
ExampleBaseClass<T> testInstance(1, 2);
testinstance.simplerMethod();
EXPECT_THAT(testInstance.m_memberVariable, Eq(100u));
}
} // namespace test
} // namespace example<commit_msg>iox-#198 sut in test example<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. 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 "source/example_component/example_base_class.hpp"
#include "test.hpp"
using namespace ::testing;
using ::testing::Return;
namespace example
{
namespace test
{
/// @req IOX_SWRS_112, IOX_SWRS_200
/// @brief Test goal: "This test suite verifies that the BaseClass function is verified"
/// @pre describe what needs to be done in setup()
/// @post describe what needs to be done in teardown()
/// @note name of the Testfixture should match to the Class you want to test
template <typename T>
class ExampleBaseClass_test : public Test
{
public:
void SetUp() override
{
}
void TearDown() override
{
}
};
/// @note name of the Testcase shall describe the test case in detail to avoid additional comments
TEST_F(ExampleBaseClass_test, FirstUnitTestCase)
{
ExampleBaseClass<T> sut(1, 2);
sut.simplerMethod();
EXPECT_THAT(sut.m_memberVariable, Eq(100u));
}
} // namespace test
} // namespace example<|endoftext|>
|
<commit_before>// 2008
// Jon 'jonanin' Morton
#include "luainc.h"
#include "Common.h"
#include "LuaInterface.h"
#include "LuaArgument.h"
#include <list>
int main() {
LuaInterface lu;
lu.ExecuteFile("test.lua");
vector<LuaArgument> retargs;
// arguments for lua function
LuaArgument largs[] = { LuaArgument(5) };
// index, function name, args array, number of args, number of results (return args), return args vector
lu.CallLua(LUA_GLOBALSINDEX, "doStuff", largs, 1, 4, &retargs);
int i = 0;
for (vector<LuaArgument>::iterator it = retargs.begin(); it < retargs.end(); it++) {
printf("arg %i: ", i++);
it->PrintDebug();
printf("\n");
}
}
<commit_msg>removing unneeded include<commit_after>// 2008
// Jon 'jonanin' Morton
#include "luainc.h"
#include "Common.h"
#include "LuaInterface.h"
#include "LuaArgument.h"s
int main() {
LuaInterface lu;
lu.ExecuteFile("test.lua");
vector<LuaArgument> retargs;
// arguments for lua function
LuaArgument largs[] = { LuaArgument(5) };
// index, function name, args array, number of args, number of results (return args), return args vector
lu.CallLua(LUA_GLOBALSINDEX, "doStuff", largs, 1, 4, &retargs);
int i = 0;
for (vector<LuaArgument>::iterator it = retargs.begin(); it < retargs.end(); it++) {
printf("arg %i: ", i++);
it->PrintDebug();
printf("\n");
}
}
<|endoftext|>
|
<commit_before>#include "../../source/thewizardplusplus/wizard_parser/parser/rule_parser.hpp"
#include "../../source/thewizardplusplus/wizard_parser/parser/lookahead_parser.hpp"
#include "../../source/thewizardplusplus/wizard_parser/lexer/token.hpp"
#include "../../source/thewizardplusplus/wizard_parser/parser/ast_node.hpp"
#include "../../source/thewizardplusplus/wizard_parser/utilities/utilities.hpp"
#include "../vendor/catch/catch.hpp"
#include "../vendor/fakeit/fakeit.hpp"
TEST_CASE("parser::lookahead_parser class", "[parser]") {
using namespace thewizardplusplus::wizard_parser;
using namespace thewizardplusplus::wizard_parser::parser::operators;
SECTION("positive lookahead without tokens") {
auto mock_parser = fakeit::Mock<parser::rule_parser>{};
fakeit::When(Method(mock_parser, parse))
.Return(parser::parsing_result{});
fakeit::Fake(Dtor(mock_parser));
const auto lookahead_parser =
&parser::rule_parser::pointer{&mock_parser.get()};
const auto [ast, rest_tokens] = lookahead_parser->parse({});
CHECK(!ast.has_value());
CHECK(rest_tokens.empty());
fakeit::Verify(Method(mock_parser, parse)).Once();
}
SECTION("positive lookahead without a match") {
auto tokens = lexer::token_group{{"one", "two", 1}, {"three", "four", 4}};
auto mock_parser = fakeit::Mock<parser::rule_parser>{};
fakeit::When(Method(mock_parser, parse))
.Return(parser::parsing_result{{}, tokens});
fakeit::Fake(Dtor(mock_parser));
const auto lookahead_parser =
&parser::rule_parser::pointer{&mock_parser.get()};
const auto [ast, rest_tokens] = lookahead_parser->parse(tokens);
CHECK(!ast.has_value());
CHECK(rest_tokens == lexer::token_span{tokens});
fakeit::Verify(Method(mock_parser, parse)).Once();
}
SECTION("positive lookahead with a match") {
const auto type = (+parser::ast_node_type::nothing)._to_string();
auto tokens = lexer::token_group{{"one", "two", 1}, {"three", "four", 4}};
auto mock_parser = fakeit::Mock<parser::rule_parser>{};
fakeit::When(Method(mock_parser, parse))
.Return(parser::parsing_result{
parser::ast_node{"one", "two", {}, 1},
lexer::token_span{tokens}.subspan(1)
});
fakeit::Fake(Dtor(mock_parser));
const auto lookahead_parser =
&parser::rule_parser::pointer{&mock_parser.get()};
const auto [ast, rest_tokens] = lookahead_parser->parse(tokens);
REQUIRE(ast.has_value());
CHECK(*ast == parser::ast_node{type, {}, {}, 1});
CHECK(rest_tokens == lexer::token_span{tokens}.subspan(1));
fakeit::Verify(Method(mock_parser, parse)).Once();
}
SECTION("negative lookahead without tokens") {
const auto type = (+parser::ast_node_type::nothing)._to_string();
auto mock_parser = fakeit::Mock<parser::rule_parser>{};
fakeit::When(Method(mock_parser, parse))
.Return(parser::parsing_result{});
fakeit::Fake(Dtor(mock_parser));
const auto lookahead_parser =
!parser::rule_parser::pointer{&mock_parser.get()};
const auto [ast, rest_tokens] = lookahead_parser->parse({});
REQUIRE(ast.has_value());
CHECK(*ast == parser::ast_node{type, {}, {}, utilities::integral_infinity});
CHECK(rest_tokens.empty());
fakeit::Verify(Method(mock_parser, parse)).Once();
}
SECTION("negative lookahead without a match") {
const auto type = (+parser::ast_node_type::nothing)._to_string();
auto tokens = lexer::token_group{{"one", "two", 1}, {"three", "four", 4}};
auto mock_parser = fakeit::Mock<parser::rule_parser>{};
fakeit::When(Method(mock_parser, parse))
.Return(parser::parsing_result{{}, tokens});
fakeit::Fake(Dtor(mock_parser));
const auto lookahead_parser =
!parser::rule_parser::pointer{&mock_parser.get()};
const auto [ast, rest_tokens] = lookahead_parser->parse(tokens);
REQUIRE(ast.has_value());
CHECK(*ast == parser::ast_node{type, {}, {}, 1});
CHECK(rest_tokens == lexer::token_span{tokens});
fakeit::Verify(Method(mock_parser, parse)).Once();
}
SECTION("negative lookahead with a match") {
auto tokens = lexer::token_group{{"one", "two", 1}, {"three", "four", 4}};
auto mock_parser = fakeit::Mock<parser::rule_parser>{};
fakeit::When(Method(mock_parser, parse))
.Return(parser::parsing_result{
parser::ast_node{"one", "two", {}, 1},
lexer::token_span{tokens}.subspan(1)
});
fakeit::Fake(Dtor(mock_parser));
const auto lookahead_parser =
!parser::rule_parser::pointer{&mock_parser.get()};
const auto [ast, rest_tokens] = lookahead_parser->parse(tokens);
CHECK(!ast.has_value());
CHECK(rest_tokens == lexer::token_span{tokens}.subspan(1));
fakeit::Verify(Method(mock_parser, parse)).Once();
}
}
<commit_msg>Upgrade and improve tests of the `parser::lookahead_parser` class<commit_after>#include "../../source/thewizardplusplus/wizard_parser/parser/rule_parser.hpp"
#include "../../source/thewizardplusplus/wizard_parser/parser/lookahead_parser.hpp"
#include "../../source/thewizardplusplus/wizard_parser/lexer/token.hpp"
#include "../../source/thewizardplusplus/wizard_parser/parser/ast_node.hpp"
#include "../../source/thewizardplusplus/wizard_parser/utilities/utilities.hpp"
#include "../vendor/catch/catch.hpp"
#include "../vendor/fakeit/fakeit.hpp"
TEST_CASE("parser::lookahead_parser class", "[parser]") {
using namespace thewizardplusplus::wizard_parser;
using namespace thewizardplusplus::wizard_parser::parser::operators;
SECTION("positive lookahead without tokens") {
auto mock_parser = fakeit::Mock<parser::rule_parser>{};
fakeit::When(Method(mock_parser, parse))
.Return(parser::parsing_result{});
fakeit::Fake(Dtor(mock_parser));
const auto lookahead_parser =
&parser::rule_parser::pointer{&mock_parser.get()};
const auto [ast, rest_tokens] = lookahead_parser->parse({});
CHECK(!ast.has_value());
CHECK(rest_tokens.empty());
fakeit::Verify(Method(mock_parser, parse)).Once();
}
SECTION("positive lookahead without a match") {
auto tokens = lexer::token_group{{"one", "two", 1}, {"three", "four", 4}};
auto mock_parser = fakeit::Mock<parser::rule_parser>{};
fakeit::When(Method(mock_parser, parse))
.Return(parser::parsing_result{{}, lexer::token_span{tokens}.subspan(1)});
fakeit::Fake(Dtor(mock_parser));
const auto lookahead_parser =
&parser::rule_parser::pointer{&mock_parser.get()};
const auto [ast, rest_tokens] = lookahead_parser->parse(tokens);
CHECK(!ast.has_value());
CHECK(rest_tokens == lexer::token_span{tokens}.subspan(1));
fakeit::Verify(Method(mock_parser, parse)).Once();
}
SECTION("positive lookahead with a match") {
const auto type = (+parser::ast_node_type::nothing)._to_string();
auto tokens = lexer::token_group{{"one", "two", 1}, {"three", "four", 4}};
auto mock_parser = fakeit::Mock<parser::rule_parser>{};
fakeit::When(Method(mock_parser, parse))
.Return(parser::parsing_result{
parser::ast_node{"one", "two", {}, 1},
lexer::token_span{tokens}.subspan(1)
});
fakeit::Fake(Dtor(mock_parser));
const auto lookahead_parser =
&parser::rule_parser::pointer{&mock_parser.get()};
const auto [ast, rest_tokens] = lookahead_parser->parse(tokens);
REQUIRE(ast.has_value());
CHECK(*ast == parser::ast_node{type, {}, {}, 1});
CHECK(rest_tokens == lexer::token_span{tokens}.subspan(1));
fakeit::Verify(Method(mock_parser, parse)).Once();
}
SECTION("negative lookahead without tokens") {
const auto type = (+parser::ast_node_type::nothing)._to_string();
auto mock_parser = fakeit::Mock<parser::rule_parser>{};
fakeit::When(Method(mock_parser, parse))
.Return(parser::parsing_result{});
fakeit::Fake(Dtor(mock_parser));
const auto lookahead_parser =
!parser::rule_parser::pointer{&mock_parser.get()};
const auto [ast, rest_tokens] = lookahead_parser->parse({});
REQUIRE(ast.has_value());
CHECK(*ast == parser::ast_node{type, {}, {}, utilities::integral_infinity});
CHECK(rest_tokens.empty());
fakeit::Verify(Method(mock_parser, parse)).Once();
}
SECTION("negative lookahead without a match") {
const auto type = (+parser::ast_node_type::nothing)._to_string();
auto tokens = lexer::token_group{{"one", "two", 1}, {"three", "four", 4}};
auto mock_parser = fakeit::Mock<parser::rule_parser>{};
fakeit::When(Method(mock_parser, parse))
.Return(parser::parsing_result{{}, lexer::token_span{tokens}.subspan(1)});
fakeit::Fake(Dtor(mock_parser));
const auto lookahead_parser =
!parser::rule_parser::pointer{&mock_parser.get()};
const auto [ast, rest_tokens] = lookahead_parser->parse(tokens);
REQUIRE(ast.has_value());
CHECK(*ast == parser::ast_node{type, {}, {}, 1});
CHECK(rest_tokens == lexer::token_span{tokens});
fakeit::Verify(Method(mock_parser, parse)).Once();
}
SECTION("negative lookahead with a match") {
auto tokens = lexer::token_group{{"one", "two", 1}, {"three", "four", 4}};
auto mock_parser = fakeit::Mock<parser::rule_parser>{};
fakeit::When(Method(mock_parser, parse))
.Return(parser::parsing_result{
parser::ast_node{"one", "two", {}, 1},
lexer::token_span{tokens}.subspan(1)
});
fakeit::Fake(Dtor(mock_parser));
const auto lookahead_parser =
!parser::rule_parser::pointer{&mock_parser.get()};
const auto [ast, rest_tokens] = lookahead_parser->parse(tokens);
CHECK(!ast.has_value());
CHECK(rest_tokens == lexer::token_span{tokens});
fakeit::Verify(Method(mock_parser, parse)).Once();
}
}
<|endoftext|>
|
<commit_before>#include "MaximumProductSubarray.hpp"
using namespace std;
int MaximumProductSubarray::maxProduct(vector<int> &nums) {
int n = nums.size();
if (n == 0)
return 0;
vector<int> a(n, 0);
vector<int> b(n, 0);
a[0] = b[0] = nums[0];
for (int i = 1; i < n; i++) {
int v1 = nums[i];
int v2 = a[i - 1] * nums[i];
int v3 = b[i - 1] * nums[i];
a[i] = max(v1, max(v2, v3));
b[i] = min(v1, min(v2, v3));
}
int ret = a[0];
for (int i = 1; i < n; i++)
ret = max(ret, a[i]);
return ret;
}
<commit_msg>Refine Problem 152. Maximum Product Subarray<commit_after>#include "MaximumProductSubarray.hpp"
#include <algorithm>
using namespace std;
int MaximumProductSubarray::maxProduct(vector<int> &nums) {
int n = nums.size();
if (n == 0)
return 0;
vector<int> a(n, 0);
vector<int> b(n, 0);
a[0] = b[0] = nums[0];
for (int i = 1; i < n; i++) {
int v1 = nums[i];
int v2 = a[i - 1] * nums[i];
int v3 = b[i - 1] * nums[i];
a[i] = max(v1, max(v2, v3));
b[i] = min(v1, min(v2, v3));
}
int ret = a[0];
for (int i = 1; i < n; i++)
ret = max(ret, a[i]);
return ret;
}
<|endoftext|>
|
<commit_before>/*
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "braininavat.h"
#include <QtGui>
#include "brainview.h"
#include "c2eBrain.h"
#include <fstream>
using namespace std;
// Constructor which creates the main window.
BrainInAVat::BrainInAVat() {
ourCreature = 0;
scrollArea = new QScrollArea(this);
ourView = new BrainView(this);
scrollArea->setWidget(ourView);
setCentralWidget(scrollArea);
(void)statusBar();
setWindowTitle(tr("openc2e's Brain in a Vat"));
resize(600, 400);
/* File menu */
openAct = new QAction(tr("&Open..."), this);
openAct->setShortcut(tr("Ctrl+O"));
openAct->setStatusTip(tr("Open a genome file"));
connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
for (int i = 0; i < MaxRecentFiles; ++i) {
recentFileActs[i] = new QAction(this);
recentFileActs[i]->setVisible(false);
connect(recentFileActs[i], SIGNAL(triggered()), this, SLOT(openRecentFile()));
}
exitAct = new QAction(tr("E&xit"), this);
exitAct->setShortcut(tr("Ctrl+Q"));
exitAct->setStatusTip(tr("Exit Brain in a Vat"));
connect(exitAct, SIGNAL(triggered()), qApp, SLOT(closeAllWindows()));
fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(openAct);
separatorAct = fileMenu->addSeparator();
for (int i = 0; i < MaxRecentFiles; ++i)
fileMenu->addAction(recentFileActs[i]);
fileMenu->addSeparator();
fileMenu->addAction(exitAct);
updateRecentFileActions();
/* View menu */
neuronActGroup = new QActionGroup(this);
dendriteActGroup = new QActionGroup(this);
thresholdActGroup = new QActionGroup(this);
// neuron/dendrite variable selection
for (unsigned int i = 0; i < 8; i++) {
// TODO: friendly names for neuron/dendrite vars
neuronActs[i] = new QAction(tr("Neuron var %1").arg(i), this);
neuronActGroup->addAction(neuronActs[i]);
neuronActs[i]->setCheckable(true);
connect(neuronActs[i], SIGNAL(triggered()), this, SLOT(setSomeVar()));
dendriteActs[i] = new QAction(tr("Dendrite var %1").arg(i), this);
dendriteActGroup->addAction(dendriteActs[i]);
dendriteActs[i]->setCheckable(true);
connect(dendriteActs[i], SIGNAL(triggered()), this, SLOT(setSomeVar()));
}
neuronActs[0]->setChecked(true);
dendriteActs[0]->setChecked(true);
// threshold for element visibility
noThresholdAct = new QAction(tr("Show all elements"), this);
thresholdActGroup->addAction(noThresholdAct);
noThresholdAct->setCheckable(true);
noThresholdAct->setChecked(true);
connect(noThresholdAct, SIGNAL(triggered()), this, SLOT(setNoThreshold()));
nonZeroThresholdAct = new QAction(tr("Show elements with non-zero values only"), this);
thresholdActGroup->addAction(nonZeroThresholdAct);
nonZeroThresholdAct->setCheckable(true);
connect(nonZeroThresholdAct, SIGNAL(triggered()), this, SLOT(setNonZeroThreshold()));
showNoneAct = new QAction(tr("Show no elements"), this);
thresholdActGroup->addAction(showNoneAct);
showNoneAct->setCheckable(true);
connect(showNoneAct, SIGNAL(triggered()), this, SLOT(setShowNone()));
viewMenu = menuBar()->addMenu(tr("&View"));
for (unsigned int i = 0; i < 8; i++)
viewMenu->addAction(neuronActs[i]);
viewMenu->addSeparator();
for (unsigned int i = 0; i < 8; i++)
viewMenu->addAction(dendriteActs[i]);
viewMenu->addSeparator();
viewMenu->addAction(noThresholdAct);
viewMenu->addAction(nonZeroThresholdAct);
viewMenu->addAction(showNoneAct);
/* Control menu */
tickAct = new QAction(tr("&Tick"), this);
tickAct->setStatusTip(tr("Run the brain through one iteration"));
tickAct->setEnabled(false);
connect(tickAct, SIGNAL(triggered()), this, SLOT(tick()));
sleepToggleAct = new QAction(tr("&Sleep"), this);
sleepToggleAct->setStatusTip(tr("Set whether the brain is asleep (and dreaming) or not"));
sleepToggleAct->setCheckable(true);
sleepToggleAct->setEnabled(false);
connect(sleepToggleAct, SIGNAL(triggered()), this, SLOT(toggleSleep()));
controlMenu = menuBar()->addMenu(tr("&Control"));
controlMenu->addAction(tickAct);
controlMenu->addAction(sleepToggleAct);
controlToolbar = addToolBar(tr("Control"));
controlToolbar->addAction(tickAct);
/* Help menu */
menuBar()->addSeparator();
aboutAct = new QAction(tr("&About"), this);
aboutAct->setStatusTip(tr("Find out about Brain in a Vat"));
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
helpMenu = menuBar()->addMenu(tr("&Help"));
helpMenu->addAction(aboutAct);
}
BrainInAVat::~BrainInAVat() {
if (ourCreature)
delete ourCreature;
delete ourView;
}
// action handlers
void BrainInAVat::open() {
QString fileName = QFileDialog::getOpenFileName(this, tr("Pick a genome"), QString(), tr("Genomes (*.gen)"));
if (!fileName.isEmpty())
loadFile(fileName);
}
void BrainInAVat::openRecentFile() {
QAction *action = qobject_cast<QAction *>(sender());
if (action)
loadFile(action->data().toString());
}
void BrainInAVat::about() {
QMessageBox::about(this, tr("openc2e's Brain in a Vat"), tr("An openc2e tool to monitor and experiment upon creature brains."));
}
void BrainInAVat::tick() {
// brain updates are every 4 ticks
// TODO: this is icky
for (unsigned int i = 0; i < 4; i++)
ourCreature->tick();
ourView->update();
}
void BrainInAVat::setSomeVar() {
QAction *action = qobject_cast<QAction *>(sender());
for (unsigned int i = 0; i < 8; i++) {
if (action == neuronActs[i])
ourView->neuron_var = i;
else if (action == dendriteActs[i])
ourView->dendrite_var = i;
}
ourView->update();
}
void BrainInAVat::setNoThreshold() {
ourView->threshold = -1000.0f;
ourView->update();
}
void BrainInAVat::setNonZeroThreshold() {
ourView->threshold = 0.0f;
ourView->update();
}
void BrainInAVat::setShowNone() {
ourView->threshold = 1000.0f;
ourView->update();
}
void BrainInAVat::toggleSleep() {
ourCreature->setDreaming(!ourCreature->isDreaming());
sleepToggleAct->setChecked(ourCreature->isDreaming());
}
// code to Do Things!
void BrainInAVat::loadFile(const QString &fileName) {
// zot any existing file
setCurrentFile(QString());
if (ourCreature) {
delete ourCreature;
ourCreature = 0;
}
tickAct->setEnabled(false);
sleepToggleAct->setChecked(false);
sleepToggleAct->setEnabled(false);
ourView->update();
ifstream f(fileName.toAscii(), std::ios::binary);
if (f.fail()) {
QMessageBox::warning(this, tr("openc2e's Brain in a Vat"), tr("Cannot read file %1.").arg(fileName));
return;
}
QApplication::setOverrideCursor(Qt::WaitCursor);
// read genome
f >> noskipws;
shared_ptr<genomeFile> gfile(new genomeFile());
try {
f >> *gfile;
} catch (genomeException &e) {
QMessageBox::warning(this, tr("openc2e's Brain in a Vat"), tr("Failed loading the genome due to error '%1'!").arg(e.what()));
QApplication::restoreOverrideCursor();
return;
}
// TODO: dialog to pick age, gender, variant?
// create creature
if (gfile->getVersion() == 3) {
ourCreature = new c2eCreature(gfile, true, 0);
} else {
QMessageBox::warning(this, tr("openc2e's Brain in a Vat"), tr("This genome is of version %1, which is unsupported.").arg(gfile->getVersion()));
QApplication::restoreOverrideCursor();
return;
}
QApplication::restoreOverrideCursor();
// we're done; update title/recent files, and display a temporary status message
tickAct->setEnabled(true);
sleepToggleAct->setEnabled(true);
ourView->resize(ourView->minimumSize());
ourView->update();
setCurrentFile(fileName);
statusBar()->showMessage(tr("Loaded %1 genes").arg(gfile->genes.size()), 2000);
}
// Some Recent Files magic.
void BrainInAVat::setCurrentFile(const QString &fileName) {
curFile = fileName;
if (curFile.isEmpty()) {
setWindowTitle(tr("openc2e's Brain in a Vat"));
return; // TODO: is this correct?
} else
setWindowTitle(tr("%1 - %2").arg(strippedName(curFile)).arg(tr("openc2e's Brain in a Vat")));
// read the list of recent files
QSettings settings("ccdevnet.org", "Brain In A Vat");
QStringList files = settings.value("recentFileList").toStringList();
// make sure the current file is at the top!
files.removeAll(fileName);
files.prepend(fileName);
// remove any which are over the size
while (files.size() > MaxRecentFiles)
files.removeLast();
// store the list of recent files
settings.setValue("recentFileList", files);
// update ourselves..
updateRecentFileActions(); // obviously assumes we only have one window
}
void BrainInAVat::updateRecentFileActions() {
// read the list of recent files
QSettings settings("ccdevnet.org", "Brain In A Vat");
QStringList files = settings.value("recentFileList").toStringList();
// enable recent files actions as needed
int numRecentFiles = qMin(files.size(), (int)MaxRecentFiles);
for (int i = 0; i < numRecentFiles; ++i) {
QString text = tr("&%1 %2").arg(i + 1).arg(strippedName(files[i]));
recentFileActs[i]->setText(text);
recentFileActs[i]->setData(files[i]);
recentFileActs[i]->setVisible(true);
}
// make sure the rest are disabled [ie, hidden]
for (int j = numRecentFiles; j < MaxRecentFiles; ++j)
recentFileActs[j]->setVisible(false);
// only show the separator if there are recent files
separatorAct->setVisible(numRecentFiles > 0);
}
QString BrainInAVat::strippedName(const QString &fullFileName) {
return QFileInfo(fullFileName).fileName();
}
<commit_msg>braininavat: catch exceptions from c2eCreature constructor<commit_after>/*
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "braininavat.h"
#include <QtGui>
#include "brainview.h"
#include "c2eBrain.h"
#include <fstream>
using namespace std;
// Constructor which creates the main window.
BrainInAVat::BrainInAVat() {
ourCreature = 0;
scrollArea = new QScrollArea(this);
ourView = new BrainView(this);
scrollArea->setWidget(ourView);
setCentralWidget(scrollArea);
(void)statusBar();
setWindowTitle(tr("openc2e's Brain in a Vat"));
resize(600, 400);
/* File menu */
openAct = new QAction(tr("&Open..."), this);
openAct->setShortcut(tr("Ctrl+O"));
openAct->setStatusTip(tr("Open a genome file"));
connect(openAct, SIGNAL(triggered()), this, SLOT(open()));
for (int i = 0; i < MaxRecentFiles; ++i) {
recentFileActs[i] = new QAction(this);
recentFileActs[i]->setVisible(false);
connect(recentFileActs[i], SIGNAL(triggered()), this, SLOT(openRecentFile()));
}
exitAct = new QAction(tr("E&xit"), this);
exitAct->setShortcut(tr("Ctrl+Q"));
exitAct->setStatusTip(tr("Exit Brain in a Vat"));
connect(exitAct, SIGNAL(triggered()), qApp, SLOT(closeAllWindows()));
fileMenu = menuBar()->addMenu(tr("&File"));
fileMenu->addAction(openAct);
separatorAct = fileMenu->addSeparator();
for (int i = 0; i < MaxRecentFiles; ++i)
fileMenu->addAction(recentFileActs[i]);
fileMenu->addSeparator();
fileMenu->addAction(exitAct);
updateRecentFileActions();
/* View menu */
neuronActGroup = new QActionGroup(this);
dendriteActGroup = new QActionGroup(this);
thresholdActGroup = new QActionGroup(this);
// neuron/dendrite variable selection
for (unsigned int i = 0; i < 8; i++) {
// TODO: friendly names for neuron/dendrite vars
neuronActs[i] = new QAction(tr("Neuron var %1").arg(i), this);
neuronActGroup->addAction(neuronActs[i]);
neuronActs[i]->setCheckable(true);
connect(neuronActs[i], SIGNAL(triggered()), this, SLOT(setSomeVar()));
dendriteActs[i] = new QAction(tr("Dendrite var %1").arg(i), this);
dendriteActGroup->addAction(dendriteActs[i]);
dendriteActs[i]->setCheckable(true);
connect(dendriteActs[i], SIGNAL(triggered()), this, SLOT(setSomeVar()));
}
neuronActs[0]->setChecked(true);
dendriteActs[0]->setChecked(true);
// threshold for element visibility
noThresholdAct = new QAction(tr("Show all elements"), this);
thresholdActGroup->addAction(noThresholdAct);
noThresholdAct->setCheckable(true);
noThresholdAct->setChecked(true);
connect(noThresholdAct, SIGNAL(triggered()), this, SLOT(setNoThreshold()));
nonZeroThresholdAct = new QAction(tr("Show elements with non-zero values only"), this);
thresholdActGroup->addAction(nonZeroThresholdAct);
nonZeroThresholdAct->setCheckable(true);
connect(nonZeroThresholdAct, SIGNAL(triggered()), this, SLOT(setNonZeroThreshold()));
showNoneAct = new QAction(tr("Show no elements"), this);
thresholdActGroup->addAction(showNoneAct);
showNoneAct->setCheckable(true);
connect(showNoneAct, SIGNAL(triggered()), this, SLOT(setShowNone()));
viewMenu = menuBar()->addMenu(tr("&View"));
for (unsigned int i = 0; i < 8; i++)
viewMenu->addAction(neuronActs[i]);
viewMenu->addSeparator();
for (unsigned int i = 0; i < 8; i++)
viewMenu->addAction(dendriteActs[i]);
viewMenu->addSeparator();
viewMenu->addAction(noThresholdAct);
viewMenu->addAction(nonZeroThresholdAct);
viewMenu->addAction(showNoneAct);
/* Control menu */
tickAct = new QAction(tr("&Tick"), this);
tickAct->setStatusTip(tr("Run the brain through one iteration"));
tickAct->setEnabled(false);
connect(tickAct, SIGNAL(triggered()), this, SLOT(tick()));
sleepToggleAct = new QAction(tr("&Sleep"), this);
sleepToggleAct->setStatusTip(tr("Set whether the brain is asleep (and dreaming) or not"));
sleepToggleAct->setCheckable(true);
sleepToggleAct->setEnabled(false);
connect(sleepToggleAct, SIGNAL(triggered()), this, SLOT(toggleSleep()));
controlMenu = menuBar()->addMenu(tr("&Control"));
controlMenu->addAction(tickAct);
controlMenu->addAction(sleepToggleAct);
controlToolbar = addToolBar(tr("Control"));
controlToolbar->addAction(tickAct);
/* Help menu */
menuBar()->addSeparator();
aboutAct = new QAction(tr("&About"), this);
aboutAct->setStatusTip(tr("Find out about Brain in a Vat"));
connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));
helpMenu = menuBar()->addMenu(tr("&Help"));
helpMenu->addAction(aboutAct);
}
BrainInAVat::~BrainInAVat() {
if (ourCreature)
delete ourCreature;
delete ourView;
}
// action handlers
void BrainInAVat::open() {
QString fileName = QFileDialog::getOpenFileName(this, tr("Pick a genome"), QString(), tr("Genomes (*.gen)"));
if (!fileName.isEmpty())
loadFile(fileName);
}
void BrainInAVat::openRecentFile() {
QAction *action = qobject_cast<QAction *>(sender());
if (action)
loadFile(action->data().toString());
}
void BrainInAVat::about() {
QMessageBox::about(this, tr("openc2e's Brain in a Vat"), tr("An openc2e tool to monitor and experiment upon creature brains."));
}
void BrainInAVat::tick() {
// brain updates are every 4 ticks
// TODO: this is icky
for (unsigned int i = 0; i < 4; i++)
ourCreature->tick();
ourView->update();
}
void BrainInAVat::setSomeVar() {
QAction *action = qobject_cast<QAction *>(sender());
for (unsigned int i = 0; i < 8; i++) {
if (action == neuronActs[i])
ourView->neuron_var = i;
else if (action == dendriteActs[i])
ourView->dendrite_var = i;
}
ourView->update();
}
void BrainInAVat::setNoThreshold() {
ourView->threshold = -1000.0f;
ourView->update();
}
void BrainInAVat::setNonZeroThreshold() {
ourView->threshold = 0.0f;
ourView->update();
}
void BrainInAVat::setShowNone() {
ourView->threshold = 1000.0f;
ourView->update();
}
void BrainInAVat::toggleSleep() {
ourCreature->setDreaming(!ourCreature->isDreaming());
sleepToggleAct->setChecked(ourCreature->isDreaming());
}
// code to Do Things!
void BrainInAVat::loadFile(const QString &fileName) {
// zot any existing file
setCurrentFile(QString());
if (ourCreature) {
delete ourCreature;
ourCreature = 0;
}
tickAct->setEnabled(false);
sleepToggleAct->setChecked(false);
sleepToggleAct->setEnabled(false);
ourView->update();
ifstream f(fileName.toAscii(), std::ios::binary);
if (f.fail()) {
QMessageBox::warning(this, tr("openc2e's Brain in a Vat"), tr("Cannot read file %1.").arg(fileName));
return;
}
QApplication::setOverrideCursor(Qt::WaitCursor);
// read genome
f >> noskipws;
shared_ptr<genomeFile> gfile(new genomeFile());
try {
f >> *gfile;
} catch (genomeException &e) {
QApplication::restoreOverrideCursor();
QMessageBox::warning(this, tr("openc2e's Brain in a Vat"), tr("Failed loading the genome due to error '%1'!").arg(e.what()));
return;
}
// TODO: dialog to pick age, gender, variant?
// create creature
if (gfile->getVersion() == 3) {
try {
ourCreature = new c2eCreature(gfile, true, 0);
} catch (creaturesException &e) {
QApplication::restoreOverrideCursor();
QMessageBox::warning(this, tr("openc2e's Brain in a Vat"), e.what());
return;
}
} else {
QApplication::restoreOverrideCursor();
QMessageBox::warning(this, tr("openc2e's Brain in a Vat"), tr("This genome is of version %1, which is unsupported.").arg(gfile->getVersion()));
return;
}
QApplication::restoreOverrideCursor();
// we're done; update title/recent files, and display a temporary status message
tickAct->setEnabled(true);
sleepToggleAct->setEnabled(true);
ourView->resize(ourView->minimumSize());
ourView->update();
setCurrentFile(fileName);
statusBar()->showMessage(tr("Loaded %1 genes").arg(gfile->genes.size()), 2000);
}
// Some Recent Files magic.
void BrainInAVat::setCurrentFile(const QString &fileName) {
curFile = fileName;
if (curFile.isEmpty()) {
setWindowTitle(tr("openc2e's Brain in a Vat"));
return; // TODO: is this correct?
} else
setWindowTitle(tr("%1 - %2").arg(strippedName(curFile)).arg(tr("openc2e's Brain in a Vat")));
// read the list of recent files
QSettings settings("ccdevnet.org", "Brain In A Vat");
QStringList files = settings.value("recentFileList").toStringList();
// make sure the current file is at the top!
files.removeAll(fileName);
files.prepend(fileName);
// remove any which are over the size
while (files.size() > MaxRecentFiles)
files.removeLast();
// store the list of recent files
settings.setValue("recentFileList", files);
// update ourselves..
updateRecentFileActions(); // obviously assumes we only have one window
}
void BrainInAVat::updateRecentFileActions() {
// read the list of recent files
QSettings settings("ccdevnet.org", "Brain In A Vat");
QStringList files = settings.value("recentFileList").toStringList();
// enable recent files actions as needed
int numRecentFiles = qMin(files.size(), (int)MaxRecentFiles);
for (int i = 0; i < numRecentFiles; ++i) {
QString text = tr("&%1 %2").arg(i + 1).arg(strippedName(files[i]));
recentFileActs[i]->setText(text);
recentFileActs[i]->setData(files[i]);
recentFileActs[i]->setVisible(true);
}
// make sure the rest are disabled [ie, hidden]
for (int j = numRecentFiles; j < MaxRecentFiles; ++j)
recentFileActs[j]->setVisible(false);
// only show the separator if there are recent files
separatorAct->setVisible(numRecentFiles > 0);
}
QString BrainInAVat::strippedName(const QString &fullFileName) {
return QFileInfo(fullFileName).fileName();
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <Windows.h>
#define NDEBUG
#include <GL/freeglut.h>
#include "Rectangle.h"
#include "Circle.h"
#include <vector>
#include <cstdlib>
#include <ctime>
MF::Circle pilka(0.6, 1.0, 0.0, 0.0);
MF::Rectangle paletka(10, 1, 0.0, 1.0, 0.0);
std::vector<MF::Rectangle> sciany;
std::vector<MF::Rectangle> klocki;
int punkty = 0;
/* GLUT callback Handlers */
void resize(int width, int height)
{
const float ar = (float)width / (float)height;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-ar, ar, -1.0, 1.0, 2.0, 100.0);
gluLookAt(0, 0, 5, 0, 0, 0, 0, 1, 0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
/*logika gry*/
void loop(int value)
{
//sprawdzanie kolizji ze cianami
for (auto itr = sciany.begin(); itr != sciany.end(); itr++)
{
pilka.Kolizja(*itr);
}
for (auto itr = klocki.begin(); itr != klocki.end();)
{
if (pilka.Kolizja(*itr))
{
itr = klocki.erase(itr);
punkty++;
// to wywouje problem - system cls jest wolne
//system("cls");
//printf("Punkty: %d", punkty);
}
else
{
itr++;
}
}
//sprawdzanie kolizji z paletk
pilka.Kolizja(paletka);
//wyliczenie nowej pozycji piki
pilka.Aktualizuj(glutGet(GLUT_ELAPSED_TIME));
pilka.UpdateFigurePosition();
glutTimerFunc(1, loop, 0);
}
void idle()
{
glutPostRedisplay();
}
void display()
{
// clear the scene
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
pilka.Draw();
paletka.Draw();
for (auto itr = sciany.begin(); itr != sciany.end(); itr++)
{
itr->Draw();
}
for (auto itr = klocki.begin(); itr != klocki.end(); itr++)
{
itr->Draw();
}
glPopMatrix();
glutSwapBuffers();
}
void passiveMouseMotion(int mouse_x, int mouse_y)
{
paletka.SetPosition((mouse_x - 300) / 15, -15);
paletka.UpdatePhysicsPosition();
}
void keyboard(unsigned char key_pressed, int mouse_x, int mouse_y)
{
switch (key_pressed)
{
case 'a':
{
paletka.Move(-1.0, 0.0);
}
break;
case 'd':
{
paletka.Move(1.0, 0.0);
}
break;
}
paletka.UpdatePhysicsPosition();
}
void InitGLUTScene(char* window_name)
{
glutInitWindowSize(600, 600);
glutInitWindowPosition(40, 40);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE);
glutCreateWindow(window_name);
// set white as the clear colour
glClearColor(1, 1, 1, 1);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
}
void SetCallbackFunctions()
{
//glutReshapeFunc(resize);
glutDisplayFunc(display);
glutIdleFunc(idle);
glutKeyboardFunc(keyboard);
glutPassiveMotionFunc(passiveMouseMotion);
glutTimerFunc(5, loop, 0);
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS);
}
void InitObjects()
{
//pika
pilka.SetPosition(0, -12);
pilka.UstawPredkosc(3e-2, 60);
pilka.UstawFizyke(9.81*1E-6, -90);
//paletka
paletka.SetPosition(0, -15);
//klocki
for (int l = 2, n = 0; l < 6; l++, n++)
{
for (int i = -16; i < 20; i += 4)
{
double red = (double)(rand() % 1000) / 1000.0;
double green = (double)(rand() % 1000) / 1000.0;
double blue = (double)(rand() % 1000) / 1000.0;
MF::Rectangle newBlock(4, 1, red, green, blue);
newBlock.SetPosition(i, l);
klocki.push_back(newBlock);
}
}
//ciany
{
MF::Rectangle sciana(68, 2, 0.5, 0.5, 0.5);
sciana.SetPosition(0, 20);
sciany.push_back(sciana);
}
{
MF::Rectangle sciana(4, 60, 0.5, 0.5, 0.5);
sciana.SetPosition(21, 0);
sciany.push_back(sciana);
}
{
MF::Rectangle sciana(4, 60, 0.5, 0.5, 0.5);
sciana.SetPosition(-21, 0);
sciany.push_back(sciana);
}
paletka.UpdatePhysicsPosition();
pilka.UpdatePhysicsPosition();
for (auto itr = klocki.begin(); itr != klocki.end(); itr++)
{
itr->UpdatePhysicsPosition();
}
for (auto itr = sciany.begin(); itr != sciany.end(); itr++)
{
itr->UpdatePhysicsPosition();
}
}
int main(int argc, char *argv[])
{
// it's still possible to use console to print messages
printf("Hello openGL world!");
// the same can be done with cout / cin
srand(time(NULL));
glutInit(&argc, argv);
InitGLUTScene("freeglut template");
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glOrtho(-20.0, 20.0, -20.0, 20.0, -20.0, 20.0);
SetCallbackFunctions();
InitObjects();
// start GLUT event loop. It ends when user close the window.
glutMainLoop();
// sposb na wykonanie czego po zakoczeniu gluta
printf("End of GLUT");
return 0;
}<commit_msg>Change from Ortho to Projection, mouse calculation to be fixed<commit_after>#include <iostream>
#include <Windows.h>
#define NDEBUG
#include <GL/freeglut.h>
#include "Rectangle.h"
#include "Circle.h"
#include <vector>
#include <cstdlib>
#include <ctime>
MF::Circle pilka(0.6, 1.0, 0.0, 0.0);
MF::Rectangle paletka(10, 1, 0.0, 1.0, 0.0);
std::vector<MF::Rectangle> sciany;
std::vector<MF::Rectangle> klocki;
int punkty = 0;
/* GLUT callback Handlers */
void resize(int width, int height)
{
const float ar = (float)width / (float)height;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-ar, ar, -1.0, 1.0, 2.0, 100.0);
gluLookAt(0, 0, 45, 0, 0, 0, 0, 1, 0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
/*logika gry*/
void loop(int value)
{
//sprawdzanie kolizji ze cianami
for (auto itr = sciany.begin(); itr != sciany.end(); itr++)
{
pilka.Kolizja(*itr);
}
for (auto itr = klocki.begin(); itr != klocki.end();)
{
if (pilka.Kolizja(*itr))
{
itr = klocki.erase(itr);
punkty++;
// to wywouje problem - system cls jest wolne
//system("cls");
//printf("Punkty: %d", punkty);
}
else
{
itr++;
}
}
//sprawdzanie kolizji z paletk
pilka.Kolizja(paletka);
//wyliczenie nowej pozycji piki
pilka.Aktualizuj(glutGet(GLUT_ELAPSED_TIME));
pilka.UpdateFigurePosition();
glutTimerFunc(1, loop, 0);
}
void idle()
{
glutPostRedisplay();
}
void display()
{
// clear the scene
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
pilka.Draw();
paletka.Draw();
for (auto itr = sciany.begin(); itr != sciany.end(); itr++)
{
itr->Draw();
}
for (auto itr = klocki.begin(); itr != klocki.end(); itr++)
{
itr->Draw();
}
glPopMatrix();
glutSwapBuffers();
}
void passiveMouseMotion(int mouse_x, int mouse_y)
{
paletka.SetPosition((mouse_x - 300) / 15, -15);
paletka.UpdatePhysicsPosition();
}
void keyboard(unsigned char key_pressed, int mouse_x, int mouse_y)
{
switch (key_pressed)
{
case 'a':
{
paletka.Move(-1.0, 0.0);
}
break;
case 'd':
{
paletka.Move(1.0, 0.0);
}
break;
}
paletka.UpdatePhysicsPosition();
}
void InitGLUTScene(char* window_name)
{
glutInitWindowSize(600, 600);
glutInitWindowPosition(40, 40);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE);
glutCreateWindow(window_name);
// set white as the clear colour
glClearColor(1, 1, 1, 1);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
}
void SetCallbackFunctions()
{
glutReshapeFunc(resize);
glutDisplayFunc(display);
glutIdleFunc(idle);
glutKeyboardFunc(keyboard);
glutPassiveMotionFunc(passiveMouseMotion);
glutTimerFunc(5, loop, 0);
glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS);
}
void InitObjects()
{
//pika
pilka.SetPosition(0, -12);
pilka.UstawPredkosc(3e-2, 60);
pilka.UstawFizyke(9.81*1E-6, -90);
//paletka
paletka.SetPosition(0, -15);
//klocki
for (int l = 2, n = 0; l < 6; l++, n++)
{
for (int i = -16; i < 20; i += 4)
{
double red = (double)(rand() % 1000) / 1000.0;
double green = (double)(rand() % 1000) / 1000.0;
double blue = (double)(rand() % 1000) / 1000.0;
MF::Rectangle newBlock(4, 1, red, green, blue);
newBlock.SetPosition(i, l);
klocki.push_back(newBlock);
}
}
//ciany
{
MF::Rectangle sciana(68, 2, 0.5, 0.5, 0.5);
sciana.SetPosition(0, 22);
sciany.push_back(sciana);
}
{
MF::Rectangle sciana(4, 60, 0.5, 0.5, 0.5);
sciana.SetPosition(21, 0);
sciany.push_back(sciana);
}
{
MF::Rectangle sciana(4, 60, 0.5, 0.5, 0.5);
sciana.SetPosition(-21, 0);
sciany.push_back(sciana);
}
paletka.UpdatePhysicsPosition();
pilka.UpdatePhysicsPosition();
for (auto itr = klocki.begin(); itr != klocki.end(); itr++)
{
itr->UpdatePhysicsPosition();
}
for (auto itr = sciany.begin(); itr != sciany.end(); itr++)
{
itr->UpdatePhysicsPosition();
}
}
int main(int argc, char *argv[])
{
// it's still possible to use console to print messages
printf("Hello openGL world!");
// the same can be done with cout / cin
srand(time(NULL));
glutInit(&argc, argv);
InitGLUTScene("freeglut template");
SetCallbackFunctions();
InitObjects();
// start GLUT event loop. It ends when user close the window.
glutMainLoop();
// sposb na wykonanie czego po zakoczeniu gluta
printf("End of GLUT");
return 0;
}<|endoftext|>
|
<commit_before>/*
* Parser.cpp
*****************************************************************************
* Copyright © 2015 - VideoLAN and VLC Authors
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "Parser.hpp"
#include "HLSSegment.hpp"
#include "Representation.hpp"
#include "../adaptative/playlist/BasePeriod.h"
#include "../adaptative/playlist/BaseAdaptationSet.h"
#include "../adaptative/playlist/SegmentList.h"
#include "../adaptative/tools/Retrieve.hpp"
#include "M3U8.hpp"
#include "Tags.hpp"
#include <vlc_strings.h>
#include <vlc_stream.h>
#include <cstdio>
#include <sstream>
#include <map>
using namespace adaptative;
using namespace adaptative::playlist;
using namespace hls::playlist;
Parser::Parser(stream_t *stream)
{
p_stream = stream;
}
Parser::~Parser ()
{
}
static std::list<Tag *> getTagsFromList(std::list<Tag *> &list, int tag)
{
std::list<Tag *> ret;
std::list<Tag *>::const_iterator it;
for(it = list.begin(); it != list.end(); ++it)
{
if( (*it)->getType() == tag )
ret.push_back(*it);
}
return ret;
}
static void releaseTagsList(std::list<Tag *> &list)
{
std::list<Tag *>::const_iterator it;
for(it = list.begin(); it != list.end(); ++it)
delete *it;
list.clear();
}
void Parser::parseAdaptationSet(BasePeriod *period, const AttributesTag *)
{
BaseAdaptationSet *adaptSet = new (std::nothrow) BaseAdaptationSet(period);
if(adaptSet)
{
period->addAdaptationSet(adaptSet);
}
}
void Parser::parseRepresentation(BaseAdaptationSet *adaptSet, const AttributesTag * tag)
{
if(!tag->getAttributeByName("URI"))
return;
Url url;
if(tag->getType() == AttributesTag::EXTXMEDIA)
{
url = Url(tag->getAttributeByName("URI")->quotedString());
}
else
{
url = Url(tag->getAttributeByName("URI")->value);
}
if(!url.hasScheme())
url = url.prepend(adaptSet->getUrlSegment());
void *p_data;
const size_t i_data = Retrieve::HTTP((vlc_object_t*)p_stream, url.toString(), &p_data);
if(p_data)
{
stream_t *substream = stream_MemoryNew((vlc_object_t *)p_stream, (uint8_t *)p_data, i_data, false);
if(substream)
{
std::list<Tag *> tagslist = parseEntries(substream);
stream_Delete(substream);
parseRepresentation(adaptSet, tag, tagslist);
releaseTagsList(tagslist);
}
}
}
void Parser::parseRepresentation(BaseAdaptationSet *adaptSet, const AttributesTag * tag,
const std::list<Tag *> &tagslist)
{
const Attribute *uriAttr = tag->getAttributeByName("URI");
const Attribute *bwAttr = tag->getAttributeByName("BANDWIDTH");
const Attribute *codecsAttr = tag->getAttributeByName("CODECS");
Representation *rep = new (std::nothrow) Representation(adaptSet);
if(rep)
{
if(uriAttr)
{
std::string uri;
if(tag->getType() == AttributesTag::EXTXMEDIA)
{
uri = uriAttr->quotedString();
}
else
{
uri = uriAttr->value;
}
size_t pos = uri.find_last_of('/');
if(pos != std::string::npos)
rep->baseUrl.Set(new Url(uri.substr(0, pos+1)));
}
if(bwAttr)
rep->setBandwidth(bwAttr->decimal());
/* if more than 1 codec, don't probe, can't be packed audio */
if(codecsAttr && codecsAttr->quotedString().find(',') != std::string::npos)
rep->setMimeType("video/mp2t");
parseSegments(rep, tagslist);
adaptSet->addRepresentation(rep);
}
}
void Parser::parseSegments(Representation *rep, const std::list<Tag *> &tagslist)
{
SegmentList *segmentList = new (std::nothrow) SegmentList(rep);
rep->setSegmentList(segmentList);
rep->timescale.Set(100);
int64_t totalduration = 0;
int64_t nzStartTime = 0;
uint64_t sequenceNumber = 0;
std::size_t prevbyterangeoffset = 0;
const SingleValueTag *ctx_byterange = NULL;
SegmentEncryption encryption;
std::list<Tag *>::const_iterator it;
for(it = tagslist.begin(); it != tagslist.end(); ++it)
{
const Tag *tag = *it;
switch(tag->getType())
{
/* using static cast as attribute type permits avoiding class check */
case SingleValueTag::EXTXMEDIASEQUENCE:
{
sequenceNumber = (static_cast<const SingleValueTag*>(tag))->getValue().decimal();
}
break;
case URITag::EXTINF:
{
const URITag *uritag = static_cast<const URITag *>(tag);
HLSSegment *segment = new (std::nothrow) HLSSegment(rep, sequenceNumber++);
if(!segment)
break;
if(uritag->getAttributeByName("URI"))
segment->setSourceUrl(uritag->getAttributeByName("URI")->value);
if(uritag->getAttributeByName("DURATION"))
{
segment->duration.Set(uritag->getAttributeByName("DURATION")->floatingPoint() * rep->timescale.Get());
segment->startTime.Set(nzStartTime);
nzStartTime += segment->duration.Get();
totalduration += segment->duration.Get();
}
segmentList->addSegment(segment);
if(ctx_byterange)
{
std::pair<std::size_t,std::size_t> range = ctx_byterange->getValue().getByteRange();
if(range.first == 0)
range.first = prevbyterangeoffset;
prevbyterangeoffset = range.first + range.second;
segment->setByteRange(range.first, prevbyterangeoffset);
ctx_byterange = NULL;
}
if(encryption.method != SegmentEncryption::NONE)
segment->setEncryption(encryption);
}
break;
case SingleValueTag::EXTXPLAYLISTTYPE:
rep->b_live = (static_cast<const SingleValueTag *>(tag)->getValue().value != "VOD");
break;
case SingleValueTag::EXTXBYTERANGE:
ctx_byterange = static_cast<const SingleValueTag *>(tag);
break;
case AttributesTag::EXTXKEY:
{
const AttributesTag *keytag = static_cast<const AttributesTag *>(tag);
if( keytag->getAttributeByName("METHOD") &&
keytag->getAttributeByName("METHOD")->value == "AES-128" &&
keytag->getAttributeByName("URI") )
{
encryption.method = SegmentEncryption::AES_128;
encryption.key.clear();
uint8_t *p_data;
const uint64_t read = Retrieve::HTTP(VLC_OBJECT(p_stream),
keytag->getAttributeByName("URI")->quotedString(),
(void **) &p_data);
if(p_data)
{
if(read == 16)
{
encryption.key.resize(16);
memcpy(&encryption.key[0], p_data, 16);
}
free(p_data);
}
if(keytag->getAttributeByName("IV"))
{
encryption.iv.clear();
encryption.iv = keytag->getAttributeByName("IV")->hexSequence();
}
}
else
{
/* unsupported or invalid */
encryption.method = SegmentEncryption::NONE;
encryption.key.clear();
encryption.iv.clear();
}
}
break;
case Tag::EXTXENDLIST:
rep->b_live = false;
break;
}
}
if(rep->isLive())
{
rep->getPlaylist()->duration.Set(0);
}
else if(totalduration > rep->getPlaylist()->duration.Get())
{
rep->getPlaylist()->duration.Set(CLOCK_FREQ * totalduration / rep->timescale.Get());
}
}
M3U8 * Parser::parse(const std::string &playlisturl)
{
char *psz_line = stream_ReadLine(p_stream);
if(!psz_line || strcmp(psz_line, "#EXTM3U"))
{
free(psz_line);
return NULL;
}
M3U8 *playlist = new (std::nothrow) M3U8(p_stream);
if(!playlist)
return NULL;
if(!playlisturl.empty())
{
size_t pos = playlisturl.find_last_of('/');
if(pos != std::string::npos)
playlist->addBaseUrl(playlisturl.substr(0, pos + 1));
}
BasePeriod *period = new (std::nothrow) BasePeriod( playlist );
if(!period)
return playlist;
std::list<Tag *> tagslist = parseEntries(p_stream);
bool b_masterplaylist = !getTagsFromList(tagslist, AttributesTag::EXTXSTREAMINF).empty();
if(b_masterplaylist)
{
std::list<Tag *>::const_iterator it;
std::map<std::string, AttributesTag *> groupsmap;
/* We'll need to create an adaptation set for each media group / alternative rendering
* we create a list of playlist being and alternative/group */
std::list<Tag *> mediainfotags = getTagsFromList(tagslist, AttributesTag::EXTXMEDIA);
for(it = mediainfotags.begin(); it != mediainfotags.end(); ++it)
{
AttributesTag *tag = dynamic_cast<AttributesTag *>(*it);
if(tag && tag->getAttributeByName("URI"))
{
std::pair<std::string, AttributesTag *> pair(tag->getAttributeByName("URI")->quotedString(), tag);
groupsmap.insert(pair);
}
}
/* Then we parse all playlists uri and add them, except when alternative */
BaseAdaptationSet *adaptSet = new (std::nothrow) BaseAdaptationSet(period);
if(adaptSet)
{
std::list<Tag *> streaminfotags = getTagsFromList(tagslist, AttributesTag::EXTXSTREAMINF);
for(it = streaminfotags.begin(); it != streaminfotags.end(); ++it)
{
AttributesTag *tag = dynamic_cast<AttributesTag *>(*it);
if(tag && tag->getAttributeByName("URI"))
{
if(groupsmap.find(tag->getAttributeByName("URI")->value) == groupsmap.end())
{
/* not a group, belong to default adaptation set */
parseRepresentation(adaptSet, tag);
}
}
}
if(!adaptSet->getRepresentations().empty())
period->addAdaptationSet(adaptSet);
else
delete adaptSet;
}
/* Finally add all groups */
std::map<std::string, AttributesTag *>::const_iterator groupsit;
for(groupsit = groupsmap.begin(); groupsit != groupsmap.end(); ++groupsit)
{
BaseAdaptationSet *altAdaptSet = new (std::nothrow) BaseAdaptationSet(period);
if(altAdaptSet)
{
std::pair<std::string, AttributesTag *> pair = *groupsit;
parseRepresentation(altAdaptSet, pair.second);
if(!altAdaptSet->getRepresentations().empty())
period->addAdaptationSet(altAdaptSet);
else
delete altAdaptSet;
}
}
}
else
{
BaseAdaptationSet *adaptSet = new (std::nothrow) BaseAdaptationSet(period);
if(adaptSet)
{
period->addAdaptationSet(adaptSet);
AttributesTag *tag = new AttributesTag(AttributesTag::EXTXSTREAMINF, "");
parseRepresentation(adaptSet, tag, tagslist);
delete tag;
}
}
playlist->addPeriod(period);
releaseTagsList(tagslist);
playlist->debug();
return playlist;
}
std::list<Tag *> Parser::parseEntries(stream_t *stream)
{
std::list<Tag *> entrieslist;
Tag *lastTag = NULL;
char *psz_line;
while((psz_line = stream_ReadLine(stream)))
{
if(*psz_line == '#')
{
if(!strncmp(psz_line, "#EXT", 4)) //tag
{
std::string key;
std::string attributes;
const char *split = strchr(psz_line, ':');
if(split)
{
key = std::string(psz_line + 1, split - psz_line - 1);
attributes = std::string(split + 1);
}
else
{
key = std::string(psz_line);
}
if(!key.empty())
{
Tag *tag = TagFactory::createTagByName(key, attributes);
if(tag)
entrieslist.push_back(tag);
lastTag = tag;
}
}
}
else if(*psz_line && lastTag)
{
AttributesTag *attrTag = dynamic_cast<AttributesTag *>(lastTag);
if(attrTag)
{
Attribute *uriAttr = new (std::nothrow) Attribute("URI", std::string(psz_line));
if(uriAttr)
attrTag->addAttribute(uriAttr);
}
lastTag = NULL;
}
else // drop
{
lastTag = NULL;
}
free(psz_line);
}
return entrieslist;
}
<commit_msg>demux: hls: add media description<commit_after>/*
* Parser.cpp
*****************************************************************************
* Copyright © 2015 - VideoLAN and VLC Authors
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "Parser.hpp"
#include "HLSSegment.hpp"
#include "Representation.hpp"
#include "../adaptative/playlist/BasePeriod.h"
#include "../adaptative/playlist/BaseAdaptationSet.h"
#include "../adaptative/playlist/SegmentList.h"
#include "../adaptative/tools/Retrieve.hpp"
#include "M3U8.hpp"
#include "Tags.hpp"
#include <vlc_strings.h>
#include <vlc_stream.h>
#include <cstdio>
#include <sstream>
#include <map>
using namespace adaptative;
using namespace adaptative::playlist;
using namespace hls::playlist;
Parser::Parser(stream_t *stream)
{
p_stream = stream;
}
Parser::~Parser ()
{
}
static std::list<Tag *> getTagsFromList(std::list<Tag *> &list, int tag)
{
std::list<Tag *> ret;
std::list<Tag *>::const_iterator it;
for(it = list.begin(); it != list.end(); ++it)
{
if( (*it)->getType() == tag )
ret.push_back(*it);
}
return ret;
}
static void releaseTagsList(std::list<Tag *> &list)
{
std::list<Tag *>::const_iterator it;
for(it = list.begin(); it != list.end(); ++it)
delete *it;
list.clear();
}
void Parser::parseAdaptationSet(BasePeriod *period, const AttributesTag *)
{
BaseAdaptationSet *adaptSet = new (std::nothrow) BaseAdaptationSet(period);
if(adaptSet)
{
period->addAdaptationSet(adaptSet);
}
}
void Parser::parseRepresentation(BaseAdaptationSet *adaptSet, const AttributesTag * tag)
{
if(!tag->getAttributeByName("URI"))
return;
Url url;
if(tag->getType() == AttributesTag::EXTXMEDIA)
{
url = Url(tag->getAttributeByName("URI")->quotedString());
}
else
{
url = Url(tag->getAttributeByName("URI")->value);
}
if(!url.hasScheme())
url = url.prepend(adaptSet->getUrlSegment());
void *p_data;
const size_t i_data = Retrieve::HTTP((vlc_object_t*)p_stream, url.toString(), &p_data);
if(p_data)
{
stream_t *substream = stream_MemoryNew((vlc_object_t *)p_stream, (uint8_t *)p_data, i_data, false);
if(substream)
{
std::list<Tag *> tagslist = parseEntries(substream);
stream_Delete(substream);
parseRepresentation(adaptSet, tag, tagslist);
releaseTagsList(tagslist);
}
}
}
void Parser::parseRepresentation(BaseAdaptationSet *adaptSet, const AttributesTag * tag,
const std::list<Tag *> &tagslist)
{
const Attribute *uriAttr = tag->getAttributeByName("URI");
const Attribute *bwAttr = tag->getAttributeByName("BANDWIDTH");
const Attribute *codecsAttr = tag->getAttributeByName("CODECS");
Representation *rep = new (std::nothrow) Representation(adaptSet);
if(rep)
{
if(uriAttr)
{
std::string uri;
if(tag->getType() == AttributesTag::EXTXMEDIA)
{
uri = uriAttr->quotedString();
}
else
{
uri = uriAttr->value;
}
size_t pos = uri.find_last_of('/');
if(pos != std::string::npos)
rep->baseUrl.Set(new Url(uri.substr(0, pos+1)));
}
if(bwAttr)
rep->setBandwidth(bwAttr->decimal());
/* if more than 1 codec, don't probe, can't be packed audio */
if(codecsAttr && codecsAttr->quotedString().find(',') != std::string::npos)
rep->setMimeType("video/mp2t");
parseSegments(rep, tagslist);
adaptSet->addRepresentation(rep);
}
}
void Parser::parseSegments(Representation *rep, const std::list<Tag *> &tagslist)
{
SegmentList *segmentList = new (std::nothrow) SegmentList(rep);
rep->setSegmentList(segmentList);
rep->timescale.Set(100);
int64_t totalduration = 0;
int64_t nzStartTime = 0;
uint64_t sequenceNumber = 0;
std::size_t prevbyterangeoffset = 0;
const SingleValueTag *ctx_byterange = NULL;
SegmentEncryption encryption;
std::list<Tag *>::const_iterator it;
for(it = tagslist.begin(); it != tagslist.end(); ++it)
{
const Tag *tag = *it;
switch(tag->getType())
{
/* using static cast as attribute type permits avoiding class check */
case SingleValueTag::EXTXMEDIASEQUENCE:
{
sequenceNumber = (static_cast<const SingleValueTag*>(tag))->getValue().decimal();
}
break;
case URITag::EXTINF:
{
const URITag *uritag = static_cast<const URITag *>(tag);
HLSSegment *segment = new (std::nothrow) HLSSegment(rep, sequenceNumber++);
if(!segment)
break;
if(uritag->getAttributeByName("URI"))
segment->setSourceUrl(uritag->getAttributeByName("URI")->value);
if(uritag->getAttributeByName("DURATION"))
{
segment->duration.Set(uritag->getAttributeByName("DURATION")->floatingPoint() * rep->timescale.Get());
segment->startTime.Set(nzStartTime);
nzStartTime += segment->duration.Get();
totalduration += segment->duration.Get();
}
segmentList->addSegment(segment);
if(ctx_byterange)
{
std::pair<std::size_t,std::size_t> range = ctx_byterange->getValue().getByteRange();
if(range.first == 0)
range.first = prevbyterangeoffset;
prevbyterangeoffset = range.first + range.second;
segment->setByteRange(range.first, prevbyterangeoffset);
ctx_byterange = NULL;
}
if(encryption.method != SegmentEncryption::NONE)
segment->setEncryption(encryption);
}
break;
case SingleValueTag::EXTXPLAYLISTTYPE:
rep->b_live = (static_cast<const SingleValueTag *>(tag)->getValue().value != "VOD");
break;
case SingleValueTag::EXTXBYTERANGE:
ctx_byterange = static_cast<const SingleValueTag *>(tag);
break;
case AttributesTag::EXTXKEY:
{
const AttributesTag *keytag = static_cast<const AttributesTag *>(tag);
if( keytag->getAttributeByName("METHOD") &&
keytag->getAttributeByName("METHOD")->value == "AES-128" &&
keytag->getAttributeByName("URI") )
{
encryption.method = SegmentEncryption::AES_128;
encryption.key.clear();
uint8_t *p_data;
const uint64_t read = Retrieve::HTTP(VLC_OBJECT(p_stream),
keytag->getAttributeByName("URI")->quotedString(),
(void **) &p_data);
if(p_data)
{
if(read == 16)
{
encryption.key.resize(16);
memcpy(&encryption.key[0], p_data, 16);
}
free(p_data);
}
if(keytag->getAttributeByName("IV"))
{
encryption.iv.clear();
encryption.iv = keytag->getAttributeByName("IV")->hexSequence();
}
}
else
{
/* unsupported or invalid */
encryption.method = SegmentEncryption::NONE;
encryption.key.clear();
encryption.iv.clear();
}
}
break;
case Tag::EXTXENDLIST:
rep->b_live = false;
break;
}
}
if(rep->isLive())
{
rep->getPlaylist()->duration.Set(0);
}
else if(totalduration > rep->getPlaylist()->duration.Get())
{
rep->getPlaylist()->duration.Set(CLOCK_FREQ * totalduration / rep->timescale.Get());
}
}
M3U8 * Parser::parse(const std::string &playlisturl)
{
char *psz_line = stream_ReadLine(p_stream);
if(!psz_line || strcmp(psz_line, "#EXTM3U"))
{
free(psz_line);
return NULL;
}
M3U8 *playlist = new (std::nothrow) M3U8(p_stream);
if(!playlist)
return NULL;
if(!playlisturl.empty())
{
size_t pos = playlisturl.find_last_of('/');
if(pos != std::string::npos)
playlist->addBaseUrl(playlisturl.substr(0, pos + 1));
}
BasePeriod *period = new (std::nothrow) BasePeriod( playlist );
if(!period)
return playlist;
std::list<Tag *> tagslist = parseEntries(p_stream);
bool b_masterplaylist = !getTagsFromList(tagslist, AttributesTag::EXTXSTREAMINF).empty();
if(b_masterplaylist)
{
std::list<Tag *>::const_iterator it;
std::map<std::string, AttributesTag *> groupsmap;
/* We'll need to create an adaptation set for each media group / alternative rendering
* we create a list of playlist being and alternative/group */
std::list<Tag *> mediainfotags = getTagsFromList(tagslist, AttributesTag::EXTXMEDIA);
for(it = mediainfotags.begin(); it != mediainfotags.end(); ++it)
{
AttributesTag *tag = dynamic_cast<AttributesTag *>(*it);
if(tag && tag->getAttributeByName("URI"))
{
std::pair<std::string, AttributesTag *> pair(tag->getAttributeByName("URI")->quotedString(), tag);
groupsmap.insert(pair);
}
}
/* Then we parse all playlists uri and add them, except when alternative */
BaseAdaptationSet *adaptSet = new (std::nothrow) BaseAdaptationSet(period);
if(adaptSet)
{
std::list<Tag *> streaminfotags = getTagsFromList(tagslist, AttributesTag::EXTXSTREAMINF);
for(it = streaminfotags.begin(); it != streaminfotags.end(); ++it)
{
AttributesTag *tag = dynamic_cast<AttributesTag *>(*it);
if(tag && tag->getAttributeByName("URI"))
{
if(groupsmap.find(tag->getAttributeByName("URI")->value) == groupsmap.end())
{
/* not a group, belong to default adaptation set */
parseRepresentation(adaptSet, tag);
}
}
}
if(!adaptSet->getRepresentations().empty())
period->addAdaptationSet(adaptSet);
else
delete adaptSet;
}
/* Finally add all groups */
std::map<std::string, AttributesTag *>::const_iterator groupsit;
for(groupsit = groupsmap.begin(); groupsit != groupsmap.end(); ++groupsit)
{
BaseAdaptationSet *altAdaptSet = new (std::nothrow) BaseAdaptationSet(period);
if(altAdaptSet)
{
std::pair<std::string, AttributesTag *> pair = *groupsit;
parseRepresentation(altAdaptSet, pair.second);
if(pair.second->getAttributeByName("NAME"))
altAdaptSet->description.Set(pair.second->getAttributeByName("NAME")->quotedString());
if(!altAdaptSet->getRepresentations().empty())
period->addAdaptationSet(altAdaptSet);
else
delete altAdaptSet;
}
}
}
else
{
BaseAdaptationSet *adaptSet = new (std::nothrow) BaseAdaptationSet(period);
if(adaptSet)
{
period->addAdaptationSet(adaptSet);
AttributesTag *tag = new AttributesTag(AttributesTag::EXTXSTREAMINF, "");
parseRepresentation(adaptSet, tag, tagslist);
delete tag;
}
}
playlist->addPeriod(period);
releaseTagsList(tagslist);
playlist->debug();
return playlist;
}
std::list<Tag *> Parser::parseEntries(stream_t *stream)
{
std::list<Tag *> entrieslist;
Tag *lastTag = NULL;
char *psz_line;
while((psz_line = stream_ReadLine(stream)))
{
if(*psz_line == '#')
{
if(!strncmp(psz_line, "#EXT", 4)) //tag
{
std::string key;
std::string attributes;
const char *split = strchr(psz_line, ':');
if(split)
{
key = std::string(psz_line + 1, split - psz_line - 1);
attributes = std::string(split + 1);
}
else
{
key = std::string(psz_line);
}
if(!key.empty())
{
Tag *tag = TagFactory::createTagByName(key, attributes);
if(tag)
entrieslist.push_back(tag);
lastTag = tag;
}
}
}
else if(*psz_line && lastTag)
{
AttributesTag *attrTag = dynamic_cast<AttributesTag *>(lastTag);
if(attrTag)
{
Attribute *uriAttr = new (std::nothrow) Attribute("URI", std::string(psz_line));
if(uriAttr)
attrTag->addAttribute(uriAttr);
}
lastTag = NULL;
}
else // drop
{
lastTag = NULL;
}
free(psz_line);
}
return entrieslist;
}
<|endoftext|>
|
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbMultivariateAlterationDetectorImageFilter.h"
typedef otb::VectorImage<unsigned short,2> ImageType;
typedef otb::VectorImage<double,2> OutputImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::ImageFileWriter<OutputImageType> WriterType;
typedef otb::MultivariateAlterationDetectorImageFilter<ImageType,OutputImageType> MADFilterType;
int otbMultivariateAlterationDetectorImageFilterNew(int argc, char* argv[])
{
MADFilterType::Pointer madFilter = MADFilterType::New();
return EXIT_SUCCESS;
}
int otbMultivariateAlterationDetectorImageFilter(int argc, char* argv[])
{
char * infname1 = argv[1];
char * infname2 = argv[2];
char * outfname = argv[3];
ReaderType::Pointer reader1 = ReaderType::New();
reader1->SetFileName(infname1);
ReaderType::Pointer reader2 = ReaderType::New();
reader2->SetFileName(infname2);
MADFilterType::Pointer madFilter = MADFilterType::New();
madFilter->SetInput1(reader1->GetOutput());
madFilter->SetInput2(reader2->GetOutput());
WriterType::Pointer writer = WriterType::New();
writer->SetInput(madFilter->GetOutput());
writer->SetFileName(outfname);
writer->Update();
return EXIT_SUCCESS;
}
<commit_msg>TEST: Adding v1, v2 and rho output in test<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbVectorImage.h"
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbMultivariateAlterationDetectorImageFilter.h"
typedef otb::VectorImage<unsigned short,2> ImageType;
typedef otb::VectorImage<double,2> OutputImageType;
typedef otb::ImageFileReader<ImageType> ReaderType;
typedef otb::ImageFileWriter<OutputImageType> WriterType;
typedef otb::MultivariateAlterationDetectorImageFilter<ImageType,OutputImageType> MADFilterType;
int otbMultivariateAlterationDetectorImageFilterNew(int argc, char* argv[])
{
MADFilterType::Pointer madFilter = MADFilterType::New();
return EXIT_SUCCESS;
}
int otbMultivariateAlterationDetectorImageFilter(int argc, char* argv[])
{
char * infname1 = argv[1];
char * infname2 = argv[2];
char * outfname = argv[3];
ReaderType::Pointer reader1 = ReaderType::New();
reader1->SetFileName(infname1);
ReaderType::Pointer reader2 = ReaderType::New();
reader2->SetFileName(infname2);
MADFilterType::Pointer madFilter = MADFilterType::New();
madFilter->SetInput1(reader1->GetOutput());
madFilter->SetInput2(reader2->GetOutput());
WriterType::Pointer writer = WriterType::New();
writer->SetInput(madFilter->GetOutput());
writer->SetFileName(outfname);
writer->Update();
std::cout<<"V1: "<<std::endl;
std::cout<<madFilter->GetV1()<<std::endl;
std::cout<<"V2: "<<std::endl;
std::cout<<madFilter->GetV2()<<std::endl;
std::cout<<"Rho: "<<std::endl;
std::cout<<madFilter->GetRho()<<std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include <stan/math/error_handling/matrix/check_cov_matrix.hpp>
#include <gtest/gtest.h>
TEST(MathErrorHandlingMatrix, checkCovMatrix) {
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> y;
double result;
y.resize(3,3);
y << 2, -1, 0, -1, 2, -1, 0, -1, 2;
EXPECT_TRUE(stan::math::check_cov_matrix("checkCovMatrix(%1%)",
y, "y", &result));
y << 1, 2, 3, 2, 1, 2, 3, 2, 1;
EXPECT_THROW(stan::math::check_cov_matrix("checkCovMatrix(%1%)", y, "y", &result),
std::domain_error);
}
<commit_msg>added NaN test for check_cov_matrix<commit_after>#include <stan/math/error_handling/matrix/check_cov_matrix.hpp>
#include <gtest/gtest.h>
TEST(MathErrorHandlingMatrix, checkCovMatrix) {
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> y;
double result;
y.resize(3,3);
y << 2, -1, 0, -1, 2, -1, 0, -1, 2;
EXPECT_TRUE(stan::math::check_cov_matrix("checkCovMatrix(%1%)",
y, "y", &result));
y << 1, 2, 3, 2, 1, 2, 3, 2, 1;
EXPECT_THROW(stan::math::check_cov_matrix("checkCovMatrix(%1%)", y, "y", &result),
std::domain_error);
}
TEST(MathErrorHandlingMatrix, checkCovMatrix_nan) {
Eigen::Matrix<double,Eigen::Dynamic,Eigen::Dynamic> y;
double result;
double nan = std::numeric_limits<double>::quiet_NaN();
y.resize(3,3);
y << 2, -1, 0, -1, 2, -1, 0, -1, 2;
EXPECT_TRUE(stan::math::check_cov_matrix("checkCovMatrix(%1%)",
y, "y", &result));
for (int i = 0; i < y.size(); i++) {
y(i) = nan;
EXPECT_THROW(stan::math::check_cov_matrix("checkCovMatrix(%1%)", y, "y", &result),
std::domain_error);
y << 2, -1, 0, -1, 2, -1, 0, -1, 2;
}
}
<|endoftext|>
|
<commit_before>/* Copyright 2020 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/compiler/xla/service/fusion_node_indexing_evaluation.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/core/platform/logging.h"
namespace xla {
FusionNodeIndexingEvaluation::FusionNodeIndexingEvaluation(
const HloInstruction* fusion)
: fusion_(fusion) {
total_emitted_instructions_ = 0;
HloInstruction* root = fusion->fused_expression_root();
indexing_users_[root].insert(fusion);
index_usage_count_[fusion] = 1;
RecomputeCache();
}
bool FusionNodeIndexingEvaluation::AverageCodeDuplicationTooHigh(
const HloInstruction* producer) const {
// This constant is arbitrarily chosen. Essentially we don't want to have too
// much code duplication, because it slows down the compilation time. There is
// a tradeoff between compilation time and runtime here.
const int64 kAllowedCodeDuplication = 15;
// index_usage_count_ contains an entry for each instruction in the fusion
// computation (except parameter instructions), plus an entry for the 'fusion'
// instruction. So the size of this map is already one bigger than the number
// of instructions in the fusion node that are emitted, thus accounting for
// the number of instructions after 'producer' is fused.
return EvaluateTotalEmittedInstructions(producer) /
index_usage_count_.size() >
kAllowedCodeDuplication;
}
int64 FusionNodeIndexingEvaluation::EvaluateTotalEmittedInstructions(
const HloInstruction* producer) const {
int64 total = total_emitted_instructions_;
for (const auto* user : indexing_users_.at(producer)) {
total += index_usage_count_.at(user);
}
return total;
}
void FusionNodeIndexingEvaluation::UpdateEvaluationCache(
const HloInstruction* producer,
absl::flat_hash_set<const HloInstruction*> indexing_users_of_producer) {
CHECK(!indexing_users_.contains(producer));
indexing_users_[producer] = std::move(indexing_users_of_producer);
UpdateIndexUsageCount(producer);
UpdateIndexingUsersOfOperands(producer);
}
absl::flat_hash_set<const HloInstruction*>
FusionNodeIndexingEvaluation::RemoveFusionOperand(
HloInstruction* fusion_operand) {
auto indexing_users_of_operand =
std::move(indexing_users_.at(fusion_operand));
indexing_users_.erase(fusion_operand);
CHECK(!index_usage_count_.contains(fusion_operand));
return indexing_users_of_operand;
}
void FusionNodeIndexingEvaluation::RecomputeCache() {
auto postorder =
fusion_->fused_instructions_computation()->MakeInstructionPostOrder();
std::reverse(postorder.begin(), postorder.end());
for (const auto* instruction : postorder) {
if (instruction->opcode() == HloOpcode::kParameter) {
continue;
}
UpdateIndexUsageCount(instruction);
UpdateIndexingUsersOfOperands(instruction);
}
}
void FusionNodeIndexingEvaluation::UpdateIndexUsageCount(
const HloInstruction* instruction) {
int64 total = 0;
for (const auto* user : indexing_users_[instruction]) {
int64 weight = 1;
// Concatenate is special: the index differs for each operand, so
// in the worst case we have to deal with as many index values as
// the number of operands of Concatenate. By considering the worst
// case, we are more conservative than necessary regarding
// counting the index usage.
if (user->opcode() == HloOpcode::kConcatenate) {
weight = user->operand_count();
}
total += index_usage_count_.at(user) * weight;
}
CHECK(index_usage_count_.emplace(instruction, total).second);
total_emitted_instructions_ += total;
}
void FusionNodeIndexingEvaluation::UpdateIndexingUsersOfOperands(
const HloInstruction* instruction) {
for (const auto* operand : instruction->operands()) {
if (operand->opcode() == HloOpcode::kParameter) {
// Although actually the parameter gets indexed, we store it as indexing
// of the corresponding fusion operand instead because parameter
// instruction pointers can be invalidated when we fuse another
// instruction into 'fusion_'.
operand = fusion_->operand(operand->parameter_number());
}
// For simplicity we assume that all shape and layout changing
// operations except Transposes invalidate index reuse. Transposes are
// special: although they are shape changing, we can reuse the
// multi-dimensional index for the operand by permuting it.
if (instruction->opcode() == HloOpcode::kTranspose ||
Shape::Equal().IgnoreElementType()(operand->shape(),
instruction->shape())) {
// If the index is reused, it means the operand gets index values
// from the same set of (indirect) users as 'instruction' itself.
indexing_users_[operand].insert(indexing_users_[instruction].begin(),
indexing_users_[instruction].end());
} else {
// If the index is not reused, it means 'instruction' computes a
// new index derived from the index it gets.
indexing_users_[operand].insert(instruction);
}
}
}
} // namespace xla
<commit_msg>We shouldn't take the worst case scenario for concatenate and fusion. This is the last step to make the new test pass.<commit_after>/* Copyright 2020 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/compiler/xla/service/fusion_node_indexing_evaluation.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/core/platform/logging.h"
namespace xla {
FusionNodeIndexingEvaluation::FusionNodeIndexingEvaluation(
const HloInstruction* fusion)
: fusion_(fusion) {
total_emitted_instructions_ = 0;
HloInstruction* root = fusion->fused_expression_root();
indexing_users_[root].insert(fusion);
index_usage_count_[fusion] = 1;
RecomputeCache();
}
bool FusionNodeIndexingEvaluation::AverageCodeDuplicationTooHigh(
const HloInstruction* producer) const {
// This constant is arbitrarily chosen. Essentially we don't want to have too
// much code duplication, because it slows down the compilation time. There is
// a tradeoff between compilation time and runtime here.
const int64 kAllowedCodeDuplication = 15;
// index_usage_count_ contains an entry for each instruction in the fusion
// computation (except parameter instructions), plus an entry for the 'fusion'
// instruction. So the size of this map is already one bigger than the number
// of instructions in the fusion node that are emitted, thus accounting for
// the number of instructions after 'producer' is fused.
return EvaluateTotalEmittedInstructions(producer) /
index_usage_count_.size() >
kAllowedCodeDuplication;
}
int64 FusionNodeIndexingEvaluation::EvaluateTotalEmittedInstructions(
const HloInstruction* producer) const {
int64 total = total_emitted_instructions_;
for (const auto* user : indexing_users_.at(producer)) {
total += index_usage_count_.at(user);
}
return total;
}
void FusionNodeIndexingEvaluation::UpdateEvaluationCache(
const HloInstruction* producer,
absl::flat_hash_set<const HloInstruction*> indexing_users_of_producer) {
CHECK(!indexing_users_.contains(producer));
indexing_users_[producer] = std::move(indexing_users_of_producer);
UpdateIndexUsageCount(producer);
UpdateIndexingUsersOfOperands(producer);
}
absl::flat_hash_set<const HloInstruction*>
FusionNodeIndexingEvaluation::RemoveFusionOperand(
HloInstruction* fusion_operand) {
auto indexing_users_of_operand =
std::move(indexing_users_.at(fusion_operand));
indexing_users_.erase(fusion_operand);
CHECK(!index_usage_count_.contains(fusion_operand));
return indexing_users_of_operand;
}
void FusionNodeIndexingEvaluation::RecomputeCache() {
auto postorder =
fusion_->fused_instructions_computation()->MakeInstructionPostOrder();
std::reverse(postorder.begin(), postorder.end());
for (const auto* instruction : postorder) {
if (instruction->opcode() == HloOpcode::kParameter) {
continue;
}
UpdateIndexUsageCount(instruction);
UpdateIndexingUsersOfOperands(instruction);
}
}
void FusionNodeIndexingEvaluation::UpdateIndexUsageCount(
const HloInstruction* instruction) {
int64 total = 0;
for (const auto* user : indexing_users_[instruction]) {
total += index_usage_count_.at(user);
}
CHECK(index_usage_count_.emplace(instruction, total).second);
total_emitted_instructions_ += total;
}
void FusionNodeIndexingEvaluation::UpdateIndexingUsersOfOperands(
const HloInstruction* instruction) {
for (const auto* operand : instruction->operands()) {
if (operand->opcode() == HloOpcode::kParameter) {
// Although actually the parameter gets indexed, we store it as indexing
// of the corresponding fusion operand instead because parameter
// instruction pointers can be invalidated when we fuse another
// instruction into 'fusion_'.
operand = fusion_->operand(operand->parameter_number());
}
// For simplicity we assume that all shape and layout changing
// operations except Transposes invalidate index reuse. Transposes are
// special: although they are shape changing, we can reuse the
// multi-dimensional index for the operand by permuting it.
if (instruction->opcode() == HloOpcode::kTranspose ||
Shape::Equal().IgnoreElementType()(operand->shape(),
instruction->shape())) {
// If the index is reused, it means the operand gets index values
// from the same set of (indirect) users as 'instruction' itself.
indexing_users_[operand].insert(indexing_users_[instruction].begin(),
indexing_users_[instruction].end());
} else {
// If the index is not reused, it means 'instruction' computes a
// new index derived from the index it gets.
indexing_users_[operand].insert(instruction);
}
}
}
} // namespace xla
<|endoftext|>
|
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
// PCL
#include <boost/thread/thread.hpp>
#include <Eigen/Geometry>
#include <pcl/common/common.h>
#define MEASURE_FUNCTION_TIME
#include <pcl/common/time.h> //fps calculations
#include <pcl/io/pcd_io.h>
#include <pcl/io/openni_grabber.h>
#include <cfloat>
#include <pcl/visualization/point_cloud_handlers.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/visualization/histogram_visualizer.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
#define SHOW_FPS 1
#if SHOW_FPS
#define FPS_CALC(_WHAT_) \
do \
{ \
static unsigned count = 0;\
static double last = pcl::getTime ();\
if (++count == 100) \
{ \
double now = pcl::getTime (); \
std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" << std::endl; \
count = 0; \
last = now; \
} \
}while(false)
#else
#define FPS_CALC(_WHAT_) \
do \
{ \
}while(false)
#endif
using pcl::console::print_color;
using pcl::console::print_error;
using pcl::console::print_error;
using pcl::console::print_warn;
using pcl::console::print_info;
using pcl::console::print_debug;
using pcl::console::print_value;
using pcl::console::print_highlight;
using pcl::console::TT_BRIGHT;
using pcl::console::TT_RED;
using pcl::console::TT_GREEN;
using pcl::console::TT_BLUE;
boost::mutex mutex_;
pcl::PointCloud<pcl::PointXYZ>::ConstPtr g_cloud;
bool new_cloud = false;
void
printHelp (int argc, char **argv)
{
//print_error ("Syntax is: %s <file_name 1..N>.pcd <options>\n", argv[0]);
print_error ("Syntax is: %s <options>\n", argv[0]);
print_info (" where options are:\n");
print_info (" -dev device_id = device to be used\n");
print_info (" maybe \"#n\", with n being the number of the device in device list.\n");
print_info (" maybe \"bus@addr\", with bus and addr being the usb bus and address where device is connected.\n");
print_info (" maybe \"serial\", with serial being the serial number of the device.\n");
print_info ("\n");
}
// Create the PCLVisualizer object
boost::shared_ptr<pcl::visualization::PCLVisualizer> p;
struct EventHelper
{
void
cloud_cb (const pcl::PointCloud<pcl::PointXYZ>::ConstPtr & cloud)
{
FPS_CALC ("callback");
if (mutex_.try_lock ())
{
g_cloud = cloud;
new_cloud = true;
mutex_.unlock ();
}
}
};
/* ---[ */
int
main (int argc, char** argv)
{
srand (time (0));
if (argc > 1)
{
for (int i = 1; i < argc; i++)
{
if (std::string (argv[i]) == "-h")
{
printHelp (argc, argv);
return (-1);
}
}
}
p.reset (new pcl::visualization::PCLVisualizer (argc, argv, "OpenNI Viewer"));
std::string device_id = "";
pcl::console::parse_argument (argc, argv, "-dev", device_id);
pcl::Grabber* interface = new pcl::OpenNIGrabber (device_id);
EventHelper h;
boost::function<void(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr&) > f = boost::bind (&EventHelper::cloud_cb, &h, _1);
boost::signals2::connection c1 = interface->registerCallback (f);
interface->start ();
while (!p->wasStopped ())
{
p->spinOnce ();
if (new_cloud && mutex_.try_lock ())
{
new_cloud = false;
if (g_cloud)
{
FPS_CALC ("drawing");
if (!p->updatePointCloud<pcl::PointXYZ> (g_cloud, "OpenNICloud"))
{
p->addPointCloud<pcl::PointXYZ> (g_cloud, "OpenNICloud");
p->resetCameraViewpoint ("OpenNICloud");
}
}
mutex_.unlock ();
}
else
boost::this_thread::sleep (boost::posix_time::microseconds (1000));
}
interface->stop ();
}
/* ]--- */
<commit_msg>openni_viewer now gets 30Hz XYZRGB<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*
*/
// PCL
#include <boost/thread/thread.hpp>
#include <Eigen/Geometry>
#include <pcl/common/common.h>
#define MEASURE_FUNCTION_TIME
#include <pcl/common/time.h> //fps calculations
#include <pcl/io/pcd_io.h>
#include <pcl/io/openni_grabber.h>
#include <cfloat>
#include <pcl/visualization/point_cloud_handlers.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/visualization/histogram_visualizer.h>
#include <pcl/console/print.h>
#include <pcl/console/parse.h>
#include <pcl/console/time.h>
#define SHOW_FPS 1
#if SHOW_FPS
#define FPS_CALC(_WHAT_) \
do \
{ \
static unsigned count = 0;\
static double last = pcl::getTime ();\
if (++count == 100) \
{ \
double now = pcl::getTime (); \
std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" << std::endl; \
count = 0; \
last = now; \
} \
}while(false)
#else
#define FPS_CALC(_WHAT_) \
do \
{ \
}while(false)
#endif
using pcl::console::print_color;
using pcl::console::print_error;
using pcl::console::print_error;
using pcl::console::print_warn;
using pcl::console::print_info;
using pcl::console::print_debug;
using pcl::console::print_value;
using pcl::console::print_highlight;
using pcl::console::TT_BRIGHT;
using pcl::console::TT_RED;
using pcl::console::TT_GREEN;
using pcl::console::TT_BLUE;
boost::mutex mutex_;
pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr g_cloud;
bool new_cloud = false;
void
printHelp (int argc, char **argv)
{
//print_error ("Syntax is: %s <file_name 1..N>.pcd <options>\n", argv[0]);
print_error ("Syntax is: %s <options>\n", argv[0]);
print_info (" where options are:\n");
print_info (" -dev device_id = device to be used\n");
print_info (" maybe \"#n\", with n being the number of the device in device list.\n");
print_info (" maybe \"bus@addr\", with bus and addr being the usb bus and address where device is connected.\n");
print_info (" maybe \"serial\", with serial being the serial number of the device.\n");
print_info ("\n");
}
// Create the PCLVisualizer object
boost::shared_ptr<pcl::visualization::PCLVisualizer> p;
struct EventHelper
{
void
cloud_cb (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr & cloud)
{
FPS_CALC ("callback");
if (mutex_.try_lock ())
{
g_cloud = cloud;
new_cloud = true;
mutex_.unlock ();
}
}
};
/* ---[ */
int
main (int argc, char** argv)
{
srand (time (0));
if (argc > 1)
{
for (int i = 1; i < argc; i++)
{
if (std::string (argv[i]) == "-h")
{
printHelp (argc, argv);
return (-1);
}
}
}
p.reset (new pcl::visualization::PCLVisualizer (argc, argv, "OpenNI Viewer"));
std::string device_id = "";
pcl::console::parse_argument (argc, argv, "-dev", device_id);
pcl::Grabber* interface = new pcl::OpenNIGrabber (device_id);
EventHelper h;
boost::function<void(const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr&) > f = boost::bind (&EventHelper::cloud_cb, &h, _1);
boost::signals2::connection c1 = interface->registerCallback (f);
interface->start ();
while (!p->wasStopped ())
{
p->spinOnce ();
if (new_cloud && mutex_.try_lock ())
{
new_cloud = false;
if (g_cloud)
{
FPS_CALC ("drawing");
pcl::visualization::PointCloudColorHandlerRGBField<pcl::PointXYZRGB> handler (g_cloud);
if (!p->updatePointCloud<pcl::PointXYZRGB> (g_cloud, handler, "OpenNICloud"))
{
p->addPointCloud<pcl::PointXYZRGB> (g_cloud, handler, "OpenNICloud");
p->resetCameraViewpoint ("OpenNICloud");
}
}
mutex_.unlock ();
}
else
boost::this_thread::sleep (boost::posix_time::microseconds (1000));
}
interface->stop ();
}
/* ]--- */
<|endoftext|>
|
<commit_before>
#include <boost/asio.hpp>
#include "vtrc-common/vtrc-mutex-typedefs.h"
#include "vtrc-bind.h"
#include "vtrc-function.h"
#include "vtrc-protocol-layer-s.h"
#include "vtrc-monotonic-timer.h"
#include "vtrc-data-queue.h"
#include "vtrc-hash-iface.h"
#include "vtrc-transformer-iface.h"
#include "vtrc-transport-iface.h"
#include "vtrc-common/vtrc-rpc-service-wrapper.h"
#include "vtrc-common/vtrc-exception.h"
#include "vtrc-common/vtrc-rpc-controller.h"
#include "vtrc-common/vtrc-call-context.h"
#include "vtrc-application.h"
#include "protocol/vtrc-errors.pb.h"
#include "protocol/vtrc-auth.pb.h"
#include "protocol/vtrc-rpc-lowlevel.pb.h"
#include "vtrc-chrono.h"
#include "vtrc-atomic.h"
#include "vtrc-common/vtrc-random-device.h"
#include "vtrc-common/vtrc-delayed-call.h"
namespace vtrc { namespace server {
namespace gpb = google::protobuf;
namespace bsys = boost::system;
namespace basio = boost::asio;
namespace {
enum init_stage_enum {
stage_begin = 1
,stage_client_select = 2
,stage_client_ready = 3
};
typedef std::map <
std::string,
common::rpc_service_wrapper_sptr
> service_map;
typedef vtrc_rpc_lowlevel::lowlevel_unit lowlevel_unit_type;
typedef vtrc::shared_ptr<lowlevel_unit_type> lowlevel_unit_sptr;
}
namespace data_queue = common::data_queue;
struct protocol_layer_s::impl {
typedef impl this_type;
typedef protocol_layer_s parent_type;
application &app_;
common::transport_iface *connection_;
protocol_layer_s *parent_;
bool ready_;
service_map services_;
shared_mutex services_lock_;
std::string client_id_;
common::delayed_call keepalive_calls_;
typedef vtrc::function<void (void)> stage_function_type;
stage_function_type stage_function_;
vtrc::atomic<unsigned> current_calls_;
const unsigned maximum_calls_;
impl( application &a, common::transport_iface *c,
unsigned maximum_calls)
:app_(a)
,connection_(c)
,ready_(false)
,current_calls_(0)
,maximum_calls_(maximum_calls)
,keepalive_calls_(a.get_io_service( ))
{
stage_function_ =
vtrc::bind( &this_type::on_client_selection, this );
/// client has only 10 seconds for init connection
/// todo: think about setting for this timeout value
keepalive_calls_.call_from_now(
vtrc::bind( &this_type::on_keepavive, this, _1 ),
boost::posix_time::seconds( 10 ));
}
common::rpc_service_wrapper_sptr get_service( const std::string &name )
{
upgradable_lock lk( services_lock_ );
common::rpc_service_wrapper_sptr result;
service_map::iterator f( services_.find( name ) );
if( f != services_.end( ) ) {
result = f->second;
} else {
result = app_.get_service_by_name( connection_, name );
if( result ) {
upgrade_to_unique ulk( lk );
services_.insert( std::make_pair( name, result ) );
}
}
return result;
}
bool pop_check_init_message( )
{
}
void pop_message( )
{
parent_->pop_message( );
}
void on_keepavive( const boost::system::error_code &error )
{
if( !error ) {
/// timeout for client init
vtrc_auth::init_capsule cap;
cap.mutable_error( )->set_code( vtrc_errors::ERR_TIMEOUT );
cap.set_ready( false );
send_and_close( cap );
}
}
bool check_message_hash( const std::string &mess )
{
return parent_->check_message( mess );
}
void send_proto_message( const gpb::Message &mess )
{
std::string s(mess.SerializeAsString( ));
connection_->write( s.c_str( ), s.size( ) );
}
void send_proto_message( const gpb::Message &mess,
common::closure_type closure, bool on_send)
{
std::string s(mess.SerializeAsString( ));
connection_->write( s.c_str( ), s.size( ), closure, on_send );
}
void send_and_close( const gpb::Message &mess )
{
send_proto_message( mess, vtrc::bind(
&this_type::close_client, this, _1,
connection_->shared_from_this( )),
true );
}
void set_client_ready( )
{
keepalive_calls_.cancel( );
stage_function_ =
vtrc::bind( &this_type::on_rcp_call_ready, this );
parent_->set_ready( true );
}
void close_client( const bsys::error_code & /*err*/,
common::connection_iface_sptr /*inst*/)
{
connection_->close( );
}
void on_client_transformer( )
{
using namespace common::transformers;
vtrc_auth::init_capsule capsule;
bool check = get_pop_message( capsule );
if( !check ) {
connection_->close( );
return;
}
if( !capsule.ready( ) ) {
connection_->close( );
return;
}
vtrc_auth::transformer_setup tsetup;
tsetup.ParseFromString( capsule.body( ) );
std::string key(app_.get_session_key( connection_, client_id_ ));
create_key( key, // input
tsetup.salt1( ), // input
tsetup.salt2( ), // input
key ); // output
common::transformer_iface *new_transformer =
erseefor::create( key.c_str( ), key.size( ) );
parent_->change_transformer( new_transformer );
capsule.Clear( );
capsule.set_ready( true );
capsule.set_text( "Kiva nahda sinut!" );
set_client_ready( );
send_proto_message( capsule );
}
void setup_transformer( unsigned id )
{
using namespace common::transformers;
vtrc_auth::transformer_setup ts;
vtrc_auth::init_capsule capsule;
if( id == vtrc_auth::TRANSFORM_NONE ) {
capsule.set_ready( true );
capsule.set_text( "Kiva nahda sinut!" );
set_client_ready( );
send_proto_message( capsule );
} else if( id == vtrc_auth::TRANSFORM_ERSEEFOR ) {
std::string key(app_.get_session_key(connection_, client_id_));
generate_key_infos( key, // input
*ts.mutable_salt1( ), // output
*ts.mutable_salt2( ), // output
key ); // output
common::transformer_iface *new_reverter =
erseefor::create( key.c_str( ), key.size( ) );
parent_->change_reverter( new_reverter );
capsule.set_ready( true );
capsule.set_body( ts.SerializeAsString( ) );
stage_function_ =
vtrc::bind( &this_type::on_client_transformer, this );
send_proto_message( capsule );
} else {
capsule.set_ready( false );
vtrc_errors::container *er(capsule.mutable_error( ));
er->set_code( vtrc_errors::ERR_INVALID_VALUE );
er->set_category(vtrc_errors::CATEGORY_INTERNAL);
er->set_additional( "Invalid transformer" );
send_and_close( capsule );
return;
}
}
void on_client_selection( )
{
vtrc_auth::init_capsule capsule;
bool check = get_pop_message( capsule );
if( !check ) {
connection_->close( );
return;
}
if( !capsule.ready( ) ) {
connection_->close( );
return;
}
vtrc_auth::client_selection cs;
cs.ParseFromString( capsule.body( ) );
common::hash_iface *new_checker(
common::hash::create_by_index( cs.hash( ) ) );
common::hash_iface *new_maker(
common::hash::create_by_index( cs.hash( ) ) );
if( !new_maker ) {
delete new_checker;
}
if( !new_maker || !new_checker ) {
connection_->close( );
return;
}
client_id_.assign( cs.id( ) );
parent_->change_hash_checker( new_checker );
parent_->change_hash_maker( new_maker );
setup_transformer( cs.transform( ) );
}
bool get_pop_message( gpb::Message &capsule )
{
std::string &mess(parent_->message_queue( ).front( ));
bool check = check_message_hash(mess);
if( !check ) {
std::cout << "message bad hash "
<< parent_->message_queue( ).size( )
<< "...";
connection_->close( );
return false;
}
parse_message( mess, capsule );
pop_message( );
return true;
}
void call_done( const boost::system::error_code & /*err*/ )
{
--current_calls_;
}
void push_call( lowlevel_unit_sptr llu,
common::connection_iface_sptr /*conn*/ )
{
parent_->make_call( llu,
vtrc::bind(&this_type::call_done, this, _1 ));
}
void send_busy( lowlevel_unit_type &llu )
{
if( llu.opt( ).wait( ) ) {
llu.clear_call( );
llu.clear_request( );
llu.clear_response( );
llu.mutable_error( )->set_code( vtrc_errors::ERR_BUSY );
parent_->call_rpc_method( llu );
}
}
void process_call( lowlevel_unit_sptr &llu )
{
if( ++current_calls_ <= maximum_calls_ ) {
app_.get_rpc_service( ).post(
vtrc::bind( &this_type::push_call, this,
llu, connection_->shared_from_this( )));
} else {
--current_calls_;
send_busy( *llu );
}
}
void push_event_answer( lowlevel_unit_sptr llu,
common::connection_iface_sptr /*conn*/ )
{
parent_->push_rpc_message( llu->id( ), llu );
}
void process_event_cb( lowlevel_unit_sptr &llu )
{
parent_->push_rpc_message( llu->id( ), llu );
}
void on_rcp_call_ready( )
{
typedef vtrc_rpc_lowlevel::message_info message_info;
while( !parent_->message_queue( ).empty( ) ) {
lowlevel_unit_sptr llu(vtrc::make_shared<lowlevel_unit_type>());
if(!get_pop_message( *llu )) {
std::cout << "bad hash message!\n";
return;
}
if( llu->has_info( ) ) {
switch (llu->info( ).message_type( )) {
case message_info::MESSAGE_CALL:
process_call( llu );
break;
case message_info::MESSAGE_EVENT:
case message_info::MESSAGE_CALLBACK:
case message_info::MESSAGE_INSERTION_CALL:
process_event_cb( llu );
break;
default:
break;
}
}
}
}
void parse_message( const std::string &block, gpb::Message &mess )
{
parent_->parse_message( block, mess );
}
std::string first_message( )
{
vtrc_auth::init_capsule cap;
vtrc_auth::init_protocol hello_mess;
cap.set_text( "Tervetuloa!" );
cap.set_ready( true );
hello_mess.add_hash_supported( vtrc_auth::HASH_NONE );
hello_mess.add_hash_supported( vtrc_auth::HASH_CRC_16 );
hello_mess.add_hash_supported( vtrc_auth::HASH_CRC_32 );
hello_mess.add_hash_supported( vtrc_auth::HASH_CRC_64 );
hello_mess.add_hash_supported( vtrc_auth::HASH_SHA2_256 );
hello_mess.add_transform_supported( vtrc_auth::TRANSFORM_NONE );
hello_mess.add_transform_supported( vtrc_auth::TRANSFORM_ERSEEFOR );
cap.set_body( hello_mess.SerializeAsString( ) );
return cap.SerializeAsString( );
}
void init( )
{
static const std::string data(first_message( ));
connection_->write(data.c_str( ), data.size( ));
}
void data_ready( )
{
stage_function_( );
}
};
protocol_layer_s::protocol_layer_s( application &a,
common::transport_iface *connection,
unsigned maximym_calls,
size_t mess_len)
:common::protocol_layer(connection, false, mess_len)
,impl_(new impl(a, connection, maximym_calls))
{
impl_->parent_ = this;
}
protocol_layer_s::~protocol_layer_s( )
{
delete impl_;
}
void protocol_layer_s::init( )
{
impl_->init( );
}
void protocol_layer_s::close( )
{
}
void protocol_layer_s::on_data_ready( )
{
impl_->data_ready( );
}
common::rpc_service_wrapper_sptr protocol_layer_s::get_service_by_name(
const std::string &name)
{
return impl_->get_service(name);
}
}}
<commit_msg>proto<commit_after>
#include <boost/asio.hpp>
#include "vtrc-common/vtrc-mutex-typedefs.h"
#include "vtrc-bind.h"
#include "vtrc-function.h"
#include "vtrc-protocol-layer-s.h"
#include "vtrc-monotonic-timer.h"
#include "vtrc-data-queue.h"
#include "vtrc-hash-iface.h"
#include "vtrc-transformer-iface.h"
#include "vtrc-transport-iface.h"
#include "vtrc-common/vtrc-rpc-service-wrapper.h"
#include "vtrc-common/vtrc-exception.h"
#include "vtrc-common/vtrc-rpc-controller.h"
#include "vtrc-common/vtrc-call-context.h"
#include "vtrc-application.h"
#include "protocol/vtrc-errors.pb.h"
#include "protocol/vtrc-auth.pb.h"
#include "protocol/vtrc-rpc-lowlevel.pb.h"
#include "vtrc-chrono.h"
#include "vtrc-atomic.h"
#include "vtrc-common/vtrc-random-device.h"
#include "vtrc-common/vtrc-delayed-call.h"
namespace vtrc { namespace server {
namespace gpb = google::protobuf;
namespace bsys = boost::system;
namespace basio = boost::asio;
namespace {
enum init_stage_enum {
stage_begin = 1
,stage_client_select = 2
,stage_client_ready = 3
};
typedef std::map <
std::string,
common::rpc_service_wrapper_sptr
> service_map;
typedef vtrc_rpc_lowlevel::lowlevel_unit lowlevel_unit_type;
typedef vtrc::shared_ptr<lowlevel_unit_type> lowlevel_unit_sptr;
}
namespace data_queue = common::data_queue;
struct protocol_layer_s::impl {
typedef impl this_type;
typedef protocol_layer_s parent_type;
application &app_;
common::transport_iface *connection_;
protocol_layer_s *parent_;
bool ready_;
service_map services_;
shared_mutex services_lock_;
std::string client_id_;
common::delayed_call keepalive_calls_;
typedef vtrc::function<void (void)> stage_function_type;
stage_function_type stage_function_;
vtrc::atomic<unsigned> current_calls_;
const unsigned maximum_calls_;
impl( application &a, common::transport_iface *c,
unsigned maximum_calls)
:app_(a)
,connection_(c)
,ready_(false)
,current_calls_(0)
,maximum_calls_(maximum_calls)
,keepalive_calls_(a.get_io_service( ))
{
stage_function_ =
vtrc::bind( &this_type::on_client_selection, this );
/// client has only 10 seconds for init connection
/// todo: think about setting for this timeout value
keepalive_calls_.call_from_now(
vtrc::bind( &this_type::on_keepavive, this, _1 ),
boost::posix_time::seconds( 10 ));
}
common::rpc_service_wrapper_sptr get_service( const std::string &name )
{
upgradable_lock lk( services_lock_ );
common::rpc_service_wrapper_sptr result;
service_map::iterator f( services_.find( name ) );
if( f != services_.end( ) ) {
result = f->second;
} else {
result = app_.get_service_by_name( connection_, name );
if( result ) {
upgrade_to_unique ulk( lk );
services_.insert( std::make_pair( name, result ) );
}
}
return result;
}
bool pop_check_init_message( )
{
}
void pop_message( )
{
parent_->pop_message( );
}
void on_keepavive( const boost::system::error_code &error )
{
if( !error ) {
/// timeout for client init
vtrc_auth::init_capsule cap;
cap.mutable_error( )->set_code( vtrc_errors::ERR_TIMEOUT );
cap.set_ready( false );
send_and_close( cap );
}
}
bool check_message_hash( const std::string &mess )
{
return parent_->check_message( mess );
}
void send_proto_message( const gpb::Message &mess )
{
std::string s(mess.SerializeAsString( ));
connection_->write( s.c_str( ), s.size( ) );
}
void send_proto_message( const gpb::Message &mess,
common::closure_type closure, bool on_send)
{
std::string s(mess.SerializeAsString( ));
connection_->write( s.c_str( ), s.size( ), closure, on_send );
}
void send_and_close( const gpb::Message &mess )
{
send_proto_message( mess, vtrc::bind(
&this_type::close_client, this, _1,
connection_->shared_from_this( )),
true );
}
void set_client_ready( )
{
keepalive_calls_.cancel( );
stage_function_ =
vtrc::bind( &this_type::on_rcp_call_ready, this );
parent_->set_ready( true );
}
void close_client( const bsys::error_code & /*err*/,
common::connection_iface_sptr /*inst*/)
{
connection_->close( );
}
void on_client_transformer( )
{
using namespace common::transformers;
vtrc_auth::init_capsule capsule;
bool check = get_pop_message( capsule );
if( !check ) {
connection_->close( );
return;
}
if( !capsule.ready( ) ) {
connection_->close( );
return;
}
vtrc_auth::transformer_setup tsetup;
tsetup.ParseFromString( capsule.body( ) );
std::string key(app_.get_session_key( connection_, client_id_ ));
create_key( key, // input
tsetup.salt1( ), // input
tsetup.salt2( ), // input
key ); // output
common::transformer_iface *new_transformer =
erseefor::create( key.c_str( ), key.size( ) );
parent_->change_transformer( new_transformer );
capsule.Clear( );
capsule.set_ready( true );
capsule.set_text( "Kiva nahda sinut!" );
set_client_ready( );
send_proto_message( capsule );
}
void setup_transformer( unsigned id )
{
using namespace common::transformers;
vtrc_auth::transformer_setup ts;
vtrc_auth::init_capsule capsule;
if( id == vtrc_auth::TRANSFORM_NONE ) {
capsule.set_ready( true );
capsule.set_text( "Kiva nahda sinut!" );
set_client_ready( );
send_proto_message( capsule );
} else if( id == vtrc_auth::TRANSFORM_ERSEEFOR ) {
std::string key(app_.get_session_key(connection_, client_id_));
generate_key_infos( key, // input
*ts.mutable_salt1( ), // output
*ts.mutable_salt2( ), // output
key ); // output
common::transformer_iface *new_reverter =
erseefor::create( key.c_str( ), key.size( ) );
parent_->change_reverter( new_reverter );
capsule.set_ready( true );
capsule.set_body( ts.SerializeAsString( ) );
stage_function_ =
vtrc::bind( &this_type::on_client_transformer, this );
send_proto_message( capsule );
} else {
capsule.set_ready( false );
vtrc_errors::container *er(capsule.mutable_error( ));
er->set_code( vtrc_errors::ERR_INVALID_VALUE );
er->set_category(vtrc_errors::CATEGORY_INTERNAL);
er->set_additional( "Invalid transformer" );
send_and_close( capsule );
return;
}
}
void on_client_selection( )
{
vtrc_auth::init_capsule capsule;
bool check = get_pop_message( capsule );
if( !check ) {
connection_->close( );
return;
}
if( !capsule.ready( ) ) {
connection_->close( );
return;
}
vtrc_auth::client_selection cs;
cs.ParseFromString( capsule.body( ) );
common::hash_iface *new_checker(
common::hash::create_by_index( cs.hash( ) ) );
common::hash_iface *new_maker(
common::hash::create_by_index( cs.hash( ) ) );
if( !new_maker ) {
delete new_checker;
}
if( !new_maker || !new_checker ) {
connection_->close( );
return;
}
client_id_.assign( cs.id( ) );
parent_->change_hash_checker( new_checker );
parent_->change_hash_maker( new_maker );
setup_transformer( cs.transform( ) );
}
bool get_pop_message( gpb::Message &capsule )
{
std::string &mess(parent_->message_queue( ).front( ));
bool check = check_message_hash(mess);
if( !check ) {
std::cout << "message bad hash "
<< parent_->message_queue( ).size( )
<< "...";
connection_->close( );
return false;
}
parse_message( mess, capsule );
pop_message( );
return true;
}
void call_done( const boost::system::error_code & /*err*/ )
{
--current_calls_;
}
void push_call( lowlevel_unit_sptr llu,
common::connection_iface_sptr /*conn*/ )
{
parent_->make_call( llu,
vtrc::bind(&this_type::call_done, this, _1 ));
}
void send_busy( lowlevel_unit_type &llu )
{
if( llu.opt( ).wait( ) ) {
llu.clear_call( );
llu.clear_request( );
llu.clear_response( );
llu.mutable_error( )->set_code( vtrc_errors::ERR_BUSY );
parent_->call_rpc_method( llu );
}
}
void process_call( lowlevel_unit_sptr &llu )
{
if( ++current_calls_ <= maximum_calls_ ) {
app_.get_rpc_service( ).post(
vtrc::bind( &this_type::push_call, this,
llu, connection_->shared_from_this( )));
} else {
--current_calls_;
send_busy( *llu );
}
}
void push_event_answer( lowlevel_unit_sptr llu,
common::connection_iface_sptr /*conn*/ )
{
parent_->push_rpc_message( llu->id( ), llu );
}
void process_event_cb( lowlevel_unit_sptr &llu )
{
parent_->push_rpc_message( llu->id( ), llu );
}
void on_rcp_call_ready( )
{
typedef vtrc_rpc_lowlevel::message_info message_info;
while( !parent_->message_queue( ).empty( ) ) {
lowlevel_unit_sptr llu(vtrc::make_shared<lowlevel_unit_type>());
if(!get_pop_message( *llu )) {
std::cout << "bad hash message!\n";
return;
}
if( llu->has_info( ) ) {
switch (llu->info( ).message_type( )) {
case message_info::MESSAGE_CALL:
process_call( llu );
break;
case message_info::MESSAGE_EVENT:
case message_info::MESSAGE_CALLBACK:
case message_info::MESSAGE_INSERTION_CALL:
process_event_cb( llu );
break;
default:
break;
}
}
}
}
void parse_message( const std::string &block, gpb::Message &mess )
{
parent_->parse_message( block, mess );
}
std::string first_message( )
{
vtrc_auth::init_capsule cap;
vtrc_auth::init_protocol hello_mess;
cap.set_text( "Tervetuloa!" );
cap.set_ready( true );
hello_mess.add_hash_supported( vtrc_auth::HASH_NONE );
hello_mess.add_hash_supported( vtrc_auth::HASH_CRC_16 );
hello_mess.add_hash_supported( vtrc_auth::HASH_CRC_32 );
hello_mess.add_hash_supported( vtrc_auth::HASH_CRC_64 );
hello_mess.add_hash_supported( vtrc_auth::HASH_SHA2_256 );
hello_mess.add_transform_supported( vtrc_auth::TRANSFORM_NONE );
hello_mess.add_transform_supported( vtrc_auth::TRANSFORM_ERSEEFOR );
cap.set_body( hello_mess.SerializeAsString( ) );
return cap.SerializeAsString( );
}
void init( )
{
static const std::string data(first_message( ));
connection_->write(data.c_str( ), data.size( ));
}
void data_ready( )
{
stage_function_( );
}
};
protocol_layer_s::protocol_layer_s( application &a,
common::transport_iface *connection,
unsigned maximym_calls,
size_t mess_len)
:common::protocol_layer(connection, false, mess_len)
,impl_(new impl(a, connection, maximym_calls))
{
impl_->parent_ = this;
}
protocol_layer_s::~protocol_layer_s( )
{
delete impl_;
}
void protocol_layer_s::init( )
{
impl_->init( );
}
void protocol_layer_s::close( )
{
}
void protocol_layer_s::on_data_ready( )
{
impl_->data_ready( );
}
common::rpc_service_wrapper_sptr protocol_layer_s::get_service_by_name(
const std::string &name)
{
return impl_->get_service(name);
}
}}
<|endoftext|>
|
<commit_before>#include "media_config_loader.h"
#include "log.h"
using ::com::kurento::log::Log;
static Log l("media_config_loader");
#define d(...) aux_debug(l, __VA_ARGS__);
#define i(...) aux_info(l, __VA_ARGS__);
#define e(...) aux_error(l, __VA_ARGS__);
#define w(...) aux_warn(l, __VA_ARGS__);
#define DEFAULT_ID "12345"
#define MEDIAS_KEY "medias"
#define MEDIA_GROUP "Media"
#define CODECS_KEY "codecs"
#define TRANSPORT_KEY "transport"
#define TRANSPORT_GROUP "Transport"
#define CODEC_GROUP "Codec"
#define ID_KEY "id"
#define NAME_KEY "name"
#define CLOCKRATE_KEY "clockRate"
#define CHANNELS "channels"
#define WIDTH "width"
#define HEIGHT "height"
#define BITRATE "bitrate"
#define EXTRA_PARAMS "extra"
using ::com::kurento::commons::mediaspec::MediaSpec;
using ::com::kurento::commons::mediaspec::Transport;
using ::com::kurento::commons::mediaspec::Payload;
static void
load_codec(Glib::KeyFile &configFile, const std::string &codecgrp, Payload &pay) {
// TODO: Implement this function
d("Loading config for: " + codecgrp);
throw Glib::KeyFileError(Glib::KeyFileError::NOT_FOUND, "Not implemented");
}
static void
load_transport(Glib::KeyFile &configFile, const std::string &transportgrp,
Transport &tr) {
// TODO: Implement this function
d("Loading config for: " + transportgrp);
throw Glib::KeyFileError(Glib::KeyFileError::NOT_FOUND, "Not implemented");
}
static void
load_media(Glib::KeyFile &configFile, const std::string &mediagrp,
MediaSpec &media)
{
d("Loading config for media: " + mediagrp);
if (!configFile.has_group(mediagrp)) {
e("No codecs set, you won't be able to communicate with others");
return;
}
Glib::ArrayHandle<Glib::ustring> codecs =
configFile.get_string_list(mediagrp, CODECS_KEY);
Glib::ArrayHandle<Glib::ustring>::const_iterator it = codecs.begin();
for (; it != codecs.end(); it ++) {
Payload pay;
try {
load_codec(configFile, CODEC_GROUP " " + *it, pay);
media.payloads.push_back(pay);
} catch (Glib::KeyFileError err) {
w(err.what());
w("error loading codec configuration: " + *it);
}
}
std::string transport = configFile.get_string(mediagrp, TRANSPORT_KEY);
load_transport(configFile, TRANSPORT_GROUP " " + transport,
media.transport);
}
void
load_spec(Glib::KeyFile &configFile, SessionSpec &spec) {
Glib::ArrayHandle<Glib::ustring> medias =
configFile.get_string_list(SERVER_GROUP, MEDIAS_KEY);
Glib::ArrayHandle<Glib::ustring>::const_iterator it = medias.begin();
for (; it != medias.end(); it ++) {
MediaSpec media;
try {
load_media(configFile, MEDIA_GROUP " " + *it, media);
spec.medias.push_back(media);
} catch (Glib::KeyFileError err) {
w(err.what());
w("Error loading media configuration: " + *it);
}
}
spec.__set_id(DEFAULT_ID);
}
<commit_msg>Add configuration loader for transport<commit_after>#include "media_config_loader.h"
#include "log.h"
using ::com::kurento::log::Log;
static Log l("media_config_loader");
#define d(...) aux_debug(l, __VA_ARGS__);
#define i(...) aux_info(l, __VA_ARGS__);
#define e(...) aux_error(l, __VA_ARGS__);
#define w(...) aux_warn(l, __VA_ARGS__);
#define DEFAULT_ID "12345"
#define MEDIAS_KEY "medias"
#define MEDIA_GROUP "Media"
#define CODECS_KEY "codecs"
#define TRANSPORT_KEY "transport"
#define TRANSPORT_GROUP "Transport"
#define ADDRESS_KEY "address"
#define CODEC_GROUP "Codec"
#define ID_KEY "id"
#define NAME_KEY "name"
#define CLOCKRATE_KEY "clockRate"
#define CHANNELS "channels"
#define WIDTH "width"
#define HEIGHT "height"
#define BITRATE "bitrate"
#define EXTRA_PARAMS "extra"
using ::com::kurento::commons::mediaspec::MediaSpec;
using ::com::kurento::commons::mediaspec::Transport;
using ::com::kurento::commons::mediaspec::Payload;
static void
load_codec(Glib::KeyFile &configFile, const std::string &codecgrp, Payload &pay) {
// TODO: Implement this function
d("Loading config for: " + codecgrp);
throw Glib::KeyFileError(Glib::KeyFileError::NOT_FOUND, "Not implemented");
}
static void
load_transport(Glib::KeyFile &configFile, const std::string &transportgrp,
Transport &tr) {
d("Loading config for: " + transportgrp);
tr.rtp.__set_address(configFile.get_string(transportgrp, ADDRESS_KEY));
tr.__isset.rtp = true;
}
static void
load_media(Glib::KeyFile &configFile, const std::string &mediagrp,
MediaSpec &media)
{
d("Loading config for media: " + mediagrp);
if (!configFile.has_group(mediagrp)) {
e("No codecs set, you won't be able to communicate with others");
return;
}
Glib::ArrayHandle<Glib::ustring> codecs =
configFile.get_string_list(mediagrp, CODECS_KEY);
Glib::ArrayHandle<Glib::ustring>::const_iterator it = codecs.begin();
for (; it != codecs.end(); it ++) {
Payload pay;
try {
load_codec(configFile, CODEC_GROUP " " + *it, pay);
media.payloads.push_back(pay);
} catch (Glib::KeyFileError err) {
w(err.what());
w("error loading codec configuration: " + *it);
}
}
std::string transport = configFile.get_string(mediagrp, TRANSPORT_KEY);
load_transport(configFile, TRANSPORT_GROUP " " + transport,
media.transport);
}
void
load_spec(Glib::KeyFile &configFile, SessionSpec &spec) {
Glib::ArrayHandle<Glib::ustring> medias =
configFile.get_string_list(SERVER_GROUP, MEDIAS_KEY);
Glib::ArrayHandle<Glib::ustring>::const_iterator it = medias.begin();
for (; it != medias.end(); it ++) {
MediaSpec media;
try {
load_media(configFile, MEDIA_GROUP " " + *it, media);
spec.medias.push_back(media);
} catch (Glib::KeyFileError err) {
w(err.what());
w("Error loading media configuration: " + *it);
}
}
spec.__set_id(DEFAULT_ID);
}
<|endoftext|>
|
<commit_before>// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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 "internal/file.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <algorithm>
#include <cassert>
#include <cerrno>
#include <cstdlib>
#include <ios>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <string_view>
#include <system_error>
#include <utility>
#include "absl/strings/string_view.h"
#include "internal/random.h"
namespace phst_rules_elisp {
file::file() { this->setp(put_.data(), put_.data() + put_.size()); }
file::file(std::string path, const file_mode mode) : file() {
this->open(std::move(path), mode);
}
file::~file() noexcept {
if (fd_ >= 0) std::clog << "file " << path_ << " still open" << std::endl;
}
void file::open(std::string path, const file_mode mode) {
int fd = -1;
while (true) {
fd = ::open(path.c_str(), static_cast<int>(mode) | O_CLOEXEC,
S_IRUSR | S_IWUSR);
if (fd >= 0 || errno != EINTR) break;
}
if (fd < 0) {
throw std::system_error(errno, std::system_category(),
"open(" + path + ')');
}
fd_ = fd;
path_ = std::move(path);
}
std::FILE* file::open_c_file(const char* const mode) {
const auto file = fdopen(fd_, mode);
if (file == nullptr) {
throw std::system_error(errno, std::system_category(), "fdopen");
}
return file;
}
void file::close() {
if (fd_ < 0) return;
if (!this->flush()) {
throw std::ios::failure("error closing file " + path_);
}
int status = -1;
while (true) {
status = ::close(fd_);
if (status == 0 || errno != EINTR) break;
}
if (status != 0) {
throw std::system_error(errno, std::system_category(), "close");
}
fd_ = -1;
this->do_close();
path_.clear();
}
void file::do_close() {}
file::int_type file::overflow(const int_type ch) {
assert(this->pptr() == this->epptr());
if (!this->flush()) return traits_type::eof();
if (traits_type::eq_int_type(ch, traits_type::eof())) {
return traits_type::not_eof(0);
}
assert(this->pptr() == put_.data());
assert(this->epptr() > put_.data());
traits_type::assign(put_.front(), traits_type::to_char_type(ch));
this->pbump(1);
return ch;
}
std::streamsize file::xsputn(const char_type* const data,
const std::streamsize count) {
if (!this->flush()) return 0;
return this->write(data, count);
}
std::size_t file::write(const char* data, std::size_t count) {
std::size_t written = 0;
while (count > 0) {
const auto n = ::write(fd_, data, count);
if (n < 0) throw std::system_error(errno, std::system_category(), "write");
if (n == 0) break;
written += n;
data += n;
count -= n;
}
return written;
}
file::int_type file::underflow() {
assert(this->gptr() == this->egptr());
const auto read = this->read(get_.data(), get_.size());
this->setg(get_.data(), get_.data(), get_.data() + read);
if (read == 0) return traits_type::eof();
assert(this->gptr() != nullptr);
assert(this->gptr() != this->egptr());
return traits_type::to_int_type(*this->gptr());
}
std::streamsize file::xsgetn(char_type* data, std::streamsize count) {
if (count == 0) return 0;
std::streamsize read = 0;
if (this->gptr() != nullptr && this->egptr() != this->gptr()) {
read = std::min(count, this->egptr() - this->gptr());
traits_type::copy(data, this->gptr(), read);
data += read;
count -= read;
this->setg(this->gptr(), this->gptr() + read, this->egptr());
}
return read + this->read(data, count);
}
std::size_t file::read(char* data, std::size_t count) {
std::size_t read = 0;
while (count > 0) {
const auto n = ::read(fd_, data, count);
if (n < 0) throw std::system_error(errno, std::system_category(), "read");
if (n == 0) break;
read += n;
data += n;
count -= n;
}
return read;
}
int file::sync() {
if (!this->flush()) return -1;
if (::fsync(fd_) < 0) {
throw std::system_error(errno, std::system_category(), "fsync");
}
return 0;
}
[[nodiscard]] bool file::flush() {
assert(this->pbase() != nullptr);
assert(this->pptr() != nullptr);
const auto signed_count = this->pptr() - this->pbase();
assert(signed_count >= 0);
const auto count = static_cast<std::size_t>(signed_count);
const auto written = this->write(this->pbase(), count);
assert(written <= count);
if (written < count) return false;
this->setp(put_.data(), put_.data() + put_.size());
return true;
}
temp_file::temp_file(const std::string& directory, const absl::string_view tmpl,
random& random) {
for (int i = 0; i < 10; i++) {
auto name = join_path(directory, random.temp_name(tmpl));
if (!file_exists(name)) {
this->open(std::move(name),
file_mode::readwrite | file_mode::create | file_mode::excl);
return;
}
}
throw std::runtime_error("can’t create temporary file in directory " +
directory + " with template " + std::string(tmpl));
}
temp_file::~temp_file() noexcept {
const auto& path = this->path();
const auto code = this->remove();
// Only print an error if removing the file failed (“false” return value), but
// the file wasn’t already removed before (zero error code).
if (code && code != std::errc::no_such_file_or_directory) {
std::clog << "error removing temporary file " << path << ": " << code
<< ": " << code.message() << std::endl;
}
}
void temp_file::do_close() {
const auto code = this->remove();
if (code) throw std::system_error(code);
}
[[nodiscard]] std::error_code temp_file::remove() noexcept {
return remove_file(this->path());
}
static constexpr absl::string_view remove_prefix(const absl::string_view string,
const char prefix) noexcept {
return (string.empty() || string.front() != prefix) ? string
: string.substr(1);
}
static constexpr absl::string_view remove_suffix(const absl::string_view string,
const char suffix) noexcept {
return (string.empty() || string.back() != suffix)
? string
: string.substr(0, string.size() - 1);
}
std::string join_path(const absl::string_view a, const absl::string_view b) {
return std::string(remove_slash(a)) + '/' +
std::string(remove_prefix(b, '/'));
}
std::string make_absolute(const absl::string_view name) {
if (is_absolute(name)) return std::string(name);
struct free {
void operator()(void* const ptr) const noexcept { std::free(ptr); }
};
const std::unique_ptr<char, free> dir(get_current_dir_name());
if (dir == nullptr) {
throw std::system_error(errno, std::system_category(),
"get_current_dir_name");
}
return join_path(dir.get(), name);
}
[[nodiscard]] bool file_exists(const std::string& name) noexcept {
struct stat info;
return ::lstat(name.c_str(), &info) == 0;
}
[[nodiscard]] std::error_code remove_file(const std::string& name) noexcept {
return std::error_code(::unlink(name.c_str()) == 0 ? 0 : errno,
std::system_category());
}
[[nodiscard]] std::string temp_dir() {
const std::array<const char*, 2> vars = {"TEST_TMPDIR", "TMPDIR"};
for (const auto var : vars) {
const auto value = std::getenv(var);
if (value != nullptr && *value != '\0') return value;
}
return "/tmp";
}
directory::directory(const std::string& name) : dir_(::opendir(name.c_str())) {
if (dir_ == nullptr) {
throw std::system_error(errno, std::system_category(),
"opendir(" + name + ')');
}
}
directory::~directory() noexcept {
const auto code = this->close();
if (code) std::clog << code << ": " << code.message() << std::endl;
}
[[nodiscard]] std::error_code directory::close() noexcept {
if (dir_ == nullptr) return std::error_code();
const std::error_code code(::closedir(dir_) == 0 ? 0 : errno,
std::system_category());
dir_ = nullptr;
return code;
}
void directory::iterator::advance() {
errno = 0;
const auto entry = ::readdir(dir_);
if (entry == nullptr) {
dir_ = nullptr;
if (errno != 0) {
throw std::system_error(errno, std::system_category(), "readdir");
}
entry_.clear();
} else {
entry_ = entry->d_name;
}
}
} // phst_rules_elisp
<commit_msg>Always call fsync, even if flushing the buffer failed.<commit_after>// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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 "internal/file.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <algorithm>
#include <cassert>
#include <cerrno>
#include <cstdlib>
#include <ios>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <string_view>
#include <system_error>
#include <utility>
#include "absl/strings/string_view.h"
#include "internal/random.h"
namespace phst_rules_elisp {
file::file() { this->setp(put_.data(), put_.data() + put_.size()); }
file::file(std::string path, const file_mode mode) : file() {
this->open(std::move(path), mode);
}
file::~file() noexcept {
if (fd_ >= 0) std::clog << "file " << path_ << " still open" << std::endl;
}
void file::open(std::string path, const file_mode mode) {
int fd = -1;
while (true) {
fd = ::open(path.c_str(), static_cast<int>(mode) | O_CLOEXEC,
S_IRUSR | S_IWUSR);
if (fd >= 0 || errno != EINTR) break;
}
if (fd < 0) {
throw std::system_error(errno, std::system_category(),
"open(" + path + ')');
}
fd_ = fd;
path_ = std::move(path);
}
std::FILE* file::open_c_file(const char* const mode) {
const auto file = fdopen(fd_, mode);
if (file == nullptr) {
throw std::system_error(errno, std::system_category(), "fdopen");
}
return file;
}
void file::close() {
if (fd_ < 0) return;
if (!this->flush()) {
throw std::ios::failure("error closing file " + path_);
}
int status = -1;
while (true) {
status = ::close(fd_);
if (status == 0 || errno != EINTR) break;
}
if (status != 0) {
throw std::system_error(errno, std::system_category(), "close");
}
fd_ = -1;
this->do_close();
path_.clear();
}
void file::do_close() {}
file::int_type file::overflow(const int_type ch) {
assert(this->pptr() == this->epptr());
if (!this->flush()) return traits_type::eof();
if (traits_type::eq_int_type(ch, traits_type::eof())) {
return traits_type::not_eof(0);
}
assert(this->pptr() == put_.data());
assert(this->epptr() > put_.data());
traits_type::assign(put_.front(), traits_type::to_char_type(ch));
this->pbump(1);
return ch;
}
std::streamsize file::xsputn(const char_type* const data,
const std::streamsize count) {
if (!this->flush()) return 0;
return this->write(data, count);
}
std::size_t file::write(const char* data, std::size_t count) {
std::size_t written = 0;
while (count > 0) {
const auto n = ::write(fd_, data, count);
if (n < 0) throw std::system_error(errno, std::system_category(), "write");
if (n == 0) break;
written += n;
data += n;
count -= n;
}
return written;
}
file::int_type file::underflow() {
assert(this->gptr() == this->egptr());
const auto read = this->read(get_.data(), get_.size());
this->setg(get_.data(), get_.data(), get_.data() + read);
if (read == 0) return traits_type::eof();
assert(this->gptr() != nullptr);
assert(this->gptr() != this->egptr());
return traits_type::to_int_type(*this->gptr());
}
std::streamsize file::xsgetn(char_type* data, std::streamsize count) {
if (count == 0) return 0;
std::streamsize read = 0;
if (this->gptr() != nullptr && this->egptr() != this->gptr()) {
read = std::min(count, this->egptr() - this->gptr());
traits_type::copy(data, this->gptr(), read);
data += read;
count -= read;
this->setg(this->gptr(), this->gptr() + read, this->egptr());
}
return read + this->read(data, count);
}
std::size_t file::read(char* data, std::size_t count) {
std::size_t read = 0;
while (count > 0) {
const auto n = ::read(fd_, data, count);
if (n < 0) throw std::system_error(errno, std::system_category(), "read");
if (n == 0) break;
read += n;
data += n;
count -= n;
}
return read;
}
int file::sync() {
const auto success = this->flush();
if (::fsync(fd_) < 0) {
throw std::system_error(errno, std::system_category(), "fsync");
}
return success ? 0 : -1;
}
[[nodiscard]] bool file::flush() {
assert(this->pbase() != nullptr);
assert(this->pptr() != nullptr);
const auto signed_count = this->pptr() - this->pbase();
assert(signed_count >= 0);
const auto count = static_cast<std::size_t>(signed_count);
const auto written = this->write(this->pbase(), count);
assert(written <= count);
if (written < count) return false;
this->setp(put_.data(), put_.data() + put_.size());
return true;
}
temp_file::temp_file(const std::string& directory, const absl::string_view tmpl,
random& random) {
for (int i = 0; i < 10; i++) {
auto name = join_path(directory, random.temp_name(tmpl));
if (!file_exists(name)) {
this->open(std::move(name),
file_mode::readwrite | file_mode::create | file_mode::excl);
return;
}
}
throw std::runtime_error("can’t create temporary file in directory " +
directory + " with template " + std::string(tmpl));
}
temp_file::~temp_file() noexcept {
const auto& path = this->path();
const auto code = this->remove();
// Only print an error if removing the file failed (“false” return value), but
// the file wasn’t already removed before (zero error code).
if (code && code != std::errc::no_such_file_or_directory) {
std::clog << "error removing temporary file " << path << ": " << code
<< ": " << code.message() << std::endl;
}
}
void temp_file::do_close() {
const auto code = this->remove();
if (code) throw std::system_error(code);
}
[[nodiscard]] std::error_code temp_file::remove() noexcept {
return remove_file(this->path());
}
static constexpr absl::string_view remove_prefix(const absl::string_view string,
const char prefix) noexcept {
return (string.empty() || string.front() != prefix) ? string
: string.substr(1);
}
static constexpr absl::string_view remove_suffix(const absl::string_view string,
const char suffix) noexcept {
return (string.empty() || string.back() != suffix)
? string
: string.substr(0, string.size() - 1);
}
std::string join_path(const absl::string_view a, const absl::string_view b) {
return std::string(remove_slash(a)) + '/' +
std::string(remove_prefix(b, '/'));
}
std::string make_absolute(const absl::string_view name) {
if (is_absolute(name)) return std::string(name);
struct free {
void operator()(void* const ptr) const noexcept { std::free(ptr); }
};
const std::unique_ptr<char, free> dir(get_current_dir_name());
if (dir == nullptr) {
throw std::system_error(errno, std::system_category(),
"get_current_dir_name");
}
return join_path(dir.get(), name);
}
[[nodiscard]] bool file_exists(const std::string& name) noexcept {
struct stat info;
return ::lstat(name.c_str(), &info) == 0;
}
[[nodiscard]] std::error_code remove_file(const std::string& name) noexcept {
return std::error_code(::unlink(name.c_str()) == 0 ? 0 : errno,
std::system_category());
}
[[nodiscard]] std::string temp_dir() {
const std::array<const char*, 2> vars = {"TEST_TMPDIR", "TMPDIR"};
for (const auto var : vars) {
const auto value = std::getenv(var);
if (value != nullptr && *value != '\0') return value;
}
return "/tmp";
}
directory::directory(const std::string& name) : dir_(::opendir(name.c_str())) {
if (dir_ == nullptr) {
throw std::system_error(errno, std::system_category(),
"opendir(" + name + ')');
}
}
directory::~directory() noexcept {
const auto code = this->close();
if (code) std::clog << code << ": " << code.message() << std::endl;
}
[[nodiscard]] std::error_code directory::close() noexcept {
if (dir_ == nullptr) return std::error_code();
const std::error_code code(::closedir(dir_) == 0 ? 0 : errno,
std::system_category());
dir_ = nullptr;
return code;
}
void directory::iterator::advance() {
errno = 0;
const auto entry = ::readdir(dir_);
if (entry == nullptr) {
dir_ = nullptr;
if (errno != 0) {
throw std::system_error(errno, std::system_category(), "readdir");
}
entry_.clear();
} else {
entry_ = entry->d_name;
}
}
} // phst_rules_elisp
<|endoftext|>
|
<commit_before>#include "propertyeditordelegate.h"
#include "propertyeditorproxymodel.h"
#include <QtCore/QDebug>
#include <QtGui/QComboBox>
#include <QtGui/QPushButton>
#include <QtGui/QPushButton>
#include "mainwindow.h"
#include "openShapeEditorButton.h"
#include "referencetypewindow.h"
#include "buttonRefWindow.h"
using namespace qReal;
PropertyEditorDelegate::PropertyEditorDelegate(QObject *parent)
: QItemDelegate(parent)
, mMainWindow(NULL)
, mLogicalModelAssistApi(NULL)
{
}
QWidget *PropertyEditorDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &/*option*/,
const QModelIndex &index) const
{
PropertyEditorModel *model = const_cast<PropertyEditorModel*>(dynamic_cast<const PropertyEditorModel*>(index.model()));
QString propertyName = model->data(index.sibling(index.row(), 0), Qt::DisplayRole).toString();
if (propertyName == "shape") {
QString propertyValue = model->data(index.sibling(index.row(), index.column()), Qt::DisplayRole).toString();
QPersistentModelIndex const actualIndex = model->modelIndex(index.row());
int role = model->roleByIndex(index.row());
OpenShapeEditorButton *button = new OpenShapeEditorButton(parent, actualIndex, role, propertyValue);
button->setText("Open Shape Editor");
QObject::connect(button, SIGNAL(clicked()), mMainWindow, SLOT(openShapeEditor()));
return button;
}
QStringList const values = model->enumValues(index);
if (!values.isEmpty()) {
QComboBox * const editor = new QComboBox(parent);
foreach (QString item, values)
editor->addItem(item);
return editor;
}
QString typeName = model->typeName(index);
if (typeName != "int" && typeName != "string" && typeName != "") {
int const role = model->roleByIndex(index.row());
QModelIndex const &actualIndex = model->modelIndex(index.row());
ButtonRefWindow * const button = new ButtonRefWindow(parent, typeName
, *mLogicalModelAssistApi, role, actualIndex, mMainWindow);
return button;
}
QLineEdit *editor = new QLineEdit(parent);
return editor;
}
void PropertyEditorDelegate::setEditorData(QWidget *editor,
const QModelIndex &index) const
{
QString value = index.model()->data(index, Qt::DisplayRole).toString();
QLineEdit *lineEdit = dynamic_cast<QLineEdit*>(editor);
if (lineEdit)
lineEdit->setText(value);
else {
QComboBox *comboEdit = dynamic_cast<QComboBox*>(editor);
if (comboEdit)
comboEdit->setCurrentIndex(comboEdit->findText(value));
}
}
void PropertyEditorDelegate::setModelData(QWidget *editor
, QAbstractItemModel *model
, const QModelIndex &index) const
{
QLineEdit *lineEdit = dynamic_cast<QLineEdit*>(editor);
QComboBox *comboEdit = dynamic_cast<QComboBox*>(editor);
QString value;
if (lineEdit)
value = lineEdit->text();
else if (comboEdit)
value = comboEdit->currentText();
else
return;
model->setData(index, value, Qt::EditRole);
mMainWindow->propertyEditorScrollTo(index);
}
void PropertyEditorDelegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option, const QModelIndex &/*index*/) const
{
editor->setGeometry(option.rect);
}
void PropertyEditorDelegate::init(MainWindow *mainWindow
, qReal::models::LogicalModelAssistApi * const logicalModelAssistApi)
{
mMainWindow = mainWindow;
mLogicalModelAssistApi = logicalModelAssistApi;
}
<commit_msg>Fixed #389, once again<commit_after>#include "propertyeditordelegate.h"
#include "propertyeditorproxymodel.h"
#include <QtCore/QDebug>
#include <QtGui/QComboBox>
#include <QtGui/QPushButton>
#include <QtGui/QPushButton>
#include "mainwindow.h"
#include "openShapeEditorButton.h"
#include "referencetypewindow.h"
#include "buttonRefWindow.h"
using namespace qReal;
PropertyEditorDelegate::PropertyEditorDelegate(QObject *parent)
: QItemDelegate(parent)
, mMainWindow(NULL)
, mLogicalModelAssistApi(NULL)
{
}
QWidget *PropertyEditorDelegate::createEditor(QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
Q_UNUSED(option);
PropertyEditorModel *model = const_cast<PropertyEditorModel*>(dynamic_cast<const PropertyEditorModel*>(index.model()));
QString propertyName = model->data(index.sibling(index.row(), 0), Qt::DisplayRole).toString();
if (propertyName == "shape") {
QString propertyValue = model->data(index.sibling(index.row(), index.column()), Qt::DisplayRole).toString();
QPersistentModelIndex const actualIndex = model->modelIndex(index.row());
int role = model->roleByIndex(index.row());
OpenShapeEditorButton *button = new OpenShapeEditorButton(parent, actualIndex, role, propertyValue);
button->setText("Open Shape Editor");
QObject::connect(button, SIGNAL(clicked()), mMainWindow, SLOT(openShapeEditor()));
return button;
}
QStringList const values = model->enumValues(index);
if (!values.isEmpty()) {
QComboBox * const editor = new QComboBox(parent);
foreach (QString item, values)
editor->addItem(item);
return editor;
}
QString typeName = model->typeName(index).toLower();
if (typeName != "int" && typeName != "string" && !typeName.isEmpty()) {
int const role = model->roleByIndex(index.row());
QModelIndex const &actualIndex = model->modelIndex(index.row());
ButtonRefWindow * const button = new ButtonRefWindow(parent, typeName
, *mLogicalModelAssistApi, role, actualIndex, mMainWindow);
return button;
}
QLineEdit * const editor = new QLineEdit(parent);
return editor;
}
void PropertyEditorDelegate::setEditorData(QWidget *editor,
const QModelIndex &index) const
{
QString value = index.model()->data(index, Qt::DisplayRole).toString();
QLineEdit *lineEdit = dynamic_cast<QLineEdit*>(editor);
if (lineEdit)
lineEdit->setText(value);
else {
QComboBox *comboEdit = dynamic_cast<QComboBox*>(editor);
if (comboEdit)
comboEdit->setCurrentIndex(comboEdit->findText(value));
}
}
void PropertyEditorDelegate::setModelData(QWidget *editor
, QAbstractItemModel *model
, const QModelIndex &index) const
{
QLineEdit *lineEdit = dynamic_cast<QLineEdit*>(editor);
QComboBox *comboEdit = dynamic_cast<QComboBox*>(editor);
QString value;
if (lineEdit)
value = lineEdit->text();
else if (comboEdit)
value = comboEdit->currentText();
else
return;
model->setData(index, value, Qt::EditRole);
mMainWindow->propertyEditorScrollTo(index);
}
void PropertyEditorDelegate::updateEditorGeometry(QWidget *editor,
const QStyleOptionViewItem &option, const QModelIndex &/*index*/) const
{
editor->setGeometry(option.rect);
}
void PropertyEditorDelegate::init(MainWindow *mainWindow
, qReal::models::LogicalModelAssistApi * const logicalModelAssistApi)
{
mMainWindow = mainWindow;
mLogicalModelAssistApi = logicalModelAssistApi;
}
<|endoftext|>
|
<commit_before>#include <tamer/fdhmsg.hh>
#include <signal.h>
void terminate(int);
int query_count = 0;
int main (void) {
char buf[8192];
int len;
int fd;
pid_t pid;
int socks[2], chfd;
fdh_msg * msg;
char * fname;
struct stat * stat;
size_t size;
ssize_t ssize;
if (signal(SIGTERM, terminate) == SIG_ERR) {
perror("unable to set signal");
exit(0);
}
for (;;) {
if ((len = fdh_recv(0, &fd, buf, sizeof(buf))) < 0) {
perror("recvmsg");
goto exit_;
} else if (len == 0)
goto exit_;
query_count ++;
msg = (fdh_msg *)buf;
switch (msg->query.req) {
case FDH_CLONE:
printf("clone %d\n", getpid());
if (socketpair(AF_UNIX, SOCK_STREAM, 0, socks) < 0) {
chfd = -1;
msg->reply.err = errno;
goto forkerr;
}
msg->reply.pid = pid = fork();
if (pid < 0) {
chfd = -1;
msg->reply.err = errno;
goto forkerr;
} else if (pid == 0) {
// child
//printf("!child %d\n", getpid());
close(0);
close(socks[0]);
if (dup2(socks[1], 0) < 0) {
close(socks[1]);
goto exit_;
}
close(socks[1]);
break;
}
chfd = socks[0];
msg->reply.err = 0;
forkerr:
close(socks[1]);
if (fdh_send(0, chfd, (char *)msg, FDH_MSG_SIZE) < 0) {
perror("sendmsg");
close(socks[0]);
goto exit_;
}
close(socks[0]);
break;
/*case FDH_KILL:
printf("kill %d\n", getpid());
goto exit_;
break;*/
case FDH_OPEN:
//printf("open %d\n", getpid());
fname = (char *)&buf[FDH_MSG_SIZE];
msg->reply.err = ((fd =
open(fname, msg->query.flags, msg->query.mode)) < 0) ? errno : 0;
if (fdh_send(0, fd, (char *)msg, FDH_MSG_SIZE) < 0) {
perror("sendmsg");
goto exit;
}
close(fd);
break;
case FDH_STAT:
//printf("stat %d\n", getpid());
stat = (struct stat *)&buf[FDH_MSG_SIZE];
msg->reply.err = (fstat(fd, stat) < 0) ? errno : 0;
if (fdh_send(0, fd, buf, sizeof(int) + sizeof(struct stat)) < 0) {
perror("sendmsg");
goto exit;
}
close(fd);
break;
case FDH_READ:
//printf("read %d\n", getpid());
if (sendfile(0, fd, NULL, msg->query.size) < 0) {
/* TODO handle error gracefully ?*/
perror("sendfile");
goto exit;
}
close(fd);
break;
case FDH_WRITE:
//printf("write %d %d\n", fd, getpid());
size = msg->query.size;
do {
if ((ssize = read(0, buf, sizeof(buf))) < 0) {
/* TODO handle error gracefully ? signal to parent?*/
perror("helper: read");
goto exit;
} else if (ssize == 0)
break;
if (ssize)
if (ssize != write(fd, buf, (size_t)ssize)) {
/* TODO handle error gracefully ? signal to parent?*/
perror("helper: write");
goto exit;
}
size -= ssize;
} while (size);
close(fd);
break;
default:
fprintf(stderr, "Unknown request\n");
goto exit;
break;
}
}
exit:
close(fd);
exit_:
//printf("exit %d query_count %d\n", getpid(), query_count);
close(0);
exit(0);
//TODO send signal to parent and restart loop instead of exiting (maybe)
}
void terminate(int) {
//printf("exit %d query_count %d\n", getpid(), query_count);
close(0);
exit(0);
}
<commit_msg>small bug in the fstat block of fdhelp.cc<commit_after>#include <tamer/fdhmsg.hh>
#include <signal.h>
void terminate(int);
int query_count = 0;
int main (void) {
char buf[8192];
int len;
int fd;
pid_t pid;
int socks[2], chfd;
fdh_msg * msg;
char * fname;
struct stat * stat;
size_t size;
ssize_t ssize;
if (signal(SIGTERM, terminate) == SIG_ERR) {
perror("unable to set signal");
exit(0);
}
for (;;) {
if ((len = fdh_recv(0, &fd, buf, sizeof(buf))) < 0) {
perror("recvmsg");
goto exit_;
} else if (len == 0)
goto exit_;
query_count ++;
msg = (fdh_msg *)buf;
switch (msg->query.req) {
case FDH_CLONE:
if (socketpair(AF_UNIX, SOCK_STREAM, 0, socks) < 0) {
chfd = -1;
msg->reply.err = errno;
goto forkerr;
}
msg->reply.pid = pid = fork();
if (pid < 0) {
chfd = -1;
msg->reply.err = errno;
goto forkerr;
} else if (pid == 0) {
// child
close(0);
close(socks[0]);
if (dup2(socks[1], 0) < 0) {
close(socks[1]);
goto exit_;
}
close(socks[1]);
break;
}
chfd = socks[0];
msg->reply.err = 0;
forkerr:
close(socks[1]);
if (fdh_send(0, chfd, (char *)msg, FDH_MSG_SIZE) < 0) {
perror("sendmsg");
close(socks[0]);
goto exit_;
}
close(socks[0]);
break;
case FDH_OPEN:
fname = (char *)&buf[FDH_MSG_SIZE];
msg->reply.err = ((fd =
open(fname, msg->query.flags, msg->query.mode)) < 0) ? errno : 0;
if (fdh_send(0, fd, (char *)msg, FDH_MSG_SIZE) < 0) {
perror("sendmsg");
goto exit;
}
close(fd);
break;
case FDH_STAT:
stat = (struct stat *)&buf[FDH_MSG_SIZE];
msg->reply.err = (fstat(fd, stat) < 0) ? errno : 0;
if (fdh_send(0, -1, (char *)msg, FDH_MSG_SIZE + sizeof(struct stat)) < 0) {
perror("sendmsg");
goto exit;
}
close(fd);
break;
case FDH_READ:
if (sendfile(0, fd, NULL, msg->query.size) < 0) {
/* TODO handle error gracefully ?*/
perror("sendfile");
goto exit;
}
close(fd);
break;
case FDH_WRITE:
size = msg->query.size;
do {
if ((ssize = read(0, buf, sizeof(buf))) < 0) {
/* TODO handle error gracefully ? signal to parent?*/
perror("helper: read");
goto exit;
} else if (ssize == 0)
break;
if (ssize)
if (ssize != write(fd, buf, (size_t)ssize)) {
/* TODO handle error gracefully ? signal to parent?*/
perror("helper: write");
goto exit;
}
size -= ssize;
} while (size);
close(fd);
break;
default:
fprintf(stderr, "Unknown request\n");
goto exit;
break;
}
}
exit:
close(fd);
exit_:
//TODO send signal to parent and restart loop instead of exiting (maybe)
terminate(0);
}
void terminate(int) {
//printf("exit %d query_count %d\n", getpid(), query_count);
close(0);
exit(0);
}
<|endoftext|>
|
<commit_before><commit_msg>Usage + commandline options<commit_after><|endoftext|>
|
<commit_before>#include <sh/sh.hpp>
#include <sh/shutil.hpp>
#include <iostream>
#include <list>
#include "Shader.hpp"
#include "Globals.hpp"
using namespace SH;
using namespace ShUtil;
// VCS direction and up
ShVector3f lightDir;
ShVector3f lightUp;
class AlgebraWrapper: public Shader {
public:
AlgebraWrapper(std::string name, int lightidx, int surfidx, int postidx)
: Shader(name), lightidx(lightidx), surfidx(surfidx), postidx(postidx) {}
bool init();
void render();
ShProgram vertex() { return vsh;}
ShProgram fragment() { return fsh;}
private:
int lightidx, surfidx, postidx;
ShProgram vsh, fsh;
};
class AlgebraShader : public Shader {
public:
AlgebraShader();
~AlgebraShader();
bool init();
ShProgram vertex() { return vsh;}
ShProgram fragment() { return fsh;}
ShProgram vsh, fsh;
static bool init_all();
private:
friend class AlgebraWrapper;
static const int LIGHT = 3;
static const int SURFACE = 6;
static const int POST = 2;
static ShProgram lightsh[LIGHT];
static const char* lightName[LIGHT];
static ShProgram surfsh[SURFACE];
static const char* surfName[SURFACE];
static ShProgram postsh[POST];
static const char* postName[POST];
typedef std::list<Shader*> ShaderList;
static std::list<Shader*> shaders;
static bool doneInit;
};
AlgebraShader::ShaderList AlgebraShader::shaders;
ShProgram AlgebraShader::lightsh[AlgebraShader::LIGHT];
ShProgram AlgebraShader::surfsh[AlgebraShader::SURFACE];
ShProgram AlgebraShader::postsh[AlgebraShader::POST];
bool AlgebraShader::doneInit = false;
const char* AlgebraShader::lightName[] = {
"Point Light",
"Spot Light",
"Textured Hemispherical Light"
};
const char* AlgebraShader::surfName[] = {
"Null Surface",
"Diffuse Surface",
"Specular Surface",
"Phong Surface",
"Textured Phong Surface",
"Gooch Surface"
};
const char* AlgebraShader::postName[] = {
"Null Postprocessor",
"Halftone Postprocessor"
};
bool AlgebraWrapper::init() {
AlgebraShader::init_all();
ShProgram lightsh = AlgebraShader::lightsh[lightidx];
ShProgram surfsh = AlgebraShader::surfsh[surfidx];
ShProgram postsh = AlgebraShader::postsh[postidx];
fsh = namedConnect(lightsh, surfsh);
fsh = namedConnect(fsh, postsh);
vsh = ShKernelLib::shVsh( Globals::mv, Globals::mvp );
vsh = vsh << shExtract("lightPos") << Globals::lightPos;
vsh = namedAlign(vsh, fsh);
return true;
}
void AlgebraWrapper::render() {
lightDir = -normalize(Globals::mv | Globals::lightDirW);
ShVector3f horiz = cross(lightDir, ShConstant3f(0.0f, 1.0f, 0.0f));
lightUp = cross(horiz, lightDir);
// set up lighting crap
Shader::render();
}
AlgebraShader::AlgebraShader()
: Shader("Algebra: Algebra Parent")
{
for(int i = 0; i < LIGHT; ++i) {
for(int j = 0; j < SURFACE; ++j) {
for(int k = 0; k < POST; ++k) {
std::string name = std::string("Algebra: ") + lightName[i] + " - " + surfName[j] + " - " + postName[k];
shaders.push_back(new AlgebraWrapper(name, i, j, k));
}
}
}
}
AlgebraShader::~AlgebraShader()
{
for(ShaderList::iterator I = shaders.begin(); I != shaders.end(); ++I) {
delete *I;
}
}
bool AlgebraShader::init() {
// put together all the different combinations!
vsh = ShKernelLib::shVsh( Globals::mv, Globals::mvp );
vsh = vsh << shExtract("lightPos") << Globals::lightPos;
std::cout << "AlgebraShader::init()" << std::endl;
fsh = surfsh[0];
vsh = namedAlign(vsh, fsh);
std::cout << "AlgebraShader::init() done" << std::endl;
return true;
}
bool AlgebraShader::init_all()
{
if( doneInit ) return true;
doneInit = true;
ShImage image;
// useful globals
ShColor3f SH_NAMEDECL(lightColor, "Light Colour") = ShConstant3f(1.0f, 1.0f, 1.0f);
ShAttrib1f SH_NAMEDECL(falloff, "Light falloff angle") = ShConstant1f(0.35f);
falloff.range(0.0f, M_PI);
ShAttrib1f SH_NAMEDECL(lightAngle, "Light cutoff angle") = ShConstant1f(0.5f);
lightAngle.range(0.0f, M_PI);
// TODO handle lightDirection and light up properly
ShColor3f SH_NAMEDECL(kd, "Diffuse Color") = ShConstant3f(1.0f, 0.5f, 0.7f);
ShColor3f SH_NAMEDECL(ks, "Specular Color") = ShConstant3f(0.7f, 0.7f, 0.7f);
ShColor3f SH_NAMEDECL(cool, "Specular Color") = ShConstant3f(0.4f, 0.4f, 1.0f);
ShColor3f SH_NAMEDECL(warm, "Specular Color") = ShConstant3f(1.0f, 0.4f, 0.4f);
ShAttrib1f SH_NAMEDECL(specExp, "Specular Exponent") = ShConstant1f(48.13f);
specExp.range(0.0f, 256.0f);
// ****************** Make light shaders
lightsh[0] = ShKernelLight::pointLight<ShColor3f>() << lightColor;
lightsh[1] = ShKernelLight::spotLight<ShColor3f>() << lightColor << falloff << lightAngle << lightDir;
ShAttrib1f SH_NAMEDECL(texLightScale, "Mask Scaling Factor") = ShConstant1f(5.0f);
texLightScale.range(1.0f, 10.0f);
image.loadPng(SHMEDIA_DIR "/mats/inv_oriental038.png");
ShTexture2D<ShColor3f> lighttex(image.width(), image.height());
lighttex.memory(image.memory());
lightsh[2] = ShKernelLight::texLight2D(lighttex) << texLightScale << lightAngle << lightDir << lightUp;
//lightsh[1] = ShKernelLight::spotLight(ShColor3f>() << lightColor << falloff << lightAngle << lightDir;
//lightName[1] = "Spot Light";
// ****************** Make surface shaders
surfsh[0] = ShKernelSurface::null<ShColor3f>();
surfsh[1] = ShKernelSurface::diffuse<ShColor3f>() << kd;
surfsh[2] = ShKernelSurface::specular<ShColor3f>() << ks << specExp;
surfsh[3] = ShKernelSurface::phong<ShColor3f>() << kd << ks << specExp;
image.loadPng(SHMEDIA_DIR "/textures/rustkd.png");
ShTexture2D<ShColor3f> difftex(image.width(), image.height());
difftex.memory(image.memory());
image.loadPng(SHMEDIA_DIR "/textures/rustks.png");
ShTexture2D<ShColor3f> spectex(image.width(), image.height());
spectex.memory(image.memory());
surfsh[4] = ShKernelSurface::phong<ShColor3f>() << ( access(difftex) & access(spectex) );
surfsh[4] = surfsh[4] << shExtract("specExp") << specExp;
surfsh[5] = ShKernelSurface::gooch<ShColor3f>() << kd << cool << warm;
// ******************* Make postprocessing shaders
image.loadPng(SHMEDIA_DIR "/textures/halftone.png");
ShTexture2D<ShColor3f> halftoneTex(image.width(), image.height());
halftoneTex.memory(image.memory());
ShAttrib1f SH_NAMEDECL(halftoneScale, "Scaling Factor") = ShConstant1f(0.005f);
halftoneScale.range(0.001f, 0.010f);
postsh[0] = keep<ShColor3f>("result");
postsh[1] = ShKernelPost::halftone<ShColor3f>(halftoneTex) << halftoneScale;
return true;
}
AlgebraShader the_algebra_shader;
<commit_msg>fixed halftoning in a way<commit_after>#include <sh/sh.hpp>
#include <sh/shutil.hpp>
#include <iostream>
#include <list>
#include "Shader.hpp"
#include "Globals.hpp"
#include "ShrikeCanvas.hpp"
using namespace SH;
using namespace ShUtil;
// VCS direction and up
ShVector3f lightDir;
ShVector3f lightUp;
ShAttrib1f width;
ShAttrib1f invwidth;
ShAttrib1f height;
ShAttrib1f invheight;
class AlgebraWrapper: public Shader {
public:
AlgebraWrapper(std::string name, int lightidx, int surfidx, int postidx)
: Shader(name), lightidx(lightidx), surfidx(surfidx), postidx(postidx) {}
bool init();
void render();
ShProgram vertex() { return vsh;}
ShProgram fragment() { return fsh;}
private:
int lightidx, surfidx, postidx;
ShProgram vsh, fsh;
};
class AlgebraShader : public Shader {
public:
AlgebraShader();
~AlgebraShader();
bool init();
ShProgram vertex() { return vsh;}
ShProgram fragment() { return fsh;}
ShProgram vsh, fsh;
static bool init_all();
private:
friend class AlgebraWrapper;
static const int LIGHT = 3;
static const int SURFACE = 6;
static const int POST = 2;
static ShProgram lightsh[LIGHT];
static const char* lightName[LIGHT];
static ShProgram surfsh[SURFACE];
static const char* surfName[SURFACE];
static ShProgram postsh[POST];
static const char* postName[POST];
typedef std::list<Shader*> ShaderList;
static std::list<Shader*> shaders;
static bool doneInit;
};
AlgebraShader::ShaderList AlgebraShader::shaders;
ShProgram AlgebraShader::lightsh[AlgebraShader::LIGHT];
ShProgram AlgebraShader::surfsh[AlgebraShader::SURFACE];
ShProgram AlgebraShader::postsh[AlgebraShader::POST];
bool AlgebraShader::doneInit = false;
const char* AlgebraShader::lightName[] = {
"Point Light",
"Spot Light",
"Textured Hemispherical Light"
};
const char* AlgebraShader::surfName[] = {
"Null Surface",
"Diffuse Surface",
"Specular Surface",
"Phong Surface",
"Textured Phong Surface",
"Gooch Surface"
};
const char* AlgebraShader::postName[] = {
"Null Postprocessor",
"Halftone Postprocessor"
};
bool AlgebraWrapper::init() {
AlgebraShader::init_all();
ShProgram lightsh = AlgebraShader::lightsh[lightidx];
ShProgram surfsh = AlgebraShader::surfsh[surfidx];
ShProgram postsh = AlgebraShader::postsh[postidx];
fsh = namedConnect(lightsh, surfsh);
fsh = namedConnect(fsh, postsh);
vsh = ShKernelLib::shVsh( Globals::mv, Globals::mvp );
vsh = vsh << shExtract("lightPos") << Globals::lightPos;
vsh = namedAlign(vsh, fsh);
return true;
}
void AlgebraWrapper::render() {
lightDir = -normalize(Globals::mv | Globals::lightDirW);
ShVector3f horiz = cross(lightDir, ShConstant3f(0.0f, 1.0f, 0.0f));
lightUp = cross(horiz, lightDir);
const ShrikeCanvas *canvas = ShrikeCanvas::instance();
width = canvas->m_width;
invwidth = 1.0f / width;
height = canvas->m_height;
invheight = 1.0f / height;
// set up lighting crap
Shader::render();
}
AlgebraShader::AlgebraShader()
: Shader("Algebra: Algebra Parent")
{
for(int i = 0; i < LIGHT; ++i) {
for(int j = 0; j < SURFACE; ++j) {
for(int k = 0; k < POST; ++k) {
std::string name = std::string("Algebra: ") + lightName[i] + " - " + surfName[j] + " - " + postName[k];
shaders.push_back(new AlgebraWrapper(name, i, j, k));
}
}
}
}
AlgebraShader::~AlgebraShader()
{
for(ShaderList::iterator I = shaders.begin(); I != shaders.end(); ++I) {
delete *I;
}
}
bool AlgebraShader::init() {
// put together all the different combinations!
vsh = ShKernelLib::shVsh( Globals::mv, Globals::mvp );
vsh = vsh << shExtract("lightPos") << Globals::lightPos;
std::cout << "AlgebraShader::init()" << std::endl;
fsh = surfsh[0];
vsh = namedAlign(vsh, fsh);
std::cout << "AlgebraShader::init() done" << std::endl;
return true;
}
bool AlgebraShader::init_all()
{
if( doneInit ) return true;
doneInit = true;
ShImage image;
// useful globals
ShColor3f SH_NAMEDECL(lightColor, "Light Colour") = ShConstant3f(1.0f, 1.0f, 1.0f);
ShAttrib1f SH_NAMEDECL(falloff, "Light falloff angle") = ShConstant1f(0.35f);
falloff.range(0.0f, M_PI);
ShAttrib1f SH_NAMEDECL(lightAngle, "Light cutoff angle") = ShConstant1f(0.5f);
lightAngle.range(0.0f, M_PI);
// TODO handle lightDirection and light up properly
ShColor3f SH_NAMEDECL(kd, "Diffuse Color") = ShConstant3f(1.0f, 0.5f, 0.7f);
ShColor3f SH_NAMEDECL(ks, "Specular Color") = ShConstant3f(0.7f, 0.7f, 0.7f);
ShColor3f SH_NAMEDECL(cool, "Specular Color") = ShConstant3f(0.4f, 0.4f, 1.0f);
ShColor3f SH_NAMEDECL(warm, "Specular Color") = ShConstant3f(1.0f, 0.4f, 0.4f);
ShAttrib1f SH_NAMEDECL(specExp, "Specular Exponent") = ShConstant1f(48.13f);
specExp.range(0.0f, 256.0f);
// ****************** Make light shaders
lightsh[0] = ShKernelLight::pointLight<ShColor3f>() << lightColor;
lightsh[1] = ShKernelLight::spotLight<ShColor3f>() << lightColor << falloff << lightAngle << lightDir;
ShAttrib1f SH_NAMEDECL(texLightScale, "Mask Scaling Factor") = ShConstant1f(5.0f);
texLightScale.range(1.0f, 10.0f);
image.loadPng(SHMEDIA_DIR "/mats/inv_oriental038.png");
ShTexture2D<ShColor3f> lighttex(image.width(), image.height());
lighttex.memory(image.memory());
lightsh[2] = ShKernelLight::texLight2D(lighttex) << texLightScale << lightAngle << lightDir << lightUp;
//lightsh[1] = ShKernelLight::spotLight(ShColor3f>() << lightColor << falloff << lightAngle << lightDir;
//lightName[1] = "Spot Light";
// ****************** Make surface shaders
surfsh[0] = ShKernelSurface::null<ShColor3f>();
surfsh[1] = ShKernelSurface::diffuse<ShColor3f>() << kd;
surfsh[2] = ShKernelSurface::specular<ShColor3f>() << ks << specExp;
surfsh[3] = ShKernelSurface::phong<ShColor3f>() << kd << ks << specExp;
image.loadPng(SHMEDIA_DIR "/textures/rustkd.png");
ShTexture2D<ShColor3f> difftex(image.width(), image.height());
difftex.memory(image.memory());
image.loadPng(SHMEDIA_DIR "/textures/rustks.png");
ShTexture2D<ShColor3f> spectex(image.width(), image.height());
spectex.memory(image.memory());
surfsh[4] = ShKernelSurface::phong<ShColor3f>() << ( access(difftex) & access(spectex) );
surfsh[4] = surfsh[4] << shExtract("specExp") << specExp;
surfsh[5] = ShKernelSurface::gooch<ShColor3f>() << kd << cool << warm;
// ******************* Make postprocessing shaders
image.loadPng(SHMEDIA_DIR "/textures/halftone.png");
ShTexture2D<ShColor3f> halftoneTex(image.width(), image.height());
halftoneTex.memory(image.memory());
postsh[0] = keep<ShColor3f>("result");
ShAttrib1f SH_NAMEDECL(htscale, "Scaling Factor") = ShConstant1f(50.0f);
htscale.range(1.0f, 400.0f);
postsh[1] = ShKernelPost::halftone<ShColor3f>(halftoneTex) << (mul<ShAttrib1f>() << htscale << invheight);
return true;
}
AlgebraShader the_algebra_shader;
<|endoftext|>
|
<commit_before>//===========================================
// PC-BSD source code
// Copyright (c) 2016, PC-BSD Software/iXsystems
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "sysadm-client.h"
#include <QSslConfiguration>
#include <QJsonArray>
#include <QProcess>
#include <QFile>
#include <QTimer>
#include <QSettings>
#include <QSslKey>
#include <QSslCertificate>
//SSL Stuff
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#define SERVERPIDFILE QString("/var/run/sysadm.pid")
extern QSettings *settings;
//Unencrypted SSL objects (after loading them by user passphrase)
extern QSslConfiguration SSL_cfg; //Check "isNull()" to see if the user settings have been loaded yet
// === PUBLIC ===
sysadm_client::sysadm_client(){
SOCKET = new QWebSocket("sysadm-client", QWebSocketProtocol::VersionLatest, this);
//SOCKET->setSslConfiguration(QSslConfiguration::defaultConfiguration());
//SOCKET->ignoreSslErrors();
//use the new Qt5 connection syntax for compile time checks that connections are valid
connect(SOCKET, &QWebSocket::connected, this, &sysadm_client::socketConnected);
connect(SOCKET, &QWebSocket::disconnected, this, &sysadm_client::socketClosed);
connect(SOCKET, &QWebSocket::textMessageReceived, this, &sysadm_client::socketMessage);
//Old connect syntax for the "error" signal (special note about issues in the docs)
connect(SOCKET, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)) );
connect(SOCKET, SIGNAL(sslErrors(const QList<QSslError>&)), this, SLOT(socketSslErrors(const QList<QSslError>&)) );
keepActive=false; //not setup yet
}
sysadm_client::~sysadm_client(){
}
// Overall Connection functions (start/stop)
void sysadm_client::openConnection(QString user, QString pass, QString hostIP){
cuser = user; cpass = pass; chost = hostIP;
//qDebug() << "Client: Setup connection:" << user << pass << hostIP;
setupSocket();
}
void sysadm_client::openConnection(QString authkey, QString hostIP){
cauthkey = authkey; chost = hostIP;
setupSocket();
}
void sysadm_client::openConnection(QString hostIP){
chost = hostIP;
setupSocket();
}
void sysadm_client::closeConnection(){
keepActive = false;
//de-authorize the current auth token
if(!cauthkey.isEmpty()){
cauthkey.clear();
clearAuth();
}
//Now close the connection
SOCKET->close(QWebSocketProtocol::CloseCodeNormal, "sysadm-client closed");
}
QString sysadm_client::currentHost(){
return chost;
}
bool sysadm_client::isActive(){
return ((SOCKET!=0) && SOCKET->isValid());
}
//Check if the sysadm server is running on the local system
bool sysadm_client::localhostAvailable(){
#ifdef __FreeBSD__
qDebug() << "Checking for Local Host:" << SERVERPIDFILE;
//Check if the local socket can connect
if(QFile::exists(SERVERPIDFILE)){
//int ret = QProcess::execute("pgrep -f \""+SERVERPIDFILE+"\"");
//return (ret==0 || ret>3);
return true;
}
#endif
return false;
}
// Register for Event Notifications (no notifications by default)
void sysadm_client::registerForEvents(EVENT_TYPE event, bool receive){
bool set = events.contains(event);
if( set && receive){ return; } //already registered
else if(!set && !receive){ return; } //already unregistered
else if(set){ events << event; }
else{ events.removeAll(event); }
//Since this can be setup before the socket is connected - see if we can send this message right away
if(SOCKET->isValid()){
sendEventSubscription(event, receive);
}
}
//Register the custom SSL Certificate with the server
void sysadm_client::registerCustomCert(){
if(SSL_cfg.isNull() || SOCKET==0 || !SOCKET->isValid()){ return; }
//Get the custom cert
QList<QSslCertificate> certs = SSL_cfg.localCertificateChain();
QString pubkey, email, nickname;
for(int i=0; i<certs.length(); i++){
if(certs[i].issuerInfo(QSslCertificate::Organization).contains("SysAdm-client")){
pubkey = QString(certs[i].publicKey().toPem().toBase64());
email = certs[i].issuerInfo(QSslCertificate::EmailAddress).join("");
nickname = certs[i].issuerInfo(QSslCertificate::Organization).join("");
break;
}
}
if(pubkey.isEmpty()){ return; } //no cert found
//Now assemble the request JSON
QJsonObject obj;
obj.insert("action","register_ssl_cert");
obj.insert("pub_key", pubkey);
obj.insert("email",email);
obj.insert("nickname",nickname);
this->communicate("sysadm-auto-cert-register","sysadm","settings", obj);
}
// Messages which are still pending a response
QStringList sysadm_client::pending(){ return PENDING; } //returns only the "id" for each
// Fetch a message from the recent cache
QJsonObject sysadm_client::cachedRequest(QString id){
if(SENT.contains(id)){ return SENT.value(id); }
else{ return QJsonObject(); }
}
QJsonValue sysadm_client::cachedReply(QString id){
if(BACK.contains(id)){ return BACK.value(id); }
else{ return QJsonObject(); }
}
// === PRIVATE ===
//Functions to do the initial socket setup
void sysadm_client::setupSocket(){
//qDebug() << "Setup Socket:" << SOCKET->isValid();
if(SOCKET->isValid()){ return; }
//Setup the SSL config as needed
SOCKET->setSslConfiguration(QSslConfiguration::defaultConfiguration());
//uses chost for setup
// - assemble the host URL
if(chost.contains("://")){ chost = chost.section("://",1,1); } //Chop off the custom http/ftp/other header (always need "wss://")
QString url = "wss://"+chost;
bool hasport = false;
url.section(":",-1).toInt(&hasport); //check if the last piece of the url is a valid number
//Could add a check for a valid port number as well - but that is a bit overkill right now
if(!hasport){ url.append(":"+QString::number(WSPORTDEFAULT)); }
qDebug() << " Open WebSocket: URL:" << url;
QTimer::singleShot(0,SOCKET, SLOT(ignoreSslErrors()) );
SOCKET->open(QUrl(url));
//QList<QSslError> ignored; ignored << QSslError(QSslError::SelfSignedCertificate) << QSslError(QSslError::HostNameMismatch);
//SOCKET->ignoreSslErrors(ignored);
}
void sysadm_client::performAuth(QString user, QString pass){
//uses cauthkey if empty inputs
QJsonObject obj;
obj.insert("namespace","rpc");
obj.insert("id","sysadm-client-auth-auto");
bool noauth = false;
if(user.isEmpty()){
if(cauthkey.isEmpty()){
//SSL Authentication (Stage 1)
obj.insert("name","auth_ssl");
obj.insert("args","");
}else{
//Saved token authentication
obj.insert("name","auth_token");
QJsonObject arg;
arg.insert("token",cauthkey);
obj.insert("args", arg);
}
}else{
//User/password authentication
obj.insert("name","auth");
QJsonObject arg;
arg.insert("username",user);
arg.insert("password",pass);
obj.insert("args", arg);
}
sendSocketMessage(obj);
if(noauth){ emit clientUnauthorized(); }
}
void sysadm_client::clearAuth(){
QJsonObject obj;
obj.insert("namespace","rpc");
obj.insert("id","sysadm-client-auth-auto");
obj.insert("name","auth_clear");
obj.insert("args","");
sendSocketMessage(obj);
emit clientUnauthorized();
}
//Communication subroutines with the server (block until message comes back)
void sysadm_client::sendEventSubscription(EVENT_TYPE event, bool subscribe){
QJsonObject obj;
obj.insert("namespace","events");
obj.insert("name", subscribe ? "subscribe" : "unsubscribe");
obj.insert("id", "sysadm-client-event-auto");
QString arg;
if(event == DISPATCHER){ arg = "dispatcher"; }
else if(event == LIFEPRESERVER){ arg = "life-preserver"; }
obj.insert("args", arg);
sendSocketMessage(obj);
}
void sysadm_client::sendSocketMessage(QJsonObject msg){
QJsonDocument doc(msg);
//qDebug() << "Send Socket Message:" << doc.toJson(QJsonDocument::Compact);
SOCKET->sendTextMessage(doc.toJson(QJsonDocument::Compact));
}
//Simplification functions
QJsonObject sysadm_client::convertServerReply(QString reply){
QJsonDocument doc = QJsonDocument::fromJson(reply.toUtf8());
if(doc.isObject()){ return doc.object(); }
else{ return QJsonObject(); }
}
QString sysadm_client::SSL_Encode_String(QString str){
//Get the private key
QByteArray privkey = SSL_cfg.privateKey().toPem();
//Now use this private key to encode the given string
unsigned char encode[4098] = {};
RSA *rsa= NULL;
BIO *keybio = NULL;
keybio = BIO_new_mem_buf(privkey.data(), -1);
if(keybio==NULL){ return ""; }
rsa = PEM_read_bio_RSAPrivateKey(keybio, &rsa,NULL, NULL);
bool ok = (-1 != RSA_private_encrypt(str.length(), (unsigned char*)(str.toLatin1().data()), encode, rsa, RSA_PKCS1_PADDING) );
if(!ok){ return ""; }
else{
//Now return this as a base64 encoded string
return QString( QByteArray( (char*)(encode) ).toBase64() );
}
}
// === PUBLIC SLOTS ===
// Communications with server (send message, get response via signal later)
void sysadm_client::communicate(QString ID, QString namesp, QString name, QJsonValue args){
//Overloaded function for a request which needs assembly
QJsonObject obj;
obj.insert("namespace",namesp);
obj.insert("name", name);
obj.insert("id", ID);
obj.insert("args", args);
//qDebug() << "Send Message:" << QJsonDocument(obj).toJson();
communicate(QList<QJsonObject>() << obj);
}
void sysadm_client::communicate(QJsonObject request){
//Overloaded function for a single JSON request
communicate(QList<QJsonObject>() << request);
}
void sysadm_client::communicate(QList<QJsonObject> requests){
for(int i=0; i<requests.length(); i++){
QString ID = requests[i].value("id").toString();
if(ID.isEmpty()){
qDebug() << "Malformed JSON request:" << requests[i];
continue;
}
//Save this into the cache
SENT.insert(ID, requests[i]);
if(BACK.contains(ID)){ BACK.remove(ID); }
PENDING << ID;
//Now send off the message
if(SOCKET->isValid()){ sendSocketMessage(requests[i]); }
}
}
// === PRIVATE SLOTS ===
//Socket signal/slot connections
void sysadm_client::socketConnected(){ //Signal: connected()
keepActive = true; //got a valid connection - try to keep this open automatically
num_fail = 0; //reset fail counter - got a valid connection
emit clientConnected();
performAuth(cuser, cpass);
cuser.clear(); cpass.clear(); //just to ensure no trace left in memory
}
void sysadm_client::socketClosed(){ //Signal: disconnected()
/*if(keepActive && num_fail < FAIL_MAX){
//Socket closed due to timeout?
// Go ahead and re-open it if possible with the last-used settings/auth
num_fail++;
setupSocket();
}else{*/
num_fail = 0; //reset back to nothing
emit clientDisconnected();
//Server cache is now invalid - completely lost connection
SENT.clear(); BACK.clear(); PENDING.clear();
//}
}
void sysadm_client::socketSslErrors(const QList<QSslError>&errlist){ //Signal: sslErrors()
qWarning() << "SSL Errors Detected:" << errlist.length();
QList<QSslError> ignored;
for(int i=0; i< errlist.length(); i++){
if(errlist[i].error()==QSslError::SelfSignedCertificate || errlist[i].error()==QSslError::HostNameMismatch ){
qDebug() << " - (IGNORED) " << errlist[i].errorString();
ignored << errlist[i];
}else{
qWarning() << " - " << errlist[i].errorString();
}
}
if(ignored.length() != errlist.length()){
SOCKET->close(); //SSL errors - close the connection
}
}
void sysadm_client::socketError(QAbstractSocket::SocketError err){ //Signal:: error()
qWarning() << "Socket Error detected:" << err;
if(err==QAbstractSocket::SslHandshakeFailedError){qWarning() << " - SSL Handshake Failed"; }
qWarning() << " - Final websocket error:" << SOCKET->errorString();
}
//void sysadm_client::socketProxyAuthRequired(const QNetworkProxy &proxy, QAuthenticator *auth); //Signal: proxyAuthenticationRequired()
// - Main message input parsing
void sysadm_client::socketMessage(QString msg){ //Signal: textMessageReceived()
//qDebug() << "New Reply From Server:" << msg;
//Convert this into a JSON object
QJsonObject obj = convertServerReply(msg);
QString ID = obj.value("id").toString();
QString namesp = obj.value("namespace").toString();
QString name = obj.value("name").toString();
//Still need to add some parsing to the return message
if(ID=="sysadm-client-auth-auto"){
//Reply to automated auth system
if(name=="error"){
closeConnection();
emit clientUnauthorized();
}else{
QJsonValue args = obj.value("args");
if(args.isArray()){
cauthkey = args.toArray().first().toString();
emit clientAuthorized();
//Now automatically re-subscribe to events as needed
for(int i=0; i<events.length(); i++){ sendEventSubscription(events[i]); }
}else if(args.isObject()){
//SSL Auth Stage 2
QString randomkey = args.toObject().value("test_string").toString();
if(!randomkey.isEmpty()){
QJsonObject obj;
obj.insert("name","auth_ssl");
obj.insert("namespace","rpc");
obj.insert("id",ID); //re-use this special ID
QJsonObject args;
args.insert("encrypted_string", SSL_Encode_String(randomkey));
obj.insert("args",args);
this->communicate(obj);
}
}
}
}else if(ID=="sysadm-client-event-auto"){
//Reply to automated event subscription - don't need to save this
}else if(namesp=="events"){
//Event notification - not tied to any particular request
if(name=="dispatcher"){ emit NewEvent(DISPATCHER, obj.value("args")); }
else if(name=="life-preserver"){ emit NewEvent(LIFEPRESERVER, obj.value("args")); }
}else{
//Now save this message into the cache for use later (if not an auth reply)
if(!ID.isEmpty()){
PENDING.removeAll(ID);
BACK.insert(ID, obj);
}
emit newReply(ID, name, namesp, obj.value("args"));
}
}
<commit_msg>Add in some more debugging in the sysadm_client.<commit_after>//===========================================
// PC-BSD source code
// Copyright (c) 2016, PC-BSD Software/iXsystems
// Available under the 3-clause BSD license
// See the LICENSE file for full details
//===========================================
#include "sysadm-client.h"
#include <QSslConfiguration>
#include <QJsonArray>
#include <QProcess>
#include <QFile>
#include <QTimer>
#include <QSettings>
#include <QSslKey>
#include <QSslCertificate>
//SSL Stuff
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#define SERVERPIDFILE QString("/var/run/sysadm.pid")
#define DEBUG 0
extern QSettings *settings;
//Unencrypted SSL objects (after loading them by user passphrase)
extern QSslConfiguration SSL_cfg; //Check "isNull()" to see if the user settings have been loaded yet
// === PUBLIC ===
sysadm_client::sysadm_client(){
SOCKET = new QWebSocket("sysadm-client", QWebSocketProtocol::VersionLatest, this);
//SOCKET->setSslConfiguration(QSslConfiguration::defaultConfiguration());
//SOCKET->ignoreSslErrors();
//use the new Qt5 connection syntax for compile time checks that connections are valid
connect(SOCKET, &QWebSocket::connected, this, &sysadm_client::socketConnected);
connect(SOCKET, &QWebSocket::disconnected, this, &sysadm_client::socketClosed);
connect(SOCKET, &QWebSocket::textMessageReceived, this, &sysadm_client::socketMessage);
//Old connect syntax for the "error" signal (special note about issues in the docs)
connect(SOCKET, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)) );
connect(SOCKET, SIGNAL(sslErrors(const QList<QSslError>&)), this, SLOT(socketSslErrors(const QList<QSslError>&)) );
keepActive=false; //not setup yet
}
sysadm_client::~sysadm_client(){
}
// Overall Connection functions (start/stop)
void sysadm_client::openConnection(QString user, QString pass, QString hostIP){
cuser = user; cpass = pass; chost = hostIP;
//qDebug() << "Client: Setup connection:" << user << pass << hostIP;
setupSocket();
}
void sysadm_client::openConnection(QString authkey, QString hostIP){
cauthkey = authkey; chost = hostIP;
setupSocket();
}
void sysadm_client::openConnection(QString hostIP){
chost = hostIP;
setupSocket();
}
void sysadm_client::closeConnection(){
keepActive = false;
//de-authorize the current auth token
if(!cauthkey.isEmpty()){
cauthkey.clear();
clearAuth();
}
//Now close the connection
SOCKET->close(QWebSocketProtocol::CloseCodeNormal, "sysadm-client closed");
}
QString sysadm_client::currentHost(){
return chost;
}
bool sysadm_client::isActive(){
return ((SOCKET!=0) && SOCKET->isValid());
}
//Check if the sysadm server is running on the local system
bool sysadm_client::localhostAvailable(){
#ifdef __FreeBSD__
if(DEBUG){ qDebug() << "Checking for Local Host:" << SERVERPIDFILE; }
//Check if the local socket can connect
if(QFile::exists(SERVERPIDFILE)){
//int ret = QProcess::execute("pgrep -f \""+SERVERPIDFILE+"\"");
//return (ret==0 || ret>3);
return true;
}
#endif
return false;
}
// Register for Event Notifications (no notifications by default)
void sysadm_client::registerForEvents(EVENT_TYPE event, bool receive){
bool set = events.contains(event);
if( set && receive){ return; } //already registered
else if(!set && !receive){ return; } //already unregistered
else if(set){ events << event; }
else{ events.removeAll(event); }
//Since this can be setup before the socket is connected - see if we can send this message right away
if(SOCKET->isValid()){
sendEventSubscription(event, receive);
}
}
//Register the custom SSL Certificate with the server
void sysadm_client::registerCustomCert(){
if(SSL_cfg.isNull() || SOCKET==0 || !SOCKET->isValid()){ return; }
//Get the custom cert
QList<QSslCertificate> certs = SSL_cfg.localCertificateChain();
QString pubkey, email, nickname;
for(int i=0; i<certs.length(); i++){
if(certs[i].issuerInfo(QSslCertificate::Organization).contains("SysAdm-client")){
pubkey = QString(certs[i].publicKey().toPem().toBase64());
email = certs[i].issuerInfo(QSslCertificate::EmailAddress).join("");
nickname = certs[i].issuerInfo(QSslCertificate::Organization).join("");
break;
}
}
if(pubkey.isEmpty()){ return; } //no cert found
//Now assemble the request JSON
QJsonObject obj;
obj.insert("action","register_ssl_cert");
obj.insert("pub_key", pubkey);
obj.insert("email",email);
obj.insert("nickname",nickname);
this->communicate("sysadm-auto-cert-register","sysadm","settings", obj);
}
// Messages which are still pending a response
QStringList sysadm_client::pending(){ return PENDING; } //returns only the "id" for each
// Fetch a message from the recent cache
QJsonObject sysadm_client::cachedRequest(QString id){
if(SENT.contains(id)){ return SENT.value(id); }
else{ return QJsonObject(); }
}
QJsonValue sysadm_client::cachedReply(QString id){
if(BACK.contains(id)){ return BACK.value(id); }
else{ return QJsonObject(); }
}
// === PRIVATE ===
//Functions to do the initial socket setup
void sysadm_client::setupSocket(){
//qDebug() << "Setup Socket:" << SOCKET->isValid();
if(SOCKET->isValid()){ return; }
//Setup the SSL config as needed
SOCKET->setSslConfiguration(QSslConfiguration::defaultConfiguration());
//uses chost for setup
// - assemble the host URL
if(chost.contains("://")){ chost = chost.section("://",1,1); } //Chop off the custom http/ftp/other header (always need "wss://")
QString url = "wss://"+chost;
bool hasport = false;
url.section(":",-1).toInt(&hasport); //check if the last piece of the url is a valid number
//Could add a check for a valid port number as well - but that is a bit overkill right now
if(!hasport){ url.append(":"+QString::number(WSPORTDEFAULT)); }
qDebug() << " Open WebSocket: URL:" << url;
QTimer::singleShot(0,SOCKET, SLOT(ignoreSslErrors()) );
SOCKET->open(QUrl(url));
//QList<QSslError> ignored; ignored << QSslError(QSslError::SelfSignedCertificate) << QSslError(QSslError::HostNameMismatch);
//SOCKET->ignoreSslErrors(ignored);
}
void sysadm_client::performAuth(QString user, QString pass){
//uses cauthkey if empty inputs
QJsonObject obj;
obj.insert("namespace","rpc");
obj.insert("id","sysadm-client-auth-auto");
bool noauth = false;
if(user.isEmpty()){
if(cauthkey.isEmpty()){
//SSL Authentication (Stage 1)
obj.insert("name","auth_ssl");
obj.insert("args","");
}else{
//Saved token authentication
obj.insert("name","auth_token");
QJsonObject arg;
arg.insert("token",cauthkey);
obj.insert("args", arg);
}
}else{
//User/password authentication
obj.insert("name","auth");
QJsonObject arg;
arg.insert("username",user);
arg.insert("password",pass);
obj.insert("args", arg);
}
sendSocketMessage(obj);
if(noauth){ emit clientUnauthorized(); }
}
void sysadm_client::clearAuth(){
QJsonObject obj;
obj.insert("namespace","rpc");
obj.insert("id","sysadm-client-auth-auto");
obj.insert("name","auth_clear");
obj.insert("args","");
sendSocketMessage(obj);
emit clientUnauthorized();
}
//Communication subroutines with the server (block until message comes back)
void sysadm_client::sendEventSubscription(EVENT_TYPE event, bool subscribe){
QJsonObject obj;
obj.insert("namespace","events");
obj.insert("name", subscribe ? "subscribe" : "unsubscribe");
obj.insert("id", "sysadm-client-event-auto");
QString arg;
if(event == DISPATCHER){ arg = "dispatcher"; }
else if(event == LIFEPRESERVER){ arg = "life-preserver"; }
obj.insert("args", arg);
sendSocketMessage(obj);
}
void sysadm_client::sendSocketMessage(QJsonObject msg){
QJsonDocument doc(msg);
if(DEBUG){ qDebug() << "Send Socket Message:" << doc.toJson(QJsonDocument::Compact); }
SOCKET->sendTextMessage(doc.toJson(QJsonDocument::Compact));
}
//Simplification functions
QJsonObject sysadm_client::convertServerReply(QString reply){
QJsonDocument doc = QJsonDocument::fromJson(reply.toUtf8());
if(doc.isObject()){ return doc.object(); }
else{ return QJsonObject(); }
}
QString sysadm_client::SSL_Encode_String(QString str){
//Get the private key
QByteArray privkey = SSL_cfg.privateKey().toPem();
//Now use this private key to encode the given string
unsigned char encode[4098] = {};
RSA *rsa= NULL;
BIO *keybio = NULL;
keybio = BIO_new_mem_buf(privkey.data(), -1);
if(keybio==NULL){ return ""; }
rsa = PEM_read_bio_RSAPrivateKey(keybio, &rsa,NULL, NULL);
bool ok = (-1 != RSA_private_encrypt(str.length(), (unsigned char*)(str.toLatin1().data()), encode, rsa, RSA_PKCS1_PADDING) );
if(!ok){ return ""; }
else{
//Now return this as a base64 encoded string
return QString( QByteArray( (char*)(encode) ).toBase64() );
}
}
// === PUBLIC SLOTS ===
// Communications with server (send message, get response via signal later)
void sysadm_client::communicate(QString ID, QString namesp, QString name, QJsonValue args){
//Overloaded function for a request which needs assembly
QJsonObject obj;
obj.insert("namespace",namesp);
obj.insert("name", name);
obj.insert("id", ID);
obj.insert("args", args);
//qDebug() << "Send Message:" << QJsonDocument(obj).toJson();
communicate(QList<QJsonObject>() << obj);
}
void sysadm_client::communicate(QJsonObject request){
//Overloaded function for a single JSON request
communicate(QList<QJsonObject>() << request);
}
void sysadm_client::communicate(QList<QJsonObject> requests){
for(int i=0; i<requests.length(); i++){
QString ID = requests[i].value("id").toString();
if(ID.isEmpty()){
qDebug() << "Malformed JSON request:" << requests[i];
continue;
}
//Save this into the cache
SENT.insert(ID, requests[i]);
if(BACK.contains(ID)){ BACK.remove(ID); }
PENDING << ID;
//Now send off the message
if(SOCKET->isValid()){ sendSocketMessage(requests[i]); }
}
}
// === PRIVATE SLOTS ===
//Socket signal/slot connections
void sysadm_client::socketConnected(){ //Signal: connected()
keepActive = true; //got a valid connection - try to keep this open automatically
num_fail = 0; //reset fail counter - got a valid connection
emit clientConnected();
performAuth(cuser, cpass);
cuser.clear(); cpass.clear(); //just to ensure no trace left in memory
}
void sysadm_client::socketClosed(){ //Signal: disconnected()
qDebug() << " - Connection Closed:" << chost;
/*if(keepActive && num_fail < FAIL_MAX){
//Socket closed due to timeout?
// Go ahead and re-open it if possible with the last-used settings/auth
num_fail++;
setupSocket();
}else{*/
num_fail = 0; //reset back to nothing
emit clientDisconnected();
//Server cache is now invalid - completely lost connection
SENT.clear(); BACK.clear(); PENDING.clear();
//}
}
void sysadm_client::socketSslErrors(const QList<QSslError>&errlist){ //Signal: sslErrors()
qWarning() << "SSL Errors Detected:" << errlist.length();
QList<QSslError> ignored;
for(int i=0; i< errlist.length(); i++){
if(errlist[i].error()==QSslError::SelfSignedCertificate || errlist[i].error()==QSslError::HostNameMismatch ){
qDebug() << " - (IGNORED) " << errlist[i].errorString();
ignored << errlist[i];
}else{
qWarning() << " - " << errlist[i].errorString();
}
}
if(ignored.length() != errlist.length()){
SOCKET->close(); //SSL errors - close the connection
}
}
void sysadm_client::socketError(QAbstractSocket::SocketError err){ //Signal:: error()
qWarning() << "Socket Error detected:" << err;
if(err==QAbstractSocket::SslHandshakeFailedError){qWarning() << " - SSL Handshake Failed"; }
qWarning() << " - Final websocket error:" << SOCKET->errorString();
}
//void sysadm_client::socketProxyAuthRequired(const QNetworkProxy &proxy, QAuthenticator *auth); //Signal: proxyAuthenticationRequired()
// - Main message input parsing
void sysadm_client::socketMessage(QString msg){ //Signal: textMessageReceived()
if(DEBUG){ qDebug() << "New Reply From Server:" << msg; }
//Convert this into a JSON object
QJsonObject obj = convertServerReply(msg);
QString ID = obj.value("id").toString();
QString namesp = obj.value("namespace").toString();
QString name = obj.value("name").toString();
//Still need to add some parsing to the return message
if(ID=="sysadm-client-auth-auto"){
//Reply to automated auth system
if(name=="error"){
closeConnection();
emit clientUnauthorized();
}else{
QJsonValue args = obj.value("args");
if(args.isArray()){
cauthkey = args.toArray().first().toString();
emit clientAuthorized();
//Now automatically re-subscribe to events as needed
for(int i=0; i<events.length(); i++){ sendEventSubscription(events[i]); }
}else if(args.isObject()){
//SSL Auth Stage 2
QString randomkey = args.toObject().value("test_string").toString();
if(!randomkey.isEmpty()){
QJsonObject obj;
obj.insert("name","auth_ssl");
obj.insert("namespace","rpc");
obj.insert("id",ID); //re-use this special ID
QJsonObject args;
args.insert("encrypted_string", SSL_Encode_String(randomkey));
obj.insert("args",args);
this->communicate(obj);
}
}
}
}else if(ID=="sysadm-client-event-auto"){
//Reply to automated event subscription - don't need to save this
}else if(namesp=="events"){
//Event notification - not tied to any particular request
if(name=="dispatcher"){ emit NewEvent(DISPATCHER, obj.value("args")); }
else if(name=="life-preserver"){ emit NewEvent(LIFEPRESERVER, obj.value("args")); }
}else{
//Now save this message into the cache for use later (if not an auth reply)
if(!ID.isEmpty()){
PENDING.removeAll(ID);
BACK.insert(ID, obj);
}
emit newReply(ID, name, namesp, obj.value("args"));
}
}
<|endoftext|>
|
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "qmljseditorconstants.h"
#include "qmljsmodelmanager.h"
#include "qmljseditor.h"
#include <coreplugin/icore.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/mimedatabase.h>
#include <qmljs/qmljsinterpreter.h>
#include <qmljs/qmljsbind.h>
#include <qmljs/parser/qmldirparser_p.h>
#include <texteditor/itexteditor.h>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QLibraryInfo>
#include <QtConcurrentRun>
#include <qtconcurrent/runextensions.h>
#include <QTextStream>
#include <QDebug>
using namespace QmlJS;
using namespace QmlJSEditor;
using namespace QmlJSEditor::Internal;
static QStringList environmentImportPaths();
ModelManager::ModelManager(QObject *parent):
ModelManagerInterface(parent),
m_core(Core::ICore::instance())
{
m_synchronizer.setCancelOnWait(true);
qRegisterMetaType<QmlJS::Document::Ptr>("QmlJS::Document::Ptr");
qRegisterMetaType<QmlJS::LibraryInfo>("QmlJS::LibraryInfo");
connect(this, SIGNAL(documentUpdated(QmlJS::Document::Ptr)),
this, SLOT(onDocumentUpdated(QmlJS::Document::Ptr)));
connect(this, SIGNAL(libraryInfoUpdated(QString,QmlJS::LibraryInfo)),
this, SLOT(onLibraryInfoUpdated(QString,QmlJS::LibraryInfo)));
loadQmlTypeDescriptions();
m_defaultImportPaths << environmentImportPaths();
m_defaultImportPaths << QLibraryInfo::location(QLibraryInfo::ImportsPath);
}
void ModelManager::loadQmlTypeDescriptions()
{
const QString resourcePath = Core::ICore::instance()->resourcePath();
const QDir typeFileDir(resourcePath + QLatin1String("/qml-type-descriptions"));
const QStringList xmlExtensions = QStringList() << QLatin1String("*.xml");
const QFileInfoList xmlFiles = typeFileDir.entryInfoList(xmlExtensions,
QDir::Files,
QDir::Name);
const QStringList errors = Interpreter::MetaTypeSystem::load(xmlFiles);
foreach (const QString &error, errors)
qWarning() << qPrintable(error);
}
Snapshot ModelManager::snapshot() const
{
QMutexLocker locker(&m_mutex);
return _snapshot;
}
void ModelManager::updateSourceFiles(const QStringList &files)
{
refreshSourceFiles(files);
}
QFuture<void> ModelManager::refreshSourceFiles(const QStringList &sourceFiles)
{
if (sourceFiles.isEmpty()) {
return QFuture<void>();
}
const QMap<QString, WorkingCopy> workingCopy = buildWorkingCopyList();
QFuture<void> result = QtConcurrent::run(&ModelManager::parse,
workingCopy, sourceFiles,
this);
if (m_synchronizer.futures().size() > 10) {
QList<QFuture<void> > futures = m_synchronizer.futures();
m_synchronizer.clearFutures();
foreach (QFuture<void> future, futures) {
if (! (future.isFinished() || future.isCanceled()))
m_synchronizer.addFuture(future);
}
}
m_synchronizer.addFuture(result);
if (sourceFiles.count() > 1) {
m_core->progressManager()->addTask(result, tr("Indexing"),
QmlJSEditor::Constants::TASK_INDEX);
}
return result;
}
QMap<QString, ModelManager::WorkingCopy> ModelManager::buildWorkingCopyList()
{
QMap<QString, WorkingCopy> workingCopy;
Core::EditorManager *editorManager = m_core->editorManager();
foreach (Core::IEditor *editor, editorManager->openedEditors()) {
const QString key = editor->file()->fileName();
if (TextEditor::ITextEditor *textEditor = qobject_cast<TextEditor::ITextEditor*>(editor)) {
if (QmlJSTextEditor *ed = qobject_cast<QmlJSTextEditor *>(textEditor->widget())) {
workingCopy[key].contents = ed->toPlainText();
workingCopy[key].documentRevision = ed->document()->revision();
}
}
}
return workingCopy;
}
void ModelManager::emitDocumentUpdated(Document::Ptr doc)
{ emit documentUpdated(doc); }
void ModelManager::onDocumentUpdated(Document::Ptr doc)
{
QMutexLocker locker(&m_mutex);
_snapshot.insert(doc);
}
void ModelManager::emitLibraryInfoUpdated(const QString &path, const LibraryInfo &info)
{ emit libraryInfoUpdated(path, info); }
void ModelManager::onLibraryInfoUpdated(const QString &path, const LibraryInfo &info)
{
QMutexLocker locker(&m_mutex);
_snapshot.insertLibraryInfo(path, info);
}
static QStringList qmlFilesInDirectory(const QString &path)
{
// ### It would suffice to build pattern once. This function needs to be thread-safe.
Core::MimeDatabase *db = Core::ICore::instance()->mimeDatabase();
Core::MimeType jsSourceTy = db->findByType(QmlJSEditor::Constants::JS_MIMETYPE);
Core::MimeType qmlSourceTy = db->findByType(QmlJSEditor::Constants::QML_MIMETYPE);
QStringList pattern;
foreach (const QRegExp &glob, jsSourceTy.globPatterns())
pattern << glob.pattern();
foreach (const QRegExp &glob, qmlSourceTy.globPatterns())
pattern << glob.pattern();
QStringList files;
const QDir dir(path);
foreach (const QFileInfo &fi, dir.entryInfoList(pattern, QDir::Files))
files += fi.absoluteFilePath();
return files;
}
static void findNewImplicitImports(const Document::Ptr &doc, const Snapshot &snapshot,
QStringList *importedFiles, QSet<QString> *scannedPaths)
{
// scan files that could be implicitly imported
// it's important we also do this for JS files, otherwise the isEmpty check will fail
if (snapshot.documentsInDirectory(doc->path()).isEmpty()) {
if (! scannedPaths->contains(doc->path())) {
*importedFiles += qmlFilesInDirectory(doc->path());
scannedPaths->insert(doc->path());
}
}
}
static void findNewFileImports(const Document::Ptr &doc, const Snapshot &snapshot,
QStringList *importedFiles, QSet<QString> *scannedPaths)
{
// scan files and directories that are explicitly imported
foreach (const QString &fileImport, doc->bind()->fileImports()) {
const QFileInfo importFileInfo(doc->path() + QLatin1Char('/') + fileImport);
const QString &importFilePath = importFileInfo.absoluteFilePath();
if (importFileInfo.isFile()) {
if (! snapshot.document(importFilePath))
*importedFiles += importFilePath;
} else if (importFileInfo.isDir()) {
if (snapshot.documentsInDirectory(importFilePath).isEmpty()) {
if (! scannedPaths->contains(importFilePath)) {
*importedFiles += qmlFilesInDirectory(importFilePath);
scannedPaths->insert(importFilePath);
}
}
}
}
}
static void findNewLibraryImports(const Document::Ptr &doc, const Snapshot &snapshot,
ModelManager *modelManager,
QStringList *importedFiles, QSet<QString> *scannedPaths)
{
// scan library imports
foreach (const QString &libraryImport, doc->bind()->libraryImports()) {
foreach (const QString &importPath, modelManager->importPaths()) {
QDir dir(importPath);
dir.cd(libraryImport);
const QString targetPath = dir.absolutePath();
// if we know there is a library, done
if (snapshot.libraryInfo(targetPath).isValid())
break;
// if there is a qmldir file, we found a new library!
if (dir.exists("qmldir")) {
QFile qmldirFile(dir.filePath("qmldir"));
qmldirFile.open(QFile::ReadOnly);
QString qmldirData = QString::fromUtf8(qmldirFile.readAll());
QmlDirParser qmldirParser;
qmldirParser.setSource(qmldirData);
qmldirParser.parse();
modelManager->emitLibraryInfoUpdated(QFileInfo(qmldirFile).absolutePath(),
LibraryInfo(qmldirParser));
// scan the qml files in the library
foreach (const QmlDirParser::Component &component, qmldirParser.components()) {
if (! component.fileName.isEmpty()) {
QFileInfo componentFileInfo(dir.filePath(component.fileName));
const QString path = componentFileInfo.absolutePath();
if (! scannedPaths->contains(path)) {
*importedFiles += qmlFilesInDirectory(path);
scannedPaths->insert(path);
}
}
}
}
}
}
}
void ModelManager::parse(QFutureInterface<void> &future,
QMap<QString, WorkingCopy> workingCopy,
QStringList files,
ModelManager *modelManager)
{
Core::MimeDatabase *db = Core::ICore::instance()->mimeDatabase();
Core::MimeType jsSourceTy = db->findByType(QLatin1String("application/javascript"));
Core::MimeType qmlSourceTy = db->findByType(QLatin1String("application/x-qml"));
int progressRange = files.size();
future.setProgressRange(0, progressRange);
Snapshot snapshot = modelManager->_snapshot;
// paths we have scanned for files and added to the files list
QSet<QString> scannedPaths;
for (int i = 0; i < files.size(); ++i) {
future.setProgressValue(qreal(i) / files.size() * progressRange);
const QString fileName = files.at(i);
const QFileInfo fileInfo(fileName);
Core::MimeType fileMimeTy = db->findByFile(fileInfo);
bool isQmlFile = true;
if (matchesMimeType(fileMimeTy, jsSourceTy))
isQmlFile = false;
else if (! matchesMimeType(fileMimeTy, qmlSourceTy))
continue; // skip it. it's not a QML or a JS file.
QString contents;
int documentRevision = 0;
if (workingCopy.contains(fileName)) {
WorkingCopy wc = workingCopy.value(fileName);
contents = wc.contents;
documentRevision = wc.documentRevision;
} else {
QFile inFile(fileName);
if (inFile.open(QIODevice::ReadOnly)) {
QTextStream ins(&inFile);
contents = ins.readAll();
inFile.close();
}
}
Document::Ptr doc = Document::create(fileName);
doc->setDocumentRevision(documentRevision);
doc->setSource(contents);
doc->parse();
// get list of referenced files not yet in snapshot or in directories already scanned
QStringList importedFiles;
findNewImplicitImports(doc, snapshot, &importedFiles, &scannedPaths);
findNewFileImports(doc, snapshot, &importedFiles, &scannedPaths);
findNewLibraryImports(doc, snapshot, modelManager, &importedFiles, &scannedPaths);
// add new files to parse list
foreach (const QString &file, importedFiles) {
if (! files.contains(file))
files.append(file);
}
modelManager->emitDocumentUpdated(doc);
}
future.setProgressValue(progressRange);
}
// Check whether fileMimeType is the same or extends knownMimeType
bool ModelManager::matchesMimeType(const Core::MimeType &fileMimeType, const Core::MimeType &knownMimeType)
{
Core::MimeDatabase *db = Core::ICore::instance()->mimeDatabase();
const QStringList knownTypeNames = QStringList(knownMimeType.type()) + knownMimeType.aliases();
foreach (const QString knownTypeName, knownTypeNames)
if (fileMimeType.matchesType(knownTypeName))
return true;
// recursion to parent types of fileMimeType
foreach (const QString &parentMimeType, fileMimeType.subClassesOf()) {
if (matchesMimeType(db->findByType(parentMimeType), knownMimeType))
return true;
}
return false;
}
void ModelManager::setProjectImportPaths(const QStringList &importPaths)
{
m_projectImportPaths = importPaths;
// check if any file in the snapshot imports something new in the new paths
Snapshot snapshot = _snapshot;
QStringList importedFiles;
QSet<QString> scannedPaths;
foreach (const Document::Ptr &doc, snapshot)
findNewLibraryImports(doc, snapshot, this, &importedFiles, &scannedPaths);
updateSourceFiles(importedFiles);
}
QStringList ModelManager::importPaths() const
{
QStringList paths;
paths << m_projectImportPaths;
paths << m_defaultImportPaths;
return paths;
}
static QStringList environmentImportPaths()
{
QStringList paths;
QByteArray envImportPath = qgetenv("QML_IMPORT_PATH");
#if defined(Q_OS_WIN)
QLatin1Char pathSep(';');
#else
QLatin1Char pathSep(':');
#endif
foreach (const QString &path, QString::fromLatin1(envImportPath).split(pathSep, QString::SkipEmptyParts)) {
QString canonicalPath = QDir(path).canonicalPath();
if (!canonicalPath.isEmpty() && !paths.contains(canonicalPath))
paths.append(canonicalPath);
}
return paths;
}
<commit_msg>QmlJSEditor: When looking for qml libraries scan the current doc's path.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "qmljseditorconstants.h"
#include "qmljsmodelmanager.h"
#include "qmljseditor.h"
#include <coreplugin/icore.h>
#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/progressmanager/progressmanager.h>
#include <coreplugin/mimedatabase.h>
#include <qmljs/qmljsinterpreter.h>
#include <qmljs/qmljsbind.h>
#include <qmljs/parser/qmldirparser_p.h>
#include <texteditor/itexteditor.h>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QLibraryInfo>
#include <QtConcurrentRun>
#include <qtconcurrent/runextensions.h>
#include <QTextStream>
#include <QDebug>
using namespace QmlJS;
using namespace QmlJSEditor;
using namespace QmlJSEditor::Internal;
static QStringList environmentImportPaths();
ModelManager::ModelManager(QObject *parent):
ModelManagerInterface(parent),
m_core(Core::ICore::instance())
{
m_synchronizer.setCancelOnWait(true);
qRegisterMetaType<QmlJS::Document::Ptr>("QmlJS::Document::Ptr");
qRegisterMetaType<QmlJS::LibraryInfo>("QmlJS::LibraryInfo");
connect(this, SIGNAL(documentUpdated(QmlJS::Document::Ptr)),
this, SLOT(onDocumentUpdated(QmlJS::Document::Ptr)));
connect(this, SIGNAL(libraryInfoUpdated(QString,QmlJS::LibraryInfo)),
this, SLOT(onLibraryInfoUpdated(QString,QmlJS::LibraryInfo)));
loadQmlTypeDescriptions();
m_defaultImportPaths << environmentImportPaths();
m_defaultImportPaths << QLibraryInfo::location(QLibraryInfo::ImportsPath);
}
void ModelManager::loadQmlTypeDescriptions()
{
const QString resourcePath = Core::ICore::instance()->resourcePath();
const QDir typeFileDir(resourcePath + QLatin1String("/qml-type-descriptions"));
const QStringList xmlExtensions = QStringList() << QLatin1String("*.xml");
const QFileInfoList xmlFiles = typeFileDir.entryInfoList(xmlExtensions,
QDir::Files,
QDir::Name);
const QStringList errors = Interpreter::MetaTypeSystem::load(xmlFiles);
foreach (const QString &error, errors)
qWarning() << qPrintable(error);
}
Snapshot ModelManager::snapshot() const
{
QMutexLocker locker(&m_mutex);
return _snapshot;
}
void ModelManager::updateSourceFiles(const QStringList &files)
{
refreshSourceFiles(files);
}
QFuture<void> ModelManager::refreshSourceFiles(const QStringList &sourceFiles)
{
if (sourceFiles.isEmpty()) {
return QFuture<void>();
}
const QMap<QString, WorkingCopy> workingCopy = buildWorkingCopyList();
QFuture<void> result = QtConcurrent::run(&ModelManager::parse,
workingCopy, sourceFiles,
this);
if (m_synchronizer.futures().size() > 10) {
QList<QFuture<void> > futures = m_synchronizer.futures();
m_synchronizer.clearFutures();
foreach (QFuture<void> future, futures) {
if (! (future.isFinished() || future.isCanceled()))
m_synchronizer.addFuture(future);
}
}
m_synchronizer.addFuture(result);
if (sourceFiles.count() > 1) {
m_core->progressManager()->addTask(result, tr("Indexing"),
QmlJSEditor::Constants::TASK_INDEX);
}
return result;
}
QMap<QString, ModelManager::WorkingCopy> ModelManager::buildWorkingCopyList()
{
QMap<QString, WorkingCopy> workingCopy;
Core::EditorManager *editorManager = m_core->editorManager();
foreach (Core::IEditor *editor, editorManager->openedEditors()) {
const QString key = editor->file()->fileName();
if (TextEditor::ITextEditor *textEditor = qobject_cast<TextEditor::ITextEditor*>(editor)) {
if (QmlJSTextEditor *ed = qobject_cast<QmlJSTextEditor *>(textEditor->widget())) {
workingCopy[key].contents = ed->toPlainText();
workingCopy[key].documentRevision = ed->document()->revision();
}
}
}
return workingCopy;
}
void ModelManager::emitDocumentUpdated(Document::Ptr doc)
{ emit documentUpdated(doc); }
void ModelManager::onDocumentUpdated(Document::Ptr doc)
{
QMutexLocker locker(&m_mutex);
_snapshot.insert(doc);
}
void ModelManager::emitLibraryInfoUpdated(const QString &path, const LibraryInfo &info)
{ emit libraryInfoUpdated(path, info); }
void ModelManager::onLibraryInfoUpdated(const QString &path, const LibraryInfo &info)
{
QMutexLocker locker(&m_mutex);
_snapshot.insertLibraryInfo(path, info);
}
static QStringList qmlFilesInDirectory(const QString &path)
{
// ### It would suffice to build pattern once. This function needs to be thread-safe.
Core::MimeDatabase *db = Core::ICore::instance()->mimeDatabase();
Core::MimeType jsSourceTy = db->findByType(QmlJSEditor::Constants::JS_MIMETYPE);
Core::MimeType qmlSourceTy = db->findByType(QmlJSEditor::Constants::QML_MIMETYPE);
QStringList pattern;
foreach (const QRegExp &glob, jsSourceTy.globPatterns())
pattern << glob.pattern();
foreach (const QRegExp &glob, qmlSourceTy.globPatterns())
pattern << glob.pattern();
QStringList files;
const QDir dir(path);
foreach (const QFileInfo &fi, dir.entryInfoList(pattern, QDir::Files))
files += fi.absoluteFilePath();
return files;
}
static void findNewImplicitImports(const Document::Ptr &doc, const Snapshot &snapshot,
QStringList *importedFiles, QSet<QString> *scannedPaths)
{
// scan files that could be implicitly imported
// it's important we also do this for JS files, otherwise the isEmpty check will fail
if (snapshot.documentsInDirectory(doc->path()).isEmpty()) {
if (! scannedPaths->contains(doc->path())) {
*importedFiles += qmlFilesInDirectory(doc->path());
scannedPaths->insert(doc->path());
}
}
}
static void findNewFileImports(const Document::Ptr &doc, const Snapshot &snapshot,
QStringList *importedFiles, QSet<QString> *scannedPaths)
{
// scan files and directories that are explicitly imported
foreach (const QString &fileImport, doc->bind()->fileImports()) {
const QFileInfo importFileInfo(doc->path() + QLatin1Char('/') + fileImport);
const QString &importFilePath = importFileInfo.absoluteFilePath();
if (importFileInfo.isFile()) {
if (! snapshot.document(importFilePath))
*importedFiles += importFilePath;
} else if (importFileInfo.isDir()) {
if (snapshot.documentsInDirectory(importFilePath).isEmpty()) {
if (! scannedPaths->contains(importFilePath)) {
*importedFiles += qmlFilesInDirectory(importFilePath);
scannedPaths->insert(importFilePath);
}
}
}
}
}
static void findNewLibraryImports(const Document::Ptr &doc, const Snapshot &snapshot,
ModelManager *modelManager,
QStringList *importedFiles, QSet<QString> *scannedPaths)
{
// scan library imports
QStringList importPaths = modelManager->importPaths();
importPaths.prepend(doc->path());
foreach (const QString &libraryImport, doc->bind()->libraryImports()) {
foreach (const QString &importPath, importPaths) {
QDir dir(importPath);
dir.cd(libraryImport);
const QString targetPath = dir.absolutePath();
// if we know there is a library, done
if (snapshot.libraryInfo(targetPath).isValid())
break;
// if there is a qmldir file, we found a new library!
if (dir.exists("qmldir")) {
QFile qmldirFile(dir.filePath("qmldir"));
qmldirFile.open(QFile::ReadOnly);
QString qmldirData = QString::fromUtf8(qmldirFile.readAll());
QmlDirParser qmldirParser;
qmldirParser.setSource(qmldirData);
qmldirParser.parse();
modelManager->emitLibraryInfoUpdated(QFileInfo(qmldirFile).absolutePath(),
LibraryInfo(qmldirParser));
// scan the qml files in the library
foreach (const QmlDirParser::Component &component, qmldirParser.components()) {
if (! component.fileName.isEmpty()) {
QFileInfo componentFileInfo(dir.filePath(component.fileName));
const QString path = componentFileInfo.absolutePath();
if (! scannedPaths->contains(path)) {
*importedFiles += qmlFilesInDirectory(path);
scannedPaths->insert(path);
}
}
}
}
}
}
}
void ModelManager::parse(QFutureInterface<void> &future,
QMap<QString, WorkingCopy> workingCopy,
QStringList files,
ModelManager *modelManager)
{
Core::MimeDatabase *db = Core::ICore::instance()->mimeDatabase();
Core::MimeType jsSourceTy = db->findByType(QLatin1String("application/javascript"));
Core::MimeType qmlSourceTy = db->findByType(QLatin1String("application/x-qml"));
int progressRange = files.size();
future.setProgressRange(0, progressRange);
Snapshot snapshot = modelManager->_snapshot;
// paths we have scanned for files and added to the files list
QSet<QString> scannedPaths;
for (int i = 0; i < files.size(); ++i) {
future.setProgressValue(qreal(i) / files.size() * progressRange);
const QString fileName = files.at(i);
const QFileInfo fileInfo(fileName);
Core::MimeType fileMimeTy = db->findByFile(fileInfo);
bool isQmlFile = true;
if (matchesMimeType(fileMimeTy, jsSourceTy))
isQmlFile = false;
else if (! matchesMimeType(fileMimeTy, qmlSourceTy))
continue; // skip it. it's not a QML or a JS file.
QString contents;
int documentRevision = 0;
if (workingCopy.contains(fileName)) {
WorkingCopy wc = workingCopy.value(fileName);
contents = wc.contents;
documentRevision = wc.documentRevision;
} else {
QFile inFile(fileName);
if (inFile.open(QIODevice::ReadOnly)) {
QTextStream ins(&inFile);
contents = ins.readAll();
inFile.close();
}
}
Document::Ptr doc = Document::create(fileName);
doc->setDocumentRevision(documentRevision);
doc->setSource(contents);
doc->parse();
// get list of referenced files not yet in snapshot or in directories already scanned
QStringList importedFiles;
findNewImplicitImports(doc, snapshot, &importedFiles, &scannedPaths);
findNewFileImports(doc, snapshot, &importedFiles, &scannedPaths);
findNewLibraryImports(doc, snapshot, modelManager, &importedFiles, &scannedPaths);
// add new files to parse list
foreach (const QString &file, importedFiles) {
if (! files.contains(file))
files.append(file);
}
modelManager->emitDocumentUpdated(doc);
}
future.setProgressValue(progressRange);
}
// Check whether fileMimeType is the same or extends knownMimeType
bool ModelManager::matchesMimeType(const Core::MimeType &fileMimeType, const Core::MimeType &knownMimeType)
{
Core::MimeDatabase *db = Core::ICore::instance()->mimeDatabase();
const QStringList knownTypeNames = QStringList(knownMimeType.type()) + knownMimeType.aliases();
foreach (const QString knownTypeName, knownTypeNames)
if (fileMimeType.matchesType(knownTypeName))
return true;
// recursion to parent types of fileMimeType
foreach (const QString &parentMimeType, fileMimeType.subClassesOf()) {
if (matchesMimeType(db->findByType(parentMimeType), knownMimeType))
return true;
}
return false;
}
void ModelManager::setProjectImportPaths(const QStringList &importPaths)
{
m_projectImportPaths = importPaths;
// check if any file in the snapshot imports something new in the new paths
Snapshot snapshot = _snapshot;
QStringList importedFiles;
QSet<QString> scannedPaths;
foreach (const Document::Ptr &doc, snapshot)
findNewLibraryImports(doc, snapshot, this, &importedFiles, &scannedPaths);
updateSourceFiles(importedFiles);
}
QStringList ModelManager::importPaths() const
{
QStringList paths;
paths << m_projectImportPaths;
paths << m_defaultImportPaths;
return paths;
}
static QStringList environmentImportPaths()
{
QStringList paths;
QByteArray envImportPath = qgetenv("QML_IMPORT_PATH");
#if defined(Q_OS_WIN)
QLatin1Char pathSep(';');
#else
QLatin1Char pathSep(':');
#endif
foreach (const QString &path, QString::fromLatin1(envImportPath).split(pathSep, QString::SkipEmptyParts)) {
QString canonicalPath = QDir(path).canonicalPath();
if (!canonicalPath.isEmpty() && !paths.contains(canonicalPath))
paths.append(canonicalPath);
}
return paths;
}
<|endoftext|>
|
<commit_before>/**
* @file
*
* @brief Source for simplespeclang plugin
*
* @copyright BSD License (see doc/COPYING or http://www.libelektra.org)
*
*/
#include "simplespeclang.hpp"
using namespace ckdb;
#include <kdbease.h>
#include <kdberrors.h>
#include <kdbmeta.h>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <sstream>
namespace
{
std::string getConfigEnum (Plugin * handle)
{
Key * k = ksLookupByName (elektraPluginGetConfig (handle), "/keyword/enum", 0);
if (!k) return "enum";
return keyString (k);
}
std::string getConfigAssign (Plugin * handle)
{
Key * k = ksLookupByName (elektraPluginGetConfig (handle), "/keyword/assign", 0);
if (!k) return "=";
return keyString (k);
}
int serialise (std::ostream & os, ckdb::Key * parentKey, ckdb::KeySet * ks, Plugin * handle)
{
ckdb::Key * cur;
ksRewind (ks);
while ((cur = ksNext (ks)) != nullptr)
{
const ckdb::Key * meta = ckdb::keyGetMeta (cur, "check/enum");
if (!meta) continue;
os << getConfigEnum (handle) << " ";
os << elektraKeyGetRelativeName (cur, parentKey) << " ";
os << getConfigAssign (handle);
while ((meta = keyNextMeta (cur)))
{
os << " " << ckdb::keyString (meta);
}
os << "\n";
}
return 1;
}
int unserialise (std::istream & is, ckdb::Key * errorKey, ckdb::KeySet * ks, Plugin * handle)
{
Key * cur = nullptr;
Key * parent = keyNew (keyName (errorKey), KEY_END);
std::string line;
while (std::getline (is, line))
{
std::string read;
std::stringstream ss (line);
ss >> read;
if (read == "mountpoint")
{
ss >> read;
keySetMeta (parent, "mountpoint", read.c_str ());
continue;
}
else if (read == "plugins")
{
std::string plugins;
while (ss >> read)
{
// replace (read.begin(), read.end(), '_', ' ');
plugins += read + " ";
}
keySetMeta (parent, "infos/plugins", plugins.c_str ());
continue;
}
else if (read != getConfigEnum (handle))
{
ELEKTRA_LOG ("not an enum %s", read.c_str ());
continue;
}
std::string name;
ss >> name;
ELEKTRA_LOG ("key name for enum is %s", name.c_str ());
cur = keyNew (keyName (errorKey), KEY_END);
keyAddName (cur, name.c_str ());
ss >> read;
if (read != getConfigAssign (handle))
{
ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_PARSE, errorKey, "Expected assignment (%s), but got (%s)",
getConfigAssign (handle).c_str (), read.c_str ());
continue;
}
int added = 0;
while (ss >> read)
{
++added;
elektraMetaArrayAdd (cur, "check/enum", read.c_str ());
}
if (added)
{
ELEKTRA_LOG ("%s is enum with %d entries (last char is %c)", name.c_str (), added, name.back ());
keySetMeta (cur, "check/enum", "#");
if (name.back () == '*')
{
keySetMeta (cur, "check/enum/multi", " ");
}
}
keySetMeta (cur, "require", "yes");
// keySetMeta (cur, "required", "yes"); // seems to have wrong semantics
keySetMeta (cur, "conflict/get/missing", "ERROR");
keySetMeta (cur, "conflict/set/missing", "ERROR");
keySetMeta (cur, "mandatory", "yes"); // TODO bug: required key removed by spec?
ckdb::ksAppendKey (ks, cur);
}
ckdb::ksAppendKey (ks, parent);
return 1;
}
}
extern "C" {
int elektraSimplespeclangGet (Plugin * handle, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
if (!elektraStrCmp (keyName (parentKey), "system/elektra/modules/simplespeclang"))
{
KeySet * contract =
ksNew (30, keyNew ("system/elektra/modules/simplespeclang", KEY_VALUE,
"simplespeclang plugin waits for your orders", KEY_END),
keyNew ("system/elektra/modules/simplespeclang/exports", KEY_END),
keyNew ("system/elektra/modules/simplespeclang/exports/get", KEY_FUNC, elektraSimplespeclangGet, KEY_END),
keyNew ("system/elektra/modules/simplespeclang/exports/set", KEY_FUNC, elektraSimplespeclangSet, KEY_END),
keyNew ("system/elektra/modules/simplespeclang/exports/checkconf", KEY_FUNC,
elektraSimplespeclangCheckConfig, KEY_END),
#include ELEKTRA_README (simplespeclang)
keyNew ("system/elektra/modules/simplespeclang/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END);
ksAppend (returned, contract);
ksDel (contract);
return 1; // success
}
std::ifstream ofs (keyString (parentKey), std::ios::binary);
if (!ofs.is_open ())
{
ELEKTRA_SET_ERROR_GET (parentKey);
return -1;
}
return unserialise (ofs, parentKey, returned, handle);
}
int elektraSimplespeclangSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
// ELEKTRA_LOG (ELEKTRA_LOG_MODULE_DUMP, "opening file %s", keyString (parentKey));
std::ofstream ofs (keyString (parentKey), std::ios::binary);
if (!ofs.is_open ())
{
ELEKTRA_SET_ERROR_SET (parentKey);
return -1;
}
return serialise (ofs, parentKey, returned, handle);
}
int elektraSimplespeclangCheckConfig (Key * errorKey ELEKTRA_UNUSED, KeySet * conf ELEKTRA_UNUSED)
{
return 0;
}
Plugin * ELEKTRA_PLUGIN_EXPORT (simplespeclang)
{
// clang-format off
return elektraPluginExport ("simplespeclang",
ELEKTRA_PLUGIN_GET, &elektraSimplespeclangGet,
ELEKTRA_PLUGIN_SET, &elektraSimplespeclangSet,
ELEKTRA_PLUGIN_END);
}
}
<commit_msg>simplespeclang: only write out enum meta+log<commit_after>/**
* @file
*
* @brief Source for simplespeclang plugin
*
* @copyright BSD License (see doc/COPYING or http://www.libelektra.org)
*
*/
#include "simplespeclang.hpp"
using namespace ckdb;
#include <kdbease.h>
#include <kdberrors.h>
#include <kdbmeta.h>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <sstream>
namespace
{
std::string getConfigEnum (Plugin * handle)
{
Key * k = ksLookupByName (elektraPluginGetConfig (handle), "/keyword/enum", 0);
if (!k) return "enum";
return keyString (k);
}
std::string getConfigAssign (Plugin * handle)
{
Key * k = ksLookupByName (elektraPluginGetConfig (handle), "/keyword/assign", 0);
if (!k) return "=";
return keyString (k);
}
bool startsWith (std::string const & str, std::string const & start)
{
return std::equal (start.begin (), start.end (), str.begin ());
}
int serialise (std::ostream & os, ckdb::Key * parentKey, ckdb::KeySet * ks, Plugin * handle)
{
ckdb::Key * cur;
ksRewind (ks);
while ((cur = ksNext (ks)) != nullptr)
{
const ckdb::Key * meta = ckdb::keyGetMeta (cur, "check/enum");
if (!meta) continue;
os << getConfigEnum (handle) << " ";
os << elektraKeyGetRelativeName (cur, parentKey) << " ";
os << getConfigAssign (handle);
while ((meta = keyNextMeta (cur)))
{
if (startsWith (keyName (meta), "check/enum/#"))
{
os << " " << ckdb::keyString (meta);
}
}
os << "\n";
}
return 1;
}
int unserialise (std::istream & is, ckdb::Key * errorKey, ckdb::KeySet * ks, Plugin * handle)
{
Key * cur = nullptr;
Key * parent = keyNew (keyName (errorKey), KEY_END);
std::string line;
while (std::getline (is, line))
{
std::string read;
std::stringstream ss (line);
ss >> read;
if (read == "mountpoint")
{
ss >> read;
keySetMeta (parent, "mountpoint", read.c_str ());
continue;
}
else if (read == "plugins")
{
std::string plugins;
while (ss >> read)
{
// replace (read.begin(), read.end(), '_', ' ');
plugins += read + " ";
}
keySetMeta (parent, "infos/plugins", plugins.c_str ());
continue;
}
else if (read != getConfigEnum (handle))
{
ELEKTRA_LOG ("not an enum %s", read.c_str ());
continue;
}
std::string name;
ss >> name;
ELEKTRA_LOG ("key name for enum is %s", name.c_str ());
cur = keyNew (keyName (errorKey), KEY_END);
keyAddName (cur, name.c_str ());
ss >> read;
if (read != getConfigAssign (handle))
{
ELEKTRA_SET_ERRORF (ELEKTRA_ERROR_PARSE, errorKey, "Expected assignment (%s), but got (%s)",
getConfigAssign (handle).c_str (), read.c_str ());
continue;
}
int added = 0;
while (ss >> read)
{
++added;
elektraMetaArrayAdd (cur, "check/enum", read.c_str ());
}
if (added)
{
ELEKTRA_LOG ("%s is enum with %d entries (last char is %c)", name.c_str (), added, name.back ());
keySetMeta (cur, "check/enum", "#");
if (name.back () == '*')
{
keySetMeta (cur, "check/enum/multi", " ");
}
}
keySetMeta (cur, "require", "1");
keySetMeta (cur, "conflict/set/missing", "ERROR");
keySetMeta (cur, "mandatory", "1");
ckdb::ksAppendKey (ks, cur);
}
ckdb::ksAppendKey (ks, parent);
return 1;
}
}
extern "C" {
int elektraSimplespeclangGet (Plugin * handle, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
if (!elektraStrCmp (keyName (parentKey), "system/elektra/modules/simplespeclang"))
{
KeySet * contract =
ksNew (30, keyNew ("system/elektra/modules/simplespeclang", KEY_VALUE,
"simplespeclang plugin waits for your orders", KEY_END),
keyNew ("system/elektra/modules/simplespeclang/exports", KEY_END),
keyNew ("system/elektra/modules/simplespeclang/exports/get", KEY_FUNC, elektraSimplespeclangGet, KEY_END),
keyNew ("system/elektra/modules/simplespeclang/exports/set", KEY_FUNC, elektraSimplespeclangSet, KEY_END),
keyNew ("system/elektra/modules/simplespeclang/exports/checkconf", KEY_FUNC,
elektraSimplespeclangCheckConfig, KEY_END),
#include ELEKTRA_README (simplespeclang)
keyNew ("system/elektra/modules/simplespeclang/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END);
ksAppend (returned, contract);
ksDel (contract);
return 1; // success
}
std::ifstream ofs (keyString (parentKey), std::ios::binary);
if (!ofs.is_open ())
{
ELEKTRA_SET_ERROR_GET (parentKey);
return -1;
}
return unserialise (ofs, parentKey, returned, handle);
}
int elektraSimplespeclangSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned ELEKTRA_UNUSED, Key * parentKey ELEKTRA_UNUSED)
{
ELEKTRA_LOG ("opening file %s", keyString (parentKey));
std::ofstream ofs (keyString (parentKey), std::ios::binary);
if (!ofs.is_open ())
{
ELEKTRA_SET_ERROR_SET (parentKey);
return -1;
}
return serialise (ofs, parentKey, returned, handle);
}
int elektraSimplespeclangCheckConfig (Key * errorKey ELEKTRA_UNUSED, KeySet * conf ELEKTRA_UNUSED)
{
return 0;
}
Plugin * ELEKTRA_PLUGIN_EXPORT (simplespeclang)
{
// clang-format off
return elektraPluginExport ("simplespeclang",
ELEKTRA_PLUGIN_GET, &elektraSimplespeclangGet,
ELEKTRA_PLUGIN_SET, &elektraSimplespeclangSet,
ELEKTRA_PLUGIN_END);
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/dock_info.h"
#include "base/basictypes.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/tabs/tab.h"
namespace {
// BaseWindowFinder -----------------------------------------------------------
// Base class used to locate a window. This is intended to be used with the
// various win32 functions that iterate over windows.
//
// A subclass need only override ShouldStopIterating to determine when
// iteration should stop.
class BaseWindowFinder {
public:
// Creates a BaseWindowFinder with the specified set of HWNDs to ignore.
explicit BaseWindowFinder(const std::set<HWND>& ignore) : ignore_(ignore) {}
virtual ~BaseWindowFinder() {}
protected:
// Returns true if iteration should stop, false if iteration should continue.
virtual bool ShouldStopIterating(HWND window) = 0;
static BOOL CALLBACK WindowCallbackProc(HWND hwnd, LPARAM lParam) {
BaseWindowFinder* finder = reinterpret_cast<BaseWindowFinder*>(lParam);
if (finder->ignore_.find(hwnd) != finder->ignore_.end())
return TRUE;
return finder->ShouldStopIterating(hwnd) ? FALSE : TRUE;
}
private:
const std::set<HWND>& ignore_;
DISALLOW_COPY_AND_ASSIGN(BaseWindowFinder);
};
// TopMostFinder --------------------------------------------------------------
// Helper class to determine if a particular point of a window is not obscured
// by another window.
class TopMostFinder : public BaseWindowFinder {
public:
// Returns true if |window| is the topmost window at the location
// |screen_loc|, not including the windows in |ignore|.
static bool IsTopMostWindowAtPoint(HWND window,
const gfx::Point& screen_loc,
const std::set<HWND>& ignore) {
TopMostFinder finder(window, screen_loc, ignore);
return finder.is_top_most_;
}
virtual bool ShouldStopIterating(HWND hwnd) {
if (hwnd == target_) {
// Window is topmost, stop iterating.
is_top_most_ = true;
return true;
}
if (!IsWindowVisible(hwnd)) {
// The window isn't visible, keep iterating.
return false;
}
RECT r;
if (!GetWindowRect(hwnd, &r) || !PtInRect(&r, screen_loc_.ToPOINT())) {
// The window doesn't contain the point, keep iterating.
return false;
}
// hwnd is at the point. Make sure the point is within the windows region.
if (GetWindowRgn(hwnd, tmp_region_.Get()) == ERROR) {
// There's no region on the window and the window contains the point. Stop
// iterating.
return true;
}
// The region is relative to the window's rect.
BOOL is_point_in_region = PtInRegion(tmp_region_.Get(),
screen_loc_.x() - r.left, screen_loc_.y() - r.top);
tmp_region_ = CreateRectRgn(0, 0, 0, 0);
// Stop iterating if the region contains the point.
return !!is_point_in_region;
}
private:
TopMostFinder(HWND window,
const gfx::Point& screen_loc,
const std::set<HWND>& ignore)
: BaseWindowFinder(ignore),
target_(window),
screen_loc_(screen_loc),
is_top_most_(false),
tmp_region_(CreateRectRgn(0, 0, 0, 0)) {
EnumWindows(WindowCallbackProc, reinterpret_cast<LPARAM>(this));
}
// The window we're looking for.
HWND target_;
// Location of window to find.
gfx::Point screen_loc_;
// Is target_ the top most window? This is initially false but set to true
// in ShouldStopIterating if target_ is passed in.
bool is_top_most_;
ScopedRegion tmp_region_;
DISALLOW_COPY_AND_ASSIGN(TopMostFinder);
};
// WindowFinder ---------------------------------------------------------------
// Helper class to determine if a particular point contains a window from our
// process.
class LocalProcessWindowFinder : public BaseWindowFinder {
public:
// Returns the hwnd from our process at screen_loc that is not obscured by
// another window. Returns NULL otherwise.
static HWND GetProcessWindowAtPoint(const gfx::Point& screen_loc,
const std::set<HWND>& ignore) {
LocalProcessWindowFinder finder(screen_loc, ignore);
if (finder.result_ &&
TopMostFinder::IsTopMostWindowAtPoint(finder.result_, screen_loc,
ignore)) {
return finder.result_;
}
return NULL;
}
protected:
virtual bool ShouldStopIterating(HWND hwnd) {
RECT r;
if (IsWindowVisible(hwnd) && GetWindowRect(hwnd, &r) &&
PtInRect(&r, screen_loc_.ToPOINT())) {
result_ = hwnd;
return true;
}
return false;
}
private:
LocalProcessWindowFinder(const gfx::Point& screen_loc,
const std::set<HWND>& ignore)
: BaseWindowFinder(ignore),
screen_loc_(screen_loc),
result_(NULL) {
EnumThreadWindows(GetCurrentThreadId(), WindowCallbackProc,
reinterpret_cast<LPARAM>(this));
}
// Position of the mouse.
gfx::Point screen_loc_;
// The resulting window. This is initially null but set to true in
// ShouldStopIterating if an appropriate window is found.
HWND result_;
DISALLOW_COPY_AND_ASSIGN(LocalProcessWindowFinder);
};
// DockToWindowFinder ---------------------------------------------------------
// Helper class for creating a DockInfo from a specified point.
class DockToWindowFinder : public BaseWindowFinder {
public:
// Returns the DockInfo for the specified point. If there is no docking
// position for the specified point the returned DockInfo has a type of NONE.
static DockInfo GetDockInfoAtPoint(const gfx::Point& screen_loc,
const std::set<HWND>& ignore) {
DockToWindowFinder finder(screen_loc, ignore);
if (!finder.result_.window() ||
!TopMostFinder::IsTopMostWindowAtPoint(finder.result_.window(),
finder.result_.hot_spot(),
ignore)) {
finder.result_.set_type(DockInfo::NONE);
}
return finder.result_;
}
protected:
virtual bool ShouldStopIterating(HWND hwnd) {
BrowserView* window = BrowserView::GetBrowserViewForNativeWindow(hwnd);
RECT bounds;
if (!window || !IsWindowVisible(hwnd) ||
!GetWindowRect(hwnd, &bounds)) {
return false;
}
// Check the three corners we allow docking to. We don't currently allow
// docking to top of window as it conflicts with docking to the tab strip.
if (CheckPoint(hwnd, bounds.left, (bounds.top + bounds.bottom) / 2,
DockInfo::LEFT_OF_WINDOW) ||
CheckPoint(hwnd, bounds.right - 1, (bounds.top + bounds.bottom) / 2,
DockInfo::RIGHT_OF_WINDOW) ||
CheckPoint(hwnd, (bounds.left + bounds.right) / 2, bounds.bottom - 1,
DockInfo::BOTTOM_OF_WINDOW)) {
return true;
}
return false;
}
private:
DockToWindowFinder(const gfx::Point& screen_loc,
const std::set<HWND>& ignore)
: BaseWindowFinder(ignore),
screen_loc_(screen_loc) {
HMONITOR monitor = MonitorFromPoint(screen_loc.ToPOINT(),
MONITOR_DEFAULTTONULL);
MONITORINFO monitor_info = {0};
monitor_info.cbSize = sizeof(MONITORINFO);
if (monitor && GetMonitorInfo(monitor, &monitor_info)) {
result_.set_monitor_bounds(gfx::Rect(monitor_info.rcWork));
EnumThreadWindows(GetCurrentThreadId(), WindowCallbackProc,
reinterpret_cast<LPARAM>(this));
}
}
bool CheckPoint(HWND hwnd, int x, int y, DockInfo::Type type) {
bool in_enable_area;
if (DockInfo::IsCloseToPoint(screen_loc_, x, y, &in_enable_area)) {
result_.set_in_enable_area(in_enable_area);
result_.set_window(hwnd);
result_.set_type(type);
result_.set_hot_spot(gfx::Point(x, y));
// Only show the hotspot if the monitor contains the bounds of the popup
// window. Otherwise we end with a weird situation where the popup window
// isn't completely visible.
return result_.monitor_bounds().Contains(result_.GetPopupRect());
}
return false;
}
// The location to look for.
gfx::Point screen_loc_;
// The resulting DockInfo.
DockInfo result_;
DISALLOW_COPY_AND_ASSIGN(DockToWindowFinder);
};
} // namespace
// DockInfo -------------------------------------------------------------------
// static
DockInfo DockInfo::GetDockInfoAtPoint(const gfx::Point& screen_point,
const std::set<HWND>& ignore) {
if (factory_)
return factory_->GetDockInfoAtPoint(screen_point, ignore);
// Try docking to a window first.
DockInfo info = DockToWindowFinder::GetDockInfoAtPoint(screen_point, ignore);
if (info.type() != DockInfo::NONE)
return info;
// No window relative positions. Try monitor relative positions.
const gfx::Rect& m_bounds = info.monitor_bounds();
int mid_x = m_bounds.x() + m_bounds.width() / 2;
int mid_y = m_bounds.y() + m_bounds.height() / 2;
bool result =
info.CheckMonitorPoint(screen_point, mid_x, m_bounds.y(),
DockInfo::MAXIMIZE) ||
info.CheckMonitorPoint(screen_point, mid_x, m_bounds.bottom(),
DockInfo::BOTTOM_HALF) ||
info.CheckMonitorPoint(screen_point, m_bounds.x(), mid_y,
DockInfo::LEFT_HALF) ||
info.CheckMonitorPoint(screen_point, m_bounds.right(), mid_y,
DockInfo::RIGHT_HALF);
return info;
}
HWND DockInfo::GetLocalProcessWindowAtPoint(const gfx::Point& screen_point,
const std::set<HWND>& ignore) {
if (factory_)
return factory_->GetLocalProcessWindowAtPoint(screen_point, ignore);
return
LocalProcessWindowFinder::GetProcessWindowAtPoint(screen_point, ignore);
}
bool DockInfo::GetWindowBounds(gfx::Rect* bounds) const {
RECT window_rect;
if (!window() || !GetWindowRect(window(), &window_rect))
return false;
*bounds = gfx::Rect(window_rect);
return true;
}
void DockInfo::SizeOtherWindowTo(const gfx::Rect& bounds) const {
if (IsZoomed(window())) {
// We're docking relative to another window, we need to make sure the
// window we're docking to isn't maximized.
ShowWindow(window(), SW_RESTORE | SW_SHOWNA);
}
SetWindowPos(window(), HWND_TOP, bounds.x(), bounds.y(), bounds.width(),
bounds.height(), SWP_NOACTIVATE | SWP_NOOWNERZORDER);
}
<commit_msg>Changes tab dragging code to ignore WS_EX_TRANSPARENT and WS_EX_LAYERED windows. Here's the comment I'm adding as to why:<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/dock_info.h"
#include "base/basictypes.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_list.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/tabs/tab.h"
namespace {
// BaseWindowFinder -----------------------------------------------------------
// Base class used to locate a window. This is intended to be used with the
// various win32 functions that iterate over windows.
//
// A subclass need only override ShouldStopIterating to determine when
// iteration should stop.
class BaseWindowFinder {
public:
// Creates a BaseWindowFinder with the specified set of HWNDs to ignore.
explicit BaseWindowFinder(const std::set<HWND>& ignore) : ignore_(ignore) {}
virtual ~BaseWindowFinder() {}
protected:
// Returns true if iteration should stop, false if iteration should continue.
virtual bool ShouldStopIterating(HWND window) = 0;
static BOOL CALLBACK WindowCallbackProc(HWND hwnd, LPARAM lParam) {
BaseWindowFinder* finder = reinterpret_cast<BaseWindowFinder*>(lParam);
if (finder->ignore_.find(hwnd) != finder->ignore_.end())
return TRUE;
return finder->ShouldStopIterating(hwnd) ? FALSE : TRUE;
}
private:
const std::set<HWND>& ignore_;
DISALLOW_COPY_AND_ASSIGN(BaseWindowFinder);
};
// TopMostFinder --------------------------------------------------------------
// Helper class to determine if a particular point of a window is not obscured
// by another window.
class TopMostFinder : public BaseWindowFinder {
public:
// Returns true if |window| is the topmost window at the location
// |screen_loc|, not including the windows in |ignore|.
static bool IsTopMostWindowAtPoint(HWND window,
const gfx::Point& screen_loc,
const std::set<HWND>& ignore) {
TopMostFinder finder(window, screen_loc, ignore);
return finder.is_top_most_;
}
virtual bool ShouldStopIterating(HWND hwnd) {
if (hwnd == target_) {
// Window is topmost, stop iterating.
is_top_most_ = true;
return true;
}
if (!IsWindowVisible(hwnd)) {
// The window isn't visible, keep iterating.
return false;
}
RECT r;
if (!GetWindowRect(hwnd, &r) || !PtInRect(&r, screen_loc_.ToPOINT())) {
// The window doesn't contain the point, keep iterating.
return false;
}
LONG ex_styles = GetWindowLong(hwnd, GWL_EXSTYLE);
if (ex_styles & WS_EX_TRANSPARENT || ex_styles & WS_EX_LAYERED) {
// Mouse events fall through WS_EX_TRANSPARENT windows, so we ignore them.
//
// WS_EX_LAYERED is trickier. Apps like Switcher create a totally
// transparent WS_EX_LAYERED window that is always on top. If we don't
// ignore WS_EX_LAYERED windows and there are totally transparent
// WS_EX_LAYERED windows then there are effectively holes on the screen
// that the user can't reattach tabs to. So we ignore them. This is a bit
// problematic in so far as WS_EX_LAYERED windows need not be totally
// transparent in which case we treat chrome windows as not being obscured
// when they really are, but this is better than not being able to
// reattach tabs.
return false;
}
// hwnd is at the point. Make sure the point is within the windows region.
if (GetWindowRgn(hwnd, tmp_region_.Get()) == ERROR) {
// There's no region on the window and the window contains the point. Stop
// iterating.
return true;
}
// The region is relative to the window's rect.
BOOL is_point_in_region = PtInRegion(tmp_region_.Get(),
screen_loc_.x() - r.left, screen_loc_.y() - r.top);
tmp_region_ = CreateRectRgn(0, 0, 0, 0);
// Stop iterating if the region contains the point.
return !!is_point_in_region;
}
private:
TopMostFinder(HWND window,
const gfx::Point& screen_loc,
const std::set<HWND>& ignore)
: BaseWindowFinder(ignore),
target_(window),
screen_loc_(screen_loc),
is_top_most_(false),
tmp_region_(CreateRectRgn(0, 0, 0, 0)) {
EnumWindows(WindowCallbackProc, reinterpret_cast<LPARAM>(this));
}
// The window we're looking for.
HWND target_;
// Location of window to find.
gfx::Point screen_loc_;
// Is target_ the top most window? This is initially false but set to true
// in ShouldStopIterating if target_ is passed in.
bool is_top_most_;
ScopedRegion tmp_region_;
DISALLOW_COPY_AND_ASSIGN(TopMostFinder);
};
// WindowFinder ---------------------------------------------------------------
// Helper class to determine if a particular point contains a window from our
// process.
class LocalProcessWindowFinder : public BaseWindowFinder {
public:
// Returns the hwnd from our process at screen_loc that is not obscured by
// another window. Returns NULL otherwise.
static HWND GetProcessWindowAtPoint(const gfx::Point& screen_loc,
const std::set<HWND>& ignore) {
LocalProcessWindowFinder finder(screen_loc, ignore);
if (finder.result_ &&
TopMostFinder::IsTopMostWindowAtPoint(finder.result_, screen_loc,
ignore)) {
return finder.result_;
}
return NULL;
}
protected:
virtual bool ShouldStopIterating(HWND hwnd) {
RECT r;
if (IsWindowVisible(hwnd) && GetWindowRect(hwnd, &r) &&
PtInRect(&r, screen_loc_.ToPOINT())) {
result_ = hwnd;
return true;
}
return false;
}
private:
LocalProcessWindowFinder(const gfx::Point& screen_loc,
const std::set<HWND>& ignore)
: BaseWindowFinder(ignore),
screen_loc_(screen_loc),
result_(NULL) {
EnumThreadWindows(GetCurrentThreadId(), WindowCallbackProc,
reinterpret_cast<LPARAM>(this));
}
// Position of the mouse.
gfx::Point screen_loc_;
// The resulting window. This is initially null but set to true in
// ShouldStopIterating if an appropriate window is found.
HWND result_;
DISALLOW_COPY_AND_ASSIGN(LocalProcessWindowFinder);
};
// DockToWindowFinder ---------------------------------------------------------
// Helper class for creating a DockInfo from a specified point.
class DockToWindowFinder : public BaseWindowFinder {
public:
// Returns the DockInfo for the specified point. If there is no docking
// position for the specified point the returned DockInfo has a type of NONE.
static DockInfo GetDockInfoAtPoint(const gfx::Point& screen_loc,
const std::set<HWND>& ignore) {
DockToWindowFinder finder(screen_loc, ignore);
if (!finder.result_.window() ||
!TopMostFinder::IsTopMostWindowAtPoint(finder.result_.window(),
finder.result_.hot_spot(),
ignore)) {
finder.result_.set_type(DockInfo::NONE);
}
return finder.result_;
}
protected:
virtual bool ShouldStopIterating(HWND hwnd) {
BrowserView* window = BrowserView::GetBrowserViewForNativeWindow(hwnd);
RECT bounds;
if (!window || !IsWindowVisible(hwnd) ||
!GetWindowRect(hwnd, &bounds)) {
return false;
}
// Check the three corners we allow docking to. We don't currently allow
// docking to top of window as it conflicts with docking to the tab strip.
if (CheckPoint(hwnd, bounds.left, (bounds.top + bounds.bottom) / 2,
DockInfo::LEFT_OF_WINDOW) ||
CheckPoint(hwnd, bounds.right - 1, (bounds.top + bounds.bottom) / 2,
DockInfo::RIGHT_OF_WINDOW) ||
CheckPoint(hwnd, (bounds.left + bounds.right) / 2, bounds.bottom - 1,
DockInfo::BOTTOM_OF_WINDOW)) {
return true;
}
return false;
}
private:
DockToWindowFinder(const gfx::Point& screen_loc,
const std::set<HWND>& ignore)
: BaseWindowFinder(ignore),
screen_loc_(screen_loc) {
HMONITOR monitor = MonitorFromPoint(screen_loc.ToPOINT(),
MONITOR_DEFAULTTONULL);
MONITORINFO monitor_info = {0};
monitor_info.cbSize = sizeof(MONITORINFO);
if (monitor && GetMonitorInfo(monitor, &monitor_info)) {
result_.set_monitor_bounds(gfx::Rect(monitor_info.rcWork));
EnumThreadWindows(GetCurrentThreadId(), WindowCallbackProc,
reinterpret_cast<LPARAM>(this));
}
}
bool CheckPoint(HWND hwnd, int x, int y, DockInfo::Type type) {
bool in_enable_area;
if (DockInfo::IsCloseToPoint(screen_loc_, x, y, &in_enable_area)) {
result_.set_in_enable_area(in_enable_area);
result_.set_window(hwnd);
result_.set_type(type);
result_.set_hot_spot(gfx::Point(x, y));
// Only show the hotspot if the monitor contains the bounds of the popup
// window. Otherwise we end with a weird situation where the popup window
// isn't completely visible.
return result_.monitor_bounds().Contains(result_.GetPopupRect());
}
return false;
}
// The location to look for.
gfx::Point screen_loc_;
// The resulting DockInfo.
DockInfo result_;
DISALLOW_COPY_AND_ASSIGN(DockToWindowFinder);
};
} // namespace
// DockInfo -------------------------------------------------------------------
// static
DockInfo DockInfo::GetDockInfoAtPoint(const gfx::Point& screen_point,
const std::set<HWND>& ignore) {
if (factory_)
return factory_->GetDockInfoAtPoint(screen_point, ignore);
// Try docking to a window first.
DockInfo info = DockToWindowFinder::GetDockInfoAtPoint(screen_point, ignore);
if (info.type() != DockInfo::NONE)
return info;
// No window relative positions. Try monitor relative positions.
const gfx::Rect& m_bounds = info.monitor_bounds();
int mid_x = m_bounds.x() + m_bounds.width() / 2;
int mid_y = m_bounds.y() + m_bounds.height() / 2;
bool result =
info.CheckMonitorPoint(screen_point, mid_x, m_bounds.y(),
DockInfo::MAXIMIZE) ||
info.CheckMonitorPoint(screen_point, mid_x, m_bounds.bottom(),
DockInfo::BOTTOM_HALF) ||
info.CheckMonitorPoint(screen_point, m_bounds.x(), mid_y,
DockInfo::LEFT_HALF) ||
info.CheckMonitorPoint(screen_point, m_bounds.right(), mid_y,
DockInfo::RIGHT_HALF);
return info;
}
HWND DockInfo::GetLocalProcessWindowAtPoint(const gfx::Point& screen_point,
const std::set<HWND>& ignore) {
if (factory_)
return factory_->GetLocalProcessWindowAtPoint(screen_point, ignore);
return
LocalProcessWindowFinder::GetProcessWindowAtPoint(screen_point, ignore);
}
bool DockInfo::GetWindowBounds(gfx::Rect* bounds) const {
RECT window_rect;
if (!window() || !GetWindowRect(window(), &window_rect))
return false;
*bounds = gfx::Rect(window_rect);
return true;
}
void DockInfo::SizeOtherWindowTo(const gfx::Rect& bounds) const {
if (IsZoomed(window())) {
// We're docking relative to another window, we need to make sure the
// window we're docking to isn't maximized.
ShowWindow(window(), SW_RESTORE | SW_SHOWNA);
}
SetWindowPos(window(), HWND_TOP, bounds.x(), bounds.y(), bounds.width(),
bounds.height(), SWP_NOACTIVATE | SWP_NOOWNERZORDER);
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/gpu_blacklist.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "base/stringprintf.h"
#include "base/sys_info.h"
#include "base/values.h"
#include "base/version.h"
#include "chrome/common/gpu_info.h"
GpuBlacklist::VersionInfo::VersionInfo(const std::string& version_op,
const std::string& version_string,
const std::string& version_string2) {
op_ = StringToOp(version_op);
if (op_ == kUnknown || op_ == kAny)
return;
version_.reset(Version::GetVersionFromString(version_string));
if (version_.get() == NULL) {
op_ = kUnknown;
return;
}
if (op_ == kBetween) {
version2_.reset(Version::GetVersionFromString(version_string2));
if (version2_.get() == NULL)
op_ = kUnknown;
}
}
GpuBlacklist::VersionInfo::~VersionInfo() {
}
bool GpuBlacklist::VersionInfo::Contains(const Version& version) const {
if (op_ == kUnknown)
return false;
if (op_ == kAny)
return true;
if (op_ == kEQ) {
// Handles cases where 10.6 is considered as containing 10.6.*.
const std::vector<uint16>& components_reference = version_->components();
const std::vector<uint16>& components = version.components();
for (size_t i = 0; i < components_reference.size(); ++i) {
if (i >= components.size() && components_reference[i] != 0)
return false;
if (components[i] != components_reference[i])
return false;
}
return true;
}
int relation = version.CompareTo(*version_);
if (op_ == kEQ)
return (relation == 0);
else if (op_ == kLT)
return (relation < 0);
else if (op_ == kLE)
return (relation <= 0);
else if (op_ == kGT)
return (relation > 0);
else if (op_ == kGE)
return (relation >= 0);
// op_ == kBetween
if (relation < 0)
return false;
return version.CompareTo(*version2_) <= 0;
}
bool GpuBlacklist::VersionInfo::IsValid() const {
return op_ != kUnknown;
}
GpuBlacklist::VersionInfo::Op GpuBlacklist::VersionInfo::StringToOp(
const std::string& version_op) {
if (version_op == "=")
return kEQ;
else if (version_op == "<")
return kLT;
else if (version_op == "<=")
return kLE;
else if (version_op == ">")
return kGT;
else if (version_op == ">=")
return kGE;
else if (version_op == "any")
return kAny;
else if (version_op == "between")
return kBetween;
return kUnknown;
}
GpuBlacklist::OsInfo::OsInfo(const std::string& os,
const std::string& version_op,
const std::string& version_string,
const std::string& version_string2) {
type_ = StringToOsType(os);
if (type_ != kOsUnknown) {
version_info_.reset(
new VersionInfo(version_op, version_string, version_string2));
}
}
bool GpuBlacklist::OsInfo::Contains(OsType type,
const Version& version) const {
if (!IsValid())
return false;
if (type_ != type && type_ != kOsAny)
return false;
return version_info_->Contains(version);
}
bool GpuBlacklist::OsInfo::IsValid() const {
return type_ != kOsUnknown && version_info_->IsValid();
}
GpuBlacklist::OsType GpuBlacklist::OsInfo::type() const {
return type_;
}
GpuBlacklist::OsType GpuBlacklist::OsInfo::StringToOsType(
const std::string& os) {
if (os == "win")
return kOsWin;
else if (os == "macosx")
return kOsMacosx;
else if (os == "linux")
return kOsLinux;
else if (os == "any")
return kOsAny;
return kOsUnknown;
}
GpuBlacklist::GpuBlacklistEntry*
GpuBlacklist::GpuBlacklistEntry::GetGpuBlacklistEntryFromValue(
DictionaryValue* value) {
if (value == NULL)
return NULL;
GpuBlacklistEntry* entry = new GpuBlacklistEntry();
DictionaryValue* os_value = NULL;
if (value->GetDictionary("os", &os_value)) {
std::string os_type;
std::string os_version_op = "any";
std::string os_version_string;
std::string os_version_string2;
os_value->GetString("type", &os_type);
DictionaryValue* os_version_value = NULL;
if (os_value->GetDictionary("version", &os_version_value)) {
os_version_value->GetString("op", &os_version_op);
os_version_value->GetString("number", &os_version_string);
os_version_value->GetString("number2", &os_version_string2);
}
if (!entry->SetOsInfo(os_type, os_version_op, os_version_string,
os_version_string2)) {
delete entry;
return NULL;
}
}
std::string vendor_id;
if (value->GetString("vendor_id", &vendor_id)) {
if (!entry->SetVendorId(vendor_id)) {
delete entry;
return NULL;
}
}
std::string device_id;
if (value->GetString("device_id", &device_id)) {
if (!entry->SetDeviceId(device_id)) {
delete entry;
return NULL;
}
}
DictionaryValue* driver_version_value = NULL;
if (value->GetDictionary("driver_version", &driver_version_value)) {
std::string driver_version_op = "any";
std::string driver_version_string;
std::string driver_version_string2;
driver_version_value->GetString("op", &driver_version_op);
driver_version_value->GetString("number", &driver_version_string);
driver_version_value->GetString("number2", &driver_version_string2);
if (!entry->SetDriverVersionInfo(driver_version_op, driver_version_string,
driver_version_string2)) {
delete entry;
return NULL;
}
}
ListValue* blacklist_value = NULL;
if (!value->GetList("blacklist", &blacklist_value)) {
delete entry;
return NULL;
}
std::vector<std::string> blacklist;
for (size_t i = 0; i < blacklist_value->GetSize(); ++i) {
std::string feature;
if (blacklist_value->GetString(i, &feature)) {
blacklist.push_back(feature);
} else {
delete entry;
return NULL;
}
}
if (!entry->SetBlacklistedFeatures(blacklist)) {
delete entry;
return NULL;
}
return entry;
}
GpuBlacklist::GpuBlacklistEntry::GpuBlacklistEntry()
: vendor_id_(0),
device_id_(0) {
}
bool GpuBlacklist::GpuBlacklistEntry::SetOsInfo(
const std::string& os,
const std::string& version_op,
const std::string& version_string,
const std::string& version_string2) {
os_info_.reset(new OsInfo(os, version_op, version_string, version_string2));
return os_info_->IsValid();
}
bool GpuBlacklist::GpuBlacklistEntry::SetVendorId(
const std::string& vendor_id_string) {
vendor_id_ = 0;
return base::HexStringToInt(vendor_id_string,
reinterpret_cast<int*>(&vendor_id_));
}
bool GpuBlacklist::GpuBlacklistEntry::SetDeviceId(
const std::string& device_id_string) {
device_id_ = 0;
return base::HexStringToInt(device_id_string,
reinterpret_cast<int*>(&device_id_));
}
bool GpuBlacklist::GpuBlacklistEntry::SetDriverVersionInfo(
const std::string& version_op,
const std::string& version_string,
const std::string& version_string2) {
driver_version_info_.reset(
new VersionInfo(version_op, version_string, version_string2));
return driver_version_info_->IsValid();
}
bool GpuBlacklist::GpuBlacklistEntry::SetBlacklistedFeatures(
const std::vector<std::string>& blacklisted_features) {
size_t size = blacklisted_features.size();
if (size == 0)
return false;
uint32 flags = 0;
for (size_t i = 0; i < size; ++i) {
GpuFeatureFlags::GpuFeatureType type =
GpuFeatureFlags::StringToGpuFeatureType(blacklisted_features[i]);
switch (type) {
case GpuFeatureFlags::kGpuFeatureAccelerated2dCanvas:
case GpuFeatureFlags::kGpuFeatureAcceleratedCompositing:
case GpuFeatureFlags::kGpuFeatureWebgl:
case GpuFeatureFlags::kGpuFeatureAll:
flags |= type;
break;
case GpuFeatureFlags::kGpuFeatureUnknown:
return false;
}
}
feature_flags_.reset(new GpuFeatureFlags());
feature_flags_->set_flags(flags);
return true;
}
bool GpuBlacklist::GpuBlacklistEntry::Contains(
OsType os_type, const Version& os_version,
uint32 vendor_id, uint32 device_id,
const Version& driver_version) const {
DCHECK(os_type != kOsAny);
if (os_info_.get() != NULL && !os_info_->Contains(os_type, os_version))
return false;
if (vendor_id_ != 0 && vendor_id_ != vendor_id)
return false;
if (device_id_ != 0 && device_id_ != device_id)
return false;
if (driver_version_info_.get() == NULL)
return true;
return driver_version_info_->Contains(driver_version);
}
GpuBlacklist::OsType GpuBlacklist::GpuBlacklistEntry::GetOsType() const {
if (os_info_.get() == NULL)
return kOsUnknown;
return os_info_->type();
}
GpuFeatureFlags GpuBlacklist::GpuBlacklistEntry::GetGpuFeatureFlags() const {
return *feature_flags_;
}
GpuBlacklist::GpuBlacklist() {
}
GpuBlacklist::~GpuBlacklist() {
Clear();
}
bool GpuBlacklist::LoadGpuBlacklist(const std::string& json_context,
bool current_os_only) {
std::vector<GpuBlacklistEntry*> entries;
scoped_ptr<Value> root;
root.reset(base::JSONReader::Read(json_context, false));
if (root.get() == NULL || !root->IsType(Value::TYPE_DICTIONARY))
return false;
ListValue* list = NULL;
static_cast<DictionaryValue*>(root.get())->GetList("entries", &list);
if (list == NULL)
return false;
for (size_t i = 0; i < list->GetSize(); ++i) {
DictionaryValue* list_item = NULL;
bool valid = list->GetDictionary(i, &list_item);
if (!valid)
break;
GpuBlacklistEntry* entry =
GpuBlacklistEntry::GetGpuBlacklistEntryFromValue(list_item);
if (entry == NULL)
break;
entries.push_back(entry);
}
if (entries.size() < list->GetSize()) {
for (size_t i = 0; i < entries.size(); ++i)
delete entries[i];
return false;
}
Clear();
// Don't apply GPU blacklist for a non-registered OS.
OsType os_filter = GetOsType();
if (os_filter != kOsUnknown) {
for (size_t i = 0; i < entries.size(); ++i) {
OsType entry_os = entries[i]->GetOsType();
if (!current_os_only ||
entry_os == kOsAny || entry_os == os_filter)
blacklist_.push_back(entries[i]);
}
}
return true;
}
GpuFeatureFlags GpuBlacklist::DetermineGpuFeatureFlags(
GpuBlacklist::OsType os,
Version* os_version,
const GPUInfo& gpu_info) const {
GpuFeatureFlags flags;
// No need to go through blacklist entries if GPUInfo isn't available.
if (gpu_info.progress() == GPUInfo::kUninitialized)
return flags;
scoped_ptr<Version> driver_version(
Version::GetVersionFromString(gpu_info.driver_version()));
if (driver_version.get() == NULL)
return flags;
if (os == kOsAny)
os = GetOsType();
scoped_ptr<Version> my_os_version;
if (os_version == NULL) {
std::string version_string;
#if defined(OS_MACOSX)
// Seems like base::SysInfo::OperatingSystemVersion() returns the wrong
// version in MacOsx.
int32 version_major, version_minor, version_bugfix;
base::SysInfo::OperatingSystemVersionNumbers(
&version_major, &version_minor, &version_bugfix);
version_string = base::StringPrintf("%d.%d.%d",
version_major,
version_minor,
version_bugfix);
#else
version_string = base::SysInfo::OperatingSystemVersion();
#endif
my_os_version.reset(Version::GetVersionFromString(version_string));
os_version = my_os_version.get();
}
DCHECK(os_version != NULL);
for (size_t i = 0; i < blacklist_.size(); ++i) {
if (blacklist_[i]->Contains(os, *os_version,
gpu_info.vendor_id(), gpu_info.device_id(),
*driver_version)) {
flags.Combine(blacklist_[i]->GetGpuFeatureFlags());
}
}
return flags;
}
GpuBlacklist::OsType GpuBlacklist::GetOsType() {
#if defined(OS_WIN)
return kOsWin;
#elif defined(OS_LINUX)
return kOsLinux;
#elif defined(OS_MACOSX)
return kOsMacosx;
#else
return kOsUnknown;
#endif
}
void GpuBlacklist::Clear() {
for (size_t i = 0; i < blacklist_.size(); ++i)
delete blacklist_[i];
blacklist_.clear();
}
<commit_msg>Fix memory leak in gpu_blacklist.cc.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/gpu_blacklist.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "base/stringprintf.h"
#include "base/sys_info.h"
#include "base/values.h"
#include "base/version.h"
#include "chrome/common/gpu_info.h"
GpuBlacklist::VersionInfo::VersionInfo(const std::string& version_op,
const std::string& version_string,
const std::string& version_string2) {
op_ = StringToOp(version_op);
if (op_ == kUnknown || op_ == kAny)
return;
version_.reset(Version::GetVersionFromString(version_string));
if (version_.get() == NULL) {
op_ = kUnknown;
return;
}
if (op_ == kBetween) {
version2_.reset(Version::GetVersionFromString(version_string2));
if (version2_.get() == NULL)
op_ = kUnknown;
}
}
GpuBlacklist::VersionInfo::~VersionInfo() {
}
bool GpuBlacklist::VersionInfo::Contains(const Version& version) const {
if (op_ == kUnknown)
return false;
if (op_ == kAny)
return true;
if (op_ == kEQ) {
// Handles cases where 10.6 is considered as containing 10.6.*.
const std::vector<uint16>& components_reference = version_->components();
const std::vector<uint16>& components = version.components();
for (size_t i = 0; i < components_reference.size(); ++i) {
if (i >= components.size() && components_reference[i] != 0)
return false;
if (components[i] != components_reference[i])
return false;
}
return true;
}
int relation = version.CompareTo(*version_);
if (op_ == kEQ)
return (relation == 0);
else if (op_ == kLT)
return (relation < 0);
else if (op_ == kLE)
return (relation <= 0);
else if (op_ == kGT)
return (relation > 0);
else if (op_ == kGE)
return (relation >= 0);
// op_ == kBetween
if (relation < 0)
return false;
return version.CompareTo(*version2_) <= 0;
}
bool GpuBlacklist::VersionInfo::IsValid() const {
return op_ != kUnknown;
}
GpuBlacklist::VersionInfo::Op GpuBlacklist::VersionInfo::StringToOp(
const std::string& version_op) {
if (version_op == "=")
return kEQ;
else if (version_op == "<")
return kLT;
else if (version_op == "<=")
return kLE;
else if (version_op == ">")
return kGT;
else if (version_op == ">=")
return kGE;
else if (version_op == "any")
return kAny;
else if (version_op == "between")
return kBetween;
return kUnknown;
}
GpuBlacklist::OsInfo::OsInfo(const std::string& os,
const std::string& version_op,
const std::string& version_string,
const std::string& version_string2) {
type_ = StringToOsType(os);
if (type_ != kOsUnknown) {
version_info_.reset(
new VersionInfo(version_op, version_string, version_string2));
}
}
bool GpuBlacklist::OsInfo::Contains(OsType type,
const Version& version) const {
if (!IsValid())
return false;
if (type_ != type && type_ != kOsAny)
return false;
return version_info_->Contains(version);
}
bool GpuBlacklist::OsInfo::IsValid() const {
return type_ != kOsUnknown && version_info_->IsValid();
}
GpuBlacklist::OsType GpuBlacklist::OsInfo::type() const {
return type_;
}
GpuBlacklist::OsType GpuBlacklist::OsInfo::StringToOsType(
const std::string& os) {
if (os == "win")
return kOsWin;
else if (os == "macosx")
return kOsMacosx;
else if (os == "linux")
return kOsLinux;
else if (os == "any")
return kOsAny;
return kOsUnknown;
}
GpuBlacklist::GpuBlacklistEntry*
GpuBlacklist::GpuBlacklistEntry::GetGpuBlacklistEntryFromValue(
DictionaryValue* value) {
if (value == NULL)
return NULL;
GpuBlacklistEntry* entry = new GpuBlacklistEntry();
DictionaryValue* os_value = NULL;
if (value->GetDictionary("os", &os_value)) {
std::string os_type;
std::string os_version_op = "any";
std::string os_version_string;
std::string os_version_string2;
os_value->GetString("type", &os_type);
DictionaryValue* os_version_value = NULL;
if (os_value->GetDictionary("version", &os_version_value)) {
os_version_value->GetString("op", &os_version_op);
os_version_value->GetString("number", &os_version_string);
os_version_value->GetString("number2", &os_version_string2);
}
if (!entry->SetOsInfo(os_type, os_version_op, os_version_string,
os_version_string2)) {
delete entry;
return NULL;
}
}
std::string vendor_id;
if (value->GetString("vendor_id", &vendor_id)) {
if (!entry->SetVendorId(vendor_id)) {
delete entry;
return NULL;
}
}
std::string device_id;
if (value->GetString("device_id", &device_id)) {
if (!entry->SetDeviceId(device_id)) {
delete entry;
return NULL;
}
}
DictionaryValue* driver_version_value = NULL;
if (value->GetDictionary("driver_version", &driver_version_value)) {
std::string driver_version_op = "any";
std::string driver_version_string;
std::string driver_version_string2;
driver_version_value->GetString("op", &driver_version_op);
driver_version_value->GetString("number", &driver_version_string);
driver_version_value->GetString("number2", &driver_version_string2);
if (!entry->SetDriverVersionInfo(driver_version_op, driver_version_string,
driver_version_string2)) {
delete entry;
return NULL;
}
}
ListValue* blacklist_value = NULL;
if (!value->GetList("blacklist", &blacklist_value)) {
delete entry;
return NULL;
}
std::vector<std::string> blacklist;
for (size_t i = 0; i < blacklist_value->GetSize(); ++i) {
std::string feature;
if (blacklist_value->GetString(i, &feature)) {
blacklist.push_back(feature);
} else {
delete entry;
return NULL;
}
}
if (!entry->SetBlacklistedFeatures(blacklist)) {
delete entry;
return NULL;
}
return entry;
}
GpuBlacklist::GpuBlacklistEntry::GpuBlacklistEntry()
: vendor_id_(0),
device_id_(0) {
}
bool GpuBlacklist::GpuBlacklistEntry::SetOsInfo(
const std::string& os,
const std::string& version_op,
const std::string& version_string,
const std::string& version_string2) {
os_info_.reset(new OsInfo(os, version_op, version_string, version_string2));
return os_info_->IsValid();
}
bool GpuBlacklist::GpuBlacklistEntry::SetVendorId(
const std::string& vendor_id_string) {
vendor_id_ = 0;
return base::HexStringToInt(vendor_id_string,
reinterpret_cast<int*>(&vendor_id_));
}
bool GpuBlacklist::GpuBlacklistEntry::SetDeviceId(
const std::string& device_id_string) {
device_id_ = 0;
return base::HexStringToInt(device_id_string,
reinterpret_cast<int*>(&device_id_));
}
bool GpuBlacklist::GpuBlacklistEntry::SetDriverVersionInfo(
const std::string& version_op,
const std::string& version_string,
const std::string& version_string2) {
driver_version_info_.reset(
new VersionInfo(version_op, version_string, version_string2));
return driver_version_info_->IsValid();
}
bool GpuBlacklist::GpuBlacklistEntry::SetBlacklistedFeatures(
const std::vector<std::string>& blacklisted_features) {
size_t size = blacklisted_features.size();
if (size == 0)
return false;
uint32 flags = 0;
for (size_t i = 0; i < size; ++i) {
GpuFeatureFlags::GpuFeatureType type =
GpuFeatureFlags::StringToGpuFeatureType(blacklisted_features[i]);
switch (type) {
case GpuFeatureFlags::kGpuFeatureAccelerated2dCanvas:
case GpuFeatureFlags::kGpuFeatureAcceleratedCompositing:
case GpuFeatureFlags::kGpuFeatureWebgl:
case GpuFeatureFlags::kGpuFeatureAll:
flags |= type;
break;
case GpuFeatureFlags::kGpuFeatureUnknown:
return false;
}
}
feature_flags_.reset(new GpuFeatureFlags());
feature_flags_->set_flags(flags);
return true;
}
bool GpuBlacklist::GpuBlacklistEntry::Contains(
OsType os_type, const Version& os_version,
uint32 vendor_id, uint32 device_id,
const Version& driver_version) const {
DCHECK(os_type != kOsAny);
if (os_info_.get() != NULL && !os_info_->Contains(os_type, os_version))
return false;
if (vendor_id_ != 0 && vendor_id_ != vendor_id)
return false;
if (device_id_ != 0 && device_id_ != device_id)
return false;
if (driver_version_info_.get() == NULL)
return true;
return driver_version_info_->Contains(driver_version);
}
GpuBlacklist::OsType GpuBlacklist::GpuBlacklistEntry::GetOsType() const {
if (os_info_.get() == NULL)
return kOsUnknown;
return os_info_->type();
}
GpuFeatureFlags GpuBlacklist::GpuBlacklistEntry::GetGpuFeatureFlags() const {
return *feature_flags_;
}
GpuBlacklist::GpuBlacklist() {
}
GpuBlacklist::~GpuBlacklist() {
Clear();
}
bool GpuBlacklist::LoadGpuBlacklist(const std::string& json_context,
bool current_os_only) {
std::vector<GpuBlacklistEntry*> entries;
scoped_ptr<Value> root;
root.reset(base::JSONReader::Read(json_context, false));
if (root.get() == NULL || !root->IsType(Value::TYPE_DICTIONARY))
return false;
ListValue* list = NULL;
static_cast<DictionaryValue*>(root.get())->GetList("entries", &list);
if (list == NULL)
return false;
for (size_t i = 0; i < list->GetSize(); ++i) {
DictionaryValue* list_item = NULL;
bool valid = list->GetDictionary(i, &list_item);
if (!valid)
break;
GpuBlacklistEntry* entry =
GpuBlacklistEntry::GetGpuBlacklistEntryFromValue(list_item);
if (entry == NULL)
break;
entries.push_back(entry);
}
if (entries.size() < list->GetSize()) {
for (size_t i = 0; i < entries.size(); ++i)
delete entries[i];
return false;
}
Clear();
// Don't apply GPU blacklist for a non-registered OS.
OsType os_filter = GetOsType();
if (os_filter != kOsUnknown) {
for (size_t i = 0; i < entries.size(); ++i) {
OsType entry_os = entries[i]->GetOsType();
if (!current_os_only ||
entry_os == kOsAny || entry_os == os_filter)
blacklist_.push_back(entries[i]);
else
delete entries[i];
}
}
return true;
}
GpuFeatureFlags GpuBlacklist::DetermineGpuFeatureFlags(
GpuBlacklist::OsType os,
Version* os_version,
const GPUInfo& gpu_info) const {
GpuFeatureFlags flags;
// No need to go through blacklist entries if GPUInfo isn't available.
if (gpu_info.progress() == GPUInfo::kUninitialized)
return flags;
scoped_ptr<Version> driver_version(
Version::GetVersionFromString(gpu_info.driver_version()));
if (driver_version.get() == NULL)
return flags;
if (os == kOsAny)
os = GetOsType();
scoped_ptr<Version> my_os_version;
if (os_version == NULL) {
std::string version_string;
#if defined(OS_MACOSX)
// Seems like base::SysInfo::OperatingSystemVersion() returns the wrong
// version in MacOsx.
int32 version_major, version_minor, version_bugfix;
base::SysInfo::OperatingSystemVersionNumbers(
&version_major, &version_minor, &version_bugfix);
version_string = base::StringPrintf("%d.%d.%d",
version_major,
version_minor,
version_bugfix);
#else
version_string = base::SysInfo::OperatingSystemVersion();
#endif
my_os_version.reset(Version::GetVersionFromString(version_string));
os_version = my_os_version.get();
}
DCHECK(os_version != NULL);
for (size_t i = 0; i < blacklist_.size(); ++i) {
if (blacklist_[i]->Contains(os, *os_version,
gpu_info.vendor_id(), gpu_info.device_id(),
*driver_version)) {
flags.Combine(blacklist_[i]->GetGpuFeatureFlags());
}
}
return flags;
}
GpuBlacklist::OsType GpuBlacklist::GetOsType() {
#if defined(OS_WIN)
return kOsWin;
#elif defined(OS_LINUX)
return kOsLinux;
#elif defined(OS_MACOSX)
return kOsMacosx;
#else
return kOsUnknown;
#endif
}
void GpuBlacklist::Clear() {
for (size_t i = 0; i < blacklist_.size(); ++i)
delete blacklist_[i];
blacklist_.clear();
}
<|endoftext|>
|
<commit_before>// 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.
#include "chrome/test/render_view_test.h"
#include "chrome/browser/extensions/extension_function_dispatcher.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/native_web_keyboard_event.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/renderer_preferences.h"
#include "chrome/renderer/extensions/event_bindings.h"
#include "chrome/renderer/extensions/extension_process_bindings.h"
#include "chrome/renderer/extensions/js_only_v8_extensions.h"
#include "chrome/renderer/extensions/renderer_extension_bindings.h"
#include "chrome/renderer/renderer_main_platform_delegate.h"
#include "webkit/api/public/WebFrame.h"
#include "webkit/api/public/WebInputEvent.h"
#include "webkit/api/public/WebKit.h"
#include "webkit/api/public/WebScriptSource.h"
#include "webkit/api/public/WebURLRequest.h"
#include "webkit/glue/webview.h"
using WebKit::WebFrame;
using WebKit::WebScriptSource;
using WebKit::WebString;
using WebKit::WebURLRequest;
namespace {
const int32 kRouteId = 5;
const int32 kOpenerId = 7;
}
void RenderViewTest::ProcessPendingMessages() {
msg_loop_.PostTask(FROM_HERE, new MessageLoop::QuitTask());
msg_loop_.Run();
}
WebFrame* RenderViewTest::GetMainFrame() {
return view_->webview()->GetMainFrame();
}
void RenderViewTest::ExecuteJavaScript(const char* js) {
GetMainFrame()->executeScript(WebScriptSource(WebString::fromUTF8(js)));
}
void RenderViewTest::LoadHTML(const char* html) {
std::string url_str = "data:text/html;charset=utf-8,";
url_str.append(html);
GURL url(url_str);
GetMainFrame()->loadRequest(WebURLRequest(url));
// The load actually happens asynchronously, so we pump messages to process
// the pending continuation.
ProcessPendingMessages();
}
void RenderViewTest::SetUp() {
sandbox_init_wrapper_.reset(new SandboxInitWrapper());
#if defined(OS_WIN)
command_line_.reset(new CommandLine(std::wstring()));
#elif defined(OS_POSIX)
command_line_.reset(new CommandLine(std::vector<std::string>()));
#endif
params_.reset(new MainFunctionParams(*command_line_, *sandbox_init_wrapper_,
NULL));
platform_.reset(new RendererMainPlatformDelegate(*params_));
platform_->PlatformInitialize();
WebKit::initialize(&webkitclient_);
WebKit::registerExtension(BaseJsV8Extension::Get());
WebKit::registerExtension(JsonSchemaJsV8Extension::Get());
WebKit::registerExtension(EventBindings::Get());
WebKit::registerExtension(ExtensionApiTestV8Extension::Get());
WebKit::registerExtension(ExtensionProcessBindings::Get());
WebKit::registerExtension(RendererExtensionBindings::Get());
EventBindings::SetRenderThread(&render_thread_);
// TODO(aa): Should some of this go to some other inheriting class?
std::vector<std::string> names;
ExtensionFunctionDispatcher::GetAllFunctionNames(&names);
ExtensionProcessBindings::SetFunctionNames(names);
std::vector<std::string> permissions(
Extension::kPermissionNames,
Extension::kPermissionNames + Extension::kNumPermissions);
ExtensionProcessBindings::SetAPIPermissions("", permissions);
mock_process_.reset(new MockProcess());
render_thread_.set_routing_id(kRouteId);
// This needs to pass the mock render thread to the view.
view_ = RenderView::Create(&render_thread_, NULL, NULL, kOpenerId,
RendererPreferences(), WebPreferences(),
new SharedRenderViewCounter(0), kRouteId);
// Attach a pseudo keyboard device to this object.
mock_keyboard_.reset(new MockKeyboard());
}
void RenderViewTest::TearDown() {
render_thread_.SendCloseMessage();
// Run the loop so the release task from the renderwidget executes.
ProcessPendingMessages();
EventBindings::SetRenderThread(NULL);
view_ = NULL;
mock_process_.reset();
WebKit::shutdown();
msg_loop_.RunAllPending();
mock_keyboard_.reset();
platform_->PlatformUninitialize();
platform_.reset();
params_.reset();
command_line_.reset();
sandbox_init_wrapper_.reset();
}
int RenderViewTest::SendKeyEvent(MockKeyboard::Layout layout,
int key_code,
MockKeyboard::Modifiers modifiers,
std::wstring* output) {
#if defined(OS_WIN)
// Retrieve the Unicode character for the given tuple (keyboard-layout,
// key-code, and modifiers).
// Exit when a keyboard-layout driver cannot assign a Unicode character to
// the tuple to prevent sending an invalid key code to the RenderView object.
CHECK(mock_keyboard_.get());
CHECK(output);
int length = mock_keyboard_->GetCharacters(layout, key_code, modifiers,
output);
if (length != 1)
return -1;
// Create IPC messages from Windows messages and send them to our
// back-end.
// A keyboard event of Windows consists of three Windows messages:
// WM_KEYDOWN, WM_CHAR, and WM_KEYUP.
// WM_KEYDOWN and WM_KEYUP sends virtual-key codes. On the other hand,
// WM_CHAR sends a composed Unicode character.
NativeWebKeyboardEvent keydown_event(NULL, WM_KEYDOWN, key_code, 0);
scoped_ptr<IPC::Message> keydown_message(new ViewMsg_HandleInputEvent(0));
keydown_message->WriteData(reinterpret_cast<const char*>(&keydown_event),
sizeof(WebKit::WebKeyboardEvent));
view_->OnHandleInputEvent(*keydown_message);
NativeWebKeyboardEvent char_event(NULL, WM_CHAR, (*output)[0], 0);
scoped_ptr<IPC::Message> char_message(new ViewMsg_HandleInputEvent(0));
char_message->WriteData(reinterpret_cast<const char*>(&char_event),
sizeof(WebKit::WebKeyboardEvent));
view_->OnHandleInputEvent(*char_message);
NativeWebKeyboardEvent keyup_event(NULL, WM_KEYUP, key_code, 0);
scoped_ptr<IPC::Message> keyup_message(new ViewMsg_HandleInputEvent(0));
keyup_message->WriteData(reinterpret_cast<const char*>(&keyup_event),
sizeof(WebKit::WebKeyboardEvent));
view_->OnHandleInputEvent(*keyup_message);
return length;
#else
NOTIMPLEMENTED();
return L'\0';
#endif
}
<commit_msg>Hopefully fix flaky RenderViewTest<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.
#include "chrome/test/render_view_test.h"
#include "chrome/browser/extensions/extension_function_dispatcher.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/native_web_keyboard_event.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/renderer_preferences.h"
#include "chrome/renderer/extensions/event_bindings.h"
#include "chrome/renderer/extensions/extension_process_bindings.h"
#include "chrome/renderer/extensions/js_only_v8_extensions.h"
#include "chrome/renderer/extensions/renderer_extension_bindings.h"
#include "chrome/renderer/renderer_main_platform_delegate.h"
#include "webkit/api/public/WebFrame.h"
#include "webkit/api/public/WebInputEvent.h"
#include "webkit/api/public/WebKit.h"
#include "webkit/api/public/WebScriptSource.h"
#include "webkit/api/public/WebURLRequest.h"
#include "webkit/glue/webview.h"
using WebKit::WebFrame;
using WebKit::WebScriptSource;
using WebKit::WebString;
using WebKit::WebURLRequest;
namespace {
const int32 kRouteId = 5;
const int32 kOpenerId = 7;
}
void RenderViewTest::ProcessPendingMessages() {
msg_loop_.PostTask(FROM_HERE, new MessageLoop::QuitTask());
msg_loop_.Run();
}
WebFrame* RenderViewTest::GetMainFrame() {
return view_->webview()->GetMainFrame();
}
void RenderViewTest::ExecuteJavaScript(const char* js) {
GetMainFrame()->executeScript(WebScriptSource(WebString::fromUTF8(js)));
}
void RenderViewTest::LoadHTML(const char* html) {
std::string url_str = "data:text/html;charset=utf-8,";
url_str.append(html);
GURL url(url_str);
GetMainFrame()->loadRequest(WebURLRequest(url));
// The load actually happens asynchronously, so we pump messages to process
// the pending continuation.
ProcessPendingMessages();
}
void RenderViewTest::SetUp() {
sandbox_init_wrapper_.reset(new SandboxInitWrapper());
#if defined(OS_WIN)
command_line_.reset(new CommandLine(std::wstring()));
#elif defined(OS_POSIX)
command_line_.reset(new CommandLine(std::vector<std::string>()));
#endif
params_.reset(new MainFunctionParams(*command_line_, *sandbox_init_wrapper_,
NULL));
platform_.reset(new RendererMainPlatformDelegate(*params_));
platform_->PlatformInitialize();
WebKit::initialize(&webkitclient_);
WebKit::registerExtension(BaseJsV8Extension::Get());
WebKit::registerExtension(JsonSchemaJsV8Extension::Get());
WebKit::registerExtension(EventBindings::Get());
WebKit::registerExtension(ExtensionApiTestV8Extension::Get());
WebKit::registerExtension(ExtensionProcessBindings::Get());
WebKit::registerExtension(RendererExtensionBindings::Get());
EventBindings::SetRenderThread(&render_thread_);
// TODO(aa): Should some of this go to some other inheriting class?
std::vector<std::string> names;
ExtensionFunctionDispatcher::GetAllFunctionNames(&names);
ExtensionProcessBindings::SetFunctionNames(names);
std::vector<std::string> permissions(
Extension::kPermissionNames,
Extension::kPermissionNames + Extension::kNumPermissions);
ExtensionProcessBindings::SetAPIPermissions("", permissions);
mock_process_.reset(new MockProcess());
render_thread_.set_routing_id(kRouteId);
// This needs to pass the mock render thread to the view.
view_ = RenderView::Create(&render_thread_, NULL, NULL, kOpenerId,
RendererPreferences(), WebPreferences(),
new SharedRenderViewCounter(0), kRouteId);
// Attach a pseudo keyboard device to this object.
mock_keyboard_.reset(new MockKeyboard());
}
void RenderViewTest::TearDown() {
render_thread_.SendCloseMessage();
// Run the loop so the release task from the renderwidget executes.
ProcessPendingMessages();
EventBindings::SetRenderThread(NULL);
view_ = NULL;
mock_process_.reset();
// After resetting the view_ and mock_process_ we may get some new tasks
// which need to be processed before shutting down WebKit
// (http://crbug.com/21508).
msg_loop_.RunAllPending();
WebKit::shutdown();
mock_keyboard_.reset();
platform_->PlatformUninitialize();
platform_.reset();
params_.reset();
command_line_.reset();
sandbox_init_wrapper_.reset();
}
int RenderViewTest::SendKeyEvent(MockKeyboard::Layout layout,
int key_code,
MockKeyboard::Modifiers modifiers,
std::wstring* output) {
#if defined(OS_WIN)
// Retrieve the Unicode character for the given tuple (keyboard-layout,
// key-code, and modifiers).
// Exit when a keyboard-layout driver cannot assign a Unicode character to
// the tuple to prevent sending an invalid key code to the RenderView object.
CHECK(mock_keyboard_.get());
CHECK(output);
int length = mock_keyboard_->GetCharacters(layout, key_code, modifiers,
output);
if (length != 1)
return -1;
// Create IPC messages from Windows messages and send them to our
// back-end.
// A keyboard event of Windows consists of three Windows messages:
// WM_KEYDOWN, WM_CHAR, and WM_KEYUP.
// WM_KEYDOWN and WM_KEYUP sends virtual-key codes. On the other hand,
// WM_CHAR sends a composed Unicode character.
NativeWebKeyboardEvent keydown_event(NULL, WM_KEYDOWN, key_code, 0);
scoped_ptr<IPC::Message> keydown_message(new ViewMsg_HandleInputEvent(0));
keydown_message->WriteData(reinterpret_cast<const char*>(&keydown_event),
sizeof(WebKit::WebKeyboardEvent));
view_->OnHandleInputEvent(*keydown_message);
NativeWebKeyboardEvent char_event(NULL, WM_CHAR, (*output)[0], 0);
scoped_ptr<IPC::Message> char_message(new ViewMsg_HandleInputEvent(0));
char_message->WriteData(reinterpret_cast<const char*>(&char_event),
sizeof(WebKit::WebKeyboardEvent));
view_->OnHandleInputEvent(*char_message);
NativeWebKeyboardEvent keyup_event(NULL, WM_KEYUP, key_code, 0);
scoped_ptr<IPC::Message> keyup_message(new ViewMsg_HandleInputEvent(0));
keyup_message->WriteData(reinterpret_cast<const char*>(&keyup_event),
sizeof(WebKit::WebKeyboardEvent));
view_->OnHandleInputEvent(*keyup_message);
return length;
#else
NOTIMPLEMENTED();
return L'\0';
#endif
}
<|endoftext|>
|
<commit_before>
#include "numerics/matrix_computations.hpp"
#include <tuple>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "numerics/fixed_arrays.hpp"
#include "numerics/unbounded_arrays.hpp"
#include "quantities/elementary_functions.hpp"
#include "testing_utilities/almost_equals.hpp"
namespace principia {
namespace numerics {
using quantities::Sqrt;
using testing_utilities::AlmostEquals;
template<typename T>
class MatrixComputationsTest : public ::testing::Test {
protected:
};
template<typename Scalar>
using FixedVector4 = FixedVector<Scalar, 4>;
template<typename Scalar>
using FixedLowerTriangularMatrix4 = FixedLowerTriangularMatrix<Scalar, 4>;
template<typename Scalar>
using FixedUpperTriangularMatrix4 = FixedUpperTriangularMatrix<Scalar, 4>;
using MatrixTypes =
::testing::Types<std::tuple<FixedVector4<double>,
FixedLowerTriangularMatrix4<double>,
FixedUpperTriangularMatrix4<double>>,
std::tuple<UnboundedVector<double>,
UnboundedLowerTriangularMatrix<double>,
UnboundedUpperTriangularMatrix<double>>>;
TYPED_TEST_SUITE(MatrixComputationsTest, MatrixTypes);
TYPED_TEST(MatrixComputationsTest, CholeskyDecomposition) {
using Vector = typename std::tuple_element<0, TypeParam>::type;
using UpperTriangularMatrix = typename std::tuple_element<2, TypeParam>::type;
UpperTriangularMatrix const hilbert4({1, 1.0 / 2.0, 1.0 / 3.0, 1.0 / 4.0,
1.0 / 3.0, 1.0 / 4.0, 1.0 / 5.0,
1.0 / 5.0, 1.0 / 6.0,
1.0 / 7.0});
UpperTriangularMatrix const r4_expected({
1, 1.0 / 2.0, 1.0 / 3.0, 1.0 / 4.0,
1.0 / Sqrt(12.0), 1.0 / Sqrt(12.0), Sqrt(27.0) / 20.0,
1.0 / Sqrt(180.0), 1.0 / Sqrt(80.0),
1.0 / Sqrt(2800.0)});
auto const r4_actual = CholeskyDecomposition(hilbert4);
EXPECT_THAT(r4_actual, AlmostEquals(r4_expected, 245));
}
TYPED_TEST(MatrixComputationsTest, ᵗRDRDecomposition) {
using Vector = typename std::tuple_element<0, TypeParam>::type;
using UpperTriangularMatrix = typename std::tuple_element<2, TypeParam>::type;
UpperTriangularMatrix const hilbert4({1, 1.0 / 2.0, 1.0 / 3.0, 1.0 / 4.0,
1.0 / 3.0, 1.0 / 4.0, 1.0 / 5.0,
1.0 / 5.0, 1.0 / 6.0,
1.0 / 7.0});
UpperTriangularMatrix const r4_expected({
1, 1.0 / 2.0, 1.0 / 3.0, 1.0 / 4.0,
1, 1, 9.0 / 10.0,
1, 3.0 / 2.0,
1});
Vector d4_expected({1, 1.0 / 12.0, 1.0 / 180.0, 1.0 / 2800.0});
UpperTriangularMatrix r4_actual(4);
Vector d4_actual(4);
ᵗRDRDecomposition(hilbert4, r4_actual, d4_actual);
EXPECT_THAT(d4_actual, AlmostEquals(d4_expected, 1615));
EXPECT_THAT(r4_actual, AlmostEquals(r4_expected, 23));
}
TYPED_TEST(MatrixComputationsTest, BackSubstitution) {
using Vector = typename std::tuple_element<0, TypeParam>::type;
using UpperTriangularMatrix = typename std::tuple_element<2, TypeParam>::type;
UpperTriangularMatrix const m4({1, 3, -2, 6,
4, 7, -1,
5, 3,
2});
Vector const b4({1, 1, -4, 4});
Vector const x4_expected({-111.0 / 4.0, 17.0 / 4.0, -2.0, 2.0});
auto const x4_actual = BackSubstitution(m4, b4);
EXPECT_THAT(x4_actual, AlmostEquals(x4_expected, 1));
}
TYPED_TEST(MatrixComputationsTest, ForwardSubstitution) {
using Vector = typename std::tuple_element<0, TypeParam>::type;
using LowerTriangularMatrix = typename std::tuple_element<1, TypeParam>::type;
LowerTriangularMatrix const m4({ 1,
3, -2,
4, 7, 5,
-6, 9, 1, 2});
Vector const b4({1, 1, -4, 4});
Vector const x4_expected({1, 1, -3, 2});
auto const x4_actual = ForwardSubstitution(m4, b4);
EXPECT_THAT(x4_actual, AlmostEquals(x4_expected, 0));
}
} // namespace numerics
} // namespace principia
<commit_msg>The tests I'd like to have.<commit_after>
#include "numerics/matrix_computations.hpp"
#include <tuple>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "numerics/fixed_arrays.hpp"
#include "numerics/unbounded_arrays.hpp"
#include "quantities/elementary_functions.hpp"
#include "testing_utilities/almost_equals.hpp"
namespace principia {
namespace numerics {
using quantities::Sqrt;
using testing_utilities::AlmostEquals;
template<typename T>
class MatrixComputationsTest : public ::testing::Test {
protected:
};
using MatrixTypes =
::testing::Types<std::tuple<FixedVector<double, 4>,
FixedLowerTriangularMatrix<double, 4>,
FixedUpperTriangularMatrix<double, 4>>,
std::tuple<UnboundedVector<double>,
UnboundedLowerTriangularMatrix<double>,
UnboundedUpperTriangularMatrix<double>>>;
TYPED_TEST_SUITE(MatrixComputationsTest, MatrixTypes);
TYPED_TEST(MatrixComputationsTest, CholeskyDecomposition) {
using Vector = typename std::tuple_element<0, TypeParam>::type;
using UpperTriangularMatrix = typename std::tuple_element<2, TypeParam>::type;
UpperTriangularMatrix const hilbert4({1, 1.0 / 2.0, 1.0 / 3.0, 1.0 / 4.0,
1.0 / 3.0, 1.0 / 4.0, 1.0 / 5.0,
1.0 / 5.0, 1.0 / 6.0,
1.0 / 7.0});
UpperTriangularMatrix const r4_expected({
1, 1.0 / 2.0, 1.0 / 3.0, 1.0 / 4.0,
1.0 / Sqrt(12.0), 1.0 / Sqrt(12.0), Sqrt(27.0) / 20.0,
1.0 / Sqrt(180.0), 1.0 / Sqrt(80.0),
1.0 / Sqrt(2800.0)});
auto const r4_actual = CholeskyDecomposition(hilbert4);
EXPECT_THAT(r4_actual, AlmostEquals(r4_expected, 245));
}
#if 0
TYPED_TEST(MatrixComputationsTest, ᵗRDRDecomposition) {
using Vector = typename std::tuple_element<0, TypeParam>::type;
using UpperTriangularMatrix = typename std::tuple_element<2, TypeParam>::type;
UpperTriangularMatrix const hilbert4({1, 1.0 / 2.0, 1.0 / 3.0, 1.0 / 4.0,
1.0 / 3.0, 1.0 / 4.0, 1.0 / 5.0,
1.0 / 5.0, 1.0 / 6.0,
1.0 / 7.0});
UpperTriangularMatrix const r4_expected({
1, 1.0 / 2.0, 1.0 / 3.0, 1.0 / 4.0,
1, 1, 9.0 / 10.0,
1, 3.0 / 2.0,
1});
Vector d4_expected({1, 1.0 / 12.0, 1.0 / 180.0, 1.0 / 2800.0});
UpperTriangularMatrix r4_actual(4);
Vector d4_actual(4);
ᵗRDRDecomposition(hilbert4, r4_actual, d4_actual);
EXPECT_THAT(d4_actual, AlmostEquals(d4_expected, 1615));
EXPECT_THAT(r4_actual, AlmostEquals(r4_expected, 23));
}
TYPED_TEST(MatrixComputationsTest, BackSubstitution) {
using Vector = typename std::tuple_element<0, TypeParam>::type;
using UpperTriangularMatrix = typename std::tuple_element<2, TypeParam>::type;
UpperTriangularMatrix const m4({1, 3, -2, 6,
4, 7, -1,
5, 3,
2});
Vector const b4({1, 1, -4, 4});
Vector const x4_expected({-111.0 / 4.0, 17.0 / 4.0, -2.0, 2.0});
auto const x4_actual = BackSubstitution(m4, b4);
EXPECT_THAT(x4_actual, AlmostEquals(x4_expected, 1));
}
TYPED_TEST(MatrixComputationsTest, ForwardSubstitution) {
using Vector = typename std::tuple_element<0, TypeParam>::type;
using LowerTriangularMatrix = typename std::tuple_element<1, TypeParam>::type;
LowerTriangularMatrix const m4({ 1,
3, -2,
4, 7, 5,
-6, 9, 1, 2});
Vector const b4({1, 1, -4, 4});
Vector const x4_expected({1, 1, -3, 2});
auto const x4_actual = ForwardSubstitution(m4, b4);
EXPECT_THAT(x4_actual, AlmostEquals(x4_expected, 0));
}
#endif
} // namespace numerics
} // namespace principia
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
// to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "content/nw/src/renderer/shell_content_renderer_client.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "content/nw/src/api/dispatcher.h"
#include "content/nw/src/common/shell_switches.h"
#include "content/nw/src/nw_version.h"
#include "content/nw/src/renderer/prerenderer/prerenderer_client.h"
#include "content/nw/src/renderer/shell_render_process_observer.h"
#include "content/nw/src/renderer/shell_render_view_observer.h"
#include "third_party/node/src/node.h"
#include "third_party/node/src/req_wrap.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityOrigin.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityPolicy.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h"
#include "v8/include/v8.h"
namespace content {
ShellContentRendererClient::ShellContentRendererClient() {
}
ShellContentRendererClient::~ShellContentRendererClient() {
}
void ShellContentRendererClient::RenderThreadStarted() {
// Change working directory
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kWorkingDirectory)) {
file_util::SetCurrentDirectory(
command_line->GetSwitchValuePath(switches::kWorkingDirectory));
}
// Initialize node after render thread is started
v8::V8::Initialize();
v8::HandleScope scope;
node::g_context = v8::Context::New();
node::g_context->Enter();
char* argv[] = { (char*)"node", NULL };
node::SetupContext(1, argv, node::g_context->Global());
// Start observers
shell_observer_.reset(new ShellRenderProcessObserver());
api_dispatcher_.reset(new api::Dispatcher());
}
void ShellContentRendererClient::RenderViewCreated(RenderView* render_view) {
new prerender::PrerendererClient(render_view);
new ShellRenderViewObserver(render_view);
}
void ShellContentRendererClient::DidCreateScriptContext(
WebKit::WebFrame* frame,
v8::Handle<v8::Context> context,
int extension_group,
int world_id) {
InstallNodeSymbols(context);
api_dispatcher_->DidCreateScriptContext(
frame, context, extension_group, world_id);
}
void ShellContentRendererClient::WillReleaseScriptContext(
WebKit::WebFrame* frame,
v8::Handle<v8::Context> context,
int world_id) {
api_dispatcher_->WillReleaseScriptContext(frame, context, world_id);
}
bool ShellContentRendererClient::WillSetSecurityToken(
WebKit::WebFrame* frame,
v8::Handle<v8::Context> context) {
// Override context's security token
context->SetSecurityToken(node::g_context->GetSecurityToken());
return true;
}
void ShellContentRendererClient::InstallNodeSymbols(
v8::Handle<v8::Context> context) {
// Do we integrate node?
bool use_node = CommandLine::ForCurrentProcess()->HasSwitch(switches::kmNodejs);
// Test if protocol is file:
v8::Local<v8::Script> protocol_script = v8::Script::New(v8::String::New(
"(function(){ return window.location.protocol == 'file:' })();"
));
bool is_file_protocol = protocol_script->Run()->BooleanValue();
// Disable nodejs in no-file protocols
use_node = is_file_protocol ? use_node : false;
// Test if protocol is 'nw:'
// test for 'about:blank' is also here becuase window.open would open 'about:blank' first
protocol_script = v8::Script::New(v8::String::New(
"(function(){ return window.location.protocol == 'nw:' || window.location == 'about:blank'; })();"
));
bool is_nw_protocol = protocol_script->Run()->BooleanValue();
if (use_node || is_nw_protocol) {
// Don't use WebKit's timers in node
v8::Local<v8::Object> disableMap = v8::Object::New();
disableMap->Set(v8::String::New("setTimeout"), v8::Integer::New(1));
disableMap->Set(v8::String::New("clearTimeout"), v8::Integer::New(1));
disableMap->Set(v8::String::New("setInterval"), v8::Integer::New(1));
disableMap->Set(v8::String::New("clearInterval"), v8::Integer::New(1));
v8::Local<v8::Object> nodeGlobal = node::g_context->Global();
v8::Local<v8::Object> v8Global = context->Global();
v8::Local<v8::Array> symbols = nodeGlobal->GetPropertyNames();
for (unsigned i = 0; i < symbols->Length(); ++i) {
v8::Local<v8::Value> key = symbols->Get(i);
if (disableMap->Has(key->ToString()))
continue;
v8Global->Set(key, nodeGlobal->Get(key));
}
}
if (use_node) {
v8::Local<v8::Script> script = v8::Script::New(v8::String::New(
// Make node's relative modules work
#if defined(OS_WIN)
"process.mainModule.filename = decodeURIComponent(window.location.pathname.substr(1));"
#else
"process.mainModule.filename = decodeURIComponent(window.location.pathname);"
#endif
"process.mainModule.paths = require('module')._nodeModulePaths(process.cwd());"
));
script->Run();
}
if (use_node || is_nw_protocol) {
v8::Local<v8::Script> script = v8::Script::New(v8::String::New(
// Use WebKit's console globally
"global.console = console;"
// Don't exit on exception
"process.on('uncaughtException', function (err) {"
"console.log(err.stack);"
"});"
// Save node-webkit version
"process.versions['node-webkit'] = '" NW_VERSION_STRING "';"
));
script->Run();
}
}
} // namespace content
<commit_msg>Only transfer necessary objects from node to DOM.<commit_after>// Copyright (c) 2012 Intel Corp
// Copyright (c) 2012 The Chromium Authors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell co
// pies of the Software, and to permit persons to whom the Software is furnished
// to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in al
// l copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IM
// PLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNES
// S FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WH
// ETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "content/nw/src/renderer/shell_content_renderer_client.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/utf_string_conversions.h"
#include "content/nw/src/api/dispatcher.h"
#include "content/nw/src/common/shell_switches.h"
#include "content/nw/src/nw_version.h"
#include "content/nw/src/renderer/prerenderer/prerenderer_client.h"
#include "content/nw/src/renderer/shell_render_process_observer.h"
#include "content/nw/src/renderer/shell_render_view_observer.h"
#include "third_party/node/src/node.h"
#include "third_party/node/src/req_wrap.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityOrigin.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityPolicy.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/platform/WebString.h"
#include "v8/include/v8.h"
namespace content {
ShellContentRendererClient::ShellContentRendererClient() {
}
ShellContentRendererClient::~ShellContentRendererClient() {
}
void ShellContentRendererClient::RenderThreadStarted() {
// Change working directory
CommandLine* command_line = CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kWorkingDirectory)) {
file_util::SetCurrentDirectory(
command_line->GetSwitchValuePath(switches::kWorkingDirectory));
}
// Initialize node after render thread is started
v8::V8::Initialize();
v8::HandleScope scope;
node::g_context = v8::Context::New();
node::g_context->Enter();
char* argv[] = { (char*)"node", NULL };
node::SetupContext(1, argv, node::g_context->Global());
// Start observers
shell_observer_.reset(new ShellRenderProcessObserver());
api_dispatcher_.reset(new api::Dispatcher());
}
void ShellContentRendererClient::RenderViewCreated(RenderView* render_view) {
new prerender::PrerendererClient(render_view);
new ShellRenderViewObserver(render_view);
}
void ShellContentRendererClient::DidCreateScriptContext(
WebKit::WebFrame* frame,
v8::Handle<v8::Context> context,
int extension_group,
int world_id) {
InstallNodeSymbols(context);
api_dispatcher_->DidCreateScriptContext(
frame, context, extension_group, world_id);
}
void ShellContentRendererClient::WillReleaseScriptContext(
WebKit::WebFrame* frame,
v8::Handle<v8::Context> context,
int world_id) {
api_dispatcher_->WillReleaseScriptContext(frame, context, world_id);
}
bool ShellContentRendererClient::WillSetSecurityToken(
WebKit::WebFrame* frame,
v8::Handle<v8::Context> context) {
// Override context's security token
context->SetSecurityToken(node::g_context->GetSecurityToken());
return true;
}
void ShellContentRendererClient::InstallNodeSymbols(
v8::Handle<v8::Context> context) {
// Do we integrate node?
bool use_node = CommandLine::ForCurrentProcess()->HasSwitch(switches::kmNodejs);
// Test if protocol is file:
v8::Local<v8::Script> protocol_script = v8::Script::New(v8::String::New(
"(function(){ return window.location.protocol == 'file:' })();"
));
bool is_file_protocol = protocol_script->Run()->BooleanValue();
// Disable nodejs in no-file protocols
use_node = is_file_protocol ? use_node : false;
// Test if protocol is 'nw:'
// test for 'about:blank' is also here becuase window.open would open 'about:blank' first
protocol_script = v8::Script::New(v8::String::New(
"(function(){ return window.location.protocol == 'nw:' || window.location == 'about:blank'; })();"
));
bool is_nw_protocol = protocol_script->Run()->BooleanValue();
if (use_node || is_nw_protocol) {
v8::Local<v8::Array> symbols = v8::Array::New(5);
symbols->Set(0, v8::String::New("require"));
symbols->Set(1, v8::String::New("global"));
symbols->Set(2, v8::String::New("process"));
symbols->Set(3, v8::String::New("Buffer"));
symbols->Set(4, v8::String::New("root"));
v8::Local<v8::Object> nodeGlobal = node::g_context->Global();
v8::Local<v8::Object> v8Global = context->Global();
for (unsigned i = 0; i < symbols->Length(); ++i) {
v8::Local<v8::Value> key = symbols->Get(i);
v8Global->Set(key, nodeGlobal->Get(key));
}
}
if (use_node) {
v8::Local<v8::Script> script = v8::Script::New(v8::String::New(
// Make node's relative modules work
#if defined(OS_WIN)
"process.mainModule.filename = decodeURIComponent(window.location.pathname.substr(1));"
#else
"process.mainModule.filename = decodeURIComponent(window.location.pathname);"
#endif
"process.mainModule.paths = require('module')._nodeModulePaths(process.cwd());"
));
script->Run();
}
if (use_node || is_nw_protocol) {
v8::Local<v8::Script> script = v8::Script::New(v8::String::New(
// Use WebKit's console globally
"global.console = console;"
// Don't exit on exception
"process.on('uncaughtException', function (err) {"
"console.log(err.stack);"
"});"
// Save node-webkit version
"process.versions['node-webkit'] = '" NW_VERSION_STRING "';"
));
script->Run();
}
}
} // namespace content
<|endoftext|>
|
<commit_before>#include <nan.h>
#include "prtscn_windows.h"
#include <stdlib.h>
using namespace v8;
void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
// Check number of arguments passed
if (args.Length() < 5) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong number of arguments")));
return;
}
//Check the argument types
if (!args[0]->IsNumber() || !args[1]->IsNumber() || !args[2]->IsNumber() || !args[3]->IsNumber()) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong arguments")));
return;
}
int x = args[0]->NumberValue();
int y = args[1]->NumberValue();
int width = args[2]->NumberValue();
int height = args[3]->NumberValue();
getScreen(x, y, width, height, *String::Utf8Value(args[4]));
//Performe the operation
Local<Function> cb = Local<Function>::Cast(args[5]);
Local<Value> argv[1] = {Null(isolate)};
cb->Call(Null(isolate), 1, argv);
}
void Init(Local<Object> exports, Local<Object> module) {
NODE_SET_METHOD(module, "exports", Method);
}
NODE_MODULE(screenshot, Init)
<commit_msg>Adding node12 support<commit_after>#include <nan.h>
#include "prtscn_windows.h"
#include <stdlib.h>
using namespace v8;
void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
// Check number of arguments passed
if (args.Length() < 5) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong number of arguments")));
return;
}
//Check the argument types
if (!args[0]->IsNumber() || !args[1]->IsNumber() || !args[2]->IsNumber() || !args[3]->IsNumber()) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong arguments")));
return;
}
int x = args[0]->NumberValue(context).FromJust();
int y = args[1]->NumberValue(context).FromJust();
int width = args[2]->NumberValue(context).FromJust();
int height = args[3]->NumberValue(context).FromJust();;
Nan::Utf8String param1(args[4]->ToString(context).ToLocalChecked());
std::string value = std::string(*param1);
getScreen(x, y, width, height, *String::Utf8Value(args[4]));
//Performe the operation
v8::Local<v8::Function> cb = Local<Function>::Cast(args[5]);
Local<Value> argv[1] = {Null(isolate)};
Nan::Callback callback(cb);
callback.Call(1,argv);
}
void Init(Local<Object> exports, Local<Object> module) {
NODE_SET_METHOD(module, "exports", Method);
}
NODE_MODULE(screenshot, Init)
<|endoftext|>
|
<commit_before>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/base/logging.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/objects/xthread.h"
#include "xenia/kernel/util/shim_utils.h"
#include "xenia/kernel/xboxkrnl_private.h"
#include "xenia/xbox.h"
namespace xe {
namespace kernel {
// TODO: clean me up!
SHIM_CALL DbgPrint_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t format_ptr = SHIM_GET_ARG_32(0);
if (format_ptr == 0) {
SHIM_SET_RETURN_64(-1);
return;
}
const char* format = (const char*)SHIM_MEM_ADDR(format_ptr);
int arg_index = 0;
char buffer[512]; // TODO: ensure it never writes past the end of the
// buffer...
char* b = buffer;
for (; *format != '\0'; ++format) {
const char* start = format;
if (*format != '%') {
*b++ = *format;
continue;
}
++format;
if (*format == '\0') {
break;
}
if (*format == '%') {
*b++ = *format;
continue;
}
const char* end;
end = format;
// skip flags
while (*end == '-' || *end == '+' || *end == ' ' || *end == '#' ||
*end == '0') {
++end;
}
if (*end == '\0') {
break;
}
int arg_extras = 0;
// skip width
if (*end == '*') {
++end;
arg_extras++;
} else {
while (*end >= '0' && *end <= '9') {
++end;
}
}
if (*end == '\0') {
break;
}
// skip precision
if (*end == '.') {
++end;
if (*end == '*') {
++end;
++arg_extras;
} else {
while (*end >= '0' && *end <= '9') {
++end;
}
}
}
if (*end == '\0') {
break;
}
// get length
int arg_size = 4;
if (*end == 'h') {
++end;
arg_size = 4;
if (*end == 'h') {
++end;
}
} else if (*end == 'l') {
++end;
arg_size = 4;
if (*end == 'l') {
++end;
arg_size = 8;
}
} else if (*end == 'j') {
arg_size = 8;
++end;
} else if (*end == 'z') {
arg_size = 4;
++end;
} else if (*end == 't') {
arg_size = 8;
++end;
} else if (*end == 'L') {
arg_size = 8;
++end;
}
if (*end == '\0') {
break;
}
if (*end == 'd' || *end == 'i' || *end == 'u' || *end == 'o' ||
*end == 'x' || *end == 'X' || *end == 'f' || *end == 'F' ||
*end == 'e' || *end == 'E' || *end == 'g' || *end == 'G' ||
*end == 'a' || *end == 'A' || *end == 'c') {
char local[512];
local[0] = '\0';
strncat(local, start, end + 1 - start);
assert_true(arg_size == 8 || arg_size == 4);
if (arg_size == 8) {
if (arg_extras == 0) {
uint64_t value =
arg_index < 7
? SHIM_GET_ARG_64(1 + arg_index)
: SHIM_MEM_32(SHIM_GPR_32(1) + 16 + ((1 + arg_index) * 8));
int result = sprintf(b, local, value);
b += result;
arg_index++;
} else {
assert_true(false);
}
} else if (arg_size == 4) {
if (arg_extras == 0) {
uint64_t value =
arg_index < 7
? SHIM_GET_ARG_64(1 + arg_index)
: SHIM_MEM_32(SHIM_GPR_32(1) + 16 + ((1 + arg_index) * 8));
int result = sprintf(b, local, (uint32_t)value);
b += result;
arg_index++;
} else {
assert_true(false);
}
}
} else if (*end == 'n') {
assert_true(arg_size == 4);
if (arg_extras == 0) {
uint32_t value = arg_index < 7
? SHIM_GET_ARG_32(1 + arg_index)
: (uint32_t)SHIM_MEM_64(SHIM_GPR_32(1) + 16 +
((1 + arg_index) * 8));
SHIM_SET_MEM_32(value, (uint32_t)((b - buffer) / sizeof(char)));
arg_index++;
} else {
assert_true(false);
}
} else if (*end == 's' || *end == 'p') {
char local[512];
local[0] = '\0';
strncat(local, start, end + 1 - start);
assert_true(arg_size == 4);
if (arg_extras == 0) {
uint32_t value = arg_index < 7
? SHIM_GET_ARG_32(1 + arg_index)
: (uint32_t)SHIM_MEM_64(SHIM_GPR_32(1) + 16 +
((1 + arg_index) * 8));
const void* pointer = (const void*)SHIM_MEM_ADDR(value);
int result = sprintf(b, local, pointer);
b += result;
arg_index++;
} else {
assert_true(false);
}
} else {
assert_true(false);
break;
}
format = end;
}
*b++ = '\0';
XELOGD("(DbgPrint) %s", buffer);
}
SHIM_CALL DbgBreakPoint_shim(PPCContext* ppc_state, KernelState* state) {
XELOGD("DbgBreakPoint()");
DebugBreak();
}
SHIM_CALL RtlRaiseException_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t record_ptr = SHIM_GET_ARG_32(0);
uint32_t code = SHIM_MEM_32(record_ptr + 0);
uint32_t flags = SHIM_MEM_32(record_ptr + 4);
// ...
uint32_t param_count = SHIM_MEM_32(record_ptr + 16);
XELOGD("RtlRaiseException(%.8X(%.8X))", record_ptr, code);
if (code == 0x406D1388) {
// SetThreadName. FFS.
uint32_t thread_info_ptr = record_ptr + 20;
uint32_t type = SHIM_MEM_32(thread_info_ptr + 0);
assert_true(type == 0x1000);
uint32_t name_ptr = SHIM_MEM_32(thread_info_ptr + 4);
uint32_t thread_id = SHIM_MEM_32(thread_info_ptr + 8);
const char* name = (const char*)SHIM_MEM_ADDR(name_ptr);
XThread* thread = NULL;
if (thread_id == -1) {
// Current thread.
thread = XThread::GetCurrentThread();
thread->Retain();
} else {
// Lookup thread by ID.
thread = state->GetThreadByID(thread_id);
}
if (thread) {
XELOGD("SetThreadName(%d, %s)", thread->thread_id(), name);
thread->set_name(name);
thread->Release();
}
// TODO(benvanik): unwinding required here?
return;
}
// TODO(benvanik): unwinding.
// This is going to suck.
DebugBreak();
}
void xeKeBugCheckEx(uint32_t code, uint32_t param1, uint32_t param2,
uint32_t param3, uint32_t param4) {
XELOGD("*** STOP: 0x%.8X (0x%.8X, 0x%.8X, 0x%.8X, 0x%.8X)", code, param1,
param2, param3, param4);
fflush(stdout);
DebugBreak();
assert_always();
}
SHIM_CALL KeBugCheck_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t code = SHIM_GET_ARG_32(0);
xeKeBugCheckEx(code, 0, 0, 0, 0);
}
SHIM_CALL KeBugCheckEx_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t code = SHIM_GET_ARG_32(0);
uint32_t param1 = SHIM_GET_ARG_32(1);
uint32_t param2 = SHIM_GET_ARG_32(2);
uint32_t param3 = SHIM_GET_ARG_32(3);
uint32_t param4 = SHIM_GET_ARG_32(4);
xeKeBugCheckEx(code, param1, param2, param3, param4);
}
} // namespace kernel
} // namespace xe
void xe::kernel::xboxkrnl::RegisterDebugExports(
xe::cpu::ExportResolver* export_resolver, KernelState* state) {
SHIM_SET_MAPPING("xboxkrnl.exe", DbgPrint, state);
SHIM_SET_MAPPING("xboxkrnl.exe", DbgBreakPoint, state);
SHIM_SET_MAPPING("xboxkrnl.exe", RtlRaiseException, state);
SHIM_SET_MAPPING("xboxkrnl.exe", KeBugCheck, state);
SHIM_SET_MAPPING("xboxkrnl.exe", KeBugCheckEx, state);
}
<commit_msg>Cleaning up some stuff in RtlRaiseException, additional notes.<commit_after>/**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/base/logging.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/objects/xthread.h"
#include "xenia/kernel/util/shim_utils.h"
#include "xenia/kernel/xboxkrnl_private.h"
#include "xenia/xbox.h"
namespace xe {
namespace kernel {
// TODO: clean me up!
SHIM_CALL DbgPrint_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t format_ptr = SHIM_GET_ARG_32(0);
if (format_ptr == 0) {
SHIM_SET_RETURN_64(-1);
return;
}
const char* format = (const char*)SHIM_MEM_ADDR(format_ptr);
int arg_index = 0;
char buffer[512]; // TODO: ensure it never writes past the end of the
// buffer...
char* b = buffer;
for (; *format != '\0'; ++format) {
const char* start = format;
if (*format != '%') {
*b++ = *format;
continue;
}
++format;
if (*format == '\0') {
break;
}
if (*format == '%') {
*b++ = *format;
continue;
}
const char* end;
end = format;
// skip flags
while (*end == '-' || *end == '+' || *end == ' ' || *end == '#' ||
*end == '0') {
++end;
}
if (*end == '\0') {
break;
}
int arg_extras = 0;
// skip width
if (*end == '*') {
++end;
arg_extras++;
} else {
while (*end >= '0' && *end <= '9') {
++end;
}
}
if (*end == '\0') {
break;
}
// skip precision
if (*end == '.') {
++end;
if (*end == '*') {
++end;
++arg_extras;
} else {
while (*end >= '0' && *end <= '9') {
++end;
}
}
}
if (*end == '\0') {
break;
}
// get length
int arg_size = 4;
if (*end == 'h') {
++end;
arg_size = 4;
if (*end == 'h') {
++end;
}
} else if (*end == 'l') {
++end;
arg_size = 4;
if (*end == 'l') {
++end;
arg_size = 8;
}
} else if (*end == 'j') {
arg_size = 8;
++end;
} else if (*end == 'z') {
arg_size = 4;
++end;
} else if (*end == 't') {
arg_size = 8;
++end;
} else if (*end == 'L') {
arg_size = 8;
++end;
}
if (*end == '\0') {
break;
}
if (*end == 'd' || *end == 'i' || *end == 'u' || *end == 'o' ||
*end == 'x' || *end == 'X' || *end == 'f' || *end == 'F' ||
*end == 'e' || *end == 'E' || *end == 'g' || *end == 'G' ||
*end == 'a' || *end == 'A' || *end == 'c') {
char local[512];
local[0] = '\0';
strncat(local, start, end + 1 - start);
assert_true(arg_size == 8 || arg_size == 4);
if (arg_size == 8) {
if (arg_extras == 0) {
uint64_t value =
arg_index < 7
? SHIM_GET_ARG_64(1 + arg_index)
: SHIM_MEM_32(SHIM_GPR_32(1) + 16 + ((1 + arg_index) * 8));
int result = sprintf(b, local, value);
b += result;
arg_index++;
} else {
assert_true(false);
}
} else if (arg_size == 4) {
if (arg_extras == 0) {
uint64_t value =
arg_index < 7
? SHIM_GET_ARG_64(1 + arg_index)
: SHIM_MEM_32(SHIM_GPR_32(1) + 16 + ((1 + arg_index) * 8));
int result = sprintf(b, local, (uint32_t)value);
b += result;
arg_index++;
} else {
assert_true(false);
}
}
} else if (*end == 'n') {
assert_true(arg_size == 4);
if (arg_extras == 0) {
uint32_t value = arg_index < 7
? SHIM_GET_ARG_32(1 + arg_index)
: (uint32_t)SHIM_MEM_64(SHIM_GPR_32(1) + 16 +
((1 + arg_index) * 8));
SHIM_SET_MEM_32(value, (uint32_t)((b - buffer) / sizeof(char)));
arg_index++;
} else {
assert_true(false);
}
} else if (*end == 's' || *end == 'p') {
char local[512];
local[0] = '\0';
strncat(local, start, end + 1 - start);
assert_true(arg_size == 4);
if (arg_extras == 0) {
uint32_t value = arg_index < 7
? SHIM_GET_ARG_32(1 + arg_index)
: (uint32_t)SHIM_MEM_64(SHIM_GPR_32(1) + 16 +
((1 + arg_index) * 8));
const void* pointer = (const void*)SHIM_MEM_ADDR(value);
int result = sprintf(b, local, pointer);
b += result;
arg_index++;
} else {
assert_true(false);
}
} else {
assert_true(false);
break;
}
format = end;
}
*b++ = '\0';
XELOGD("(DbgPrint) %s", buffer);
}
SHIM_CALL DbgBreakPoint_shim(PPCContext* ppc_state, KernelState* state) {
XELOGD("DbgBreakPoint()");
DebugBreak();
}
// https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
typedef struct {
xe::be<uint32_t> type;
xe::be<uint32_t> name_ptr;
xe::be<uint32_t> thread_id;
xe::be<uint32_t> flags;
} X_THREADNAME_INFO;
static_assert_size(X_THREADNAME_INFO, 0x10);
// https://msdn.microsoft.com/en-us/library/windows/desktop/aa363082.aspx
typedef struct {
xe::be<uint32_t> exception_code;
xe::be<uint32_t> exception_flags;
xe::be<uint32_t> exception_record;
xe::be<uint32_t> exception_address;
xe::be<uint32_t> number_parameters;
xe::be<uint32_t> exception_information[15];
} X_EXCEPTION_RECORD;
static_assert_size(X_EXCEPTION_RECORD, 0x50);
SHIM_CALL RtlRaiseException_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t record_ptr = SHIM_GET_ARG_32(0);
auto record = reinterpret_cast<X_EXCEPTION_RECORD*>(SHIM_MEM_ADDR(record_ptr));
XELOGD("RtlRaiseException(%.8X(%.8X))", record_ptr, record->exception_code);
if (record->exception_code == 0x406D1388) {
// SetThreadName. FFS.
// https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
// TODO: check record->number_parameters to make sure it's a correct size
auto thread_info = reinterpret_cast<X_THREADNAME_INFO*>(&record->exception_information[0]);
assert_true(thread_info->type == 0x1000);
const char* name = (const char*)SHIM_MEM_ADDR(thread_info->name_ptr);
XThread* thread = NULL;
if (thread_info->thread_id == -1) {
// Current thread.
thread = XThread::GetCurrentThread();
thread->Retain();
} else {
// Lookup thread by ID.
thread = state->GetThreadByID(thread_info->thread_id);
}
if (thread) {
XELOGD("SetThreadName(%d, %s)", thread->thread_id(), name);
thread->set_name(name);
thread->Release();
}
// TODO(benvanik): unwinding required here?
return;
}
if (record->exception_code == 0xE06D7363) {
// C++ exception.
// http://blogs.msdn.com/b/oldnewthing/archive/2010/07/30/10044061.aspx
DebugBreak();
return;
}
// TODO(benvanik): unwinding.
// This is going to suck.
DebugBreak();
}
void xeKeBugCheckEx(uint32_t code, uint32_t param1, uint32_t param2,
uint32_t param3, uint32_t param4) {
XELOGD("*** STOP: 0x%.8X (0x%.8X, 0x%.8X, 0x%.8X, 0x%.8X)", code, param1,
param2, param3, param4);
fflush(stdout);
DebugBreak();
assert_always();
}
SHIM_CALL KeBugCheck_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t code = SHIM_GET_ARG_32(0);
xeKeBugCheckEx(code, 0, 0, 0, 0);
}
SHIM_CALL KeBugCheckEx_shim(PPCContext* ppc_state, KernelState* state) {
uint32_t code = SHIM_GET_ARG_32(0);
uint32_t param1 = SHIM_GET_ARG_32(1);
uint32_t param2 = SHIM_GET_ARG_32(2);
uint32_t param3 = SHIM_GET_ARG_32(3);
uint32_t param4 = SHIM_GET_ARG_32(4);
xeKeBugCheckEx(code, param1, param2, param3, param4);
}
} // namespace kernel
} // namespace xe
void xe::kernel::xboxkrnl::RegisterDebugExports(
xe::cpu::ExportResolver* export_resolver, KernelState* state) {
SHIM_SET_MAPPING("xboxkrnl.exe", DbgPrint, state);
SHIM_SET_MAPPING("xboxkrnl.exe", DbgBreakPoint, state);
SHIM_SET_MAPPING("xboxkrnl.exe", RtlRaiseException, state);
SHIM_SET_MAPPING("xboxkrnl.exe", KeBugCheck, state);
SHIM_SET_MAPPING("xboxkrnl.exe", KeBugCheckEx, state);
}
<|endoftext|>
|
<commit_before>#include <fstream>
#include <iostream>
#include <map>
#include "sst/verbs.h"
using std::ofstream;
using std::map;
using std::cin;
using std::cout;
using std::endl;
using std::string;
using namespace sst;
// number of reruns
long long int num_reruns = 10000;
int main() {
ofstream fout;
fout.open("data_write_avg_time", ofstream::app);
// input number of nodes and the local node id
int num_nodes, node_rank;
cin >> node_rank;
cin >> num_nodes;
// input the ip addresses
map<uint32_t, string> ip_addrs;
for(int i = 0; i < num_nodes; ++i) {
cin >> ip_addrs[i];
}
// initialize the rdma resources
verbs_initialize(ip_addrs, node_rank);
int r_index = num_nodes - 1 - node_rank;
for(int size = 1; size < 100000; ++size) {
// create buffer for write and read
char *write_buf, *read_buf;
write_buf = (char *)malloc(size);
read_buf = (char *)malloc(size);
resources res(r_index, read_buf, write_buf, size, size);
// start the timing experiment
struct timespec start_time;
struct timespec end_time;
long long int nanoseconds_elapsed;
if(node_rank == 0) {
clock_gettime(CLOCK_REALTIME, &start_time);
for(int i = 0; i < num_reruns; ++i) {
// write the entire buffer
res.post_remote_write(0, size);
// poll for completion
verbs_poll_completion();
}
clock_gettime(CLOCK_REALTIME, &end_time);
nanoseconds_elapsed = (end_time.tv_sec - start_time.tv_sec) * 1000000000 + (end_time.tv_nsec - start_time.tv_nsec);
fout << size << " " << (nanoseconds_elapsed + 0.0) / (1000 * num_reruns) << endl;
free(write_buf);
free(read_buf);
}
sync (r_index);
}
sync(r_index);
fout.close();
return 0;
}
<commit_msg>Carried out the experiments and got the results<commit_after>#include <fstream>
#include <iostream>
#include <map>
#include "sst/verbs.h"
using std::ofstream;
using std::map;
using std::cin;
using std::cout;
using std::endl;
using std::string;
using namespace sst;
// number of reruns
long long int num_reruns = 10000;
int main() {
ofstream fout;
fout.open("data_write_avg_time", ofstream::app);
cout << "FOR THIS EXPERIMENT TO WORK, DO NOT START THE POLLING THREAD!!!" << endl;
// input number of nodes and the local node id
int num_nodes, node_rank;
cin >> node_rank;
cin >> num_nodes;
// input the ip addresses
map<uint32_t, string> ip_addrs;
for(int i = 0; i < num_nodes; ++i) {
cin >> ip_addrs[i];
}
// initialize the rdma resources
verbs_initialize(ip_addrs, node_rank);
int r_index = num_nodes - 1 - node_rank;
for(int size = 1; size <= 10000; ++size) {
// create buffer for write and read
char *write_buf, *read_buf;
write_buf = (char *)malloc(size);
read_buf = (char *)malloc(size);
resources res(r_index, read_buf, write_buf, size, size);
// start the timing experiment
struct timespec start_time;
struct timespec end_time;
long long int nanoseconds_elapsed;
if(node_rank == 0) {
clock_gettime(CLOCK_REALTIME, &start_time);
for(int i = 0; i < num_reruns; ++i) {
// write the entire buffer
res.post_remote_write_with_completion(0, size);
// poll for completion
verbs_poll_completion();
}
clock_gettime(CLOCK_REALTIME, &end_time);
nanoseconds_elapsed = (end_time.tv_sec - start_time.tv_sec) * 1000000000 + (end_time.tv_nsec - start_time.tv_nsec);
fout << size << " " << (nanoseconds_elapsed + 0.0) / (1000 * num_reruns) << endl;
free(write_buf);
free(read_buf);
}
sync (r_index);
}
sync(r_index);
fout.close();
return 0;
}
<|endoftext|>
|
<commit_before>//
// MIT License
//
// Copyright (c) 2017 Thibault Martinez
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
//
#include <unordered_map>
#include "Keccak384.hpp"
#include "gtest/gtest.h"
static std::unordered_map<std::string, std::string> hashes = {
{ "Message",
"0c8d6ff6e6a1cf18a0d55b20f0bca160d0d1c914"
"a5e842f3707a25eeb20a279f6b4e83eda8e43a67"
"697832c7f69f53ca" },
{ "Keccak-384",
"924bd16d2ae40f6b93d58f488002de88f9288a75"
"986c60944005e99b55fec03b1f55ff91186142c6"
"4c2547de5a85815e" },
{ "IOTA",
"7ea0e8132692844c737a527baedb3045900d8ef7"
"102e4aaec87c47450717c0cfa7b23db6429e8359"
"09ca4393c5a171d5" },
{ "Crypto",
"29c016cf4476900cc2d17e3255137f45af2e4836"
"ac8281bf6f6d76978dec2926c386723b7bf65e73"
"01b5a062686bd227" },
{ "Input",
"fad2b6d11d8b32a8554775321441091eecbe13fc"
"3aa4f835eb81449303d8bd8f0407838bc265a4cf"
"60261133e4da9a22" },
{ "Tangle",
"5c7685f3c667c8a2c44d6d85174af11c57bbf9c7"
"6260af885588e6bcd05b8e485de284e24c3614c0"
"3f9072b5f67675bd" },
{ "Hash",
"b6cea85560278fa023f1ceea13b434c45d223529e8c6760473c2f6f6a9f2c566aa0407d6ada26256945a595bfe07df"
"c6" },
{ "b6cea85560278fa023f1ceea13b434c45d223529e8c6760473c2f6f6a9f2c566aa0407d6ada26256945a595bfe07df"
"c6",
"674d7600f0596b2074a19c6eb5ef785d5fc6a1e1b7af81cd776eb1296e1e10de7f11926be182509538f2eb5225e3d6"
"2a" },
{ "674d7600f0596b2074a19c6eb5ef785d5fc6a1e1b7af81cd776eb1296e1e10de7f11926be182509538f2eb5225e3d6"
"2a",
"1d48d470066949b60ad2a0929be916f4e32743cbeba99bcb7178e5ee46f6ed6ee513e26c812a8a16ec8210cfa51556"
"8f" },
{ "1d48d470066949b60ad2a0929be916f4e32743cbeba99bcb7178e5ee46f6ed6ee513e26c812a8a16ec8210cfa51556"
"8f",
"2ed08bff9d7d000275911940152c7f7ab5b05b36be1904004eef366f63febde86b0bf86de8ea4a8896f2fbb8427d35"
"c1" },
{ "2ed08bff9d7d000275911940152c7f7ab5b05b36be1904004eef366f63febde86b0bf86de8ea4a8896f2fbb8427d35"
"c1",
"3fa3a52ad49e76a3545f7e8d19fa2a328637dc017357729f465a03d91e7e6d5a1cb923a737a76752eeecd5c4ad73f7"
"49" }
};
TEST(Keccak384Test, Hash) {
IOTA::Crypto::Keccak384 k;
for (auto& input : hashes) {
std::vector<int8_t> vinput(std::begin(input.first), std::end(input.first));
k.update(vinput);
EXPECT_EQ(input.second, k.digest());
k.reset();
}
}
<commit_msg>Keccak384 tests<commit_after>//
// MIT License
//
// Copyright (c) 2017 Thibault Martinez
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
//
#include <fstream>
#include "Keccak384.hpp"
#include "gtest/gtest.h"
TEST(Keccak384Test, digest) {
std::ifstream file("/root/iota.lib.cpp/test/files/keccak384");
std::string line;
ASSERT_TRUE(file.is_open());
IOTA::Crypto::Keccak384 k;
while (std::getline(file, line)) {
auto semicolon = line.find(';');
auto input = line.substr(0, semicolon);
auto digest = line.substr(semicolon + 1);
std::vector<int8_t> vinput(std::begin(input), std::end(input));
k.update(vinput);
EXPECT_EQ(digest, k.digest());
k.reset();
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/test/base/xwalk_test_suite.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/stats_table.h"
#include "base/path_service.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "xwalk/runtime/browser/xwalk_content_browser_client.h"
#include "xwalk/runtime/common/xwalk_content_client.h"
#include "xwalk/runtime/common/xwalk_paths.h"
#include "content/public/test/test_launcher.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/dns/mock_host_resolver.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/resource/resource_handle.h"
#if defined(OS_POSIX)
#include "base/memory/shared_memory.h"
#endif
namespace {
void RemoveSharedMemoryFile(const std::string& filename) {
// Stats uses SharedMemory under the hood. On posix, this results in a file
// on disk.
#if defined(OS_POSIX)
base::SharedMemory memory;
memory.Delete(filename);
#endif
}
class XWalkTestSuiteInitializer : public testing::EmptyTestEventListener {
public:
XWalkTestSuiteInitializer() {
}
virtual void OnTestStart(const testing::TestInfo& test_info) OVERRIDE {
content_client_.reset(new xwalk::XWalkContentClient);
content::SetContentClient(content_client_.get());
browser_content_client_.reset(new xwalk::XWalkContentBrowserClient());
SetBrowserClientForTesting(browser_content_client_.get());
}
virtual void OnTestEnd(const testing::TestInfo& test_info) OVERRIDE {
browser_content_client_.reset();
content_client_.reset();
content::SetContentClient(NULL);
}
private:
scoped_ptr<xwalk::XWalkContentClient> content_client_;
scoped_ptr<xwalk::XWalkContentBrowserClient> browser_content_client_;
DISALLOW_COPY_AND_ASSIGN(XWalkTestSuiteInitializer);
};
} // namespace
XWalkTestSuite::XWalkTestSuite(int argc, char** argv)
: content::ContentTestSuiteBase(argc, argv) {
}
XWalkTestSuite::~XWalkTestSuite() {
}
void XWalkTestSuite::Initialize() {
xwalk::RegisterPathProvider();
// Initialize after overriding paths as some content paths depend on correct
// values for DIR_EXE and DIR_MODULE.
content::ContentTestSuiteBase::Initialize();
base::FilePath pak_dir;
PathService::Get(base::DIR_MODULE, &pak_dir);
DCHECK(!pak_dir.empty());
base::FilePath resources_pack_path;
resources_pack_path = pak_dir.Append(FILE_PATH_LITERAL("xwalk.pak"));
ui::ResourceBundle::InitSharedInstanceWithPakPath(resources_pack_path);
stats_filename_ = base::StringPrintf("unit_tests-%d",
::base::GetCurrentProcId());
RemoveSharedMemoryFile(stats_filename_);
stats_table_.reset(new base::StatsTable(stats_filename_, 20, 200));
base::StatsTable::set_current(stats_table_.get());
testing::TestEventListeners& listeners =
testing::UnitTest::GetInstance()->listeners();
listeners.Append(new XWalkTestSuiteInitializer);
}
content::ContentClient* XWalkTestSuite::CreateClientForInitialization() {
return new xwalk::XWalkContentClient();
}
void XWalkTestSuite::Shutdown() {
ResourceBundle::CleanupSharedInstance();
base::StatsTable::set_current(NULL);
stats_table_.reset();
RemoveSharedMemoryFile(stats_filename_);
base::TestSuite::Shutdown();
}
<commit_msg>Fix build for Windows.<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/test/base/xwalk_test_suite.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/memory/ref_counted.h"
#include "base/metrics/stats_table.h"
#include "base/path_service.h"
#include "base/process/process_handle.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "xwalk/runtime/browser/xwalk_content_browser_client.h"
#include "xwalk/runtime/common/xwalk_content_client.h"
#include "xwalk/runtime/common/xwalk_paths.h"
#include "content/public/test/test_launcher.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "net/dns/mock_host_resolver.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/resource/resource_handle.h"
#if defined(OS_POSIX)
#include "base/memory/shared_memory.h"
#endif
namespace {
void RemoveSharedMemoryFile(const std::string& filename) {
// Stats uses SharedMemory under the hood. On posix, this results in a file
// on disk.
#if defined(OS_POSIX)
base::SharedMemory memory;
memory.Delete(filename);
#endif
}
class XWalkTestSuiteInitializer : public testing::EmptyTestEventListener {
public:
XWalkTestSuiteInitializer() {
}
virtual void OnTestStart(const testing::TestInfo& test_info) OVERRIDE {
content_client_.reset(new xwalk::XWalkContentClient);
content::SetContentClient(content_client_.get());
browser_content_client_.reset(new xwalk::XWalkContentBrowserClient());
SetBrowserClientForTesting(browser_content_client_.get());
}
virtual void OnTestEnd(const testing::TestInfo& test_info) OVERRIDE {
browser_content_client_.reset();
content_client_.reset();
content::SetContentClient(NULL);
}
private:
scoped_ptr<xwalk::XWalkContentClient> content_client_;
scoped_ptr<xwalk::XWalkContentBrowserClient> browser_content_client_;
DISALLOW_COPY_AND_ASSIGN(XWalkTestSuiteInitializer);
};
} // namespace
XWalkTestSuite::XWalkTestSuite(int argc, char** argv)
: content::ContentTestSuiteBase(argc, argv) {
}
XWalkTestSuite::~XWalkTestSuite() {
}
void XWalkTestSuite::Initialize() {
xwalk::RegisterPathProvider();
// Initialize after overriding paths as some content paths depend on correct
// values for DIR_EXE and DIR_MODULE.
content::ContentTestSuiteBase::Initialize();
base::FilePath pak_dir;
PathService::Get(base::DIR_MODULE, &pak_dir);
DCHECK(!pak_dir.empty());
base::FilePath resources_pack_path;
resources_pack_path = pak_dir.Append(FILE_PATH_LITERAL("xwalk.pak"));
ui::ResourceBundle::InitSharedInstanceWithPakPath(resources_pack_path);
stats_filename_ = base::StringPrintf("unit_tests-%d",
base::GetCurrentProcId());
RemoveSharedMemoryFile(stats_filename_);
stats_table_.reset(new base::StatsTable(stats_filename_, 20, 200));
base::StatsTable::set_current(stats_table_.get());
testing::TestEventListeners& listeners =
testing::UnitTest::GetInstance()->listeners();
listeners.Append(new XWalkTestSuiteInitializer);
}
content::ContentClient* XWalkTestSuite::CreateClientForInitialization() {
return new xwalk::XWalkContentClient();
}
void XWalkTestSuite::Shutdown() {
ResourceBundle::CleanupSharedInstance();
base::StatsTable::set_current(NULL);
stats_table_.reset();
RemoveSharedMemoryFile(stats_filename_);
base::TestSuite::Shutdown();
}
<|endoftext|>
|
<commit_before>#include "gtest/gtest.h"
#include <fstream>
#include <ydsh/ydsh.h>
#include <constant.h>
#include <vm.h>
#include "../test_common.h"
class HistoryTest : public ExpectOutput, public TempFileFactory {
protected:
DSState *state{nullptr};
public:
HistoryTest() {
this->state = DSState_create();
std::string value;
value += '"';
value += this->tmpFileName;
value += '"';
this->assignValue(VAR_HISTFILE, std::move(value));
}
~HistoryTest() override {
DSState_delete(&this->state);
}
void setHistSize(unsigned int size, bool sync = true) {
this->assignUintValue(VAR_HISTSIZE, size);
if(sync) {
DSState_syncHistorySize(this->state);
}
}
void setHistFileSize(unsigned int size) {
this->assignUintValue(VAR_HISTFILESIZE, size);
}
template <typename ...T>
void history(T && ...arg) {
constexpr auto size = sizeof...(T) + 2;
std::array<const char *, size> argv = { "history", std::forward<T>(arg)..., nullptr };
this->exec(argv.data());
}
void addHistory(const char *value) {
this->history("-s", value);
}
void clearHistory() {
this->history("-c");
}
void loadHistory(const char *fileName = nullptr) {
this->history("-r", fileName);
}
void saveHistory(const char *fileName = nullptr) {
this->history("-w", fileName);
}
private:
void assignValue(const char *varName, std::string &&value) {
std::string str = "$";
str += varName;
str += " = ";
str += value;
auto r = DSState_eval(this->state, "(dummy)", str.c_str(), str.size(), nullptr);
SCOPED_TRACE("");
ASSERT_NO_FATAL_FAILURE(ASSERT_TRUE(r == 0));
}
void assignUintValue(const char *varName, unsigned int value) {
std::string str = std::to_string(value);
str += "u";
this->assignValue(varName, std::move(str));
}
void exec(const char **argv) {
int s = DSState_getExitStatus(this->state);
DSState_exec(this->state, (char **)argv);
DSState_setExitStatus(this->state, s);
}
};
TEST_F(HistoryTest, base) {
SCOPED_TRACE("");
auto *history = DSState_history(this->state);
// default size
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(0u, DSHistory_size(history)));
// after synchronization (call DSState_syncHistory)
this->setHistSize(100, false);
DSState_syncHistorySize(this->state);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(0u, DSHistory_size(history)));
}
TEST_F(HistoryTest, add) {
this->setHistSize(2);
this->addHistory("aaa");
this->addHistory("bbb");
auto *history = DSState_history(this->state);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(2u, DSHistory_size(history)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("aaa", DSHistory_get(history, 0)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("bbb", DSHistory_get(history, 1)));
this->addHistory("ccc");
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(2u, DSHistory_size(history)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("bbb", DSHistory_get(history, 0)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("ccc", DSHistory_get(history, 1)));
this->addHistory("ccc");
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(2u, DSHistory_size(history)));
}
TEST_F(HistoryTest, set) {
SCOPED_TRACE("");
this->setHistSize(10);
this->addHistory("aaa");
this->addHistory("bbb");
auto *history = DSState_history(this->state);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(2u, DSHistory_size(history)));
DSHistory_set(history, 1, "ccc");
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("ccc", DSHistory_get(history, 1)));
DSHistory_set(history, 3, "ccc"); // do nothing, if out of range
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(2u, DSHistory_size(history)));
DSHistory_set(history, 1000, "ccc"); // do nothing, if out of range
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(2u, DSHistory_size(history)));
}
TEST_F(HistoryTest, remove) {
SCOPED_TRACE("");
this->setHistSize(10);
this->addHistory("aaa");
this->addHistory("bbb");
this->addHistory("ccc");
this->addHistory("ddd");
this->addHistory("eee");
auto *history = DSState_history(this->state);
DSHistory_delete(history, 2);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(4u, DSHistory_size(history)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("aaa", DSHistory_get(history, 0)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("bbb", DSHistory_get(history, 1)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("ddd", DSHistory_get(history, 2)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("eee", DSHistory_get(history, 3)));
DSHistory_delete(history, 3);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(3u, DSHistory_size(history)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("aaa", DSHistory_get(history, 0)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("bbb", DSHistory_get(history, 1)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("ddd", DSHistory_get(history, 2)));
// do nothing, if out of range
DSHistory_delete(history, 6);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(3u, DSHistory_size(history)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("aaa", DSHistory_get(history, 0)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("bbb", DSHistory_get(history, 1)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("ddd", DSHistory_get(history, 2)));
// do nothing, if out of range
DSHistory_delete(history, 600);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(3u, DSHistory_size(history)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("aaa", DSHistory_get(history, 0)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("bbb", DSHistory_get(history, 1)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("ddd", DSHistory_get(history, 2)));
}
TEST_F(HistoryTest, clear) {
SCOPED_TRACE("");
this->setHistSize(10);
this->addHistory("aaa");
this->addHistory("bbb");
this->addHistory("ccc");
this->addHistory("ddd");
this->addHistory("eee");
auto *history = DSState_history(this->state);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(5u, DSHistory_size(history)));
this->clearHistory();
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(0u, DSHistory_size(history)));
}
TEST_F(HistoryTest, resize) {
this->setHistSize(10);
for(unsigned int i = 0; i < 10; i++) {
this->addHistory(std::to_string(i).c_str());
}
auto *history = DSState_history(this->state);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(10u, DSHistory_size(history)));
this->setHistSize(5);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(5u, DSHistory_size(history)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("0", DSHistory_get(history, 0)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("1", DSHistory_get(history, 1)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("2", DSHistory_get(history, 2)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("3", DSHistory_get(history, 3)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("4", DSHistory_get(history, 4)));
}
TEST_F(HistoryTest, file) {
this->setHistSize(10);
for(unsigned int i = 0; i < 10; i++) {
this->addHistory(std::to_string(i).c_str());
}
auto *history = DSState_history(this->state);
this->setHistFileSize(15);
/**
* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
*/
this->saveHistory();
this->clearHistory();
this->loadHistory();
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(10u, DSHistory_size(history)));
for(unsigned int i = 0; i < 10; i++) {
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ(std::to_string(i).c_str(), DSHistory_get(history, i)));
}
for(unsigned int i = 0; i < 5; i++) {
this->addHistory(std::to_string(i + 10).c_str());
}
for(unsigned int i = 0; i < 10; i++) {
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ(std::to_string(i + 5).c_str(), DSHistory_get(history, i)));
}
/**
* previous hist file content
* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
*
* newly added content
* 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
*
* current hist file content
* 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
*/
this->saveHistory();
this->clearHistory();
this->setHistSize(15);
this->loadHistory();
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(10u, DSHistory_size(history)));
for(unsigned int i = 0; i < 10; i++) {
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ(std::to_string(i + 5).c_str(), DSHistory_get(history, i)));
}
// not overwrite history file when buffer size is 0
this->clearHistory();
this->saveHistory();
this->loadHistory();
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(10u, DSHistory_size(history)));
for(unsigned int i = 0; i < 10; i++) {
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ(std::to_string(i + 5).c_str(), DSHistory_get(history, i)));
}
// not overwrite history file when hist file size is 0
this->setHistFileSize(0);
this->clearHistory();
this->addHistory("hoge");
this->saveHistory();
this->loadHistory();
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(11u, DSHistory_size(history)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("hoge", DSHistory_get(history, 0)));
for(unsigned int i = 1; i < 11; i++) {
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ(std::to_string(i + 4).c_str(), DSHistory_get(history, i)));
}
}
TEST_F(HistoryTest, file2) {
this->setHistFileSize(DS_HISTFILESIZE_LIMIT + 10);
this->setHistSize(DS_HISTFILESIZE_LIMIT);
for(unsigned int i = 0; i < DS_HISTFILESIZE_LIMIT; i++) {
this->addHistory(std::to_string(i).c_str());
}
auto *history = DSState_history(this->state);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(DS_HISTFILESIZE_LIMIT, DSHistory_size(history)));
this->saveHistory();
this->clearHistory();
this->loadHistory();
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(DS_HISTFILESIZE_LIMIT, DSHistory_size(history)));
for(unsigned int i = 0; i < DS_HISTFILESIZE_LIMIT; i++) {
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ(std::to_string(i).c_str(), DSHistory_get(history, i)));
}
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}<commit_msg>fix build error<commit_after>#include "gtest/gtest.h"
#include <fstream>
#include <ydsh/ydsh.h>
#include <constant.h>
#include <vm.h>
#include "../test_common.h"
class HistoryTest : public ExpectOutput, public TempFileFactory {
protected:
DSState *state{nullptr};
public:
HistoryTest() {
this->state = DSState_create();
std::string value;
value += '"';
value += this->tmpFileName;
value += '"';
this->assignValue(VAR_HISTFILE, std::move(value));
}
~HistoryTest() override {
DSState_delete(&this->state);
}
void setHistSize(unsigned int size, bool sync = true) {
this->assignUintValue(VAR_HISTSIZE, size);
if(sync) {
DSState_syncHistorySize(this->state);
}
}
void setHistFileSize(unsigned int size) {
this->assignUintValue(VAR_HISTFILESIZE, size);
}
template <typename ...T>
void history(T && ...arg) {
constexpr auto size = sizeof...(T) + 2;
std::array<const char *, size> argv = {{ "history", std::forward<T>(arg)..., nullptr }};
this->exec(argv.data());
}
void addHistory(const char *value) {
this->history("-s", value);
}
void clearHistory() {
this->history("-c");
}
void loadHistory(const char *fileName = nullptr) {
this->history("-r", fileName);
}
void saveHistory(const char *fileName = nullptr) {
this->history("-w", fileName);
}
private:
void assignValue(const char *varName, std::string &&value) {
std::string str = "$";
str += varName;
str += " = ";
str += value;
auto r = DSState_eval(this->state, "(dummy)", str.c_str(), str.size(), nullptr);
SCOPED_TRACE("");
ASSERT_NO_FATAL_FAILURE(ASSERT_TRUE(r == 0));
}
void assignUintValue(const char *varName, unsigned int value) {
std::string str = std::to_string(value);
str += "u";
this->assignValue(varName, std::move(str));
}
void exec(const char **argv) {
int s = DSState_getExitStatus(this->state);
DSState_exec(this->state, (char **)argv);
DSState_setExitStatus(this->state, s);
}
};
TEST_F(HistoryTest, base) {
SCOPED_TRACE("");
auto *history = DSState_history(this->state);
// default size
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(0u, DSHistory_size(history)));
// after synchronization (call DSState_syncHistory)
this->setHistSize(100, false);
DSState_syncHistorySize(this->state);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(0u, DSHistory_size(history)));
}
TEST_F(HistoryTest, add) {
this->setHistSize(2);
this->addHistory("aaa");
this->addHistory("bbb");
auto *history = DSState_history(this->state);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(2u, DSHistory_size(history)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("aaa", DSHistory_get(history, 0)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("bbb", DSHistory_get(history, 1)));
this->addHistory("ccc");
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(2u, DSHistory_size(history)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("bbb", DSHistory_get(history, 0)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("ccc", DSHistory_get(history, 1)));
this->addHistory("ccc");
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(2u, DSHistory_size(history)));
}
TEST_F(HistoryTest, set) {
SCOPED_TRACE("");
this->setHistSize(10);
this->addHistory("aaa");
this->addHistory("bbb");
auto *history = DSState_history(this->state);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(2u, DSHistory_size(history)));
DSHistory_set(history, 1, "ccc");
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("ccc", DSHistory_get(history, 1)));
DSHistory_set(history, 3, "ccc"); // do nothing, if out of range
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(2u, DSHistory_size(history)));
DSHistory_set(history, 1000, "ccc"); // do nothing, if out of range
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(2u, DSHistory_size(history)));
}
TEST_F(HistoryTest, remove) {
SCOPED_TRACE("");
this->setHistSize(10);
this->addHistory("aaa");
this->addHistory("bbb");
this->addHistory("ccc");
this->addHistory("ddd");
this->addHistory("eee");
auto *history = DSState_history(this->state);
DSHistory_delete(history, 2);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(4u, DSHistory_size(history)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("aaa", DSHistory_get(history, 0)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("bbb", DSHistory_get(history, 1)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("ddd", DSHistory_get(history, 2)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("eee", DSHistory_get(history, 3)));
DSHistory_delete(history, 3);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(3u, DSHistory_size(history)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("aaa", DSHistory_get(history, 0)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("bbb", DSHistory_get(history, 1)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("ddd", DSHistory_get(history, 2)));
// do nothing, if out of range
DSHistory_delete(history, 6);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(3u, DSHistory_size(history)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("aaa", DSHistory_get(history, 0)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("bbb", DSHistory_get(history, 1)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("ddd", DSHistory_get(history, 2)));
// do nothing, if out of range
DSHistory_delete(history, 600);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(3u, DSHistory_size(history)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("aaa", DSHistory_get(history, 0)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("bbb", DSHistory_get(history, 1)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("ddd", DSHistory_get(history, 2)));
}
TEST_F(HistoryTest, clear) {
SCOPED_TRACE("");
this->setHistSize(10);
this->addHistory("aaa");
this->addHistory("bbb");
this->addHistory("ccc");
this->addHistory("ddd");
this->addHistory("eee");
auto *history = DSState_history(this->state);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(5u, DSHistory_size(history)));
this->clearHistory();
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(0u, DSHistory_size(history)));
}
TEST_F(HistoryTest, resize) {
this->setHistSize(10);
for(unsigned int i = 0; i < 10; i++) {
this->addHistory(std::to_string(i).c_str());
}
auto *history = DSState_history(this->state);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(10u, DSHistory_size(history)));
this->setHistSize(5);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(5u, DSHistory_size(history)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("0", DSHistory_get(history, 0)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("1", DSHistory_get(history, 1)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("2", DSHistory_get(history, 2)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("3", DSHistory_get(history, 3)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("4", DSHistory_get(history, 4)));
}
TEST_F(HistoryTest, file) {
this->setHistSize(10);
for(unsigned int i = 0; i < 10; i++) {
this->addHistory(std::to_string(i).c_str());
}
auto *history = DSState_history(this->state);
this->setHistFileSize(15);
/**
* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
*/
this->saveHistory();
this->clearHistory();
this->loadHistory();
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(10u, DSHistory_size(history)));
for(unsigned int i = 0; i < 10; i++) {
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ(std::to_string(i).c_str(), DSHistory_get(history, i)));
}
for(unsigned int i = 0; i < 5; i++) {
this->addHistory(std::to_string(i + 10).c_str());
}
for(unsigned int i = 0; i < 10; i++) {
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ(std::to_string(i + 5).c_str(), DSHistory_get(history, i)));
}
/**
* previous hist file content
* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
*
* newly added content
* 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
*
* current hist file content
* 5, 6, 7, 8, 9, 10, 11, 12, 13, 14
*/
this->saveHistory();
this->clearHistory();
this->setHistSize(15);
this->loadHistory();
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(10u, DSHistory_size(history)));
for(unsigned int i = 0; i < 10; i++) {
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ(std::to_string(i + 5).c_str(), DSHistory_get(history, i)));
}
// not overwrite history file when buffer size is 0
this->clearHistory();
this->saveHistory();
this->loadHistory();
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(10u, DSHistory_size(history)));
for(unsigned int i = 0; i < 10; i++) {
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ(std::to_string(i + 5).c_str(), DSHistory_get(history, i)));
}
// not overwrite history file when hist file size is 0
this->setHistFileSize(0);
this->clearHistory();
this->addHistory("hoge");
this->saveHistory();
this->loadHistory();
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(11u, DSHistory_size(history)));
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ("hoge", DSHistory_get(history, 0)));
for(unsigned int i = 1; i < 11; i++) {
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ(std::to_string(i + 4).c_str(), DSHistory_get(history, i)));
}
}
TEST_F(HistoryTest, file2) {
this->setHistFileSize(DS_HISTFILESIZE_LIMIT + 10);
this->setHistSize(DS_HISTFILESIZE_LIMIT);
for(unsigned int i = 0; i < DS_HISTFILESIZE_LIMIT; i++) {
this->addHistory(std::to_string(i).c_str());
}
auto *history = DSState_history(this->state);
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(DS_HISTFILESIZE_LIMIT, DSHistory_size(history)));
this->saveHistory();
this->clearHistory();
this->loadHistory();
ASSERT_NO_FATAL_FAILURE(ASSERT_EQ(DS_HISTFILESIZE_LIMIT, DSHistory_size(history)));
for(unsigned int i = 0; i < DS_HISTFILESIZE_LIMIT; i++) {
ASSERT_NO_FATAL_FAILURE(ASSERT_STREQ(std::to_string(i).c_str(), DSHistory_get(history, i)));
}
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}<|endoftext|>
|
<commit_before>#include "catch.hpp"
#include "EventThreader.hpp"
TEST_CASE( "EventThreader", "[EventThreader]" ) {
std::stringstream ss;
SECTION("Abitrary use") {
/* Example of most basic use */
auto f = [&ss](std::function<void(void)> switchToMainThread){
for(int i = 0; i < 100; i++) { ss << "*"; }
switchToMainThread();
for(int i = 0; i < 50; i++) { ss << "*"; }
switchToMainThread();
};
EventThreader et(f);
et.switchToEventThread();
for(int i = 0; i < 75; i++) { ss << "$"; }
et.switchToEventThread();
for(int i = 0; i < 25; i++) { ss << "$"; }
et.join();
/* Generate what the result should look like */
std::string requirement;
for(int i = 0; i < 100; i++) { requirement += "*"; }
for(int i = 0; i < 75; i++) { requirement += "$"; }
for(int i = 0; i < 50; i++) { requirement += "*"; }
for(int i = 0; i < 25; i++) { requirement += "$"; }
REQUIRE( requirement == ss.str());
}
SECTION("Empty event - no switch, most basic use") {
auto f = [&ss](std::function<void(void)> switchToMainThread){};
EventThreader et(f);
et.join();
REQUIRE( ss.str() == "" );
}
SECTION("Empty event - no switch, main prints a thing") {
auto f = [&ss](std::function<void(void)> switchToMainThread){};
EventThreader et(f);
ss << "here";
et.join();
REQUIRE( ss.str() == "here" );
}
SECTION("event is run without switch") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
et.join();
REQUIRE( ss.str() == "f" );
}
SECTION("event is run at join (not asked to run before)") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
ss << "p";
et.join();
REQUIRE( ss.str() == "pf" );
}
SECTION("one switch to event without a switch to main") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
REQUIRE_THROWS_AS(et.switchToEventThread(), std::runtime_error);
}
SECTION("one switch to event without a switch to main - text") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
REQUIRE_THROWS_WITH(et.switchToEventThread(), "switch to event not matched with a switch to calling");
}
SECTION("two switches to event with no switches to main") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
REQUIRE_THROWS_AS(et.switchToEventThread(), std::runtime_error);
REQUIRE_THROWS_AS(et.switchToEventThread(), std::runtime_error);
}
SECTION("two switches to event with no switches to main - text") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
REQUIRE_THROWS_WITH(et.switchToEventThread(), "switch to event not matched with a switch to calling");
REQUIRE_THROWS_WITH(et.switchToEventThread(), "switch to event not matched with a switch to calling");
}
SECTION("print order") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << 1;
switchToMainThread();
ss << 3;
switchToMainThread();
ss << 5;
switchToMainThread();
};
EventThreader et(f);
ss << 0;
et.switchToEventThread();
ss << 2;
et.switchToEventThread();
ss << 4;
et.switchToEventThread();
ss << 6;
et.join();
REQUIRE( ss.str() == "0123456" );
}
SECTION("no event switch to main") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "1";
ss << "2";
};
EventThreader et(f);
et.join();
REQUIRE( ss.str() == "12" );
}
SECTION("one event switch to main") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "1";
switchToMainThread();
ss << "2";
};
EventThreader et(f);
et.switchToEventThread();
et.join();
REQUIRE( ss.str() == "12" );
}
SECTION("premiture join with exception message") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
switchToMainThread();
switchToMainThread();
};
EventThreader et(f);
et.switchToEventThread();
REQUIRE_THROWS_WITH(et.join(), "switch to calling not matched with a switch to event");
}
SECTION("clean up") {
int var = 100;
auto f = [&var](std::function<void(void)> switchToMainThread){
var = 1;
switchToMainThread();
};
EventThreader et(f);
et.setEventCleanup([&var](){
var = 10;
});
REQUIRE( var == 100);
et.switchToEventThread();
REQUIRE( var == 1);
et.join();
REQUIRE( var = 10 );
}
}
<commit_msg>bring coverage up to >80%<commit_after>#include "catch.hpp"
#include "EventThreader.hpp"
TEST_CASE( "EventThreader", "[EventThreader]" ) {
std::stringstream ss;
SECTION("Abitrary use") {
/* Example of most basic use */
auto f = [&ss](std::function<void(void)> switchToMainThread){
for(int i = 0; i < 100; i++) { ss << "*"; }
switchToMainThread();
for(int i = 0; i < 50; i++) { ss << "*"; }
switchToMainThread();
};
EventThreader et(f);
et.switchToEventThread();
for(int i = 0; i < 75; i++) { ss << "$"; }
et.switchToEventThread();
for(int i = 0; i < 25; i++) { ss << "$"; }
et.join();
/* Generate what the result should look like */
std::string requirement;
for(int i = 0; i < 100; i++) { requirement += "*"; }
for(int i = 0; i < 75; i++) { requirement += "$"; }
for(int i = 0; i < 50; i++) { requirement += "*"; }
for(int i = 0; i < 25; i++) { requirement += "$"; }
REQUIRE( requirement == ss.str());
}
SECTION("Empty event - no switch, most basic use") {
auto f = [&ss](std::function<void(void)> switchToMainThread){};
EventThreader et(f);
et.join();
REQUIRE( ss.str() == "" );
}
SECTION("Empty event - no switch, main prints a thing") {
auto f = [&ss](std::function<void(void)> switchToMainThread){};
EventThreader et(f);
ss << "here";
et.join();
REQUIRE( ss.str() == "here" );
}
SECTION("event is run without switch") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
et.join();
REQUIRE( ss.str() == "f" );
}
SECTION("event is run at join (not asked to run before)") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
ss << "p";
et.join();
REQUIRE( ss.str() == "pf" );
}
SECTION("one switch to event without a switch to main") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
REQUIRE_THROWS_AS(et.switchToEventThread(), std::runtime_error);
}
SECTION("one switch to event without a switch to main - text") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
REQUIRE_THROWS_WITH(et.switchToEventThread(), "switch to event not matched with a switch to calling");
}
SECTION("two switches to event with no switches to main") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
REQUIRE_THROWS_AS(et.switchToEventThread(), std::runtime_error);
REQUIRE_THROWS_AS(et.switchToEventThread(), std::runtime_error);
}
SECTION("two switches to event with no switches to main - text") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "f";
};
EventThreader et(f);
REQUIRE_THROWS_WITH(et.switchToEventThread(), "switch to event not matched with a switch to calling");
REQUIRE_THROWS_WITH(et.switchToEventThread(), "switch to event not matched with a switch to calling");
}
SECTION("print order") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << 1;
switchToMainThread();
ss << 3;
switchToMainThread();
ss << 5;
switchToMainThread();
};
EventThreader et(f);
ss << 0;
et.switchToEventThread();
ss << 2;
et.switchToEventThread();
ss << 4;
et.switchToEventThread();
ss << 6;
et.join();
REQUIRE( ss.str() == "0123456" );
}
SECTION("no event switch to main") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "1";
ss << "2";
};
EventThreader et(f);
et.join();
REQUIRE( ss.str() == "12" );
}
SECTION("one event switch to main") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
ss << "1";
switchToMainThread();
ss << "2";
};
EventThreader et(f);
et.switchToEventThread();
et.join();
REQUIRE( ss.str() == "12" );
}
SECTION("premiture join with exception message") {
auto f = [&ss](std::function<void(void)> switchToMainThread){
switchToMainThread();
switchToMainThread();
};
EventThreader et(f);
et.switchToEventThread();
REQUIRE_THROWS_WITH(et.join(), "switch to calling not matched with a switch to event");
}
SECTION("clean up") {
int var = 100;
auto f = [&var](std::function<void(void)> switchToMainThread){
var = 1;
switchToMainThread();
};
EventThreader et(f);
et.setEventCleanup([&var](){
var = 10;
});
REQUIRE( var == 100);
et.switchToEventThread();
REQUIRE( var == 1);
et.join();
REQUIRE( var == 10 );
}
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include "any.h"
#include "anyTest.h"
using ::testing::Return;
anyTest::anyTest() {
// Have qux return true by default
ON_CALL(m_bar,qux()).WillByDefault(Return(true));
// Have norf return false by default
ON_CALL(m_bar,norf()).WillByDefault(Return(false));
}
anyTest::~anyTest() {};
void anyTest::SetUp() {};
void anyTest::TearDown() {};
class testObject {
public:
int _value;
testObject(int val): _value{val}{}
};
std::ostream& operator<<(std::ostream& out, const testObject& b)
{
out << b._value;
return out ;
}
TEST_F(anyTest, typeBool) {
any a0 = true;
EXPECT_EQ( a0._<bool>() , true);
}
TEST_F(anyTest, typeChar) {
any a1 = 'A';
EXPECT_EQ( a1._<char>() , 'A');
}
TEST_F(anyTest, typeInt) {
any a2 = 6;
EXPECT_EQ( a2._<int>(), 6);
}
TEST_F(anyTest, typeDouble) {
any a3 = 3.14;
EXPECT_EQ( a3._<double>() , 3.14);
}
TEST_F(anyTest, typeChars) {
any a4 = "hello,";
auto expected = "hello,";
EXPECT_EQ( a4._<const char*>() , expected);
}
TEST_F(anyTest, typeVectorInt) {
any a5 = std::vector<int>{6, 5, 4, 3, 2, 1, 0};
auto expected = std::vector<int>{ 6, 5, 4, 3, 2, 1, 0 };
EXPECT_EQ( a5._<std::vector<int>>() , expected);
}
TEST_F(anyTest, typeString) {
any a6 = std::string("world!");
EXPECT_EQ( a6._<std::string>() , "world!");
}
TEST_F(anyTest, typeStruct) {
any a7 = testObject{3};
std::cout << "[7] testObject : " << a7._<testObject>() << std::endl;
EXPECT_TRUE(a7.is<testObject>());
}
<commit_msg>testing<commit_after>#include <iostream>
#include "any.h"
#include "anyTest.h"
using ::testing::Return;
anyTest::anyTest() {
// Have qux return true by default
ON_CALL(m_bar, qux()).WillByDefault(Return(true));
// Have norf return false by default
ON_CALL(m_bar, norf()).WillByDefault(Return(false));
}
anyTest::~anyTest() { };
void anyTest::SetUp() { };
void anyTest::TearDown() { };
class testObject {
public:
int _value;
testObject(int val) : _value{val} { }
};
std::ostream &operator<<(std::ostream &out, const testObject &b) {
out << "testObject { int _value = " << b._value << "}";
return out;
}
TEST_F(anyTest, typeBool) {
any a0 = true;
EXPECT_EQ(a0._<bool>(), true);
}
TEST_F(anyTest, typeChar) {
any a1 = 'A';
EXPECT_EQ(a1._<char>(), 'A');
}
TEST_F(anyTest, typeInt) {
any a2 = 6;
EXPECT_EQ(a2._<int>(), 6);
}
TEST_F(anyTest, typeDouble) {
any a3 = 3.14;
EXPECT_EQ(a3._<double>(), 3.14);
}
TEST_F(anyTest, typeChars) {
any a4 = "hello,";
auto expected = "hello,";
EXPECT_EQ(a4._<const char *>(), expected);
}
TEST_F(anyTest, typeVectorInt) {
any a5 = std::vector<int>{6, 5, 4, 3, 2, 1, 0};
auto expected = std::vector<int>{6, 5, 4, 3, 2, 1, 0};
EXPECT_EQ(a5._<std::vector<int>>(), expected);
}
TEST_F(anyTest, typeString) {
any a6 = std::string("world!");
EXPECT_EQ(a6._<std::string>(), "world!");
}
TEST_F(anyTest, typeStruct) {
any a7 = testObject{3};
std::cout << "[7] testObject : " << a7._<testObject>() << std::endl;
EXPECT_TRUE(a7.is<testObject>());
}
<|endoftext|>
|
<commit_before>#include "testsettings.hpp"
#ifdef TEST_COLUMN_DATETIME
#include <realm/column_datetime.hpp>
#include <realm.hpp>
#include "test.hpp"
using namespace realm;
// Test independence and thread-safety
// -----------------------------------
//
// All tests must be thread safe and independent of each other. This
// is required because it allows for both shuffling of the execution
// order and for parallelized testing.
//
// In particular, avoid using std::rand() since it is not guaranteed
// to be thread safe. Instead use the API offered in
// `test/util/random.hpp`.
//
// All files created in tests must use the TEST_PATH macro (or one of
// its friends) to obtain a suitable file system path. See
// `test/util/test_path.hpp`.
//
//
// Debugging and the ONLY() macro
// ------------------------------
//
// A simple way of disabling all tests except one called `Foo`, is to
// replace TEST(Foo) with ONLY(Foo) and then recompile and rerun the
// test suite. Note that you can also use filtering by setting the
// environment varible `UNITTEST_FILTER`. See `README.md` for more on
// this.
//
// Another way to debug a particular test, is to copy that test into
// `experiments/testcase.cpp` and then run `sh build.sh
// check-testcase` (or one of its friends) from the command line.
/*
TEST(DateTimeColumn_Basic)
{
DateTimeColumn c;
c.add(NewDate(123,123));
NewDate ndt = c.get(0);
CHECK(ndt == NewDate(123, 123));
}
*/
TEST(DateTimeColumn_Basic_Nulls)
{
// Test that default value is null() for nullable column and non-null for non-nullable column
Table t;
t.add_column(type_NewDate, "date", false /*nullable*/);
t.add_column(type_NewDate, "date", true /*nullable*/);
t.add_empty_row();
CHECK(!t.is_null(0, 0));
CHECK(t.is_null(1, 0));
CHECK_THROW_ANY(t.set_null(0, 0));
t.set_null(1, 0);
}
TEST(DateTimeColumn_Relocate)
{
// Fill so much data in a column that it relocates, to check if relocation propagates up correctly
Table t;
t.add_column(type_NewDate, "date", true /*nullable*/);
for (size_t i = 0; i < 10000; i++) {
t.add_empty_row();
t.set_newdate(0, i, NewDate(i, i));
}
}
#endif // TEST_COLUMN_DATETIME
<commit_msg>Re-enabled the basic unit test for DateTimeColumn.<commit_after>#include "testsettings.hpp"
#ifdef TEST_COLUMN_DATETIME
#include <realm/column_datetime.hpp>
#include <realm.hpp>
#include "test.hpp"
using namespace realm;
// Test independence and thread-safety
// -----------------------------------
//
// All tests must be thread safe and independent of each other. This
// is required because it allows for both shuffling of the execution
// order and for parallelized testing.
//
// In particular, avoid using std::rand() since it is not guaranteed
// to be thread safe. Instead use the API offered in
// `test/util/random.hpp`.
//
// All files created in tests must use the TEST_PATH macro (or one of
// its friends) to obtain a suitable file system path. See
// `test/util/test_path.hpp`.
//
//
// Debugging and the ONLY() macro
// ------------------------------
//
// A simple way of disabling all tests except one called `Foo`, is to
// replace TEST(Foo) with ONLY(Foo) and then recompile and rerun the
// test suite. Note that you can also use filtering by setting the
// environment varible `UNITTEST_FILTER`. See `README.md` for more on
// this.
//
// Another way to debug a particular test, is to copy that test into
// `experiments/testcase.cpp` and then run `sh build.sh
// check-testcase` (or one of its friends) from the command line.
TEST(DateTimeColumn_Basic)
{
ref_type ref = DateTimeColumn::create(Allocator::get_default());
DateTimeColumn c(Allocator::get_default(), ref);
c.add(NewDate(123,123));
NewDate ndt = c.get(0);
CHECK(ndt == NewDate(123, 123));
}
TEST(DateTimeColumn_Basic_Nulls)
{
// Test that default value is null() for nullable column and non-null for non-nullable column
Table t;
t.add_column(type_NewDate, "date", false /*nullable*/);
t.add_column(type_NewDate, "date", true /*nullable*/);
t.add_empty_row();
CHECK(!t.is_null(0, 0));
CHECK(t.is_null(1, 0));
CHECK_THROW_ANY(t.set_null(0, 0));
t.set_null(1, 0);
}
TEST(DateTimeColumn_Relocate)
{
// Fill so much data in a column that it relocates, to check if relocation propagates up correctly
Table t;
t.add_column(type_NewDate, "date", true /*nullable*/);
for (size_t i = 0; i < 10000; i++) {
t.add_empty_row();
t.set_newdate(0, i, NewDate(i, i));
}
}
#endif // TEST_COLUMN_DATETIME
<|endoftext|>
|
<commit_before>#include <QtTest>
#include <QtCore>
#include <QtNetwork>
#include <Arangodbdriver.h>
using namespace arangodb;
/**
* @brief The StartTest class
*/
class StartTest : public QObject
{
Q_OBJECT
public:
StartTest();
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void testSaveAndDeleteDocument();
void testSaveDocument2Times();
void testPartialUpdate();
private:
/**
* @brief waitForDocumentReady
* @param doc
*/
inline void waitForDocumentReady(Document* doc) {
QEventLoop loop;
connect(doc, &Document::error, &loop, &QEventLoop::quit);
connect(doc, &Document::ready, &loop, &QEventLoop::quit);
loop.exec();
}
/**
* @brief waitForDocumentReady
* @param doc
*/
inline void waitForDocumentDeleted(Document* doc) {
QEventLoop loop;
connect(doc, &Document::error, &loop, &QEventLoop::quit);
connect(doc, &Document::dataDeleted, &loop, &QEventLoop::quit);
loop.exec();
}
};
StartTest::StartTest()
{
}
void StartTest::initTestCase()
{
}
void StartTest::cleanupTestCase()
{
}
/**
* @brief StartTest::testSaveAndDeleteDocument
*/
void StartTest::testSaveAndDeleteDocument()
{
Arangodbdriver driver;
Document *doc = driver.createDocument("test");
// Set fuu with ss
doc->set("fuu", QVariant("ss"));
// Save the document
doc->save();
waitForDocumentReady(doc);
// Check if the flag isCreated is set
Q_ASSERT_X(doc->isCreated(), "testSaveAndDeleteDocument", doc->errorMessage().toLocal8Bit());
// Get the same document from the db again
Document *docFromDb = driver.getDocument(doc->docID());
waitForDocumentReady(docFromDb);
// check if there is really the document
Q_ASSERT_X( !docFromDb->hasErrorOccurred(), "testSaveAndDeleteDocument", docFromDb->errorMessage().toLocal8Bit() );
QCOMPARE( docFromDb->get("fuu").toString(), QString("ss") );
// Delete the test document again
doc->drop();
waitForDocumentDeleted(doc);
// Try get the same document from the db again
docFromDb = driver.getDocument(doc->docID());
waitForDocumentReady(docFromDb);
// check if the document doesn't exist anymore
Q_ASSERT( docFromDb->hasErrorOccurred() );
}
/**
* @brief StartTest::testSaveDocument2Times
*/
void StartTest::testSaveDocument2Times()
{
Arangodbdriver driver;
Document *doc = driver.createDocument("test");
// Save the document
doc->save();
waitForDocumentReady(doc);
// Change the document and save/update
doc->set("lll", QVariant("aaa"));
QCOMPARE(doc->dirtyAttributes().size(), 1);
Q_ASSERT(doc->isEveryAttributeDirty());
doc->save();
waitForDocumentReady(doc);
// check if there wasn't an error
Q_ASSERT_X( !doc->hasErrorOccurred(), "!doc->hasErrorOccurred()", doc->errorMessage().toLocal8Bit() );
// Delete the test document again
doc->drop();
waitForDocumentDeleted(doc);
}
/**
* @brief StartTest::testPartialUpdate
*/
void StartTest::testPartialUpdate()
{
Arangodbdriver driver;
Document *doc = driver.createDocument("test");
doc->set("lll", QVariant("aaa"));
doc->set("dd", QVariant("aaa"));
doc->set("aa", QVariant("aaa"));
// Save the document
doc->save();
waitForDocumentReady(doc);
// Change the document and save/update
doc->set("lll", QVariant("bb"));
QCOMPARE(doc->dirtyAttributes().size(), 1);
Q_ASSERT( !doc->isEveryAttributeDirty() );
doc->save();
waitForDocumentReady(doc);
// check if there wasn't an error
Q_ASSERT_X( !doc->hasErrorOccurred(), "!doc->hasErrorOccurred()", doc->errorMessage().toLocal8Bit() );
// Delete the test document again
doc->drop();
waitForDocumentDeleted(doc);
}
QTEST_MAIN(StartTest)
#include "tst_StartTest.moc"
<commit_msg>Added a test for the status update<commit_after>#include <QtTest>
#include <QtCore>
#include <QtNetwork>
#include <Arangodbdriver.h>
using namespace arangodb;
/**
* @brief The StartTest class
*/
class StartTest : public QObject
{
Q_OBJECT
public:
StartTest();
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void testSaveAndDeleteDocument();
void testSaveDocument2Times();
void testPartialUpdate();
void testHeadOperation();
private:
/**
* @brief waitForDocumentReady
* @param doc
*/
inline void waitForDocumentReady(Document* doc) {
QEventLoop loop;
connect(doc, &Document::error, &loop, &QEventLoop::quit);
connect(doc, &Document::ready, &loop, &QEventLoop::quit);
loop.exec();
}
/**
* @brief waitForDocumentReady
* @param doc
*/
inline void waitForDocumentDeleted(Document* doc) {
QEventLoop loop;
connect(doc, &Document::error, &loop, &QEventLoop::quit);
connect(doc, &Document::dataDeleted, &loop, &QEventLoop::quit);
loop.exec();
}
};
StartTest::StartTest()
{
}
void StartTest::initTestCase()
{
}
void StartTest::cleanupTestCase()
{
}
/**
* @brief StartTest::testSaveAndDeleteDocument
*/
void StartTest::testSaveAndDeleteDocument()
{
Arangodbdriver driver;
Document *doc = driver.createDocument("test");
// Set fuu with ss
doc->set("fuu", QVariant("ss"));
// Save the document
doc->save();
waitForDocumentReady(doc);
// Check if the flag isCreated is set
Q_ASSERT_X(doc->isCreated(), "testSaveAndDeleteDocument", doc->errorMessage().toLocal8Bit());
// Get the same document from the db again
Document *docFromDb = driver.getDocument(doc->docID());
waitForDocumentReady(docFromDb);
// check if there is really the document
Q_ASSERT_X( !docFromDb->hasErrorOccurred(), "testSaveAndDeleteDocument", docFromDb->errorMessage().toLocal8Bit() );
QCOMPARE( docFromDb->get("fuu").toString(), QString("ss") );
// Delete the test document again
doc->drop();
waitForDocumentDeleted(doc);
// Try get the same document from the db again
docFromDb = driver.getDocument(doc->docID());
waitForDocumentReady(docFromDb);
// check if the document doesn't exist anymore
Q_ASSERT( docFromDb->hasErrorOccurred() );
}
/**
* @brief StartTest::testSaveDocument2Times
*/
void StartTest::testSaveDocument2Times()
{
Arangodbdriver driver;
Document *doc = driver.createDocument("test");
// Save the document
doc->save();
waitForDocumentReady(doc);
// Change the document and save/update
doc->set("lll", QVariant("aaa"));
QCOMPARE(doc->dirtyAttributes().size(), 1);
Q_ASSERT(doc->isEveryAttributeDirty());
doc->save();
waitForDocumentReady(doc);
// check if there wasn't an error
Q_ASSERT_X( !doc->hasErrorOccurred(), "!doc->hasErrorOccurred()", doc->errorMessage().toLocal8Bit() );
// Delete the test document again
doc->drop();
waitForDocumentDeleted(doc);
}
/**
* @brief StartTest::testPartialUpdate
*/
void StartTest::testPartialUpdate()
{
Arangodbdriver driver;
Document *doc = driver.createDocument("test");
doc->set("lll", QVariant("aaa"));
doc->set("dd", QVariant("aaa"));
doc->set("aa", QVariant("aaa"));
// Save the document
doc->save();
waitForDocumentReady(doc);
// Change the document and save/update
doc->set("lll", QVariant("bb"));
QCOMPARE(doc->dirtyAttributes().size(), 1);
Q_ASSERT( !doc->isEveryAttributeDirty() );
doc->save();
waitForDocumentReady(doc);
// check if there wasn't an error
Q_ASSERT_X( !doc->hasErrorOccurred(), "!doc->hasErrorOccurred()", doc->errorMessage().toLocal8Bit() );
// Delete the test document again
doc->drop();
waitForDocumentDeleted(doc);
}
void StartTest::testHeadOperation()
{
Arangodbdriver driver;
Document *doc = driver.createDocument("test");
doc->set("lll", QVariant("aaa"));
// Save the document
doc->save();
waitForDocumentReady(doc);
// Try get the same document from the db again
Document *docFromDb = driver.getDocument(doc->docID());
waitForDocumentReady(docFromDb);
docFromDb->updateStatus();
waitForDocumentReady(docFromDb);
QCOMPARE( docFromDb->isCreated(), true );
QCOMPARE( docFromDb->isCurrent(), true );
doc->set("lllmmmm", "fuu");
doc->save();
waitForDocumentReady(doc);
docFromDb->updateStatus();
waitForDocumentReady(docFromDb);
QCOMPARE( docFromDb->isCreated(), true );
QCOMPARE( docFromDb->isCurrent(), false );
doc->drop();
waitForDocumentDeleted(doc);
docFromDb->updateStatus();
waitForDocumentReady(docFromDb);
QCOMPARE( docFromDb->isCreated(), false );
QCOMPARE( docFromDb->isCurrent(), false );
}
QTEST_MAIN(StartTest)
#include "tst_StartTest.moc"
<|endoftext|>
|
<commit_before>// window.cpp
#include <QDebug>
#include <QDir>
#include <math.h>
#include "ui_window.h"
#include "window.hpp"
#include "augmentation_widget.hpp"
#ifndef RES_DIR
#define RES_DIR ""
#endif
Window::Window (QWidget* parent)
: QWidget (parent)
, ui (new Ui::Window) {
_augmentation = new augmentation_widget ();
_augmentation->show ();
ui->setupUi (this);
// fill model selection box
ui->loadBox->addItem ("Select Model");
QDir path (":/3D_models/");
QStringList files = path.entryList (QDir::Files);
ui->loadBox->addItems (files);
connect (ui->loadBox, SIGNAL (currentIndexChanged (QString)), this,
SLOT (loadBox_indexchanged (QString)));
connect (ui->texButton, SIGNAL (clicked ()), this, SLOT (texButton_clicked ()));
connect (ui->scaleSlider, SIGNAL (valueChanged (int)), this,
SLOT (scaleSlider_valueChanged (int)));
connect (ui->posXSlider, SIGNAL (valueChanged (int)), this,
SLOT (posXSlider_valueChanged (int)));
connect (ui->posYSlider, SIGNAL (valueChanged (int)), this,
SLOT (posYSlider_valueChanged (int)));
connect (ui->rotXSlider, SIGNAL (valueChanged (int)), this,
SLOT (rotXSlider_valueChanged (int)));
connect (ui->rotYSlider, SIGNAL (valueChanged (int)), this,
SLOT (rotYSlider_valueChanged (int)));
connect (ui->rotZSlider, SIGNAL (valueChanged (int)), this,
SLOT (rotZSlider_valueChanged (int)));
}
Window::~Window () {
delete _augmentation;
delete ui;
}
void Window::keyPressEvent (QKeyEvent* e) {
if (e->key () == Qt::Key_Escape)
close ();
else
QWidget::keyPressEvent (e);
}
void Window::loadBox_indexchanged (QString selection) {
_augmentation->loadObject (selection.prepend (":/3D_models/"));
_augmentation->update ();
}
void Window::texButton_clicked () {
QImage image_qt;
image_t image;
if (image_qt.load (":/debug_samples/textest.png")) {
size_t size = image_qt.width () * image_qt.height ();
image_qt = image_qt.convertToFormat (QImage::Format_RGB888);
image.data = (uint8_t*)malloc (size * 3);
memcpy (image.data, image_qt.bits (), size * 3);
image.format = RGB24;
image.height = image_qt.height ();
image.width = image_qt.width ();
_augmentation->setBackground (image);
} else {
qDebug () << "no image";
}
}
void Window::scaleSlider_valueChanged (int new_value) {
_augmentation->setScale (((float)new_value) / 100);
_augmentation->update ();
}
void Window::posXSlider_valueChanged (int new_value) {
_augmentation->setXPosition (((float)new_value) / 100);
_augmentation->update ();
}
void Window::posYSlider_valueChanged (int new_value) {
_augmentation->setYPosition (((float)new_value) / 100);
_augmentation->update ();
}
void Window::rotXSlider_valueChanged (int new_value) {
_augmentation->setXRotation (new_value);
_augmentation->update ();
}
void Window::rotYSlider_valueChanged (int new_value) {
_augmentation->setYRotation (new_value);
_augmentation->update ();
}
void Window::rotZSlider_valueChanged (int new_value) {
_augmentation->setZRotation (new_value);
_augmentation->update ();
}
/*derived from https://www.opengl.org/sdk/docs/man2/xhtml/glRotate.xml*/
void Window::angle_to_matrix (float mat[16], float angle, float x, float y, float z) {
float deg2rad = 3.14159265f / 180.0f;
float c = cosf (angle * deg2rad);
float s = sinf (angle * deg2rad);
float c1 = 1.0f - c;
// build rotation matrix
mat[0] = (x * x * c1) + c;
mat[1] = (x * y * c1) - (z * s);
mat[2] = (x * z * c1) + (y * s);
mat[3] = 0;
mat[4] = (y * x * c1) + (z * s);
mat[5] = (y * y * c1) + c;
mat[6] = (y * z * c1) - (x * s);
mat[7] = 0;
mat[8] = (z * x * c1) - (y * s);
mat[9] = (z * y * c1) + (x * s);
mat[10] = (z * z * c1) + c;
mat[11] = 0;
mat[12] = 0;
mat[13] = 0;
mat[14] = 0;
mat[15] = 1;
}
<commit_msg>change test to update after texture change<commit_after>// window.cpp
#include <QDebug>
#include <QDir>
#include <math.h>
#include "ui_window.h"
#include "window.hpp"
#include "augmentation_widget.hpp"
#ifndef RES_DIR
#define RES_DIR ""
#endif
Window::Window (QWidget* parent)
: QWidget (parent)
, ui (new Ui::Window) {
_augmentation = new augmentation_widget ();
_augmentation->show ();
ui->setupUi (this);
// fill model selection box
ui->loadBox->addItem ("Select Model");
QDir path (":/3D_models/");
QStringList files = path.entryList (QDir::Files);
ui->loadBox->addItems (files);
connect (ui->loadBox, SIGNAL (currentIndexChanged (QString)), this,
SLOT (loadBox_indexchanged (QString)));
connect (ui->texButton, SIGNAL (clicked ()), this, SLOT (texButton_clicked ()));
connect (ui->scaleSlider, SIGNAL (valueChanged (int)), this,
SLOT (scaleSlider_valueChanged (int)));
connect (ui->posXSlider, SIGNAL (valueChanged (int)), this,
SLOT (posXSlider_valueChanged (int)));
connect (ui->posYSlider, SIGNAL (valueChanged (int)), this,
SLOT (posYSlider_valueChanged (int)));
connect (ui->rotXSlider, SIGNAL (valueChanged (int)), this,
SLOT (rotXSlider_valueChanged (int)));
connect (ui->rotYSlider, SIGNAL (valueChanged (int)), this,
SLOT (rotYSlider_valueChanged (int)));
connect (ui->rotZSlider, SIGNAL (valueChanged (int)), this,
SLOT (rotZSlider_valueChanged (int)));
}
Window::~Window () {
delete _augmentation;
delete ui;
}
void Window::keyPressEvent (QKeyEvent* e) {
if (e->key () == Qt::Key_Escape)
close ();
else
QWidget::keyPressEvent (e);
}
void Window::loadBox_indexchanged (QString selection) {
_augmentation->loadObject (selection.prepend (":/3D_models/"));
_augmentation->update ();
}
void Window::texButton_clicked () {
QImage image_qt;
image_t image;
if (image_qt.load (":/debug_samples/textest.png")) {
size_t size = image_qt.width () * image_qt.height ();
image_qt = image_qt.convertToFormat (QImage::Format_RGB888);
image.data = (uint8_t*)malloc (size * 3);
memcpy (image.data, image_qt.bits (), size * 3);
image.format = RGB24;
image.height = image_qt.height ();
image.width = image_qt.width ();
_augmentation->setBackground (image);
_augmentation->update ();
} else {
qDebug () << "no image";
}
}
void Window::scaleSlider_valueChanged (int new_value) {
_augmentation->setScale (((float)new_value) / 100);
_augmentation->update ();
}
void Window::posXSlider_valueChanged (int new_value) {
_augmentation->setXPosition (((float)new_value) / 100);
_augmentation->update ();
}
void Window::posYSlider_valueChanged (int new_value) {
_augmentation->setYPosition (((float)new_value) / 100);
_augmentation->update ();
}
void Window::rotXSlider_valueChanged (int new_value) {
_augmentation->setXRotation (new_value);
_augmentation->update ();
}
void Window::rotYSlider_valueChanged (int new_value) {
_augmentation->setYRotation (new_value);
_augmentation->update ();
}
void Window::rotZSlider_valueChanged (int new_value) {
_augmentation->setZRotation (new_value);
_augmentation->update ();
}
/*derived from https://www.opengl.org/sdk/docs/man2/xhtml/glRotate.xml*/
void Window::angle_to_matrix (float mat[16], float angle, float x, float y, float z) {
float deg2rad = 3.14159265f / 180.0f;
float c = cosf (angle * deg2rad);
float s = sinf (angle * deg2rad);
float c1 = 1.0f - c;
// build rotation matrix
mat[0] = (x * x * c1) + c;
mat[1] = (x * y * c1) - (z * s);
mat[2] = (x * z * c1) + (y * s);
mat[3] = 0;
mat[4] = (y * x * c1) + (z * s);
mat[5] = (y * y * c1) + c;
mat[6] = (y * z * c1) - (x * s);
mat[7] = 0;
mat[8] = (z * x * c1) - (y * s);
mat[9] = (z * y * c1) + (x * s);
mat[10] = (z * z * c1) + c;
mat[11] = 0;
mat[12] = 0;
mat[13] = 0;
mat[14] = 0;
mat[15] = 1;
}
<|endoftext|>
|
<commit_before>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#include "MediaFile.h"
#include <iostream>
#include <string>
#include <algorithm>
#ifdef WIN32
void ConvertPath(std::string &path)
{
std::replace(path.begin(), path.end(), '/', '\\');
}
#endif
//
// MediaFile
//
MediaFile::MediaFile(std::istream* _stream) : stream(_stream)
{
// do nothing
}
MediaFile::~MediaFile()
{
// do nothing
}
bool MediaFile::isOkay() const
{
return (stream != NULL && stream->good());
}
void MediaFile::readRaw(void* vbuffer, uint32_t bytes)
{
char* buffer = reinterpret_cast<char*>(vbuffer);
stream->read(buffer, bytes);
}
void MediaFile::skip(uint32_t bytes)
{
stream->ignore(bytes);
}
uint16_t MediaFile::read16LE()
{
uint16_t b;
stream->read(reinterpret_cast<char*>(&b), sizeof(b));
return swap16LE(&b);
}
uint16_t MediaFile::read16BE()
{
uint16_t b;
stream->read(reinterpret_cast<char*>(&b), sizeof(b));
return swap16BE(&b);
}
uint32_t MediaFile::read32LE()
{
uint32_t b;
stream->read(reinterpret_cast<char*>(&b), sizeof(b));
return swap32LE(&b);
}
uint32_t MediaFile::read32BE()
{
uint32_t b;
stream->read(reinterpret_cast<char*>(&b), sizeof(b));
return swap32BE(&b);
}
uint16_t MediaFile::swap16LE(uint16_t* d)
{
unsigned char* b = reinterpret_cast<unsigned char*>(d);
*d = static_cast<uint16_t>(b[0]) + (static_cast<uint16_t>(b[1]) << 8);
return *d;
}
uint16_t MediaFile::swap16BE(uint16_t* d)
{
unsigned char* b = reinterpret_cast<unsigned char*>(d);
*d = static_cast<uint16_t>(b[1]) + (static_cast<uint16_t>(b[0]) << 8);
return *d;
}
uint32_t MediaFile::swap32LE(uint32_t* d)
{
unsigned char* b = reinterpret_cast<unsigned char*>(d);
*d = static_cast<uint32_t>(b[0]) + (static_cast<uint32_t>(b[1]) << 8) +
(static_cast<uint32_t>(b[2]) << 16) +
(static_cast<uint32_t>(b[3]) << 24);
return *d;
}
uint32_t MediaFile::swap32BE(uint32_t* d)
{
unsigned char* b = reinterpret_cast<unsigned char*>(d);
*d = static_cast<uint32_t>(b[3]) + (static_cast<uint32_t>(b[2]) << 8) +
(static_cast<uint32_t>(b[1]) << 16) +
(static_cast<uint32_t>(b[0]) << 24);
return *d;
}
//
// utility methods to read various media files in any supported format
//
#include "FileManager.h"
#include "SGIImageFile.h"
#include "PNGImageFile.h"
#include "WaveAudioFile.h"
#define OPENMEDIA(_T) \
do { \
stream = FILEMGR.createDataInStream(filename, true); \
if (stream == NULL) \
stream = FILEMGR.createDataInStream(filename + \
_T::getExtension(), true); \
if (stream != NULL) { \
file = new _T(stream); \
if (!file->isOpen()) { \
file = NULL; \
delete stream; \
stream = NULL; \
} \
} \
} while (0)
unsigned char* MediaFile::readImage(
std::string filename,
int* width, int* height)
{
#ifdef WIN32
// cheat and make sure the file is a windows file path
ConvertPath(filename);
#endif //WIN32
// try opening file as an image
std::istream* stream;
ImageFile* file = NULL;
if (file == NULL)
OPENMEDIA(PNGImageFile);
if (file == NULL)
OPENMEDIA(SGIImageFile);
// read the image
unsigned char* image = NULL;
if (file != NULL) {
// get the image size
int dx = *width = file->getWidth();
int dy = *height = file->getHeight();
int dz = file->getNumChannels();
// make buffer for final image
image = new unsigned char[dx * dy * 4];
// make buffer to read image. if the image file has 4 channels
// then read directly into the final image buffer.
unsigned char* buffer = (dz == 4) ? image : new unsigned char[dx * dy * dz];
// read the image
if (image != NULL && buffer != NULL) {
if (!file->read(buffer)) {
// failed to read image. clean up.
if (buffer != image)
delete[] buffer;
delete[] image;
image = NULL;
buffer = NULL;
} else {
// expand image into 4 channels
int n = dx * dy;
const unsigned char* src = buffer;
unsigned char* dst = image;
if (dz == 1) {
// r=g=b=i, a=max
for (; n > 0; --n) {
dst[0] = dst[1] = dst[2] = src[0];
dst[3] = 0xff;
src += 1;
dst += 4;
}
} else if (dz == 2) {
// r=g=b=i
for (; n > 0; --n) {
dst[0] = dst[1] = dst[2] = src[0];
dst[3] = src[1];
src += 2;
dst += 4;
}
} else if (dz == 3) {
// a=max
for (; n > 0; --n) {
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst[3] = 0xff;
src += 3;
dst += 4;
}
}
}
}
// clean up
if (buffer != image)
delete[] buffer;
delete file;
}
// clean up
delete stream;
return image;
}
/*
float* MediaFile::readSound(
const std::string& filename,
int* _numFrames, int* rate)
{
// try opening as an audio file
std::istream* stream;
AudioFile* file = NULL;
if (file == NULL)
OPENMEDIA(WaveAudioFile);
// read the audio
float* audio = NULL;
if (file != NULL) {
// get the audio info
*rate = file->getFramesPerSecond();
int numChannels = file->getNumChannels();
int numFrames = file->getNumFrames();
int sampleWidth = file->getSampleWidth();
// make a buffer to read into
unsigned char* raw = new unsigned char[numFrames * numChannels * sampleWidth];
// read raw samples
if (file->read(raw, numFrames)) {
// prepare conversion parameters
int step = 1;
#if defined(HALF_RATE_AUDIO)
step *= 2;
numFrames /= 2;
*rate /= 2;
#endif
// make final audio buffer
audio = new float[2 * numFrames];
// convert
if (numChannels == 1) {
if (sampleWidth == 1) {
signed char* src = reinterpret_cast<signed char*>(raw);
for (int i = 0; i < numFrames; ++i) {
audio[2 * i] = audio[2 * i + 1] = 257.0f * static_cast<float>(*src);
src += step;
}
} else {
int16_t* src = reinterpret_cast<int16_t*>(raw);
for (int i = 0; i < numFrames; ++i) {
audio[2 * i] = audio[2 * i + 1] = static_cast<float>(*src);
src += step;
}
}
} else {
step *= 2;
if (sampleWidth == 1) {
signed char* src = reinterpret_cast<signed char*>(raw);
for (int i = 0; i < numFrames; ++i) {
audio[2 * i] = 257.0f * static_cast<float>(src[0]);
audio[2 * i + 1] = 257.0f * static_cast<float>(src[1]);
src += step;
}
} else {
int16_t* src = reinterpret_cast<int16_t*>(raw);
for (int i = 0; i < numFrames; ++i) {
audio[2 * i] = static_cast<float>(src[0]);
audio[2 * i + 1] = static_cast<float>(src[1]);
src += step;
}
}
}
}
// clean up
delete[] raw;
delete file;
*_numFrames = numFrames;
}
// clean up
delete stream;
return audio;
}
*/
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>- loadTexture() can now use cached textures from their URL names. (ex: BZDB _rainTexture and _rainPuddleTexture). These textures can be signalled for downloading using unbound materials. Let it rain cats and dogs...<commit_after>/* bzflag
* Copyright (c) 1993 - 2005 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named LICENSE that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// implementation header
#include "CacheManager.h"
// system headers
#include <iostream>
#include <string>
#include <algorithm>
// common headers
#include "MediaFile.h"
#ifdef WIN32
void ConvertPath(std::string &path)
{
std::replace(path.begin(), path.end(), '/', '\\');
}
#endif
//
// MediaFile
//
MediaFile::MediaFile(std::istream* _stream) : stream(_stream)
{
// do nothing
}
MediaFile::~MediaFile()
{
// do nothing
}
bool MediaFile::isOkay() const
{
return (stream != NULL && stream->good());
}
void MediaFile::readRaw(void* vbuffer, uint32_t bytes)
{
char* buffer = reinterpret_cast<char*>(vbuffer);
stream->read(buffer, bytes);
}
void MediaFile::skip(uint32_t bytes)
{
stream->ignore(bytes);
}
uint16_t MediaFile::read16LE()
{
uint16_t b;
stream->read(reinterpret_cast<char*>(&b), sizeof(b));
return swap16LE(&b);
}
uint16_t MediaFile::read16BE()
{
uint16_t b;
stream->read(reinterpret_cast<char*>(&b), sizeof(b));
return swap16BE(&b);
}
uint32_t MediaFile::read32LE()
{
uint32_t b;
stream->read(reinterpret_cast<char*>(&b), sizeof(b));
return swap32LE(&b);
}
uint32_t MediaFile::read32BE()
{
uint32_t b;
stream->read(reinterpret_cast<char*>(&b), sizeof(b));
return swap32BE(&b);
}
uint16_t MediaFile::swap16LE(uint16_t* d)
{
unsigned char* b = reinterpret_cast<unsigned char*>(d);
*d = static_cast<uint16_t>(b[0]) + (static_cast<uint16_t>(b[1]) << 8);
return *d;
}
uint16_t MediaFile::swap16BE(uint16_t* d)
{
unsigned char* b = reinterpret_cast<unsigned char*>(d);
*d = static_cast<uint16_t>(b[1]) + (static_cast<uint16_t>(b[0]) << 8);
return *d;
}
uint32_t MediaFile::swap32LE(uint32_t* d)
{
unsigned char* b = reinterpret_cast<unsigned char*>(d);
*d = static_cast<uint32_t>(b[0]) + (static_cast<uint32_t>(b[1]) << 8) +
(static_cast<uint32_t>(b[2]) << 16) +
(static_cast<uint32_t>(b[3]) << 24);
return *d;
}
uint32_t MediaFile::swap32BE(uint32_t* d)
{
unsigned char* b = reinterpret_cast<unsigned char*>(d);
*d = static_cast<uint32_t>(b[3]) + (static_cast<uint32_t>(b[2]) << 8) +
(static_cast<uint32_t>(b[1]) << 16) +
(static_cast<uint32_t>(b[0]) << 24);
return *d;
}
//
// utility methods to read various media files in any supported format
//
#include "FileManager.h"
#include "SGIImageFile.h"
#include "PNGImageFile.h"
#include "WaveAudioFile.h"
#define OPENMEDIA(_T) \
do { \
stream = FILEMGR.createDataInStream(filename, true); \
if (stream == NULL) \
stream = FILEMGR.createDataInStream(filename + \
_T::getExtension(), true); \
if (stream != NULL) { \
file = new _T(stream); \
if (!file->isOpen()) { \
file = NULL; \
delete stream; \
stream = NULL; \
} \
} \
} while (0)
unsigned char* MediaFile::readImage(
std::string filename,
int* width, int* height)
{
// get the absolute filename for cache textures
if (CACHEMGR.isCacheFileType(filename)) {
filename = CACHEMGR.getLocalName(filename);
}
#ifdef WIN32
// cheat and make sure the file is a windows file path
ConvertPath(filename);
#endif //WIN32
// try opening file as an image
std::istream* stream;
ImageFile* file = NULL;
if (file == NULL)
OPENMEDIA(PNGImageFile);
if (file == NULL)
OPENMEDIA(SGIImageFile);
// read the image
unsigned char* image = NULL;
if (file != NULL) {
// get the image size
int dx = *width = file->getWidth();
int dy = *height = file->getHeight();
int dz = file->getNumChannels();
// make buffer for final image
image = new unsigned char[dx * dy * 4];
// make buffer to read image. if the image file has 4 channels
// then read directly into the final image buffer.
unsigned char* buffer = (dz == 4) ? image : new unsigned char[dx * dy * dz];
// read the image
if (image != NULL && buffer != NULL) {
if (!file->read(buffer)) {
// failed to read image. clean up.
if (buffer != image)
delete[] buffer;
delete[] image;
image = NULL;
buffer = NULL;
} else {
// expand image into 4 channels
int n = dx * dy;
const unsigned char* src = buffer;
unsigned char* dst = image;
if (dz == 1) {
// r=g=b=i, a=max
for (; n > 0; --n) {
dst[0] = dst[1] = dst[2] = src[0];
dst[3] = 0xff;
src += 1;
dst += 4;
}
} else if (dz == 2) {
// r=g=b=i
for (; n > 0; --n) {
dst[0] = dst[1] = dst[2] = src[0];
dst[3] = src[1];
src += 2;
dst += 4;
}
} else if (dz == 3) {
// a=max
for (; n > 0; --n) {
dst[0] = src[0];
dst[1] = src[1];
dst[2] = src[2];
dst[3] = 0xff;
src += 3;
dst += 4;
}
}
}
}
// clean up
if (buffer != image)
delete[] buffer;
delete file;
}
// clean up
delete stream;
return image;
}
/*
float* MediaFile::readSound(
const std::string& filename,
int* _numFrames, int* rate)
{
// try opening as an audio file
std::istream* stream;
AudioFile* file = NULL;
if (file == NULL)
OPENMEDIA(WaveAudioFile);
// read the audio
float* audio = NULL;
if (file != NULL) {
// get the audio info
*rate = file->getFramesPerSecond();
int numChannels = file->getNumChannels();
int numFrames = file->getNumFrames();
int sampleWidth = file->getSampleWidth();
// make a buffer to read into
unsigned char* raw = new unsigned char[numFrames * numChannels * sampleWidth];
// read raw samples
if (file->read(raw, numFrames)) {
// prepare conversion parameters
int step = 1;
#if defined(HALF_RATE_AUDIO)
step *= 2;
numFrames /= 2;
*rate /= 2;
#endif
// make final audio buffer
audio = new float[2 * numFrames];
// convert
if (numChannels == 1) {
if (sampleWidth == 1) {
signed char* src = reinterpret_cast<signed char*>(raw);
for (int i = 0; i < numFrames; ++i) {
audio[2 * i] = audio[2 * i + 1] = 257.0f * static_cast<float>(*src);
src += step;
}
} else {
int16_t* src = reinterpret_cast<int16_t*>(raw);
for (int i = 0; i < numFrames; ++i) {
audio[2 * i] = audio[2 * i + 1] = static_cast<float>(*src);
src += step;
}
}
} else {
step *= 2;
if (sampleWidth == 1) {
signed char* src = reinterpret_cast<signed char*>(raw);
for (int i = 0; i < numFrames; ++i) {
audio[2 * i] = 257.0f * static_cast<float>(src[0]);
audio[2 * i + 1] = 257.0f * static_cast<float>(src[1]);
src += step;
}
} else {
int16_t* src = reinterpret_cast<int16_t*>(raw);
for (int i = 0; i < numFrames; ++i) {
audio[2 * i] = static_cast<float>(src[0]);
audio[2 * i + 1] = static_cast<float>(src[1]);
src += step;
}
}
}
}
// clean up
delete[] raw;
delete file;
*_numFrames = numFrames;
}
// clean up
delete stream;
return audio;
}
*/
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: dinfedt.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: pb $ $Date: 2001-06-28 13:44:05 $
*
* 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
#include "dinfedt.hxx"
#include "sfxresid.hxx"
#include "sfx.hrc"
#include "dinfedt.hrc"
// class InfoEdit_Impl ---------------------------------------------------
void InfoEdit_Impl::KeyInput( const KeyEvent& rKEvent )
{
if ( rKEvent.GetCharCode() != '~' )
Edit::KeyInput( rKEvent );
}
// class SfxDocInfoEditDlg -----------------------------------------------
SfxDocInfoEditDlg::SfxDocInfoEditDlg( Window* pParent ) :
ModalDialog( pParent, SfxResId( DLG_DOCINFO_EDT ) ),
aInfoFL ( this, ResId( FL_INFO ) ),
aInfo1ED ( this, ResId( ED_INFO1 ) ),
aInfo2ED ( this, ResId( ED_INFO2 ) ),
aInfo3ED ( this, ResId( ED_INFO3 ) ),
aInfo4ED ( this, ResId( ED_INFO4 ) ),
aOkBT ( this, ResId( BT_OK ) ),
aCancelBT ( this, ResId( BT_CANCEL ) ),
aHelpBtn ( this, ResId( BTN_HELP ) )
{
FreeResource();
}
<commit_msg>INTEGRATION: CWS ooo20040329 (1.2.464); FILE MERGED 2004/03/18 10:36:43 waratah 1.2.464.1: :#i1858# exclude pragma hdrstop by bracketting for gcc<commit_after>/*************************************************************************
*
* $RCSfile: dinfedt.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: svesik $ $Date: 2004-04-21 13:11:22 $
*
* 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 GCC
#pragma hdrstop
#endif
#include "dinfedt.hxx"
#include "sfxresid.hxx"
#include "sfx.hrc"
#include "dinfedt.hrc"
// class InfoEdit_Impl ---------------------------------------------------
void InfoEdit_Impl::KeyInput( const KeyEvent& rKEvent )
{
if ( rKEvent.GetCharCode() != '~' )
Edit::KeyInput( rKEvent );
}
// class SfxDocInfoEditDlg -----------------------------------------------
SfxDocInfoEditDlg::SfxDocInfoEditDlg( Window* pParent ) :
ModalDialog( pParent, SfxResId( DLG_DOCINFO_EDT ) ),
aInfoFL ( this, ResId( FL_INFO ) ),
aInfo1ED ( this, ResId( ED_INFO1 ) ),
aInfo2ED ( this, ResId( ED_INFO2 ) ),
aInfo3ED ( this, ResId( ED_INFO3 ) ),
aInfo4ED ( this, ResId( ED_INFO4 ) ),
aOkBT ( this, ResId( BT_OK ) ),
aCancelBT ( this, ResId( BT_CANCEL ) ),
aHelpBtn ( this, ResId( BTN_HELP ) )
{
FreeResource();
}
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2019 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//
#include "win_storage_native_target.h"
#include <target_windows_storage_config.h>
#include <nanoHAL_Windows_Storage.h>
#include <target_platform.h>
#include "Esp32_DeviceMapping.h"
// Defines for Windows.Storage.c
extern "C"
{
bool Storage_InitSDCardSPI(char * vfsName, int maxFiles, int pin_Miso, int pin_Mosi, int pin_Clk, int pin_Cs);
bool Storage_InitSDCardMMC(char * vfsName, int maxFiles, bool bit1Mode);
bool Storage_UnMountSDCard();
}
HRESULT Library_win_storage_native_Windows_Storage_Devices_SDCard::MountMMCNative___STATIC__VOID__BOOLEAN(CLR_RT_StackFrame& stack)
{
NANOCLR_HEADER();
#if defined(HAL_USE_SDC)
bool bit1Mode = stack.Arg0().NumericByRef().s4;
char mountPoint[] = INDEX0_DRIVE_LETTER;
// Change fatfs drive letter to mount point D: -> /D
mountPoint[1] = mountPoint[0];
mountPoint[0] = '/';
// Try mounting
if (!Storage_InitSDCardMMC(mountPoint, SDC_MAX_OPEN_FILES, bit1Mode) )
{
NANOCLR_SET_AND_LEAVE(CLR_E_VOLUME_NOT_FOUND);
}
#else
NANOCLR_SET_AND_LEAVE(stack.NotImplementedStub());
#endif
NANOCLR_NOCLEANUP();
}
HRESULT Library_win_storage_native_Windows_Storage_Devices_SDCard::MountSpiNative___STATIC__VOID__I4__I4(CLR_RT_StackFrame& stack)
{
NANOCLR_HEADER();
#if defined(HAL_USE_SDC)
int spiBus;
uint32_t CSPin;
char mountPoint[] = INDEX0_DRIVE_LETTER;
// Change fatfs drive letter to mount point D: -> /D
mountPoint[1] = mountPoint[0];
mountPoint[0] = '/';
// Get passed SPi bus number
spiBus = stack.Arg0().NumericByRef().s4;
// get Gpio pin for Chip select
CSPin = stack.Arg1().NumericByRef().s4;
// Get current gpio pins used by SPI device
int mosiPin = Esp32_GetMappedDevicePins(DEV_TYPE_SPI, spiBus, 0);
int misoPin = Esp32_GetMappedDevicePins(DEV_TYPE_SPI, spiBus, 1);
int clockPin = Esp32_GetMappedDevicePins(DEV_TYPE_SPI, spiBus, 2);
// Try mounting
if ( !Storage_InitSDCardSPI(mountPoint, SDC_MAX_OPEN_FILES, misoPin, mosiPin, clockPin, CSPin) )
{
NANOCLR_SET_AND_LEAVE(CLR_E_VOLUME_NOT_FOUND);
}
#else
(void)stack;
NANOCLR_SET_AND_LEAVE(stack.NotImplementedStub());
#endif
NANOCLR_NOCLEANUP();
}
HRESULT Library_win_storage_native_Windows_Storage_Devices_SDCard::UnmountNative___STATIC__VOID(CLR_RT_StackFrame& stack)
{
NANOCLR_HEADER();
(void)stack;
#if defined(HAL_USE_SDC)
// Unmount SPI device
if (!Storage_UnMountSDCard())
{
// SDcard not mounted
NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_OPERATION);
}
#else
NANOCLR_SET_AND_LEAVE(stack.NotImplementedStub());
#endif
NANOCLR_NOCLEANUP();
}
<commit_msg>Spi SDcard fix (#1444)<commit_after>//
// Copyright (c) 2019 The nanoFramework project contributors
// See LICENSE file in the project root for full license information.
//
#include "win_storage_native_target.h"
#include <target_windows_storage_config.h>
#include <nanoHAL_Windows_Storage.h>
#include <target_platform.h>
#include "Esp32_DeviceMapping.h"
// Defines for Windows.Storage.c
extern "C"
{
bool Storage_InitSDCardSPI(char * vfsName, int maxFiles, int pin_Miso, int pin_Mosi, int pin_Clk, int pin_Cs);
bool Storage_InitSDCardMMC(char * vfsName, int maxFiles, bool bit1Mode);
bool Storage_UnMountSDCard();
}
HRESULT Library_win_storage_native_Windows_Storage_Devices_SDCard::MountMMCNative___STATIC__VOID__BOOLEAN(CLR_RT_StackFrame& stack)
{
NANOCLR_HEADER();
#if defined(HAL_USE_SDC)
bool bit1Mode = stack.Arg0().NumericByRef().s4;
char mountPoint[] = INDEX0_DRIVE_LETTER;
// Change fatfs drive letter to mount point D: -> /D
mountPoint[1] = mountPoint[0];
mountPoint[0] = '/';
// Try mounting
if (!Storage_InitSDCardMMC(mountPoint, SDC_MAX_OPEN_FILES, bit1Mode) )
{
NANOCLR_SET_AND_LEAVE(CLR_E_VOLUME_NOT_FOUND);
}
#else
NANOCLR_SET_AND_LEAVE(stack.NotImplementedStub());
#endif
NANOCLR_NOCLEANUP();
}
HRESULT Library_win_storage_native_Windows_Storage_Devices_SDCard::MountSpiNative___STATIC__VOID__I4__I4(CLR_RT_StackFrame& stack)
{
NANOCLR_HEADER();
#if defined(HAL_USE_SDC)
int spiBus;
uint32_t CSPin;
char mountPoint[] = INDEX0_DRIVE_LETTER;
// Change fatfs drive letter to mount point D: -> /D
mountPoint[1] = mountPoint[0];
mountPoint[0] = '/';
// Get passed SPi bus number 1 or 2
spiBus = stack.Arg0().NumericByRef().s4;
// get Gpio pin for Chip select
CSPin = stack.Arg1().NumericByRef().s4;
// Get current gpio pins used by SPI device
spiBus--; // Spi devnumber 0 & 1
int mosiPin = Esp32_GetMappedDevicePins(DEV_TYPE_SPI, spiBus, 0);
int misoPin = Esp32_GetMappedDevicePins(DEV_TYPE_SPI, spiBus, 1);
int clockPin = Esp32_GetMappedDevicePins(DEV_TYPE_SPI, spiBus, 2);
// Try mounting
if ( !Storage_InitSDCardSPI(mountPoint, SDC_MAX_OPEN_FILES, misoPin, mosiPin, clockPin, CSPin) )
{
NANOCLR_SET_AND_LEAVE(CLR_E_VOLUME_NOT_FOUND);
}
#else
(void)stack;
NANOCLR_SET_AND_LEAVE(stack.NotImplementedStub());
#endif
NANOCLR_NOCLEANUP();
}
HRESULT Library_win_storage_native_Windows_Storage_Devices_SDCard::UnmountNative___STATIC__VOID(CLR_RT_StackFrame& stack)
{
NANOCLR_HEADER();
(void)stack;
#if defined(HAL_USE_SDC)
// Unmount SPI device
if (!Storage_UnMountSDCard())
{
// SDcard not mounted
NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_OPERATION);
}
#else
NANOCLR_SET_AND_LEAVE(stack.NotImplementedStub());
#endif
NANOCLR_NOCLEANUP();
}
<|endoftext|>
|
<commit_before>#define FEBIRD_HAS_INHERITING_CONSTRUCTORS
<commit_msg>git rm src/nark/my_auto_config.hpp<commit_after><|endoftext|>
|
<commit_before>#include "util/bitmap.h"
#include "network.h"
#include "chat_server.h"
#include "chat.h"
#include "util/bitmap.h"
#include "util/funcs.h"
#include "util/keyboard.h"
#include "util/font.h"
#include "globals.h"
#include "init.h"
#include <iostream>
#include <signal.h>
using namespace std;
static const char * DEFAULT_FONT = "/fonts/arial.ttf";
Client::Client( Network::Socket socket, ChatServer * server, unsigned int id ):
socket( socket ),
server( server ),
id( id ),
alive( true ){
pthread_mutex_init( &lock, NULL );
}
Client::~Client(){
}
string Client::getName(){
string s;
pthread_mutex_lock( &lock );
s = name;
pthread_mutex_unlock( &lock );
return s;
}
void Client::kill(){
pthread_mutex_lock( &lock );
alive = false;
pthread_mutex_unlock( &lock );
}
bool Client::isAlive(){
bool b;
pthread_mutex_lock( &lock );
b = alive;
pthread_mutex_unlock( &lock );
return b;
}
void Client::setName( const std::string & s ){
pthread_mutex_lock( &lock );
name = s;
pthread_mutex_unlock( &lock );
}
static void * clientInput( void * client_ ){
Client * client = (Client *) client_;
bool done = false;
while ( ! done ){
try{
Network::Message message( client->getSocket() );
Global::debug( 1 ) << "Got a message: '" << message.path << "'" << endl;
int type;
message >> type;
switch ( type ){
case CHANGE_NAME : {
message << client->getId();
client->getServer()->sendMessage( message, client->getId() );
client->setName( message.path );
client->getServer()->needUpdate();
break;
}
case ADD_MESSAGE : {
client->getServer()->addMessage( client->getName() + ":" + message.path, client->getId() );
break;
}
}
done = ! client->isAlive();
} catch ( const Network::NetworkException & e ){
Global::debug( 0 ) << "Client input " << client->getId() << " died" << endl;
done = true;
}
}
if ( client->isAlive() ){
client->getServer()->killClient( client );
}
return NULL;
}
static void * clientOutput( void * client_ ){
Client * client = (Client *) client_;
bool done = false;
while ( ! done ){
Network::Message message;
done = ! client->isAlive();
if ( client->getOutgoing( message ) != false ){
Global::debug( 1 ) << "Sending a message to " << client->getId() << endl;
try{
/*
Network::Message net;
net.path = message;
net.send( client->getSocket() );
*/
message.send( client->getSocket() );
} catch ( const Network::NetworkException & e ){
Global::debug( 0 ) << "Client output " << client->getId() << " died" << endl;
done = true;
}
} else {
Util::rest( 1 );
}
}
if ( client->isAlive() ){
client->getServer()->killClient( client );
}
return NULL;
}
bool Client::getOutgoing( Network::Message & m ){
bool has;
pthread_mutex_lock( &lock );
has = ! outgoing.empty();
if ( has ){
m = outgoing.front();
outgoing.erase( outgoing.begin() );
}
pthread_mutex_unlock( &lock );
return has;
}
void Client::addOutputMessage( const Network::Message & s ){
pthread_mutex_lock( &lock );
outgoing.push_back( s );
pthread_mutex_unlock( &lock );
}
void Client::startThreads(){
pthread_create( &inputThread, NULL, clientInput, this );
pthread_create( &outputThread, NULL, clientOutput, this );
}
static void * acceptConnections( void * server_ ){
bool done = false;
ChatServer * server = (ChatServer *) server_;
Network::Socket socket = server->getSocket();
while ( ! done ){
try{
server->addConnection( Network::accept( socket ) );
} catch ( const Network::NoConnectionsPendingException & e ){
} catch ( const Network::NetworkException & e ){
Global::debug( 0 ) << "Error accepting connections: " << e.getMessage() << endl;
}
Util::rest( 1 );
}
return NULL;
}
ChatServer::ChatServer( const string & name, Network::Socket socket ):
need_update( true ),
socket( socket ),
messages( 400, 350 ),
focus( INPUT_BOX ),
client_id( 1 ),
name( name ){
background = new Bitmap( Util::getDataPath() + "/paintown-title.png" );
Network::listen( socket );
pthread_mutex_init( &lock, NULL );
pthread_create( &acceptThread, NULL, acceptConnections, this );
}
void ChatServer::addConnection( Network::Socket s ){
Client * client = new Client( s, this, clientId() );
{
Network::Message message;
message << ADD_BUDDY;
message << 0;
message.path = getName();
client->addOutputMessage( message );
}
pthread_mutex_lock( &lock );
for ( vector< Client * >::iterator it = clients.begin(); it != clients.end(); it++ ){
Client * c = *it;
Network::Message message;
message << ADD_BUDDY;
message << c->getId();
message.path = c->getName();
client->addOutputMessage( message );
}
pthread_mutex_unlock( &lock );
Global::debug( 1 ) << "Adding client " << client->getId() << endl;
Network::Message message;
message << ADD_BUDDY;
message << client->getId();
sendMessage( message, 0 );
pthread_mutex_lock( &lock );
clients.push_back( client );
pthread_mutex_unlock( &lock );
client->startThreads();
}
static char lowerCase( const char * x ){
if ( x[0] >= 'A' && x[0] <= 'Z' ){
return x[0] - 'A' + 'a';
}
return x[0];
}
void ChatServer::sendMessage( const Network::Message & message, unsigned int id ){
pthread_mutex_lock( &lock );
for ( vector< Client * >::iterator it = clients.begin(); it != clients.end(); it++ ){
Client * c = *it;
if ( c->getId() != id ){
c->addOutputMessage( message );
}
}
pthread_mutex_unlock( &lock );
}
void ChatServer::addMessage( const string & s, unsigned int id ){
Network::Message message;
message << ADD_MESSAGE;
message.path = s;
pthread_mutex_lock( &lock );
messages.addMessage( s );
needUpdate();
pthread_mutex_unlock( &lock );
sendMessage( message, id );
/*
for ( vector< Client * >::iterator it = clients.begin(); it != clients.end(); it++ ){
Client * c = *it;
if ( c->getId() != id ){
c->addOutputMessage( message );
}
}
*/
}
void ChatServer::handleInput( Keyboard & keyboard ){
vector< int > keys;
keyboard.readKeys( keys );
for ( vector< int >::iterator it = keys.begin(); it != keys.end(); it++ ){
int key = *it;
if ( key == Keyboard::Key_BACKSPACE ){
if ( input != "" ){
input = input.substr( 0, input.length() - 1 );
needUpdate();
}
} else if ( Keyboard::isAlpha( key ) ){
input += lowerCase( Keyboard::keyToName( key ) );
needUpdate();
} else if ( key == Keyboard::Key_SPACE ){
input += " ";
needUpdate();
} else if ( key == Keyboard::Key_ENTER ){
addMessage( name + ": " + input, 0 );
input = "";
needUpdate();
}
}
}
void ChatServer::killClient( Client * c ){
int id = c->getId();
string name = c->getName();
pthread_mutex_lock( &lock );
for ( vector< Client * >::iterator it = clients.begin(); it != clients.end(); ){
Client * client = *it;
if ( client == c ){
Global::debug( 0 ) << "Killing socket" << endl;
c->kill();
Network::close( c->getSocket() );
Global::debug( 0 ) << "Waiting for input thread to die" << endl;
pthread_join( c->getInputThread(), NULL );
Global::debug( 0 ) << "Waiting for output thread to die" << endl;
pthread_join( c->getOutputThread(), NULL );
Global::debug( 0 ) << "Deleting client" << endl;
delete client;
it = clients.erase( it );
} else {
it++;
}
}
needUpdate();
pthread_mutex_unlock( &lock );
addMessage( "** " + name + " quit", 0 );
Network::Message remove;
remove << REMOVE_BUDDY;
remove << id;
sendMessage( remove, 0 );
}
void ChatServer::logic( Keyboard & keyboard ){
if ( keyboard[ Keyboard::Key_TAB ] ){
focus = nextFocus( focus );
needUpdate();
}
switch ( focus ){
case INPUT_BOX : {
handleInput( keyboard );
break;
}
case QUIT : {
break;
}
}
}
void ChatServer::needUpdate(){
need_update = true;
}
Focus ChatServer::nextFocus( Focus f ){
switch ( f ){
case INPUT_BOX : return QUIT;
case QUIT : return INPUT_BOX;
default : return INPUT_BOX;
}
}
bool ChatServer::needToDraw(){
return need_update;
}
void ChatServer::drawInputBox( int x, int y, const Bitmap & work ){
const Font & font = Font::getFont( Util::getDataPath() + DEFAULT_FONT, 20, 20 );
work.drawingMode( Bitmap::MODE_TRANS );
Bitmap::transBlender( 0, 0, 0, 128 );
work.rectangleFill( x, y, x + messages.getWidth(), y + font.getHeight() + 1, Bitmap::makeColor( 0, 0, 0 ) );
work.drawingMode( Bitmap::MODE_SOLID );
int color = Bitmap::makeColor( 255, 255, 255 );
if ( focus == INPUT_BOX ){
color = Bitmap::makeColor( 255, 255, 0 );
}
work.rectangle( x, y, x + messages.getWidth(), y + font.getHeight(), color );
Bitmap input_box( work, x + 1, y, messages.getWidth(), font.getHeight() );
// font.printf( x + 1, y, Bitmap::makeColor( 255, 255, 255 ), work, input, 0 );
font.printf( 0, 0, Bitmap::makeColor( 255, 255, 255 ), input_box, input, 0 );
}
void ChatServer::drawBuddyList( int x, int y, const Bitmap & work, const Font & font ){
Bitmap buddyList( work, x, y, GFX_X - x - 5, 200 );
buddyList.drawingMode( Bitmap::MODE_TRANS );
Bitmap::transBlender( 0, 0, 0, 128 );
buddyList.rectangleFill( 0, 0, buddyList.getWidth(), buddyList.getHeight(), Bitmap::makeColor( 0, 0, 0 ) );
buddyList.drawingMode( Bitmap::MODE_SOLID );
buddyList.rectangle( 0, 0, buddyList.getWidth() -1, buddyList.getHeight() - 1, Bitmap::makeColor( 255, 255, 255 ) );
int fy = 1;
for ( vector< Client * >::iterator it = clients.begin(); it != clients.end(); it++ ){
Client * client = *it;
const string & name = client->getName();
font.printf( 1, fy, Bitmap::makeColor( 255, 255, 255 ), buddyList, name, 0 );
fy += font.getHeight();
}
}
void ChatServer::draw( const Bitmap & work ){
int start_x = 20;
int start_y = 20;
const Font & font = Font::getFont( Util::getDataPath() + DEFAULT_FONT, 20, 20 );
background->Blit( work );
messages.draw( start_x, start_y, work, font );
drawInputBox( start_x, start_y + messages.getHeight() + 5, work );
drawBuddyList( start_x + messages.getWidth() + 10, start_y, work, font );
need_update = false;
}
void ChatServer::run(){
Global::speed_counter = 0;
Bitmap work( GFX_X, GFX_Y );
Keyboard keyboard;
keyboard.setAllDelay( 200 );
keyboard.setDelay( Keyboard::Key_TAB, 200 );
keyboard.setDelay( Keyboard::Key_ESC, 0 );
bool done = false;
while ( ! done ){
int think = Global::speed_counter;
while ( think > 0 ){
keyboard.poll();
logic( keyboard );
think -= 1;
Global::speed_counter = 0;
done = keyboard[ Keyboard::Key_ESC ];
}
if ( needToDraw() ){
draw( work );
work.BlitToScreen();
work.clear();
}
while ( Global::speed_counter == 0 ){
Util::rest( 1 );
keyboard.poll();
}
}
}
ChatServer::~ChatServer(){
delete background;
}
<commit_msg>add some comments<commit_after>#include "util/bitmap.h"
#include "network.h"
#include "chat_server.h"
#include "chat.h"
#include "util/bitmap.h"
#include "util/funcs.h"
#include "util/keyboard.h"
#include "util/font.h"
#include "globals.h"
#include "init.h"
#include <iostream>
#include <signal.h>
using namespace std;
static const char * DEFAULT_FONT = "/fonts/arial.ttf";
Client::Client( Network::Socket socket, ChatServer * server, unsigned int id ):
socket( socket ),
server( server ),
id( id ),
alive( true ){
pthread_mutex_init( &lock, NULL );
}
Client::~Client(){
}
string Client::getName(){
string s;
pthread_mutex_lock( &lock );
s = name;
pthread_mutex_unlock( &lock );
return s;
}
void Client::kill(){
pthread_mutex_lock( &lock );
alive = false;
pthread_mutex_unlock( &lock );
}
bool Client::isAlive(){
bool b;
pthread_mutex_lock( &lock );
b = alive;
pthread_mutex_unlock( &lock );
return b;
}
void Client::setName( const std::string & s ){
pthread_mutex_lock( &lock );
name = s;
pthread_mutex_unlock( &lock );
}
static void * clientInput( void * client_ ){
Client * client = (Client *) client_;
bool done = false;
while ( ! done ){
try{
Network::Message message( client->getSocket() );
Global::debug( 1 ) << "Got a message: '" << message.path << "'" << endl;
int type;
message >> type;
switch ( type ){
case CHANGE_NAME : {
message << client->getId();
client->getServer()->sendMessage( message, client->getId() );
client->setName( message.path );
client->getServer()->needUpdate();
break;
}
case ADD_MESSAGE : {
client->getServer()->addMessage( client->getName() + ":" + message.path, client->getId() );
break;
}
}
done = ! client->isAlive();
} catch ( const Network::NetworkException & e ){
Global::debug( 0 ) << "Client input " << client->getId() << " died" << endl;
done = true;
}
}
/* this is not thread safe with the output client thread */
if ( client->isAlive() ){
Global::debug( 0 ) << "Input thread killing client" << endl;
client->getServer()->killClient( client );
}
return NULL;
}
static void * clientOutput( void * client_ ){
Client * client = (Client *) client_;
bool done = false;
while ( ! done ){
Network::Message message;
done = ! client->isAlive();
if ( client->getOutgoing( message ) != false ){
Global::debug( 1 ) << "Sending a message to " << client->getId() << endl;
try{
/*
Network::Message net;
net.path = message;
net.send( client->getSocket() );
*/
message.send( client->getSocket() );
} catch ( const Network::NetworkException & e ){
Global::debug( 0 ) << "Client output " << client->getId() << " died" << endl;
done = true;
}
} else {
Util::rest( 1 );
}
}
/* this is not thread safe with the input client thread */
if ( client->isAlive() ){
Global::debug( 0 ) << "Output thread killing client" << endl;
client->getServer()->killClient( client );
}
return NULL;
}
bool Client::getOutgoing( Network::Message & m ){
bool has;
pthread_mutex_lock( &lock );
has = ! outgoing.empty();
if ( has ){
m = outgoing.front();
outgoing.erase( outgoing.begin() );
}
pthread_mutex_unlock( &lock );
return has;
}
void Client::addOutputMessage( const Network::Message & s ){
pthread_mutex_lock( &lock );
outgoing.push_back( s );
pthread_mutex_unlock( &lock );
}
void Client::startThreads(){
pthread_create( &inputThread, NULL, clientInput, this );
pthread_create( &outputThread, NULL, clientOutput, this );
}
static void * acceptConnections( void * server_ ){
bool done = false;
ChatServer * server = (ChatServer *) server_;
Network::Socket socket = server->getSocket();
while ( ! done ){
try{
server->addConnection( Network::accept( socket ) );
} catch ( const Network::NoConnectionsPendingException & e ){
} catch ( const Network::NetworkException & e ){
Global::debug( 0 ) << "Error accepting connections: " << e.getMessage() << endl;
}
Util::rest( 1 );
}
return NULL;
}
ChatServer::ChatServer( const string & name, Network::Socket socket ):
need_update( true ),
socket( socket ),
messages( 400, 350 ),
focus( INPUT_BOX ),
client_id( 1 ),
name( name ){
background = new Bitmap( Util::getDataPath() + "/paintown-title.png" );
Network::listen( socket );
pthread_mutex_init( &lock, NULL );
pthread_create( &acceptThread, NULL, acceptConnections, this );
}
void ChatServer::addConnection( Network::Socket s ){
Client * client = new Client( s, this, clientId() );
{
Network::Message message;
message << ADD_BUDDY;
message << 0;
message.path = getName();
client->addOutputMessage( message );
}
pthread_mutex_lock( &lock );
for ( vector< Client * >::iterator it = clients.begin(); it != clients.end(); it++ ){
Client * c = *it;
Network::Message message;
message << ADD_BUDDY;
message << c->getId();
message.path = c->getName();
client->addOutputMessage( message );
}
pthread_mutex_unlock( &lock );
Global::debug( 1 ) << "Adding client " << client->getId() << endl;
Network::Message message;
message << ADD_BUDDY;
message << client->getId();
sendMessage( message, 0 );
pthread_mutex_lock( &lock );
clients.push_back( client );
pthread_mutex_unlock( &lock );
client->startThreads();
}
static char lowerCase( const char * x ){
if ( x[0] >= 'A' && x[0] <= 'Z' ){
return x[0] - 'A' + 'a';
}
return x[0];
}
void ChatServer::sendMessage( const Network::Message & message, unsigned int id ){
pthread_mutex_lock( &lock );
for ( vector< Client * >::iterator it = clients.begin(); it != clients.end(); it++ ){
Client * c = *it;
if ( c->getId() != id ){
c->addOutputMessage( message );
}
}
pthread_mutex_unlock( &lock );
}
void ChatServer::addMessage( const string & s, unsigned int id ){
Network::Message message;
message << ADD_MESSAGE;
message.path = s;
pthread_mutex_lock( &lock );
messages.addMessage( s );
needUpdate();
pthread_mutex_unlock( &lock );
sendMessage( message, id );
/*
for ( vector< Client * >::iterator it = clients.begin(); it != clients.end(); it++ ){
Client * c = *it;
if ( c->getId() != id ){
c->addOutputMessage( message );
}
}
*/
}
void ChatServer::handleInput( Keyboard & keyboard ){
vector< int > keys;
keyboard.readKeys( keys );
for ( vector< int >::iterator it = keys.begin(); it != keys.end(); it++ ){
int key = *it;
if ( key == Keyboard::Key_BACKSPACE ){
if ( input != "" ){
input = input.substr( 0, input.length() - 1 );
needUpdate();
}
} else if ( Keyboard::isAlpha( key ) ){
input += lowerCase( Keyboard::keyToName( key ) );
needUpdate();
} else if ( key == Keyboard::Key_SPACE ){
input += " ";
needUpdate();
} else if ( key == Keyboard::Key_ENTER ){
addMessage( name + ": " + input, 0 );
input = "";
needUpdate();
}
}
}
void ChatServer::killClient( Client * c ){
int id = c->getId();
string name = c->getName();
pthread_mutex_lock( &lock );
for ( vector< Client * >::iterator it = clients.begin(); it != clients.end(); ){
Client * client = *it;
if ( client == c ){
Global::debug( 0 ) << "Killing socket" << endl;
c->kill();
Network::close( c->getSocket() );
/* the client thread that called killClient will wait for
* itself to die, but pthreads won't deadlock on join
*/
Global::debug( 0 ) << "Waiting for input thread to die " << c->getInputThread() << endl;
pthread_join( c->getInputThread(), NULL );
Global::debug( 0 ) << "Waiting for output thread to die" << endl;
pthread_join( c->getOutputThread(), NULL );
Global::debug( 0 ) << "Deleting client" << endl;
delete client;
it = clients.erase( it );
} else {
it++;
}
}
needUpdate();
pthread_mutex_unlock( &lock );
addMessage( "** " + name + " quit", 0 );
Network::Message remove;
remove << REMOVE_BUDDY;
remove << id;
sendMessage( remove, 0 );
}
void ChatServer::logic( Keyboard & keyboard ){
if ( keyboard[ Keyboard::Key_TAB ] ){
focus = nextFocus( focus );
needUpdate();
}
switch ( focus ){
case INPUT_BOX : {
handleInput( keyboard );
break;
}
case QUIT : {
break;
}
}
}
void ChatServer::needUpdate(){
need_update = true;
}
Focus ChatServer::nextFocus( Focus f ){
switch ( f ){
case INPUT_BOX : return QUIT;
case QUIT : return INPUT_BOX;
default : return INPUT_BOX;
}
}
bool ChatServer::needToDraw(){
return need_update;
}
void ChatServer::drawInputBox( int x, int y, const Bitmap & work ){
const Font & font = Font::getFont( Util::getDataPath() + DEFAULT_FONT, 20, 20 );
work.drawingMode( Bitmap::MODE_TRANS );
Bitmap::transBlender( 0, 0, 0, 128 );
work.rectangleFill( x, y, x + messages.getWidth(), y + font.getHeight() + 1, Bitmap::makeColor( 0, 0, 0 ) );
work.drawingMode( Bitmap::MODE_SOLID );
int color = Bitmap::makeColor( 255, 255, 255 );
if ( focus == INPUT_BOX ){
color = Bitmap::makeColor( 255, 255, 0 );
}
work.rectangle( x, y, x + messages.getWidth(), y + font.getHeight(), color );
Bitmap input_box( work, x + 1, y, messages.getWidth(), font.getHeight() );
// font.printf( x + 1, y, Bitmap::makeColor( 255, 255, 255 ), work, input, 0 );
font.printf( 0, 0, Bitmap::makeColor( 255, 255, 255 ), input_box, input, 0 );
}
void ChatServer::drawBuddyList( int x, int y, const Bitmap & work, const Font & font ){
Bitmap buddyList( work, x, y, GFX_X - x - 5, 200 );
buddyList.drawingMode( Bitmap::MODE_TRANS );
Bitmap::transBlender( 0, 0, 0, 128 );
buddyList.rectangleFill( 0, 0, buddyList.getWidth(), buddyList.getHeight(), Bitmap::makeColor( 0, 0, 0 ) );
buddyList.drawingMode( Bitmap::MODE_SOLID );
buddyList.rectangle( 0, 0, buddyList.getWidth() -1, buddyList.getHeight() - 1, Bitmap::makeColor( 255, 255, 255 ) );
int fy = 1;
for ( vector< Client * >::iterator it = clients.begin(); it != clients.end(); it++ ){
Client * client = *it;
const string & name = client->getName();
font.printf( 1, fy, Bitmap::makeColor( 255, 255, 255 ), buddyList, name, 0 );
fy += font.getHeight();
}
}
void ChatServer::draw( const Bitmap & work ){
int start_x = 20;
int start_y = 20;
const Font & font = Font::getFont( Util::getDataPath() + DEFAULT_FONT, 20, 20 );
background->Blit( work );
messages.draw( start_x, start_y, work, font );
drawInputBox( start_x, start_y + messages.getHeight() + 5, work );
drawBuddyList( start_x + messages.getWidth() + 10, start_y, work, font );
need_update = false;
}
void ChatServer::run(){
Global::speed_counter = 0;
Bitmap work( GFX_X, GFX_Y );
Keyboard keyboard;
keyboard.setAllDelay( 200 );
keyboard.setDelay( Keyboard::Key_TAB, 200 );
keyboard.setDelay( Keyboard::Key_ESC, 0 );
bool done = false;
while ( ! done ){
int think = Global::speed_counter;
while ( think > 0 ){
keyboard.poll();
logic( keyboard );
think -= 1;
Global::speed_counter = 0;
done = keyboard[ Keyboard::Key_ESC ];
}
if ( needToDraw() ){
draw( work );
work.BlitToScreen();
work.clear();
}
while ( Global::speed_counter == 0 ){
Util::rest( 1 );
keyboard.poll();
}
}
}
ChatServer::~ChatServer(){
delete background;
}
<|endoftext|>
|
<commit_before>#include "object/jsbasicobject.h"
#include "object/function.h"
#include "object/argument.h"
#include "object/jsobject.h"
namespace grok {
namespace obj {
std::string JSObject::AsString() const
{
std::string buff = "";
buff += "{ ";
for (const auto &it : object_) {
auto prop = it.second->as<JSObject>();
if (!prop->IsEnumerable())
continue;
buff += it.first + ": ";
buff += it.second->as<JSObject>()->ToString() += ", ";
}
buff.pop_back(); // " "
buff += " }";
return buff;
}
std::string JSObject::ToString() const
{
return "[ object Object ]";
}
std::shared_ptr<Object> toString(std::shared_ptr<Argument> Args)
{
auto This = Args->GetProperty("this");
auto result = CreateJSString(This->as<JSObject>()->ToString());
return result;
}
std::shared_ptr<Object> hasOwnProperty(std::shared_ptr<Argument> Args)
{
auto This = Args->GetProperty("this");
auto Prop = Args->GetProperty("prop");
auto Name = Prop->as<JSObject>()->ToString();
// not according to ECMAScript standard
return CreateJSNumber(This->as<JSObject>()->HasProperty(Name));
}
void DefineInternalObjectProperties(JSObject *obj)
{
auto F = std::make_shared<Function>(toString);
F->SetNonWritable();
F->SetNonEnumerable();
obj->AddProperty(std::string("toString"), std::make_shared<Object>(F));
F = std::make_shared<Function>(hasOwnProperty);
F->SetNonWritable();
F->SetNonEnumerable();
F->SetParams({ "prop" });
obj->AddProperty(std::string("hasOwnProperty"),
std::make_shared<Object>(F));
// add the prototype property default is undefined
auto P = CreateUndefinedObject();
F->SetNonEnumerable();
obj->AddProperty(std::string("prototype"), std::make_shared<Object>(P));
}
std::shared_ptr<Object> CreateJSObject()
{
auto O = std::make_shared<JSObject>();
DefineInternalObjectProperties(O.get());
return std::make_shared<Object>(O);
}
std::shared_ptr<Object> ObjectConstructor(std::shared_ptr<Argument> Args)
{
if (Args->Size() < 1) {
return CreateJSObject();
}
return Args->At(0);
}
std::shared_ptr<Object> CreateCopy(std::shared_ptr<Object> obj)
{
if (IsJSNumber(obj)) {
return CreateJSNumber(obj->as<JSNumber>()->GetNumber());
} else if (IsJSString(obj)) {
return CreateJSString(obj->as<JSString>()->ToString());
}
// else return reference
return obj;
}
} // obj
} // grok
<commit_msg>Typo: JSNumber ==> JSDouble<commit_after>#include "object/jsbasicobject.h"
#include "object/function.h"
#include "object/argument.h"
#include "object/jsobject.h"
namespace grok {
namespace obj {
std::string JSObject::AsString() const
{
std::string buff = "";
buff += "{ ";
for (const auto &it : object_) {
auto prop = it.second->as<JSObject>();
if (!prop->IsEnumerable())
continue;
buff += it.first + ": ";
buff += it.second->as<JSObject>()->ToString() += ", ";
}
buff.pop_back(); // " "
buff += " }";
return buff;
}
std::string JSObject::ToString() const
{
return "[ object Object ]";
}
std::shared_ptr<Object> toString(std::shared_ptr<Argument> Args)
{
auto This = Args->GetProperty("this");
auto result = CreateJSString(This->as<JSObject>()->ToString());
return result;
}
std::shared_ptr<Object> hasOwnProperty(std::shared_ptr<Argument> Args)
{
auto This = Args->GetProperty("this");
auto Prop = Args->GetProperty("prop");
auto Name = Prop->as<JSObject>()->ToString();
// not according to ECMAScript standard
return CreateJSNumber(This->as<JSObject>()->HasProperty(Name));
}
void DefineInternalObjectProperties(JSObject *obj)
{
auto F = std::make_shared<Function>(toString);
F->SetNonWritable();
F->SetNonEnumerable();
obj->AddProperty(std::string("toString"), std::make_shared<Object>(F));
F = std::make_shared<Function>(hasOwnProperty);
F->SetNonWritable();
F->SetNonEnumerable();
F->SetParams({ "prop" });
obj->AddProperty(std::string("hasOwnProperty"),
std::make_shared<Object>(F));
// add the prototype property default is undefined
auto P = CreateUndefinedObject();
F->SetNonEnumerable();
obj->AddProperty(std::string("prototype"), std::make_shared<Object>(P));
}
std::shared_ptr<Object> CreateJSObject()
{
auto O = std::make_shared<JSObject>();
DefineInternalObjectProperties(O.get());
return std::make_shared<Object>(O);
}
std::shared_ptr<Object> ObjectConstructor(std::shared_ptr<Argument> Args)
{
if (Args->Size() < 1) {
return CreateJSObject();
}
return Args->At(0);
}
std::shared_ptr<Object> CreateCopy(std::shared_ptr<Object> obj)
{
if (IsJSNumber(obj)) {
return CreateJSNumber(obj->as<JSDouble>()->GetNumber());
} else if (IsJSString(obj)) {
return CreateJSString(obj->as<JSString>()->ToString());
}
// else return reference
return obj;
}
} // obj
} // grok
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (c) 2019, Nefelus Inc
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "dbRegion.h"
#include "db.h"
#include "dbBlock.h"
#include "dbBlockCallBackObj.h"
#include "dbBox.h"
#include "dbBoxItr.h"
#include "dbDatabase.h"
#include "dbInst.h"
#include "dbRegion.h"
#include "dbRegionInstItr.h"
#include "dbRegionItr.h"
#include "dbTable.h"
#include "dbTable.hpp"
namespace odb {
template class dbTable<_dbRegion>;
_dbRegion::_dbRegion(_dbDatabase*)
{
_flags._type = dbRegionType::INCLUSIVE;
_flags._invalid = false;
_name = NULL;
}
_dbRegion::_dbRegion(_dbDatabase*, const _dbRegion& r)
: _flags(r._flags),
_name(NULL),
_insts(r._insts),
_boxes(r._boxes),
_parent(r._parent),
_children(r._children),
_next_child(r._next_child)
{
if (r._name)
_name = strdup(r._name);
}
_dbRegion::~_dbRegion()
{
if (_name)
free((void*) _name);
}
bool _dbRegion::operator==(const _dbRegion& rhs) const
{
if (_flags._type != rhs._flags._type)
return false;
if (_flags._invalid != rhs._flags._invalid)
return false;
if (_name && rhs._name) {
if (strcmp(_name, rhs._name) != 0)
return false;
} else if (_name || rhs._name)
return false;
if (_insts != rhs._insts)
return false;
if (_parent != rhs._parent)
return false;
if (_children != rhs._children)
return false;
if (_next_child != rhs._next_child)
return false;
return true;
}
bool _dbRegion::operator<(const _dbRegion& rhs) const
{
if (_flags._type < rhs._flags._type)
return false;
if (_flags._type > rhs._flags._type)
return true;
if (_flags._invalid < rhs._flags._invalid)
return false;
if (_flags._invalid > rhs._flags._invalid)
return true;
if (_insts < rhs._insts)
return true;
if (_insts > rhs._insts)
return false;
if (_parent < rhs._parent)
return true;
if (_parent > rhs._parent)
return false;
if (_children < rhs._children)
return true;
if (_children > rhs._children)
return false;
if (_next_child < rhs._next_child)
return true;
if (_next_child > rhs._next_child)
return false;
return _boxes < rhs._boxes;
}
void _dbRegion::differences(dbDiff& diff,
const char* field,
const _dbRegion& rhs) const
{
if (diff.deepDiff())
return;
DIFF_BEGIN
DIFF_FIELD(_flags._type);
DIFF_FIELD(_flags._invalid);
DIFF_FIELD(_name);
DIFF_FIELD(_insts);
DIFF_FIELD(_boxes);
DIFF_FIELD(_parent);
DIFF_FIELD(_children);
DIFF_FIELD(_next_child);
DIFF_END
}
void _dbRegion::out(dbDiff& diff, char side, const char* field) const
{
if (diff.deepDiff())
return;
DIFF_OUT_BEGIN
DIFF_OUT_FIELD(_flags._type);
DIFF_OUT_FIELD(_flags._invalid);
DIFF_OUT_FIELD(_name);
DIFF_OUT_FIELD(_insts);
DIFF_OUT_FIELD(_boxes);
DIFF_OUT_FIELD(_parent);
DIFF_OUT_FIELD(_children);
DIFF_OUT_FIELD(_next_child);
DIFF_END
}
dbOStream& operator<<(dbOStream& stream, const _dbRegion& r)
{
uint* bit_field = (uint*) &r._flags;
stream << *bit_field;
stream << r._name;
stream << r._insts;
stream << r._boxes;
stream << r._parent;
stream << r._children;
stream << r._next_child;
return stream;
}
dbIStream& operator>>(dbIStream& stream, _dbRegion& r)
{
uint* bit_field = (uint*) &r._flags;
stream >> *bit_field;
stream >> r._name;
stream >> r._insts;
stream >> r._boxes;
stream >> r._parent;
stream >> r._children;
stream >> r._next_child;
return stream;
}
std::string dbRegion::getName()
{
_dbRegion* region = (_dbRegion*) this;
return region->_name;
}
dbRegionType dbRegion::getRegionType()
{
_dbRegion* region = (_dbRegion*) this;
dbRegionType t(region->_flags._type);
return t;
}
void dbRegion::setInvalid(bool v)
{
_dbRegion* region = (_dbRegion*) this;
region->_flags._invalid = v;
}
bool dbRegion::isInvalid()
{
_dbRegion* region = (_dbRegion*) this;
return region->_flags._invalid == 1;
}
void dbRegion::setRegionType(dbRegionType type)
{
_dbRegion* region = (_dbRegion*) this;
region->_flags._type = type;
}
dbSet<dbInst> dbRegion::getRegionInsts()
{
_dbRegion* region = (_dbRegion*) this;
_dbBlock* block = (_dbBlock*) region->getOwner();
return dbSet<dbInst>(region, block->_region_inst_itr);
}
dbSet<dbBox> dbRegion::getBoundaries()
{
_dbRegion* region = (_dbRegion*) this;
_dbBlock* block = (_dbBlock*) region->getOwner();
return dbSet<dbBox>(region, block->_box_itr);
}
void dbRegion::addInst(dbInst* inst_)
{
_dbRegion* region = (_dbRegion*) this;
_dbInst* inst = (_dbInst*) inst_;
_dbBlock* block = (_dbBlock*) region->getOwner();
if (inst->_region != 0) {
dbRegion* r = dbRegion::getRegion((dbBlock*) block, inst->_region);
r->removeInst(inst_);
}
inst->_region = region->getOID();
if (region->_insts != 0) {
_dbInst* tail = block->_inst_tbl->getPtr(region->_insts);
inst->_region_next = region->_insts;
inst->_region_prev = 0;
tail->_region_prev = inst->getOID();
} else {
inst->_region_next = 0;
inst->_region_prev = 0;
}
region->_insts = inst->getOID();
}
void dbRegion::removeInst(dbInst* inst_)
{
_dbRegion* region = (_dbRegion*) this;
_dbInst* inst = (_dbInst*) inst_;
_dbBlock* block = (_dbBlock*) region->getOwner();
uint id = inst->getOID();
if (region->_insts == id) {
region->_insts = inst->_region_next;
if (region->_insts != 0) {
_dbInst* t = block->_inst_tbl->getPtr(region->_insts);
t->_region_prev = 0;
}
} else {
if (inst->_region_next != 0) {
_dbInst* next = block->_inst_tbl->getPtr(inst->_region_next);
next->_region_prev = inst->_region_prev;
}
if (inst->_region_prev != 0) {
_dbInst* prev = block->_inst_tbl->getPtr(inst->_region_prev);
prev->_region_next = inst->_region_next;
}
}
inst->_region = 0;
}
dbRegion* dbRegion::getParent()
{
_dbRegion* region = (_dbRegion*) this;
_dbBlock* block = (_dbBlock*) region->getOwner();
if (region->_parent == 0)
return NULL;
_dbRegion* p = block->_region_tbl->getPtr(region->_parent);
return (dbRegion*) p;
}
dbSet<dbRegion> dbRegion::getChildren()
{
_dbRegion* region = (_dbRegion*) this;
_dbBlock* block = (_dbBlock*) region->getOwner();
dbSet<dbRegion> children(region, block->_region_itr);
return children;
}
void dbRegion::addChild(dbRegion* child_)
{
_dbRegion* child = (_dbRegion*) child_;
_dbRegion* parent = (_dbRegion*) this;
//_dbBlock * block = (_dbBlock *) getOwner();
if (child->_parent || (parent == child))
return;
child->_parent = parent->getOID();
child->_next_child = parent->_children;
parent->_children = child->getOID();
}
dbBlock* dbRegion::getBlock()
{
return (dbBlock*) getImpl()->getOwner();
}
dbRegion* dbRegion::create(dbBlock* block_, const char* name)
{
_dbBlock* block = (_dbBlock*) block_;
if (block_->findRegion(name))
return NULL;
_dbRegion* region = block->_region_tbl->create();
region->_name = strdup(name);
ZALLOCATED(region->_name);
for (auto callback : block->_callbacks)
callback->inDbRegionCreate((dbRegion*) region);
return (dbRegion*) region;
}
dbRegion* dbRegion::create(dbRegion* parent_, const char* name)
{
_dbRegion* parent = (_dbRegion*) parent_;
_dbBlock* block = (_dbBlock*) parent->getOwner();
if (((dbBlock*) block)->findRegion(name))
return NULL;
_dbRegion* region = block->_region_tbl->create();
region->_name = strdup(name);
ZALLOCATED(region->_name);
region->_parent = parent->getOID();
region->_next_child = parent->_children;
parent->_children = region->getOID();
for (auto callback : block->_callbacks)
callback->inDbRegionCreate((dbRegion*) region);
return (dbRegion*) region;
}
void dbRegion::destroy(dbRegion* region_)
{
_dbRegion* region = (_dbRegion*) region_;
_dbBlock* block = (_dbBlock*) region->getOwner();
dbSet<dbRegion> children = region_->getChildren();
dbSet<dbRegion>::iterator childItr;
for (childItr = children.begin(); childItr != children.end();
childItr = children.begin()) {
dbRegion* child = *childItr;
child->destroy(child);
}
for (auto callback : block->_callbacks)
callback->inDbRegionDestroy((dbRegion*) region);
dbSet<dbInst> insts = region_->getRegionInsts();
dbSet<dbInst>::iterator iitr;
for (iitr = insts.begin(); iitr != insts.end(); iitr = insts.begin()) {
dbInst* inst = *iitr;
region_->removeInst(inst);
}
dbSet<dbBox> boxes = region_->getBoundaries();
dbSet<dbBox>::iterator bitr;
for (bitr = boxes.begin(); bitr != boxes.end();) {
dbSet<dbBox>::iterator next = ++bitr;
dbBox* box = *bitr;
dbProperty::destroyProperties(box);
block->_box_tbl->destroy((_dbBox*) box);
bitr = next;
}
if (region->_parent) {
_dbRegion* parent = block->_region_tbl->getPtr(region->_parent);
_dbRegion* prev = NULL;
_dbRegion* cur = block->_region_tbl->getPtr(parent->_children);
while (cur) {
if (cur == region)
break;
prev = cur;
cur = block->_region_tbl->getPtr(cur->_next_child);
}
if (prev == NULL)
parent->_children = region->_next_child;
else
prev->_next_child = region->_next_child;
}
dbProperty::destroyProperties(region);
block->_region_tbl->destroy(region);
}
dbSet<dbRegion>::iterator dbRegion::destroy(dbSet<dbRegion>::iterator& itr)
{
dbRegion* r = *itr;
dbSet<dbRegion>::iterator next = ++itr;
destroy(r);
return next;
}
dbRegion* dbRegion::getRegion(dbBlock* block_, uint dbid_)
{
_dbBlock* block = (_dbBlock*) block_;
return (dbRegion*) block->_region_tbl->getPtr(dbid_);
}
} // namespace odb
<commit_msg>odb: fix bug in dbRegion::destory<commit_after>///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (c) 2019, Nefelus Inc
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "dbRegion.h"
#include "db.h"
#include "dbBlock.h"
#include "dbBlockCallBackObj.h"
#include "dbBox.h"
#include "dbBoxItr.h"
#include "dbDatabase.h"
#include "dbInst.h"
#include "dbRegion.h"
#include "dbRegionInstItr.h"
#include "dbRegionItr.h"
#include "dbTable.h"
#include "dbTable.hpp"
namespace odb {
template class dbTable<_dbRegion>;
_dbRegion::_dbRegion(_dbDatabase*)
{
_flags._type = dbRegionType::INCLUSIVE;
_flags._invalid = false;
_name = NULL;
}
_dbRegion::_dbRegion(_dbDatabase*, const _dbRegion& r)
: _flags(r._flags),
_name(NULL),
_insts(r._insts),
_boxes(r._boxes),
_parent(r._parent),
_children(r._children),
_next_child(r._next_child)
{
if (r._name)
_name = strdup(r._name);
}
_dbRegion::~_dbRegion()
{
if (_name)
free((void*) _name);
}
bool _dbRegion::operator==(const _dbRegion& rhs) const
{
if (_flags._type != rhs._flags._type)
return false;
if (_flags._invalid != rhs._flags._invalid)
return false;
if (_name && rhs._name) {
if (strcmp(_name, rhs._name) != 0)
return false;
} else if (_name || rhs._name)
return false;
if (_insts != rhs._insts)
return false;
if (_parent != rhs._parent)
return false;
if (_children != rhs._children)
return false;
if (_next_child != rhs._next_child)
return false;
return true;
}
bool _dbRegion::operator<(const _dbRegion& rhs) const
{
if (_flags._type < rhs._flags._type)
return false;
if (_flags._type > rhs._flags._type)
return true;
if (_flags._invalid < rhs._flags._invalid)
return false;
if (_flags._invalid > rhs._flags._invalid)
return true;
if (_insts < rhs._insts)
return true;
if (_insts > rhs._insts)
return false;
if (_parent < rhs._parent)
return true;
if (_parent > rhs._parent)
return false;
if (_children < rhs._children)
return true;
if (_children > rhs._children)
return false;
if (_next_child < rhs._next_child)
return true;
if (_next_child > rhs._next_child)
return false;
return _boxes < rhs._boxes;
}
void _dbRegion::differences(dbDiff& diff,
const char* field,
const _dbRegion& rhs) const
{
if (diff.deepDiff())
return;
DIFF_BEGIN
DIFF_FIELD(_flags._type);
DIFF_FIELD(_flags._invalid);
DIFF_FIELD(_name);
DIFF_FIELD(_insts);
DIFF_FIELD(_boxes);
DIFF_FIELD(_parent);
DIFF_FIELD(_children);
DIFF_FIELD(_next_child);
DIFF_END
}
void _dbRegion::out(dbDiff& diff, char side, const char* field) const
{
if (diff.deepDiff())
return;
DIFF_OUT_BEGIN
DIFF_OUT_FIELD(_flags._type);
DIFF_OUT_FIELD(_flags._invalid);
DIFF_OUT_FIELD(_name);
DIFF_OUT_FIELD(_insts);
DIFF_OUT_FIELD(_boxes);
DIFF_OUT_FIELD(_parent);
DIFF_OUT_FIELD(_children);
DIFF_OUT_FIELD(_next_child);
DIFF_END
}
dbOStream& operator<<(dbOStream& stream, const _dbRegion& r)
{
uint* bit_field = (uint*) &r._flags;
stream << *bit_field;
stream << r._name;
stream << r._insts;
stream << r._boxes;
stream << r._parent;
stream << r._children;
stream << r._next_child;
return stream;
}
dbIStream& operator>>(dbIStream& stream, _dbRegion& r)
{
uint* bit_field = (uint*) &r._flags;
stream >> *bit_field;
stream >> r._name;
stream >> r._insts;
stream >> r._boxes;
stream >> r._parent;
stream >> r._children;
stream >> r._next_child;
return stream;
}
std::string dbRegion::getName()
{
_dbRegion* region = (_dbRegion*) this;
return region->_name;
}
dbRegionType dbRegion::getRegionType()
{
_dbRegion* region = (_dbRegion*) this;
dbRegionType t(region->_flags._type);
return t;
}
void dbRegion::setInvalid(bool v)
{
_dbRegion* region = (_dbRegion*) this;
region->_flags._invalid = v;
}
bool dbRegion::isInvalid()
{
_dbRegion* region = (_dbRegion*) this;
return region->_flags._invalid == 1;
}
void dbRegion::setRegionType(dbRegionType type)
{
_dbRegion* region = (_dbRegion*) this;
region->_flags._type = type;
}
dbSet<dbInst> dbRegion::getRegionInsts()
{
_dbRegion* region = (_dbRegion*) this;
_dbBlock* block = (_dbBlock*) region->getOwner();
return dbSet<dbInst>(region, block->_region_inst_itr);
}
dbSet<dbBox> dbRegion::getBoundaries()
{
_dbRegion* region = (_dbRegion*) this;
_dbBlock* block = (_dbBlock*) region->getOwner();
return dbSet<dbBox>(region, block->_box_itr);
}
void dbRegion::addInst(dbInst* inst_)
{
_dbRegion* region = (_dbRegion*) this;
_dbInst* inst = (_dbInst*) inst_;
_dbBlock* block = (_dbBlock*) region->getOwner();
if (inst->_region != 0) {
dbRegion* r = dbRegion::getRegion((dbBlock*) block, inst->_region);
r->removeInst(inst_);
}
inst->_region = region->getOID();
if (region->_insts != 0) {
_dbInst* tail = block->_inst_tbl->getPtr(region->_insts);
inst->_region_next = region->_insts;
inst->_region_prev = 0;
tail->_region_prev = inst->getOID();
} else {
inst->_region_next = 0;
inst->_region_prev = 0;
}
region->_insts = inst->getOID();
}
void dbRegion::removeInst(dbInst* inst_)
{
_dbRegion* region = (_dbRegion*) this;
_dbInst* inst = (_dbInst*) inst_;
_dbBlock* block = (_dbBlock*) region->getOwner();
uint id = inst->getOID();
if (region->_insts == id) {
region->_insts = inst->_region_next;
if (region->_insts != 0) {
_dbInst* t = block->_inst_tbl->getPtr(region->_insts);
t->_region_prev = 0;
}
} else {
if (inst->_region_next != 0) {
_dbInst* next = block->_inst_tbl->getPtr(inst->_region_next);
next->_region_prev = inst->_region_prev;
}
if (inst->_region_prev != 0) {
_dbInst* prev = block->_inst_tbl->getPtr(inst->_region_prev);
prev->_region_next = inst->_region_next;
}
}
inst->_region = 0;
}
dbRegion* dbRegion::getParent()
{
_dbRegion* region = (_dbRegion*) this;
_dbBlock* block = (_dbBlock*) region->getOwner();
if (region->_parent == 0)
return NULL;
_dbRegion* p = block->_region_tbl->getPtr(region->_parent);
return (dbRegion*) p;
}
dbSet<dbRegion> dbRegion::getChildren()
{
_dbRegion* region = (_dbRegion*) this;
_dbBlock* block = (_dbBlock*) region->getOwner();
dbSet<dbRegion> children(region, block->_region_itr);
return children;
}
void dbRegion::addChild(dbRegion* child_)
{
_dbRegion* child = (_dbRegion*) child_;
_dbRegion* parent = (_dbRegion*) this;
//_dbBlock * block = (_dbBlock *) getOwner();
if (child->_parent || (parent == child))
return;
child->_parent = parent->getOID();
child->_next_child = parent->_children;
parent->_children = child->getOID();
}
dbBlock* dbRegion::getBlock()
{
return (dbBlock*) getImpl()->getOwner();
}
dbRegion* dbRegion::create(dbBlock* block_, const char* name)
{
_dbBlock* block = (_dbBlock*) block_;
if (block_->findRegion(name))
return NULL;
_dbRegion* region = block->_region_tbl->create();
region->_name = strdup(name);
ZALLOCATED(region->_name);
for (auto callback : block->_callbacks)
callback->inDbRegionCreate((dbRegion*) region);
return (dbRegion*) region;
}
dbRegion* dbRegion::create(dbRegion* parent_, const char* name)
{
_dbRegion* parent = (_dbRegion*) parent_;
_dbBlock* block = (_dbBlock*) parent->getOwner();
if (((dbBlock*) block)->findRegion(name))
return NULL;
_dbRegion* region = block->_region_tbl->create();
region->_name = strdup(name);
ZALLOCATED(region->_name);
region->_parent = parent->getOID();
region->_next_child = parent->_children;
parent->_children = region->getOID();
for (auto callback : block->_callbacks)
callback->inDbRegionCreate((dbRegion*) region);
return (dbRegion*) region;
}
void dbRegion::destroy(dbRegion* region_)
{
_dbRegion* region = (_dbRegion*) region_;
_dbBlock* block = (_dbBlock*) region->getOwner();
dbSet<dbRegion> children = region_->getChildren();
dbSet<dbRegion>::iterator childItr;
for (childItr = children.begin(); childItr != children.end();
childItr = children.begin()) {
dbRegion* child = *childItr;
child->destroy(child);
}
for (auto callback : block->_callbacks)
callback->inDbRegionDestroy((dbRegion*) region);
dbSet<dbInst> insts = region_->getRegionInsts();
dbSet<dbInst>::iterator iitr;
for (iitr = insts.begin(); iitr != insts.end(); iitr = insts.begin()) {
dbInst* inst = *iitr;
region_->removeInst(inst);
}
dbSet<dbBox> boxes = region_->getBoundaries();
dbSet<dbBox>::iterator bitr;
for (bitr = boxes.begin(); bitr != boxes.end();) {
dbBox* box = *bitr;
dbSet<dbBox>::iterator next = ++bitr;
dbProperty::destroyProperties(box);
block->_box_tbl->destroy((_dbBox*) box);
bitr = next;
}
if (region->_parent) {
_dbRegion* parent = block->_region_tbl->getPtr(region->_parent);
_dbRegion* prev = NULL;
_dbRegion* cur = block->_region_tbl->getPtr(parent->_children);
while (cur) {
if (cur == region)
break;
prev = cur;
cur = block->_region_tbl->getPtr(cur->_next_child);
}
if (prev == NULL)
parent->_children = region->_next_child;
else
prev->_next_child = region->_next_child;
}
dbProperty::destroyProperties(region);
block->_region_tbl->destroy(region);
}
dbSet<dbRegion>::iterator dbRegion::destroy(dbSet<dbRegion>::iterator& itr)
{
dbRegion* r = *itr;
dbSet<dbRegion>::iterator next = ++itr;
destroy(r);
return next;
}
dbRegion* dbRegion::getRegion(dbBlock* block_, uint dbid_)
{
_dbBlock* block = (_dbBlock*) block_;
return (dbRegion*) block->_region_tbl->getPtr(dbid_);
}
} // namespace odb
<|endoftext|>
|
<commit_before>#include <PCU.h>
#include <MeshSim.h>
#include <SimPartitionedMesh.h>
#include <SimUtil.h>
#include <SimParasolidKrnl.h>
#include <apfSIM.h>
#include <apfMDS.h>
#include <gmi_sim.h>
#include <apf.h>
#include <apfConvert.h>
#include <apfMesh2.h>
int main(int argc, char** argv)
{
MPI_Init(&argc, &argv);
PCU_Comm_Init();
if (argc != 4) {
if(0==PCU_Comm_Self())
std::cerr << "usage: " << argv[0] << " <model file> <simmetrix mesh> <scorec mesh>\n";
return 0;
}
Sim_readLicenseFile(NULL);
SimPartitionedMesh_start(&argc,&argv);
SimModel_start();
pProgress progress = Progress_new();
Progress_setDefaultCallback(progress);
pGModel simModel;
simModel = GM_load(argv[1], NULL, progress);
pParMesh sim_mesh = PM_load(argv[2],sthreadNone,0,progress);
apf::Mesh* simApfMesh = apf::createMesh(sim_mesh);
gmi_register_sim();
gmi_model* mdl = gmi_import_sim(simModel);
apf::Mesh2* mesh = apf::createMdsMesh(mdl, simApfMesh);
apf::destroyMesh(simApfMesh);
M_release(sim_mesh);
if (mesh->hasMatching()) {
if (apf::alignMdsMatches(mesh))
printf("fixed misaligned matches\n");
else
printf("matches were aligned\n");
assert( ! apf::alignMdsMatches(mesh));
}
mesh->verify();
mesh->writeNative(argv[3]);
mesh->destroyNative();
apf::destroyMesh(mesh);
GM_release(simModel);
Progress_delete(progress);
SimModel_stop();
SimPartitionedMesh_stop();
Sim_unregisterAllKeys();
PCU_Comm_Free();
MPI_Finalize();
}
<commit_msg>add layer cleanup to convert<commit_after>#include <PCU.h>
#include <MeshSim.h>
#include <SimPartitionedMesh.h>
#include <SimUtil.h>
#include <SimParasolidKrnl.h>
#include <apfSIM.h>
#include <apfMDS.h>
#include <gmi_sim.h>
#include <apf.h>
#include <apfConvert.h>
#include <apfMesh2.h>
static void fixMatches(apf::Mesh2* m)
{
if (m->hasMatching()) {
if (apf::alignMdsMatches(m))
printf("fixed misaligned matches\n");
else
printf("matches were aligned\n");
assert( ! apf::alignMdsMatches(m));
}
}
static void fixPyramids(apf::Mesh2* m)
{
ma::Input* in = ma::configureIdentity(m);
in->shouldCleanupLayer = true;
ma::adapt(in);
}
static void postConvert(apf::Mesh2* m)
{
fixMatches(m);
fixPyramids(m);
m->verify();
}
int main(int argc, char** argv)
{
MPI_Init(&argc, &argv);
PCU_Comm_Init();
if (argc != 4) {
if(0==PCU_Comm_Self())
std::cerr << "usage: " << argv[0] << " <model file> <simmetrix mesh> <scorec mesh>\n";
return EXIT_FAILURE;
}
Sim_readLicenseFile(NULL);
SimPartitionedMesh_start(&argc,&argv);
SimModel_start();
pProgress progress = Progress_new();
Progress_setDefaultCallback(progress);
pGModel simModel;
simModel = GM_load(argv[1], NULL, progress);
pParMesh sim_mesh = PM_load(argv[2],sthreadNone,0,progress);
apf::Mesh* simApfMesh = apf::createMesh(sim_mesh);
gmi_register_sim();
gmi_model* mdl = gmi_import_sim(simModel);
apf::Mesh2* mesh = apf::createMdsMesh(mdl, simApfMesh);
apf::destroyMesh(simApfMesh);
M_release(sim_mesh);
postConvert(mesh);
mesh->writeNative(argv[3]);
mesh->destroyNative();
apf::destroyMesh(mesh);
GM_release(simModel);
Progress_delete(progress);
SimModel_stop();
SimPartitionedMesh_stop();
Sim_unregisterAllKeys();
PCU_Comm_Free();
MPI_Finalize();
}
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: OOXMLTestService.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: os $ $Date: 2007-06-19 05:33: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
*
************************************************************************/
/**
Copyright 2005 Sun Microsystems, Inc.
*/
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XMAIN_HPP_
#include <com/sun/star/lang/XMain.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#include "OOXMLTestService.hxx"
#include <stdio.h>
#include <wchar.h>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XSeekable.hpp>
#include <com/sun/star/io/XTruncate.hpp>
#include <com/sun/star/task/XStatusIndicator.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <ucbhelper/contentbroker.hxx>
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#include <osl/process.h>
#include <rtl/string.hxx>
#include <hash_set>
#include <assert.h>
#include <cppuhelper/implbase2.hxx>
#include <com/sun/star/embed/XTransactedObject.hpp>
#include <com/sun/star/embed/XStorage.hpp>
#include <com/sun/star/util/XCloseable.hpp>
#include <comphelper/storagehelper.hxx>
#include <com/sun/star/embed/XTransactedObject.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <comphelper/seqstream.hxx>
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/container/XNameContainer.hpp>
#include <ooxml/OOXMLDocument.hxx>
#include <ctype.h>
using namespace ::com::sun::star;
namespace writerfilter { namespace ooxmltest {
const sal_Char ScannerTestService::SERVICE_NAME[40] = "debugservices.ooxml.ScannerTestService";
const sal_Char ScannerTestService::IMPLEMENTATION_NAME[40] = "debugservices.ooxml.ScannerTestService";
ScannerTestService::ScannerTestService(const uno::Reference< uno::XComponentContext > &xContext_) :
xContext( xContext_ )
{
}
sal_Int32 SAL_CALL ScannerTestService::run( const uno::Sequence< rtl::OUString >& aArguments ) throw (uno::RuntimeException)
{
uno::Sequence<uno::Any> aUcbInitSequence(2);
aUcbInitSequence[0] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Local"));
aUcbInitSequence[1] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Office"));
uno::Reference<lang::XMultiServiceFactory> xServiceFactory(xContext->getServiceManager(), uno::UNO_QUERY_THROW);
uno::Reference<lang::XMultiComponentFactory> xFactory(xContext->getServiceManager(), uno::UNO_QUERY_THROW );
if (::ucbhelper::ContentBroker::initialize(xServiceFactory, aUcbInitSequence))
{
rtl::OUString arg=aArguments[0];
::comphelper::setProcessServiceFactory(xServiceFactory);
uno::Reference<com::sun::star::ucb::XSimpleFileAccess> xFileAccess(
xFactory->createInstanceWithContext(
::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.ucb.SimpleFileAccess")),
xContext), uno::UNO_QUERY_THROW );
rtl_uString *dir=NULL;
osl_getProcessWorkingDir(&dir);
rtl::OUString absFileUrl;
osl_getAbsoluteFileURL(dir, arg.pData, &absFileUrl.pData);
rtl_uString_release(dir);
uno::Reference<io::XInputStream> xInputStream = xFileAccess->openFileRead(absFileUrl);
ooxml::OOXMLStream::Pointer_t pDocStream = ooxml::OOXMLDocumentFactory::createStream(xContext, xInputStream);
ooxml::OOXMLDocument::Pointer_t pDocument(ooxml::OOXMLDocumentFactory::createDocument(pDocStream));
#if 0
TimeValue t1; osl_getSystemTime(&t1);
#endif
doctok::Stream::Pointer_t pStream = doctok::createStreamHandler();
pDocument->resolve(*pStream);
#if 0
TimeValue t2; osl_getSystemTime(&t2);
printf("time=%is\n", t2.Seconds-t1.Seconds);
#endif
::ucbhelper::ContentBroker::deinitialize();
}
else
{
fprintf(stderr, "can't initialize UCB");
}
return 0;
}
::rtl::OUString ScannerTestService_getImplementationName ()
{
return rtl::OUString::createFromAscii ( ScannerTestService::IMPLEMENTATION_NAME );
}
sal_Bool SAL_CALL ScannerTestService_supportsService( const ::rtl::OUString& ServiceName )
{
return ServiceName.equals( rtl::OUString::createFromAscii( ScannerTestService::SERVICE_NAME ) );
}
uno::Sequence< rtl::OUString > SAL_CALL ScannerTestService_getSupportedServiceNames( ) throw (uno::RuntimeException)
{
uno::Sequence < rtl::OUString > aRet(1);
rtl::OUString* pArray = aRet.getArray();
pArray[0] = rtl::OUString::createFromAscii ( ScannerTestService::SERVICE_NAME );
return aRet;
}
uno::Reference< uno::XInterface > SAL_CALL ScannerTestService_createInstance( const uno::Reference< uno::XComponentContext > & xContext) throw( uno::Exception )
{
return (cppu::OWeakObject*) new ScannerTestService( xContext );
}
} } /* end namespace writerfilter::ooxml */
<commit_msg>INTEGRATION: CWS xmlfilter02 (1.4.12); FILE MERGED 2007/11/29 15:50:13 hbrinkm 1.4.12.2: clean up 2007/11/14 13:01:09 hbrinkm 1.4.12.1: namespace clean up<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: OOXMLTestService.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2008-01-10 12:19: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
*
************************************************************************/
/**
Copyright 2005 Sun Microsystems, Inc.
*/
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _COM_SUN_STAR_LANG_XMAIN_HPP_
#include <com/sun/star/lang/XMain.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#include "OOXMLTestService.hxx"
#include <stdio.h>
#include <wchar.h>
#include <com/sun/star/io/XStream.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XSeekable.hpp>
#include <com/sun/star/io/XTruncate.hpp>
#include <com/sun/star/task/XStatusIndicator.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <ucbhelper/contentbroker.hxx>
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#include <osl/process.h>
#include <rtl/string.hxx>
#include <hash_set>
#include <assert.h>
#include <cppuhelper/implbase2.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <com/sun/star/embed/XTransactedObject.hpp>
#include <com/sun/star/embed/XStorage.hpp>
#include <com/sun/star/util/XCloseable.hpp>
#include <comphelper/storagehelper.hxx>
#include <com/sun/star/embed/XTransactedObject.hpp>
#include <com/sun/star/beans/PropertyValue.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <comphelper/seqstream.hxx>
#include <com/sun/star/ucb/XSimpleFileAccess.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XMultiComponentFactory.hpp>
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/text/XTextDocument.hpp>
#include <com/sun/star/drawing/XDrawPageSupplier.hpp>
#include <ooxml/OOXMLDocument.hxx>
#include <ctype.h>
using namespace ::com::sun::star;
namespace writerfilter { namespace ooxmltest {
const sal_Char ScannerTestService::SERVICE_NAME[40] = "debugservices.ooxml.ScannerTestService";
const sal_Char ScannerTestService::IMPLEMENTATION_NAME[40] = "debugservices.ooxml.ScannerTestService";
ScannerTestService::ScannerTestService(const uno::Reference< uno::XComponentContext > &xContext_) :
xContext( xContext_ )
{
}
sal_Int32 SAL_CALL ScannerTestService::run( const uno::Sequence< rtl::OUString >& aArguments ) throw (uno::RuntimeException)
{
uno::Sequence<uno::Any> aUcbInitSequence(2);
aUcbInitSequence[0] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Local"));
aUcbInitSequence[1] <<= rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("Office"));
uno::Reference<lang::XMultiServiceFactory> xServiceFactory(xContext->getServiceManager(), uno::UNO_QUERY_THROW);
uno::Reference<lang::XMultiComponentFactory> xFactory(xContext->getServiceManager(), uno::UNO_QUERY_THROW );
if (::ucbhelper::ContentBroker::initialize(xServiceFactory, aUcbInitSequence))
{
rtl::OUString arg=aArguments[0];
::comphelper::setProcessServiceFactory(xServiceFactory);
uno::Reference<com::sun::star::ucb::XSimpleFileAccess> xFileAccess
(xFactory->createInstanceWithContext
(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
("com.sun.star.ucb.SimpleFileAccess")),
xContext), uno::UNO_QUERY_THROW );
rtl_uString *dir=NULL;
osl_getProcessWorkingDir(&dir);
rtl::OUString absFileUrl;
osl_getAbsoluteFileURL(dir, arg.pData, &absFileUrl.pData);
rtl_uString_release(dir);
uno::Reference<io::XInputStream> xInputStream =
xFileAccess->openFileRead(absFileUrl);
ooxml::OOXMLStream::Pointer_t pDocStream =
ooxml::OOXMLDocumentFactory::createStream(xContext, xInputStream);
ooxml::OOXMLDocument::Pointer_t pDocument
(ooxml::OOXMLDocumentFactory::createDocument(pDocStream));
#if 0
uno::Reference<text::XTextDocument> xDocument
(xFactory->createInstanceWithContext
(::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM
("com.sun.star.text.TextDocument")),
xContext), uno::UNO_QUERY_THROW );
uno::Reference<frame::XModel> xModel
(xDocument, uno::UNO_QUERY_THROW);
uno::Reference<drawing::XDrawPageSupplier> xDrawPageSupplier
(xDocument, uno::UNO_QUERY_THROW);
uno::Reference<drawing::XShapes> xShapes
(xDrawPageSupplier->getDrawPage(), uno::UNO_QUERY_THROW);
pDocument->setModel(xModel);
pDocument->setShapes(xShapes);
#endif
Stream::Pointer_t pStream = createStreamHandler();
pDocument->resolve(*pStream);
::ucbhelper::ContentBroker::deinitialize();
}
else
{
fprintf(stderr, "can't initialize UCB");
}
return 0;
}
::rtl::OUString ScannerTestService_getImplementationName ()
{
return rtl::OUString::createFromAscii ( ScannerTestService::IMPLEMENTATION_NAME );
}
sal_Bool SAL_CALL ScannerTestService_supportsService( const ::rtl::OUString& ServiceName )
{
return ServiceName.equals( rtl::OUString::createFromAscii( ScannerTestService::SERVICE_NAME ) );
}
uno::Sequence< rtl::OUString > SAL_CALL ScannerTestService_getSupportedServiceNames( ) throw (uno::RuntimeException)
{
uno::Sequence < rtl::OUString > aRet(1);
rtl::OUString* pArray = aRet.getArray();
pArray[0] = rtl::OUString::createFromAscii ( ScannerTestService::SERVICE_NAME );
return aRet;
}
uno::Reference< uno::XInterface > SAL_CALL ScannerTestService_createInstance( const uno::Reference< uno::XComponentContext > & xContext) throw( uno::Exception )
{
return (cppu::OWeakObject*) new ScannerTestService( xContext );
}
} } /* end namespace writerfilter::ooxml */
<|endoftext|>
|
<commit_before>#include "xchainer/native/native_device.h"
#include <cstddef>
#include <memory>
#include <thread>
#include <vector>
#include <gtest/gtest.h>
#include "xchainer/context.h"
#include "xchainer/native/native_backend.h"
namespace xchainer {
namespace native {
namespace {
template <typename T>
void ExpectDataEqual(const std::shared_ptr<void>& expected, const std::shared_ptr<void>& actual, size_t size) {
auto expected_raw_ptr = static_cast<const T*>(expected.get());
auto actual_raw_ptr = static_cast<const T*>(actual.get());
for (size_t i = 0; i < size; ++i) {
EXPECT_EQ(expected_raw_ptr[i], actual_raw_ptr[i]);
}
}
NativeDevice& GetNativeDevice(Context& ctx, int device_index) {
// Using dynamic_cast to ensure it's actually NativeDevice
return dynamic_cast<NativeDevice&>(ctx.GetDevice({"native", device_index}));
}
TEST(NativeDeviceTest, Allocate) {
Context ctx;
NativeDevice& device = GetNativeDevice(ctx, 0);
size_t bytesize = 3;
std::shared_ptr<void> ptr = device.Allocate(bytesize);
EXPECT_NE(nullptr, ptr);
}
TEST(NativeDeviceTest, AllocateZero) {
Context ctx;
NativeDevice& device = GetNativeDevice(ctx, 0);
std::shared_ptr<void> ptr = device.Allocate(size_t{0});
EXPECT_NE(ptr, nullptr);
}
TEST(NativeDeviceTest, AllocateFreeThreadSafe) {
static constexpr size_t kNumThreads = 2;
static constexpr size_t kNumLoopsPerThread = 1;
Context ctx;
NativeDevice& device = GetNativeDevice(ctx, 0);
// Allocate-and-free loop
auto func = [&device](size_t size) {
for (size_t j = 0; j < kNumLoopsPerThread; ++j) {
std::shared_ptr<void> ptr = device.Allocate(size);
(void)ptr; // unused
}
};
// Launch threads
std::vector<std::thread> threads;
threads.reserve(kNumThreads);
for (size_t i = 0; i < kNumThreads; ++i) {
threads.emplace_back(func, i);
}
// Join threads
for (size_t i = 0; i < kNumThreads; ++i) {
threads[i].join();
}
}
TEST(NativeDeviceTest, MakeDataFromForeignPointer) {
Context ctx;
NativeDevice& device = GetNativeDevice(ctx, 0);
size_t bytesize = 3;
std::shared_ptr<void> data = device.Allocate(bytesize);
EXPECT_EQ(data.get(), device.MakeDataFromForeignPointer(data).get());
}
TEST(NativeDeviceTest, FromHostMemory) {
size_t size = 3;
size_t bytesize = size * sizeof(float);
float raw_data[] = {0, 1, 2};
std::shared_ptr<void> src(raw_data, [](const float* ptr) {
(void)ptr; // unused
});
Context ctx;
NativeDevice& device = GetNativeDevice(ctx, 0);
std::shared_ptr<void> dst = device.FromHostMemory(src, bytesize);
EXPECT_EQ(src.get(), dst.get());
}
TEST(NativeDeviceTest, Synchronize) {
Context ctx;
NativeDevice& device = GetNativeDevice(ctx, 0);
device.Synchronize(); // no throw
}
} // namespace
} // namespace native
} // namespace xchainer
<commit_msg>Add xchainer::NativeDevice thread safety test<commit_after>#include "xchainer/native/native_device.h"
#include <cstddef>
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include <gtest/gtest.h>
#include "xchainer/context.h"
#include "xchainer/native/native_backend.h"
#include "xchainer/testing/threading.h"
namespace xchainer {
namespace native {
namespace {
template <typename T>
void ExpectDataEqual(const std::shared_ptr<void>& expected, const std::shared_ptr<void>& actual, size_t size) {
auto expected_raw_ptr = static_cast<const T*>(expected.get());
auto actual_raw_ptr = static_cast<const T*>(actual.get());
for (size_t i = 0; i < size; ++i) {
EXPECT_EQ(expected_raw_ptr[i], actual_raw_ptr[i]);
}
}
NativeDevice& GetNativeDevice(Context& ctx, int device_index) {
// Using dynamic_cast to ensure it's actually NativeDevice
return dynamic_cast<NativeDevice&>(ctx.GetDevice({"native", device_index}));
}
void RunThreads(const std::function<void(void)>& func) {
testing::RunThreads(2, [&func](size_t /*thread_index*/) {
func();
return nullptr;
});
}
TEST(NativeDeviceTest, Allocate) {
Context ctx;
NativeDevice& device = GetNativeDevice(ctx, 0);
size_t bytesize = 3;
std::shared_ptr<void> ptr = device.Allocate(bytesize);
EXPECT_NE(nullptr, ptr);
}
TEST(NativeDeviceTest, AllocateZero) {
Context ctx;
NativeDevice& device = GetNativeDevice(ctx, 0);
std::shared_ptr<void> ptr = device.Allocate(size_t{0});
EXPECT_NE(ptr, nullptr);
}
TEST(NativeDeviceTest, AllocateFreeThreadSafe) {
static constexpr size_t kNumThreads = 2;
static constexpr size_t kNumLoopsPerThread = 1;
Context ctx;
NativeDevice& device = GetNativeDevice(ctx, 0);
// Allocate-and-free loop
auto func = [&device](size_t size) {
for (size_t j = 0; j < kNumLoopsPerThread; ++j) {
std::shared_ptr<void> ptr = device.Allocate(size);
(void)ptr; // unused
}
};
// Launch threads
std::vector<std::thread> threads;
threads.reserve(kNumThreads);
for (size_t i = 0; i < kNumThreads; ++i) {
threads.emplace_back(func, i);
}
// Join threads
for (size_t i = 0; i < kNumThreads; ++i) {
threads[i].join();
}
}
TEST(NativeDeviceTest, MakeDataFromForeignPointer) {
Context ctx;
NativeDevice& device = GetNativeDevice(ctx, 0);
size_t bytesize = 3;
std::shared_ptr<void> data = device.Allocate(bytesize);
EXPECT_EQ(data.get(), device.MakeDataFromForeignPointer(data).get());
}
TEST(NativeDeviceTest, FromHostMemory) {
size_t size = 3;
size_t bytesize = size * sizeof(float);
float raw_data[] = {0, 1, 2};
std::shared_ptr<void> src(raw_data, [](const float* ptr) {
(void)ptr; // unused
});
Context ctx;
NativeDevice& device = GetNativeDevice(ctx, 0);
std::shared_ptr<void> dst = device.FromHostMemory(src, bytesize);
EXPECT_EQ(src.get(), dst.get());
}
TEST(NativeDeviceTest, Synchronize) {
Context ctx;
NativeDevice& device = GetNativeDevice(ctx, 0);
device.Synchronize(); // no throw
}
TEST(NativeDeviceTest, GetDeviceMultiThread) {
Context ctx;
RunThreads([&ctx]() {
NativeDevice& device = GetNativeDevice(ctx, 0);
(void)device;
});
}
TEST(NativeDeviceTest, GetBackendMultiThread) {
Context ctx;
NativeDevice& device = GetNativeDevice(ctx, 0);
Backend& expected_backend = device.backend();
RunThreads([&device, &expected_backend]() {
Backend& backend = device.backend();
EXPECT_EQ(&expected_backend, &backend);
});
}
TEST(NativeDeviceTest, GetIndexMultiThread) {
Context ctx;
NativeDevice& device = GetNativeDevice(ctx, 0);
int expected_index = device.index();
RunThreads([&device, &expected_index]() {
int index = device.index();
EXPECT_EQ(expected_index, index);
});
}
TEST(NativeDeviceTest, GetNameMultiThread) {
Context ctx;
NativeDevice& device = GetNativeDevice(ctx, 0);
std::string expected_name = device.name();
RunThreads([&device, &expected_name]() {
std::string name = device.name();
EXPECT_EQ(expected_name, name);
});
}
TEST(NativeDeviceTest, GetContextMultiThread) {
Context ctx;
NativeDevice& device = GetNativeDevice(ctx, 0);
RunThreads([&ctx, &device]() {
Context& context = device.context();
EXPECT_EQ(&ctx, &context);
});
}
} // namespace
} // namespace native
} // namespace xchainer
<|endoftext|>
|
<commit_before>#define BOOST_TEST_MODULE "test_serialize_file"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml.hpp>
#include <iostream>
#include <fstream>
BOOST_AUTO_TEST_CASE(test_example)
{
const auto data = toml::parse("toml/tests/example.toml");
{
std::ofstream ofs("tmp1.toml");
ofs << std::setw(80) << data;
}
auto serialized = toml::parse("tmp1.toml");
{
auto& owner = toml::find<toml::table>(serialized, "owner");
auto& bio = toml::get<std::string>(owner.at("bio"));
const auto CR = std::find(bio.begin(), bio.end(), '\r');
if(CR != bio.end())
{
bio.erase(CR);
}
}
BOOST_CHECK(data == serialized);
}
BOOST_AUTO_TEST_CASE(test_fruit)
{
const auto data = toml::parse("toml/tests/fruit.toml");
{
std::ofstream ofs("tmp2.toml");
ofs << std::setw(80) << data;
}
const auto serialized = toml::parse("tmp2.toml");
BOOST_CHECK(data == serialized);
}
BOOST_AUTO_TEST_CASE(test_hard_example)
{
const auto data = toml::parse("toml/tests/hard_example.toml");
{
std::ofstream ofs("tmp3.toml");
ofs << std::setw(80) << data;
}
const auto serialized = toml::parse("tmp3.toml");
BOOST_CHECK(data == serialized);
}
<commit_msg>test: check serialization keeps comments<commit_after>#define BOOST_TEST_MODULE "test_serialize_file"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml.hpp>
#include <iostream>
#include <fstream>
BOOST_AUTO_TEST_CASE(test_example)
{
const auto data = toml::parse("toml/tests/example.toml");
{
std::ofstream ofs("tmp1.toml");
ofs << std::setw(80) << data;
}
auto serialized = toml::parse("tmp1.toml");
{
auto& owner = toml::find<toml::table>(serialized, "owner");
auto& bio = toml::get<std::string>(owner.at("bio"));
const auto CR = std::find(bio.begin(), bio.end(), '\r');
if(CR != bio.end())
{
bio.erase(CR);
}
}
BOOST_CHECK(data == serialized);
}
BOOST_AUTO_TEST_CASE(test_example_with_comment)
{
const auto data = toml::parse<toml::preserve_comments>("toml/tests/example.toml");
{
std::ofstream ofs("tmp1_com.toml");
ofs << std::setw(80) << data;
}
auto serialized = toml::parse<toml::preserve_comments>("tmp1_com.toml");
{
auto& owner = toml::find<typename decltype(serialized)::table_type>(serialized, "owner");
auto& bio = toml::get<std::string>(owner.at("bio"));
const auto CR = std::find(bio.begin(), bio.end(), '\r');
if(CR != bio.end())
{
bio.erase(CR);
}
}
BOOST_CHECK(data == serialized);
{
std::ofstream ofs("tmp1_com1.toml");
ofs << std::setw(80) << serialized;
}
}
BOOST_AUTO_TEST_CASE(test_fruit)
{
const auto data = toml::parse("toml/tests/fruit.toml");
{
std::ofstream ofs("tmp2.toml");
ofs << std::setw(80) << data;
}
const auto serialized = toml::parse("tmp2.toml");
BOOST_CHECK(data == serialized);
}
BOOST_AUTO_TEST_CASE(test_fruit_with_comments)
{
const auto data = toml::parse<toml::preserve_comments>("toml/tests/fruit.toml");
{
std::ofstream ofs("tmp2_com.toml");
ofs << std::setw(80) << data;
}
const auto serialized = toml::parse<toml::preserve_comments>("tmp2_com.toml");
BOOST_CHECK(data == serialized);
}
BOOST_AUTO_TEST_CASE(test_hard_example)
{
const auto data = toml::parse("toml/tests/hard_example.toml");
{
std::ofstream ofs("tmp3.toml");
ofs << std::setw(80) << data;
}
const auto serialized = toml::parse("tmp3.toml");
BOOST_CHECK(data == serialized);
}
BOOST_AUTO_TEST_CASE(test_hard_example_with_comment)
{
const auto data = toml::parse<toml::preserve_comments>("toml/tests/hard_example.toml");
{
std::ofstream ofs("tmp3_com.toml");
ofs << std::setw(80) << data;
}
const auto serialized = toml::parse<toml::preserve_comments>("tmp3_com.toml");
{
std::ofstream ofs("tmp3_com1.toml");
ofs << std::setw(80) << serialized;
}
BOOST_CHECK(data == serialized);
}
<|endoftext|>
|
<commit_before>/*
* Copyright 2019 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "node.h"
#include <folly/portability/Unistd.h>
#include <nlohmann/json.hpp>
#include <platform/dirutils.h>
#include <platform/strerror.h>
#include <protocol/connection/client_connection_map.h>
#ifndef WIN32
#include <signal.h>
#include <sys/wait.h>
#endif
#include <chrono>
#include <fstream>
#include <iostream>
#include <thread>
namespace cb::test {
Node::~Node() = default;
Node::Node(std::string directory) : directory(std::move(directory)) {
}
class NodeImpl : public Node {
public:
NodeImpl(std::string directory, std::string id);
~NodeImpl() override;
void startMemcachedServer();
std::unique_ptr<MemcachedConnection> getConnection() override;
protected:
void parsePortnumberFile();
std::string configfile;
nlohmann::json config;
ConnectionMap connectionMap;
const std::string id;
};
NodeImpl::NodeImpl(std::string directory, std::string id)
: Node(std::move(directory)), id(std::move(id)) {
const auto errmaps =
cb::io::sanitizePath(SOURCE_ROOT "/etc/couchbase/kv/error_maps");
const auto rbac = cb::io::sanitizePath(SOURCE_ROOT
"/tests/testapp_cluster/rbac.json");
const auto log_filename =
cb::io::sanitizePath(NodeImpl::directory + "/memcached_log");
const auto portnumber_file =
cb::io::sanitizePath(NodeImpl::directory + "/memcached.ports.json");
const auto minidump_dir =
cb::io::sanitizePath(NodeImpl::directory + "/crash");
cb::io::mkdirp(minidump_dir);
config = {{"max_connections", 1000},
{"system_connections", 250},
{"stdin_listener", false},
{"datatype_json", true},
{"datatype_snappy", true},
{"xattr_enabled", true},
{"dedupe_nmvb_maps", false},
{"active_external_users_push_interval", "30 m"},
{"error_maps_dir", errmaps},
{"external_auth_service", true},
{"rbac_file", rbac},
{"ssl_cipher_list", "HIGH"},
{"ssl_minimum_protocol", "tlsv1"},
{"opcode_attributes_override",
{{"version", 1}, {"EWB_CTL", {{"slow", 50}}}}},
{"logger",
{{"unit_test", true},
{"console", false},
{"filename", log_filename}}},
{"breakpad",
{{"enabled", true},
{"minidump_dir", minidump_dir},
{"content", "default"}}},
{"portnumber_file", portnumber_file},
{"parent_identifier", (int)getpid()}};
config["interfaces"][0] = {{"tag", "plain"},
{"system", true},
{"port", 0},
{"ipv4", "required"},
{"host", "*"}};
configfile = cb::io::sanitizePath(NodeImpl::directory + "/memcached.json");
std::ofstream out(configfile);
out << config.dump(2);
out.close();
}
void NodeImpl::startMemcachedServer() {
#ifdef WIN32
STARTUPINFO sinfo{};
PROCESS_INFORMATION pinfo{};
sinfo.cb = sizeof(sinfo);
char commandline[1024];
sprintf(commandline, "memcached.exe -C %s", configfile.c_str());
if (!CreateProcess("memcached.exe", // lpApplicationName
commandline, // lpCommandLine
nullptr, // lpProcessAttributes
nullptr, // lpThreadAttributes
false, // bInheritHandles
0, // dwCreationFlags
nullptr, // lpEnvironment
nullptr, // lpCurrentDirectory
&sinfo, // lpStartupInfo
&pinfo)) { // lpProcessInfoqrmation
throw std::system_error(GetLastError(),
std::system_category(),
"Failed to execute memcached");
}
child = pinfo.hProcess;
#else
child = fork();
if (child == -1) {
throw std::system_error(
errno, std::system_category(), "Failed to start client");
}
if (child == 0) {
std::string binary(OBJECT_ROOT);
binary.append("/memcached");
const char* argv[20];
int arg = 0;
argv[arg++] = binary.c_str();
argv[arg++] = "-C";
argv[arg++] = configfile.c_str();
argv[arg++] = nullptr;
execvp(argv[0], const_cast<char**>(argv));
throw std::system_error(
errno, std::system_category(), "Failed to execute memcached");
}
#endif
// wait and read the portnumber file
parsePortnumberFile();
}
NodeImpl::~NodeImpl() {
if (isRunning()) {
#ifdef WIN32
// @todo This should be made a bit more robust
TerminateProcess(child, 0);
WaitForSingleObject(child, 60000);
DWORD status;
GetExitCodeProcess(child, &status);
#else
// Start by giving it a slow and easy start...
const auto timeout =
std::chrono::steady_clock::now() + std::chrono::seconds(15);
kill(child, SIGTERM);
do {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
} while (isRunning() && std::chrono::steady_clock::now() < timeout);
if (isRunning()) {
// no mercy!
kill(child, SIGKILL);
int status;
pid_t ret;
while (true) {
ret = waitpid(child, &status, 0);
if (ret == reinterpret_cast<pid_t>(-1) && errno == EINTR) {
// Just loop again
continue;
}
break;
}
}
#endif
}
if (!configfile.empty()) {
try {
cb::io::rmrf(configfile);
} catch (const std::exception& e) {
std::cerr << "WARNING: Failed to remove \"" << configfile
<< "\": " << e.what() << std::endl;
}
}
}
void NodeImpl::parsePortnumberFile() {
connectionMap.initialize(nlohmann::json::parse(cb::io::loadFile(
config["portnumber_file"], std::chrono::minutes{5})));
cb::io::rmrf(config["portnumber_file"]);
}
#ifdef WIN32
bool Node::isRunning() const {
if (child != INVALID_HANDLE_VALUE) {
DWORD status;
if (!GetExitCodeProcess(child, &status)) {
throw std::system_error(
GetLastError(),
std::system_category(),
"NodeImpl::isRunning: GetExitCodeProcess failed");
std::cerr << "GetExitCodeProcess: failed: " << cb_strerror()
<< std::endl;
exit(EXIT_FAILURE);
}
if (status == STILL_ACTIVE) {
return true;
}
CloseHandle(child);
child = INVALID_HANDLE_VALUE;
}
return false;
}
#else
bool Node::isRunning() const {
if (child != 0) {
int status;
auto next = waitpid(child, &status, WNOHANG);
if (next == static_cast<pid_t>(-1)) {
throw std::system_error(errno,
std::system_category(),
"NodeImpl::isRunning: waitpid failed");
}
if (next == child) {
child = 0;
return false;
}
return true;
}
return false;
}
#endif
std::unique_ptr<MemcachedConnection> NodeImpl::getConnection() {
auto ret = connectionMap.getConnection().clone();
ret->setAutoRetryTmpfail(true);
std::vector<cb::mcbp::Feature> features = {
{cb::mcbp::Feature::MUTATION_SEQNO,
cb::mcbp::Feature::XATTR,
cb::mcbp::Feature::XERROR,
cb::mcbp::Feature::JSON}};
ret->setFeatures("cluster_testapp", features);
return ret;
}
std::unique_ptr<Node> Node::create(const std::string& directory,
const std::string& id) {
auto ret = std::make_unique<NodeImpl>(directory, id);
ret->startMemcachedServer();
return ret;
}
} // namespace cb::test
<commit_msg>[cluster_test] Add error handling in node shutdown WIN32<commit_after>/*
* Copyright 2019 Couchbase, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "node.h"
#include <folly/portability/Unistd.h>
#include <nlohmann/json.hpp>
#include <platform/dirutils.h>
#include <platform/strerror.h>
#include <protocol/connection/client_connection_map.h>
#ifndef WIN32
#include <signal.h>
#include <sys/wait.h>
#endif
#include <chrono>
#include <fstream>
#include <iostream>
#include <thread>
namespace cb::test {
Node::~Node() = default;
Node::Node(std::string directory) : directory(std::move(directory)) {
}
class NodeImpl : public Node {
public:
NodeImpl(std::string directory, std::string id);
~NodeImpl() override;
void startMemcachedServer();
std::unique_ptr<MemcachedConnection> getConnection() override;
protected:
void parsePortnumberFile();
std::string configfile;
nlohmann::json config;
ConnectionMap connectionMap;
const std::string id;
};
NodeImpl::NodeImpl(std::string directory, std::string id)
: Node(std::move(directory)), id(std::move(id)) {
const auto errmaps =
cb::io::sanitizePath(SOURCE_ROOT "/etc/couchbase/kv/error_maps");
const auto rbac = cb::io::sanitizePath(SOURCE_ROOT
"/tests/testapp_cluster/rbac.json");
const auto log_filename =
cb::io::sanitizePath(NodeImpl::directory + "/memcached_log");
const auto portnumber_file =
cb::io::sanitizePath(NodeImpl::directory + "/memcached.ports.json");
const auto minidump_dir =
cb::io::sanitizePath(NodeImpl::directory + "/crash");
cb::io::mkdirp(minidump_dir);
config = {{"max_connections", 1000},
{"system_connections", 250},
{"stdin_listener", false},
{"datatype_json", true},
{"datatype_snappy", true},
{"xattr_enabled", true},
{"dedupe_nmvb_maps", false},
{"active_external_users_push_interval", "30 m"},
{"error_maps_dir", errmaps},
{"external_auth_service", true},
{"rbac_file", rbac},
{"ssl_cipher_list", "HIGH"},
{"ssl_minimum_protocol", "tlsv1"},
{"opcode_attributes_override",
{{"version", 1}, {"EWB_CTL", {{"slow", 50}}}}},
{"logger",
{{"unit_test", true},
{"console", false},
{"filename", log_filename}}},
{"breakpad",
{{"enabled", true},
{"minidump_dir", minidump_dir},
{"content", "default"}}},
{"portnumber_file", portnumber_file},
{"parent_identifier", (int)getpid()}};
config["interfaces"][0] = {{"tag", "plain"},
{"system", true},
{"port", 0},
{"ipv4", "required"},
{"host", "*"}};
configfile = cb::io::sanitizePath(NodeImpl::directory + "/memcached.json");
std::ofstream out(configfile);
out << config.dump(2);
out.close();
}
void NodeImpl::startMemcachedServer() {
#ifdef WIN32
STARTUPINFO sinfo{};
PROCESS_INFORMATION pinfo{};
sinfo.cb = sizeof(sinfo);
char commandline[1024];
sprintf(commandline, "memcached.exe -C %s", configfile.c_str());
if (!CreateProcess("memcached.exe", // lpApplicationName
commandline, // lpCommandLine
nullptr, // lpProcessAttributes
nullptr, // lpThreadAttributes
false, // bInheritHandles
0, // dwCreationFlags
nullptr, // lpEnvironment
nullptr, // lpCurrentDirectory
&sinfo, // lpStartupInfo
&pinfo)) { // lpProcessInfoqrmation
throw std::system_error(GetLastError(),
std::system_category(),
"Failed to execute memcached");
}
child = pinfo.hProcess;
#else
child = fork();
if (child == -1) {
throw std::system_error(
errno, std::system_category(), "Failed to start client");
}
if (child == 0) {
std::string binary(OBJECT_ROOT);
binary.append("/memcached");
const char* argv[20];
int arg = 0;
argv[arg++] = binary.c_str();
argv[arg++] = "-C";
argv[arg++] = configfile.c_str();
argv[arg++] = nullptr;
execvp(argv[0], const_cast<char**>(argv));
throw std::system_error(
errno, std::system_category(), "Failed to execute memcached");
}
#endif
// wait and read the portnumber file
parsePortnumberFile();
}
NodeImpl::~NodeImpl() {
if (isRunning()) {
#ifdef WIN32
// @todo This should be made a bit more robust
if (!TerminateProcess(child, 0)) {
std::cerr << "TerminateProcess failed!" << std::endl;
std::cerr.flush();
_exit(EXIT_FAILURE);
}
DWORD status;
if ((status = WaitForSingleObject(child, 60000)) != WAIT_OBJECT_0) {
std::cerr << "Unexpected return value from WaitForSingleObject: "
<< status << std::endl;
std::cerr.flush();
_exit(EXIT_FAILURE);
}
if (!GetExitCodeProcess(child, &status)) {
std::cerr << "GetExitCodeProcess failed: " << GetLastError()
<< std::endl;
std::cerr.flush();
_exit(EXIT_FAILURE);
}
#else
// Start by giving it a slow and easy start...
const auto timeout =
std::chrono::steady_clock::now() + std::chrono::seconds(15);
kill(child, SIGTERM);
do {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
} while (isRunning() && std::chrono::steady_clock::now() < timeout);
if (isRunning()) {
// no mercy!
kill(child, SIGKILL);
int status;
pid_t ret;
while (true) {
ret = waitpid(child, &status, 0);
if (ret == reinterpret_cast<pid_t>(-1) && errno == EINTR) {
// Just loop again
continue;
}
break;
}
}
#endif
}
if (!configfile.empty()) {
try {
cb::io::rmrf(configfile);
} catch (const std::exception& e) {
std::cerr << "WARNING: Failed to remove \"" << configfile
<< "\": " << e.what() << std::endl;
}
}
}
void NodeImpl::parsePortnumberFile() {
connectionMap.initialize(nlohmann::json::parse(cb::io::loadFile(
config["portnumber_file"], std::chrono::minutes{5})));
cb::io::rmrf(config["portnumber_file"]);
}
#ifdef WIN32
bool Node::isRunning() const {
if (child != INVALID_HANDLE_VALUE) {
DWORD status;
if (!GetExitCodeProcess(child, &status)) {
throw std::system_error(
GetLastError(),
std::system_category(),
"NodeImpl::isRunning: GetExitCodeProcess failed");
std::cerr << "GetExitCodeProcess: failed: " << cb_strerror()
<< std::endl;
exit(EXIT_FAILURE);
}
if (status == STILL_ACTIVE) {
return true;
}
CloseHandle(child);
child = INVALID_HANDLE_VALUE;
}
return false;
}
#else
bool Node::isRunning() const {
if (child != 0) {
int status;
auto next = waitpid(child, &status, WNOHANG);
if (next == static_cast<pid_t>(-1)) {
throw std::system_error(errno,
std::system_category(),
"NodeImpl::isRunning: waitpid failed");
}
if (next == child) {
child = 0;
return false;
}
return true;
}
return false;
}
#endif
std::unique_ptr<MemcachedConnection> NodeImpl::getConnection() {
auto ret = connectionMap.getConnection().clone();
ret->setAutoRetryTmpfail(true);
std::vector<cb::mcbp::Feature> features = {
{cb::mcbp::Feature::MUTATION_SEQNO,
cb::mcbp::Feature::XATTR,
cb::mcbp::Feature::XERROR,
cb::mcbp::Feature::JSON}};
ret->setFeatures("cluster_testapp", features);
return ret;
}
std::unique_ptr<Node> Node::create(const std::string& directory,
const std::string& id) {
auto ret = std::make_unique<NodeImpl>(directory, id);
ret->startMemcachedServer();
return ret;
}
} // namespace cb::test
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: versioner.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2003-04-01 13:17:07 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "versionhelper.hxx"
#include <rtl/ustring.hxx>
#include <iostream>
// ----------------------------------- Main -----------------------------------
#if (defined UNX) || (defined OS2)
int main( int argc, char* argv[] )
#else
int _cdecl main( int argc, char* argv[] )
#endif
{
static char* optionSet[] = {
"-time, display time only",
"-date, display date only",
"-upd, display UPD only",
"-minor, display minor only",
"-build, display build only",
"-inpath, display inpath only",
"-verbose, be verbose",
"-h:s, display help or help on option",
"-help:s, see -h",
NULL
};
GetOpt opt( argv, optionSet );
// someone indicates that he needs help
if ( opt.hasOpt( "-h" ) || opt.hasOpt( "-help" ) )
{
opt.showUsage();
exit(0);
}
if (opt.getParams().empty())
{
// std::cerr << "error: At least a library should given." << std::endl;
fprintf(stderr, "error: At least a library should given.\n");
opt.showUsage();
exit(0);
}
rtl::OUString suLibraryName = rtl::OStringToOUString(opt.getFirstParam(), RTL_TEXTENCODING_ASCII_US );
VersionHelper aHelper(suLibraryName, opt);
if (! aHelper.isOk() )
{
fprintf(stderr, "error: No version info found.\n");
exit(1);
}
if (opt.hasOpt("-time"))
{
fprintf(stdout, "%s\n", aHelper.getTime().getStr());
}
else if (opt.hasOpt("-date"))
{
fprintf(stdout, "%s\n", aHelper.getDate().getStr());
}
else if (opt.hasOpt("-upd"))
{
fprintf(stdout, "%s\n", aHelper.getUpd().getStr());
}
else if (opt.hasOpt("-minor"))
{
fprintf(stdout, "%s\n", aHelper.getMinor().getStr());
}
else if (opt.hasOpt("-build"))
{
fprintf(stdout, "%s\n", aHelper.getBuild().getStr());
}
else if (opt.hasOpt("-inpath"))
{
fprintf(stdout, "%s\n", aHelper.getInpath().getStr());
}
else
{
// std::cout << aHelper << std::endl;
aHelper.printall(stdout);
}
return 0;
}
<commit_msg>INTEGRATION: CWS ooo19126 (1.5.70); FILE MERGED 2005/09/05 17:28:45 rt 1.5.70.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: versioner.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-09-09 12:08:18 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "versionhelper.hxx"
#include <rtl/ustring.hxx>
#include <iostream>
// ----------------------------------- Main -----------------------------------
#if (defined UNX) || (defined OS2)
int main( int argc, char* argv[] )
#else
int _cdecl main( int argc, char* argv[] )
#endif
{
static char* optionSet[] = {
"-time, display time only",
"-date, display date only",
"-upd, display UPD only",
"-minor, display minor only",
"-build, display build only",
"-inpath, display inpath only",
"-verbose, be verbose",
"-h:s, display help or help on option",
"-help:s, see -h",
NULL
};
GetOpt opt( argv, optionSet );
// someone indicates that he needs help
if ( opt.hasOpt( "-h" ) || opt.hasOpt( "-help" ) )
{
opt.showUsage();
exit(0);
}
if (opt.getParams().empty())
{
// std::cerr << "error: At least a library should given." << std::endl;
fprintf(stderr, "error: At least a library should given.\n");
opt.showUsage();
exit(0);
}
rtl::OUString suLibraryName = rtl::OStringToOUString(opt.getFirstParam(), RTL_TEXTENCODING_ASCII_US );
VersionHelper aHelper(suLibraryName, opt);
if (! aHelper.isOk() )
{
fprintf(stderr, "error: No version info found.\n");
exit(1);
}
if (opt.hasOpt("-time"))
{
fprintf(stdout, "%s\n", aHelper.getTime().getStr());
}
else if (opt.hasOpt("-date"))
{
fprintf(stdout, "%s\n", aHelper.getDate().getStr());
}
else if (opt.hasOpt("-upd"))
{
fprintf(stdout, "%s\n", aHelper.getUpd().getStr());
}
else if (opt.hasOpt("-minor"))
{
fprintf(stdout, "%s\n", aHelper.getMinor().getStr());
}
else if (opt.hasOpt("-build"))
{
fprintf(stdout, "%s\n", aHelper.getBuild().getStr());
}
else if (opt.hasOpt("-inpath"))
{
fprintf(stdout, "%s\n", aHelper.getInpath().getStr());
}
else
{
// std::cout << aHelper << std::endl;
aHelper.printall(stdout);
}
return 0;
}
<|endoftext|>
|
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osgDB/FileNameUtils>
#if defined(__sgi)
#include <ctype.h>
#elif defined(__GNUC__) || !defined(WIN32) || defined(__MWERKS__)
#include <cctype>
using std::tolower;
using std::strlen;
#endif
#include <osg/Notify>
using namespace std;
std::string osgDB::getFilePath(const std::string& fileName)
{
std::string::size_type slash1 = fileName.find_last_of('/');
std::string::size_type slash2 = fileName.find_last_of('\\');
if (slash1==std::string::npos)
{
if (slash2==std::string::npos) return std::string();
return std::string(fileName,0,slash2);
}
if (slash2==std::string::npos) return std::string(fileName,0,slash1);
return std::string(fileName, 0, slash1>slash2 ? slash1 : slash2);
}
std::string osgDB::getSimpleFileName(const std::string& fileName)
{
std::string::size_type slash1 = fileName.find_last_of('/');
std::string::size_type slash2 = fileName.find_last_of('\\');
if (slash1==std::string::npos)
{
if (slash2==std::string::npos) return fileName;
return std::string(fileName.begin()+slash2+1,fileName.end());
}
if (slash2==std::string::npos) return std::string(fileName.begin()+slash1+1,fileName.end());
return std::string(fileName.begin()+(slash1>slash2?slash1:slash2)+1,fileName.end());
}
std::string osgDB::getFileExtension(const std::string& fileName)
{
std::string::size_type dot = fileName.find_last_of('.');
if (dot==std::string::npos) return std::string("");
return std::string(fileName.begin()+dot+1,fileName.end());
}
std::string osgDB::convertFileNameToWindowsStyle(const std::string& fileName)
{
std::string new_fileName(fileName);
std::string::size_type slash = 0;
while( (slash=new_fileName.find_first_of('/',slash)) != std::string::npos)
{
new_fileName[slash]='\\';
}
return new_fileName;
}
std::string osgDB::convertFileNameToUnixStyle(const std::string& fileName)
{
osg::notify(osg::NOTICE)<<"convertFileNameToUnixStyle("<<fileName<<")"<<std::endl;
std::string new_fileName(fileName);
std::string::size_type slash = 0;
while( (slash=new_fileName.find_first_of('\\',slash)) != std::string::npos)
{
new_fileName[slash]='/';
}
osg::notify(osg::NOTICE)<<"convertFileNameToUnixStyle("<<new_fileName<<")"<<std::endl;
return new_fileName;
}
bool osgDB::isFileNameNativeStyle(const std::string& fileName)
{
#ifdef WIN32
return fileName.find('/') == std::string::npos; // return true if no unix style slash exist
#else
return fileName.find('\\') == std::string::npos; // return true if no windows style slash exist
#endif
}
std::string osgDB::convertFileNameToNativeStyle(const std::string& fileName)
{
#ifdef WIN32
return convertFileNameToWindowsStyle(fileName);
#else
return convertFileNameToUnixStyle(fileName);
#endif
}
std::string osgDB::getLowerCaseFileExtension(const std::string& filename)
{
std::string ext = osgDB::getFileExtension(filename);
for(std::string::iterator itr=ext.begin();
itr!=ext.end();
++itr)
{
*itr = tolower(*itr);
}
return ext;
}
// strip one level of extension from the filename.
std::string osgDB::getNameLessExtension(const std::string& fileName)
{
std::string::size_type dot = fileName.find_last_of('.');
if (dot==std::string::npos) return fileName;
return std::string(fileName.begin(),fileName.begin()+dot);
}
std::string osgDB::getStrippedName(const std::string& fileName)
{
std::string simpleName = getSimpleFileName(fileName);
return getNameLessExtension( simpleName );
}
bool osgDB::equalCaseInsensitive(const std::string& lhs,const std::string& rhs)
{
if (lhs.size()!=rhs.size()) return false;
std::string::const_iterator litr = lhs.begin();
std::string::const_iterator ritr = rhs.begin();
while (litr!=lhs.end())
{
if (tolower(*litr)!=tolower(*ritr)) return false;
++litr;
++ritr;
}
return true;
}
bool osgDB::equalCaseInsensitive(const std::string& lhs,const char* rhs)
{
if (rhs==NULL || lhs.size()!=strlen(rhs)) return false;
std::string::const_iterator litr = lhs.begin();
const char* cptr = rhs;
while (litr!=lhs.end())
{
if (tolower(*litr)!=tolower(*cptr)) return false;
++litr;
++cptr;
}
return true;
}
bool osgDB::containsServerAddress(const std::string& filename)
{
// need to check for http://
if (filename.size()<7) return false;
if (filename.compare(0,7,"http://")==0) return true;
return false;
}
std::string osgDB::getServerAddress(const std::string& filename)
{
if (filename.size()>=7 && filename.compare(0,7,"http://")==0)
{
std::string::size_type pos_slash = filename.find_first_of('/',7);
if (pos_slash!=std::string::npos)
{
return filename.substr(7,pos_slash-7);
}
else
{
return filename.substr(7,std::string::npos);
}
}
return "";
}
std::string osgDB::getServerFileName(const std::string& filename)
{
if (filename.size()>=7 && filename.compare(0,7,"http://")==0)
{
std::string::size_type pos_slash = filename.find_first_of('/',7);
if (pos_slash!=std::string::npos)
{
return filename.substr(pos_slash+1,std::string::npos);
}
else
{
return "";
}
}
return filename;
}
// // here a little test I wrote to make sure a couple of the above methods are
// // working fine.
// void test()
// {
// std::string test("/here/we/are.exe");
// std::string test2("\\there\\you\\go.dll");
// std::cout << "getFilePath("<<test<<") "<<osgDB::getFilePath(test)<<std::endl;
// std::cout << "getFilePath("<<test2<<") "<<osgDB::getFilePath(test2)<<std::endl;
// std::cout << "getSimpleFileName("<<test<<") "<<osgDB::getSimpleFileName(test)<<std::endl;
// std::cout << "getSimpleFileName("<<test2<<") "<<osgDB::getSimpleFileName(test2)<<std::endl;
// std::cout << "getStrippedName("<<test<<") "<<osgDB::getStrippedName(test)<<std::endl;
// std::cout << "getStrippedName("<<test2<<") "<<osgDB::getStrippedName(test2)<<std::endl;
// }
<commit_msg>Removed debugging messages<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2003 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osgDB/FileNameUtils>
#if defined(__sgi)
#include <ctype.h>
#elif defined(__GNUC__) || !defined(WIN32) || defined(__MWERKS__)
#include <cctype>
using std::tolower;
using std::strlen;
#endif
using namespace std;
std::string osgDB::getFilePath(const std::string& fileName)
{
std::string::size_type slash1 = fileName.find_last_of('/');
std::string::size_type slash2 = fileName.find_last_of('\\');
if (slash1==std::string::npos)
{
if (slash2==std::string::npos) return std::string();
return std::string(fileName,0,slash2);
}
if (slash2==std::string::npos) return std::string(fileName,0,slash1);
return std::string(fileName, 0, slash1>slash2 ? slash1 : slash2);
}
std::string osgDB::getSimpleFileName(const std::string& fileName)
{
std::string::size_type slash1 = fileName.find_last_of('/');
std::string::size_type slash2 = fileName.find_last_of('\\');
if (slash1==std::string::npos)
{
if (slash2==std::string::npos) return fileName;
return std::string(fileName.begin()+slash2+1,fileName.end());
}
if (slash2==std::string::npos) return std::string(fileName.begin()+slash1+1,fileName.end());
return std::string(fileName.begin()+(slash1>slash2?slash1:slash2)+1,fileName.end());
}
std::string osgDB::getFileExtension(const std::string& fileName)
{
std::string::size_type dot = fileName.find_last_of('.');
if (dot==std::string::npos) return std::string("");
return std::string(fileName.begin()+dot+1,fileName.end());
}
std::string osgDB::convertFileNameToWindowsStyle(const std::string& fileName)
{
std::string new_fileName(fileName);
std::string::size_type slash = 0;
while( (slash=new_fileName.find_first_of('/',slash)) != std::string::npos)
{
new_fileName[slash]='\\';
}
return new_fileName;
}
std::string osgDB::convertFileNameToUnixStyle(const std::string& fileName)
{
std::string new_fileName(fileName);
std::string::size_type slash = 0;
while( (slash=new_fileName.find_first_of('\\',slash)) != std::string::npos)
{
new_fileName[slash]='/';
}
return new_fileName;
}
bool osgDB::isFileNameNativeStyle(const std::string& fileName)
{
#ifdef WIN32
return fileName.find('/') == std::string::npos; // return true if no unix style slash exist
#else
return fileName.find('\\') == std::string::npos; // return true if no windows style slash exist
#endif
}
std::string osgDB::convertFileNameToNativeStyle(const std::string& fileName)
{
#ifdef WIN32
return convertFileNameToWindowsStyle(fileName);
#else
return convertFileNameToUnixStyle(fileName);
#endif
}
std::string osgDB::getLowerCaseFileExtension(const std::string& filename)
{
std::string ext = osgDB::getFileExtension(filename);
for(std::string::iterator itr=ext.begin();
itr!=ext.end();
++itr)
{
*itr = tolower(*itr);
}
return ext;
}
// strip one level of extension from the filename.
std::string osgDB::getNameLessExtension(const std::string& fileName)
{
std::string::size_type dot = fileName.find_last_of('.');
if (dot==std::string::npos) return fileName;
return std::string(fileName.begin(),fileName.begin()+dot);
}
std::string osgDB::getStrippedName(const std::string& fileName)
{
std::string simpleName = getSimpleFileName(fileName);
return getNameLessExtension( simpleName );
}
bool osgDB::equalCaseInsensitive(const std::string& lhs,const std::string& rhs)
{
if (lhs.size()!=rhs.size()) return false;
std::string::const_iterator litr = lhs.begin();
std::string::const_iterator ritr = rhs.begin();
while (litr!=lhs.end())
{
if (tolower(*litr)!=tolower(*ritr)) return false;
++litr;
++ritr;
}
return true;
}
bool osgDB::equalCaseInsensitive(const std::string& lhs,const char* rhs)
{
if (rhs==NULL || lhs.size()!=strlen(rhs)) return false;
std::string::const_iterator litr = lhs.begin();
const char* cptr = rhs;
while (litr!=lhs.end())
{
if (tolower(*litr)!=tolower(*cptr)) return false;
++litr;
++cptr;
}
return true;
}
bool osgDB::containsServerAddress(const std::string& filename)
{
// need to check for http://
if (filename.size()<7) return false;
if (filename.compare(0,7,"http://")==0) return true;
return false;
}
std::string osgDB::getServerAddress(const std::string& filename)
{
if (filename.size()>=7 && filename.compare(0,7,"http://")==0)
{
std::string::size_type pos_slash = filename.find_first_of('/',7);
if (pos_slash!=std::string::npos)
{
return filename.substr(7,pos_slash-7);
}
else
{
return filename.substr(7,std::string::npos);
}
}
return "";
}
std::string osgDB::getServerFileName(const std::string& filename)
{
if (filename.size()>=7 && filename.compare(0,7,"http://")==0)
{
std::string::size_type pos_slash = filename.find_first_of('/',7);
if (pos_slash!=std::string::npos)
{
return filename.substr(pos_slash+1,std::string::npos);
}
else
{
return "";
}
}
return filename;
}
// // here a little test I wrote to make sure a couple of the above methods are
// // working fine.
// void test()
// {
// std::string test("/here/we/are.exe");
// std::string test2("\\there\\you\\go.dll");
// std::cout << "getFilePath("<<test<<") "<<osgDB::getFilePath(test)<<std::endl;
// std::cout << "getFilePath("<<test2<<") "<<osgDB::getFilePath(test2)<<std::endl;
// std::cout << "getSimpleFileName("<<test<<") "<<osgDB::getSimpleFileName(test)<<std::endl;
// std::cout << "getSimpleFileName("<<test2<<") "<<osgDB::getSimpleFileName(test2)<<std::endl;
// std::cout << "getStrippedName("<<test<<") "<<osgDB::getStrippedName(test)<<std::endl;
// std::cout << "getStrippedName("<<test2<<") "<<osgDB::getStrippedName(test2)<<std::endl;
// }
<|endoftext|>
|
<commit_before>/**********************************************************************
*
* FILE: Text.cpp
*
* DESCRIPTION: Read/Write osgText::Text in binary format to disk.
*
* CREATED BY: Auto generated by iveGenerator
* and later modified by Rune Schmidt Jensen.
*
* HISTORY: Created 27.3.2003
*
* Copyright 2003 VR-C
**********************************************************************/
#include "Exception.h"
#include "Text.h"
#include "Drawable.h"
#include "Object.h"
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osg/Notify>
using namespace ive;
void Text::write(DataOutputStream* out){
// Write Text's identification.
out->writeInt(IVETEXT);
// If the osg class is inherited by any other class we should also write this to file.
osg::Object* obj = dynamic_cast<osg::Object*>(this);
if(obj){
((ive::Drawable*)(obj))->write(out);
}
else
throw Exception("Text::write(): Could not cast this osgText::Text to an osg::Drawable.");
// Write Text's properties.
if( getFont() )
{
std::string fname = getFont()->getFileName();
if(!fname.empty())
{
if(out->getUseOriginalExternalReferences())
{
out->writeString(fname); //Saving file name with local directory
}
else
{
out->writeString(osgDB::getSimpleFileName(fname)); //Saving original file name
}
}
else
out->writeString(""); //Blank string
}
else
out->writeString(""); //Blank string
out->writeUInt(getFontWidth());
out->writeUInt(getFontHeight());
out->writeFloat(getCharacterHeight());
out->writeFloat(getCharacterAspectRatio());
out->writeUInt(getCharacterSizeMode());
out->writeFloat(getMaximumWidth());
out->writeFloat(getMaximumHeight());
out->writeUInt(getAlignment());
out->writeQuat(getRotation()); //FIXME: controllare che ci sia
out->writeBool(getAutoRotateToScreen());
out->writeUInt(getLayout());
out->writeVec3(getPosition());
out->writeVec4(getColor());
out->writeUInt(getDrawMode());
// text :: Modified from osgPlugins::osg
const osgText::String& textstring = getText();
bool isACString = true;
osgText::String::const_iterator itr;
for(itr=textstring.begin();
itr!=textstring.end() && isACString;
++itr)
{
if (*itr==0 || *itr>256) isACString=false;
}
if (isACString)
{
std::string str;
for(itr=textstring.begin();
itr!=textstring.end();
++itr)
{
str += (char)(*itr);
}
//std::copy(textstring.begin(),textstring.end(),std::back_inserter(str));
out->writeBool(true);
out->writeString(str);
}
else
{
// do it the hardway...output each character as an int
osg::ref_ptr<osg::UByteArray> strarr = new osg::UByteArray(textstring.size());
for(itr=textstring.begin();
itr!=textstring.end();
++itr)
{
strarr->push_back((char)(*itr));
}
out->writeBool(false);
out->writeUByteArray(strarr.get());
}
}
void Text::read(DataInputStream* in){
// Peek on Text's identification.
int id = in->peekInt();
if(id == IVETEXT){
// Read Text's identification.
id = in->readInt();
// If the osg class is inherited by any other class we should also read this from file.
osg::Object* obj = dynamic_cast<osg::Object*>(this);
if(obj){
((ive::Drawable*)(obj))->read(in);
}
else
throw Exception("Text::read(): Could not cast this osgText::Text to an osg::Drawable.");
// Read Text's properties
unsigned int width, height;
float c_height, aspectRatio;
setFont(in->readString());
width = in->readUInt();
height = in->readUInt();
setFontResolution(width,height);
c_height = in->readFloat();
aspectRatio = in->readFloat();
setCharacterSize(height,aspectRatio);
setCharacterSizeMode((osgText::Text::CharacterSizeMode) in->readUInt());
setMaximumWidth(in->readFloat());
setMaximumHeight(in->readFloat());
setAlignment((osgText::Text::AlignmentType) in->readUInt());
//Nothing to do...
//setAxisAlignment((osgText::Text::AxisAlignment) in->readUint());
setRotation(in->readQuat());
setAutoRotateToScreen(in->readBool());
setLayout((osgText::Text::Layout) in->readUInt());
setPosition(in->readVec3());
setColor(in->readVec4());
setDrawMode(in->readUInt());
if(in->readBool())
setText(in->readString());
else
{
std::string textstr;
osg::ref_ptr<osg::UByteArray> arr = in->readUByteArray();
for(unsigned int i = 0; i < arr->getNumElements(); i++)
{
textstr += (char) arr->at(i);
}
setText(textstr);
}
}
else{
throw Exception("ShadeModel::read(): Expected ShadeModel identification.");
}
}
<commit_msg>From Carlo Camporesi, fixed .ive handling of character height and aspect ratio.<commit_after>/**********************************************************************
*
* FILE: Text.cpp
*
* DESCRIPTION: Read/Write osgText::Text in binary format to disk.
*
* CREATED BY: Auto generated by iveGenerator
* and later modified by Rune Schmidt Jensen.
*
* HISTORY: Created 27.3.2003
*
* Copyright 2003 VR-C
**********************************************************************/
#include "Exception.h"
#include "Text.h"
#include "Drawable.h"
#include "Object.h"
#include <osgDB/FileUtils>
#include <osgDB/FileNameUtils>
#include <osg/Notify>
using namespace ive;
void Text::write(DataOutputStream* out){
// Write Text's identification.
out->writeInt(IVETEXT);
// If the osg class is inherited by any other class we should also write this to file.
osg::Object* obj = dynamic_cast<osg::Object*>(this);
if(obj){
((ive::Drawable*)(obj))->write(out);
}
else
throw Exception("Text::write(): Could not cast this osgText::Text to an osg::Drawable.");
// Write Text's properties.
if( getFont() )
{
std::string fname = getFont()->getFileName();
if(!fname.empty())
{
if(out->getUseOriginalExternalReferences())
{
out->writeString(fname); //Saving file name with local directory
}
else
{
out->writeString(osgDB::getSimpleFileName(fname)); //Saving original file name
}
}
else
out->writeString(""); //Blank string
}
else
out->writeString(""); //Blank string
out->writeUInt(getFontWidth());
out->writeUInt(getFontHeight());
out->writeFloat(getCharacterHeight());
out->writeFloat(getCharacterAspectRatio());
out->writeUInt(getCharacterSizeMode());
out->writeFloat(getMaximumWidth());
out->writeFloat(getMaximumHeight());
out->writeUInt(getAlignment());
out->writeQuat(getRotation()); //FIXME: controllare che ci sia
out->writeBool(getAutoRotateToScreen());
out->writeUInt(getLayout());
out->writeVec3(getPosition());
out->writeVec4(getColor());
out->writeUInt(getDrawMode());
// text :: Modified from osgPlugins::osg
const osgText::String& textstring = getText();
bool isACString = true;
osgText::String::const_iterator itr;
for(itr=textstring.begin();
itr!=textstring.end() && isACString;
++itr)
{
if (*itr==0 || *itr>256) isACString=false;
}
if (isACString)
{
std::string str;
for(itr=textstring.begin();
itr!=textstring.end();
++itr)
{
str += (char)(*itr);
}
//std::copy(textstring.begin(),textstring.end(),std::back_inserter(str));
out->writeBool(true);
out->writeString(str);
}
else
{
// do it the hardway...output each character as an int
osg::ref_ptr<osg::UByteArray> strarr = new osg::UByteArray(textstring.size());
for(itr=textstring.begin();
itr!=textstring.end();
++itr)
{
strarr->push_back((char)(*itr));
}
out->writeBool(false);
out->writeUByteArray(strarr.get());
}
}
void Text::read(DataInputStream* in){
// Peek on Text's identification.
int id = in->peekInt();
if(id == IVETEXT){
// Read Text's identification.
id = in->readInt();
// If the osg class is inherited by any other class we should also read this from file.
osg::Object* obj = dynamic_cast<osg::Object*>(this);
if(obj){
((ive::Drawable*)(obj))->read(in);
}
else
throw Exception("Text::read(): Could not cast this osgText::Text to an osg::Drawable.");
// Read Text's properties
unsigned int width, height;
float c_height, aspectRatio;
setFont(in->readString());
width = in->readUInt();
height = in->readUInt();
setFontResolution(width,height);
c_height = in->readFloat();
aspectRatio = in->readFloat();
setCharacterSize(c_height,aspectRatio);
setCharacterSizeMode((osgText::Text::CharacterSizeMode) in->readUInt());
setMaximumWidth(in->readFloat());
setMaximumHeight(in->readFloat());
setAlignment((osgText::Text::AlignmentType) in->readUInt());
//Nothing to do...
//setAxisAlignment((osgText::Text::AxisAlignment) in->readUint());
setRotation(in->readQuat());
setAutoRotateToScreen(in->readBool());
setLayout((osgText::Text::Layout) in->readUInt());
setPosition(in->readVec3());
setColor(in->readVec4());
setDrawMode(in->readUInt());
if(in->readBool())
setText(in->readString());
else
{
std::string textstr;
osg::ref_ptr<osg::UByteArray> arr = in->readUByteArray();
for(unsigned int i = 0; i < arr->getNumElements(); i++)
{
textstr += (char) arr->at(i);
}
setText(textstr);
}
}
else{
throw Exception("ShadeModel::read(): Expected ShadeModel identification.");
}
}
<|endoftext|>
|
<commit_before>//////////////////////////////////////////////////////////////////////////////
// oxygenwindowmanager.cpp
// pass some window mouse press/release/move event actions to window manager
// -------------------
//
// Copyright (c) 2010 Cédric Bellegarde <gnumdk@gmail.com>
//
// Largely inspired from Qtcurve style
// Copyright (C) Craig Drummond, 2003 - 2010 craig.p.drummond@gmail.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//////////////////////////////////////////////////////////////////////////////
#include <string>
#include "oxygenwindowmanager.h"
#include "oxygenstyle.h"
#define GE_IS_CONTAINER(object) ((object) && objectIsA((GObject*)(object), "GtkContainer"))
#define GE_IS_WIDGET(object) ((object) && objectIsA((GObject*)(object), "GtkWidget"))
#define GE_IS_MENUITEM(object) ((object) && objectIsA((GObject*)(object), "GtkMenuItem"))
#define GE_IS_SCROLL(object) ((object) && objectIsA((GObject*)(object), "GtkScrolledWindow"))
#define GE_IS_NOTEBOOK(object) ((object) && objectIsA((GObject*)(object), "GtkNotebook"))
namespace Oxygen
{
namespace Gtk
{
static bool drag = FALSE;
// check object type
static bool objectIsA( const GObject * object, const gchar * type_name )
{
if( ( object ) )
{
GType tmp = g_type_from_name( type_name );
if( tmp )
return g_type_check_instance_is_a( ( GTypeInstance * ) object, tmp );
}
return false;
}
//_________________________________________________
WindowManager::WindowManager( GtkWidget *widget )
{
// setup window management
if( !g_object_get_data( G_OBJECT( widget ), "OXYGEN_WM_MOVE_HACK_SET" ) )
{
// Force widget to listen to events
gtk_widget_add_events( widget, GDK_BUTTON_RELEASE_MASK |
GDK_BUTTON_PRESS_MASK |
GDK_LEAVE_NOTIFY_MASK |
GDK_BUTTON1_MOTION_MASK );
g_object_set_data( G_OBJECT( widget ), "OXYGEN_WM_MOVE_HACK_SET", ( gpointer )1 );
_leaveId.connect( G_OBJECT( widget ), "leave-notify-event", G_CALLBACK( wmButtonRelease ), NULL );
_destroyId.connect( G_OBJECT( widget ), "destroy-event", G_CALLBACK( wmDestroy ), this );
_styleId.connect( G_OBJECT( widget ), "style-set", G_CALLBACK( wmStyleSet ), this );
_pressId.connect( G_OBJECT( widget ), "button-press-event", G_CALLBACK( wmButtonPress ), widget );
_releaseId.connect( G_OBJECT( widget ), "button-release-event", G_CALLBACK( wmButtonRelease ), widget );
_motionId.connect( G_OBJECT( widget ), "motion-notify-event", G_CALLBACK( wmMotion ), NULL );
_widget = widget;
}
else
_widget = NULL;
}
//_________________________________________________
WindowManager::~WindowManager()
{
if( _widget )
{
_leaveId.disconnect();
_destroyId.disconnect();
_styleId.disconnect();
_pressId.disconnect();
_releaseId.disconnect();
g_object_steal_data( G_OBJECT( _widget ), "OXYGEN_WM_MOVE_HACK_SET" );
}
}
//_________________________________________________
bool WindowManager::isValid()
{
return _widget != NULL;
}
//_________________________________________________
bool WindowManager::isWindowDragWidget( GtkWidget *widget, GdkEventButton *event )
{
return withinWidget(widget, event ) && useEvent( widget, event );
}
//_________________________________________________
bool WindowManager::withinWidget( GtkWidget *widget, GdkEventButton *event )
{
GtkAllocation alloc;
GdkWindow *window = gtk_widget_get_parent_window( widget );
int nx = 0,
ny = 0;
if( !window )
return true;
/* Need to get absolute co-ordinates... */
#if GTK_CHECK_VERSION(2, 18, 0)
gtk_widget_get_allocation( widget, &alloc );
#else
alloc = widget->allocation;
#endif
gdk_window_get_origin(window, &nx, &ny );
alloc.x += nx;
alloc.y += ny;
return alloc.x <= event->x_root && alloc.y <= event->y_root &&
(alloc.x + alloc.width) > event->x_root && (alloc.y + alloc.height) > event->y_root;
}
//_________________________________________________
bool WindowManager::useEvent( GtkWidget *widget, GdkEventButton *event )
{
bool usable = true;
// check if there is an hovered tab
if( GE_IS_NOTEBOOK( widget ) )
{
if( Style::instance().animations().tabWidgetEngine().hoveredTab( widget ) != -1 )
{
usable = false;
}
}
// need to check all children that may be listening to event
else if(GE_IS_CONTAINER( widget ) )
{
GList *containers = NULL;
containers = g_list_prepend( containers, widget );
while( g_list_length( containers ) )
{
GtkContainer *c = GTK_CONTAINER( g_list_nth_data(containers, 0) );
GList *children = gtk_container_get_children( GTK_CONTAINER( c ) );
for( GList *child = g_list_first( children ); child && usable ; child = g_list_next( child ) )
{
if( child->data )
{
if( GE_IS_CONTAINER( child->data ) )
{
containers = g_list_prepend( containers, child->data );
}
// if widget is prelight, we don't need to check where event happen,
// any prelight widget indicate we can't do a move
if( GTK_WIDGET_STATE( GTK_WIDGET( child->data ) ) == GTK_STATE_PRELIGHT )
{
usable = false;
}
// if event happen in widget
else if( GE_IS_WIDGET( child->data ) && event && withinWidget( GTK_WIDGET( child->data ), event ) )
{
// widget listening to press event
if( gtk_widget_get_events ( GTK_WIDGET( child->data ) ) & GDK_BUTTON_PRESS_MASK )
{
// here deal with notebook: widget may be not visible
GdkWindow *window = gtk_widget_get_window( GTK_WIDGET ( child->data ) );
if( window && gdk_window_is_visible ( window ) )
{
usable = false;
}
}
// deal with menu item, GtkMenuItem only listen to
// GDK_BUTTON_PRESS_MASK when state == GTK_STATE_PRELIGHT
// so previous check are invalids :(
//
// same for ScrolledWindow, they do not send motion events
// to parents so not usable
else if( GE_IS_MENUITEM( G_OBJECT( child->data ) ) ||
GE_IS_SCROLL( G_OBJECT( child->data ) ) )
{
usable = false;
}
}
}
}
if( children )
g_list_free( children );
containers = g_list_remove( containers, c );
}
}
return usable;
}
//_________________________________________________
bool WindowManager::wmMove( GtkWidget *widget, int x, int y )
{
XEvent xev;
GtkWindow *topLevel = GTK_WINDOW( gtk_widget_get_toplevel( widget ) );
GdkWindow *window = gtk_widget_get_window( GTK_WIDGET( topLevel ) );
GdkDisplay *display = gtk_widget_get_display( GTK_WIDGET( topLevel ) );
GdkWindow *root = gdk_screen_get_root_window( gtk_window_get_screen( topLevel ) );
xev.xclient.type = ClientMessage;
xev.xclient.message_type = gdk_x11_get_xatom_by_name_for_display(display, "_NET_WM_MOVERESIZE");
xev.xclient.display = GDK_DISPLAY_XDISPLAY(display);
xev.xclient.window = GDK_WINDOW_XID(window);
xev.xclient.format = 32;
xev.xclient.data.l[0] = x;
xev.xclient.data.l[1] = y;
xev.xclient.data.l[2] = 8; // NET::Move
xev.xclient.data.l[3] = Button1;
xev.xclient.data.l[4] = 0;
XUngrabPointer(GDK_DISPLAY_XDISPLAY(display), CurrentTime);
XSendEvent(GDK_DISPLAY_XDISPLAY(display), GDK_WINDOW_XID(root), False,
SubstructureRedirectMask | SubstructureNotifyMask, &xev);
// force a release as some widgets miss it...
wmButtonRelease( widget, NULL, NULL );
return true;
}
//_________________________________________________
bool WindowManager::wmMotion( GtkWidget *widget, GdkEventMotion *event, gpointer user_data )
{
if( drag )
{
wmMove( widget, event->x_root, event->y_root );
return true;
}
return false;
}
//_________________________________________________
bool WindowManager::wmButtonPress(GtkWidget *widget, GdkEventButton *event, gpointer user_data )
{
if( event->type == GDK_BUTTON_PRESS && event->button == 1 &&
isWindowDragWidget( widget, event ) )
{
drag = true;
return true;
}
return false;
}
//_________________________________________________
bool WindowManager::wmButtonRelease(GtkWidget *widget, GdkEventButton *event, gpointer user_data )
{
if( drag )
{
gtk_grab_remove(widget);
gdk_pointer_ungrab( CurrentTime );
drag = false;
return true;
}
return false;
}
//_________________________________________________
bool WindowManager::wmStyleSet( GtkWidget *widget, GtkStyle *style, gpointer user_data )
{
delete static_cast<WindowManager*>(user_data);
return false;
}
//_________________________________________________
bool WindowManager::wmDestroy( GtkWidget *widget, GtkStyle *style, gpointer user_data )
{
delete static_cast<WindowManager*>(user_data);
return false;
}
}
}
<commit_msg>Fix regression due to notebook support<commit_after>//////////////////////////////////////////////////////////////////////////////
// oxygenwindowmanager.cpp
// pass some window mouse press/release/move event actions to window manager
// -------------------
//
// Copyright (c) 2010 Cédric Bellegarde <gnumdk@gmail.com>
//
// Largely inspired from Qtcurve style
// Copyright (C) Craig Drummond, 2003 - 2010 craig.p.drummond@gmail.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//////////////////////////////////////////////////////////////////////////////
#include <string>
#include "oxygenwindowmanager.h"
#include "oxygenstyle.h"
#define GE_IS_CONTAINER(object) ((object) && objectIsA((GObject*)(object), "GtkContainer"))
#define GE_IS_WIDGET(object) ((object) && objectIsA((GObject*)(object), "GtkWidget"))
#define GE_IS_MENUITEM(object) ((object) && objectIsA((GObject*)(object), "GtkMenuItem"))
#define GE_IS_SCROLL(object) ((object) && objectIsA((GObject*)(object), "GtkScrolledWindow"))
#define GE_IS_NOTEBOOK(object) ((object) && objectIsA((GObject*)(object), "GtkNotebook"))
namespace Oxygen
{
namespace Gtk
{
static bool drag = FALSE;
// check object type
static bool objectIsA( const GObject * object, const gchar * type_name )
{
if( ( object ) )
{
GType tmp = g_type_from_name( type_name );
if( tmp )
return g_type_check_instance_is_a( ( GTypeInstance * ) object, tmp );
}
return false;
}
//_________________________________________________
WindowManager::WindowManager( GtkWidget *widget )
{
// setup window management
if( !g_object_get_data( G_OBJECT( widget ), "OXYGEN_WM_MOVE_HACK_SET" ) )
{
// Force widget to listen to events
gtk_widget_add_events( widget, GDK_BUTTON_RELEASE_MASK |
GDK_BUTTON_PRESS_MASK |
GDK_LEAVE_NOTIFY_MASK |
GDK_BUTTON1_MOTION_MASK );
g_object_set_data( G_OBJECT( widget ), "OXYGEN_WM_MOVE_HACK_SET", ( gpointer )1 );
_leaveId.connect( G_OBJECT( widget ), "leave-notify-event", G_CALLBACK( wmButtonRelease ), NULL );
_destroyId.connect( G_OBJECT( widget ), "destroy-event", G_CALLBACK( wmDestroy ), this );
_styleId.connect( G_OBJECT( widget ), "style-set", G_CALLBACK( wmStyleSet ), this );
_pressId.connect( G_OBJECT( widget ), "button-press-event", G_CALLBACK( wmButtonPress ), widget );
_releaseId.connect( G_OBJECT( widget ), "button-release-event", G_CALLBACK( wmButtonRelease ), widget );
_motionId.connect( G_OBJECT( widget ), "motion-notify-event", G_CALLBACK( wmMotion ), NULL );
_widget = widget;
}
else
_widget = NULL;
}
//_________________________________________________
WindowManager::~WindowManager()
{
if( _widget )
{
_leaveId.disconnect();
_destroyId.disconnect();
_styleId.disconnect();
_pressId.disconnect();
_releaseId.disconnect();
g_object_steal_data( G_OBJECT( _widget ), "OXYGEN_WM_MOVE_HACK_SET" );
}
}
//_________________________________________________
bool WindowManager::isValid()
{
return _widget != NULL;
}
//_________________________________________________
bool WindowManager::isWindowDragWidget( GtkWidget *widget, GdkEventButton *event )
{
return withinWidget(widget, event ) && useEvent( widget, event );
}
//_________________________________________________
bool WindowManager::withinWidget( GtkWidget *widget, GdkEventButton *event )
{
GtkAllocation alloc;
GdkWindow *window = gtk_widget_get_parent_window( widget );
int nx = 0,
ny = 0;
if( !window )
return true;
/* Need to get absolute co-ordinates... */
#if GTK_CHECK_VERSION(2, 18, 0)
gtk_widget_get_allocation( widget, &alloc );
#else
alloc = widget->allocation;
#endif
gdk_window_get_origin(window, &nx, &ny );
alloc.x += nx;
alloc.y += ny;
return alloc.x <= event->x_root && alloc.y <= event->y_root &&
(alloc.x + alloc.width) > event->x_root && (alloc.y + alloc.height) > event->y_root;
}
//_________________________________________________
bool WindowManager::useEvent( GtkWidget *widget, GdkEventButton *event )
{
bool usable = true;
// check if there is an hovered tab
if( GE_IS_NOTEBOOK( widget ) )
{
if( Style::instance().animations().tabWidgetEngine().hoveredTab( widget ) != -1 )
{
usable = false;
}
}
// need to check all children that may be listening to event
else if(GE_IS_CONTAINER( widget ) )
{
GList *containers = NULL;
containers = g_list_prepend( containers, widget );
while( g_list_length( containers ) )
{
GtkContainer *c = GTK_CONTAINER( g_list_nth_data(containers, 0) );
GList *children = gtk_container_get_children( GTK_CONTAINER( c ) );
for( GList *child = g_list_first( children ); child && usable ; child = g_list_next( child ) )
{
if( child->data )
{
if( GE_IS_CONTAINER( child->data ) )
{
containers = g_list_prepend( containers, child->data );
}
// if widget is prelight, we don't need to check where event happen,
// any prelight widget indicate we can't do a move
if( GTK_WIDGET_STATE( GTK_WIDGET( child->data ) ) == GTK_STATE_PRELIGHT )
{
usable = false;
}
// if event happen in widget
// check not a notebook: event in but notebook don't get it...
else if( GE_IS_WIDGET( child->data ) && !GE_IS_NOTEBOOK ( child->data ) &&
event && withinWidget( GTK_WIDGET( child->data ), event ) )
{
// here deal with notebook: widget may be not visible
GdkWindow *window = gtk_widget_get_window( GTK_WIDGET ( child->data ) );
if( window && gdk_window_is_visible ( window ) )
{
// widget listening to press event
if( gtk_widget_get_events ( GTK_WIDGET( child->data ) ) & GDK_BUTTON_PRESS_MASK )
{
usable = false;
}
// deal with menu item, GtkMenuItem only listen to
// GDK_BUTTON_PRESS_MASK when state == GTK_STATE_PRELIGHT
// so previous check are invalids :(
//
// same for ScrolledWindow, they do not send motion events
// to parents so not usable
else if( GE_IS_MENUITEM( G_OBJECT( child->data ) ) ||
GE_IS_SCROLL( G_OBJECT( child->data ) ) )
{
usable = false;
}
}
}
}
}
if( children )
g_list_free( children );
containers = g_list_remove( containers, c );
}
}
return usable;
}
//_________________________________________________
bool WindowManager::wmMove( GtkWidget *widget, int x, int y )
{
XEvent xev;
GtkWindow *topLevel = GTK_WINDOW( gtk_widget_get_toplevel( widget ) );
GdkWindow *window = gtk_widget_get_window( GTK_WIDGET( topLevel ) );
GdkDisplay *display = gtk_widget_get_display( GTK_WIDGET( topLevel ) );
GdkWindow *root = gdk_screen_get_root_window( gtk_window_get_screen( topLevel ) );
xev.xclient.type = ClientMessage;
xev.xclient.message_type = gdk_x11_get_xatom_by_name_for_display(display, "_NET_WM_MOVERESIZE");
xev.xclient.display = GDK_DISPLAY_XDISPLAY(display);
xev.xclient.window = GDK_WINDOW_XID(window);
xev.xclient.format = 32;
xev.xclient.data.l[0] = x;
xev.xclient.data.l[1] = y;
xev.xclient.data.l[2] = 8; // NET::Move
xev.xclient.data.l[3] = Button1;
xev.xclient.data.l[4] = 0;
XUngrabPointer(GDK_DISPLAY_XDISPLAY(display), CurrentTime);
XSendEvent(GDK_DISPLAY_XDISPLAY(display), GDK_WINDOW_XID(root), False,
SubstructureRedirectMask | SubstructureNotifyMask, &xev);
// force a release as some widgets miss it...
wmButtonRelease( widget, NULL, NULL );
return true;
}
//_________________________________________________
bool WindowManager::wmMotion( GtkWidget *widget, GdkEventMotion *event, gpointer user_data )
{
if( drag )
{
wmMove( widget, event->x_root, event->y_root );
return true;
}
return false;
}
//_________________________________________________
bool WindowManager::wmButtonPress(GtkWidget *widget, GdkEventButton *event, gpointer user_data )
{
if( event->type == GDK_BUTTON_PRESS && event->button == 1 &&
isWindowDragWidget( widget, event ) )
{
drag = true;
return true;
}
return false;
}
//_________________________________________________
bool WindowManager::wmButtonRelease(GtkWidget *widget, GdkEventButton *event, gpointer user_data )
{
if( drag )
{
gtk_grab_remove(widget);
gdk_pointer_ungrab( CurrentTime );
drag = false;
return true;
}
return false;
}
//_________________________________________________
bool WindowManager::wmStyleSet( GtkWidget *widget, GtkStyle *style, gpointer user_data )
{
delete static_cast<WindowManager*>(user_data);
return false;
}
//_________________________________________________
bool WindowManager::wmDestroy( GtkWidget *widget, GtkStyle *style, gpointer user_data )
{
delete static_cast<WindowManager*>(user_data);
return false;
}
}
}
<|endoftext|>
|
<commit_before>#include <cmath>
#include <iostream>
#include <fstream>
#include <thread>
#include <QWidget>
#include <QMouseEvent>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QStackedLayout>
#include <QLayout>
#include <QDateTime>
#include "common/params.h"
#include "home.hpp"
#include "paint.hpp"
#include "qt_window.hpp"
#include "widgets/drive_stats.hpp"
#define BACKLIGHT_DT 0.25
#define BACKLIGHT_TS 2.00
OffroadHome::OffroadHome(QWidget *parent) : QWidget(parent) {
QVBoxLayout *main_layout = new QVBoxLayout();
main_layout->setContentsMargins(sbr_w + 50, 50, 50, 50);
// top header
QHBoxLayout *header_layout = new QHBoxLayout();
date = new QLabel();
date->setStyleSheet(R"(font-size: 55px;)");
header_layout->addWidget(date, 0, Qt::AlignTop | Qt::AlignLeft);
QLabel *version = new QLabel(QString::fromStdString("openpilot v" + Params().get("Version")));
version->setStyleSheet(R"(font-size: 45px;)");
header_layout->addWidget(version, 0, Qt::AlignTop | Qt::AlignRight);
main_layout->addLayout(header_layout);
alert_notification = new QPushButton();
QObject::connect(alert_notification, SIGNAL(released()), this, SLOT(openAlerts()));
main_layout->addWidget(alert_notification, 0, Qt::AlignTop | Qt::AlignRight);
// main content
main_layout->addSpacing(25);
center_layout = new QStackedLayout();
DriveStats *drive = new DriveStats;
drive->setFixedSize(1000, 800);
center_layout->addWidget(drive);
alerts_widget = new OffroadAlert();
QObject::connect(alerts_widget, SIGNAL(closeAlerts()), this, SLOT(closeAlerts()));
center_layout->addWidget(alerts_widget);
center_layout->setAlignment(alerts_widget, Qt::AlignCenter);
main_layout->addLayout(center_layout, 1);
// set up refresh timer
timer = new QTimer(this);
QObject::connect(timer, SIGNAL(timeout()), this, SLOT(refresh()));
refresh();
timer->start(10 * 1000);
setLayout(main_layout);
setStyleSheet(R"(background-color: none;)");
}
void OffroadHome::openAlerts() {
center_layout->setCurrentIndex(1);
}
void OffroadHome::closeAlerts() {
center_layout->setCurrentIndex(0);
}
void OffroadHome::refresh() {
bool first_refresh = !date->text().size();
if (!isVisible() && !first_refresh) {
return;
}
date->setText(QDateTime::currentDateTime().toString("dddd, MMMM d"));
// update alerts
alerts_widget->refresh();
if (!alerts_widget->alerts.size() && !alerts_widget->updateAvailable) {
alert_notification->setVisible(false);
return;
}
if (alerts_widget->updateAvailable) {
// There is a new release
alert_notification->setText("UPDATE");
} else {
int alerts = alerts_widget->alerts.size();
alert_notification->setText(QString::number(alerts) + " ALERT" + (alerts == 1 ? "" : "S"));
}
alert_notification->setVisible(true);
// Red background for alerts, blue for update available
QString style = QString(R"(
padding: 15px;
padding-left: 30px;
padding-right: 30px;
border: 1px solid;
border-radius: 5px;
font-size: 40px;
font-weight: bold;
background-color: #E22C2C;
)");
if (alerts_widget->updateAvailable){
style.replace("#E22C2C", "#364DEF");
}
alert_notification->setStyleSheet(style);
}
HomeWindow::HomeWindow(QWidget *parent) : QWidget(parent) {
layout = new QGridLayout;
layout->setMargin(0);
// onroad UI
glWindow = new GLWindow(this);
layout->addWidget(glWindow, 0, 0);
// draw offroad UI on top of onroad UI
home = new OffroadHome();
layout->addWidget(home, 0, 0);
QObject::connect(glWindow, SIGNAL(offroadTransition(bool)), this, SLOT(setVisibility(bool)));
QObject::connect(this, SIGNAL(openSettings()), home, SLOT(refresh()));
setLayout(layout);
setStyleSheet(R"(
* {
color: white;
}
)");
}
void HomeWindow::setVisibility(bool offroad) {
home->setVisible(offroad);
}
void HomeWindow::mousePressEvent(QMouseEvent *e) {
UIState *ui_state = glWindow->ui_state;
glWindow->wake();
// Settings button click
if (!ui_state->scene.sidebar_collapsed && settings_btn.ptInRect(e->x(), e->y())) {
emit openSettings();
}
// Vision click
if (ui_state->started && (e->x() >= ui_state->scene.viz_rect.x - bdr_s)) {
ui_state->scene.sidebar_collapsed = !ui_state->scene.sidebar_collapsed;
}
}
static void handle_display_state(UIState *s, int dt, bool user_input) {
static int awake_timeout = 0;
awake_timeout = std::max(awake_timeout-dt, 0);
if (user_input || s->ignition || s->started) {
s->awake = true;
awake_timeout = 30*UI_FREQ;
} else if (awake_timeout == 0) {
s->awake = false;
}
}
static void set_backlight(int brightness) {
std::ofstream brightness_control("/sys/class/backlight/panel0-backlight/brightness");
if (brightness_control.is_open()) {
brightness_control << brightness << "\n";
brightness_control.close();
}
}
GLWindow::GLWindow(QWidget *parent) : QOpenGLWidget(parent) {
timer = new QTimer(this);
QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timerUpdate()));
backlight_timer = new QTimer(this);
QObject::connect(backlight_timer, SIGNAL(timeout()), this, SLOT(backlightUpdate()));
int result = read_param(&brightness_b, "BRIGHTNESS_B", true);
result += read_param(&brightness_m, "BRIGHTNESS_M", true);
if (result != 0) {
brightness_b = 200.0;
brightness_m = 10.0;
}
smooth_brightness = 512;
}
GLWindow::~GLWindow() {
makeCurrent();
doneCurrent();
}
void GLWindow::initializeGL() {
initializeOpenGLFunctions();
std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
std::cout << "OpenGL vendor: " << glGetString(GL_VENDOR) << std::endl;
std::cout << "OpenGL renderer: " << glGetString(GL_RENDERER) << std::endl;
std::cout << "OpenGL language version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
ui_state = new UIState();
ui_state->sound = &sound;
ui_init(ui_state);
wake();
timer->start(0);
backlight_timer->start(BACKLIGHT_DT * 1000);
}
void GLWindow::backlightUpdate() {
// Update brightness
float k = (BACKLIGHT_DT / BACKLIGHT_TS) / (1.0f + BACKLIGHT_DT / BACKLIGHT_TS);
float clipped_brightness = std::min(1023.0f, (ui_state->light_sensor*brightness_m) + brightness_b);
smooth_brightness = clipped_brightness * k + smooth_brightness * (1.0f - k);
int brightness = smooth_brightness;
if (!ui_state->awake) {
brightness = 0;
}
std::thread{set_backlight, brightness}.detach();
}
void GLWindow::timerUpdate() {
if (ui_state->started != onroad) {
onroad = ui_state->started;
emit offroadTransition(!onroad);
#ifdef QCOM2
timer->setInterval(onroad ? 0 : 1000);
#endif
}
// Fix awake timeout if running 1 Hz when offroad
int dt = timer->interval() == 0 ? 1 : 20;
handle_display_state(ui_state, dt, false);
ui_update(ui_state);
repaint();
}
void GLWindow::resizeGL(int w, int h) {
std::cout << "resize " << w << "x" << h << std::endl;
}
void GLWindow::paintGL() {
ui_draw(ui_state);
}
void GLWindow::wake() {
// UI state might not be initialized yet
if (ui_state != nullptr) {
handle_display_state(ui_state, 1, true);
}
}
FramebufferState* framebuffer_init(const char* name, int32_t layer, int alpha,
int *out_w, int *out_h) {
*out_w = vwp_w;
*out_h = vwp_h;
return (FramebufferState*)1; // not null
}
<commit_msg>Remove spaces (#19779)<commit_after>#include <cmath>
#include <iostream>
#include <fstream>
#include <thread>
#include <QWidget>
#include <QMouseEvent>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QStackedLayout>
#include <QLayout>
#include <QDateTime>
#include "common/params.h"
#include "home.hpp"
#include "paint.hpp"
#include "qt_window.hpp"
#include "widgets/drive_stats.hpp"
#define BACKLIGHT_DT 0.25
#define BACKLIGHT_TS 2.00
OffroadHome::OffroadHome(QWidget *parent) : QWidget(parent) {
QVBoxLayout *main_layout = new QVBoxLayout();
main_layout->setContentsMargins(sbr_w + 50, 50, 50, 50);
// top header
QHBoxLayout *header_layout = new QHBoxLayout();
date = new QLabel();
date->setStyleSheet(R"(font-size: 55px;)");
header_layout->addWidget(date, 0, Qt::AlignTop | Qt::AlignLeft);
QLabel *version = new QLabel(QString::fromStdString("openpilot v" + Params().get("Version")));
version->setStyleSheet(R"(font-size: 45px;)");
header_layout->addWidget(version, 0, Qt::AlignTop | Qt::AlignRight);
main_layout->addLayout(header_layout);
alert_notification = new QPushButton();
QObject::connect(alert_notification, SIGNAL(released()), this, SLOT(openAlerts()));
main_layout->addWidget(alert_notification, 0, Qt::AlignTop | Qt::AlignRight);
// main content
main_layout->addSpacing(25);
center_layout = new QStackedLayout();
DriveStats *drive = new DriveStats;
drive->setFixedSize(1000, 800);
center_layout->addWidget(drive);
alerts_widget = new OffroadAlert();
QObject::connect(alerts_widget, SIGNAL(closeAlerts()), this, SLOT(closeAlerts()));
center_layout->addWidget(alerts_widget);
center_layout->setAlignment(alerts_widget, Qt::AlignCenter);
main_layout->addLayout(center_layout, 1);
// set up refresh timer
timer = new QTimer(this);
QObject::connect(timer, SIGNAL(timeout()), this, SLOT(refresh()));
refresh();
timer->start(10 * 1000);
setLayout(main_layout);
setStyleSheet(R"(background-color: none;)");
}
void OffroadHome::openAlerts() {
center_layout->setCurrentIndex(1);
}
void OffroadHome::closeAlerts() {
center_layout->setCurrentIndex(0);
}
void OffroadHome::refresh() {
bool first_refresh = !date->text().size();
if (!isVisible() && !first_refresh) {
return;
}
date->setText(QDateTime::currentDateTime().toString("dddd, MMMM d"));
// update alerts
alerts_widget->refresh();
if (!alerts_widget->alerts.size() && !alerts_widget->updateAvailable) {
alert_notification->setVisible(false);
return;
}
if (alerts_widget->updateAvailable) {
// There is a new release
alert_notification->setText("UPDATE");
} else {
int alerts = alerts_widget->alerts.size();
alert_notification->setText(QString::number(alerts) + " ALERT" + (alerts == 1 ? "" : "S"));
}
alert_notification->setVisible(true);
// Red background for alerts, blue for update available
QString style = QString(R"(
padding: 15px;
padding-left: 30px;
padding-right: 30px;
border: 1px solid;
border-radius: 5px;
font-size: 40px;
font-weight: bold;
background-color: #E22C2C;
)");
if (alerts_widget->updateAvailable){
style.replace("#E22C2C", "#364DEF");
}
alert_notification->setStyleSheet(style);
}
HomeWindow::HomeWindow(QWidget *parent) : QWidget(parent) {
layout = new QGridLayout;
layout->setMargin(0);
// onroad UI
glWindow = new GLWindow(this);
layout->addWidget(glWindow, 0, 0);
// draw offroad UI on top of onroad UI
home = new OffroadHome();
layout->addWidget(home, 0, 0);
QObject::connect(glWindow, SIGNAL(offroadTransition(bool)), this, SLOT(setVisibility(bool)));
QObject::connect(this, SIGNAL(openSettings()), home, SLOT(refresh()));
setLayout(layout);
setStyleSheet(R"(
* {
color: white;
}
)");
}
void HomeWindow::setVisibility(bool offroad) {
home->setVisible(offroad);
}
void HomeWindow::mousePressEvent(QMouseEvent *e) {
UIState *ui_state = glWindow->ui_state;
glWindow->wake();
// Settings button click
if (!ui_state->scene.sidebar_collapsed && settings_btn.ptInRect(e->x(), e->y())) {
emit openSettings();
}
// Vision click
if (ui_state->started && (e->x() >= ui_state->scene.viz_rect.x - bdr_s)) {
ui_state->scene.sidebar_collapsed = !ui_state->scene.sidebar_collapsed;
}
}
static void handle_display_state(UIState *s, int dt, bool user_input) {
static int awake_timeout = 0;
awake_timeout = std::max(awake_timeout-dt, 0);
if (user_input || s->ignition || s->started) {
s->awake = true;
awake_timeout = 30*UI_FREQ;
} else if (awake_timeout == 0) {
s->awake = false;
}
}
static void set_backlight(int brightness) {
std::ofstream brightness_control("/sys/class/backlight/panel0-backlight/brightness");
if (brightness_control.is_open()) {
brightness_control << brightness << "\n";
brightness_control.close();
}
}
GLWindow::GLWindow(QWidget *parent) : QOpenGLWidget(parent) {
timer = new QTimer(this);
QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timerUpdate()));
backlight_timer = new QTimer(this);
QObject::connect(backlight_timer, SIGNAL(timeout()), this, SLOT(backlightUpdate()));
int result = read_param(&brightness_b, "BRIGHTNESS_B", true);
result += read_param(&brightness_m, "BRIGHTNESS_M", true);
if (result != 0) {
brightness_b = 200.0;
brightness_m = 10.0;
}
smooth_brightness = 512;
}
GLWindow::~GLWindow() {
makeCurrent();
doneCurrent();
}
void GLWindow::initializeGL() {
initializeOpenGLFunctions();
std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
std::cout << "OpenGL vendor: " << glGetString(GL_VENDOR) << std::endl;
std::cout << "OpenGL renderer: " << glGetString(GL_RENDERER) << std::endl;
std::cout << "OpenGL language version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
ui_state = new UIState();
ui_state->sound = &sound;
ui_init(ui_state);
wake();
timer->start(0);
backlight_timer->start(BACKLIGHT_DT * 1000);
}
void GLWindow::backlightUpdate() {
// Update brightness
float k = (BACKLIGHT_DT / BACKLIGHT_TS) / (1.0f + BACKLIGHT_DT / BACKLIGHT_TS);
float clipped_brightness = std::min(1023.0f, (ui_state->light_sensor*brightness_m) + brightness_b);
smooth_brightness = clipped_brightness * k + smooth_brightness * (1.0f - k);
int brightness = smooth_brightness;
if (!ui_state->awake) {
brightness = 0;
}
std::thread{set_backlight, brightness}.detach();
}
void GLWindow::timerUpdate() {
if (ui_state->started != onroad) {
onroad = ui_state->started;
emit offroadTransition(!onroad);
#ifdef QCOM2
timer->setInterval(onroad ? 0 : 1000);
#endif
}
// Fix awake timeout if running 1 Hz when offroad
int dt = timer->interval() == 0 ? 1 : 20;
handle_display_state(ui_state, dt, false);
ui_update(ui_state);
repaint();
}
void GLWindow::resizeGL(int w, int h) {
std::cout << "resize " << w << "x" << h << std::endl;
}
void GLWindow::paintGL() {
ui_draw(ui_state);
}
void GLWindow::wake() {
// UI state might not be initialized yet
if (ui_state != nullptr) {
handle_display_state(ui_state, 1, true);
}
}
FramebufferState* framebuffer_init(const char* name, int32_t layer, int alpha,
int *out_w, int *out_h) {
*out_w = vwp_w;
*out_h = vwp_h;
return (FramebufferState*)1; // not null
}
<|endoftext|>
|
<commit_before>#include <cmath>
#include <fstream>
#include <iostream>
#include <thread>
#include <QDateTime>
#include <QHBoxLayout>
#include <QLayout>
#include <QMouseEvent>
#include <QStackedLayout>
#include <QVBoxLayout>
#include <QWidget>
#include "common/params.h"
#include "home.hpp"
#include "paint.hpp"
#include "qt_window.hpp"
#include "widgets/drive_stats.hpp"
#include "widgets/setup.hpp"
#define BACKLIGHT_DT 0.25
#define BACKLIGHT_TS 2.00
OffroadHome::OffroadHome(QWidget* parent) : QWidget(parent) {
QVBoxLayout* main_layout = new QVBoxLayout();
main_layout->setContentsMargins(sbr_w + 50, 50, 50, 50);
// top header
QHBoxLayout* header_layout = new QHBoxLayout();
date = new QLabel();
date->setStyleSheet(R"(font-size: 55px;)");
header_layout->addWidget(date, 0, Qt::AlignTop | Qt::AlignLeft);
QLabel* version = new QLabel(QString::fromStdString("openpilot v" + Params().get("Version")));
version->setStyleSheet(R"(font-size: 45px;)");
header_layout->addWidget(version, 0, Qt::AlignTop | Qt::AlignRight);
main_layout->addLayout(header_layout);
alert_notification = new QPushButton();
QObject::connect(alert_notification, SIGNAL(released()), this, SLOT(openAlerts()));
main_layout->addWidget(alert_notification, 0, Qt::AlignTop | Qt::AlignRight);
// main content
main_layout->addSpacing(25);
center_layout = new QStackedLayout();
QHBoxLayout* statsAndSetup = new QHBoxLayout();
DriveStats* drive = new DriveStats;
drive->setFixedSize(1000, 800);
statsAndSetup->addWidget(drive);
SetupWidget* setup = new SetupWidget;
statsAndSetup->addWidget(setup);
QWidget* statsAndSetupWidget = new QWidget();
statsAndSetupWidget->setLayout(statsAndSetup);
center_layout->addWidget(statsAndSetupWidget);
alerts_widget = new OffroadAlert();
QObject::connect(alerts_widget, SIGNAL(closeAlerts()), this, SLOT(closeAlerts()));
center_layout->addWidget(alerts_widget);
center_layout->setAlignment(alerts_widget, Qt::AlignCenter);
main_layout->addLayout(center_layout, 1);
// set up refresh timer
timer = new QTimer(this);
QObject::connect(timer, SIGNAL(timeout()), this, SLOT(refresh()));
refresh();
timer->start(10 * 1000);
setLayout(main_layout);
setStyleSheet(R"(background-color: none;)");
}
void OffroadHome::openAlerts() {
center_layout->setCurrentIndex(1);
}
void OffroadHome::closeAlerts() {
center_layout->setCurrentIndex(0);
}
void OffroadHome::refresh() {
bool first_refresh = !date->text().size();
if (!isVisible() && !first_refresh) {
return;
}
date->setText(QDateTime::currentDateTime().toString("dddd, MMMM d"));
// update alerts
alerts_widget->refresh();
if (!alerts_widget->alerts.size() && !alerts_widget->updateAvailable) {
alert_notification->setVisible(false);
return;
}
if (alerts_widget->updateAvailable) {
// There is a new release
alert_notification->setText("UPDATE");
} else {
int alerts = alerts_widget->alerts.size();
alert_notification->setText(QString::number(alerts) + " ALERT" + (alerts == 1 ? "" : "S"));
}
alert_notification->setVisible(true);
// Red background for alerts, blue for update available
QString style = QString(R"(
padding: 15px;
padding-left: 30px;
padding-right: 30px;
border: 1px solid;
border-radius: 5px;
font-size: 40px;
font-weight: bold;
background-color: #E22C2C;
)");
if (alerts_widget->updateAvailable) {
style.replace("#E22C2C", "#364DEF");
}
alert_notification->setStyleSheet(style);
}
HomeWindow::HomeWindow(QWidget* parent) : QWidget(parent) {
layout = new QGridLayout;
layout->setMargin(0);
// onroad UI
glWindow = new GLWindow(this);
layout->addWidget(glWindow, 0, 0);
// draw offroad UI on top of onroad UI
home = new OffroadHome();
layout->addWidget(home, 0, 0);
QObject::connect(glWindow, SIGNAL(offroadTransition(bool)), this, SLOT(setVisibility(bool)));
QObject::connect(this, SIGNAL(openSettings()), home, SLOT(refresh()));
setLayout(layout);
setStyleSheet(R"(
* {
color: white;
}
)");
}
void HomeWindow::setVisibility(bool offroad) {
home->setVisible(offroad);
}
void HomeWindow::mousePressEvent(QMouseEvent* e) {
UIState* ui_state = &glWindow->ui_state;
glWindow->wake();
// Settings button click
if (!ui_state->scene.sidebar_collapsed && settings_btn.ptInRect(e->x(), e->y())) {
emit openSettings();
}
// Vision click
if (ui_state->started && (e->x() >= ui_state->scene.viz_rect.x - bdr_s)) {
ui_state->scene.sidebar_collapsed = !ui_state->scene.sidebar_collapsed;
}
}
static void handle_display_state(UIState* s, bool user_input) {
static int awake_timeout = 0; // Somehow this only gets called on program start
awake_timeout = std::max(awake_timeout - 1, 0);
if (user_input || s->ignition || s->started) {
s->awake = true;
awake_timeout = 30 * UI_FREQ;
} else if (awake_timeout == 0) {
s->awake = false;
}
}
static void set_backlight(int brightness) {
std::ofstream brightness_control("/sys/class/backlight/panel0-backlight/brightness");
if (brightness_control.is_open()) {
brightness_control << brightness << "\n";
brightness_control.close();
}
}
GLWindow::GLWindow(QWidget* parent) : QOpenGLWidget(parent) {
timer = new QTimer(this);
QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timerUpdate()));
backlight_timer = new QTimer(this);
QObject::connect(backlight_timer, SIGNAL(timeout()), this, SLOT(backlightUpdate()));
int result = read_param(&brightness_b, "BRIGHTNESS_B", true);
result += read_param(&brightness_m, "BRIGHTNESS_M", true);
if (result != 0) {
brightness_b = 200.0;
brightness_m = 10.0;
}
smooth_brightness = 512;
}
GLWindow::~GLWindow() {
makeCurrent();
doneCurrent();
}
void GLWindow::initializeGL() {
initializeOpenGLFunctions();
std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
std::cout << "OpenGL vendor: " << glGetString(GL_VENDOR) << std::endl;
std::cout << "OpenGL renderer: " << glGetString(GL_RENDERER) << std::endl;
std::cout << "OpenGL language version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
ui_state.sound = &sound;
ui_init(&ui_state);
wake();
timer->start(1000 / UI_FREQ);
backlight_timer->start(BACKLIGHT_DT * 1000);
}
void GLWindow::backlightUpdate() {
// Update brightness
float k = (BACKLIGHT_DT / BACKLIGHT_TS) / (1.0f + BACKLIGHT_DT / BACKLIGHT_TS);
float clipped_brightness = std::min(1023.0f, (ui_state.light_sensor * brightness_m) + brightness_b);
smooth_brightness = clipped_brightness * k + smooth_brightness * (1.0f - k);
int brightness = smooth_brightness;
if (!ui_state.awake) {
brightness = 0;
}
std::thread{set_backlight, brightness}.detach();
}
void GLWindow::timerUpdate() {
// Connecting to visionIPC requires opengl to be current
if (!ui_state.vipc_client->connected){
makeCurrent();
}
if (ui_state.started != onroad) {
onroad = ui_state.started;
emit offroadTransition(!onroad);
}
handle_display_state(&ui_state, false);
ui_update(&ui_state);
repaint();
}
void GLWindow::resizeGL(int w, int h) {
std::cout << "resize " << w << "x" << h << std::endl;
}
void GLWindow::paintGL() {
if(GLWindow::ui_state.awake){
ui_draw(&ui_state);
}
}
void GLWindow::wake() {
handle_display_state(&ui_state, true);
}
FramebufferState* framebuffer_init(const char* name, int32_t layer, int alpha,
int *out_w, int *out_h) {
*out_w = vwp_w;
*out_h = vwp_h;
return (FramebufferState*)1; // not null
}
<commit_msg>qt ui: sync fps with camera<commit_after>#include <cmath>
#include <fstream>
#include <iostream>
#include <thread>
#include <QDateTime>
#include <QHBoxLayout>
#include <QLayout>
#include <QMouseEvent>
#include <QStackedLayout>
#include <QVBoxLayout>
#include <QWidget>
#include "common/params.h"
#include "home.hpp"
#include "paint.hpp"
#include "qt_window.hpp"
#include "widgets/drive_stats.hpp"
#include "widgets/setup.hpp"
#define BACKLIGHT_DT 0.25
#define BACKLIGHT_TS 2.00
OffroadHome::OffroadHome(QWidget* parent) : QWidget(parent) {
QVBoxLayout* main_layout = new QVBoxLayout();
main_layout->setContentsMargins(sbr_w + 50, 50, 50, 50);
// top header
QHBoxLayout* header_layout = new QHBoxLayout();
date = new QLabel();
date->setStyleSheet(R"(font-size: 55px;)");
header_layout->addWidget(date, 0, Qt::AlignTop | Qt::AlignLeft);
QLabel* version = new QLabel(QString::fromStdString("openpilot v" + Params().get("Version")));
version->setStyleSheet(R"(font-size: 45px;)");
header_layout->addWidget(version, 0, Qt::AlignTop | Qt::AlignRight);
main_layout->addLayout(header_layout);
alert_notification = new QPushButton();
QObject::connect(alert_notification, SIGNAL(released()), this, SLOT(openAlerts()));
main_layout->addWidget(alert_notification, 0, Qt::AlignTop | Qt::AlignRight);
// main content
main_layout->addSpacing(25);
center_layout = new QStackedLayout();
QHBoxLayout* statsAndSetup = new QHBoxLayout();
DriveStats* drive = new DriveStats;
drive->setFixedSize(1000, 800);
statsAndSetup->addWidget(drive);
SetupWidget* setup = new SetupWidget;
statsAndSetup->addWidget(setup);
QWidget* statsAndSetupWidget = new QWidget();
statsAndSetupWidget->setLayout(statsAndSetup);
center_layout->addWidget(statsAndSetupWidget);
alerts_widget = new OffroadAlert();
QObject::connect(alerts_widget, SIGNAL(closeAlerts()), this, SLOT(closeAlerts()));
center_layout->addWidget(alerts_widget);
center_layout->setAlignment(alerts_widget, Qt::AlignCenter);
main_layout->addLayout(center_layout, 1);
// set up refresh timer
timer = new QTimer(this);
QObject::connect(timer, SIGNAL(timeout()), this, SLOT(refresh()));
refresh();
timer->start(10 * 1000);
setLayout(main_layout);
setStyleSheet(R"(background-color: none;)");
}
void OffroadHome::openAlerts() {
center_layout->setCurrentIndex(1);
}
void OffroadHome::closeAlerts() {
center_layout->setCurrentIndex(0);
}
void OffroadHome::refresh() {
bool first_refresh = !date->text().size();
if (!isVisible() && !first_refresh) {
return;
}
date->setText(QDateTime::currentDateTime().toString("dddd, MMMM d"));
// update alerts
alerts_widget->refresh();
if (!alerts_widget->alerts.size() && !alerts_widget->updateAvailable) {
alert_notification->setVisible(false);
return;
}
if (alerts_widget->updateAvailable) {
// There is a new release
alert_notification->setText("UPDATE");
} else {
int alerts = alerts_widget->alerts.size();
alert_notification->setText(QString::number(alerts) + " ALERT" + (alerts == 1 ? "" : "S"));
}
alert_notification->setVisible(true);
// Red background for alerts, blue for update available
QString style = QString(R"(
padding: 15px;
padding-left: 30px;
padding-right: 30px;
border: 1px solid;
border-radius: 5px;
font-size: 40px;
font-weight: bold;
background-color: #E22C2C;
)");
if (alerts_widget->updateAvailable) {
style.replace("#E22C2C", "#364DEF");
}
alert_notification->setStyleSheet(style);
}
HomeWindow::HomeWindow(QWidget* parent) : QWidget(parent) {
layout = new QGridLayout;
layout->setMargin(0);
// onroad UI
glWindow = new GLWindow(this);
layout->addWidget(glWindow, 0, 0);
// draw offroad UI on top of onroad UI
home = new OffroadHome();
layout->addWidget(home, 0, 0);
QObject::connect(glWindow, SIGNAL(offroadTransition(bool)), this, SLOT(setVisibility(bool)));
QObject::connect(this, SIGNAL(openSettings()), home, SLOT(refresh()));
setLayout(layout);
setStyleSheet(R"(
* {
color: white;
}
)");
}
void HomeWindow::setVisibility(bool offroad) {
home->setVisible(offroad);
}
void HomeWindow::mousePressEvent(QMouseEvent* e) {
UIState* ui_state = &glWindow->ui_state;
glWindow->wake();
// Settings button click
if (!ui_state->scene.sidebar_collapsed && settings_btn.ptInRect(e->x(), e->y())) {
emit openSettings();
}
// Vision click
if (ui_state->started && (e->x() >= ui_state->scene.viz_rect.x - bdr_s)) {
ui_state->scene.sidebar_collapsed = !ui_state->scene.sidebar_collapsed;
}
}
static void handle_display_state(UIState* s, bool user_input) {
static int awake_timeout = 0; // Somehow this only gets called on program start
awake_timeout = std::max(awake_timeout - 1, 0);
if (user_input || s->ignition || s->started) {
s->awake = true;
awake_timeout = 30 * UI_FREQ;
} else if (awake_timeout == 0) {
s->awake = false;
}
}
static void set_backlight(int brightness) {
std::ofstream brightness_control("/sys/class/backlight/panel0-backlight/brightness");
if (brightness_control.is_open()) {
brightness_control << brightness << "\n";
brightness_control.close();
}
}
GLWindow::GLWindow(QWidget* parent) : QOpenGLWidget(parent) {
timer = new QTimer(this);
QObject::connect(timer, SIGNAL(timeout()), this, SLOT(timerUpdate()));
backlight_timer = new QTimer(this);
QObject::connect(backlight_timer, SIGNAL(timeout()), this, SLOT(backlightUpdate()));
int result = read_param(&brightness_b, "BRIGHTNESS_B", true);
result += read_param(&brightness_m, "BRIGHTNESS_M", true);
if (result != 0) {
brightness_b = 200.0;
brightness_m = 10.0;
}
smooth_brightness = 512;
}
GLWindow::~GLWindow() {
makeCurrent();
doneCurrent();
}
void GLWindow::initializeGL() {
initializeOpenGLFunctions();
std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
std::cout << "OpenGL vendor: " << glGetString(GL_VENDOR) << std::endl;
std::cout << "OpenGL renderer: " << glGetString(GL_RENDERER) << std::endl;
std::cout << "OpenGL language version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
ui_state.sound = &sound;
ui_init(&ui_state);
wake();
timer->start(1000 / UI_FREQ);
backlight_timer->start(BACKLIGHT_DT * 1000);
}
void GLWindow::backlightUpdate() {
// Update brightness
float k = (BACKLIGHT_DT / BACKLIGHT_TS) / (1.0f + BACKLIGHT_DT / BACKLIGHT_TS);
float clipped_brightness = std::min(1023.0f, (ui_state.light_sensor * brightness_m) + brightness_b);
smooth_brightness = clipped_brightness * k + smooth_brightness * (1.0f - k);
int brightness = smooth_brightness;
if (!ui_state.awake) {
brightness = 0;
}
std::thread{set_backlight, brightness}.detach();
}
void GLWindow::timerUpdate() {
// Connecting to visionIPC requires opengl to be current
if (!ui_state.vipc_client->connected){
makeCurrent();
}
if (ui_state.started != onroad) {
onroad = ui_state.started;
emit offroadTransition(!onroad);
// Change timeout to 0 when onroad, this will call timerUpdate continously.
// This puts visionIPC in charge of update frequency, reducing video latency
timer->start(onroad ? 0 : 1000 / UI_FREQ);
}
handle_display_state(&ui_state, false);
ui_update(&ui_state);
repaint();
}
void GLWindow::resizeGL(int w, int h) {
std::cout << "resize " << w << "x" << h << std::endl;
}
void GLWindow::paintGL() {
if(GLWindow::ui_state.awake){
ui_draw(&ui_state);
}
}
void GLWindow::wake() {
handle_display_state(&ui_state, true);
}
FramebufferState* framebuffer_init(const char* name, int32_t layer, int alpha,
int *out_w, int *out_h) {
*out_w = vwp_w;
*out_h = vwp_h;
return (FramebufferState*)1; // not null
}
<|endoftext|>
|
<commit_before>#include "test_macros.hpp"
#include <matrix/math.hpp>
using namespace matrix;
int main()
{
float data1[] = {1,2,3,4,5};
float data2[] = {6,7,8,9,10};
Vector<float, 5> v1(data1);
TEST(isEqualF(v1.norm(), 7.416198487095663f));
TEST(isEqualF(v1.norm(), v1.length()));
Vector<float, 5> v2(data2);
TEST(isEqualF(v1.dot(v2), 130.0f));
v2.normalize();
Vector<float, 5> v3(v2);
TEST(isEqual(v2, v3));
float data1_sq[] = {1,4,9,16,25};
Vector<float, 5> v4(data1_sq);
TEST(isEqual(v1, v4.pow(0.5)));
// dot product operator
v1 = Vector<float, 5>(data1);
v2 = Vector<float, 5>(data2);
float dprod = v1 * v2;
TEST(isEqualF(dprod, 130.0f));
return 0;
}
/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
<commit_msg>Test vector: structured & commented, added normalize and unit_or_zero tests, removed duplicate data preparation<commit_after>#include "test_macros.hpp"
#include <matrix/math.hpp>
using namespace matrix;
int main()
{
// test data
float data1[] = {1,2,3,4,5};
float data2[] = {6,7,8,9,10};
Vector<float, 5> v1(data1);
Vector<float, 5> v2(data2);
// copy constructor
Vector<float, 5> v3(v2);
TEST(isEqual(v2, v3));
// norm, dot product
TEST(isEqualF(v1.norm(), 7.416198487095663f));
TEST(isEqualF(v1.norm(), v1.length()));
TEST(isEqualF(v1.dot(v2), 130.0f));
TEST(isEqualF(v1.dot(v2), v1 * v2));
// unit, unit_zero, normalize
TEST(isEqualF(v2.unit().norm(), 1.f));
TEST(isEqualF(v2.unit_or_zero().norm(), 1.f));
TEST(isEqualF(Vector<float, 5>().unit_or_zero().norm(), 0.f));
v2.normalize();
TEST(isEqualF(v2.norm(), 1.f));
// power
float data1_sq[] = {1,4,9,16,25};
Vector<float, 5> v4(data1_sq);
TEST(isEqual(v1, v4.pow(0.5)));
return 0;
}
/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : */
<|endoftext|>
|
<commit_before>/**
* @file
*
* @brief
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
#include "ccode.hpp"
#include <kdblogger.h>
namespace
{
/**
* @brief Cast a character to an unsigned character.
*
* @param character This parameter specifies the character this function casts to an unsigned value.
*
* @return A unsigned character corresponding to the given argument
*/
inline constexpr unsigned char operator"" _uc (char character) noexcept
{
return static_cast<unsigned char> (character);
}
/**
* @brief This function maps hex characters to integer numbers.
*
* @pre The specified character has to be between
*
* - `'0'`–`'9'`,
* - `'a'`-`'f'`, or
* - `'A'`-`'F'`
*
* .
*
* @param character This argument specifies the (hexadecimal) character this function converts.
*
* @return An integer number between `0` and `15` if the precondition is valid or `0` otherwise
*/
inline int elektraHexcodeConvFromHex (char character)
{
if (character >= '0' && character <= '9') return character - '0';
if (character >= 'a' && character <= 'f') return character - 'a' + 10;
if (character >= 'A' && character <= 'F') return character - 'A' + 10;
return 0; /* Unknown escape char */
}
} // end namespace
using namespace ckdb;
extern "C" {
/**
* @brief This function sets default values for the encoding and decoding character mapping.
*
* @param mapping This parameter stores the encoding and decoding table this function fills with default values.
*/
void setDefaultConfig (CCodeData * const mapping)
{
unsigned char pairs[][2] = { { '\b'_uc, 'b'_uc }, { '\t'_uc, 't'_uc }, { '\n'_uc, 'n'_uc }, { '\v'_uc, 'v'_uc },
{ '\f'_uc, 'f'_uc }, { '\r'_uc, 'r'_uc }, { '\\'_uc, '\\'_uc }, { '\''_uc, '\''_uc },
{ '\"'_uc, '"'_uc }, { '\0'_uc, '0'_uc } };
for (size_t pair = 0; pair < sizeof (pairs) / sizeof (pairs[0]); pair++)
{
unsigned char character = pairs[pair][0];
unsigned char replacement = pairs[pair][1];
mapping->encode[character] = replacement;
mapping->decode[replacement] = character;
}
}
/**
* @brief This function sets values for the encoding and decoding character mapping.
*
* @param mapping This parameter stores the encoding and decoding table this function fills with the values specified in `config`.
* @param config This key set stores the character mappings this function stores inside `mappings`.
* @param root This key stores the root key for the character mapping stored in `config`.
*/
void readConfig (CCodeData * const mapping, KeySet * const config, Key const * const root)
{
Key const * key = 0;
while ((key = ksNext (config)) != 0)
{
/* Ignore keys that are not directly below the config root key or have an incorrect size */
if (keyRel (root, key) != 1 || keyGetBaseNameSize (key) != 3 || keyGetValueSize (key) != 3) continue;
int character = elektraHexcodeConvFromHex (keyBaseName (key)[1]);
character += elektraHexcodeConvFromHex (keyBaseName (key)[0]) * 16;
int replacement = elektraHexcodeConvFromHex (keyString (key)[1]);
replacement += elektraHexcodeConvFromHex (keyString (key)[0]) * 16;
/* Hexencode this character! */
mapping->encode[character & 255] = replacement;
mapping->decode[replacement & 255] = character;
}
}
/**
* @brief This function replaces escaped character in a key value with unescaped characters.
*
* The function stores the unescaped result value both in `mapping->buffer` and the given key.
*
* @pre The variable `mapping->buffer` needs to be as large as the key value’s size.
*
* @param key This key holds the value this function decodes.
* @param mapping This variable stores the buffer and the character mapping this function uses to decode the value of the given key.
*/
void elektraCcodeDecode (Key * key, CCodeData * mapping)
{
const char * value = static_cast<const char *> (keyValue (key));
if (!value) return;
size_t const SIZE = keyGetValueSize (key) - 1;
size_t out = 0;
for (size_t in = 0; in < SIZE; ++in)
{
unsigned char character = value[in];
if (character == mapping->escape)
{
++in; /* Advance twice */
character = value[in];
mapping->buffer[out] = mapping->decode[character & 255];
}
else
{
mapping->buffer[out] = character;
}
++out; /* Only one char is written */
}
mapping->buffer[out] = 0; // null termination for keyString()
keySetRaw (key, mapping->buffer, out + 1);
}
/**
* @brief This function replaces unescaped character in a key value with escaped characters.
*
* The function stores the escaped result value both in `mapping->buffer` and the given key.
*
* @pre The variable `mapping->buffer` needs to be twice as large as the key value’s size.
*
* @param cur This key stores the value this function escapes.
* @param mapping This variable stores the buffer and the character mapping this function uses to encode the value of the given key.
*/
void elektraCcodeEncode (Key * cur, CCodeData * mapping)
{
size_t valsize = keyGetValueSize (cur);
const char * val = static_cast<const char *> (keyValue (cur));
if (!val) return;
size_t out = 0;
for (size_t in = 0; in < valsize - 1; ++in)
{
unsigned char character = val[in];
if (mapping->encode[character])
{
mapping->buffer[out + 1] = mapping->encode[character];
// Escape char
mapping->buffer[out] = mapping->escape;
out += 2;
}
else
{
// just copy one character
mapping->buffer[out] = val[in];
// advance out cursor
out++;
// go to next char
}
}
mapping->buffer[out] = 0; // null termination for keyString()
keySetRaw (cur, mapping->buffer, out + 1);
}
// ====================
// = Plugin Interface =
// ====================
int elektraCcodeOpen (Plugin * handle, Key * key ELEKTRA_UNUSED)
{
CCodeData * mapping = new CCodeData ();
/* Store for later use...*/
elektraPluginSetData (handle, mapping);
KeySet * config = elektraPluginGetConfig (handle);
Key * escape = ksLookupByName (config, "/escape", 0);
mapping->escape = '\\';
if (escape && keyGetBaseNameSize (escape) && keyGetValueSize (escape) == 3)
{
int res;
res = elektraHexcodeConvFromHex (keyString (escape)[1]);
res += elektraHexcodeConvFromHex (keyString (escape)[0]) * 16;
mapping->escape = res & 255;
}
ELEKTRA_LOG_DEBUG ("Use “%c” as escape character", mapping->escape);
Key * root = ksLookupByName (config, "/chars", 0);
if (root)
{
readConfig (mapping, config, root);
}
else
{
setDefaultConfig (mapping);
}
return 0;
}
int elektraCcodeClose (Plugin * handle, Key * key ELEKTRA_UNUSED)
{
CCodeData * mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));
delete[](mapping->buffer);
delete (mapping);
return 0;
}
int elektraCcodeGet (Plugin * handle, KeySet * returned, Key * parentKey)
{
/* get all keys */
if (!strcmp (keyName (parentKey), "system/elektra/modules/ccode"))
{
KeySet * pluginConfig =
ksNew (30, keyNew ("system/elektra/modules/ccode", KEY_VALUE, "ccode plugin waits for your orders", KEY_END),
keyNew ("system/elektra/modules/ccode/exports", KEY_END),
keyNew ("system/elektra/modules/ccode/exports/open", KEY_FUNC, elektraCcodeOpen, KEY_END),
keyNew ("system/elektra/modules/ccode/exports/close", KEY_FUNC, elektraCcodeClose, KEY_END),
keyNew ("system/elektra/modules/ccode/exports/get", KEY_FUNC, elektraCcodeGet, KEY_END),
keyNew ("system/elektra/modules/ccode/exports/set", KEY_FUNC, elektraCcodeSet, KEY_END),
#include "readme_ccode.c"
keyNew ("system/elektra/modules/ccode/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END);
ksAppend (returned, pluginConfig);
ksDel (pluginConfig);
return 1;
}
CCodeData * mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));
if (!mapping->buffer)
{
mapping->bufalloc = 1000;
mapping->buffer = new unsigned char[mapping->bufalloc];
}
Key * cur;
ksRewind (returned);
while ((cur = ksNext (returned)) != 0)
{
size_t valsize = keyGetValueSize (cur);
if (valsize > mapping->bufalloc)
{
mapping->bufalloc = valsize;
mapping->buffer = new unsigned char[mapping->bufalloc];
}
elektraCcodeDecode (cur, mapping);
}
return 1; /* success */
}
int elektraCcodeSet (Plugin * handle, KeySet * returned, Key * parentKey ELEKTRA_UNUSED)
{
/* set all keys */
CCodeData * mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));
if (!mapping->buffer)
{
mapping->bufalloc = 1000;
mapping->buffer = new unsigned char[mapping->bufalloc];
}
Key * cur;
ksRewind (returned);
while ((cur = ksNext (returned)) != 0)
{
size_t valsize = keyGetValueSize (cur);
if (valsize * 2 > mapping->bufalloc)
{
mapping->bufalloc = valsize * 2;
mapping->buffer = new unsigned char[mapping->bufalloc];
}
elektraCcodeEncode (cur, mapping);
}
return 1; /* success */
}
Plugin * ELEKTRA_PLUGIN_EXPORT (ccode)
{
// clang-format off
return elektraPluginExport("ccode",
ELEKTRA_PLUGIN_OPEN, &elektraCcodeOpen,
ELEKTRA_PLUGIN_CLOSE, &elektraCcodeClose,
ELEKTRA_PLUGIN_GET, &elektraCcodeGet,
ELEKTRA_PLUGIN_SET, &elektraCcodeSet,
ELEKTRA_PLUGIN_END);
}
} // end extern "C"
<commit_msg>CCode: Only read size if we need it<commit_after>/**
* @file
*
* @brief
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
#include "ccode.hpp"
#include <kdblogger.h>
namespace
{
/**
* @brief Cast a character to an unsigned character.
*
* @param character This parameter specifies the character this function casts to an unsigned value.
*
* @return A unsigned character corresponding to the given argument
*/
inline constexpr unsigned char operator"" _uc (char character) noexcept
{
return static_cast<unsigned char> (character);
}
/**
* @brief This function maps hex characters to integer numbers.
*
* @pre The specified character has to be between
*
* - `'0'`–`'9'`,
* - `'a'`-`'f'`, or
* - `'A'`-`'F'`
*
* .
*
* @param character This argument specifies the (hexadecimal) character this function converts.
*
* @return An integer number between `0` and `15` if the precondition is valid or `0` otherwise
*/
inline int elektraHexcodeConvFromHex (char character)
{
if (character >= '0' && character <= '9') return character - '0';
if (character >= 'a' && character <= 'f') return character - 'a' + 10;
if (character >= 'A' && character <= 'F') return character - 'A' + 10;
return 0; /* Unknown escape char */
}
} // end namespace
using namespace ckdb;
extern "C" {
/**
* @brief This function sets default values for the encoding and decoding character mapping.
*
* @param mapping This parameter stores the encoding and decoding table this function fills with default values.
*/
void setDefaultConfig (CCodeData * const mapping)
{
unsigned char pairs[][2] = { { '\b'_uc, 'b'_uc }, { '\t'_uc, 't'_uc }, { '\n'_uc, 'n'_uc }, { '\v'_uc, 'v'_uc },
{ '\f'_uc, 'f'_uc }, { '\r'_uc, 'r'_uc }, { '\\'_uc, '\\'_uc }, { '\''_uc, '\''_uc },
{ '\"'_uc, '"'_uc }, { '\0'_uc, '0'_uc } };
for (size_t pair = 0; pair < sizeof (pairs) / sizeof (pairs[0]); pair++)
{
unsigned char character = pairs[pair][0];
unsigned char replacement = pairs[pair][1];
mapping->encode[character] = replacement;
mapping->decode[replacement] = character;
}
}
/**
* @brief This function sets values for the encoding and decoding character mapping.
*
* @param mapping This parameter stores the encoding and decoding table this function fills with the values specified in `config`.
* @param config This key set stores the character mappings this function stores inside `mappings`.
* @param root This key stores the root key for the character mapping stored in `config`.
*/
void readConfig (CCodeData * const mapping, KeySet * const config, Key const * const root)
{
Key const * key = 0;
while ((key = ksNext (config)) != 0)
{
/* Ignore keys that are not directly below the config root key or have an incorrect size */
if (keyRel (root, key) != 1 || keyGetBaseNameSize (key) != 3 || keyGetValueSize (key) != 3) continue;
int character = elektraHexcodeConvFromHex (keyBaseName (key)[1]);
character += elektraHexcodeConvFromHex (keyBaseName (key)[0]) * 16;
int replacement = elektraHexcodeConvFromHex (keyString (key)[1]);
replacement += elektraHexcodeConvFromHex (keyString (key)[0]) * 16;
/* Hexencode this character! */
mapping->encode[character & 255] = replacement;
mapping->decode[replacement & 255] = character;
}
}
/**
* @brief This function replaces escaped character in a key value with unescaped characters.
*
* The function stores the unescaped result value both in `mapping->buffer` and the given key.
*
* @pre The variable `mapping->buffer` needs to be as large as the key value’s size.
*
* @param key This key holds the value this function decodes.
* @param mapping This variable stores the buffer and the character mapping this function uses to decode the value of the given key.
*/
void elektraCcodeDecode (Key * key, CCodeData * mapping)
{
const char * value = static_cast<const char *> (keyValue (key));
if (!value) return;
size_t const SIZE = keyGetValueSize (key) - 1;
size_t out = 0;
for (size_t in = 0; in < SIZE; ++in)
{
unsigned char character = value[in];
if (character == mapping->escape)
{
++in; /* Advance twice */
character = value[in];
mapping->buffer[out] = mapping->decode[character & 255];
}
else
{
mapping->buffer[out] = character;
}
++out; /* Only one char is written */
}
mapping->buffer[out] = 0; // null termination for keyString()
keySetRaw (key, mapping->buffer, out + 1);
}
/**
* @brief This function replaces unescaped character in a key value with escaped characters.
*
* The function stores the escaped result value both in `mapping->buffer` and the given key.
*
* @pre The variable `mapping->buffer` needs to be twice as large as the key value’s size.
*
* @param cur This key stores the value this function escapes.
* @param mapping This variable stores the buffer and the character mapping this function uses to encode the value of the given key.
*/
void elektraCcodeEncode (Key * cur, CCodeData * mapping)
{
const char * val = static_cast<const char *> (keyValue (cur));
if (!val) return;
size_t valsize = keyGetValueSize (cur);
size_t out = 0;
for (size_t in = 0; in < valsize - 1; ++in)
{
unsigned char character = val[in];
if (mapping->encode[character])
{
mapping->buffer[out + 1] = mapping->encode[character];
// Escape char
mapping->buffer[out] = mapping->escape;
out += 2;
}
else
{
// just copy one character
mapping->buffer[out] = val[in];
// advance out cursor
out++;
// go to next char
}
}
mapping->buffer[out] = 0; // null termination for keyString()
keySetRaw (cur, mapping->buffer, out + 1);
}
// ====================
// = Plugin Interface =
// ====================
int elektraCcodeOpen (Plugin * handle, Key * key ELEKTRA_UNUSED)
{
CCodeData * mapping = new CCodeData ();
/* Store for later use...*/
elektraPluginSetData (handle, mapping);
KeySet * config = elektraPluginGetConfig (handle);
Key * escape = ksLookupByName (config, "/escape", 0);
mapping->escape = '\\';
if (escape && keyGetBaseNameSize (escape) && keyGetValueSize (escape) == 3)
{
int res;
res = elektraHexcodeConvFromHex (keyString (escape)[1]);
res += elektraHexcodeConvFromHex (keyString (escape)[0]) * 16;
mapping->escape = res & 255;
}
ELEKTRA_LOG_DEBUG ("Use “%c” as escape character", mapping->escape);
Key * root = ksLookupByName (config, "/chars", 0);
if (root)
{
readConfig (mapping, config, root);
}
else
{
setDefaultConfig (mapping);
}
return 0;
}
int elektraCcodeClose (Plugin * handle, Key * key ELEKTRA_UNUSED)
{
CCodeData * mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));
delete[](mapping->buffer);
delete (mapping);
return 0;
}
int elektraCcodeGet (Plugin * handle, KeySet * returned, Key * parentKey)
{
/* get all keys */
if (!strcmp (keyName (parentKey), "system/elektra/modules/ccode"))
{
KeySet * pluginConfig =
ksNew (30, keyNew ("system/elektra/modules/ccode", KEY_VALUE, "ccode plugin waits for your orders", KEY_END),
keyNew ("system/elektra/modules/ccode/exports", KEY_END),
keyNew ("system/elektra/modules/ccode/exports/open", KEY_FUNC, elektraCcodeOpen, KEY_END),
keyNew ("system/elektra/modules/ccode/exports/close", KEY_FUNC, elektraCcodeClose, KEY_END),
keyNew ("system/elektra/modules/ccode/exports/get", KEY_FUNC, elektraCcodeGet, KEY_END),
keyNew ("system/elektra/modules/ccode/exports/set", KEY_FUNC, elektraCcodeSet, KEY_END),
#include "readme_ccode.c"
keyNew ("system/elektra/modules/ccode/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END);
ksAppend (returned, pluginConfig);
ksDel (pluginConfig);
return 1;
}
CCodeData * mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));
if (!mapping->buffer)
{
mapping->bufalloc = 1000;
mapping->buffer = new unsigned char[mapping->bufalloc];
}
Key * cur;
ksRewind (returned);
while ((cur = ksNext (returned)) != 0)
{
size_t valsize = keyGetValueSize (cur);
if (valsize > mapping->bufalloc)
{
mapping->bufalloc = valsize;
mapping->buffer = new unsigned char[mapping->bufalloc];
}
elektraCcodeDecode (cur, mapping);
}
return 1; /* success */
}
int elektraCcodeSet (Plugin * handle, KeySet * returned, Key * parentKey ELEKTRA_UNUSED)
{
/* set all keys */
CCodeData * mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));
if (!mapping->buffer)
{
mapping->bufalloc = 1000;
mapping->buffer = new unsigned char[mapping->bufalloc];
}
Key * cur;
ksRewind (returned);
while ((cur = ksNext (returned)) != 0)
{
size_t valsize = keyGetValueSize (cur);
if (valsize * 2 > mapping->bufalloc)
{
mapping->bufalloc = valsize * 2;
mapping->buffer = new unsigned char[mapping->bufalloc];
}
elektraCcodeEncode (cur, mapping);
}
return 1; /* success */
}
Plugin * ELEKTRA_PLUGIN_EXPORT (ccode)
{
// clang-format off
return elektraPluginExport("ccode",
ELEKTRA_PLUGIN_OPEN, &elektraCcodeOpen,
ELEKTRA_PLUGIN_CLOSE, &elektraCcodeClose,
ELEKTRA_PLUGIN_GET, &elektraCcodeGet,
ELEKTRA_PLUGIN_SET, &elektraCcodeSet,
ELEKTRA_PLUGIN_END);
}
} // end extern "C"
<|endoftext|>
|
<commit_before>/**
* @file
*
* @brief
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
#include "ccode.hpp"
#include <kdblogger.h>
namespace
{
/**
* @brief Cast a character to an unsigned character.
*
* @param character This parameter specifies the character this function casts to an unsigned value.
*
* @return A unsigned character corresponding to the given argument
*/
inline constexpr unsigned char operator"" _uc (char character) noexcept
{
return static_cast<unsigned char> (character);
}
/**
* @brief This function maps hex characters to integer numbers.
*
* @pre The specified character has to be between
*
* - `'0'`–`'9'`,
* - `'a'`-`'f'`, or
* - `'A'`-`'F'`
*
* .
*
* @param character This argument specifies the (hexadecimal) character this function converts.
*
* @return An integer number between `0` and `15` if the precondition is valid or `0` otherwise
*/
inline int elektraHexcodeConvFromHex (char character)
{
if (character >= '0' && character <= '9') return character - '0';
if (character >= 'a' && character <= 'f') return character - 'a' + 10;
if (character >= 'A' && character <= 'F') return character - 'A' + 10;
return 0; /* Unknown escape char */
}
} // end namespace
using namespace ckdb;
extern "C" {
/**
* @brief This function sets default values for the encoding and decoding character mapping.
*
* @param mapping This parameter stores the encoding and decoding table this function fills with default values.
*/
void setDefaultConfig (CCodeData * mapping)
{
mapping->encode['\b'_uc] = 'b'_uc;
mapping->encode['\t'_uc] = 't'_uc;
mapping->encode['\n'_uc] = 'n'_uc;
mapping->encode['\v'_uc] = 'v'_uc;
mapping->encode['\f'_uc] = 'f'_uc;
mapping->encode['\r'_uc] = 'r'_uc;
mapping->encode['\\'_uc] = '\\'_uc;
mapping->encode['\''_uc] = '\''_uc;
mapping->encode['\"'_uc] = '"'_uc;
mapping->encode['\0'_uc] = '0'_uc;
mapping->decode['b'_uc] = '\b'_uc;
mapping->decode['t'_uc] = '\t'_uc;
mapping->decode['n'_uc] = '\n'_uc;
mapping->decode['v'_uc] = '\v'_uc;
mapping->decode['f'_uc] = '\f'_uc;
mapping->decode['r'_uc] = '\r'_uc;
mapping->decode['\\'_uc] = '\\'_uc;
mapping->decode['\''_uc] = '\''_uc;
mapping->decode['"'_uc] = '\"'_uc;
mapping->decode['0'_uc] = '\0'_uc;
}
void readConfig (CCodeData * const mapping, KeySet * const config, Key const * const root)
{
Key * cur = 0;
while ((cur = ksNext (config)) != 0)
{
/* Ignore keys that are not directly below the config root key or have an incorrect size */
if (keyRel (root, cur) != 1 || keyGetBaseNameSize (cur) != 3 || keyGetValueSize (cur) != 3) continue;
int res;
res = elektraHexcodeConvFromHex (keyBaseName (cur)[1]);
res += elektraHexcodeConvFromHex (keyBaseName (cur)[0]) * 16;
int val;
val = elektraHexcodeConvFromHex (keyString (cur)[1]);
val += elektraHexcodeConvFromHex (keyString (cur)[0]) * 16;
/* Hexencode this character! */
mapping->encode[res & 255] = val;
mapping->decode[val & 255] = res;
}
}
int elektraCcodeOpen (Plugin * handle, Key * key ELEKTRA_UNUSED)
{
CCodeData * mapping = new CCodeData ();
/* Store for later use...*/
elektraPluginSetData (handle, mapping);
KeySet * config = elektraPluginGetConfig (handle);
Key * escape = ksLookupByName (config, "/escape", 0);
mapping->escape = '\\';
if (escape && keyGetBaseNameSize (escape) && keyGetValueSize (escape) == 3)
{
int res;
res = elektraHexcodeConvFromHex (keyString (escape)[1]);
res += elektraHexcodeConvFromHex (keyString (escape)[0]) * 16;
mapping->escape = res & 255;
}
ELEKTRA_LOG_DEBUG ("Use “%c” as escape character", mapping->escape);
Key * root = ksLookupByName (config, "/chars", 0);
if (root)
{
readConfig (mapping, config, root);
}
else
{
setDefaultConfig (mapping);
}
return 0;
}
int elektraCcodeClose (Plugin * handle, Key * key ELEKTRA_UNUSED)
{
CCodeData * mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));
delete[](mapping->buf);
delete (mapping);
return 0;
}
/** Reads the value of the key and decodes all escaping
* codes into the buffer.
* @pre the buffer needs to be as large as value's size.
* @param cur the key holding the value to decode
* @param mapping the buffer to write to
*/
void elektraCcodeDecode (Key * cur, CCodeData * mapping)
{
size_t valsize = keyGetValueSize (cur);
const char * val = static_cast<const char *> (keyValue (cur));
if (!val) return;
size_t out = 0;
for (size_t in = 0; in < valsize - 1; ++in)
{
unsigned char character = val[in];
if (character == mapping->escape)
{
++in; /* Advance twice */
character = val[in];
mapping->buf[out] = mapping->decode[character & 255];
}
else
{
mapping->buf[out] = character;
}
++out; /* Only one char is written */
}
mapping->buf[out] = 0; // null termination for keyString()
keySetRaw (cur, mapping->buf, out + 1);
}
int elektraCcodeGet (Plugin * handle, KeySet * returned, Key * parentKey)
{
/* get all keys */
if (!strcmp (keyName (parentKey), "system/elektra/modules/ccode"))
{
KeySet * pluginConfig =
ksNew (30, keyNew ("system/elektra/modules/ccode", KEY_VALUE, "ccode plugin waits for your orders", KEY_END),
keyNew ("system/elektra/modules/ccode/exports", KEY_END),
keyNew ("system/elektra/modules/ccode/exports/open", KEY_FUNC, elektraCcodeOpen, KEY_END),
keyNew ("system/elektra/modules/ccode/exports/close", KEY_FUNC, elektraCcodeClose, KEY_END),
keyNew ("system/elektra/modules/ccode/exports/get", KEY_FUNC, elektraCcodeGet, KEY_END),
keyNew ("system/elektra/modules/ccode/exports/set", KEY_FUNC, elektraCcodeSet, KEY_END),
#include "readme_ccode.c"
keyNew ("system/elektra/modules/ccode/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END);
ksAppend (returned, pluginConfig);
ksDel (pluginConfig);
return 1;
}
CCodeData * mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));
if (!mapping->buf)
{
mapping->bufalloc = 1000;
mapping->buf = new unsigned char[mapping->bufalloc];
}
Key * cur;
ksRewind (returned);
while ((cur = ksNext (returned)) != 0)
{
size_t valsize = keyGetValueSize (cur);
if (valsize > mapping->bufalloc)
{
mapping->bufalloc = valsize;
mapping->buf = new unsigned char[mapping->bufalloc];
}
elektraCcodeDecode (cur, mapping);
}
return 1; /* success */
}
/** Reads the value of the key and encodes it in
* c-style in the buffer.
*
* @param cur the key which value is to encode
* @param mapping the buffer
* @pre the buffer needs to have twice as much space as the value's size
*/
void elektraCcodeEncode (Key * cur, CCodeData * mapping)
{
size_t valsize = keyGetValueSize (cur);
const char * val = static_cast<const char *> (keyValue (cur));
if (!val) return;
size_t out = 0;
for (size_t in = 0; in < valsize - 1; ++in)
{
unsigned char character = val[in];
if (mapping->encode[character])
{
mapping->buf[out + 1] = mapping->encode[character];
// Escape char
mapping->buf[out] = mapping->escape;
out += 2;
}
else
{
// just copy one character
mapping->buf[out] = val[in];
// advance out cursor
out++;
// go to next char
}
}
mapping->buf[out] = 0; // null termination for keyString()
keySetRaw (cur, mapping->buf, out + 1);
}
int elektraCcodeSet (Plugin * handle, KeySet * returned, Key * parentKey ELEKTRA_UNUSED)
{
/* set all keys */
CCodeData * mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));
if (!mapping->buf)
{
mapping->bufalloc = 1000;
mapping->buf = new unsigned char[mapping->bufalloc];
}
Key * cur;
ksRewind (returned);
while ((cur = ksNext (returned)) != 0)
{
size_t valsize = keyGetValueSize (cur);
if (valsize * 2 > mapping->bufalloc)
{
mapping->bufalloc = valsize * 2;
mapping->buf = new unsigned char[mapping->bufalloc];
}
elektraCcodeEncode (cur, mapping);
}
return 1; /* success */
}
Plugin * ELEKTRA_PLUGIN_EXPORT (ccode)
{
// clang-format off
return elektraPluginExport("ccode",
ELEKTRA_PLUGIN_OPEN, &elektraCcodeOpen,
ELEKTRA_PLUGIN_CLOSE, &elektraCcodeClose,
ELEKTRA_PLUGIN_GET, &elektraCcodeGet,
ELEKTRA_PLUGIN_SET, &elektraCcodeSet,
ELEKTRA_PLUGIN_END);
}
} // end extern "C"
<commit_msg>CCode: Simplify function `setDefaultConfig`<commit_after>/**
* @file
*
* @brief
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*/
#include "ccode.hpp"
#include <kdblogger.h>
namespace
{
/**
* @brief Cast a character to an unsigned character.
*
* @param character This parameter specifies the character this function casts to an unsigned value.
*
* @return A unsigned character corresponding to the given argument
*/
inline constexpr unsigned char operator"" _uc (char character) noexcept
{
return static_cast<unsigned char> (character);
}
/**
* @brief This function maps hex characters to integer numbers.
*
* @pre The specified character has to be between
*
* - `'0'`–`'9'`,
* - `'a'`-`'f'`, or
* - `'A'`-`'F'`
*
* .
*
* @param character This argument specifies the (hexadecimal) character this function converts.
*
* @return An integer number between `0` and `15` if the precondition is valid or `0` otherwise
*/
inline int elektraHexcodeConvFromHex (char character)
{
if (character >= '0' && character <= '9') return character - '0';
if (character >= 'a' && character <= 'f') return character - 'a' + 10;
if (character >= 'A' && character <= 'F') return character - 'A' + 10;
return 0; /* Unknown escape char */
}
} // end namespace
using namespace ckdb;
extern "C" {
/**
* @brief This function sets default values for the encoding and decoding character mapping.
*
* @param mapping This parameter stores the encoding and decoding table this function fills with default values.
*/
void setDefaultConfig (CCodeData * mapping)
{
unsigned char pairs[][2] = { { '\b'_uc, 'b'_uc }, { '\t'_uc, 't'_uc }, { '\n'_uc, 'n'_uc }, { '\v'_uc, 'v'_uc },
{ '\f'_uc, 'f'_uc }, { '\r'_uc, 'r'_uc }, { '\\'_uc, '\\'_uc }, { '\''_uc, '\''_uc },
{ '\"'_uc, '"'_uc }, { '\0'_uc, '0'_uc } };
for (size_t pair = 0; pair < sizeof (pairs) / sizeof (pairs[0]); pair++)
{
unsigned char character = pairs[pair][0];
unsigned char replacement = pairs[pair][1];
mapping->encode[character] = replacement;
mapping->decode[replacement] = character;
}
}
void readConfig (CCodeData * const mapping, KeySet * const config, Key const * const root)
{
Key * cur = 0;
while ((cur = ksNext (config)) != 0)
{
/* Ignore keys that are not directly below the config root key or have an incorrect size */
if (keyRel (root, cur) != 1 || keyGetBaseNameSize (cur) != 3 || keyGetValueSize (cur) != 3) continue;
int res;
res = elektraHexcodeConvFromHex (keyBaseName (cur)[1]);
res += elektraHexcodeConvFromHex (keyBaseName (cur)[0]) * 16;
int val;
val = elektraHexcodeConvFromHex (keyString (cur)[1]);
val += elektraHexcodeConvFromHex (keyString (cur)[0]) * 16;
/* Hexencode this character! */
mapping->encode[res & 255] = val;
mapping->decode[val & 255] = res;
}
}
int elektraCcodeOpen (Plugin * handle, Key * key ELEKTRA_UNUSED)
{
CCodeData * mapping = new CCodeData ();
/* Store for later use...*/
elektraPluginSetData (handle, mapping);
KeySet * config = elektraPluginGetConfig (handle);
Key * escape = ksLookupByName (config, "/escape", 0);
mapping->escape = '\\';
if (escape && keyGetBaseNameSize (escape) && keyGetValueSize (escape) == 3)
{
int res;
res = elektraHexcodeConvFromHex (keyString (escape)[1]);
res += elektraHexcodeConvFromHex (keyString (escape)[0]) * 16;
mapping->escape = res & 255;
}
ELEKTRA_LOG_DEBUG ("Use “%c” as escape character", mapping->escape);
Key * root = ksLookupByName (config, "/chars", 0);
if (root)
{
readConfig (mapping, config, root);
}
else
{
setDefaultConfig (mapping);
}
return 0;
}
int elektraCcodeClose (Plugin * handle, Key * key ELEKTRA_UNUSED)
{
CCodeData * mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));
delete[](mapping->buf);
delete (mapping);
return 0;
}
/** Reads the value of the key and decodes all escaping
* codes into the buffer.
* @pre the buffer needs to be as large as value's size.
* @param cur the key holding the value to decode
* @param mapping the buffer to write to
*/
void elektraCcodeDecode (Key * cur, CCodeData * mapping)
{
size_t valsize = keyGetValueSize (cur);
const char * val = static_cast<const char *> (keyValue (cur));
if (!val) return;
size_t out = 0;
for (size_t in = 0; in < valsize - 1; ++in)
{
unsigned char character = val[in];
if (character == mapping->escape)
{
++in; /* Advance twice */
character = val[in];
mapping->buf[out] = mapping->decode[character & 255];
}
else
{
mapping->buf[out] = character;
}
++out; /* Only one char is written */
}
mapping->buf[out] = 0; // null termination for keyString()
keySetRaw (cur, mapping->buf, out + 1);
}
int elektraCcodeGet (Plugin * handle, KeySet * returned, Key * parentKey)
{
/* get all keys */
if (!strcmp (keyName (parentKey), "system/elektra/modules/ccode"))
{
KeySet * pluginConfig =
ksNew (30, keyNew ("system/elektra/modules/ccode", KEY_VALUE, "ccode plugin waits for your orders", KEY_END),
keyNew ("system/elektra/modules/ccode/exports", KEY_END),
keyNew ("system/elektra/modules/ccode/exports/open", KEY_FUNC, elektraCcodeOpen, KEY_END),
keyNew ("system/elektra/modules/ccode/exports/close", KEY_FUNC, elektraCcodeClose, KEY_END),
keyNew ("system/elektra/modules/ccode/exports/get", KEY_FUNC, elektraCcodeGet, KEY_END),
keyNew ("system/elektra/modules/ccode/exports/set", KEY_FUNC, elektraCcodeSet, KEY_END),
#include "readme_ccode.c"
keyNew ("system/elektra/modules/ccode/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END), KS_END);
ksAppend (returned, pluginConfig);
ksDel (pluginConfig);
return 1;
}
CCodeData * mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));
if (!mapping->buf)
{
mapping->bufalloc = 1000;
mapping->buf = new unsigned char[mapping->bufalloc];
}
Key * cur;
ksRewind (returned);
while ((cur = ksNext (returned)) != 0)
{
size_t valsize = keyGetValueSize (cur);
if (valsize > mapping->bufalloc)
{
mapping->bufalloc = valsize;
mapping->buf = new unsigned char[mapping->bufalloc];
}
elektraCcodeDecode (cur, mapping);
}
return 1; /* success */
}
/** Reads the value of the key and encodes it in
* c-style in the buffer.
*
* @param cur the key which value is to encode
* @param mapping the buffer
* @pre the buffer needs to have twice as much space as the value's size
*/
void elektraCcodeEncode (Key * cur, CCodeData * mapping)
{
size_t valsize = keyGetValueSize (cur);
const char * val = static_cast<const char *> (keyValue (cur));
if (!val) return;
size_t out = 0;
for (size_t in = 0; in < valsize - 1; ++in)
{
unsigned char character = val[in];
if (mapping->encode[character])
{
mapping->buf[out + 1] = mapping->encode[character];
// Escape char
mapping->buf[out] = mapping->escape;
out += 2;
}
else
{
// just copy one character
mapping->buf[out] = val[in];
// advance out cursor
out++;
// go to next char
}
}
mapping->buf[out] = 0; // null termination for keyString()
keySetRaw (cur, mapping->buf, out + 1);
}
int elektraCcodeSet (Plugin * handle, KeySet * returned, Key * parentKey ELEKTRA_UNUSED)
{
/* set all keys */
CCodeData * mapping = static_cast<CCodeData *> (elektraPluginGetData (handle));
if (!mapping->buf)
{
mapping->bufalloc = 1000;
mapping->buf = new unsigned char[mapping->bufalloc];
}
Key * cur;
ksRewind (returned);
while ((cur = ksNext (returned)) != 0)
{
size_t valsize = keyGetValueSize (cur);
if (valsize * 2 > mapping->bufalloc)
{
mapping->bufalloc = valsize * 2;
mapping->buf = new unsigned char[mapping->bufalloc];
}
elektraCcodeEncode (cur, mapping);
}
return 1; /* success */
}
Plugin * ELEKTRA_PLUGIN_EXPORT (ccode)
{
// clang-format off
return elektraPluginExport("ccode",
ELEKTRA_PLUGIN_OPEN, &elektraCcodeOpen,
ELEKTRA_PLUGIN_CLOSE, &elektraCcodeClose,
ELEKTRA_PLUGIN_GET, &elektraCcodeGet,
ELEKTRA_PLUGIN_SET, &elektraCcodeSet,
ELEKTRA_PLUGIN_END);
}
} // end extern "C"
<|endoftext|>
|
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Ash Berlin, Rüdiger Sonderfeld
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "flusspferd/class.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/security.hpp"
#include "flusspferd/modules.hpp"
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <cerrno>
using namespace flusspferd;
namespace {
int errno_getter() {
return errno;
}
void errno_setter(int errno_) {
errno = errno_;
}
std::string strerror_(int errno_) {
return std::strerror(errno_);
}
FLUSSPFERD_LOADER(posix) {
local_root_scope scope;
#ifdef HAVE_FORK
// TODO: Need to work out how to make this play nice with the interactive repl
create_native_function(posix, "fork", &::fork);
#endif
create_native_function(posix, "sleep", &::sleep);
#ifdef HAVE_USLEEP
create_native_function(posix, "usleep", usleep);
#endif
// errno
object errno_obj = create_object();
function get_errno = create_native_function(errno_obj, "get", &errno_getter);
function set_errno = create_native_function(errno_obj, "set", &errno_setter);
property_attributes errno_attr(permanent_shared_property,
get_errno, set_errno);
posix.define_property("errno", errno, errno_attr);
create_native_function(posix, "strerror", &strerror_);
create_native_function(posix, "perror", &std::perror);
}
}
<commit_msg>posix: include header <cstdio>, as required<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008 Ash Berlin, Rüdiger Sonderfeld
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "flusspferd/class.hpp"
#include "flusspferd/create.hpp"
#include "flusspferd/security.hpp"
#include "flusspferd/modules.hpp"
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <cerrno>
#include <cstdio>
using namespace flusspferd;
namespace {
int errno_getter() {
return errno;
}
void errno_setter(int errno_) {
errno = errno_;
}
std::string strerror_(int errno_) {
return std::strerror(errno_);
}
FLUSSPFERD_LOADER(posix) {
local_root_scope scope;
#ifdef HAVE_FORK
// TODO: Need to work out how to make this play nice with the interactive repl
create_native_function(posix, "fork", &::fork);
#endif
create_native_function(posix, "sleep", &::sleep);
#ifdef HAVE_USLEEP
create_native_function(posix, "usleep", usleep);
#endif
// errno
object errno_obj = create_object();
function get_errno = create_native_function(errno_obj, "get", &errno_getter);
function set_errno = create_native_function(errno_obj, "set", &errno_setter);
property_attributes errno_attr(permanent_shared_property,
get_errno, set_errno);
posix.define_property("errno", errno, errno_attr);
create_native_function(posix, "strerror", &strerror_);
create_native_function(posix, "perror", &std::perror);
}
}
<|endoftext|>
|
<commit_before>
#include "EulerProblem.h"
#include "CLawCellMaterial.h"
#include "CLawFaceMaterial.h"
#include "CLawBoundaryMaterial.h"
using Eigen::Vector3d;
template<>
InputParameters validParams<EulerProblem>()
{
InputParameters params = validParams<CFDProblem>();
return params;
}
EulerProblem::EulerProblem(const std::string & name, InputParameters params) :
CFDProblem(name, params)
{
}
void EulerProblem::computeCellFlux(RealGradient* flux, Real* source, Real* uh, RealGradient* duh)
{
RealVectorValue inv_term[10], vis_term[10], source_term[10], artificial_term[10];
inviscousTerm(inv_term, uh);
viscousTerm(vis_term, uh, duh);
sourceTerm(source, uh, duh);
artificialViscous(artificial_term, uh, duh);
for (int eq = 0; eq < _n_equations; ++eq)
flux[eq] = inv_term[eq] - vis_term[eq] - artificial_term[eq];
}
void EulerProblem::computeFaceFlux(Real* flux, RealVectorValue* lift, Real* ul, Real* ur, RealGradient* dul, RealGradient* dur, Point& normal, Real penalty)
{
RealVectorValue ifl[10], ifr[10], vfl[10], vfr[10];
computeLift(lift, ul, ur, normal);
viscousTerm(vfl, ul, dul);
viscousTerm(vfr, ur, dur);
fluxRiemann(flux, ul, ur, normal);
for (int eq = 0; eq < _n_equations; ++eq)
{
flux[eq] -= 0.5*((vfl[eq]+vfr[eq])-penalty*lift[eq])*normal;
}
}
void EulerProblem::artificialViscous(RealVectorValue* artificial_viscous, Real* uh, RealGradient* duh)
{
RealVectorValue vel(uh[1], uh[2], uh[3]);
vel /= uh[0];
Real c = std::sqrt(temperature(uh))/_mach;
Real indicator = uh[5] ;
// Real viscosity = 1000;//10000*indicator;//* duh[0].size()/uh[0]*0.01;
Real viscosity = 4*(vel.size() + c)*indicator;
int component = 0;
artificial_viscous[component] = viscosity*duh[component];
component = 1;
artificial_viscous[component] = viscosity*duh[component];
component = 2;
artificial_viscous[component] = viscosity*duh[component];
component = 3;
artificial_viscous[component] = viscosity*duh[component];
component = 4;
artificial_viscous[component] = viscosity*duh[component];
}
void EulerProblem::inviscousTerm(RealVectorValue* inviscous_term, Real* uh)
{
Real rho, p, h;
Real u, v, w;
rho = uh[0];
u = uh[1]/rho;
v = uh[2]/rho;
w = uh[3]/rho;
p = pressure(uh);
h = enthalpy(uh);
int component = 0;
component = 0;
inviscous_term[component](0) = uh[1]; // rhou
inviscous_term[component](1) = uh[2]; // rhov
inviscous_term[component](2) = uh[3]; // rhow
component = 1;
inviscous_term[component](0) = uh[1] * u + p;
inviscous_term[component](1) = uh[1] * v;
inviscous_term[component](2) = uh[1] * w;
component = 2;
inviscous_term[component](0) = uh[2] * u;
inviscous_term[component](1) = uh[2] * v + p;
inviscous_term[component](2) = uh[2] * w;
component = 3;
inviscous_term[component](0) = uh[3] * u;
inviscous_term[component](1) = uh[3] * v;
inviscous_term[component](2) = uh[3] * w + p;
component = 4;
inviscous_term[component](0) = rho * h * u;
inviscous_term[component](1) = rho * h * v;
inviscous_term[component](2) = rho * h * w;
}
void EulerProblem::viscousTerm(RealVectorValue* viscous_term, Real* uh, RealGradient* duh)
{
Real viscosity = 0.000;
int component = 0;
viscous_term[component](0) = 0.;
viscous_term[component](1) = 0.;
viscous_term[component](2) = 0.;
viscous_term[component] = viscosity*duh[component];
component = 1;
viscous_term[component](0) = 0.;
viscous_term[component](1) = 0.;
viscous_term[component](2) = 0.;
viscous_term[component] = viscosity*duh[component];
component = 2;
viscous_term[component](0) = 0.;
viscous_term[component](1) = 0.;
viscous_term[component](2) = 0.;
viscous_term[component] = viscosity*duh[component];
component = 3;
viscous_term[component](0) = 0.;
viscous_term[component](1) = 0.;
viscous_term[component](2) = 0.;
viscous_term[component] = viscosity*duh[component];
component = 4;
viscous_term[component](0) = 0.;
viscous_term[component](1) = 0.;
viscous_term[component](2) = 0.;
viscous_term[component] = viscosity*duh[component];
}
void EulerProblem::fluxRiemann(Real* flux, Real* ul, Real* ur, Point &normal)
{
RealVectorValue ifl[5], ifr[5], vfl[5], vfr[5];
Real uh[5];
inviscousTerm(ifl, ul);
inviscousTerm(ifr, ur);
for (int eq = 0; eq < _n_equations; ++eq)
uh[eq] = (ul[eq]+ur[eq])/2;
for (int eq = 0; eq < _n_equations; ++eq)
flux[eq] = 0.5*(ifl[eq] + ifr[eq])*normal + maxEigenValue(uh, normal)*(ul[eq] - ur[eq]);
}
void EulerProblem::boundaryCondition(Real *ur, Real *ul, Point &normal, std::string bc_type)
{
if(bc_type == "wall")
{
wall(ur, ul, normal);
return;
}
if(bc_type == "far_field")
{
farField(ur, ul, normal);
return;
}
if(bc_type == "symmetric")
{
symmetric(ur, ul, normal);
return;
}
mooseError( bc_type << "未定义的边界条件类型");
}
void EulerProblem::wall(Real *ur, Real *ul, Point &normal)
{
RealVectorValue momentum(ul[1], ul[2], ul[3]);
Real vn = momentum*normal;
Real pre = pressure(ul);
ur[0] = ul[0];
ur[1] = ul[1] - 2.0 * vn * normal(0);
ur[2] = ul[2] - 2.0 * vn * normal(1);
ur[3] = ul[3] - 2.0 * vn * normal(2);
ur[4] = pre/(_gamma-1) + 0.5*momentum.size_sq()/ur[0];
}
void EulerProblem::symmetric(Real *ur, Real *ul, Point &normal)
{
wall(ur, ul, normal);
}
void EulerProblem::farField(Real *ur, Real *ul, Point &normal)
{
Real rhoR, uR, vR, wR, pR;
Real rhoL, uL, vL, wL, pL;
Real cR, cL, cb;
Real vnR, vnL, vnb;
Real vel, s;
Real Rp, Rm;
Vector3d velocity = _attitude.earthFromWind()*Vector3d::UnitX();
uR = velocity(0);
vR = velocity(1);
wR = velocity(2);
rhoR = 1.0;
pR = 1 / _gamma /_mach / _mach;
cR = sqrt(fabs(_gamma * pR / rhoR));
vnR = normal(0) * uR + normal(1) * vR + normal(2) * wR;
rhoL = ul[0];
uL = ul[1] / rhoL;
vL = ul[2] / rhoL;
wL = ul[3] / rhoL;
vel = sqrt(uL * uL + vL * vL + wL * wL);
pL = pressure(ul);
cL = sqrt(fabs(_gamma * pL / rhoL));
vnL = normal(0) * uL + normal(1) * vL + normal(2) * wL;
if (vel >= cL) { //超声速
if (vnL >= 0.0) //exit
{
ur[0] = ul[0];
ur[1] = ul[1];
ur[2] = ul[2];
ur[3] = ul[3];
ur[4] = ul[4];
}
else //inlet
{
ur[0] = rhoR;
ur[1] = rhoR * uR;
ur[2] = rhoR * vR;
ur[3] = rhoR * wR;
ur[4] = pR / (_gamma - 1) + 0.5 * rhoR * (uR * uR + vR * vR + wR * wR);
}
}
else
{ // 亚声速
if (vnL >= 0.0)
{ //exit
s = pL / pow(rhoL, _gamma);
Rp = vnL + 2 * cL / (_gamma - 1);
Rm = vnR - 2 * cR / (_gamma - 1);
vnb = (Rp + Rm) / 2.0;
cb = (Rp - Rm) * (_gamma - 1) / 4.0;
ur[0] = pow((cb * cb) / (s * _gamma), 1.0 / (_gamma - 1));
ur[1] = ur[0] * (uL + normal(0) * (vnb - vnL));
ur[2] = ur[0] * (vL + normal(1) * (vnb - vnL));
ur[3] = ur[0] * (wL + normal(2) * (vnb - vnL));
ur[4] = cb * cb * ur[0] / _gamma / (_gamma - 1) + 0.5 * (ur[1] * ur[1] + ur[2] * ur[2] + ur[3] * ur[3]) / ur[0];
}
else
{
s = pR / pow(rhoR, _gamma);
Rp = -vnR + 2.0 * cR / (_gamma - 1);
Rm = -vnL - 2.0 * cL / (_gamma - 1);
vnb = -(Rp + Rm) / 2.0;
cb = (Rp - Rm) * (_gamma - 1) / 4.0;
ur[0] = pow((cb * cb) / (s * _gamma), 1.0 / (_gamma - 1));
ur[1] = ur[0] * (uR + normal(0) * (vnb - vnR));
ur[2] = ur[0] * (vR + normal(1) * (vnb - vnR));
ur[3] = ur[0] * (wR + normal(2) * (vnb - vnR));
ur[4] = cb * cb * ur[0] / _gamma / (_gamma - 1) + 0.5 * (ur[1] * ur[1] + ur[2] * ur[2] + ur[3] * ur[3]) / ur[0];
}
}
}
Real EulerProblem::physicalViscosity(Real* uh)
{
return 0;
}
void EulerProblem::updateDependValue(DependValue& denpend_value, Real *uh)
{
denpend_value.pressure = pressure(uh);
}
<commit_msg>测试BlastWave不成功<commit_after>
#include "EulerProblem.h"
#include "CLawCellMaterial.h"
#include "CLawFaceMaterial.h"
#include "CLawBoundaryMaterial.h"
using Eigen::Vector3d;
template<>
InputParameters validParams<EulerProblem>()
{
InputParameters params = validParams<CFDProblem>();
return params;
}
EulerProblem::EulerProblem(const std::string & name, InputParameters params) :
CFDProblem(name, params)
{
}
void EulerProblem::computeCellFlux(RealGradient* flux, Real* source, Real* uh, RealGradient* duh)
{
RealVectorValue inv_term[10], vis_term[10], source_term[10], artificial_term[10];
inviscousTerm(inv_term, uh);
viscousTerm(vis_term, uh, duh);
sourceTerm(source, uh, duh);
artificialViscous(artificial_term, uh, duh);
for (int eq = 0; eq < _n_equations; ++eq)
flux[eq] = inv_term[eq] - vis_term[eq] - artificial_term[eq];
}
void EulerProblem::computeFaceFlux(Real* flux, RealVectorValue* lift, Real* ul, Real* ur, RealGradient* dul, RealGradient* dur, Point& normal, Real penalty)
{
RealVectorValue ifl[10], ifr[10], vfl[10], vfr[10];
computeLift(lift, ul, ur, normal);
viscousTerm(vfl, ul, dul);
viscousTerm(vfr, ur, dur);
fluxRiemann(flux, ul, ur, normal);
for (int eq = 0; eq < _n_equations; ++eq)
{
flux[eq] -= 0.5*((vfl[eq]+vfr[eq])-penalty*lift[eq])*normal;
}
}
void EulerProblem::artificialViscous(RealVectorValue* artificial_viscous, Real* uh, RealGradient* duh)
{
RealVectorValue vel(uh[1], uh[2], uh[3]);
vel /= uh[0];
Real c = std::sqrt(temperature(uh))/_mach;
Real indicator = uh[5] ;
// Real viscosity = 1000;//10000*indicator;//* duh[0].size()/uh[0]*0.01;
Real viscosity = 100;4*(vel.size() + c)*indicator;
int component = 0;
artificial_viscous[component] = viscosity*duh[component];
component = 1;
artificial_viscous[component] = viscosity*duh[component];
component = 2;
artificial_viscous[component] = viscosity*duh[component];
component = 3;
artificial_viscous[component] = viscosity*duh[component];
component = 4;
artificial_viscous[component] = viscosity*duh[component];
}
void EulerProblem::inviscousTerm(RealVectorValue* inviscous_term, Real* uh)
{
Real rho, p, h;
Real u, v, w;
rho = uh[0];
u = uh[1]/rho;
v = uh[2]/rho;
w = uh[3]/rho;
p = pressure(uh);
h = enthalpy(uh);
int component = 0;
component = 0;
inviscous_term[component](0) = uh[1]; // rhou
inviscous_term[component](1) = uh[2]; // rhov
inviscous_term[component](2) = uh[3]; // rhow
component = 1;
inviscous_term[component](0) = uh[1] * u + p;
inviscous_term[component](1) = uh[1] * v;
inviscous_term[component](2) = uh[1] * w;
component = 2;
inviscous_term[component](0) = uh[2] * u;
inviscous_term[component](1) = uh[2] * v + p;
inviscous_term[component](2) = uh[2] * w;
component = 3;
inviscous_term[component](0) = uh[3] * u;
inviscous_term[component](1) = uh[3] * v;
inviscous_term[component](2) = uh[3] * w + p;
component = 4;
inviscous_term[component](0) = rho * h * u;
inviscous_term[component](1) = rho * h * v;
inviscous_term[component](2) = rho * h * w;
}
void EulerProblem::viscousTerm(RealVectorValue* viscous_term, Real* uh, RealGradient* duh)
{
Real viscosity = 0.000;
int component = 0;
viscous_term[component](0) = 0.;
viscous_term[component](1) = 0.;
viscous_term[component](2) = 0.;
viscous_term[component] = viscosity*duh[component];
component = 1;
viscous_term[component](0) = 0.;
viscous_term[component](1) = 0.;
viscous_term[component](2) = 0.;
viscous_term[component] = viscosity*duh[component];
component = 2;
viscous_term[component](0) = 0.;
viscous_term[component](1) = 0.;
viscous_term[component](2) = 0.;
viscous_term[component] = viscosity*duh[component];
component = 3;
viscous_term[component](0) = 0.;
viscous_term[component](1) = 0.;
viscous_term[component](2) = 0.;
viscous_term[component] = viscosity*duh[component];
component = 4;
viscous_term[component](0) = 0.;
viscous_term[component](1) = 0.;
viscous_term[component](2) = 0.;
viscous_term[component] = viscosity*duh[component];
}
void EulerProblem::fluxRiemann(Real* flux, Real* ul, Real* ur, Point &normal)
{
RealVectorValue ifl[5], ifr[5], vfl[5], vfr[5];
Real uh[5];
inviscousTerm(ifl, ul);
inviscousTerm(ifr, ur);
for (int eq = 0; eq < _n_equations; ++eq)
uh[eq] = (ul[eq]+ur[eq])/2;
for (int eq = 0; eq < _n_equations; ++eq)
flux[eq] = 0.5*(ifl[eq] + ifr[eq])*normal + maxEigenValue(uh, normal)*(ul[eq] - ur[eq]);
}
void EulerProblem::boundaryCondition(Real *ur, Real *ul, Point &normal, std::string bc_type)
{
if(bc_type == "wall")
{
wall(ur, ul, normal);
return;
}
if(bc_type == "far_field")
{
farField(ur, ul, normal);
return;
}
if(bc_type == "symmetric")
{
symmetric(ur, ul, normal);
return;
}
mooseError( bc_type << "未定义的边界条件类型");
}
void EulerProblem::wall(Real *ur, Real *ul, Point &normal)
{
RealVectorValue momentum(ul[1], ul[2], ul[3]);
Real vn = momentum*normal;
Real pre = pressure(ul);
ur[0] = ul[0];
ur[1] = ul[1] - 2.0 * vn * normal(0);
ur[2] = ul[2] - 2.0 * vn * normal(1);
ur[3] = ul[3] - 2.0 * vn * normal(2);
ur[4] = pre/(_gamma-1) + 0.5*momentum.size_sq()/ur[0];
}
void EulerProblem::symmetric(Real *ur, Real *ul, Point &normal)
{
wall(ur, ul, normal);
}
void EulerProblem::farField(Real *ur, Real *ul, Point &normal)
{
Real rhoR, uR, vR, wR, pR;
Real rhoL, uL, vL, wL, pL;
Real cR, cL, cb;
Real vnR, vnL, vnb;
Real vel, s;
Real Rp, Rm;
Vector3d velocity = _attitude.earthFromWind()*Vector3d::UnitX();
uR = velocity(0);
vR = velocity(1);
wR = velocity(2);
rhoR = 1.0;
pR = 1 / _gamma /_mach / _mach;
cR = sqrt(fabs(_gamma * pR / rhoR));
vnR = normal(0) * uR + normal(1) * vR + normal(2) * wR;
rhoL = ul[0];
uL = ul[1] / rhoL;
vL = ul[2] / rhoL;
wL = ul[3] / rhoL;
vel = sqrt(uL * uL + vL * vL + wL * wL);
pL = pressure(ul);
cL = sqrt(fabs(_gamma * pL / rhoL));
vnL = normal(0) * uL + normal(1) * vL + normal(2) * wL;
if (vel >= cL) { //超声速
if (vnL >= 0.0) //exit
{
ur[0] = ul[0];
ur[1] = ul[1];
ur[2] = ul[2];
ur[3] = ul[3];
ur[4] = ul[4];
}
else //inlet
{
ur[0] = rhoR;
ur[1] = rhoR * uR;
ur[2] = rhoR * vR;
ur[3] = rhoR * wR;
ur[4] = pR / (_gamma - 1) + 0.5 * rhoR * (uR * uR + vR * vR + wR * wR);
}
}
else
{ // 亚声速
if (vnL >= 0.0)
{ //exit
s = pL / pow(rhoL, _gamma);
Rp = vnL + 2 * cL / (_gamma - 1);
Rm = vnR - 2 * cR / (_gamma - 1);
vnb = (Rp + Rm) / 2.0;
cb = (Rp - Rm) * (_gamma - 1) / 4.0;
ur[0] = pow((cb * cb) / (s * _gamma), 1.0 / (_gamma - 1));
ur[1] = ur[0] * (uL + normal(0) * (vnb - vnL));
ur[2] = ur[0] * (vL + normal(1) * (vnb - vnL));
ur[3] = ur[0] * (wL + normal(2) * (vnb - vnL));
ur[4] = cb * cb * ur[0] / _gamma / (_gamma - 1) + 0.5 * (ur[1] * ur[1] + ur[2] * ur[2] + ur[3] * ur[3]) / ur[0];
}
else
{
s = pR / pow(rhoR, _gamma);
Rp = -vnR + 2.0 * cR / (_gamma - 1);
Rm = -vnL - 2.0 * cL / (_gamma - 1);
vnb = -(Rp + Rm) / 2.0;
cb = (Rp - Rm) * (_gamma - 1) / 4.0;
ur[0] = pow((cb * cb) / (s * _gamma), 1.0 / (_gamma - 1));
ur[1] = ur[0] * (uR + normal(0) * (vnb - vnR));
ur[2] = ur[0] * (vR + normal(1) * (vnb - vnR));
ur[3] = ur[0] * (wR + normal(2) * (vnb - vnR));
ur[4] = cb * cb * ur[0] / _gamma / (_gamma - 1) + 0.5 * (ur[1] * ur[1] + ur[2] * ur[2] + ur[3] * ur[3]) / ur[0];
}
}
}
Real EulerProblem::physicalViscosity(Real* uh)
{
return 0;
}
void EulerProblem::updateDependValue(DependValue& denpend_value, Real *uh)
{
denpend_value.pressure = pressure(uh);
}
<|endoftext|>
|
<commit_before>/*
* 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/.
*
* Copyright (C) 2017, James R. Barlow (https://github.com/jbarlow83/)
*/
/*
* Convert Python types <-> QPDFObjectHandle types
*/
#include <vector>
#include <map>
#include <cmath>
#include <qpdf/Constants.h>
#include <qpdf/Types.h>
#include <qpdf/DLL.h>
#include <qpdf/QPDFExc.hh>
#include <qpdf/QPDFObjGen.hh>
#include <qpdf/PointerHolder.hh>
#include <qpdf/Buffer.hh>
#include <qpdf/QPDFObjectHandle.hh>
#include <qpdf/QPDF.hh>
#include <qpdf/QPDFWriter.hh>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "pikepdf.h"
extern uint DECIMAL_PRECISION;
std::map<std::string, QPDFObjectHandle>
dict_builder(const py::dict dict)
{
StackGuard sg(" dict_builder");
std::map<std::string, QPDFObjectHandle> result;
for (const auto& item: dict) {
std::string key = item.first.cast<std::string>();
auto value = objecthandle_encode(item.second);
result[key] = value;
}
return result;
}
std::vector<QPDFObjectHandle>
array_builder(const py::iterable iter)
{
StackGuard sg(" array_builder");
std::vector<QPDFObjectHandle> result;
int narg = 0;
for (const auto& item: iter) {
narg++;
auto value = objecthandle_encode(item);
result.push_back(value);
}
return result;
}
class DecimalPrecision {
public:
DecimalPrecision(uint calc_precision) :
decimal_context(py::module::import("decimal").attr("getcontext")()),
saved_precision(decimal_context.attr("prec").cast<uint>())
{
decimal_context.attr("prec") = calc_precision;
}
~DecimalPrecision() {
decimal_context.attr("prec") = saved_precision;
}
DecimalPrecision(const DecimalPrecision& other) = delete;
DecimalPrecision(DecimalPrecision&& other) = delete;
DecimalPrecision& operator= (const DecimalPrecision& other) = delete;
DecimalPrecision& operator= (DecimalPrecision&& other) = delete;
private:
py::object decimal_context;
uint saved_precision;
};
QPDFObjectHandle objecthandle_encode(const py::handle handle)
{
if (handle.is_none())
return QPDFObjectHandle::newNull();
// Ensure that when we return QPDFObjectHandle/pikepdf.Object to the Py
// environment, that we can recover it
try {
auto as_qobj = handle.cast<QPDFObjectHandle>();
return as_qobj;
} catch (const py::cast_error&) {}
// Special-case booleans since pybind11 coerces nonzero integers to boolean
if (py::isinstance<py::bool_>(handle)) {
bool as_bool = handle.cast<bool>();
return QPDFObjectHandle::newBool(as_bool);
}
auto decimal_module = py::module::import("decimal");
auto Decimal = decimal_module.attr("Decimal");
if (py::isinstance(handle, Decimal)) {
DecimalPrecision dp(DECIMAL_PRECISION);
auto rounded = py::reinterpret_steal<py::object>(PyNumber_Positive(handle.ptr()));
if (! rounded.attr("is_finite")().cast<bool>())
throw py::value_error("Can't convert NaN or Infinity to PDF real number");
return QPDFObjectHandle::newReal(py::str(rounded));
} else if (py::isinstance<py::int_>(handle)) {
auto as_int = handle.cast<long long>();
return QPDFObjectHandle::newInteger(as_int);
} else if (py::isinstance<py::float_>(handle)) {
auto as_double = handle.cast<double>();
if (! isfinite(as_double))
throw py::value_error("Can't convert NaN or Infinity to PDF real number");
return QPDFObjectHandle::newReal(as_double);
}
py::object obj = py::reinterpret_borrow<py::object>(handle);
if (py::isinstance<py::bytes>(obj)) {
py::bytes py_bytes = obj;
return QPDFObjectHandle::newString(static_cast<std::string>(py_bytes));
} else if (py::isinstance<py::str>(obj)) {
py::str py_str = obj;
return QPDFObjectHandle::newUnicodeString(static_cast<std::string>(py_str));
}
if (py::hasattr(obj, "__iter__")) {
//py::print(py::repr(obj));
bool is_mapping = false; // PyMapping_Check is unreliable in Py3
if (py::hasattr(obj, "keys"))
is_mapping = true;
bool is_sequence = PySequence_Check(obj.ptr());
if (is_mapping) {
return QPDFObjectHandle::newDictionary(dict_builder(obj));
} else if (is_sequence) {
return QPDFObjectHandle::newArray(array_builder(obj));
}
}
throw py::cast_error(std::string("don't know how to encode value ") + std::string(py::repr(obj)));
}
py::object decimal_from_pdfobject(QPDFObjectHandle h)
{
auto decimal_constructor = py::module::import("decimal").attr("Decimal");
if (h.getTypeCode() == QPDFObject::object_type_e::ot_integer) {
auto value = h.getIntValue();
return decimal_constructor(py::cast(value));
} else if (h.getTypeCode() == QPDFObject::object_type_e::ot_real) {
auto value = h.getRealValue();
return decimal_constructor(py::cast(value));
} else if (h.getTypeCode() == QPDFObject::object_type_e::ot_boolean) {
auto value = h.getBoolValue();
return decimal_constructor(py::cast(value));
}
throw py::type_error("object has no Decimal() representation");
}
<commit_msg>Use std::isfinite() to fix compilation on GCC 5<commit_after>/*
* 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/.
*
* Copyright (C) 2017, James R. Barlow (https://github.com/jbarlow83/)
*/
/*
* Convert Python types <-> QPDFObjectHandle types
*/
#include <vector>
#include <map>
#include <cmath>
#include <qpdf/Constants.h>
#include <qpdf/Types.h>
#include <qpdf/DLL.h>
#include <qpdf/QPDFExc.hh>
#include <qpdf/QPDFObjGen.hh>
#include <qpdf/PointerHolder.hh>
#include <qpdf/Buffer.hh>
#include <qpdf/QPDFObjectHandle.hh>
#include <qpdf/QPDF.hh>
#include <qpdf/QPDFWriter.hh>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "pikepdf.h"
extern uint DECIMAL_PRECISION;
std::map<std::string, QPDFObjectHandle>
dict_builder(const py::dict dict)
{
StackGuard sg(" dict_builder");
std::map<std::string, QPDFObjectHandle> result;
for (const auto& item: dict) {
std::string key = item.first.cast<std::string>();
auto value = objecthandle_encode(item.second);
result[key] = value;
}
return result;
}
std::vector<QPDFObjectHandle>
array_builder(const py::iterable iter)
{
StackGuard sg(" array_builder");
std::vector<QPDFObjectHandle> result;
int narg = 0;
for (const auto& item: iter) {
narg++;
auto value = objecthandle_encode(item);
result.push_back(value);
}
return result;
}
class DecimalPrecision {
public:
DecimalPrecision(uint calc_precision) :
decimal_context(py::module::import("decimal").attr("getcontext")()),
saved_precision(decimal_context.attr("prec").cast<uint>())
{
decimal_context.attr("prec") = calc_precision;
}
~DecimalPrecision() {
decimal_context.attr("prec") = saved_precision;
}
DecimalPrecision(const DecimalPrecision& other) = delete;
DecimalPrecision(DecimalPrecision&& other) = delete;
DecimalPrecision& operator= (const DecimalPrecision& other) = delete;
DecimalPrecision& operator= (DecimalPrecision&& other) = delete;
private:
py::object decimal_context;
uint saved_precision;
};
QPDFObjectHandle objecthandle_encode(const py::handle handle)
{
if (handle.is_none())
return QPDFObjectHandle::newNull();
// Ensure that when we return QPDFObjectHandle/pikepdf.Object to the Py
// environment, that we can recover it
try {
auto as_qobj = handle.cast<QPDFObjectHandle>();
return as_qobj;
} catch (const py::cast_error&) {}
// Special-case booleans since pybind11 coerces nonzero integers to boolean
if (py::isinstance<py::bool_>(handle)) {
bool as_bool = handle.cast<bool>();
return QPDFObjectHandle::newBool(as_bool);
}
auto decimal_module = py::module::import("decimal");
auto Decimal = decimal_module.attr("Decimal");
if (py::isinstance(handle, Decimal)) {
DecimalPrecision dp(DECIMAL_PRECISION);
auto rounded = py::reinterpret_steal<py::object>(PyNumber_Positive(handle.ptr()));
if (! rounded.attr("is_finite")().cast<bool>())
throw py::value_error("Can't convert NaN or Infinity to PDF real number");
return QPDFObjectHandle::newReal(py::str(rounded));
} else if (py::isinstance<py::int_>(handle)) {
auto as_int = handle.cast<long long>();
return QPDFObjectHandle::newInteger(as_int);
} else if (py::isinstance<py::float_>(handle)) {
auto as_double = handle.cast<double>();
if (! std::isfinite(as_double))
throw py::value_error("Can't convert NaN or Infinity to PDF real number");
return QPDFObjectHandle::newReal(as_double);
}
py::object obj = py::reinterpret_borrow<py::object>(handle);
if (py::isinstance<py::bytes>(obj)) {
py::bytes py_bytes = obj;
return QPDFObjectHandle::newString(static_cast<std::string>(py_bytes));
} else if (py::isinstance<py::str>(obj)) {
py::str py_str = obj;
return QPDFObjectHandle::newUnicodeString(static_cast<std::string>(py_str));
}
if (py::hasattr(obj, "__iter__")) {
//py::print(py::repr(obj));
bool is_mapping = false; // PyMapping_Check is unreliable in Py3
if (py::hasattr(obj, "keys"))
is_mapping = true;
bool is_sequence = PySequence_Check(obj.ptr());
if (is_mapping) {
return QPDFObjectHandle::newDictionary(dict_builder(obj));
} else if (is_sequence) {
return QPDFObjectHandle::newArray(array_builder(obj));
}
}
throw py::cast_error(std::string("don't know how to encode value ") + std::string(py::repr(obj)));
}
py::object decimal_from_pdfobject(QPDFObjectHandle h)
{
auto decimal_constructor = py::module::import("decimal").attr("Decimal");
if (h.getTypeCode() == QPDFObject::object_type_e::ot_integer) {
auto value = h.getIntValue();
return decimal_constructor(py::cast(value));
} else if (h.getTypeCode() == QPDFObject::object_type_e::ot_real) {
auto value = h.getRealValue();
return decimal_constructor(py::cast(value));
} else if (h.getTypeCode() == QPDFObject::object_type_e::ot_boolean) {
auto value = h.getBoolValue();
return decimal_constructor(py::cast(value));
}
throw py::type_error("object has no Decimal() representation");
}
<|endoftext|>
|
<commit_before>#include <framesgallery.hpp>
#include <QHBoxLayout>
#include <QFrame>
#include <QLabel>
#include <QMouseEvent>
#include <QMenu>
#include <animationframewidget.hpp>
FramesGallery::FramesGallery(QWidget *parent)
:
QWidget(parent),
m_layout(new QHBoxLayout(this)),
m_draggedFrame(nullptr),
m_startDragIndex(-1),
m_spacerIndex(-1),
m_dragSpacer(new QSpacerItem(0, 0))
{
setLayout(m_layout);
}
FramesGallery::~FramesGallery()
{
delete m_dragSpacer;
}
void FramesGallery::reset()
{
setSpritesheet();
setFrames();
}
void FramesGallery::setFrames(const std::vector<AnimationFrame>& frames)
{
clearGallery();
int i = 0;
for(const AnimationFrame& frame : frames)
{
m_frameWidgets.push_back(createFrameWidget(frame));
m_layout->addWidget(m_frameWidgets.back());
++i;
}
if(!m_frameWidgets.empty())
{
m_frameWidgets.front()->setStyleSheet("background: #ADD8E6;");
emit frameSelected(frames.front());
}
}
void FramesGallery::updateGallery()
{
}
void FramesGallery::addFrame(const AnimationFrame& frame)
{
auto&& frameWidget = createFrameWidget(frame);
m_frameWidgets.emplace_back(frameWidget);
m_layout->addWidget(m_frameWidgets.back());
}
void FramesGallery::updateFrame(int at, const AnimationFrame &updatedFrame)
{
if(at >= 0 && static_cast<unsigned>(at) < m_frameWidgets.size())
{
m_frameWidgets[at]->deleteLater();
auto&& frameWidget = createFrameWidget(updatedFrame);
m_layout->replaceWidget(m_frameWidgets[at], frameWidget);
m_frameWidgets[at] = frameWidget;
}
}
AnimationFrameWidget *FramesGallery::createFrameWidget(const AnimationFrame &frame)
{
AnimationFrameWidget* frameWidget = new AnimationFrameWidget(frame.getName(),
m_spritesheet.copy(frame.getRect()),
this);
connect(frameWidget, &AnimationFrameWidget::framePressed, [this, frame, frameWidget]
{
//Reset all widgets stylesheet
std::for_each(m_frameWidgets.begin(), m_frameWidgets.end(), [](QWidget* w) { w->setStyleSheet(""); });
frameWidget->setStyleSheet("background: #ADD8E6;");
emit frameSelected(frame);
//Handle dragging
m_draggedFrame = frameWidget;
//Get start drag position
m_startDragPos = mapFromGlobal(QCursor::pos());
//Get index of frame in layout so we can replace it with spacer item
m_startDragIndex = m_spacerIndex = m_layout->indexOf(m_draggedFrame);
//Remove widget from layout
m_layout->removeWidget(m_draggedFrame);
//Make spacer width and height same as dragged frame
m_dragSpacer->changeSize(m_draggedFrame->size().width(), m_draggedFrame->size().height());
//And insert spacer at position
m_layout->insertSpacerItem(m_spacerIndex, m_dragSpacer);
});
connect(frameWidget, &AnimationFrameWidget::frameReleased, [this, frameWidget]
{
if(m_draggedFrame == frameWidget)
{
//Insert dragged frame at spacer position
m_layout->removeItem(m_dragSpacer);
m_layout->insertWidget(m_spacerIndex, m_draggedFrame);
if(m_spacerIndex != m_startDragIndex)
emit frameMoved(m_startDragIndex, m_spacerIndex);
m_startDragIndex = m_spacerIndex = -1;
m_draggedFrame = nullptr;
}
});
connect(frameWidget, &AnimationFrameWidget::frameRightClicked, [this, frame, frameWidget]
{
std::for_each(m_frameWidgets.begin(), m_frameWidgets.end(), [](QWidget* w) { w->setStyleSheet(""); });
frameWidget->setStyleSheet("background: #ADD8E6;");
emit frameSelected(frame);
QMenu contextMenu(tr("Frame context"), this);
QAction newFrameAction(tr("New frame"), this);
connect(&newFrameAction, &QAction::triggered, [this](bool){ emit newFrameRequested(); });
QAction removeFrameAction(tr("Remove frame"), this);
//TODO
QAction editFrameAction(tr("Edit frame"), this);
connect(&editFrameAction, &QAction::triggered, [this, frameWidget](bool){ emit editFrameRequested(m_layout->indexOf(frameWidget)); });
contextMenu.addAction(&newFrameAction);
contextMenu.addAction(&removeFrameAction);
contextMenu.addSeparator();
contextMenu.addAction(&editFrameAction);
contextMenu.exec(QCursor::pos());
});
connect(frameWidget, &AnimationFrameWidget::frameDoubleClicked, [this, frameWidget]
{
emit frameDoubleClicked(m_layout->indexOf(frameWidget));
});
return frameWidget;
}
void FramesGallery::setSpritesheet(const QPixmap &spritesheet)
{
m_spritesheet = spritesheet;
}
void FramesGallery::clearGallery()
{
if(m_frameWidgets.size() > 0)
{
std::for_each(m_frameWidgets.begin(), m_frameWidgets.end(), [](AnimationFrameWidget* widget) { widget->deleteLater(); });
m_frameWidgets.clear();
m_layout->removeItem(m_dragSpacer);
}
}
void FramesGallery::mouseReleaseEvent(QMouseEvent *event)
{
if(event->button() == Qt::MouseButton::RightButton)
{
QMenu contextMenu(tr("New frame context"), this);
QAction newFrameAction(tr("New frame"), this);
connect(&newFrameAction, &QAction::triggered, [this](bool){ emit newFrameRequested(); });
contextMenu.addAction(&newFrameAction);
contextMenu.exec(QCursor::pos());
}
}
void FramesGallery::mouseMoveEvent(QMouseEvent *event)
{
if(m_draggedFrame)
{
QPoint subPos = event->pos() - m_startDragPos;
if(m_draggedFrame->pos().x() + subPos.x() >= pos().x() - (m_draggedFrame->size().width() / 2) &&
m_draggedFrame->pos().x() + m_draggedFrame->size().width() + subPos.x() < pos().x() + size().width() + (m_draggedFrame->size().width() / 2))
m_draggedFrame->move(m_draggedFrame->pos().x() + subPos.x(), m_draggedFrame->pos().y());
m_startDragPos = event->pos();
//TODO I believe this can look better
if(m_layout->count() > 1)
{
//When spacer is in middle of frames but not at the beggining and end
if(m_spacerIndex > 0 && m_spacerIndex < m_layout->count() - 1)
{
const auto widgetAfterSpacer = m_layout->itemAt(m_spacerIndex + 1)->widget();
//Handle after spacer
if(m_draggedFrame->pos().x() > widgetAfterSpacer->pos().x())
{
m_layout->removeItem(m_dragSpacer);
m_layout->insertSpacerItem(++m_spacerIndex, m_dragSpacer);
}
const auto widgetBeforeSpacer = m_layout->itemAt(m_spacerIndex - 1)->widget();
//Handle before spacer
if(m_draggedFrame->pos().x() < widgetBeforeSpacer->pos().x())
{
m_layout->removeItem(m_dragSpacer);
m_layout->insertSpacerItem(--m_spacerIndex, m_dragSpacer);
}
}
else if(m_spacerIndex == 0) // Spacer at the beginning
{
const auto widgetAfterSpacer = m_layout->itemAt(m_spacerIndex + 1)->widget();
if(m_draggedFrame->pos().x() > widgetAfterSpacer->pos().x())
{
m_layout->removeItem(m_dragSpacer);
m_layout->insertSpacerItem(++m_spacerIndex, m_dragSpacer);
}
}
else if(m_spacerIndex == m_layout->count() - 1) // Spacer at the end
{
const auto widgetBeforeSpacer = m_layout->itemAt(m_spacerIndex - 1)->widget();
if(m_draggedFrame->pos().x() < widgetBeforeSpacer->pos().x())
{
m_layout->removeItem(m_dragSpacer);
m_layout->insertSpacerItem(--m_spacerIndex, m_dragSpacer);
}
}
}
}
}
<commit_msg>Deleted updateGallery method which caused build to fail<commit_after>#include <framesgallery.hpp>
#include <QHBoxLayout>
#include <QFrame>
#include <QLabel>
#include <QMouseEvent>
#include <QMenu>
#include <animationframewidget.hpp>
FramesGallery::FramesGallery(QWidget *parent)
:
QWidget(parent),
m_layout(new QHBoxLayout(this)),
m_draggedFrame(nullptr),
m_startDragIndex(-1),
m_spacerIndex(-1),
m_dragSpacer(new QSpacerItem(0, 0))
{
setLayout(m_layout);
}
FramesGallery::~FramesGallery()
{
delete m_dragSpacer;
}
void FramesGallery::reset()
{
setSpritesheet();
setFrames();
}
void FramesGallery::setFrames(const std::vector<AnimationFrame>& frames)
{
clearGallery();
int i = 0;
for(const AnimationFrame& frame : frames)
{
m_frameWidgets.push_back(createFrameWidget(frame));
m_layout->addWidget(m_frameWidgets.back());
++i;
}
if(!m_frameWidgets.empty())
{
m_frameWidgets.front()->setStyleSheet("background: #ADD8E6;");
emit frameSelected(frames.front());
}
}
void FramesGallery::addFrame(const AnimationFrame& frame)
{
auto&& frameWidget = createFrameWidget(frame);
m_frameWidgets.emplace_back(frameWidget);
m_layout->addWidget(m_frameWidgets.back());
}
void FramesGallery::updateFrame(int at, const AnimationFrame &updatedFrame)
{
if(at >= 0 && static_cast<unsigned>(at) < m_frameWidgets.size())
{
m_frameWidgets[at]->deleteLater();
auto&& frameWidget = createFrameWidget(updatedFrame);
m_layout->replaceWidget(m_frameWidgets[at], frameWidget);
m_frameWidgets[at] = frameWidget;
}
}
AnimationFrameWidget *FramesGallery::createFrameWidget(const AnimationFrame &frame)
{
AnimationFrameWidget* frameWidget = new AnimationFrameWidget(frame.getName(),
m_spritesheet.copy(frame.getRect()),
this);
connect(frameWidget, &AnimationFrameWidget::framePressed, [this, frame, frameWidget]
{
//Reset all widgets stylesheet
std::for_each(m_frameWidgets.begin(), m_frameWidgets.end(), [](QWidget* w) { w->setStyleSheet(""); });
frameWidget->setStyleSheet("background: #ADD8E6;");
emit frameSelected(frame);
//Handle dragging
m_draggedFrame = frameWidget;
//Get start drag position
m_startDragPos = mapFromGlobal(QCursor::pos());
//Get index of frame in layout so we can replace it with spacer item
m_startDragIndex = m_spacerIndex = m_layout->indexOf(m_draggedFrame);
//Remove widget from layout
m_layout->removeWidget(m_draggedFrame);
//Make spacer width and height same as dragged frame
m_dragSpacer->changeSize(m_draggedFrame->size().width(), m_draggedFrame->size().height());
//And insert spacer at position
m_layout->insertSpacerItem(m_spacerIndex, m_dragSpacer);
});
connect(frameWidget, &AnimationFrameWidget::frameReleased, [this, frameWidget]
{
if(m_draggedFrame == frameWidget)
{
//Insert dragged frame at spacer position
m_layout->removeItem(m_dragSpacer);
m_layout->insertWidget(m_spacerIndex, m_draggedFrame);
if(m_spacerIndex != m_startDragIndex)
emit frameMoved(m_startDragIndex, m_spacerIndex);
m_startDragIndex = m_spacerIndex = -1;
m_draggedFrame = nullptr;
}
});
connect(frameWidget, &AnimationFrameWidget::frameRightClicked, [this, frame, frameWidget]
{
std::for_each(m_frameWidgets.begin(), m_frameWidgets.end(), [](QWidget* w) { w->setStyleSheet(""); });
frameWidget->setStyleSheet("background: #ADD8E6;");
emit frameSelected(frame);
QMenu contextMenu(tr("Frame context"), this);
QAction newFrameAction(tr("New frame"), this);
connect(&newFrameAction, &QAction::triggered, [this](bool){ emit newFrameRequested(); });
QAction removeFrameAction(tr("Remove frame"), this);
//TODO
QAction editFrameAction(tr("Edit frame"), this);
connect(&editFrameAction, &QAction::triggered, [this, frameWidget](bool){ emit editFrameRequested(m_layout->indexOf(frameWidget)); });
contextMenu.addAction(&newFrameAction);
contextMenu.addAction(&removeFrameAction);
contextMenu.addSeparator();
contextMenu.addAction(&editFrameAction);
contextMenu.exec(QCursor::pos());
});
connect(frameWidget, &AnimationFrameWidget::frameDoubleClicked, [this, frameWidget]
{
emit frameDoubleClicked(m_layout->indexOf(frameWidget));
});
return frameWidget;
}
void FramesGallery::setSpritesheet(const QPixmap &spritesheet)
{
m_spritesheet = spritesheet;
}
void FramesGallery::clearGallery()
{
if(m_frameWidgets.size() > 0)
{
std::for_each(m_frameWidgets.begin(), m_frameWidgets.end(), [](AnimationFrameWidget* widget) { widget->deleteLater(); });
m_frameWidgets.clear();
m_layout->removeItem(m_dragSpacer);
}
}
void FramesGallery::mouseReleaseEvent(QMouseEvent *event)
{
if(event->button() == Qt::MouseButton::RightButton)
{
QMenu contextMenu(tr("New frame context"), this);
QAction newFrameAction(tr("New frame"), this);
connect(&newFrameAction, &QAction::triggered, [this](bool){ emit newFrameRequested(); });
contextMenu.addAction(&newFrameAction);
contextMenu.exec(QCursor::pos());
}
}
void FramesGallery::mouseMoveEvent(QMouseEvent *event)
{
if(m_draggedFrame)
{
QPoint subPos = event->pos() - m_startDragPos;
if(m_draggedFrame->pos().x() + subPos.x() >= pos().x() - (m_draggedFrame->size().width() / 2) &&
m_draggedFrame->pos().x() + m_draggedFrame->size().width() + subPos.x() < pos().x() + size().width() + (m_draggedFrame->size().width() / 2))
m_draggedFrame->move(m_draggedFrame->pos().x() + subPos.x(), m_draggedFrame->pos().y());
m_startDragPos = event->pos();
//TODO I believe this can look better
if(m_layout->count() > 1)
{
//When spacer is in middle of frames but not at the beggining and end
if(m_spacerIndex > 0 && m_spacerIndex < m_layout->count() - 1)
{
const auto widgetAfterSpacer = m_layout->itemAt(m_spacerIndex + 1)->widget();
//Handle after spacer
if(m_draggedFrame->pos().x() > widgetAfterSpacer->pos().x())
{
m_layout->removeItem(m_dragSpacer);
m_layout->insertSpacerItem(++m_spacerIndex, m_dragSpacer);
}
const auto widgetBeforeSpacer = m_layout->itemAt(m_spacerIndex - 1)->widget();
//Handle before spacer
if(m_draggedFrame->pos().x() < widgetBeforeSpacer->pos().x())
{
m_layout->removeItem(m_dragSpacer);
m_layout->insertSpacerItem(--m_spacerIndex, m_dragSpacer);
}
}
else if(m_spacerIndex == 0) // Spacer at the beginning
{
const auto widgetAfterSpacer = m_layout->itemAt(m_spacerIndex + 1)->widget();
if(m_draggedFrame->pos().x() > widgetAfterSpacer->pos().x())
{
m_layout->removeItem(m_dragSpacer);
m_layout->insertSpacerItem(++m_spacerIndex, m_dragSpacer);
}
}
else if(m_spacerIndex == m_layout->count() - 1) // Spacer at the end
{
const auto widgetBeforeSpacer = m_layout->itemAt(m_spacerIndex - 1)->widget();
if(m_draggedFrame->pos().x() < widgetBeforeSpacer->pos().x())
{
m_layout->removeItem(m_dragSpacer);
m_layout->insertSpacerItem(--m_spacerIndex, m_dragSpacer);
}
}
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2014 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 <android/log.h>
#include <dlfcn.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
namespace art {
class SignalAction {
public:
SignalAction() : claimed_(false) {
}
// Claim the signal and keep the action specified.
void Claim(const struct sigaction& action) {
action_ = action;
claimed_ = true;
}
// Unclaim the signal and restore the old action.
void Unclaim(int signal) {
claimed_ = false;
sigaction(signal, &action_, NULL); // Restore old action.
}
// Get the action associated with this signal.
const struct sigaction& GetAction() const {
return action_;
}
// Is the signal claimed?
bool IsClaimed() const {
return claimed_;
}
// Change the recorded action to that specified.
void SetAction(const struct sigaction& action) {
action_ = action;
}
private:
struct sigaction action_; // Action to be performed.
bool claimed_; // Whether signal is claimed or not.
};
// User's signal handlers
static SignalAction user_sigactions[_NSIG];
static void log(const char* format, ...) {
char buf[256];
va_list ap;
va_start(ap, format);
vsnprintf(buf, sizeof(buf), format, ap);
__android_log_write(ANDROID_LOG_ERROR, "libsigchain", buf);
va_end(ap);
}
static void CheckSignalValid(int signal) {
if (signal <= 0 || signal >= _NSIG) {
log("Invalid signal %d", signal);
abort();
}
}
// Claim a signal chain for a particular signal.
void ClaimSignalChain(int signal, struct sigaction* oldaction) {
CheckSignalValid(signal);
user_sigactions[signal].Claim(*oldaction);
}
void UnclaimSignalChain(int signal) {
CheckSignalValid(signal);
user_sigactions[signal].Unclaim(signal);
}
// Invoke the user's signal handler.
void InvokeUserSignalHandler(int sig, siginfo_t* info, void* context) {
// Check the arguments.
CheckSignalValid(sig);
// The signal must have been claimed in order to get here. Check it.
if (!user_sigactions[sig].IsClaimed()) {
abort();
}
const struct sigaction& action = user_sigactions[sig].GetAction();
// Only deliver the signal if the signal was not masked out.
if (sigismember(&action.sa_mask, sig)) {
return;
}
if ((action.sa_flags & SA_SIGINFO) == 0) {
if (action.sa_handler != NULL) {
action.sa_handler(sig);
}
} else {
if (action.sa_sigaction != NULL) {
action.sa_sigaction(sig, info, context);
}
}
}
extern "C" {
// These functions are C linkage since they replace the functions in libc.
int sigaction(int signal, const struct sigaction* new_action, struct sigaction* old_action) {
// If this signal has been claimed as a signal chain, record the user's
// action but don't pass it on to the kernel.
// Note that we check that the signal number is in range here. An out of range signal
// number should behave exactly as the libc sigaction.
if (signal > 0 && signal < _NSIG && user_sigactions[signal].IsClaimed()) {
if (old_action != NULL) {
*old_action = user_sigactions[signal].GetAction();
}
if (new_action != NULL) {
user_sigactions[signal].SetAction(*new_action);
}
return 0;
}
// Will only get here if the signal chain has not been claimed. We want
// to pass the sigaction on to the kernel via the real sigaction in libc.
void* linked_sigaction_sym = dlsym(RTLD_NEXT, "sigaction");
if (linked_sigaction_sym == nullptr) {
log("Unable to find next sigaction in signal chain");
abort();
}
typedef int (*SigAction)(int, const struct sigaction*, struct sigaction*);
SigAction linked_sigaction = reinterpret_cast<SigAction>(linked_sigaction_sym);
return linked_sigaction(signal, new_action, old_action);
}
int sigprocmask(int how, const sigset_t* bionic_new_set, sigset_t* bionic_old_set) {
const sigset_t* new_set_ptr = bionic_new_set;
sigset_t tmpset;
if (bionic_new_set != NULL) {
tmpset = *bionic_new_set;
if (how == SIG_BLOCK) {
// Don't allow claimed signals in the mask. If a signal chain has been claimed
// we can't allow the user to block that signal.
for (int i = 0 ; i < _NSIG; ++i) {
if (user_sigactions[i].IsClaimed() && sigismember(&tmpset, i)) {
sigdelset(&tmpset, i);
}
}
}
new_set_ptr = &tmpset;
}
void* linked_sigprocmask_sym = dlsym(RTLD_NEXT, "sigprocmask");
if (linked_sigprocmask_sym == nullptr) {
log("Unable to find next sigprocmask in signal chain");
abort();
}
typedef int (*SigProcMask)(int how, const sigset_t*, sigset_t*);
SigProcMask linked_sigprocmask= reinterpret_cast<SigProcMask>(linked_sigprocmask_sym);
return linked_sigprocmask(how, new_set_ptr, bionic_old_set);
}
} // extern "C"
} // namespace art
<commit_msg>am b796d1bf: Merge "Remove incorrect check for sa_mask in signal chaining"<commit_after>/*
* Copyright (C) 2014 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 <android/log.h>
#include <dlfcn.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
namespace art {
class SignalAction {
public:
SignalAction() : claimed_(false) {
}
// Claim the signal and keep the action specified.
void Claim(const struct sigaction& action) {
action_ = action;
claimed_ = true;
}
// Unclaim the signal and restore the old action.
void Unclaim(int signal) {
claimed_ = false;
sigaction(signal, &action_, NULL); // Restore old action.
}
// Get the action associated with this signal.
const struct sigaction& GetAction() const {
return action_;
}
// Is the signal claimed?
bool IsClaimed() const {
return claimed_;
}
// Change the recorded action to that specified.
void SetAction(const struct sigaction& action) {
action_ = action;
}
private:
struct sigaction action_; // Action to be performed.
bool claimed_; // Whether signal is claimed or not.
};
// User's signal handlers
static SignalAction user_sigactions[_NSIG];
static void log(const char* format, ...) {
char buf[256];
va_list ap;
va_start(ap, format);
vsnprintf(buf, sizeof(buf), format, ap);
__android_log_write(ANDROID_LOG_ERROR, "libsigchain", buf);
va_end(ap);
}
static void CheckSignalValid(int signal) {
if (signal <= 0 || signal >= _NSIG) {
log("Invalid signal %d", signal);
abort();
}
}
// Claim a signal chain for a particular signal.
void ClaimSignalChain(int signal, struct sigaction* oldaction) {
CheckSignalValid(signal);
user_sigactions[signal].Claim(*oldaction);
}
void UnclaimSignalChain(int signal) {
CheckSignalValid(signal);
user_sigactions[signal].Unclaim(signal);
}
// Invoke the user's signal handler.
void InvokeUserSignalHandler(int sig, siginfo_t* info, void* context) {
// Check the arguments.
CheckSignalValid(sig);
// The signal must have been claimed in order to get here. Check it.
if (!user_sigactions[sig].IsClaimed()) {
abort();
}
const struct sigaction& action = user_sigactions[sig].GetAction();
if ((action.sa_flags & SA_SIGINFO) == 0) {
if (action.sa_handler != NULL) {
action.sa_handler(sig);
}
} else {
if (action.sa_sigaction != NULL) {
action.sa_sigaction(sig, info, context);
}
}
}
extern "C" {
// These functions are C linkage since they replace the functions in libc.
int sigaction(int signal, const struct sigaction* new_action, struct sigaction* old_action) {
// If this signal has been claimed as a signal chain, record the user's
// action but don't pass it on to the kernel.
// Note that we check that the signal number is in range here. An out of range signal
// number should behave exactly as the libc sigaction.
if (signal > 0 && signal < _NSIG && user_sigactions[signal].IsClaimed()) {
if (old_action != NULL) {
*old_action = user_sigactions[signal].GetAction();
}
if (new_action != NULL) {
user_sigactions[signal].SetAction(*new_action);
}
return 0;
}
// Will only get here if the signal chain has not been claimed. We want
// to pass the sigaction on to the kernel via the real sigaction in libc.
void* linked_sigaction_sym = dlsym(RTLD_NEXT, "sigaction");
if (linked_sigaction_sym == nullptr) {
log("Unable to find next sigaction in signal chain");
abort();
}
typedef int (*SigAction)(int, const struct sigaction*, struct sigaction*);
SigAction linked_sigaction = reinterpret_cast<SigAction>(linked_sigaction_sym);
return linked_sigaction(signal, new_action, old_action);
}
int sigprocmask(int how, const sigset_t* bionic_new_set, sigset_t* bionic_old_set) {
const sigset_t* new_set_ptr = bionic_new_set;
sigset_t tmpset;
if (bionic_new_set != NULL) {
tmpset = *bionic_new_set;
if (how == SIG_BLOCK) {
// Don't allow claimed signals in the mask. If a signal chain has been claimed
// we can't allow the user to block that signal.
for (int i = 0 ; i < _NSIG; ++i) {
if (user_sigactions[i].IsClaimed() && sigismember(&tmpset, i)) {
sigdelset(&tmpset, i);
}
}
}
new_set_ptr = &tmpset;
}
void* linked_sigprocmask_sym = dlsym(RTLD_NEXT, "sigprocmask");
if (linked_sigprocmask_sym == nullptr) {
log("Unable to find next sigprocmask in signal chain");
abort();
}
typedef int (*SigProcMask)(int how, const sigset_t*, sigset_t*);
SigProcMask linked_sigprocmask= reinterpret_cast<SigProcMask>(linked_sigprocmask_sym);
return linked_sigprocmask(how, new_set_ptr, bionic_old_set);
}
} // extern "C"
} // namespace art
<|endoftext|>
|
<commit_before>#include "serialized_fast_value_attribute.h"
#include "streamed_value_saver.h"
#include <vespa/eval/eval/value.h>
#include <vespa/eval/eval/fast_value.hpp>
#include <vespa/eval/streamed/streamed_value_utils.h>
#include <vespa/fastlib/io/bufferedfile.h>
#include <vespa/searchlib/attribute/readerbase.h>
#include <vespa/searchlib/util/fileutil.h>
#include <vespa/vespalib/util/rcuvector.hpp>
#include <vespa/log/log.h>
LOG_SETUP(".searchlib.tensor.serialized_fast_value_attribute");
#include "blob_sequence_reader.h"
#include "tensor_attribute.hpp"
using namespace vespalib;
using namespace vespalib::eval;
namespace search::tensor {
namespace {
constexpr uint32_t TENSOR_ATTRIBUTE_VERSION = 0;
struct ValueBlock : LabelBlock {
TypedCells cells;
};
class ValueBlockStream {
private:
const StreamedValueStore::DataFromType &_from_type;
LabelBlockStream _label_block_stream;
const char *_cells_ptr;
size_t dsss() const { return _from_type.dense_subspace_size; }
auto cell_type() const { return _from_type.cell_type; }
public:
ValueBlock next_block() {
auto labels = _label_block_stream.next_block();
if (labels) {
TypedCells subspace_cells(_cells_ptr, cell_type(), dsss());
_cells_ptr += CellTypeUtils::mem_size(cell_type(), dsss());
return ValueBlock{labels, subspace_cells};
} else {
TypedCells none(nullptr, cell_type(), 0);
return ValueBlock{labels, none};
}
}
ValueBlockStream(const StreamedValueStore::DataFromType &from_type,
const StreamedValueStore::StreamedValueData &from_store)
: _from_type(from_type),
_label_block_stream(from_store.num_subspaces,
from_store.labels_buffer,
from_type.num_mapped_dimensions),
_cells_ptr((const char *)from_store.cells_ref.data)
{
_label_block_stream.reset();
}
~ValueBlockStream();
};
ValueBlockStream::~ValueBlockStream() = default;
class OnlyFastValueIndex : public Value {
private:
const ValueType &_type;
TypedCells _cells;
FastValueIndex my_index;
public:
OnlyFastValueIndex(const ValueType &type,
const StreamedValueStore::DataFromType &from_type,
const StreamedValueStore::StreamedValueData &from_store)
: _type(type),
_cells(from_store.cells_ref),
my_index(from_type.num_mapped_dimensions,
from_store.num_subspaces)
{
assert(_type.cell_type() == _cells.type);
std::vector<vespalib::stringref> address(from_type.num_mapped_dimensions);
auto block_stream = ValueBlockStream(from_type, from_store);
size_t ss = 0;
while (auto block = block_stream.next_block()) {
size_t idx = my_index.map.add_mapping(block.address);
if (idx != ss) {
LOG(error, "add_mapping returned idx=%zu for subspace %zu", idx, ss);
}
++ss;
}
if (ss != from_store.num_subspaces) {
LOG(error, "expected %zu subspaces but got %zu", from_store.num_subspaces, ss);
abort();
}
}
~OnlyFastValueIndex();
const ValueType &type() const final override { return _type; }
TypedCells cells() const final override { return _cells; }
const Index &index() const final override { return my_index; }
vespalib::MemoryUsage get_memory_usage() const final override {
auto usage = self_memory_usage<OnlyFastValueIndex>();
usage.merge(my_index.map.estimate_extra_memory_usage());
return usage;
}
};
OnlyFastValueIndex::~OnlyFastValueIndex() = default;
}
SerializedFastValueAttribute::SerializedFastValueAttribute(stringref name, const Config &cfg)
: TensorAttribute(name, cfg, _streamedValueStore),
_tensor_type(cfg.tensorType()),
_streamedValueStore(_tensor_type),
_data_from_type(_tensor_type)
{
}
SerializedFastValueAttribute::~SerializedFastValueAttribute()
{
getGenerationHolder().clearHoldLists();
_tensorStore.clearHoldLists();
}
void
SerializedFastValueAttribute::setTensor(DocId docId, const vespalib::eval::Value &tensor)
{
EntryRef ref = _streamedValueStore.store_tensor(tensor);
setTensorRef(docId, ref);
if (!ref.valid()) {
checkTensorType(tensor);
}
}
std::unique_ptr<Value>
SerializedFastValueAttribute::getTensor(DocId docId) const
{
EntryRef ref;
if (docId < getCommittedDocIdLimit()) {
ref = _refVector[docId];
}
if (!ref.valid()) {
return {};
}
if (auto data_from_store = _streamedValueStore.get_tensor_data(ref)) {
return std::make_unique<OnlyFastValueIndex>(_tensor_type,
_data_from_type,
data_from_store);
}
return {};
}
bool
SerializedFastValueAttribute::onLoad()
{
BlobSequenceReader tensorReader(*this);
if (!tensorReader.hasData()) {
return false;
}
setCreateSerialNum(tensorReader.getCreateSerialNum());
assert(tensorReader.getVersion() == TENSOR_ATTRIBUTE_VERSION);
uint32_t numDocs(tensorReader.getDocIdLimit());
_refVector.reset();
_refVector.unsafe_reserve(numDocs);
vespalib::Array<char> buffer(1024);
for (uint32_t lid = 0; lid < numDocs; ++lid) {
uint32_t tensorSize = tensorReader.getNextSize();
if (tensorSize != 0) {
if (tensorSize > buffer.size()) {
buffer.resize(tensorSize + 1024);
}
tensorReader.readBlob(&buffer[0], tensorSize);
vespalib::nbostream source(&buffer[0], tensorSize);
EntryRef ref = _streamedValueStore.store_encoded_tensor(source);
_refVector.push_back(ref);
} else {
EntryRef invalid;
_refVector.push_back(invalid);
}
}
setNumDocs(numDocs);
setCommittedDocIdLimit(numDocs);
return true;
}
std::unique_ptr<AttributeSaver>
SerializedFastValueAttribute::onInitSave(vespalib::stringref fileName)
{
vespalib::GenerationHandler::Guard guard(getGenerationHandler().
takeGuard());
return std::make_unique<StreamedValueSaver>
(std::move(guard),
this->createAttributeHeader(fileName),
getRefCopy(),
_streamedValueStore);
}
void
SerializedFastValueAttribute::compactWorst()
{
doCompactWorst<StreamedValueStore::RefType>();
}
}
<commit_msg>more consistent version checking<commit_after>#include "serialized_fast_value_attribute.h"
#include "streamed_value_saver.h"
#include <vespa/eval/eval/value.h>
#include <vespa/eval/eval/fast_value.hpp>
#include <vespa/eval/streamed/streamed_value_utils.h>
#include <vespa/fastlib/io/bufferedfile.h>
#include <vespa/searchlib/attribute/readerbase.h>
#include <vespa/searchlib/util/fileutil.h>
#include <vespa/vespalib/util/rcuvector.hpp>
#include <vespa/log/log.h>
LOG_SETUP(".searchlib.tensor.serialized_fast_value_attribute");
#include "blob_sequence_reader.h"
#include "tensor_attribute.hpp"
using namespace vespalib;
using namespace vespalib::eval;
namespace search::tensor {
namespace {
struct ValueBlock : LabelBlock {
TypedCells cells;
};
class ValueBlockStream {
private:
const StreamedValueStore::DataFromType &_from_type;
LabelBlockStream _label_block_stream;
const char *_cells_ptr;
size_t dsss() const { return _from_type.dense_subspace_size; }
auto cell_type() const { return _from_type.cell_type; }
public:
ValueBlock next_block() {
auto labels = _label_block_stream.next_block();
if (labels) {
TypedCells subspace_cells(_cells_ptr, cell_type(), dsss());
_cells_ptr += CellTypeUtils::mem_size(cell_type(), dsss());
return ValueBlock{labels, subspace_cells};
} else {
TypedCells none(nullptr, cell_type(), 0);
return ValueBlock{labels, none};
}
}
ValueBlockStream(const StreamedValueStore::DataFromType &from_type,
const StreamedValueStore::StreamedValueData &from_store)
: _from_type(from_type),
_label_block_stream(from_store.num_subspaces,
from_store.labels_buffer,
from_type.num_mapped_dimensions),
_cells_ptr((const char *)from_store.cells_ref.data)
{
_label_block_stream.reset();
}
~ValueBlockStream();
};
ValueBlockStream::~ValueBlockStream() = default;
class OnlyFastValueIndex : public Value {
private:
const ValueType &_type;
TypedCells _cells;
FastValueIndex my_index;
public:
OnlyFastValueIndex(const ValueType &type,
const StreamedValueStore::DataFromType &from_type,
const StreamedValueStore::StreamedValueData &from_store)
: _type(type),
_cells(from_store.cells_ref),
my_index(from_type.num_mapped_dimensions,
from_store.num_subspaces)
{
assert(_type.cell_type() == _cells.type);
std::vector<vespalib::stringref> address(from_type.num_mapped_dimensions);
auto block_stream = ValueBlockStream(from_type, from_store);
size_t ss = 0;
while (auto block = block_stream.next_block()) {
size_t idx = my_index.map.add_mapping(block.address);
if (idx != ss) {
LOG(error, "add_mapping returned idx=%zu for subspace %zu", idx, ss);
}
++ss;
}
if (ss != from_store.num_subspaces) {
LOG(error, "expected %zu subspaces but got %zu", from_store.num_subspaces, ss);
abort();
}
}
~OnlyFastValueIndex();
const ValueType &type() const final override { return _type; }
TypedCells cells() const final override { return _cells; }
const Index &index() const final override { return my_index; }
vespalib::MemoryUsage get_memory_usage() const final override {
auto usage = self_memory_usage<OnlyFastValueIndex>();
usage.merge(my_index.map.estimate_extra_memory_usage());
return usage;
}
};
OnlyFastValueIndex::~OnlyFastValueIndex() = default;
}
SerializedFastValueAttribute::SerializedFastValueAttribute(stringref name, const Config &cfg)
: TensorAttribute(name, cfg, _streamedValueStore),
_tensor_type(cfg.tensorType()),
_streamedValueStore(_tensor_type),
_data_from_type(_tensor_type)
{
}
SerializedFastValueAttribute::~SerializedFastValueAttribute()
{
getGenerationHolder().clearHoldLists();
_tensorStore.clearHoldLists();
}
void
SerializedFastValueAttribute::setTensor(DocId docId, const vespalib::eval::Value &tensor)
{
EntryRef ref = _streamedValueStore.store_tensor(tensor);
setTensorRef(docId, ref);
if (!ref.valid()) {
checkTensorType(tensor);
}
}
std::unique_ptr<Value>
SerializedFastValueAttribute::getTensor(DocId docId) const
{
EntryRef ref;
if (docId < getCommittedDocIdLimit()) {
ref = _refVector[docId];
}
if (!ref.valid()) {
return {};
}
if (auto data_from_store = _streamedValueStore.get_tensor_data(ref)) {
return std::make_unique<OnlyFastValueIndex>(_tensor_type,
_data_from_type,
data_from_store);
}
return {};
}
bool
SerializedFastValueAttribute::onLoad()
{
BlobSequenceReader tensorReader(*this);
if (!tensorReader.hasData()) {
return false;
}
setCreateSerialNum(tensorReader.getCreateSerialNum());
assert(tensorReader.getVersion() == getVersion());
uint32_t numDocs(tensorReader.getDocIdLimit());
_refVector.reset();
_refVector.unsafe_reserve(numDocs);
vespalib::Array<char> buffer(1024);
for (uint32_t lid = 0; lid < numDocs; ++lid) {
uint32_t tensorSize = tensorReader.getNextSize();
if (tensorSize != 0) {
if (tensorSize > buffer.size()) {
buffer.resize(tensorSize + 1024);
}
tensorReader.readBlob(&buffer[0], tensorSize);
vespalib::nbostream source(&buffer[0], tensorSize);
EntryRef ref = _streamedValueStore.store_encoded_tensor(source);
_refVector.push_back(ref);
} else {
EntryRef invalid;
_refVector.push_back(invalid);
}
}
setNumDocs(numDocs);
setCommittedDocIdLimit(numDocs);
return true;
}
std::unique_ptr<AttributeSaver>
SerializedFastValueAttribute::onInitSave(vespalib::stringref fileName)
{
vespalib::GenerationHandler::Guard guard(getGenerationHandler().
takeGuard());
return std::make_unique<StreamedValueSaver>
(std::move(guard),
this->createAttributeHeader(fileName),
getRefCopy(),
_streamedValueStore);
}
void
SerializedFastValueAttribute::compactWorst()
{
doCompactWorst<StreamedValueStore::RefType>();
}
}
<|endoftext|>
|
<commit_before>#include <string>
#include <stdio.h>
#include "stdlib.h"
#include "dag.h"
#include "engine.h"
#include "failure.h"
void diamond_dag() {
DAG dag("test/diamond.dag");
Engine engine(dag);
if (!engine.has_ready_task()) {
myfailure("Did not queue root tasks");
}
Task *a = engine.next_ready_task();
if (a->name.compare("A") != 0) {
myfailure("Queued non root task %s", a->name.c_str());
}
if (engine.has_ready_task()) {
myfailure("Queued non-root tasks");
}
engine.mark_task_finished(a, 0);
if (!engine.has_ready_task()) {
myfailure("Marking did not release tasks");
}
Task *bc = engine.next_ready_task();
if (!engine.has_ready_task()) {
myfailure("Marking did not release tasks");
}
Task *cb = engine.next_ready_task();
if (engine.has_ready_task()) {
myfailure("Marking released too many tasks");
}
if (bc->name.compare("B") != 0 && bc->name.compare("C") != 0) {
myfailure("Wrong task released: %s", bc->name.c_str());
}
if (cb->name.compare("B") != 0 && cb->name.compare("C") != 0) {
myfailure("Wrong task released: %s", cb->name.c_str());
}
engine.mark_task_finished(bc, 0);
if (engine.has_ready_task()) {
myfailure("Marking released a task when it shouldn't");
}
engine.mark_task_finished(cb, 0);
if (!engine.has_ready_task()) {
myfailure("Marking all parents did not release task D");
}
Task *d = engine.next_ready_task();
if (d->name.compare("D") != 0) {
myfailure("Not task D");
}
if (engine.has_ready_task()) {
myfailure("No more tasks are available");
}
if (engine.is_finished()) {
myfailure("DAG is not finished");
}
engine.mark_task_finished(d, 0);
if (!engine.is_finished()) {
myfailure("DAG is finished");
}
}
void diamond_dag_rescue() {
DAG dag("test/diamond.dag","test/diamond.rescue");
Engine engine(dag);
if (!engine.has_ready_task()) {
myfailure("Should have ready D task");
}
Task *d = engine.next_ready_task();
if (d->name.compare("D") != 0) {
myfailure("Ready task is not D");
}
engine.mark_task_finished(d, 1);
if (engine.has_ready_task()) {
myfailure("Ready tasks even though D failed");
}
if (!engine.is_finished()) {
myfailure("DAG should have been finished after D failed");
}
if (!engine.is_failed()) {
myfailure("DAG should be failed");
}
}
void diamond_dag_failure() {
DAG dag("test/diamond.dag");
Engine engine(dag);
if (!engine.has_ready_task()) {
myfailure("Did not queue root tasks");
}
Task *a = engine.next_ready_task();
if (a->name.compare("A") != 0) {
myfailure("Queued non root task %s", a->name.c_str());
}
if (engine.has_ready_task()) {
myfailure("Queued non-root tasks");
}
engine.mark_task_finished(a, 1);
if (engine.has_ready_task()) {
myfailure("Released tasks even though parent failed");
}
if (!engine.is_finished()) {
myfailure("DAG should have been finished after A failed");
}
}
void read_file(char *fname, char *buf) {
FILE *f = fopen(fname, "r");
int read = fread(buf, 1, 1024, f);
buf[read] = '\0';
fclose(f);
}
void diamond_dag_newrescue() {
char temp[1024];
sprintf(temp,"file_XXXXXX");
mkstemp(temp);
DAG dag("test/diamond.dag");
Engine engine(dag, temp);
Task *a = engine.next_ready_task();
engine.mark_task_finished(a, 0);
Task *bc = engine.next_ready_task();
engine.mark_task_finished(bc, 0);
Task *cb = engine.next_ready_task();
engine.mark_task_finished(cb, 0);
Task *d = engine.next_ready_task();
engine.mark_task_finished(d, 1);
if (!engine.is_finished()) {
myfailure("DAG should be finished");
}
if (!engine.is_failed()) {
myfailure("DAG should be failed");
}
char buf[1024];
read_file(temp, buf);
if (strcmp(buf, "\nDONE A\nDONE B\nDONE C") != 0) {
myfailure("Rescue file not updated properly: %s", temp);
} else {
unlink(temp);
}
}
void diamond_dag_oldrescue() {
char temp[1024];
sprintf(temp, "file_XXXXXX");
mkstemp(temp);
DAG dag("test/diamond.dag", "test/diamond.rescue");
Engine engine(dag, temp);
if (!engine.has_ready_task()) {
myfailure("Should have ready D task");
}
Task *d = engine.next_ready_task();
if (d->name.compare("D") != 0) {
myfailure("Ready task is not D");
}
engine.mark_task_finished(d, 0);
if (engine.has_ready_task()) {
myfailure("Ready tasks even though D finished");
}
if (!engine.is_finished()) {
myfailure("DAG should have been finished after D finished");
}
if (engine.is_failed()) {
myfailure("DAG should not be failed");
}
char buf[1024];
read_file(temp, buf);
if (strcmp(buf, "\nDONE A\nDONE B\nDONE C\nDONE D") != 0) {
myfailure("Rescue file not updated properly: %s: %s", temp, buf);
} else {
unlink(temp);
}
}
void diamond_dag_max_failures() {
DAG dag("test/diamond.dag");
Engine engine(dag, "", 1);
if (!engine.has_ready_task()) {
myfailure("Did not queue root tasks");
}
Task *a = engine.next_ready_task();
if (a->name.compare("A") != 0) {
myfailure("Queued non root task %s", a->name.c_str());
}
if (engine.has_ready_task()) {
myfailure("Queued non-root tasks");
}
engine.mark_task_finished(a, 0);
Task *bc = engine.next_ready_task();
engine.mark_task_finished(bc, 1);
if (engine.has_ready_task()) {
myfailure("DAG should not have a ready task because %s failed", bc->name.c_str());
}
}
void diamond_dag_retries() {
int tries = 3;
DAG dag("test/diamond.dag");
Engine engine(dag, "", 0, tries);
Task *a;
for (int i=0; i<tries; i++) {
if (!engine.has_ready_task()) {
myfailure("A should have been ready");
}
a = engine.next_ready_task();
if (a->name.compare("A") != 0) {
myfailure("A should have been ready");
}
engine.mark_task_finished(a, 1);
}
if (engine.has_ready_task()) {
myfailure("DAG should not have a ready task because A failed");
}
}
void diamond_dag_retries2() {
int tries = 3;
DAG dag("test/diamond.dag");
Engine engine(dag, "", 0, tries);
Task *a;
for (int i=0; i<tries-1; i++) {
if (!engine.has_ready_task()) {
myfailure("A should have been ready");
}
a = engine.next_ready_task();
if (a->name.compare("A") != 0) {
myfailure("A should have been ready");
}
engine.mark_task_finished(a, 1);
}
if (!engine.has_ready_task()) {
myfailure("A should have been ready");
}
a = engine.next_ready_task();
if (a->name.compare("A") != 0) {
myfailure("A should have been ready");
}
engine.mark_task_finished(a, 0);
if (!engine.has_ready_task()) {
myfailure("DAG should have a ready task because A finally succeeded");
}
Task *bc = engine.next_ready_task();
if (bc->name.compare("B")!=0 && bc->name.compare("C")!=0) {
myfailure("B or C should have been ready");
}
}
int main(int argc, char *argv[]) {
diamond_dag();
diamond_dag_failure();
diamond_dag_max_failures();
diamond_dag_retries();
diamond_dag_retries2();
diamond_dag_oldrescue();
diamond_dag_newrescue();
diamond_dag_rescue();
return 0;
}
<commit_msg>PMC: Add unistd.h to test-engine.cpp<commit_after>#include <string>
#include <stdio.h>
#include <unistd.h>
#include "stdlib.h"
#include "dag.h"
#include "engine.h"
#include "failure.h"
void diamond_dag() {
DAG dag("test/diamond.dag");
Engine engine(dag);
if (!engine.has_ready_task()) {
myfailure("Did not queue root tasks");
}
Task *a = engine.next_ready_task();
if (a->name.compare("A") != 0) {
myfailure("Queued non root task %s", a->name.c_str());
}
if (engine.has_ready_task()) {
myfailure("Queued non-root tasks");
}
engine.mark_task_finished(a, 0);
if (!engine.has_ready_task()) {
myfailure("Marking did not release tasks");
}
Task *bc = engine.next_ready_task();
if (!engine.has_ready_task()) {
myfailure("Marking did not release tasks");
}
Task *cb = engine.next_ready_task();
if (engine.has_ready_task()) {
myfailure("Marking released too many tasks");
}
if (bc->name.compare("B") != 0 && bc->name.compare("C") != 0) {
myfailure("Wrong task released: %s", bc->name.c_str());
}
if (cb->name.compare("B") != 0 && cb->name.compare("C") != 0) {
myfailure("Wrong task released: %s", cb->name.c_str());
}
engine.mark_task_finished(bc, 0);
if (engine.has_ready_task()) {
myfailure("Marking released a task when it shouldn't");
}
engine.mark_task_finished(cb, 0);
if (!engine.has_ready_task()) {
myfailure("Marking all parents did not release task D");
}
Task *d = engine.next_ready_task();
if (d->name.compare("D") != 0) {
myfailure("Not task D");
}
if (engine.has_ready_task()) {
myfailure("No more tasks are available");
}
if (engine.is_finished()) {
myfailure("DAG is not finished");
}
engine.mark_task_finished(d, 0);
if (!engine.is_finished()) {
myfailure("DAG is finished");
}
}
void diamond_dag_rescue() {
DAG dag("test/diamond.dag","test/diamond.rescue");
Engine engine(dag);
if (!engine.has_ready_task()) {
myfailure("Should have ready D task");
}
Task *d = engine.next_ready_task();
if (d->name.compare("D") != 0) {
myfailure("Ready task is not D");
}
engine.mark_task_finished(d, 1);
if (engine.has_ready_task()) {
myfailure("Ready tasks even though D failed");
}
if (!engine.is_finished()) {
myfailure("DAG should have been finished after D failed");
}
if (!engine.is_failed()) {
myfailure("DAG should be failed");
}
}
void diamond_dag_failure() {
DAG dag("test/diamond.dag");
Engine engine(dag);
if (!engine.has_ready_task()) {
myfailure("Did not queue root tasks");
}
Task *a = engine.next_ready_task();
if (a->name.compare("A") != 0) {
myfailure("Queued non root task %s", a->name.c_str());
}
if (engine.has_ready_task()) {
myfailure("Queued non-root tasks");
}
engine.mark_task_finished(a, 1);
if (engine.has_ready_task()) {
myfailure("Released tasks even though parent failed");
}
if (!engine.is_finished()) {
myfailure("DAG should have been finished after A failed");
}
}
void read_file(char *fname, char *buf) {
FILE *f = fopen(fname, "r");
int read = fread(buf, 1, 1024, f);
buf[read] = '\0';
fclose(f);
}
void diamond_dag_newrescue() {
char temp[1024];
sprintf(temp,"file_XXXXXX");
mkstemp(temp);
DAG dag("test/diamond.dag");
Engine engine(dag, temp);
Task *a = engine.next_ready_task();
engine.mark_task_finished(a, 0);
Task *bc = engine.next_ready_task();
engine.mark_task_finished(bc, 0);
Task *cb = engine.next_ready_task();
engine.mark_task_finished(cb, 0);
Task *d = engine.next_ready_task();
engine.mark_task_finished(d, 1);
if (!engine.is_finished()) {
myfailure("DAG should be finished");
}
if (!engine.is_failed()) {
myfailure("DAG should be failed");
}
char buf[1024];
read_file(temp, buf);
if (strcmp(buf, "\nDONE A\nDONE B\nDONE C") != 0) {
myfailure("Rescue file not updated properly: %s", temp);
} else {
unlink(temp);
}
}
void diamond_dag_oldrescue() {
char temp[1024];
sprintf(temp, "file_XXXXXX");
mkstemp(temp);
DAG dag("test/diamond.dag", "test/diamond.rescue");
Engine engine(dag, temp);
if (!engine.has_ready_task()) {
myfailure("Should have ready D task");
}
Task *d = engine.next_ready_task();
if (d->name.compare("D") != 0) {
myfailure("Ready task is not D");
}
engine.mark_task_finished(d, 0);
if (engine.has_ready_task()) {
myfailure("Ready tasks even though D finished");
}
if (!engine.is_finished()) {
myfailure("DAG should have been finished after D finished");
}
if (engine.is_failed()) {
myfailure("DAG should not be failed");
}
char buf[1024];
read_file(temp, buf);
if (strcmp(buf, "\nDONE A\nDONE B\nDONE C\nDONE D") != 0) {
myfailure("Rescue file not updated properly: %s: %s", temp, buf);
} else {
unlink(temp);
}
}
void diamond_dag_max_failures() {
DAG dag("test/diamond.dag");
Engine engine(dag, "", 1);
if (!engine.has_ready_task()) {
myfailure("Did not queue root tasks");
}
Task *a = engine.next_ready_task();
if (a->name.compare("A") != 0) {
myfailure("Queued non root task %s", a->name.c_str());
}
if (engine.has_ready_task()) {
myfailure("Queued non-root tasks");
}
engine.mark_task_finished(a, 0);
Task *bc = engine.next_ready_task();
engine.mark_task_finished(bc, 1);
if (engine.has_ready_task()) {
myfailure("DAG should not have a ready task because %s failed", bc->name.c_str());
}
}
void diamond_dag_retries() {
int tries = 3;
DAG dag("test/diamond.dag");
Engine engine(dag, "", 0, tries);
Task *a;
for (int i=0; i<tries; i++) {
if (!engine.has_ready_task()) {
myfailure("A should have been ready");
}
a = engine.next_ready_task();
if (a->name.compare("A") != 0) {
myfailure("A should have been ready");
}
engine.mark_task_finished(a, 1);
}
if (engine.has_ready_task()) {
myfailure("DAG should not have a ready task because A failed");
}
}
void diamond_dag_retries2() {
int tries = 3;
DAG dag("test/diamond.dag");
Engine engine(dag, "", 0, tries);
Task *a;
for (int i=0; i<tries-1; i++) {
if (!engine.has_ready_task()) {
myfailure("A should have been ready");
}
a = engine.next_ready_task();
if (a->name.compare("A") != 0) {
myfailure("A should have been ready");
}
engine.mark_task_finished(a, 1);
}
if (!engine.has_ready_task()) {
myfailure("A should have been ready");
}
a = engine.next_ready_task();
if (a->name.compare("A") != 0) {
myfailure("A should have been ready");
}
engine.mark_task_finished(a, 0);
if (!engine.has_ready_task()) {
myfailure("DAG should have a ready task because A finally succeeded");
}
Task *bc = engine.next_ready_task();
if (bc->name.compare("B")!=0 && bc->name.compare("C")!=0) {
myfailure("B or C should have been ready");
}
}
int main(int argc, char *argv[]) {
diamond_dag();
diamond_dag_failure();
diamond_dag_max_failures();
diamond_dag_retries();
diamond_dag_retries2();
diamond_dag_oldrescue();
diamond_dag_newrescue();
diamond_dag_rescue();
return 0;
}
<|endoftext|>
|
<commit_before>//===-- GDBRemoteCommunicationReplayServer.cpp ------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <errno.h>
#include "lldb/Host/Config.h"
#include "GDBRemoteCommunicationReplayServer.h"
#include "ProcessGDBRemoteLog.h"
// C Includes
// C++ Includes
#include <cstring>
// Project includes
#include "lldb/Host/ThreadLauncher.h"
#include "lldb/Utility/ConstString.h"
#include "lldb/Utility/Event.h"
#include "lldb/Utility/FileSpec.h"
#include "lldb/Utility/StreamString.h"
#include "lldb/Utility/StringExtractorGDBRemote.h"
using namespace llvm;
using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::process_gdb_remote;
static bool unexpected(llvm::StringRef expected, llvm::StringRef actual) {
// The 'expected' string contains the raw data, including the leading $ and
// trailing checksum. The 'actual' string contains only the packet's content.
if (expected.contains(actual))
return false;
if (expected == "+" || actual == "+")
return false;
// Contains a PID which might be different.
if (expected.contains("vAttach"))
return false;
// Contains a ascii-hex-path.
if (expected.contains("QSetSTD"))
return false;
// Contains environment values.
if (expected.contains("QEnvironment"))
return false;
return true;
}
GDBRemoteCommunicationReplayServer::GDBRemoteCommunicationReplayServer()
: GDBRemoteCommunication("gdb-remote.server",
"gdb-remote.server.rx_packet"),
m_async_broadcaster(nullptr, "lldb.gdb-remote.server.async-broadcaster"),
m_async_listener_sp(
Listener::MakeListener("lldb.gdb-remote.server.async-listener")),
m_async_thread_state_mutex(), m_skip_acks(false) {
m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
"async thread continue");
m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
"async thread should exit");
const uint32_t async_event_mask =
eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
m_async_listener_sp->StartListeningForEvents(&m_async_broadcaster,
async_event_mask);
}
GDBRemoteCommunicationReplayServer::~GDBRemoteCommunicationReplayServer() {
StopAsyncThread();
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationReplayServer::GetPacketAndSendResponse(
Timeout<std::micro> timeout, Status &error, bool &interrupt, bool &quit) {
std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
StringExtractorGDBRemote packet;
PacketResult packet_result = WaitForPacketNoLock(packet, timeout, false);
if (packet_result != PacketResult::Success) {
if (!IsConnected()) {
error.SetErrorString("lost connection");
quit = true;
} else {
error.SetErrorString("timeout");
}
return packet_result;
}
m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue);
if (m_skip_acks) {
const StringExtractorGDBRemote::ServerPacketType packet_type =
packet.GetServerPacketType();
switch (packet_type) {
case StringExtractorGDBRemote::eServerPacketType_nack:
case StringExtractorGDBRemote::eServerPacketType_ack:
return PacketResult::Success;
default:
break;
}
} else if (packet.GetStringRef() == "QStartNoAckMode") {
m_skip_acks = true;
m_send_acks = false;
}
// A QEnvironment packet is sent for every environment variable. If the
// number of environment variables is different during replay, the replies
// become out of sync.
if (packet.GetStringRef().find("QEnvironment") == 0) {
return SendRawPacketNoLock("$OK#9a", true);
}
Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
while (!m_packet_history.empty()) {
// Pop last packet from the history.
GDBRemoteCommunicationHistory::Entry entry = m_packet_history.back();
m_packet_history.pop_back();
if (entry.type == GDBRemoteCommunicationHistory::ePacketTypeSend) {
if (unexpected(entry.packet.data, packet.GetStringRef())) {
LLDB_LOG(log,
"GDBRemoteCommunicationReplayServer expected packet: '{0}'",
entry.packet.data);
LLDB_LOG(log,
"GDBRemoteCommunicationReplayServer actual packet: '{0}'",
packet.GetStringRef());
}
// Ignore QEnvironment packets as they're handled earlier.
if (entry.packet.data.find("QEnvironment") == 1) {
assert(m_packet_history.back().type ==
GDBRemoteCommunicationHistory::ePacketTypeRecv);
m_packet_history.pop_back();
}
continue;
}
if (entry.type == GDBRemoteCommunicationHistory::ePacketTypeInvalid) {
LLDB_LOG(
log,
"GDBRemoteCommunicationReplayServer skipped invalid packet: '{0}'",
packet.GetStringRef());
continue;
}
return SendRawPacketNoLock(entry.packet.data, true);
}
quit = true;
return packet_result;
}
LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(
std::vector<
lldb_private::process_gdb_remote::GDBRemoteCommunicationHistory::Entry>)
llvm::Error
GDBRemoteCommunicationReplayServer::LoadReplayHistory(const FileSpec &path) {
auto error_or_file = MemoryBuffer::getFile(path.GetPath());
if (auto err = error_or_file.getError())
return errorCodeToError(err);
yaml::Input yin((*error_or_file)->getBuffer());
yin >> m_packet_history;
if (auto err = yin.error())
return errorCodeToError(err);
// We want to manipulate the vector like a stack so we need to reverse the
// order of the packets to have the oldest on at the back.
std::reverse(m_packet_history.begin(), m_packet_history.end());
return Error::success();
}
bool GDBRemoteCommunicationReplayServer::StartAsyncThread() {
std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
if (!m_async_thread.IsJoinable()) {
// Create a thread that watches our internal state and controls which
// events make it to clients (into the DCProcess event queue).
m_async_thread = ThreadLauncher::LaunchThread(
"<lldb.gdb-remote.server.async>",
GDBRemoteCommunicationReplayServer::AsyncThread, this, nullptr);
}
// Wait for handshake.
m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue);
return m_async_thread.IsJoinable();
}
void GDBRemoteCommunicationReplayServer::StopAsyncThread() {
std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
if (!m_async_thread.IsJoinable())
return;
// Request thread to stop.
m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
// Disconnect client.
Disconnect();
// Stop the thread.
m_async_thread.Join(nullptr);
m_async_thread.Reset();
}
void GDBRemoteCommunicationReplayServer::ReceivePacket(
GDBRemoteCommunicationReplayServer &server, bool &done) {
Status error;
bool interrupt;
auto packet_result = server.GetPacketAndSendResponse(std::chrono::seconds(1),
error, interrupt, done);
if (packet_result != GDBRemoteCommunication::PacketResult::Success &&
packet_result !=
GDBRemoteCommunication::PacketResult::ErrorReplyTimeout) {
done = true;
} else {
server.m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue);
}
}
thread_result_t GDBRemoteCommunicationReplayServer::AsyncThread(void *arg) {
GDBRemoteCommunicationReplayServer *server =
(GDBRemoteCommunicationReplayServer *)arg;
EventSP event_sp;
bool done = false;
while (true) {
if (server->m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
const uint32_t event_type = event_sp->GetType();
if (event_sp->BroadcasterIs(&server->m_async_broadcaster)) {
switch (event_type) {
case eBroadcastBitAsyncContinue:
ReceivePacket(*server, done);
if (done)
return {};
break;
case eBroadcastBitAsyncThreadShouldExit:
default:
return {};
}
}
}
}
return {};
}
<commit_msg>[Reproducers] Fix GDB remote flakiness during replay<commit_after>//===-- GDBRemoteCommunicationReplayServer.cpp ------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <errno.h>
#include "lldb/Host/Config.h"
#include "GDBRemoteCommunicationReplayServer.h"
#include "ProcessGDBRemoteLog.h"
// C Includes
// C++ Includes
#include <cstring>
// Project includes
#include "lldb/Host/ThreadLauncher.h"
#include "lldb/Utility/ConstString.h"
#include "lldb/Utility/Event.h"
#include "lldb/Utility/FileSpec.h"
#include "lldb/Utility/StreamString.h"
#include "lldb/Utility/StringExtractorGDBRemote.h"
using namespace llvm;
using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::process_gdb_remote;
static bool unexpected(llvm::StringRef expected, llvm::StringRef actual) {
// The 'expected' string contains the raw data, including the leading $ and
// trailing checksum. The 'actual' string contains only the packet's content.
if (expected.contains(actual))
return false;
// Contains a PID which might be different.
if (expected.contains("vAttach"))
return false;
// Contains a ascii-hex-path.
if (expected.contains("QSetSTD"))
return false;
// Contains environment values.
if (expected.contains("QEnvironment"))
return false;
return true;
}
GDBRemoteCommunicationReplayServer::GDBRemoteCommunicationReplayServer()
: GDBRemoteCommunication("gdb-replay", "gdb-replay.rx_packet"),
m_async_broadcaster(nullptr, "lldb.gdb-replay.async-broadcaster"),
m_async_listener_sp(
Listener::MakeListener("lldb.gdb-replay.async-listener")),
m_async_thread_state_mutex(), m_skip_acks(false) {
m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
"async thread continue");
m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
"async thread should exit");
const uint32_t async_event_mask =
eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
m_async_listener_sp->StartListeningForEvents(&m_async_broadcaster,
async_event_mask);
}
GDBRemoteCommunicationReplayServer::~GDBRemoteCommunicationReplayServer() {
StopAsyncThread();
}
GDBRemoteCommunication::PacketResult
GDBRemoteCommunicationReplayServer::GetPacketAndSendResponse(
Timeout<std::micro> timeout, Status &error, bool &interrupt, bool &quit) {
std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
StringExtractorGDBRemote packet;
PacketResult packet_result = WaitForPacketNoLock(packet, timeout, false);
if (packet_result != PacketResult::Success) {
if (!IsConnected()) {
error.SetErrorString("lost connection");
quit = true;
} else {
error.SetErrorString("timeout");
}
return packet_result;
}
m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue);
// If m_send_acks is true, we're before the handshake phase. We've already
// acknowledge the '+' packet so we're done here.
if (m_send_acks && packet.GetStringRef() == "+")
return PacketResult::Success;
// This completes the handshake. Since m_send_acks was true, we can unset it
// already.
if (packet.GetStringRef() == "QStartNoAckMode")
m_send_acks = false;
// A QEnvironment packet is sent for every environment variable. If the
// number of environment variables is different during replay, the replies
// become out of sync.
if (packet.GetStringRef().find("QEnvironment") == 0) {
return SendRawPacketNoLock("$OK#9a");
}
Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
while (!m_packet_history.empty()) {
// Pop last packet from the history.
GDBRemoteCommunicationHistory::Entry entry = m_packet_history.back();
m_packet_history.pop_back();
// We're handled the handshake implicitly before. Skip the packet and move
// on.
if (entry.packet.data == "+")
continue;
if (entry.type == GDBRemoteCommunicationHistory::ePacketTypeSend) {
if (unexpected(entry.packet.data, packet.GetStringRef())) {
LLDB_LOG(log,
"GDBRemoteCommunicationReplayServer expected packet: '{0}'",
entry.packet.data);
LLDB_LOG(log, "GDBRemoteCommunicationReplayServer actual packet: '{0}'",
packet.GetStringRef());
}
// Ignore QEnvironment packets as they're handled earlier.
if (entry.packet.data.find("QEnvironment") == 1) {
assert(m_packet_history.back().type ==
GDBRemoteCommunicationHistory::ePacketTypeRecv);
m_packet_history.pop_back();
}
continue;
}
if (entry.type == GDBRemoteCommunicationHistory::ePacketTypeInvalid) {
LLDB_LOG(
log,
"GDBRemoteCommunicationReplayServer skipped invalid packet: '{0}'",
packet.GetStringRef());
continue;
}
LLDB_LOG(log,
"GDBRemoteCommunicationReplayServer replied to '{0}' with '{1}'",
packet.GetStringRef(), entry.packet.data);
return SendRawPacketNoLock(entry.packet.data);
}
quit = true;
return packet_result;
}
LLVM_YAML_IS_DOCUMENT_LIST_VECTOR(
std::vector<
lldb_private::process_gdb_remote::GDBRemoteCommunicationHistory::Entry>)
llvm::Error
GDBRemoteCommunicationReplayServer::LoadReplayHistory(const FileSpec &path) {
auto error_or_file = MemoryBuffer::getFile(path.GetPath());
if (auto err = error_or_file.getError())
return errorCodeToError(err);
yaml::Input yin((*error_or_file)->getBuffer());
yin >> m_packet_history;
if (auto err = yin.error())
return errorCodeToError(err);
// We want to manipulate the vector like a stack so we need to reverse the
// order of the packets to have the oldest on at the back.
std::reverse(m_packet_history.begin(), m_packet_history.end());
return Error::success();
}
bool GDBRemoteCommunicationReplayServer::StartAsyncThread() {
std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
if (!m_async_thread.IsJoinable()) {
// Create a thread that watches our internal state and controls which
// events make it to clients (into the DCProcess event queue).
m_async_thread = ThreadLauncher::LaunchThread(
"<lldb.gdb-replay.async>",
GDBRemoteCommunicationReplayServer::AsyncThread, this, nullptr);
}
// Wait for handshake.
m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue);
return m_async_thread.IsJoinable();
}
void GDBRemoteCommunicationReplayServer::StopAsyncThread() {
std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
if (!m_async_thread.IsJoinable())
return;
// Request thread to stop.
m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
// Disconnect client.
Disconnect();
// Stop the thread.
m_async_thread.Join(nullptr);
m_async_thread.Reset();
}
void GDBRemoteCommunicationReplayServer::ReceivePacket(
GDBRemoteCommunicationReplayServer &server, bool &done) {
Status error;
bool interrupt;
auto packet_result = server.GetPacketAndSendResponse(std::chrono::seconds(1),
error, interrupt, done);
if (packet_result != GDBRemoteCommunication::PacketResult::Success &&
packet_result !=
GDBRemoteCommunication::PacketResult::ErrorReplyTimeout) {
done = true;
} else {
server.m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue);
}
}
thread_result_t GDBRemoteCommunicationReplayServer::AsyncThread(void *arg) {
GDBRemoteCommunicationReplayServer *server =
(GDBRemoteCommunicationReplayServer *)arg;
EventSP event_sp;
bool done = false;
while (true) {
if (server->m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
const uint32_t event_type = event_sp->GetType();
if (event_sp->BroadcasterIs(&server->m_async_broadcaster)) {
switch (event_type) {
case eBroadcastBitAsyncContinue:
ReceivePacket(*server, done);
if (done)
return {};
break;
case eBroadcastBitAsyncThreadShouldExit:
default:
return {};
}
}
}
}
return {};
}
<|endoftext|>
|
<commit_before><commit_msg>algorithms: use std::stable_sort<commit_after><|endoftext|>
|
<commit_before><commit_msg>Treeview may lose focus when left/right arrow is used<commit_after><|endoftext|>
|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: numhead.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-08 16:34:04 $
*
* 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 GCC
#pragma hdrstop
#endif
#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#include "numhead.hxx"
// ID's fuer Dateien:
#define SV_NUMID_SIZES 0x4200
// STATIC DATA -----------------------------------------------------------
//SEG_EOFGLOBALS()
// =======================================================================
/* wird fuer SvNumberformatter nicht gebraucht
//#pragma SEG_FUNCDEF(numhead_01)
SvNumReadHeader::SvNumReadHeader(SvStream& rNewStream) :
rStream( rNewStream )
{
ULONG nDataSize;
rStream >> nDataSize;
nDataEnd = rStream.Tell() + nDataSize;
}
//#pragma SEG_FUNCDEF(numhead_02)
SvNumReadHeader::~SvNumReadHeader()
{
ULONG nReadEnd = rStream.Tell();
DBG_ASSERT( nReadEnd <= nDataEnd, "zuviele Bytes gelesen" );
if ( nReadEnd != nDataEnd )
rStream.Seek(nDataEnd); // Rest ueberspringen
}
//#pragma SEG_FUNCDEF(numhead_03)
ULONG SvNumReadHeader::BytesLeft() const
{
ULONG nReadEnd = rStream.Tell();
if (nReadEnd <= nDataEnd)
return nDataEnd-nReadEnd;
DBG_ERROR("Fehler bei SvNumReadHeader::BytesLeft");
return 0;
}
// -----------------------------------------------------------------------
//#pragma SEG_FUNCDEF(numhead_04)
SvNumWriteHeader::SvNumWriteHeader(SvStream& rNewStream, ULONG nDefault) :
rStream( rNewStream )
{
nDataSize = nDefault;
rStream << nDataSize;
nDataPos = rStream.Tell();
}
//#pragma SEG_FUNCDEF(numhead_05)
SvNumWriteHeader::~SvNumWriteHeader()
{
ULONG nPos = rStream.Tell();
if ( nPos - nDataPos != nDataSize ) // Default getroffen?
{
nDataSize = nPos - nDataPos;
rStream.Seek(nDataPos - sizeof(ULONG));
rStream << nDataSize; // Groesse am Anfang eintragen
rStream.Seek(nPos);
}
}
*/
// =======================================================================
//#pragma SEG_FUNCDEF(numhead_06)
//! mit Skip() synchron
ImpSvNumMultipleReadHeader::ImpSvNumMultipleReadHeader(SvStream& rNewStream) :
rStream( rNewStream )
{
ULONG nDataSize;
rStream >> nDataSize;
ULONG nDataPos = rStream.Tell();
nEntryEnd = nDataPos;
rStream.SeekRel(nDataSize);
USHORT nID;
rStream >> nID;
if (nID != SV_NUMID_SIZES)
{
DBG_ERROR("SV_NUMID_SIZES nicht gefunden");
}
ULONG nSizeTableLen;
rStream >> nSizeTableLen;
pBuf = new char[nSizeTableLen];
rStream.Read( pBuf, nSizeTableLen );
pMemStream = new SvMemoryStream( pBuf, nSizeTableLen, STREAM_READ );
nEndPos = rStream.Tell();
rStream.Seek( nDataPos );
}
//#pragma SEG_FUNCDEF(numhead_07)
ImpSvNumMultipleReadHeader::~ImpSvNumMultipleReadHeader()
{
DBG_ASSERT( pMemStream->Tell() == pMemStream->GetSize(),
"Sizes nicht vollstaendig gelesen" );
delete pMemStream;
delete [] pBuf;
rStream.Seek(nEndPos);
}
//! mit ctor synchron
// static
void ImpSvNumMultipleReadHeader::Skip( SvStream& rStream )
{
ULONG nDataSize;
rStream >> nDataSize;
rStream.SeekRel( nDataSize );
USHORT nID;
rStream >> nID;
if ( nID != SV_NUMID_SIZES )
{
DBG_ERROR("SV_NUMID_SIZES nicht gefunden");
}
ULONG nSizeTableLen;
rStream >> nSizeTableLen;
rStream.SeekRel( nSizeTableLen );
}
//#pragma SEG_FUNCDEF(numhead_08)
void ImpSvNumMultipleReadHeader::EndEntry()
{
ULONG nPos = rStream.Tell();
DBG_ASSERT( nPos <= nEntryEnd, "zuviel gelesen" );
if ( nPos != nEntryEnd )
rStream.Seek( nEntryEnd ); // Rest ueberspringen
}
//#pragma SEG_FUNCDEF(numhead_0d)
void ImpSvNumMultipleReadHeader::StartEntry()
{
ULONG nPos = rStream.Tell();
ULONG nEntrySize;
(*pMemStream) >> nEntrySize;
nEntryEnd = nPos + nEntrySize;
}
//#pragma SEG_FUNCDEF(numhead_09)
ULONG ImpSvNumMultipleReadHeader::BytesLeft() const
{
ULONG nReadEnd = rStream.Tell();
if (nReadEnd <= nEntryEnd)
return nEntryEnd-nReadEnd;
DBG_ERROR("Fehler bei ImpSvNumMultipleReadHeader::BytesLeft");
return 0;
}
// -----------------------------------------------------------------------
//#pragma SEG_FUNCDEF(numhead_0a)
ImpSvNumMultipleWriteHeader::ImpSvNumMultipleWriteHeader(SvStream& rNewStream,
ULONG nDefault) :
rStream( rNewStream ),
aMemStream( 4096, 4096 )
{
nDataSize = nDefault;
rStream << nDataSize;
nDataPos = rStream.Tell();
nEntryStart = nDataPos;
}
//#pragma SEG_FUNCDEF(numhead_0b)
ImpSvNumMultipleWriteHeader::~ImpSvNumMultipleWriteHeader()
{
ULONG nDataEnd = rStream.Tell();
rStream << (USHORT) SV_NUMID_SIZES;
rStream << aMemStream.Tell();
rStream.Write( aMemStream.GetData(), aMemStream.Tell() );
if ( nDataEnd - nDataPos != nDataSize ) // Default getroffen?
{
nDataSize = nDataEnd - nDataPos;
ULONG nPos = rStream.Tell();
rStream.Seek(nDataPos-sizeof(ULONG));
rStream << nDataSize; // Groesse am Anfang eintragen
rStream.Seek(nPos);
}
}
//#pragma SEG_FUNCDEF(numhead_0c)
void ImpSvNumMultipleWriteHeader::EndEntry()
{
ULONG nPos = rStream.Tell();
aMemStream << nPos - nEntryStart;
}
//#pragma SEG_FUNCDEF(numhead_0e)
void ImpSvNumMultipleWriteHeader::StartEntry()
{
ULONG nPos = rStream.Tell();
nEntryStart = nPos;
}
<commit_msg>INTEGRATION: CWS sixtyfour02 (1.5.178); FILE MERGED 2006/02/22 12:02:10 cmc 1.5.178.1: #i62425# streaming longs to disk<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: numhead.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: vg $ $Date: 2006-03-16 13:05:56 $
*
* 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 GCC
#pragma hdrstop
#endif
#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#include "numhead.hxx"
// ID's fuer Dateien:
#define SV_NUMID_SIZES 0x4200
// STATIC DATA -----------------------------------------------------------
//SEG_EOFGLOBALS()
// =======================================================================
/* wird fuer SvNumberformatter nicht gebraucht
//#pragma SEG_FUNCDEF(numhead_01)
SvNumReadHeader::SvNumReadHeader(SvStream& rNewStream) :
rStream( rNewStream )
{
ULONG nDataSize;
rStream >> nDataSize;
nDataEnd = rStream.Tell() + nDataSize;
}
//#pragma SEG_FUNCDEF(numhead_02)
SvNumReadHeader::~SvNumReadHeader()
{
ULONG nReadEnd = rStream.Tell();
DBG_ASSERT( nReadEnd <= nDataEnd, "zuviele Bytes gelesen" );
if ( nReadEnd != nDataEnd )
rStream.Seek(nDataEnd); // Rest ueberspringen
}
//#pragma SEG_FUNCDEF(numhead_03)
ULONG SvNumReadHeader::BytesLeft() const
{
ULONG nReadEnd = rStream.Tell();
if (nReadEnd <= nDataEnd)
return nDataEnd-nReadEnd;
DBG_ERROR("Fehler bei SvNumReadHeader::BytesLeft");
return 0;
}
// -----------------------------------------------------------------------
//#pragma SEG_FUNCDEF(numhead_04)
SvNumWriteHeader::SvNumWriteHeader(SvStream& rNewStream, ULONG nDefault) :
rStream( rNewStream )
{
nDataSize = nDefault;
rStream << nDataSize;
nDataPos = rStream.Tell();
}
//#pragma SEG_FUNCDEF(numhead_05)
SvNumWriteHeader::~SvNumWriteHeader()
{
ULONG nPos = rStream.Tell();
if ( nPos - nDataPos != nDataSize ) // Default getroffen?
{
nDataSize = nPos - nDataPos;
rStream.Seek(nDataPos - sizeof(ULONG));
rStream << nDataSize; // Groesse am Anfang eintragen
rStream.Seek(nPos);
}
}
*/
// =======================================================================
//#pragma SEG_FUNCDEF(numhead_06)
//! mit Skip() synchron
ImpSvNumMultipleReadHeader::ImpSvNumMultipleReadHeader(SvStream& rNewStream) :
rStream( rNewStream )
{
sal_uInt32 nDataSize;
rStream >> nDataSize;
ULONG nDataPos = rStream.Tell();
nEntryEnd = nDataPos;
rStream.SeekRel(nDataSize);
USHORT nID;
rStream >> nID;
if (nID != SV_NUMID_SIZES)
{
DBG_ERROR("SV_NUMID_SIZES nicht gefunden");
}
sal_uInt32 nSizeTableLen;
rStream >> nSizeTableLen;
pBuf = new char[nSizeTableLen];
rStream.Read( pBuf, nSizeTableLen );
pMemStream = new SvMemoryStream( pBuf, nSizeTableLen, STREAM_READ );
nEndPos = rStream.Tell();
rStream.Seek( nDataPos );
}
//#pragma SEG_FUNCDEF(numhead_07)
ImpSvNumMultipleReadHeader::~ImpSvNumMultipleReadHeader()
{
DBG_ASSERT( pMemStream->Tell() == pMemStream->GetSize(),
"Sizes nicht vollstaendig gelesen" );
delete pMemStream;
delete [] pBuf;
rStream.Seek(nEndPos);
}
//! mit ctor synchron
// static
void ImpSvNumMultipleReadHeader::Skip( SvStream& rStream )
{
sal_uInt32 nDataSize;
rStream >> nDataSize;
rStream.SeekRel( nDataSize );
USHORT nID;
rStream >> nID;
if ( nID != SV_NUMID_SIZES )
{
DBG_ERROR("SV_NUMID_SIZES nicht gefunden");
}
sal_uInt32 nSizeTableLen;
rStream >> nSizeTableLen;
rStream.SeekRel( nSizeTableLen );
}
//#pragma SEG_FUNCDEF(numhead_08)
void ImpSvNumMultipleReadHeader::EndEntry()
{
ULONG nPos = rStream.Tell();
DBG_ASSERT( nPos <= nEntryEnd, "zuviel gelesen" );
if ( nPos != nEntryEnd )
rStream.Seek( nEntryEnd ); // Rest ueberspringen
}
//#pragma SEG_FUNCDEF(numhead_0d)
void ImpSvNumMultipleReadHeader::StartEntry()
{
ULONG nPos = rStream.Tell();
sal_uInt32 nEntrySize;
(*pMemStream) >> nEntrySize;
nEntryEnd = nPos + nEntrySize;
}
//#pragma SEG_FUNCDEF(numhead_09)
ULONG ImpSvNumMultipleReadHeader::BytesLeft() const
{
ULONG nReadEnd = rStream.Tell();
if (nReadEnd <= nEntryEnd)
return nEntryEnd-nReadEnd;
DBG_ERROR("Fehler bei ImpSvNumMultipleReadHeader::BytesLeft");
return 0;
}
// -----------------------------------------------------------------------
//#pragma SEG_FUNCDEF(numhead_0a)
ImpSvNumMultipleWriteHeader::ImpSvNumMultipleWriteHeader(SvStream& rNewStream,
ULONG nDefault) :
rStream( rNewStream ),
aMemStream( 4096, 4096 )
{
nDataSize = nDefault;
rStream << nDataSize;
nDataPos = rStream.Tell();
nEntryStart = nDataPos;
}
//#pragma SEG_FUNCDEF(numhead_0b)
ImpSvNumMultipleWriteHeader::~ImpSvNumMultipleWriteHeader()
{
ULONG nDataEnd = rStream.Tell();
rStream << (USHORT) SV_NUMID_SIZES;
rStream << static_cast<sal_uInt32>(aMemStream.Tell());
rStream.Write( aMemStream.GetData(), aMemStream.Tell() );
if ( nDataEnd - nDataPos != nDataSize ) // Default getroffen?
{
nDataSize = nDataEnd - nDataPos;
ULONG nPos = rStream.Tell();
rStream.Seek(nDataPos-sizeof(ULONG));
rStream << nDataSize; // Groesse am Anfang eintragen
rStream.Seek(nPos);
}
}
//#pragma SEG_FUNCDEF(numhead_0c)
void ImpSvNumMultipleWriteHeader::EndEntry()
{
ULONG nPos = rStream.Tell();
aMemStream << static_cast<sal_uInt32>(nPos - nEntryStart);
}
//#pragma SEG_FUNCDEF(numhead_0e)
void ImpSvNumMultipleWriteHeader::StartEntry()
{
ULONG nPos = rStream.Tell();
nEntryStart = nPos;
}
<|endoftext|>
|
<commit_before><commit_msg>Cleaning up commented out code.<commit_after><|endoftext|>
|
<commit_before>#include "recorder_base.h"
#include "globals.h"
#include "threads.h"
#include "sift_assert.h"
#include "recorder_control.h"
#include "syscall_modeling.h"
#include <iostream>
VOID countInsns(THREADID threadid, INT32 count)
{
thread_data[threadid].icount += count;
if (thread_data[threadid].icount >= fast_forward_target && !KnobUseROI.Value() && !KnobMPIImplicitROI.Value())
{
if (KnobVerbose.Value())
std::cerr << "[SIFT_RECORDER:" << app_id << ":" << thread_data[threadid].thread_num << "] Changing to detailed after " << thread_data[threadid].icount << " instructions" << std::endl;
if (!thread_data[threadid].output)
openFile(threadid);
thread_data[threadid].icount = 0;
any_thread_in_detail = true;
PIN_RemoveInstrumentation();
}
}
VOID sendInstruction(THREADID threadid, ADDRINT addr, UINT32 size, UINT32 num_addresses, BOOL is_branch, BOOL taken, BOOL is_predicate, BOOL executing, BOOL isbefore, BOOL ispause)
{
// We're still called for instructions in the same basic block as ROI end, ignore these
if (!thread_data[threadid].output)
return;
++thread_data[threadid].icount;
++thread_data[threadid].icount_detailed;
// Reconstruct basic blocks (we could ask Pin, but do it the same way as TraceThread will do it)
if (thread_data[threadid].bbv_end || thread_data[threadid].bbv_last != addr)
{
// We're the start of a new basic block
thread_data[threadid].bbv->count(thread_data[threadid].bbv_base, thread_data[threadid].bbv_count);
thread_data[threadid].bbv_base = addr;
thread_data[threadid].bbv_count = 0;
}
thread_data[threadid].bbv_count++;
thread_data[threadid].bbv_last = addr + size;
// Force BBV end on non-taken branches
thread_data[threadid].bbv_end = is_branch;
uint64_t addresses[Sift::MAX_DYNAMIC_ADDRESSES] = { 0 };
for(uint8_t i = 0; i < num_addresses; ++i)
{
addresses[i] = thread_data[threadid].dyn_address_queue->front();
sift_assert(!thread_data[threadid].dyn_address_queue->empty());
thread_data[threadid].dyn_address_queue->pop_front();
if (isbefore)
{
// If the instruction hasn't executed yet, access the address to ensure a page fault if the mapping wasn't set up yet
static char dummy = 0;
dummy += *(char *)addresses[i];
}
}
sift_assert(thread_data[threadid].dyn_address_queue->empty());
thread_data[threadid].output->Instruction(addr, size, num_addresses, addresses, is_branch, taken, is_predicate, executing);
if (KnobUseResponseFiles.Value() && KnobFlowControl.Value() && (thread_data[threadid].icount > thread_data[threadid].flowcontrol_target || ispause))
{
thread_data[threadid].output->Sync();
thread_data[threadid].flowcontrol_target = thread_data[threadid].icount + KnobFlowControl.Value();
}
if (detailed_target != 0 && thread_data[threadid].icount_detailed >= detailed_target)
{
closeFile(threadid);
PIN_Detach();
return;
}
if (blocksize && thread_data[threadid].icount >= blocksize)
{
openFile(threadid);
thread_data[threadid].icount = 0;
}
}
VOID handleMemory(THREADID threadid, ADDRINT address)
{
// We're still called for instructions in the same basic block as ROI end, ignore these
if (!thread_data[threadid].output)
return;
thread_data[threadid].dyn_address_queue->push_back(address);
}
UINT32 addMemoryModeling(INS ins)
{
UINT32 num_addresses = 0;
if (INS_IsMemoryRead (ins) || INS_IsMemoryWrite (ins))
{
for (unsigned int i = 0; i < INS_MemoryOperandCount(ins); i++)
{
INS_InsertCall(ins, IPOINT_BEFORE,
AFUNPTR(handleMemory),
IARG_THREAD_ID,
IARG_MEMORYOP_EA, i,
IARG_END);
num_addresses++;
}
}
sift_assert(num_addresses <= Sift::MAX_DYNAMIC_ADDRESSES);
return num_addresses;
}
VOID insertCall(INS ins, IPOINT ipoint, UINT32 num_addresses, BOOL is_branch, BOOL taken)
{
INS_InsertCall(ins, ipoint,
AFUNPTR(sendInstruction),
IARG_THREAD_ID,
IARG_ADDRINT, INS_Address(ins),
IARG_UINT32, UINT32(INS_Size(ins)),
IARG_UINT32, num_addresses,
IARG_BOOL, is_branch,
IARG_BOOL, taken,
IARG_BOOL, INS_IsPredicated(ins),
IARG_EXECUTING,
IARG_BOOL, ipoint == IPOINT_BEFORE,
IARG_BOOL, INS_Opcode(ins) == XED_ICLASS_PAUSE,
IARG_END);
}
static VOID traceCallback(TRACE trace, void *v)
{
BBL bbl_head = TRACE_BblHead(trace);
for (BBL bbl = bbl_head; BBL_Valid(bbl); bbl = BBL_Next(bbl))
{
for(INS ins = BBL_InsHead(bbl); ; ins = INS_Next(ins))
{
// Simics-style magic instruction: xchg bx, bx
if (INS_IsXchg(ins) && INS_OperandReg(ins, 0) == REG_BX && INS_OperandReg(ins, 1) == REG_BX)
{
INS_InsertPredicatedCall(ins, IPOINT_BEFORE, (AFUNPTR)handleMagic, IARG_RETURN_REGS, REG_GAX, IARG_THREAD_ID, IARG_REG_VALUE, REG_GAX, IARG_REG_VALUE, REG_GBX, IARG_REG_VALUE, REG_GCX, IARG_END);
}
// Handle emulated syscalls
if (INS_IsSyscall(ins))
{
INS_InsertPredicatedCall(ins, IPOINT_BEFORE, AFUNPTR(emulateSyscallFunc), IARG_THREAD_ID, IARG_CONST_CONTEXT, IARG_END);
}
if (ins == BBL_InsTail(bbl))
break;
}
if (!any_thread_in_detail)
{
BBL_InsertCall(bbl, IPOINT_ANYWHERE, (AFUNPTR)countInsns, IARG_THREAD_ID, IARG_UINT32, BBL_NumIns(bbl), IARG_END);
}
else
{
for(INS ins = BBL_InsHead(bbl); ; ins = INS_Next(ins))
{
// For memory instructions, we should populate data items before we send the MicroOp
UINT32 num_addresses = addMemoryModeling(ins);
bool is_branch = INS_IsBranch(ins) && INS_HasFallThrough(ins);
if (is_branch)
{
insertCall(ins, IPOINT_AFTER, num_addresses, true /* is_branch */, false /* taken */);
insertCall(ins, IPOINT_TAKEN_BRANCH, num_addresses, true /* is_branch */, true /* taken */);
}
else
{
// Whenever possible, use IPOINT_AFTER as this allows us to process addresses after the application has used them.
// This ensures that their logical to physical mapping has been set up.
insertCall(ins, INS_HasFallThrough(ins) ? IPOINT_AFTER : IPOINT_BEFORE, num_addresses, false /* is_branch */, false /* taken */);
}
if (ins == BBL_InsTail(bbl))
break;
}
}
}
}
void initRecorderBase()
{
TRACE_AddInstrumentFunction(traceCallback, 0);
}
<commit_msg>[sift_recorder] Fix magic instruction support for the 32-bit architecture<commit_after>#include "recorder_base.h"
#include "globals.h"
#include "threads.h"
#include "sift_assert.h"
#include "recorder_control.h"
#include "syscall_modeling.h"
#include <iostream>
VOID countInsns(THREADID threadid, INT32 count)
{
thread_data[threadid].icount += count;
if (thread_data[threadid].icount >= fast_forward_target && !KnobUseROI.Value() && !KnobMPIImplicitROI.Value())
{
if (KnobVerbose.Value())
std::cerr << "[SIFT_RECORDER:" << app_id << ":" << thread_data[threadid].thread_num << "] Changing to detailed after " << thread_data[threadid].icount << " instructions" << std::endl;
if (!thread_data[threadid].output)
openFile(threadid);
thread_data[threadid].icount = 0;
any_thread_in_detail = true;
PIN_RemoveInstrumentation();
}
}
VOID sendInstruction(THREADID threadid, ADDRINT addr, UINT32 size, UINT32 num_addresses, BOOL is_branch, BOOL taken, BOOL is_predicate, BOOL executing, BOOL isbefore, BOOL ispause)
{
// We're still called for instructions in the same basic block as ROI end, ignore these
if (!thread_data[threadid].output)
return;
++thread_data[threadid].icount;
++thread_data[threadid].icount_detailed;
// Reconstruct basic blocks (we could ask Pin, but do it the same way as TraceThread will do it)
if (thread_data[threadid].bbv_end || thread_data[threadid].bbv_last != addr)
{
// We're the start of a new basic block
thread_data[threadid].bbv->count(thread_data[threadid].bbv_base, thread_data[threadid].bbv_count);
thread_data[threadid].bbv_base = addr;
thread_data[threadid].bbv_count = 0;
}
thread_data[threadid].bbv_count++;
thread_data[threadid].bbv_last = addr + size;
// Force BBV end on non-taken branches
thread_data[threadid].bbv_end = is_branch;
uint64_t addresses[Sift::MAX_DYNAMIC_ADDRESSES] = { 0 };
for(uint8_t i = 0; i < num_addresses; ++i)
{
addresses[i] = thread_data[threadid].dyn_address_queue->front();
sift_assert(!thread_data[threadid].dyn_address_queue->empty());
thread_data[threadid].dyn_address_queue->pop_front();
if (isbefore)
{
// If the instruction hasn't executed yet, access the address to ensure a page fault if the mapping wasn't set up yet
static char dummy = 0;
dummy += *(char *)addresses[i];
}
}
sift_assert(thread_data[threadid].dyn_address_queue->empty());
thread_data[threadid].output->Instruction(addr, size, num_addresses, addresses, is_branch, taken, is_predicate, executing);
if (KnobUseResponseFiles.Value() && KnobFlowControl.Value() && (thread_data[threadid].icount > thread_data[threadid].flowcontrol_target || ispause))
{
thread_data[threadid].output->Sync();
thread_data[threadid].flowcontrol_target = thread_data[threadid].icount + KnobFlowControl.Value();
}
if (detailed_target != 0 && thread_data[threadid].icount_detailed >= detailed_target)
{
closeFile(threadid);
PIN_Detach();
return;
}
if (blocksize && thread_data[threadid].icount >= blocksize)
{
openFile(threadid);
thread_data[threadid].icount = 0;
}
}
VOID handleMemory(THREADID threadid, ADDRINT address)
{
// We're still called for instructions in the same basic block as ROI end, ignore these
if (!thread_data[threadid].output)
return;
thread_data[threadid].dyn_address_queue->push_back(address);
}
UINT32 addMemoryModeling(INS ins)
{
UINT32 num_addresses = 0;
if (INS_IsMemoryRead (ins) || INS_IsMemoryWrite (ins))
{
for (unsigned int i = 0; i < INS_MemoryOperandCount(ins); i++)
{
INS_InsertCall(ins, IPOINT_BEFORE,
AFUNPTR(handleMemory),
IARG_THREAD_ID,
IARG_MEMORYOP_EA, i,
IARG_END);
num_addresses++;
}
}
sift_assert(num_addresses <= Sift::MAX_DYNAMIC_ADDRESSES);
return num_addresses;
}
VOID insertCall(INS ins, IPOINT ipoint, UINT32 num_addresses, BOOL is_branch, BOOL taken)
{
INS_InsertCall(ins, ipoint,
AFUNPTR(sendInstruction),
IARG_THREAD_ID,
IARG_ADDRINT, INS_Address(ins),
IARG_UINT32, UINT32(INS_Size(ins)),
IARG_UINT32, num_addresses,
IARG_BOOL, is_branch,
IARG_BOOL, taken,
IARG_BOOL, INS_IsPredicated(ins),
IARG_EXECUTING,
IARG_BOOL, ipoint == IPOINT_BEFORE,
IARG_BOOL, INS_Opcode(ins) == XED_ICLASS_PAUSE,
IARG_END);
}
static VOID traceCallback(TRACE trace, void *v)
{
BBL bbl_head = TRACE_BblHead(trace);
for (BBL bbl = bbl_head; BBL_Valid(bbl); bbl = BBL_Next(bbl))
{
for(INS ins = BBL_InsHead(bbl); ; ins = INS_Next(ins))
{
// Simics-style magic instruction: xchg bx, bx
if (INS_IsXchg(ins) && INS_OperandReg(ins, 0) == REG_BX && INS_OperandReg(ins, 1) == REG_BX)
{
INS_InsertPredicatedCall(ins, IPOINT_BEFORE, (AFUNPTR)handleMagic, IARG_RETURN_REGS, REG_GAX, IARG_THREAD_ID, IARG_REG_VALUE, REG_GAX,
#ifdef TARGET_IA32
IARG_REG_VALUE, REG_GDX,
#else
IARG_REG_VALUE, REG_GBX,
#endif
IARG_REG_VALUE, REG_GCX, IARG_END);
}
// Handle emulated syscalls
if (INS_IsSyscall(ins))
{
INS_InsertPredicatedCall(ins, IPOINT_BEFORE, AFUNPTR(emulateSyscallFunc), IARG_THREAD_ID, IARG_CONST_CONTEXT, IARG_END);
}
if (ins == BBL_InsTail(bbl))
break;
}
if (!any_thread_in_detail)
{
BBL_InsertCall(bbl, IPOINT_ANYWHERE, (AFUNPTR)countInsns, IARG_THREAD_ID, IARG_UINT32, BBL_NumIns(bbl), IARG_END);
}
else
{
for(INS ins = BBL_InsHead(bbl); ; ins = INS_Next(ins))
{
// For memory instructions, we should populate data items before we send the MicroOp
UINT32 num_addresses = addMemoryModeling(ins);
bool is_branch = INS_IsBranch(ins) && INS_HasFallThrough(ins);
if (is_branch)
{
insertCall(ins, IPOINT_AFTER, num_addresses, true /* is_branch */, false /* taken */);
insertCall(ins, IPOINT_TAKEN_BRANCH, num_addresses, true /* is_branch */, true /* taken */);
}
else
{
// Whenever possible, use IPOINT_AFTER as this allows us to process addresses after the application has used them.
// This ensures that their logical to physical mapping has been set up.
insertCall(ins, INS_HasFallThrough(ins) ? IPOINT_AFTER : IPOINT_BEFORE, num_addresses, false /* is_branch */, false /* taken */);
}
if (ins == BBL_InsTail(bbl))
break;
}
}
}
}
void initRecorderBase()
{
TRACE_AddInstrumentFunction(traceCallback, 0);
}
<|endoftext|>
|
<commit_before>/* This is free and unencumbered software released into the public domain. */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "rdfjson.h"
#include <cassert> /* for assert() */
namespace {
struct implementation : public rdf::writer::implementation {
implementation(FILE* stream,
const char* content_type,
const char* charset,
const char* base_uri);
virtual ~implementation() noexcept override;
virtual void configure(const char* key, const char* value) override;
virtual void begin() override;
virtual void finish() override;
virtual void write_triple(const rdf::triple& triple) override;
virtual void write_quad(const rdf::quad& quad) override;
virtual void write_comment(const char* comment) override;
virtual void flush() override;
};
}
rdf::writer::implementation*
rdf_writer_for_rdfjson(FILE* const stream,
const char* const content_type,
const char* const charset,
const char* const base_uri) {
(void)stream, (void)content_type, (void)charset, (void)base_uri;
return nullptr; // TODO
}
<commit_msg>Implemented a simple native RDF/JSON serializer.<commit_after>/* This is free and unencumbered software released into the public domain. */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "rdfjson.h"
#include <rfc/json/json_writer.h>
#include <cassert> /* for assert() */
#include <map> /* for std::map */
#include <memory> /* for std::unique_ptr */
#include <vector> /* for std::vector */
using namespace rfc4627;
namespace {
struct implementation : public rdf::writer::implementation {
implementation(FILE* stream,
const char* content_type,
const char* charset,
const char* base_uri);
virtual ~implementation() noexcept override;
virtual void configure(const char* key, const char* value) override;
virtual void begin() override;
virtual void finish() override;
virtual void write_triple(const rdf::triple& triple) override;
virtual void write_quad(const rdf::quad& quad) override;
virtual void write_comment(const char* comment) override;
virtual void flush() override;
protected:
void write_object_term(const rdf::term& term);
private:
using object_set = std::vector<std::unique_ptr<rdf::term>>;
using predicate_map = std::map<std::string, object_set>;
using subject_map = std::map<std::string, predicate_map>;
json_writer _json;
subject_map _data;
};
}
rdf::writer::implementation*
rdf_writer_for_rdfjson(FILE* const stream,
const char* const content_type,
const char* const charset,
const char* const base_uri) {
return new implementation(stream, content_type, charset, base_uri);
}
implementation::implementation(FILE* const stream,
const char* const content_type,
const char* const charset,
const char* const base_uri)
: _json{stream} {
assert(stream != nullptr);
static_cast<void>(content_type);
static_cast<void>(charset);
static_cast<void>(base_uri);
}
implementation::~implementation() noexcept {}
void
implementation::configure(const char* const key,
const char* const value) {
static_cast<void>(key); // TODO
static_cast<void>(value);
}
void
implementation::begin() {
/* @see http://www.w3.org/TR/rdf-json/#section-serialization */
_json.begin_object();
}
void
implementation::finish() {
/* @see http://www.w3.org/TR/rdf-json/#section-serialization */
auto& subject_map = _data;
for (auto& element : subject_map) {
const auto& subject_string = element.first.c_str();
auto& predicate_map = element.second;
_json.write_string(subject_string);
_json.begin_object();
for (auto& element : predicate_map) {
const auto& predicate_uri = element.first.c_str();
auto& object_set = element.second;
_json.write_string(predicate_uri);
_json.begin_array();
for (const auto& object : object_set) {
write_object_term(*object);
}
object_set.clear();
_json.finish_array();
}
predicate_map.clear();
_json.finish_object();
}
subject_map.clear();
_json.finish_object();
}
void
implementation::write_triple(const rdf::triple& triple) {
const auto& subject = *triple.subject;
const auto& predicate = *triple.predicate;
const auto& object = *triple.object;
_data[subject.string][predicate.string].emplace_back(object.clone());
_count++;
}
void
implementation::write_quad(const rdf::quad& quad) {
const auto& subject = *quad.subject;
const auto& predicate = *quad.predicate;
const auto& object = *quad.object;
_data[subject.string][predicate.string].emplace_back(object.clone());
_count++;
}
void
implementation::write_comment(const char* const comment) {
static_cast<void>(comment); /* JSON doesn't support comments */
}
void
implementation::flush() {
_json.flush();
}
void
implementation::write_object_term(const rdf::term& term_) {
_json.begin_object();
switch (term_.type) {
case rdf::term_type::uri_reference: {
const auto& term = dynamic_cast<const rdf::uri_reference&>(term_);
_json.write_string("type");
_json.write_string("uri");
_json.write_string("value");
_json.write_string(term.string.c_str());
break;
}
case rdf::term_type::blank_node: {
const auto& term = dynamic_cast<const rdf::blank_node&>(term_);
_json.write_string("type");
_json.write_string("bnode");
_json.write_string("value");
std::string buffer{"_:"};
buffer.append(term.string);
_json.write_string(buffer.c_str());
break;
}
case rdf::term_type::plain_literal: {
const auto& term = dynamic_cast<const rdf::plain_literal&>(term_);
_json.write_string("type");
_json.write_string("literal");
_json.write_string("value");
_json.write_string(term.string.c_str());
if (!term.language_tag.empty()) {
_json.write_string("lang");
_json.write_string(term.language_tag.c_str());
}
break;
}
case rdf::term_type::typed_literal: {
const auto& term = dynamic_cast<const rdf::typed_literal&>(term_);
_json.write_string("type");
_json.write_string("literal");
_json.write_string("value");
_json.write_string(term.string.c_str());
_json.write_string("datatype");
_json.write_string(term.datatype_uri.c_str());
break;
}
case rdf::term_type::none:
default:
assert(false && "invalid term type for #write_object_term");
}
_json.finish_object();
}
<|endoftext|>
|
<commit_before>/*
* bacteria-core, core for cellular automaton
* Copyright (C) 2016 Pavel Dolgov
*
* See the LICENSE file for terms of use.
*/
#ifndef CORE_CONSTANTS_HPP_
#define CORE_CONSTANTS_HPP_
/** Mass increase per one 'eat' command */
const int EAT_MASS = 1;
/** Mass increase per one 'go' command */
const int GO_MASS = -1;
/** Mass increase per one 'clon' command */
const int CLON_MASS = -10;
/** Mass increase per one 'str' command */
const int STR_MASS = -1;
/** Max additional damage per one 'str' command */
const int MAX_STR_DAMAGE = -2;
const int MAX_COMMANDS_PER_INSTRUCTION = 100;
const int MIN_COMMANDS_PER_INSTRUCTION = 1;
/** Maximum randomly generated number of actions (per instruction) */
const int RANDOM_MAX_ACTIONS = 5;
/** Maximum number of actions per move */
const int MAX_ACTIONS = 1;
/** Maximum number of pseudo actions per move */
const int MAX_PSEUDO_ACTIONS = 30;
/** Default mass of new bacteria */
const int DEFAULT_MASS = 5;
/** Default mass of cloned bacteria */
const int DEFAULT_CLON_MASS = 2;
/** Minimum width of board */
const int MIN_WIDTH = 5;
/** Maximum width of board */
const int MAX_WIDTH = 500;
/** Minimum height of board */
const int MIN_HEIGHT = 5;
/** Maximum height of board */
const int MAX_HEIGHT = 500;
#endif
<commit_msg>Add constant PSEUDO_ACTIONS_EXCESS_PENALTY<commit_after>/*
* bacteria-core, core for cellular automaton
* Copyright (C) 2016 Pavel Dolgov
*
* See the LICENSE file for terms of use.
*/
#ifndef CORE_CONSTANTS_HPP_
#define CORE_CONSTANTS_HPP_
/** Mass increase per one 'eat' command */
const int EAT_MASS = 1;
/** Mass increase per one 'go' command */
const int GO_MASS = -1;
/** Mass increase per one 'clon' command */
const int CLON_MASS = -10;
/** Mass increase per one 'str' command */
const int STR_MASS = -1;
/** Max additional damage per one 'str' command */
const int MAX_STR_DAMAGE = -2;
const int MAX_COMMANDS_PER_INSTRUCTION = 100;
const int MIN_COMMANDS_PER_INSTRUCTION = 1;
/** Maximum randomly generated number of actions (per instruction) */
const int RANDOM_MAX_ACTIONS = 5;
/** Maximum number of actions per move */
const int MAX_ACTIONS = 1;
/** Maximum number of pseudo actions per move */
const int MAX_PSEUDO_ACTIONS = 30;
/** Mass penalty (if pseudo actions >= MAX_PSEUDO_ACTIONS) */
const int PSEUDO_ACTIONS_EXCESS_PENALTY = -5;
/** Default mass of new bacteria */
const int DEFAULT_MASS = 5;
/** Default mass of cloned bacteria */
const int DEFAULT_CLON_MASS = 2;
/** Minimum width of board */
const int MIN_WIDTH = 5;
/** Maximum width of board */
const int MAX_WIDTH = 500;
/** Minimum height of board */
const int MIN_HEIGHT = 5;
/** Maximum height of board */
const int MAX_HEIGHT = 500;
#endif
<|endoftext|>
|
<commit_before>#pragma once
#include <sstream>
#include <iod/utils.hh>
#include <silicon/symbols.hh>
namespace sl
{
using s::_primary_key;
using s::_auto_increment;
using s::_read_only;
namespace sql_orm_internals
{
auto remove_members_with_attribute = [] (const auto& o, const auto& a)
{
typedef std::decay_t<decltype(a)> A;
return foreach2(o) | [&] (auto& m)
{
typedef typename std::decay_t<decltype(m)>::attributes_type attrs;
return ::iod::static_if<!has_symbol<attrs, A>::value>(
[&] () { return m; },
[&] () {});
};
};
auto extract_members_with_attribute = [] (const auto& o, const auto& a)
{
typedef std::decay_t<decltype(a)> A;
return foreach2(o) | [&] (auto& m)
{
typedef typename std::decay_t<decltype(m)>::attributes_type attrs;
return ::iod::static_if<has_symbol<attrs, A>::value>(
[&] () { return m; },
[&] () {});
};
};
template <typename T>
using remove_auto_increment_t = decltype(remove_members_with_attribute(std::declval<T>(), _auto_increment));
template <typename T>
using remove_read_only_fields_t = decltype(remove_members_with_attribute(std::declval<T>(), _read_only));
template <typename T>
using extract_primary_keys_t = decltype(extract_members_with_attribute(std::declval<T>(), _primary_key));
template <typename T>
using remove_primary_keys_t = decltype(remove_members_with_attribute(std::declval<T>(), _primary_key));
}
template <typename C, typename O>
struct sql_orm
{
typedef O object_type;
// O without auto increment for create procedure.
typedef sql_orm_internals::remove_auto_increment_t<O> without_auto_inc_type;
// Object with only the primary keys for the delete and update procedures.
typedef sql_orm_internals::extract_primary_keys_t<O> PKS;
static_assert(!std::is_same<PKS, void>::value, "You must set at least one member of the CRUD object as primary key.");
sql_orm(const std::string& table, C& con) : table_name_(table), con_(con) {}
int find_by_id(int id, O& o)
{
return con_("SELECT * from " + table_name_ + " where id = ?")(id) >> o;
}
// save all fields except auto increment.
// The db will automatically fill auto increment keys.
template <typename N>
int insert(const N& o)
{
std::stringstream ss;
std::stringstream vs;
ss << "INSERT into " << table_name_ << "(";
bool first = true;
auto values = foreach(without_auto_inc_type()) | [&] (auto& m) {
if (!first) { ss << ","; vs << ","; }
first = false;
ss << m.symbol().name();
vs << "?";
return m.symbol() = m.symbol().member_access(o);
};
ss << ") VALUES (" << vs.str() << ")";
auto req = con_(ss.str());
apply(values, req);
return req.last_insert_id();
};
// Iterate on all the rows of the table.
template <typename F>
void forall(F f)
{
std::stringstream ss;
ss << "SELECT * from " << table_name_;
con_(ss.str())() | f;
}
// Update N's members except auto increment members.
// N must have at least one primary key.
template <typename N>
int update(const N& o)
{
// check if N has at least one member of PKS.
auto pk = intersect(o, PKS());
static_assert(decltype(pk)::size() > 0, "You must provide at least one primary key to update an object.");
std::stringstream ss;
ss << "UPDATE " << table_name_ << " SET ";
bool first = true;
auto values = foreach(o) | [&] (auto& m) {
if (!first) ss << ",";
first = false;
ss << m.symbol().name() << " = ?";
return m;
};
ss << " WHERE ";
first = true;
auto pks_values = foreach(pk) | [&] (auto& m) {
if (!first) ss << " and ";
first = false;
ss << m.symbol().name() << " = ? ";
return m.symbol() = m.value();
};
auto stmt = con_(ss.str());
apply(values, pks_values, stmt);
return stmt.last_insert_id();
}
template <typename T>
void destroy(const T& o)
{
std::stringstream ss;
ss << "DELETE from " << table_name_ << " WHERE ";
bool first = true;
auto values = foreach(PKS()) | [&] (auto& m) {
if (!first) ss << " and ";
first = false;
ss << m.symbol().name() << " = ? ";
return m.symbol() = o[m.symbol()];
};
apply(values, con_(ss.str()));
}
std::string table_name_;
C con_;
};
struct sqlite_connection;
struct mysql_connection;
template <typename C, typename O>
struct sql_orm_factory
{
typedef O object_type;
typedef sql_orm<C, O> instance_type;
sql_orm_factory(const std::string& table_name) : table_name_(table_name) {}
void initialize(C& c)
{
std::stringstream ss;
ss << "CREATE TABLE if not exists " << table_name_ << " (";
bool first = true;
foreach(O()) | [&] (auto& m)
{
if (!first) ss << ", ";
ss << m.symbol().name() << " " << c.type_to_string(m.value());
if (std::is_same<C, sqlite_connection>::value)
{
if (m.attributes().has(_auto_increment) || m.attributes().has(_primary_key))
ss << " PRIMARY KEY ";
}
if (std::is_same<C, mysql_connection>::value)
{
if (m.attributes().has(_auto_increment))
ss << " AUTO_INCREMENT NOT NULL";
if (m.attributes().has(_primary_key))
ss << " PRIMARY KEY ";
}
// To activate when pgsql_connection is implemented.
// if (std::is_same<C, pgsql_connection>::value and
// m.attributes().has(_auto_increment))
// ss << " SERIAL ";
first = false;
};
ss << ");";
try
{
c(ss.str())();
}
catch (std::exception e)
{
std::cout << "Warning: Silicon could not create the " << table_name_ << " sql table." << std::endl
<< "You can ignore this message if the table already exists."
<< "The sql error is: " << e.what() << std::endl;
}
}
sql_orm<C, O> instantiate(C& con) {
return sql_orm<C, O>(table_name_, con);
};
std::string table_name_;
};
}
<commit_msg>Add iostream header<commit_after>#pragma once
#include <iostream>
#include <sstream>
#include <iod/utils.hh>
#include <silicon/symbols.hh>
namespace sl
{
using s::_primary_key;
using s::_auto_increment;
using s::_read_only;
namespace sql_orm_internals
{
auto remove_members_with_attribute = [] (const auto& o, const auto& a)
{
typedef std::decay_t<decltype(a)> A;
return foreach2(o) | [&] (auto& m)
{
typedef typename std::decay_t<decltype(m)>::attributes_type attrs;
return ::iod::static_if<!has_symbol<attrs, A>::value>(
[&] () { return m; },
[&] () {});
};
};
auto extract_members_with_attribute = [] (const auto& o, const auto& a)
{
typedef std::decay_t<decltype(a)> A;
return foreach2(o) | [&] (auto& m)
{
typedef typename std::decay_t<decltype(m)>::attributes_type attrs;
return ::iod::static_if<has_symbol<attrs, A>::value>(
[&] () { return m; },
[&] () {});
};
};
template <typename T>
using remove_auto_increment_t = decltype(remove_members_with_attribute(std::declval<T>(), _auto_increment));
template <typename T>
using remove_read_only_fields_t = decltype(remove_members_with_attribute(std::declval<T>(), _read_only));
template <typename T>
using extract_primary_keys_t = decltype(extract_members_with_attribute(std::declval<T>(), _primary_key));
template <typename T>
using remove_primary_keys_t = decltype(remove_members_with_attribute(std::declval<T>(), _primary_key));
}
template <typename C, typename O>
struct sql_orm
{
typedef O object_type;
// O without auto increment for create procedure.
typedef sql_orm_internals::remove_auto_increment_t<O> without_auto_inc_type;
// Object with only the primary keys for the delete and update procedures.
typedef sql_orm_internals::extract_primary_keys_t<O> PKS;
static_assert(!std::is_same<PKS, void>::value, "You must set at least one member of the CRUD object as primary key.");
sql_orm(const std::string& table, C& con) : table_name_(table), con_(con) {}
int find_by_id(int id, O& o)
{
return con_("SELECT * from " + table_name_ + " where id = ?")(id) >> o;
}
// save all fields except auto increment.
// The db will automatically fill auto increment keys.
template <typename N>
int insert(const N& o)
{
std::stringstream ss;
std::stringstream vs;
ss << "INSERT into " << table_name_ << "(";
bool first = true;
auto values = foreach(without_auto_inc_type()) | [&] (auto& m) {
if (!first) { ss << ","; vs << ","; }
first = false;
ss << m.symbol().name();
vs << "?";
return m.symbol() = m.symbol().member_access(o);
};
ss << ") VALUES (" << vs.str() << ")";
auto req = con_(ss.str());
apply(values, req);
return req.last_insert_id();
};
// Iterate on all the rows of the table.
template <typename F>
void forall(F f)
{
std::stringstream ss;
ss << "SELECT * from " << table_name_;
con_(ss.str())() | f;
}
// Update N's members except auto increment members.
// N must have at least one primary key.
template <typename N>
int update(const N& o)
{
// check if N has at least one member of PKS.
auto pk = intersect(o, PKS());
static_assert(decltype(pk)::size() > 0, "You must provide at least one primary key to update an object.");
std::stringstream ss;
ss << "UPDATE " << table_name_ << " SET ";
bool first = true;
auto values = foreach(o) | [&] (auto& m) {
if (!first) ss << ",";
first = false;
ss << m.symbol().name() << " = ?";
return m;
};
ss << " WHERE ";
first = true;
auto pks_values = foreach(pk) | [&] (auto& m) {
if (!first) ss << " and ";
first = false;
ss << m.symbol().name() << " = ? ";
return m.symbol() = m.value();
};
auto stmt = con_(ss.str());
apply(values, pks_values, stmt);
return stmt.last_insert_id();
}
template <typename T>
void destroy(const T& o)
{
std::stringstream ss;
ss << "DELETE from " << table_name_ << " WHERE ";
bool first = true;
auto values = foreach(PKS()) | [&] (auto& m) {
if (!first) ss << " and ";
first = false;
ss << m.symbol().name() << " = ? ";
return m.symbol() = o[m.symbol()];
};
apply(values, con_(ss.str()));
}
std::string table_name_;
C con_;
};
struct sqlite_connection;
struct mysql_connection;
template <typename C, typename O>
struct sql_orm_factory
{
typedef O object_type;
typedef sql_orm<C, O> instance_type;
sql_orm_factory(const std::string& table_name) : table_name_(table_name) {}
void initialize(C& c)
{
std::stringstream ss;
ss << "CREATE TABLE if not exists " << table_name_ << " (";
bool first = true;
foreach(O()) | [&] (auto& m)
{
if (!first) ss << ", ";
ss << m.symbol().name() << " " << c.type_to_string(m.value());
if (std::is_same<C, sqlite_connection>::value)
{
if (m.attributes().has(_auto_increment) || m.attributes().has(_primary_key))
ss << " PRIMARY KEY ";
}
if (std::is_same<C, mysql_connection>::value)
{
if (m.attributes().has(_auto_increment))
ss << " AUTO_INCREMENT NOT NULL";
if (m.attributes().has(_primary_key))
ss << " PRIMARY KEY ";
}
// To activate when pgsql_connection is implemented.
// if (std::is_same<C, pgsql_connection>::value and
// m.attributes().has(_auto_increment))
// ss << " SERIAL ";
first = false;
};
ss << ");";
try
{
c(ss.str())();
}
catch (std::exception e)
{
std::cout << "Warning: Silicon could not create the " << table_name_ << " sql table." << std::endl
<< "You can ignore this message if the table already exists."
<< "The sql error is: " << e.what() << std::endl;
}
}
sql_orm<C, O> instantiate(C& con) {
return sql_orm<C, O>(table_name_, con);
};
std::string table_name_;
};
}
<|endoftext|>
|
<commit_before>#pragma once
#include <sstream>
#include <iod/utils.hh>
#include <silicon/symbols.hh>
namespace sl
{
using s::_primary_key;
using s::_auto_increment;
using s::_read_only;
namespace sql_orm_internals
{
auto remove_members_with_attribute = [] (const auto& o, const auto& a)
{
typedef std::decay_t<decltype(a)> A;
return foreach(o) | [&] (auto& m)
{
typedef typename std::decay_t<decltype(m)>::attributes_type attrs;
return ::iod::static_if<!has_symbol<attrs, A>::value>(
[&] () { return m; },
[&] () {});
};
};
auto extract_members_with_attribute = [] (const auto& o, const auto& a)
{
typedef std::decay_t<decltype(a)> A;
return foreach(o) | [&] (auto& m)
{
typedef typename std::decay_t<decltype(m)>::attributes_type attrs;
return ::iod::static_if<has_symbol<attrs, A>::value>(
[&] () { return m; },
[&] () {});
};
};
template <typename T>
using remove_auto_increment_t = decltype(remove_members_with_attribute(std::declval<T>(), _auto_increment));
template <typename T>
using remove_read_only_fields_t = decltype(remove_members_with_attribute(std::declval<T>(), _read_only));
template <typename T>
using extract_primary_keys_t = decltype(extract_members_with_attribute(std::declval<T>(), _primary_key));
}
template <typename C, typename O>
struct sql_orm
{
typedef O object_type;
// O without auto increment for create procedure.
typedef sql_orm_internals::remove_auto_increment_t<O> without_auto_inc_type;
// Object with only the primary keys for the delete and update procedures.
typedef sql_orm_internals::extract_primary_keys_t<O> PKS;
static_assert(!std::is_same<PKS, void>::value, "You must set at least one member of the CRUD object as primary key.");
sql_orm(const std::string& table, C& con) : table_name_(table), con_(con) {}
int find_by_id(int id, O& o)
{
return con_("SELECT * from " + table_name_ + " where id = ?")(id) >> o;
}
// save all fields except auto increment.
// The db will automatically fill auto increment keys.
template <typename N>
int insert(const N& o)
{
std::stringstream ss;
std::stringstream vs;
ss << "INSERT into " << table_name_ << "(";
bool first = true;
auto values = foreach(without_auto_inc_type()) | [&] (auto& m) {
if (!first) { ss << ","; vs << ","; }
first = false;
ss << m.symbol().name();
vs << "?";
return m.symbol() = m.symbol().member_access(o);
};
ss << ") VALUES (" << vs.str() << ")";
auto req = con_(ss.str());
apply(values, req);
return req.last_insert_id();
};
// Update N's members except auto increment members.
// N must have at least one primary key.
template <typename N>
int update(const N& o)
{
// check if N has at least one member of PKS.
auto pk = intersect(o, PKS());
static_assert(decltype(pk)::size() > 0, "You must provide at least one primary key to update an object.");
std::stringstream ss;
ss << "UPDATE " << table_name_ << " SET ";
bool first = true;
auto values = foreach(o) | [&] (auto& m) {
if (!first) ss << ",";
first = false;
ss << m.symbol().name() << " = ?";
return m;
};
ss << " WHERE ";
first = true;
auto pks_values = foreach(pk) | [&] (auto& m) {
if (!first) ss << " and ";
first = false;
ss << m.symbol().name() << " = ? ";
return m.symbol() = m.value();
};
auto stmt = con_(ss.str());
apply(values, pks_values, stmt);
return stmt.last_insert_id();
}
template <typename T>
void destroy(const T& o)
{
std::stringstream ss;
ss << "DELETE from " << table_name_ << " WHERE ";
bool first = true;
auto values = foreach(PKS()) | [&] (auto& m) {
if (!first) ss << " and ";
first = false;
ss << m.symbol().name() << " = ? ";
return m.symbol() = o[m.symbol()];
};
apply(values, con_(ss.str()));
}
std::string table_name_;
C con_;
};
struct sqlite_connection;
struct mysql_connection;
template <typename C, typename O>
struct sql_orm_factory
{
typedef O object_type;
typedef sql_orm<C, O> instance_type;
sql_orm_factory(const std::string& table_name) : table_name_(table_name) {}
void initialize(C& c)
{
std::stringstream ss;
ss << "CREATE TABLE if not exists " << table_name_ << " (";
bool first = true;
foreach(O()) | [&] (auto& m)
{
if (!first) ss << ", ";
ss << m.symbol().name() << " " << c.type_to_string(m.value());
if (std::is_same<C, sqlite_connection>::value)
{
if (m.attributes().has(_auto_increment) || m.attributes().has(_primary_key))
ss << " PRIMARY KEY ";
}
if (std::is_same<C, mysql_connection>::value)
{
if (m.attributes().has(_auto_increment))
ss << " AUTO_INCREMENT NOT NULL";
if (m.attributes().has(_primary_key))
ss << " PRIMARY KEY ";
}
// To activate when pgsql_connection is implemented.
// if (std::is_same<C, pgsql_connection>::value and
// m.attributes().has(_auto_increment))
// ss << " SERIAL ";
first = false;
};
ss << ");";
c(ss.str())();
}
sql_orm<C, O> instantiate(C& con) {
return sql_orm<C, O>(table_name_, con);
};
std::string table_name_;
};
}
<commit_msg>Add sql_orm::forall.<commit_after>#pragma once
#include <sstream>
#include <iod/utils.hh>
#include <silicon/symbols.hh>
namespace sl
{
using s::_primary_key;
using s::_auto_increment;
using s::_read_only;
namespace sql_orm_internals
{
auto remove_members_with_attribute = [] (const auto& o, const auto& a)
{
typedef std::decay_t<decltype(a)> A;
return foreach(o) | [&] (auto& m)
{
typedef typename std::decay_t<decltype(m)>::attributes_type attrs;
return ::iod::static_if<!has_symbol<attrs, A>::value>(
[&] () { return m; },
[&] () {});
};
};
auto extract_members_with_attribute = [] (const auto& o, const auto& a)
{
typedef std::decay_t<decltype(a)> A;
return foreach(o) | [&] (auto& m)
{
typedef typename std::decay_t<decltype(m)>::attributes_type attrs;
return ::iod::static_if<has_symbol<attrs, A>::value>(
[&] () { return m; },
[&] () {});
};
};
template <typename T>
using remove_auto_increment_t = decltype(remove_members_with_attribute(std::declval<T>(), _auto_increment));
template <typename T>
using remove_read_only_fields_t = decltype(remove_members_with_attribute(std::declval<T>(), _read_only));
template <typename T>
using extract_primary_keys_t = decltype(extract_members_with_attribute(std::declval<T>(), _primary_key));
}
template <typename C, typename O>
struct sql_orm
{
typedef O object_type;
// O without auto increment for create procedure.
typedef sql_orm_internals::remove_auto_increment_t<O> without_auto_inc_type;
// Object with only the primary keys for the delete and update procedures.
typedef sql_orm_internals::extract_primary_keys_t<O> PKS;
static_assert(!std::is_same<PKS, void>::value, "You must set at least one member of the CRUD object as primary key.");
sql_orm(const std::string& table, C& con) : table_name_(table), con_(con) {}
int find_by_id(int id, O& o)
{
return con_("SELECT * from " + table_name_ + " where id = ?")(id) >> o;
}
// save all fields except auto increment.
// The db will automatically fill auto increment keys.
template <typename N>
int insert(const N& o)
{
std::stringstream ss;
std::stringstream vs;
ss << "INSERT into " << table_name_ << "(";
bool first = true;
auto values = foreach(without_auto_inc_type()) | [&] (auto& m) {
if (!first) { ss << ","; vs << ","; }
first = false;
ss << m.symbol().name();
vs << "?";
return m.symbol() = m.symbol().member_access(o);
};
ss << ") VALUES (" << vs.str() << ")";
auto req = con_(ss.str());
apply(values, req);
return req.last_insert_id();
};
// Iterate on all the rows of the table.
template <typename F>
void forall(F f)
{
std::stringstream ss;
ss << "SELECT * from " << table_name_ << ";";
con_(ss.str()) | f;
}
// Update N's members except auto increment members.
// N must have at least one primary key.
template <typename N>
int update(const N& o)
{
// check if N has at least one member of PKS.
auto pk = intersect(o, PKS());
static_assert(decltype(pk)::size() > 0, "You must provide at least one primary key to update an object.");
std::stringstream ss;
ss << "UPDATE " << table_name_ << " SET ";
bool first = true;
auto values = foreach(o) | [&] (auto& m) {
if (!first) ss << ",";
first = false;
ss << m.symbol().name() << " = ?";
return m;
};
ss << " WHERE ";
first = true;
auto pks_values = foreach(pk) | [&] (auto& m) {
if (!first) ss << " and ";
first = false;
ss << m.symbol().name() << " = ? ";
return m.symbol() = m.value();
};
auto stmt = con_(ss.str());
apply(values, pks_values, stmt);
return stmt.last_insert_id();
}
template <typename T>
void destroy(const T& o)
{
std::stringstream ss;
ss << "DELETE from " << table_name_ << " WHERE ";
bool first = true;
auto values = foreach(PKS()) | [&] (auto& m) {
if (!first) ss << " and ";
first = false;
ss << m.symbol().name() << " = ? ";
return m.symbol() = o[m.symbol()];
};
apply(values, con_(ss.str()));
}
std::string table_name_;
C con_;
};
struct sqlite_connection;
struct mysql_connection;
template <typename C, typename O>
struct sql_orm_factory
{
typedef O object_type;
typedef sql_orm<C, O> instance_type;
sql_orm_factory(const std::string& table_name) : table_name_(table_name) {}
void initialize(C& c)
{
std::stringstream ss;
ss << "CREATE TABLE if not exists " << table_name_ << " (";
bool first = true;
foreach(O()) | [&] (auto& m)
{
if (!first) ss << ", ";
ss << m.symbol().name() << " " << c.type_to_string(m.value());
if (std::is_same<C, sqlite_connection>::value)
{
if (m.attributes().has(_auto_increment) || m.attributes().has(_primary_key))
ss << " PRIMARY KEY ";
}
if (std::is_same<C, mysql_connection>::value)
{
if (m.attributes().has(_auto_increment))
ss << " AUTO_INCREMENT NOT NULL";
if (m.attributes().has(_primary_key))
ss << " PRIMARY KEY ";
}
// To activate when pgsql_connection is implemented.
// if (std::is_same<C, pgsql_connection>::value and
// m.attributes().has(_auto_increment))
// ss << " SERIAL ";
first = false;
};
ss << ");";
c(ss.str())();
}
sql_orm<C, O> instantiate(C& con) {
return sql_orm<C, O>(table_name_, con);
};
std::string table_name_;
};
}
<|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 "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRobustAutomaticThresholdImageFilter.h"
#include "itkGradientMagnitudeRecursiveGaussianImageFilter.h"
int main(int argc, char * argv [] )
{
if( argc != 4 )
{
std::cerr << "usage: " << argv[0] << " inputImage outputImage pow" << std::endl;
return EXIT_FAILURE;
}
const unsigned int Dimension = 2;
typedef unsigned short PixelType;
typedef itk::Image< PixelType, Dimension > ImageType;
typedef float RealPixelType;
typedef itk::Image< RealPixelType, Dimension > RealImageType;
typedef itk::ImageFileReader< ImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
reader->Update();
ImageType::ConstPointer inputImage = reader->GetOutput();
ImageType::SpacingType spacing = inputImage->GetSpacing();
typedef itk::GradientMagnitudeRecursiveGaussianImageFilter< ImageType, RealImageType > GradientType;
GradientType::Pointer gradient = GradientType::New();
gradient->SetInput( reader->GetOutput() );
gradient->SetSigma( spacing[2] );
gradient->Update();
typedef itk::RobustAutomaticThresholdImageFilter< ImageType, RealImageType > FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput( reader->GetOutput() );
filter->SetGradientImage( gradient->GetOutput() );
filter->SetPow( atof(argv[3]) );
typedef itk::ImageFileWriter< ImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( filter->GetOutput() );
writer->SetFileName( argv[2] );
try
{
writer->Update();
}
catch ( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>BUG: Fixed Sigma.<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 "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkRobustAutomaticThresholdImageFilter.h"
#include "itkGradientMagnitudeRecursiveGaussianImageFilter.h"
int main(int argc, char * argv [] )
{
if( argc != 4 )
{
std::cerr << "usage: " << argv[0] << " inputImage outputImage pow" << std::endl;
return EXIT_FAILURE;
}
const unsigned int Dimension = 2;
typedef unsigned short PixelType;
typedef itk::Image< PixelType, Dimension > ImageType;
typedef float RealPixelType;
typedef itk::Image< RealPixelType, Dimension > RealImageType;
typedef itk::ImageFileReader< ImageType > ReaderType;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName( argv[1] );
reader->Update();
ImageType::ConstPointer inputImage = reader->GetOutput();
ImageType::SpacingType spacing = inputImage->GetSpacing();
const double sigma = spacing[0] * 1.0;
std::cout << "Sigma = " << sigma << std::endl;
typedef itk::GradientMagnitudeRecursiveGaussianImageFilter< ImageType, RealImageType > GradientType;
GradientType::Pointer gradient = GradientType::New();
gradient->SetInput( reader->GetOutput() );
gradient->SetSigma( sigma );
gradient->Update();
typedef itk::ImageFileWriter< RealImageType > RealWriterType;
RealWriterType::Pointer realwriter = RealWriterType::New();
realwriter->SetInput( gradient->GetOutput() );
realwriter->SetFileName( "gradient.mha" );
realwriter->Update();
typedef itk::RobustAutomaticThresholdImageFilter< ImageType, RealImageType > FilterType;
FilterType::Pointer filter = FilterType::New();
filter->SetInput( reader->GetOutput() );
filter->SetGradientImage( gradient->GetOutput() );
filter->SetPow( atof(argv[3]) );
typedef itk::ImageFileWriter< ImageType > WriterType;
WriterType::Pointer writer = WriterType::New();
writer->SetInput( filter->GetOutput() );
writer->SetFileName( argv[2] );
try
{
writer->Update();
}
catch ( itk::ExceptionObject & excp )
{
std::cerr << excp << std::endl;
return EXIT_FAILURE;
}
std::cout << "Computed Threshold = " << filter->GetThreshold() << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|>
|
<commit_before>#include "Editor.hpp"
#include <Engine/Util/Input.hpp>
#include "Util/EditorSettings.hpp"
#include <Engine/Hymn.hpp>
#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ScriptManager.hpp>
#include <Engine/Util/FileSystem.hpp>
#include <Engine/MainWindow.hpp>
#include <imgui.h>
#include <GLFW/glfw3.h>
Editor::Editor() {
// Assign controls.
Input()->AssignButton(InputHandler::PROFILE, InputHandler::KEYBOARD, GLFW_KEY_F2);
Input()->AssignButton(InputHandler::PLAYTEST, InputHandler::KEYBOARD, GLFW_KEY_F5);
Input()->AssignButton(InputHandler::CONTROL, InputHandler::KEYBOARD, GLFW_KEY_LEFT_CONTROL);
Input()->AssignButton(InputHandler::NEW, InputHandler::KEYBOARD, GLFW_KEY_N);
Input()->AssignButton(InputHandler::OPEN, InputHandler::KEYBOARD, GLFW_KEY_O);
}
void Editor::Show() {
bool play = false;
ImVec2 size(MainWindow::GetInstance()->GetSize().x, MainWindow::GetInstance()->GetSize().y);
// Main menu bar.
if (ImGui::BeginMainMenuBar()) {
// File menu.
if (ImGui::BeginMenu("File")) {
if (ImGui::MenuItem("New Hymn", "CTRL+N"))
NewHymn();
if (ImGui::MenuItem("Open Hymn", "CTRL+O"))
OpenHymn();
ImGui::EndMenu();
}
// View menu.
if (ImGui::BeginMenu("View")) {
static bool soundSources = EditorSettings::GetInstance().GetBool("Sound Source Icons");
ImGui::MenuItem("Sound Sources", "", &soundSources);
EditorSettings::GetInstance().SetBool("Sound Source Icons", soundSources);
static bool particleEmitters = EditorSettings::GetInstance().GetBool("Particle Emitter Icons");
ImGui::MenuItem("Particle Emitters", "", &particleEmitters);
EditorSettings::GetInstance().SetBool("Particle Emitter Icons", particleEmitters);
static bool lightSources = EditorSettings::GetInstance().GetBool("Light Source Icons");
ImGui::MenuItem("Light Sources", "", &lightSources);
EditorSettings::GetInstance().SetBool("Light Source Icons", lightSources);
ImGui::EndMenu();
}
// Play
if (ImGui::BeginMenu("Play")) {
if (ImGui::MenuItem("Play", "F5")) {
Managers().scriptManager->RegisterInput();
Managers().scriptManager->BuildAllScripts();
play = true;
}
ImGui::EndMenu();
}
// Input
if(Hymn().GetPath() != "") {
if (ImGui::BeginMenu("Input")) {
inputWindow.SetVisible(true);
ImGui::EndMenu();
}
}
ImGui::EndMainMenuBar();
}
// Show hymn selection window.
if (selectHymnWindow.IsVisible()) {
ImGui::SetNextWindowPosCenter();
selectHymnWindow.Show();
}
if (inputWindow.IsVisible())
inputWindow.Show();
// Show resource list.
if (resourceList.IsVisible()) {
ImGui::SetNextWindowPos(ImVec2(0, size.y - 250));
ImGui::SetNextWindowSize(ImVec2(size.x - 250, 250));
resourceList.Show();
}
if (Input()->Triggered(InputHandler::PLAYTEST))
play = true;
if (Input()->Triggered(InputHandler::NEW) && Input()->Pressed(InputHandler::CONTROL))
NewHymn();
if (Input()->Triggered(InputHandler::OPEN) && Input()->Pressed(InputHandler::CONTROL))
OpenHymn();
if (play)
Play();
}
void Editor::Save() const {
resourceList.SaveScene();
Hymn().Save();
}
bool Editor::IsVisible() const {
return visible;
}
void Editor::SetVisible(bool visible) {
this->visible = visible;
}
void Editor::Play() {
Save();
SetVisible(false);
resourceList.HideEditors();
resourceList.ResetScene();
}
void Editor::NewHymn() {
selectHymnWindow.Scan();
selectHymnWindow.SetClosedCallback(std::bind(&Editor::NewHymnClosed, this, std::placeholders::_1));
selectHymnWindow.SetTitle("New Hymn");
selectHymnWindow.SetOpenButtonName("Create");
selectHymnWindow.SetVisible(true);
}
void Editor::NewHymnClosed(const std::string& hymn) {
// Create new hymn
if (!hymn.empty()) {
resourceList.ResetScene();
Hymn().Clear();
Hymn().SetPath(FileSystem::DataPath("Hymn to Beauty", hymn.c_str()));
resourceList.SetVisible(true);
}
selectHymnWindow.SetVisible(false);
}
void Editor::OpenHymn() {
selectHymnWindow.Scan();
selectHymnWindow.SetClosedCallback(std::bind(&Editor::OpenHymnClosed, this, std::placeholders::_1));
selectHymnWindow.SetTitle("Open Hymn");
selectHymnWindow.SetOpenButtonName("Open");
selectHymnWindow.SetVisible(true);
}
void Editor::OpenHymnClosed(const std::string& hymn) {
// Open hymn.
if (!hymn.empty()) {
resourceList.ResetScene();
Hymn().Load(FileSystem::DataPath("Hymn to Beauty", hymn.c_str()));
resourceList.SetVisible(true);
}
selectHymnWindow.SetVisible(false);
}
<commit_msg>Fix playing by pressing F5<commit_after>#include "Editor.hpp"
#include <Engine/Util/Input.hpp>
#include "Util/EditorSettings.hpp"
#include <Engine/Hymn.hpp>
#include <Engine/Manager/Managers.hpp>
#include <Engine/Manager/ScriptManager.hpp>
#include <Engine/Util/FileSystem.hpp>
#include <Engine/MainWindow.hpp>
#include <imgui.h>
#include <GLFW/glfw3.h>
Editor::Editor() {
// Assign controls.
Input()->AssignButton(InputHandler::PROFILE, InputHandler::KEYBOARD, GLFW_KEY_F2);
Input()->AssignButton(InputHandler::PLAYTEST, InputHandler::KEYBOARD, GLFW_KEY_F5);
Input()->AssignButton(InputHandler::CONTROL, InputHandler::KEYBOARD, GLFW_KEY_LEFT_CONTROL);
Input()->AssignButton(InputHandler::NEW, InputHandler::KEYBOARD, GLFW_KEY_N);
Input()->AssignButton(InputHandler::OPEN, InputHandler::KEYBOARD, GLFW_KEY_O);
}
void Editor::Show() {
bool play = false;
ImVec2 size(MainWindow::GetInstance()->GetSize().x, MainWindow::GetInstance()->GetSize().y);
// Main menu bar.
if (ImGui::BeginMainMenuBar()) {
// File menu.
if (ImGui::BeginMenu("File")) {
if (ImGui::MenuItem("New Hymn", "CTRL+N"))
NewHymn();
if (ImGui::MenuItem("Open Hymn", "CTRL+O"))
OpenHymn();
ImGui::EndMenu();
}
// View menu.
if (ImGui::BeginMenu("View")) {
static bool soundSources = EditorSettings::GetInstance().GetBool("Sound Source Icons");
ImGui::MenuItem("Sound Sources", "", &soundSources);
EditorSettings::GetInstance().SetBool("Sound Source Icons", soundSources);
static bool particleEmitters = EditorSettings::GetInstance().GetBool("Particle Emitter Icons");
ImGui::MenuItem("Particle Emitters", "", &particleEmitters);
EditorSettings::GetInstance().SetBool("Particle Emitter Icons", particleEmitters);
static bool lightSources = EditorSettings::GetInstance().GetBool("Light Source Icons");
ImGui::MenuItem("Light Sources", "", &lightSources);
EditorSettings::GetInstance().SetBool("Light Source Icons", lightSources);
ImGui::EndMenu();
}
// Play
if (ImGui::BeginMenu("Play")) {
if (ImGui::MenuItem("Play", "F5"))
play = true;
ImGui::EndMenu();
}
// Input
if(Hymn().GetPath() != "") {
if (ImGui::BeginMenu("Input")) {
inputWindow.SetVisible(true);
ImGui::EndMenu();
}
}
ImGui::EndMainMenuBar();
}
// Show hymn selection window.
if (selectHymnWindow.IsVisible()) {
ImGui::SetNextWindowPosCenter();
selectHymnWindow.Show();
}
if (inputWindow.IsVisible())
inputWindow.Show();
// Show resource list.
if (resourceList.IsVisible()) {
ImGui::SetNextWindowPos(ImVec2(0, size.y - 250));
ImGui::SetNextWindowSize(ImVec2(size.x - 250, 250));
resourceList.Show();
}
if (Input()->Triggered(InputHandler::PLAYTEST))
play = true;
if (Input()->Triggered(InputHandler::NEW) && Input()->Pressed(InputHandler::CONTROL))
NewHymn();
if (Input()->Triggered(InputHandler::OPEN) && Input()->Pressed(InputHandler::CONTROL))
OpenHymn();
if (play)
Play();
}
void Editor::Save() const {
resourceList.SaveScene();
Hymn().Save();
}
bool Editor::IsVisible() const {
return visible;
}
void Editor::SetVisible(bool visible) {
this->visible = visible;
}
void Editor::Play() {
Save();
SetVisible(false);
resourceList.HideEditors();
resourceList.ResetScene();
Managers().scriptManager->RegisterInput();
Managers().scriptManager->BuildAllScripts();
}
void Editor::NewHymn() {
selectHymnWindow.Scan();
selectHymnWindow.SetClosedCallback(std::bind(&Editor::NewHymnClosed, this, std::placeholders::_1));
selectHymnWindow.SetTitle("New Hymn");
selectHymnWindow.SetOpenButtonName("Create");
selectHymnWindow.SetVisible(true);
}
void Editor::NewHymnClosed(const std::string& hymn) {
// Create new hymn
if (!hymn.empty()) {
resourceList.ResetScene();
Hymn().Clear();
Hymn().SetPath(FileSystem::DataPath("Hymn to Beauty", hymn.c_str()));
resourceList.SetVisible(true);
}
selectHymnWindow.SetVisible(false);
}
void Editor::OpenHymn() {
selectHymnWindow.Scan();
selectHymnWindow.SetClosedCallback(std::bind(&Editor::OpenHymnClosed, this, std::placeholders::_1));
selectHymnWindow.SetTitle("Open Hymn");
selectHymnWindow.SetOpenButtonName("Open");
selectHymnWindow.SetVisible(true);
}
void Editor::OpenHymnClosed(const std::string& hymn) {
// Open hymn.
if (!hymn.empty()) {
resourceList.ResetScene();
Hymn().Load(FileSystem::DataPath("Hymn to Beauty", hymn.c_str()));
resourceList.SetVisible(true);
}
selectHymnWindow.SetVisible(false);
}
<|endoftext|>
|
<commit_before>/*
* This is an open source non-commercial project. Dear PVS-Studio, please check it.
* PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
*/
#include "mips_memory.h"
#include "mips_instr.h"
#include <infra/instrcache/instr_cache.h>
#include <iostream>
FuncInstr MIPSMemory::fetch_instr( Addr PC)
{
auto it = instr_cache.find( PC);
FuncInstr instr = ( it != instr_cache.end())
? FuncInstr( it->second)
: FuncInstr( read( PC), PC);
if ( it != instr_cache.end())
instr_cache.update( PC, instr);
return instr;
}
<commit_msg>Update InstrCache in case of cache miss<commit_after>/*
* This is an open source non-commercial project. Dear PVS-Studio, please check it.
* PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
*/
#include "mips_memory.h"
#include "mips_instr.h"
#include <infra/instrcache/instr_cache.h>
FuncInstr MIPSMemory::fetch_instr( Addr PC)
{
auto it = instr_cache.find( PC);
FuncInstr instr = ( it != instr_cache.end())
? FuncInstr( it->second)
: FuncInstr( read( PC), PC);
instr_cache.update( PC, instr);
return instr;
}
<|endoftext|>
|
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver Qt Agent
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@nokia.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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <QApplication>
#include <QGraphicsItem>
#include <QGraphicsWidget>
#include <QWidget>
#include <QGraphicsView>
#include <QLocale>
#include "tasuitraverser.h"
#include "taslogger.h"
#include "testabilityutils.h"
#include "tastraverserloader.h"
#include "tasdeviceutils.h"
TasUiTraverser::TasUiTraverser(QList<TasTraverseInterface*> traversers)
{
mTraversers = traversers;
mFilter = new TraverseFilter();
}
TasUiTraverser::~TasUiTraverser()
{
QMutableListIterator<TasTraverseInterface*> i(mTraversers);
while (i.hasNext()){
delete i.next();
}
mTraversers.clear();
delete mFilter;
}
void TasUiTraverser::setFilters(TasCommand* command)
{
if(!command){
return;
}
//if the command contains filtering instructions
//set the them for all traverser plugins
QStringList attributeBlackList;
if(!command->apiParameter("attributeBlackList").isEmpty()){
attributeBlackList = command->apiParameter("attributeBlackList").split(",");
}
QStringList attributeWhiteList;
if(!command->apiParameter("attributeWhiteList").isEmpty()){
attributeWhiteList = command->apiParameter("attributeWhiteList").split(",");
}
QStringList pluginBlackList;
if(!command->apiParameter("pluginBlackList").isEmpty()){
pluginBlackList = command->apiParameter("pluginBlackList").split(",");
}
QStringList pluginWhiteList;
if(!command->apiParameter("pluginWhiteList").isEmpty()){
pluginWhiteList = command->apiParameter("pluginWhiteList").split(",");
}
bool filterProps = false;
if(command->apiParameter("filterProperties") =="true"){
filterProps = true;
}
mFilter->initialize(filterProps, attributeBlackList, attributeWhiteList, pluginBlackList, pluginWhiteList);
for (int i = 0; i < mTraversers.size(); i++) {
mTraversers.at(i)->setFilter(mFilter);
}
}
TasDataModel* TasUiTraverser::getUiState(TasCommand* command)
{
setFilters(command);
TasDataModel* model = new TasDataModel();
QString qtVersion = "Qt" + QString(qVersion());
TasObjectContainer& container = model->addNewObjectContainer(1, qtVersion, "qt");
TasObject& application = container.addNewObject(QString::number(qApp->applicationPid()), getApplicationName(), "application");
addApplicationDetails(application, command);
QWidgetList widgetList = qApp->topLevelWidgets();
if (!widgetList.empty()){
QListIterator<QWidget*> iter(qApp->topLevelWidgets());
while(iter.hasNext()){
QWidget *widget = iter.next();
//only print widgets if they are visible
if (!widget->graphicsProxyWidget() &&
(TestabilityUtils::isCustomTraverse() || widget->isVisible()
)) /*&& !wasTraversed(widget)*/{
traverseObject(application.addObject(), widget, command);
}
}
}
//reset filters after uistate made so that thet will not be used for
//any other tasks done by traversers
for (int i = 0; i < mTraversers.size(); i++) {
mTraversers.at(i)->resetFilter();
}
mFilter->clear();
return model;
}
void TasUiTraverser::traverseObject(TasObject& objectInfo, QObject* object, TasCommand* command)
{
for (int i = 0; i < mTraversers.size(); i++) {
if(!mFilter->filterPlugin(mTraversers.at(i)->getPluginName())){
mTraversers.at(i)->traverseObject(&objectInfo, object, command);
}
}
//check decendants
//1. is graphicsview
if(object->inherits("QGraphicsView")){
traverseGraphicsViewItems(objectInfo, qobject_cast<QGraphicsView*>(object), command);
}
//2. is GraphicsWidget
QGraphicsWidget* graphicsWidget = qobject_cast<QGraphicsWidget*>(object);
if(graphicsWidget){
traverseGraphicsItemList(objectInfo, graphicsWidget,command);
}
//3. Widget children
else{
QObjectList children = object->children();
if (!children.isEmpty()) {
for (int i = 0; i < children.size(); ++i){
QObject *obj = children.at(i);
//only include widgets
if (obj->isWidgetType() && obj->parent() == object){
QWidget *widget = qobject_cast<QWidget*>(obj);
// TODO This (and other similar hacks) needs to be moved to plugins once OSS changes are done
if (TestabilityUtils::isCustomTraverse() || widget->isVisible() ) /*&& !wasTraversed(widget)*/{
traverseObject(objectInfo.addObject(), widget, command);
}
}
}
}
}
}
void TasUiTraverser::traverseGraphicsItem(TasObject& objectInfo, QGraphicsItem* graphicsItem, TasCommand* command)
{
if (graphicsItem->isWindow() || graphicsItem->isWidget()) {
QObject * object = (QObject*)((QGraphicsWidget*)graphicsItem);
traverseObject(objectInfo, object, command);
// Traverse the actual widget under the proxy, if available
QGraphicsProxyWidget* proxy = qobject_cast<QGraphicsProxyWidget*>(object);
if (proxy) {
traverseObject(objectInfo.addObject(), proxy->widget(), command);
}
}
else{
objectInfo.setType("QGraphicsItem");
for (int i = 0; i < mTraversers.size(); i++) {
if(!mFilter->filterPlugin(mTraversers.at(i)->getPluginName())){
mTraversers.at(i)->traverseGraphicsItem(&objectInfo, graphicsItem, command);
}
}
traverseGraphicsItemList(objectInfo, graphicsItem, command);
}
}
void TasUiTraverser::traverseGraphicsItemList(TasObject& parent, QGraphicsItem* graphicsItem, TasCommand* command)
{
foreach (QGraphicsItem* item, graphicsItem->childItems()){
if(graphicsItem == item->parentItem()){
// TODO This needs to be moved to plugins once OSS changes are done
if(TestabilityUtils::isCustomTraverse()|| item->isVisible() ) {
traverseGraphicsItem(parent.addObject(), item, command);
}
}
}
}
void TasUiTraverser::traverseGraphicsViewItems(TasObject& parent, QGraphicsView* view, TasCommand* command)
{
foreach(QGraphicsItem* item, view->items()){
if(item->parentItem() == 0){
// TODO This needs to be moved to plugins once OSS changes are done
if(TestabilityUtils::isCustomTraverse() || item->isVisible()
) {
traverseGraphicsItem(parent.addObject(), item, command);
}
}
}
}
void TasUiTraverser::addApplicationDetails(TasObject& application, TasCommand* command)
{
traverseObject(application, qApp, command);
//set these again cause properties overwrite them
application.setName(getApplicationName());
application.setId(QString::number(qApp->applicationPid()));
#ifdef Q_OS_SYMBIAN
quintptr uid = CEikonEnv::Static()->EikAppUi()->Application()->AppDllUid().iUid;
application.addAttribute("applicationUid", QString::number(uid));
#endif
application.addAttribute("exepath", qApp->applicationFilePath().toLatin1().data());
application.addAttribute("FullName", qApp->applicationFilePath().toLatin1().data());
application.addAttribute("dirpath", qApp->applicationDirPath().toLatin1().data());
application.addAttribute("processId", QString::number(qApp->applicationPid()).toLatin1().data());
application.addAttribute("version", qApp->applicationVersion().toLatin1().data());
application.addAttribute("objectType", TYPE_APPLICATION_VIEW);
application.addAttribute("objectId", TasCoreUtils::objectId(qApp));
int mem = TasDeviceUtils::currentProcessHeapSize();
if(mem != -1){
application.addAttribute("memUsage", mem);
}
QLocale defaultLocale;
application.addAttribute("localeName", defaultLocale.name());
application.addAttribute("localeCountry", defaultLocale.countryToString(defaultLocale.country()));
application.addAttribute("localeLanguage", defaultLocale.languageToString(defaultLocale.language()));
}
<commit_msg>Multiple traverse bug fix. Objects were traversed twice if they appeared in the object tree and under the app (qApp->topLevelWidgets). Fix proposal made so that a widget listed as a top level widget cannot have a parent (unless qApp) for it to be trraversed.<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver Qt Agent
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@nokia.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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <QApplication>
#include <QGraphicsItem>
#include <QGraphicsWidget>
#include <QWidget>
#include <QGraphicsView>
#include <QLocale>
#include "tasuitraverser.h"
#include "taslogger.h"
#include "testabilityutils.h"
#include "tastraverserloader.h"
#include "tasdeviceutils.h"
TasUiTraverser::TasUiTraverser(QList<TasTraverseInterface*> traversers)
{
mTraversers = traversers;
mFilter = new TraverseFilter();
}
TasUiTraverser::~TasUiTraverser()
{
QMutableListIterator<TasTraverseInterface*> i(mTraversers);
while (i.hasNext()){
delete i.next();
}
mTraversers.clear();
delete mFilter;
}
void TasUiTraverser::setFilters(TasCommand* command)
{
if(!command){
return;
}
//if the command contains filtering instructions
//set the them for all traverser plugins
QStringList attributeBlackList;
if(!command->apiParameter("attributeBlackList").isEmpty()){
attributeBlackList = command->apiParameter("attributeBlackList").split(",");
}
QStringList attributeWhiteList;
if(!command->apiParameter("attributeWhiteList").isEmpty()){
attributeWhiteList = command->apiParameter("attributeWhiteList").split(",");
}
QStringList pluginBlackList;
if(!command->apiParameter("pluginBlackList").isEmpty()){
pluginBlackList = command->apiParameter("pluginBlackList").split(",");
}
QStringList pluginWhiteList;
if(!command->apiParameter("pluginWhiteList").isEmpty()){
pluginWhiteList = command->apiParameter("pluginWhiteList").split(",");
}
bool filterProps = false;
if(command->apiParameter("filterProperties") =="true"){
filterProps = true;
}
mFilter->initialize(filterProps, attributeBlackList, attributeWhiteList, pluginBlackList, pluginWhiteList);
for (int i = 0; i < mTraversers.size(); i++) {
mTraversers.at(i)->setFilter(mFilter);
}
}
TasDataModel* TasUiTraverser::getUiState(TasCommand* command)
{
setFilters(command);
TasDataModel* model = new TasDataModel();
QString qtVersion = "Qt" + QString(qVersion());
TasObjectContainer& container = model->addNewObjectContainer(1, qtVersion, "qt");
TasObject& application = container.addNewObject(QString::number(qApp->applicationPid()), getApplicationName(), "application");
addApplicationDetails(application, command);
QWidgetList widgetList = qApp->topLevelWidgets();
if (!widgetList.empty()){
QListIterator<QWidget*> iter(qApp->topLevelWidgets());
while(iter.hasNext()){
QWidget *widget = iter.next();
//only print widgets if they are visible
if (!widget->graphicsProxyWidget() && (TestabilityUtils::isCustomTraverse() || widget->isVisible())){
//widgets that have a parent will not be traversed unless the parent is the app
//this is done to avoid objects being traversed more than once
if(!widget->parent() || widget->parent() == qApp){
traverseObject(application.addObject(), widget, command);
}
}
}
}
//reset filters after uistate made so that thet will not be used for
//any other tasks done by traversers
for (int i = 0; i < mTraversers.size(); i++) {
mTraversers.at(i)->resetFilter();
}
mFilter->clear();
return model;
}
void TasUiTraverser::traverseObject(TasObject& objectInfo, QObject* object, TasCommand* command)
{
for (int i = 0; i < mTraversers.size(); i++) {
if(!mFilter->filterPlugin(mTraversers.at(i)->getPluginName())){
mTraversers.at(i)->traverseObject(&objectInfo, object, command);
}
}
//check decendants
//1. is graphicsview
if(object->inherits("QGraphicsView")){
traverseGraphicsViewItems(objectInfo, qobject_cast<QGraphicsView*>(object), command);
}
//2. is GraphicsWidget
QGraphicsWidget* graphicsWidget = qobject_cast<QGraphicsWidget*>(object);
if(graphicsWidget){
traverseGraphicsItemList(objectInfo, graphicsWidget,command);
}
//3. Widget children
else{
QObjectList children = object->children();
if (!children.isEmpty()) {
for (int i = 0; i < children.size(); ++i){
QObject *obj = children.at(i);
//only include widgets
if (obj->isWidgetType() && obj->parent() == object){
QWidget *widget = qobject_cast<QWidget*>(obj);
// TODO This (and other similar hacks) needs to be moved to plugins once OSS changes are done
if (TestabilityUtils::isCustomTraverse() || widget->isVisible() ) /*&& !wasTraversed(widget)*/{
traverseObject(objectInfo.addObject(), widget, command);
}
}
}
}
}
}
void TasUiTraverser::traverseGraphicsItem(TasObject& objectInfo, QGraphicsItem* graphicsItem, TasCommand* command)
{
if (graphicsItem->isWindow() || graphicsItem->isWidget()) {
QObject * object = (QObject*)((QGraphicsWidget*)graphicsItem);
traverseObject(objectInfo, object, command);
// Traverse the actual widget under the proxy, if available
QGraphicsProxyWidget* proxy = qobject_cast<QGraphicsProxyWidget*>(object);
if (proxy) {
traverseObject(objectInfo.addObject(), proxy->widget(), command);
}
}
else{
objectInfo.setType("QGraphicsItem");
for (int i = 0; i < mTraversers.size(); i++) {
if(!mFilter->filterPlugin(mTraversers.at(i)->getPluginName())){
mTraversers.at(i)->traverseGraphicsItem(&objectInfo, graphicsItem, command);
}
}
traverseGraphicsItemList(objectInfo, graphicsItem, command);
}
}
void TasUiTraverser::traverseGraphicsItemList(TasObject& parent, QGraphicsItem* graphicsItem, TasCommand* command)
{
foreach (QGraphicsItem* item, graphicsItem->childItems()){
if(graphicsItem == item->parentItem()){
// TODO This needs to be moved to plugins once OSS changes are done
if(TestabilityUtils::isCustomTraverse()|| item->isVisible() ) {
traverseGraphicsItem(parent.addObject(), item, command);
}
}
}
}
void TasUiTraverser::traverseGraphicsViewItems(TasObject& parent, QGraphicsView* view, TasCommand* command)
{
foreach(QGraphicsItem* item, view->items()){
if(item->parentItem() == 0){
// TODO This needs to be moved to plugins once OSS changes are done
if(TestabilityUtils::isCustomTraverse() || item->isVisible()
) {
traverseGraphicsItem(parent.addObject(), item, command);
}
}
}
}
void TasUiTraverser::addApplicationDetails(TasObject& application, TasCommand* command)
{
traverseObject(application, qApp, command);
//set these again cause properties overwrite them
application.setName(getApplicationName());
application.setId(QString::number(qApp->applicationPid()));
#ifdef Q_OS_SYMBIAN
quintptr uid = CEikonEnv::Static()->EikAppUi()->Application()->AppDllUid().iUid;
application.addAttribute("applicationUid", QString::number(uid));
#endif
application.addAttribute("exepath", qApp->applicationFilePath().toLatin1().data());
application.addAttribute("FullName", qApp->applicationFilePath().toLatin1().data());
application.addAttribute("dirpath", qApp->applicationDirPath().toLatin1().data());
application.addAttribute("processId", QString::number(qApp->applicationPid()).toLatin1().data());
application.addAttribute("version", qApp->applicationVersion().toLatin1().data());
application.addAttribute("objectType", TYPE_APPLICATION_VIEW);
application.addAttribute("objectId", TasCoreUtils::objectId(qApp));
int mem = TasDeviceUtils::currentProcessHeapSize();
if(mem != -1){
application.addAttribute("memUsage", mem);
}
QLocale defaultLocale;
application.addAttribute("localeName", defaultLocale.name());
application.addAttribute("localeCountry", defaultLocale.countryToString(defaultLocale.country()));
application.addAttribute("localeLanguage", defaultLocale.languageToString(defaultLocale.language()));
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.